diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 559a2249..3d52d03a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -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: "/" diff --git a/.github/workflows/create_dmg.yml b/.github/workflows/create_dmg.yml deleted file mode 100644 index adf07bfc..00000000 --- a/.github/workflows/create_dmg.yml +++ /dev/null @@ -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 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 98fa39ef..10ce1c4b 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8498c0d3..168e5da6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/.gitignore b/.gitignore index dc112eb8..c85ad094 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/.goreleaser.yaml b/.goreleaser.yaml index fe43a092..1df46d2b 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -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: >- --- diff --git a/Makefile b/Makefile index 3e36c5c1..6059486e 100644 --- a/Makefile +++ b/Makefile @@ -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..." diff --git a/README.md b/README.md index a351c98d..dba7057e 100644 --- a/README.md +++ b/README.md @@ -64,8 +64,6 @@

-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. -
Earlier news... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (alternative) - -```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 -``` - -
- -
-macOS — First Launch Security Warning - -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: - -

-macOS Gatekeeper warning -

- -> *"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. - -

-macOS Privacy & Security — Open Anyway -

- -After this one-time step, `picoclaw-launcher` will open normally on subsequent launches. - -
- - -### 📱 Android - -Give your decade-old phone a second life! Turn it into a smart AI Assistant with PicoClaw. - -**Option 1: APK Install** - -Preview: - - - - - - - - -
- -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). - -
-Terminal Launcher (for resource-constrained environments) - -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. - -PicoClaw on Termux - -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 ``` +
+Docker (alternative) + +```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 +``` +
+ +### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/assets/fui_log_page.jpg b/assets/fui_log_page.jpg deleted file mode 100644 index 188c4698..00000000 Binary files a/assets/fui_log_page.jpg and /dev/null differ diff --git a/assets/fui_main_page.jpg b/assets/fui_main_page.jpg deleted file mode 100644 index f9c5b5c3..00000000 Binary files a/assets/fui_main_page.jpg and /dev/null differ diff --git a/assets/fui_setting_page.jpg b/assets/fui_setting_page.jpg deleted file mode 100644 index 3481088e..00000000 Binary files a/assets/fui_setting_page.jpg and /dev/null differ diff --git a/assets/fui_web_page.jpg b/assets/fui_web_page.jpg deleted file mode 100644 index 2f57c64c..00000000 Binary files a/assets/fui_web_page.jpg and /dev/null differ diff --git a/assets/launcher-webui.jpg b/assets/launcher-webui.jpg deleted file mode 100644 index 9e7c699b..00000000 Binary files a/assets/launcher-webui.jpg and /dev/null differ diff --git a/assets/macos-gatekeeper-allow.jpg b/assets/macos-gatekeeper-allow.jpg deleted file mode 100644 index 9128eb31..00000000 Binary files a/assets/macos-gatekeeper-allow.jpg and /dev/null differ diff --git a/assets/macos-gatekeeper-warning.jpg b/assets/macos-gatekeeper-warning.jpg deleted file mode 100644 index c88c1fc7..00000000 Binary files a/assets/macos-gatekeeper-warning.jpg and /dev/null differ diff --git a/assets/wecom-qr-binding.jpg b/assets/wecom-qr-binding.jpg deleted file mode 100644 index 4768d0d7..00000000 Binary files a/assets/wecom-qr-binding.jpg and /dev/null differ diff --git a/docker/Dockerfile.goreleaser.launcher b/docker/Dockerfile.goreleaser.launcher deleted file mode 100644 index 97944afc..00000000 --- a/docker/Dockerfile.goreleaser.launcher +++ /dev/null @@ -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"] diff --git a/docker/Dockerfile.launcher b/docker/Dockerfile.launcher deleted file mode 100644 index 33fdc6d6..00000000 --- a/docker/Dockerfile.launcher +++ /dev/null @@ -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"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index b12959fc..bb88ea24 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -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 diff --git a/docs/README.md b/docs/README.md index 529eb49e..7d5c446a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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: diff --git a/docs/architecture/routing-system.md b/docs/architecture/routing-system.md index ad6c3abf..6df97143 100644 --- a/docs/architecture/routing-system.md +++ b/docs/architecture/routing-system.md @@ -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` diff --git a/docs/architecture/routing-system.zh.md b/docs/architecture/routing-system.zh.md index 018b9e7b..c0de0ee4 100644 --- a/docs/architecture/routing-system.zh.md +++ b/docs/architecture/routing-system.zh.md @@ -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` diff --git a/docs/architecture/session-system.md b/docs/architecture/session-system.md index b87f9c38..7ed2aed0 100644 --- a/docs/architecture/session-system.md +++ b/docs/architecture/session-system.md @@ -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. diff --git a/docs/architecture/session-system.zh.md b/docs/architecture/session-system.zh.md index 8de4e515..d87abf37 100644 --- a/docs/architecture/session-system.zh.md +++ b/docs/architecture/session-system.zh.md @@ -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。 diff --git a/docs/channels/wecom/README.fr.md b/docs/channels/wecom/README.fr.md index 843943bd..3ca0db90 100644 --- a/docs/channels/wecom/README.fr.md +++ b/docs/channels/wecom/README.fr.md @@ -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. - -

-Liaison QR WeCom dans l'interface Web -

- -### 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 : diff --git a/docs/channels/wecom/README.ja.md b/docs/channels/wecom/README.ja.md index 459a922a..5d8c8bf7 100644 --- a/docs/channels/wecom/README.ja.md +++ b/docs/channels/wecom/README.ja.md @@ -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 コードをスキャンし、アプリ内で確認すると、認証情報が自動的に保存されます。 - -

-Web UI での WeCom QR バインディング -

- -### オプション 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` を既にお持ちの場合、直接設定できます: diff --git a/docs/channels/wecom/README.md b/docs/channels/wecom/README.md index bb94d743..d78b1a14 100644 --- a/docs/channels/wecom/README.md +++ b/docs/channels/wecom/README.md @@ -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. - -

-WeCom QR binding in Web UI -

- -### 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: diff --git a/docs/channels/wecom/README.pt-br.md b/docs/channels/wecom/README.pt-br.md index 07a5e23b..fa6c72a8 100644 --- a/docs/channels/wecom/README.pt-br.md +++ b/docs/channels/wecom/README.pt-br.md @@ -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. - -

-Vinculação QR do WeCom na Web UI -

- -### 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: diff --git a/docs/channels/wecom/README.vi.md b/docs/channels/wecom/README.vi.md index 4769fd6d..a6ea4d9a 100644 --- a/docs/channels/wecom/README.vi.md +++ b/docs/channels/wecom/README.vi.md @@ -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. - -

-Liên kết QR WeCom trong Web UI -

- -### 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: diff --git a/docs/channels/wecom/README.zh.md b/docs/channels/wecom/README.zh.md index 8303a8f8..f0dfcd0c 100644 --- a/docs/channels/wecom/README.zh.md +++ b/docs/channels/wecom/README.zh.md @@ -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 内确认,凭据自动保存。 - -

-Web UI 企业微信扫码绑定 -

- -### 方式二:CLI 扫码登录 +### 方式一:CLI 扫码登录 运行: @@ -50,7 +42,7 @@ picoclaw auth wecom --timeout 10m > ⚠️ 仅扫描二维码还不够——必须在企业微信 App 内点击**确认**,否则命令会超时。 -### 方式三:手动配置 +### 方式二:手动配置 如果已有企业微信 AI Bot 的 `bot_id` 和 `secret`,可直接配置: diff --git a/docs/design/current-hardware-support-and-serial.zh.md b/docs/design/current-hardware-support-and-serial.zh.md index bf91355c..5730ae8c 100644 --- a/docs/design/current-hardware-support-and-serial.zh.md +++ b/docs/design/current-hardware-support-and-serial.zh.md @@ -32,8 +32,6 @@ - 配置项:`tools.serial.enabled` - Tool 注册:`pkg/agent/agent_init.go` -- Web 工具页:`/api/tools` 能展示与切换 `serial` -- 前端状态文案:新增 `requires_serial_platform` ## Serial Tool 设计 diff --git a/docs/guides/README.md b/docs/guides/README.md index 4b912e64..9d9a0bb4 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -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. diff --git a/docs/guides/android-termux.md b/docs/guides/android-termux.md index 2766a0ff..c57eb6ed 100644 --- a/docs/guides/android-termux.md +++ b/docs/guides/android-termux.md @@ -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 diff --git a/docs/guides/configuration.fr.md b/docs/guides/configuration.fr.md index dcacc187..64812ddc 100644 --- a/docs/guides/configuration.fr.md +++ b/docs/guides/configuration.fr.md @@ -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}`. diff --git a/docs/guides/configuration.it.md b/docs/guides/configuration.it.md index 213ca107..1fcb3cbb 100644 --- a/docs/guides/configuration.it.md +++ b/docs/guides/configuration.it.md @@ -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}`. diff --git a/docs/guides/configuration.ja.md b/docs/guides/configuration.ja.md index 7dd67644..27fe7c07 100644 --- a/docs/guides/configuration.ja.md +++ b/docs/guides/configuration.ja.md @@ -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}` を書く必要はありません。 diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 3b278fdb..5065fb84 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -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}`. diff --git a/docs/guides/configuration.ms.md b/docs/guides/configuration.ms.md index 4448829a..ad4c184f 100644 --- a/docs/guides/configuration.ms.md +++ b/docs/guides/configuration.ms.md @@ -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}`. diff --git a/docs/guides/configuration.pt-br.md b/docs/guides/configuration.pt-br.md index bb5d1413..41d34b22 100644 --- a/docs/guides/configuration.pt-br.md +++ b/docs/guides/configuration.pt-br.md @@ -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}`. diff --git a/docs/guides/configuration.vi.md b/docs/guides/configuration.vi.md index 516ebe9f..82880302 100644 --- a/docs/guides/configuration.vi.md +++ b/docs/guides/configuration.vi.md @@ -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}`. diff --git a/docs/guides/configuration.zh.md b/docs/guides/configuration.zh.md index 3ff49bbb..cd5774b9 100644 --- a/docs/guides/configuration.zh.md +++ b/docs/guides/configuration.zh.md @@ -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}`。 diff --git a/docs/guides/docker.fr.md b/docs/guides/docker.fr.md index e174298a..5684d21c 100644 --- a/docs/guides/docker.fr.md +++ b/docs/guides/docker.fr.md @@ -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 diff --git a/docs/guides/docker.ja.md b/docs/guides/docker.ja.md index 19199aaa..0da4f8e6 100644 --- a/docs/guides/docker.ja.md +++ b/docs/guides/docker.ja.md @@ -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 diff --git a/docs/guides/docker.md b/docs/guides/docker.md index e2e472fb..d19637a1 100644 --- a/docs/guides/docker.md +++ b/docs/guides/docker.md @@ -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 diff --git a/docs/guides/docker.ms.md b/docs/guides/docker.ms.md index 5a426cb9..a53b3cbc 100644 --- a/docs/guides/docker.ms.md +++ b/docs/guides/docker.ms.md @@ -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 diff --git a/docs/guides/docker.pt-br.md b/docs/guides/docker.pt-br.md index ab71af8e..48b16114 100644 --- a/docs/guides/docker.pt-br.md +++ b/docs/guides/docker.pt-br.md @@ -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 diff --git a/docs/guides/docker.vi.md b/docs/guides/docker.vi.md index e91450bb..81eefa0b 100644 --- a/docs/guides/docker.vi.md +++ b/docs/guides/docker.vi.md @@ -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 diff --git a/docs/guides/docker.zh.md b/docs/guides/docker.zh.md index 855375d9..ff387082 100644 --- a/docs/guides/docker.zh.md +++ b/docs/guides/docker.zh.md @@ -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 -``` - -在浏览器中打开 。Launcher 会自动管理 Gateway 进程。 - -> [!WARNING] -> Web 控制台通过 dashboard 登录密码保护。**不要**将启动器暴露到不可信网络或公网。完整说明见 [配置指南](configuration.md) 中的「Web 启动器控制台」一节。 - ### Agent 模式 (一次性运行) ```bash diff --git a/docs/project/README.fr.md b/docs/project/README.fr.md index 1fd58e47..8d90e004 100644 --- a/docs/project/README.fr.md +++ b/docs/project/README.fr.md @@ -65,16 +65,12 @@

-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. -
Actualités précédentes... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (alternative) - -```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 -``` - -
- -
-macOS — Avertissement de sécurité au premier lancement - -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 : - -

-Avertissement macOS Gatekeeper -

- -> *"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. - -

-macOS Confidentialité et sécurité — Ouvrir quand même -

- -Après cette étape unique, `picoclaw-launcher` s'ouvrira normalement lors des lancements suivants. - -
- - -### 📱 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 : - - - - - - - - -
- -Téléchargez l'APK depuis [picoclaw.io](https://picoclaw.io/download/) et installez-le directement. Pas besoin de Termux ! - -**Option 2 : Termux** - -
-Terminal Launcher (pour les environnements à ressources limitées) - -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. - -PicoClaw on Termux - -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 ``` +
+Docker (alternative) + +```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 +``` +
+ +### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/docs/project/README.id.md b/docs/project/README.id.md index d129e7c9..0435f74b 100644 --- a/docs/project/README.id.md +++ b/docs/project/README.id.md @@ -64,16 +64,12 @@

-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. -
Berita sebelumnya... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (alternatif) - -```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 -``` - -
- -
-macOS — Peringatan Keamanan saat Pertama Kali Diluncurkan - -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: - -

-Peringatan macOS Gatekeeper -

- -> *"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. - -

-macOS Privasi & Keamanan — Tetap Buka -

- -Setelah langkah satu kali ini, `picoclaw-launcher` akan terbuka secara normal pada peluncuran berikutnya. - -
- -### 📱 Android - -Berikan kehidupan kedua untuk ponsel lama Anda! Ubah menjadi Asisten AI pintar dengan PicoClaw. - -**Opsi 1: Instal APK** - -Pratinjau: - - - - - - - - -
- -Unduh APK dari [picoclaw.io](https://picoclaw.io/download/) dan instal langsung. Tanpa Termux! - -**Opsi 2: Termux** - -
-Terminal Launcher (untuk lingkungan dengan sumber daya terbatas) - -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. - -PicoClaw on Termux - -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 ``` +
+Docker (alternatif) + +```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 +``` +
+### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/docs/project/README.it.md b/docs/project/README.it.md index 9261ad82..1e28afc3 100644 --- a/docs/project/README.it.md +++ b/docs/project/README.it.md @@ -64,16 +64,12 @@

-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. -
Notizie precedenti... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (alternativa) - -```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 -``` - -
- -
-macOS — Avviso di sicurezza al primo avvio - -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: - -

-Avviso macOS Gatekeeper -

- -> *"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. - -

-macOS Privacy e sicurezza — Apri comunque -

- -Dopo questo passaggio una tantum, `picoclaw-launcher` si aprirà normalmente ai lanci successivi. - -
- -### 📱 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: - - - - - - - - -
- -Scarica l'APK da [picoclaw.io](https://picoclaw.io/download/) e installa direttamente. Senza Termux! - -**Opzione 2: Termux** - -
-Terminal Launcher (per ambienti con risorse limitate) - -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. - -PicoClaw on Termux - -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 ``` +
+Docker (alternativa) + +```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 +``` +
+### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/docs/project/README.ja.md b/docs/project/README.ja.md index 1fd748d2..6fe6b354 100644 --- a/docs/project/README.ja.md +++ b/docs/project/README.ja.md @@ -64,16 +64,12 @@

-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 サポート。 -
過去のニュース... @@ -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 -> ``` - -

-WebUI Launcher -

- -**始め方:** - -WebUI を開いたら:**1)** Provider を設定(LLM API キーを追加)→ **2)** Channel を設定(例:Telegram)→ **3)** Gateway を起動 → **4)** チャット! - -WebUI の詳細なドキュメントは [docs.picoclaw.io](https://docs.picoclaw.io) を参照してください。 - -
-Docker(代替手段) - -```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 -``` - -
- -
-macOS — 初回起動時のセキュリティ警告 - -`picoclaw-launcher` はインターネットからダウンロードされ、Mac App Store を通じて公証されていないため、macOS が初回起動時にブロックする場合があります。 - -**ステップ 1:** `picoclaw-launcher` をダブルクリックすると、セキュリティ警告が表示されます: - -

-macOS Gatekeeper 警告 -

- -> *"picoclaw-launcher" は開けません — "picoclaw-launcher" がMacに害を与えたりプライバシーを侵害するマルウェアを含まないことをAppleは確認できません。* - -**ステップ 2:** **システム設定** → **プライバシーとセキュリティ** を開き、**セキュリティ** セクションまでスクロールして **このまま開く** をクリック → ダイアログで再度 **開く** をクリックします。 - -

-macOS プライバシーとセキュリティ — このまま開く -

- -この操作を一度行うと、以降の起動では警告が表示されなくなります。 - -
- - -### 📱 Android - -10 年前のスマホに第二の人生を!PicoClaw でスマート AI アシスタントに変身させましょう。 - -**オプション 1: APK インストール** - -プレビュー: - - - - - - - - -
- -[picoclaw.io](https://picoclaw.io/download/) から APK をダウンロードして直接インストール。Termux 不要! - -**オプション 2: Termux** - -
-Terminal Launcher(リソース制約環境向け) - -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 セクションの手順に従って設定を完了してください。 - -PicoClaw on Termux - -`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 ``` +
+Docker(代替手段) + +```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 +``` +
+ +### 📱 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 ファイルシステムレイアウトを提供 +``` + +PicoClaw on Termux + +[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 設定 | diff --git a/docs/project/README.ko.md b/docs/project/README.ko.md index 2c79d161..484acb74 100644 --- a/docs/project/README.ko.md +++ b/docs/project/README.ko.md @@ -64,16 +64,12 @@

-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 런처 지원과 함께 출시되었습니다. -
이전 뉴스... @@ -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 -> ``` - -

-WebUI Launcher -

- -**시작 방법:** - -WebUI를 연 뒤 다음 순서로 진행하세요. **1)** 프로바이더 설정(LLM API 키 추가) -> **2)** 채널 설정(예: Telegram) -> **3)** 게이트웨이 시작 -> **4)** 채팅! - -자세한 WebUI 문서는 [docs.picoclaw.io](https://docs.picoclaw.io)를 참고하세요. - -
-Docker(대안) - -```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 -``` - -
- -
-macOS - 첫 실행 보안 경고 - -macOS에서는 인터넷에서 다운로드한 앱이고 Mac App Store 공증을 거치지 않았기 때문에, 첫 실행 시 `picoclaw-launcher`가 차단될 수 있습니다. - -**1단계:** `picoclaw-launcher`를 더블클릭합니다. 그러면 보안 경고가 표시됩니다. - -

-macOS Gatekeeper warning -

- -> *"picoclaw-launcher"을(를) 열 수 없습니다. Apple에서 이 앱이 악성 소프트웨어가 없으며 Mac이나 개인 정보를 해치지 않는다고 확인할 수 없습니다.* - -**2단계:** **시스템 설정** -> **개인정보 보호 및 보안** 으로 이동한 뒤 **보안** 섹션까지 스크롤하여 **그래도 열기(Open Anyway)** 를 클릭하고, 대화상자에서 다시 한 번 **그래도 열기**를 확인합니다. - -

-macOS Privacy & Security — Open Anyway -

- -이 과정을 한 번만 거치면 이후에는 `picoclaw-launcher`가 정상적으로 열립니다. - -
- -### 📱 Android - -오래된 스마트폰에 새 생명을 불어넣어 보세요! PicoClaw를 설치하면 스마트 AI 어시스턴트로 바꿀 수 있습니다. - -**옵션 1: APK 설치** - -미리보기: - - - - - - - - -
- -[picoclaw.io](https://picoclaw.io/download/)에서 APK를 다운로드해 바로 설치하세요. Termux가 필요 없습니다! - -**옵션 2: 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 파일시스템 레이아웃을 제공합니다 -``` - -그다음 아래의 터미널 런처 섹션을 따라 설정을 마무리하세요. - -PicoClaw on Termux - -런처 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 ``` +
+Docker(대안) + +```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 +``` +
+### 📱 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 파일시스템 레이아웃을 제공합니다 +``` + +PicoClaw on Termux + +[Android Termux Guide](../guides/android-termux.md). + ## 🔌 프로바이더(LLM) PicoClaw는 `model_list` 설정을 통해 30개 이상의 LLM 프로바이더를 지원합니다. 형식은 `protocol/model`입니다. diff --git a/docs/project/README.ms.md b/docs/project/README.ms.md index 068208fa..3edbd4dd 100644 --- a/docs/project/README.ms.md +++ b/docs/project/README.ms.md @@ -64,16 +64,12 @@

-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. -
Berita terdahulu... @@ -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 -> ``` - -

-Pelancar WebUI -

- -**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). - -
-Docker (alternatif) - -```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 -``` - -
- - -
-macOS — Amaran Keselamatan Pelancaran Pertama - -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: - -

-Amaran macOS Gatekeeper -

- -> *"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. - -

-macOS Privasi & Keselamatan — Buka Juga -

- -Selepas langkah sekali ini, `picoclaw-launcher` akan dibuka secara normal pada pelancaran seterusnya. - -
- -### 📱 Android - -Berikan telefon lama anda kehidupan baru! Jadikannya Pembantu AI pintar dengan PicoClaw. - -**Pilihan 1: Pasang APK** - -Pratonton: - - - - - - - - -
- -Muat turun APK dari [picoclaw.io](https://picoclaw.io/download/) dan pasang secara langsung. Tiada Termux diperlukan! - -**Pilihan 2: Termux** - -
-Pelancar Terminal (untuk persekitaran terhad sumber) - -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. - -PicoClaw pada Termux - -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 ``` +
+Docker (alternatif) + +```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 +``` +
+### 📱 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 +``` + +PicoClaw pada Termux + +[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 | diff --git a/docs/project/README.pt-br.md b/docs/project/README.pt-br.md index d9f6d0c0..914e0feb 100644 --- a/docs/project/README.pt-br.md +++ b/docs/project/README.pt-br.md @@ -64,16 +64,12 @@

-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. -
Notícias anteriores... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (alternativa) - -```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 -``` - -
- -
-macOS — Aviso de segurança no primeiro lançamento - -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: - -

-Aviso do macOS Gatekeeper -

- -> *"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. - -

-macOS Privacidade e Segurança — Abrir Mesmo Assim -

- -Após esta etapa única, o `picoclaw-launcher` abrirá normalmente nos lançamentos seguintes. - -
- - -### 📱 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: - - - - - - - - -
- -Baixe o APK de [picoclaw.io](https://picoclaw.io/download/) e instale diretamente. Sem necessidade de Termux! - -**Opção 2: Termux** - -
-Terminal Launcher (para ambientes com recursos limitados) - -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. - -PicoClaw on Termux - -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 ``` +
+Docker (alternativa) + +```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 +``` +
+ +### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/docs/project/README.vi.md b/docs/project/README.vi.md index 36c72bc2..15aceea1 100644 --- a/docs/project/README.vi.md +++ b/docs/project/README.vi.md @@ -64,16 +64,12 @@

-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. -
Tin tức trước đó... @@ -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 -> ``` - -

-WebUI Launcher -

- -**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). - -
-Docker (thay thế) - -```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 -``` - -
- -
-macOS — Cảnh báo bảo mật khi khởi chạy lần đầu - -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: - -

-Cảnh báo macOS Gatekeeper -

- -> *"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. - -

-macOS Quyền riêng tư & Bảo mật — Vẫn Mở -

- -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. - -
- - -### 📱 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: - - - - - - - - -
- -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** - -
-Terminal Launcher (cho môi trường hạn chế tài nguyên) - -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. - -PicoClaw on Termux - -Đố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 ``` +
+Docker (thay thế) + +```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 +``` +
+ +### 📱 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 +``` + +PicoClaw on Termux + +[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 | diff --git a/docs/project/README.zh.md b/docs/project/README.zh.md index 4d643b91..bf9fbe08 100644 --- a/docs/project/README.zh.md +++ b/docs/project/README.zh.md @@ -64,16 +64,12 @@

-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 启动器。 -
更早的新闻... @@ -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 -> ``` - -

-WebUI Launcher -

- -**开始使用:** - -打开 WebUI,然后:**1)** 配置 Provider(填入 LLM API Key)-> **2)** 配置 Channel(如 Telegram)-> **3)** 启动 Gateway -> **4)** 开始聊天! - -详细 WebUI 文档请参阅 [docs.picoclaw.io](https://docs.picoclaw.io)。 - -
-Docker(备选方案) - -```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 -``` - -
- -
-macOS — 首次启动安全警告 - -macOS 可能会在首次启动时拦截 `picoclaw-launcher`,因为它从互联网下载,未经 Mac App Store 公证。 - -**第一步:** 双击 `picoclaw-launcher`,会出现安全警告: - -

-macOS Gatekeeper 警告 -

- -> *"picoclaw-launcher" 无法打开 — Apple 无法验证 "picoclaw-launcher" 不含可能损害 Mac 或危及隐私的恶意软件。* - -**第二步:** 打开**系统设置** → **隐私与安全性** → 向下滚动找到**安全性**部分 → 点击**仍要打开** → 在弹窗中再次点击**打开**。 - -

-macOS 隐私与安全性 — 仍要打开 -

- -完成这一次操作后,后续启动 `picoclaw-launcher` 将不再弹出警告。 - -
- - -### 📱 Android - -让你十年前的旧手机焕发新生!将它变成你的 AI 助手。 - -**方式一:APK 安装** - -预览: - - - - - - - - -
- -从 [picoclaw.io](https://picoclaw.io/download/) 下载 APK 并直接安装,无需 Termux! - -**方式二:Termux** - -
-Terminal Launcher(适用于资源受限环境) - -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"章节继续配置。 - -PicoClaw on Termux - -对于只有 `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 ``` +
+Docker(备选方案) + +```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 +``` +
+ +### 📱 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 文件系统布局 +``` + +PicoClaw on Termux + +[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 配置 | diff --git a/go.mod b/go.mod index a85ddd40..29b7e81b 100644 --- a/go.mod +++ b/go.mod @@ -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 ) diff --git a/go.sum b/go.sum index 7fbeda96..c252133e 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/pkg/channels/pico/pico.go b/pkg/channels/pico/pico.go index 3a7ab1f2..363692dc 100644 --- a/pkg/channels/pico/pico.go +++ b/pkg/channels/pico/pico.go @@ -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) { diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 30e7077f..52dbea3b 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -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 } diff --git a/pkg/config/envkeys.go b/pkg/config/envkeys.go index 5a259029..45693bff 100644 --- a/pkg/config/envkeys.go +++ b/pkg/config/envkeys.go @@ -33,11 +33,6 @@ const ( // Default: /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" diff --git a/pkg/credential/credential.go b/pkg/credential/credential.go index 8ecd6783..e4298c61 100644 --- a/pkg/credential/credential.go +++ b/pkg/credential/credential.go @@ -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) } diff --git a/pkg/memory/jsonl.go b/pkg/memory/jsonl.go index 3b2f9ff3..ef34d3bc 100644 --- a/pkg/memory/jsonl.go +++ b/pkg/memory/jsonl.go @@ -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, diff --git a/pkg/providers/factory_provider.go b/pkg/providers/factory_provider.go index 8a4af9f1..c0e4a6e1 100644 --- a/pkg/providers/factory_provider.go +++ b/pkg/providers/factory_provider.go @@ -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 "" } diff --git a/pkg/providers/factory_provider_test.go b/pkg/providers/factory_provider_test.go index 272ffe9f..a70d3eca 100644 --- a/pkg/providers/factory_provider_test.go +++ b/pkg/providers/factory_provider_test.go @@ -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) diff --git a/pkg/providers/provider_catalog.go b/pkg/providers/provider_catalog.go index b2056563..4d59d72c 100644 --- a/pkg/providers/provider_catalog.go +++ b/pkg/providers/provider_catalog.go @@ -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. diff --git a/pkg/providers/provider_metadata.go b/pkg/providers/provider_metadata.go index 90a2206b..6690cfc8 100644 --- a/pkg/providers/provider_metadata.go +++ b/pkg/providers/provider_metadata.go @@ -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 } diff --git a/scripts/build-macos-app.sh b/scripts/build-macos-app.sh deleted file mode 100755 index df2100ae..00000000 --- a/scripts/build-macos-app.sh +++ /dev/null @@ -1,108 +0,0 @@ -#!/bin/bash -# Build macOS .app bundle for PicoClaw Launcher - -set -e - -EXECUTABLE=$1 - -if [ -z "$EXECUTABLE" ]; then - echo "Usage: $0 " - 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' - - - - - CFBundleExecutable - picoclaw-launcher - CFBundleIdentifier - com.picoclaw.launcher - CFBundleName - PicoClaw Launcher - CFBundleDisplayName - PicoClaw Launcher - CFBundleIconFile - icon.icns - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - NSHighResolutionCapable - - NSSupportsAutomaticGraphicsSwitching - - LSUIElement - - LSMinimumSystemVersion - 10.11 - - -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 "" diff --git a/scripts/icon.icns b/scripts/icon.icns deleted file mode 100644 index bcf9adcd..00000000 Binary files a/scripts/icon.icns and /dev/null differ diff --git a/scripts/setup.iss b/scripts/setup.iss deleted file mode 100644 index c081d4df..00000000 --- a/scripts/setup.iss +++ /dev/null @@ -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 - diff --git a/web/Makefile b/web/Makefile deleted file mode 100644 index 254c439e..00000000 --- a/web/Makefile +++ /dev/null @@ -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 diff --git a/web/README.md b/web/README.md deleted file mode 100644 index 5dc88b03..00000000 --- a/web/README.md +++ /dev/null @@ -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-- -``` - -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) diff --git a/web/backend/.gitignore b/web/backend/.gitignore deleted file mode 100644 index 50904217..00000000 --- a/web/backend/.gitignore +++ /dev/null @@ -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/ \ No newline at end of file diff --git a/web/backend/api/auth.go b/web/backend/api/auth.go deleted file mode 100644 index 9104eeb1..00000000 --- a/web/backend/api/auth.go +++ /dev/null @@ -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) + `}`)) -} diff --git a/web/backend/api/auth_csrf_test.go b/web/backend/api/auth_csrf_test.go deleted file mode 100644 index 50b0fefd..00000000 --- a/web/backend/api/auth_csrf_test.go +++ /dev/null @@ -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) - } -} diff --git a/web/backend/api/auth_login_limiter.go b/web/backend/api/auth_login_limiter.go deleted file mode 100644 index d606f03c..00000000 --- a/web/backend/api/auth_login_limiter.go +++ /dev/null @@ -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 -} diff --git a/web/backend/api/auth_test.go b/web/backend/api/auth_test.go deleted file mode 100644 index f7f6037a..00000000 --- a/web/backend/api/auth_test.go +++ /dev/null @@ -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()) - } -} diff --git a/web/backend/api/channels.go b/web/backend/api/channels.go deleted file mode 100644 index b98c0557..00000000 --- a/web/backend/api/channels.go +++ /dev/null @@ -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 -} diff --git a/web/backend/api/channels_test.go b/web/backend/api/channels_test.go deleted file mode 100644 index a70c9ba4..00000000 --- a/web/backend/api/channels_test.go +++ /dev/null @@ -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) - } -} diff --git a/web/backend/api/config.go b/web/backend/api/config.go deleted file mode 100644 index f567fe52..00000000 --- a/web/backend/api/config.go +++ /dev/null @@ -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) - } - } - } - } - } - } - } -} diff --git a/web/backend/api/config_test.go b/web/backend/api/config_test.go deleted file mode 100644 index 8a23b7a3..00000000 --- a/web/backend/api/config_test.go +++ /dev/null @@ -1,1453 +0,0 @@ -package api - -import ( - "bytes" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -func TestHandlePatchConfig_PreservesTurnProfile(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Agents.Defaults.TurnProfile = config.TurnProfileConfig{ - Enabled: true, - History: config.TurnProfileBlock{Mode: config.TurnProfileModeOff}, - SystemPrompt: config.TurnProfileBlock{Mode: config.TurnProfileModeOff}, - Skills: config.TurnProfileBlock{Mode: config.TurnProfileModeOff}, - Tools: config.TurnProfileBlock{ - Mode: config.TurnProfileModeCustom, - Allow: []string{"web_search", "web_fetch"}, - }, - } - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "agents": { - "defaults": { - "max_tokens": 1234 - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - 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(updated) error = %v", err) - } - profile := updated.Agents.Defaults.TurnProfile - if profile.Tools.Mode != config.TurnProfileModeCustom || - strings.Join(profile.Tools.Allow, ",") != "web_search,web_fetch" { - t.Fatalf("profile tools = %#v, want custom web_search/web_fetch", profile.Tools) - } -} - -func TestHandlePatchConfig_RejectsInvalidTurnProfile(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "agents": { - "defaults": { - "turn_profile": { - "enabled": true, - "history": { "mode": "custom" } - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusBadRequest { - t.Fatalf( - "status = %d, want %d, body=%s", - rec.Code, - http.StatusBadRequest, - rec.Body.String(), - ) - } - if !strings.Contains(rec.Body.String(), "history.mode custom is not supported") { - t.Fatalf("body=%s, want turn profile validation error", rec.Body.String()) - } - - if _, err := config.LoadConfig(configPath); err != nil { - t.Fatalf("LoadConfig() after rejected patch error = %v", err) - } -} - -func assertGatewayLogLevelApplied(t *testing.T, method, body string, want logger.LogLevel) { - t.Helper() - - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - initialLevel := logger.GetLevel() - logger.SetLevel(logger.INFO) - t.Cleanup(func() { - logger.SetLevel(initialLevel) - }) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(method, "/api/config", bytes.NewBufferString(body)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "%s /api/config status = %d, want %d, body=%s", - method, - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - if got := logger.GetLevel(); got != want { - t.Fatalf("logger.GetLevel() = %v, want %v", got, want) - } -} - -func TestHandleUpdateConfig_PreservesExecAllowRemoteDefaultWhenOmitted(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewBufferString(`{ -"version": 3, - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace" - } - }, - "model_list": [ - { - "model_name": "custom-default", - "model": "openai/gpt-4o", - "api_keys": ["sk-default"] - } - ] - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if !cfg.Tools.Exec.AllowRemote { - t.Fatal("tools.exec.allow_remote should remain true when omitted from PUT /api/config") - } -} - -func TestHandleUpdateConfig_DoesNotInheritDefaultModelFields(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewBufferString(`{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace" - } - }, - "model_list": [ - { - "model_name": "custom-default", - "model": "openai/gpt-4o", - "api_key": "sk-default" - } - ] - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := cfg.ModelList[0].APIBase; got != "" { - t.Fatalf("model_list[0].api_base = %q, want empty string", got) - } -} - -func TestHandlePatchConfig_RejectsInvalidExecRegexPatterns(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "tools": { - "exec": { - "custom_deny_patterns": ["("] - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusBadRequest { - t.Fatalf( - "status = %d, want %d, body=%s", - rec.Code, - http.StatusBadRequest, - rec.Body.String(), - ) - } - if !bytes.Contains(rec.Body.Bytes(), []byte("custom_deny_patterns")) { - t.Fatalf( - "expected validation error mentioning custom_deny_patterns, body=%s", - rec.Body.String(), - ) - } -} - -func TestHandlePatchConfig_AllowsInvalidExecRegexPatternsWhenExecDisabled(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "tools": { - "exec": { - "enabled": false, - "custom_deny_patterns": ["("], - "custom_allow_patterns": ["("] - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } -} - -func TestHandlePatchConfig_SavesChannelListSettingsPatch(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "feishu": { - "enabled": true, - "allow_from": ["ou_patch_user"], - "settings": { - "app_id": "cli_patch_app", - "app_secret": "patch-secret", - "is_lark": true - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - bc := cfg.Channels[config.ChannelFeishu] - if !bc.Enabled { - t.Fatal("feishu should be enabled after PATCH") - } - if len(bc.AllowFrom) != 1 || bc.AllowFrom[0] != "ou_patch_user" { - t.Fatalf("feishu allow_from = %#v, want [\"ou_patch_user\"]", bc.AllowFrom) - } - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - feishuCfg := decoded.(*config.FeishuSettings) - if got := feishuCfg.AppID; got != "cli_patch_app" { - t.Fatalf("feishu app_id = %q, want %q", got, "cli_patch_app") - } - if got := feishuCfg.AppSecret.String(); got != "patch-secret" { - t.Fatalf("feishu app_secret = %q, want %q", got, "patch-secret") - } - if !feishuCfg.IsLark { - t.Fatal("feishu is_lark should be true after PATCH") - } -} - -func TestHandlePatchConfig_NormalizesStringChannelArrayFields(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "pico": { - "type": "pico", - "allow_from": " ou_a\u200b,\u2060ou_b\tou_c\u202e,ou_a ", - "group_trigger": { - "prefixes": "/,!;\n?,/" - }, - "settings": { - "allow_origins": "https://a.example.com,http://localhost:5173,https://a.example.com" - } - }, - "irc": { - "type": "irc", - "settings": { - "channels": "#ops,\n#dev,\n#ops", - "request_caps": "multi-prefix,echo-message\tbatch,multi-prefix" - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - picoChannel := cfg.Channels[config.ChannelPico] - if len(picoChannel.AllowFrom) != 3 || - picoChannel.AllowFrom[0] != "ou_a" || - picoChannel.AllowFrom[1] != "ou_b" || - picoChannel.AllowFrom[2] != "ou_c" { - t.Fatalf( - "pico allow_from = %#v, want [\"ou_a\", \"ou_b\", \"ou_c\"]", - picoChannel.AllowFrom, - ) - } - if len(picoChannel.GroupTrigger.Prefixes) != 3 || - picoChannel.GroupTrigger.Prefixes[0] != "/" || - picoChannel.GroupTrigger.Prefixes[1] != "!;" || - picoChannel.GroupTrigger.Prefixes[2] != "?" { - t.Fatalf( - "pico group_trigger.prefixes = %#v, want [\"/\", \"!;\", \"?\"]", - picoChannel.GroupTrigger.Prefixes, - ) - } - - decoded, err := picoChannel.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() pico error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if len(picoCfg.AllowOrigins) != 2 || - picoCfg.AllowOrigins[0] != "https://a.example.com" || - picoCfg.AllowOrigins[1] != "http://localhost:5173" { - t.Fatalf( - "pico allow_origins = %#v, want [\"https://a.example.com\", \"http://localhost:5173\"]", - picoCfg.AllowOrigins, - ) - } - - ircChannel := cfg.Channels[config.ChannelIRC] - decoded, err = ircChannel.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() irc error = %v", err) - } - ircCfg := decoded.(*config.IRCSettings) - if len(ircCfg.Channels) != 2 || - ircCfg.Channels[0] != "#ops" || - ircCfg.Channels[1] != "#dev" { - t.Fatalf("irc channels = %#v, want [\"#ops\", \"#dev\"]", ircCfg.Channels) - } - if len(ircCfg.RequestCaps) != 3 || - ircCfg.RequestCaps[0] != "multi-prefix" || - ircCfg.RequestCaps[1] != "echo-message" || - ircCfg.RequestCaps[2] != "batch" { - t.Fatalf( - "irc request_caps = %#v, want [\"multi-prefix\", \"echo-message\", \"batch\"]", - ircCfg.RequestCaps, - ) - } -} - -func TestHandlePatchConfig_NormalizesSingleNumericAllowFrom(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "telegram": { - "type": "telegram", - "allow_from": 123456 - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - telegramChannel := cfg.Channels[config.ChannelTelegram] - if len(telegramChannel.AllowFrom) != 1 || telegramChannel.AllowFrom[0] != "123456" { - t.Fatalf("telegram allow_from = %#v, want [\"123456\"]", telegramChannel.AllowFrom) - } -} - -func TestHandlePatchConfig_RejectsInvalidChannelArrayFields(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - telegramChannel := cfg.Channels[config.ChannelTelegram] - telegramChannel.AllowFrom = config.FlexibleStringSlice{"existing-user"} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - tests := []struct { - name string - body string - }{ - { - name: "object allow_from", - body: `{ - "channel_list": { - "telegram": { - "type": "telegram", - "allow_from": {"id": "bad"} - } - } - }`, - }, - { - name: "boolean allow_from", - body: `{ - "channel_list": { - "telegram": { - "type": "telegram", - "allow_from": true - } - } - }`, - }, - { - name: "object settings array", - body: `{ - "channel_list": { - "irc": { - "type": "irc", - "settings": { - "channels": {"name": "#ops"} - } - } - } - }`, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest( - http.MethodPatch, - "/api/config", - bytes.NewBufferString(tt.body), - ) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusBadRequest { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusBadRequest, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - telegramChannel := cfg.Channels[config.ChannelTelegram] - if len(telegramChannel.AllowFrom) != 1 || - telegramChannel.AllowFrom[0] != "existing-user" { - t.Fatalf( - "telegram allow_from = %#v, want unchanged [\"existing-user\"]", - telegramChannel.AllowFrom, - ) - } - }) - } -} - -func TestHandlePatchConfig_RejectsNegativeStreamingDeliveryValues(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "pico": { - "settings": { - "streaming": { - "enabled": true, - "throttle_seconds": -1 - } - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusBadRequest { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusBadRequest, - rec.Body.String(), - ) - } - if !strings.Contains(rec.Body.String(), "streaming.throttle_seconds") { - t.Fatalf( - "response body = %q, want streaming.throttle_seconds validation error", - rec.Body.String(), - ) - } -} - -func TestHandlePatchConfig_ClearingAllowFromDoesNotLeaveEmptyStringItem(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - feishuChannel := cfg.Channels[config.ChannelFeishu] - feishuChannel.Enabled = true - feishuChannel.AllowFrom = config.FlexibleStringSlice{"ou_existing_user"} - decoded, err := feishuChannel.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - feishuCfg := decoded.(*config.FeishuSettings) - feishuCfg.AppID = "cli_existing_app" - feishuCfg.AppSecret = *config.NewSecureString("existing-secret") - 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.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "feishu": { - "enabled": true, - "allow_from": "", - "settings": { - "app_id": "cli_existing_app" - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err = config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - feishuChannel = cfg.Channels[config.ChannelFeishu] - if len(feishuChannel.AllowFrom) != 0 { - t.Fatalf("feishu allow_from = %#v, want empty slice", feishuChannel.AllowFrom) - } - - configData, err := os.ReadFile(configPath) - if err != nil { - t.Fatalf("ReadFile(configPath) error = %v", err) - } - if strings.Contains(string(configData), `"allow_from": [""]`) { - t.Fatalf( - "config file should not contain empty-string allow_from item: %s", - string(configData), - ) - } -} - -func TestHandlePatchConfig_CreatesMissingChannelWithTypeAndSecret(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.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": { - "irc": { - "enabled": true, - "type": "irc", - "settings": { - "server": "irc.example.com", - "password": "irc-patch-password" - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err = config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - bc := cfg.Channels[config.ChannelIRC] - if bc == nil { - t.Fatal("irc channel should exist after PATCH") - } - if got := bc.Type; got != config.ChannelIRC { - t.Fatalf("irc type = %q, want %q", got, config.ChannelIRC) - } - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - ircCfg := decoded.(*config.IRCSettings) - if got := ircCfg.Server; got != "irc.example.com" { - t.Fatalf("irc server = %q, want %q", got, "irc.example.com") - } - if got := ircCfg.Password.String(); got != "irc-patch-password" { - t.Fatalf("irc password = %q, want %q", got, "irc-patch-password") - } - configData, err := os.ReadFile(configPath) - if err != nil { - t.Fatalf("ReadFile(configPath) error = %v", err) - } - if bytes.Contains(configData, []byte("irc-patch-password")) { - t.Fatalf("config file leaked irc password: %s", string(configData)) - } -} - -// setupPicoEnabledEnv creates a test environment with Pico channel enabled and -// its token stored only in .security.yml (not in the JSON payload). -func setupPicoEnabledEnv(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" - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - bc.Enabled = true - picoCfg.Token = *config.NewSecureString("test-pico-token") - - 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 TestHandleUpdateConfig_SucceedsWhenPicoTokenInSecurityOnly(t *testing.T) { - configPath, cleanup := setupPicoEnabledEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - // PUT request with pico enabled but no token in JSON — token is in .security.yml - req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewBufferString(`{ - "version": 1, - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "custom-default" - } - }, - "channels": { - "pico": { - "enabled": true, - "ping_interval": 30, - "read_timeout": 60, - "write_timeout": 10, - "max_connections": 100 - } - }, - "model_list": [ - { - "model_name": "custom-default", - "model": "openai/gpt-4o", - "api_keys": ["sk-default"] - } - ] - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PUT /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } -} - -func TestHandlePatchConfig_SucceedsWhenPicoTokenInSecurityOnly(t *testing.T) { - configPath, cleanup := setupPicoEnabledEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - // PATCH request changing an unrelated field — pico token still in .security.yml - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "gateway": { - "log_level": "info" - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } -} - -func TestHandleUpdateConfig_AppliesGatewayLogLevel(t *testing.T) { - assertGatewayLogLevelApplied(t, http.MethodPut, `{ - "version": 1, - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "custom-default" - } - }, - "gateway": { - "log_level": "error" - }, - "model_list": [ - { - "model_name": "custom-default", - "model": "openai/gpt-4o", - "api_keys": ["sk-default"] - } - ] - }`, logger.ERROR) -} - -func TestHandlePatchConfig_AppliesGatewayLogLevel(t *testing.T) { - assertGatewayLogLevelApplied(t, http.MethodPatch, `{ - "gateway": { - "log_level": "debug" - } - }`, logger.DEBUG) -} - -func TestHandlePatchConfig_PreservesDebugFlagOverride(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - initialLevel := logger.GetLevel() - logger.SetLevel(logger.INFO) - t.Cleanup(func() { - logger.SetLevel(initialLevel) - }) - - h := NewHandler(configPath) - h.SetDebug(true) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "gateway": { - "log_level": "error" - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - if got := logger.GetLevel(); got != logger.DEBUG { - t.Fatalf("logger.GetLevel() = %v, want %v", got, logger.DEBUG) - } -} - -func TestHandlePatchConfig_SavesDiscordTokenFromPayload(t *testing.T) { - t.Skip("TODO: fix this test") - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "channel_list": [ - { - "name":"discord", - "enabled": true, - "token": "discord-test-token" - } - ] - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - bc := cfg.Channels[config.ChannelDiscord] - if !bc.Enabled { - t.Fatal("discord should be enabled after PATCH") - } - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - if got := decoded.(*config.DiscordSettings).Token.String(); got != "discord-test-token" { - t.Fatalf("discord token = %q, want %q", got, "discord-test-token") - } -} - -func TestHandlePatchConfig_DoesNotPersistShadowRegistryAuthTokenField(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "tools": { - "skills": { - "registries": { - "github": { - "_auth_token": "ghp-shadow-token" - } - } - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf( - "PATCH /api/config status = %d, want %d, body=%s", - rec.Code, - http.StatusOK, - rec.Body.String(), - ) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - githubRegistry, ok := cfg.Tools.Skills.Registries.Get("github") - if !ok { - t.Fatal("github registry missing after PATCH") - } - if got := githubRegistry.AuthToken.String(); got != "ghp-shadow-token" { - t.Fatalf("github registry auth token = %q, want %q", got, "ghp-shadow-token") - } - if got := githubRegistry.BaseURL; got != "https://github.com" { - t.Fatalf("github registry base_url = %q, want %q", got, "https://github.com") - } - - rawConfig, err := os.ReadFile(configPath) - if err != nil { - t.Fatalf("ReadFile(configPath) error = %v", err) - } - if strings.Contains(string(rawConfig), "_auth_token") { - t.Fatalf( - "config.json should not persist _auth_token shadow field, got:\n%s", - string(rawConfig), - ) - } -} - -func TestHandlePatchConfig_AllowsInvalidDenyRegexPatternsWhenDenyPatternsDisabled(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - req := httptest.NewRequest(http.MethodPatch, "/api/config", bytes.NewBufferString(`{ - "tools": { - "exec": { - "enabled": true, - "enable_deny_patterns": false, - "custom_deny_patterns": ["("] - } - } - }`)) - req.Header.Set("Content-Type", "application/json") - - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } -} - -// testCommandPatterns is a helper that sets up a handler and sends a test-command-patterns request. -func testCommandPatterns(t *testing.T, configPath string, body string) *httptest.ResponseRecorder { - t.Helper() - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - req := httptest.NewRequest( - http.MethodPost, - "/api/config/test-command-patterns", - bytes.NewBufferString(body), - ) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - return rec -} - -func TestHandleTestCommandPatterns_MatchesWhitelist(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": ["^echo\\s+hello"], - "deny_patterns": ["^rm\\s+-rf"], - "command": "echo hello world" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf("expected allowed=true, body=%s", rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"blocked":true`)) { - t.Fatalf("expected blocked=false when whitelist matches, body=%s", rec.Body.String()) - } -} - -func TestHandleTestCommandPatterns_MatchesBlacklistNotWhitelist(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": ["^echo\\s+hello"], - "deny_patterns": ["^rm\\s+-rf"], - "command": "rm -rf /tmp" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`"blocked":true`)) { - t.Fatalf("expected blocked=true, body=%s", rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf( - "expected allowed=false when blacklist matches but not whitelist, body=%s", - rec.Body.String(), - ) - } -} - -func TestHandleTestCommandPatterns_MatchesNeither(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": ["^echo\\s+hello"], - "deny_patterns": ["^rm\\s+-rf"], - "command": "ls -la" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf("expected allowed=false, body=%s", rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"blocked":true`)) { - t.Fatalf("expected blocked=false, body=%s", rec.Body.String()) - } -} - -func TestHandleTestCommandPatterns_CaseInsensitiveWithGoFlag(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": ["(?i)^ECHO"], - "deny_patterns": [], - "command": "echo hello" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf("expected allowed=true with Go (?i) flag, body=%s", rec.Body.String()) - } -} - -func TestHandleTestCommandPatterns_EmptyPatterns(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": [], - "deny_patterns": [], - "command": "rm -rf /tmp" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf("expected allowed=false with empty patterns, body=%s", rec.Body.String()) - } - if bytes.Contains(rec.Body.Bytes(), []byte(`"blocked":true`)) { - t.Fatalf("expected blocked=false with empty patterns, body=%s", rec.Body.String()) - } -} - -func TestHandleTestCommandPatterns_InvalidRegexSkipped(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": ["([[", "^echo"], - "deny_patterns": [], - "command": "echo hello" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`"allowed":true`)) { - t.Fatalf( - "expected allowed=true, invalid pattern skipped and valid one matched, body=%s", - rec.Body.String(), - ) - } -} - -func TestHandleTestCommandPatterns_ReturnsMatchedPattern(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - rec := testCommandPatterns(t, configPath, `{ - "allow_patterns": [], - "deny_patterns": ["\\$(?i)[a-zA-Z_]*(SECRET|KEY|PASSWORD|TOKEN|AUTH)[a-zA-Z0-9_]*"], - "command": "echo $GITHUB_API_KEY" - }`) - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`"blocked":true`)) { - t.Fatalf("expected blocked=true, body=%s", rec.Body.String()) - } - if !bytes.Contains(rec.Body.Bytes(), []byte(`matched_blacklist`)) { - t.Fatalf("expected matched_blacklist field, body=%s", rec.Body.String()) - } -} - -func TestHandleTestCommandPatterns_InvalidJSON(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - req := httptest.NewRequest( - http.MethodPost, - "/api/config/test-command-patterns", - bytes.NewBufferString(`{invalid json}`), - ) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - 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 TestApplyConfigSecretsFromMap_TelegramToken(t *testing.T) { - cfg := config.DefaultConfig() - bc := cfg.Channels["telegram"] - bc.Enabled = true - // Pre-decode so extend is populated - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - tgCfg := decoded.(*config.TelegramSettings) - tgCfg.Token = *config.NewSecureString("original-token") - - raw := map[string]any{ - "channel_list": map[string]any{ - "telegram": map[string]any{ - "enabled": true, - "token": "secret-from-api", - }, - }, - } - - applyConfigSecretsFromMap(cfg, raw) - - if got := tgCfg.Token.String(); got != "secret-from-api" { - t.Fatalf("telegram token = %q, want %q", got, "secret-from-api") - } -} - -func TestApplyConfigSecretsFromMap_TeamsWebhook(t *testing.T) { - // applyConfigSecretsFromMap recurses into nested maps to find - // SecureString fields at any depth (e.g. webhook_url inside webhooks map). - cfg := config.DefaultConfig() - bc := &config.Channel{Enabled: true, Type: config.ChannelTeamsWebHook} - cfg.Channels["teams_webhook"] = bc - target := &config.TeamsWebhookSettings{ - Webhooks: map[string]config.TeamsWebhookTarget{ - "default": { - WebhookURL: *config.NewSecureString("https://example.com/hook1"), - Title: "Default", - }, - }, - } - if err := bc.Decode(target); err != nil { - t.Fatalf("Decode() error = %v", err) - } - - raw := map[string]any{ - "channel_list": map[string]any{ - "teams_webhook": map[string]any{ - "enabled": true, - "settings": map[string]any{ - "webhooks": map[string]any{ - "default": map[string]any{ - "webhook_url": "https://example.com/hook-updated", - "title": "Default Updated", - }, - }, - }, - }, - }, - } - - applyConfigSecretsFromMap(cfg, raw) - - // Verify the decoded struct has the updated SecureString value - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - twCfg, ok := decoded.(*config.TeamsWebhookSettings) - if !ok { - t.Fatalf("expected *TeamsWebhookSettings, got %T", decoded) - } - - hookURL := twCfg.Webhooks["default"].WebhookURL - if got := hookURL.String(); got != "https://example.com/hook-updated" { - t.Fatalf("webhook_url = %q, want %q", got, "https://example.com/hook-updated") - } - // Note: title is a plain string, not a SecureString, so it is NOT updated - // by applyConfigSecretsFromMap (only secure fields are handled). -} - -func TestApplyConfigSecretsFromMap_MultipleChannels(t *testing.T) { - cfg := config.DefaultConfig() - - // Setup telegram - bc := cfg.Channels["telegram"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() telegram error = %v", err) - } - tgCfg := decoded.(*config.TelegramSettings) - tgCfg.Token = *config.NewSecureString("old-telegram-token") - - // Setup discord - bc = cfg.Channels["discord"] - bc.Enabled = true - decoded, err = bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() discord error = %v", err) - } - discCfg := decoded.(*config.DiscordSettings) - discCfg.Token = *config.NewSecureString("old-discord-token") - - raw := map[string]any{ - "channel_list": map[string]any{ - "telegram": map[string]any{ - "enabled": true, - "settings": map[string]any{ - "token": "new-telegram-token", - }, - }, - "discord": map[string]any{ - "enabled": true, - "settings": map[string]any{ - "token": "new-discord-token", - }, - }, - }, - } - - applyConfigSecretsFromMap(cfg, raw) - - if got := tgCfg.Token.String(); got != "new-telegram-token" { - t.Fatalf("telegram token = %q, want %q", got, "new-telegram-token") - } - if got := discCfg.Token.String(); got != "new-discord-token" { - t.Fatalf("discord token = %q, want %q", got, "new-discord-token") - } -} - -func TestApplyConfigSecretsFromMap_SkipsNonStringValues(t *testing.T) { - cfg := config.DefaultConfig() - bc := cfg.Channels["telegram"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - tgCfg := decoded.(*config.TelegramSettings) - tgCfg.Token = *config.NewSecureString("original-token") - - raw := map[string]any{ - "channel_list": map[string]any{ - "telegram": map[string]any{ - "enabled": true, - "token": 12345, // not a string, should be skipped - }, - }, - } - - applyConfigSecretsFromMap(cfg, raw) - - if got := tgCfg.Token.String(); got != "original-token" { - t.Fatalf("telegram token = %q, want %q", got, "original-token") - } -} - -func TestApplyConfigSecretsFromMap_ChannelNotDecodedYet(t *testing.T) { - cfg := config.DefaultConfig() - bc := cfg.Channels["telegram"] - bc.Enabled = true - // Don't decode — let the function handle lazy decoding - bc.Type = config.ChannelTelegram - - raw := map[string]any{ - "channel_list": map[string]any{ - "telegram": map[string]any{ - "enabled": true, - "token": "lazy-decoded-token", - }, - }, - } - - applyConfigSecretsFromMap(cfg, raw) - - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - tgCfg := decoded.(*config.TelegramSettings) - if got := tgCfg.Token.String(); got != "lazy-decoded-token" { - t.Fatalf("telegram token = %q, want %q", got, "lazy-decoded-token") - } -} diff --git a/web/backend/api/exec_nonwindows.go b/web/backend/api/exec_nonwindows.go deleted file mode 100644 index 27a4fc75..00000000 --- a/web/backend/api/exec_nonwindows.go +++ /dev/null @@ -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) -} diff --git a/web/backend/api/exec_windows.go b/web/backend/api/exec_windows.go deleted file mode 100644 index 79cbbf6a..00000000 --- a/web/backend/api/exec_windows.go +++ /dev/null @@ -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) -} diff --git a/web/backend/api/gateway.go b/web/backend/api/gateway.go deleted file mode 100644 index 636f7448..00000000 --- a/web/backend/api/gateway.go +++ /dev/null @@ -1,1571 +0,0 @@ -package api - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "os" - "os/exec" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "syscall" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/health" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/netbind" - ppid "github.com/sipeed/picoclaw/pkg/pid" - "github.com/sipeed/picoclaw/pkg/providers" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -// gateway holds the state for the managed gateway process. -var gateway = struct { - mu sync.Mutex - cmd *exec.Cmd - owned bool // true if we started the process, false if we attached to an existing one - bootDefaultModel string - bootConfigSignature string - runtimeStatus string - startupDeadline time.Time - logs *LogBuffer - pidData *ppid.PidFileData // pid file data read from picoclaw.pid.json - picoToken string // cached raw pico token for upstream gateway proxy injection -}{ - runtimeStatus: "stopped", - logs: NewLogBuffer(200), -} - -// refreshPicoTokensLocked reads the pico token from config and caches it. -// Caller must hold gateway.mu (or be sole writer). -func refreshPicoTokensLocked(configPath string) { - cfg, err := config.LoadConfig(configPath) - if err != nil { - return - } - var picoCfg config.PicoSettings - if bc := cfg.Channels.GetByType(config.ChannelPico); bc != nil { - decoded, err := bc.GetDecoded() - if err == nil && decoded != nil { - if p, ok := decoded.(*config.PicoSettings); ok { - picoCfg = *p - } - } - } - gateway.picoToken = picoCfg.Token.String() -} - -// ensurePicoTokenCachedLocked lazily fills the in-memory pico token cache when -// the launcher has already discovered a running gateway via pidData, but has -// not yet refreshed the token into memory. -func ensurePicoTokenCachedLocked(configPath string) { - if gateway.picoToken != "" { - return - } - refreshPicoTokensLocked(configPath) -} - -func (h *Handler) gatewayCommandArgs() []string { - args := []string{"gateway", "-E"} - if h.debug { - args = append(args, "-d") - } - return args -} - -const ( - protocolKey = "Sec-Websocket-Protocol" - tokenPrefix = "token." -) - -// picoGatewayProtocol returns the gateway-facing pico subprotocol that the -// launcher should inject when proxying browser traffic upstream. -func picoGatewayProtocol() string { - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.picoToken == "" { - return "" - } - return tokenPrefix + gateway.picoToken -} - -var ( - gatewayStartupWindow = 15 * time.Second - gatewayRestartGracePeriod = 5 * time.Second - gatewayRestartForceKillWindow = 3 * time.Second - gatewayRestartPollInterval = 100 * time.Millisecond - gatewayExecCommand = exec.Command -) - -var gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) { - client := http.Client{Timeout: timeout} - return client.Get(url) -} - -var gatewayProcessMatcher = isLikelyGatewayProcess - -// getGatewayHealth checks the gateway health endpoint and returns the status response. -// Returns (*health.StatusResponse, statusCode, error). If error is not nil, the other values are not valid. -func (h *Handler) getGatewayHealth(cfg *config.Config, timeout time.Duration) (*health.StatusResponse, int, error) { - // Prefer port/host from pidData when available. - var port int - var host string - gateway.mu.Lock() - if d := gateway.pidData; d != nil && d.Port > 0 { - port = d.Port - host = gatewayProbeHost(d.Host) - } - gateway.mu.Unlock() - if port == 0 { - port = 18790 - if cfg != nil && cfg.Gateway.Port != 0 { - port = cfg.Gateway.Port - } - } - if host == "" { - host = gatewayProbeHost(h.effectiveGatewayBindHost(cfg)) - } - - url := "http://" + net.JoinHostPort(host, strconv.Itoa(port)) + "/health" - - return getGatewayHealthByURL(url, timeout) -} - -func getGatewayHealthByURL(url string, timeout time.Duration) (*health.StatusResponse, int, error) { - resp, err := gatewayHealthGet(url, timeout) - if err != nil { - return nil, 0, err - } - defer resp.Body.Close() - - var healthResponse health.StatusResponse - if decErr := json.NewDecoder(resp.Body).Decode(&healthResponse); decErr != nil { - return nil, resp.StatusCode, decErr - } - - return &healthResponse, resp.StatusCode, nil -} - -// isLikelyGatewayProcess returns whether PID appears to be a picoclaw gateway -// process plus whether inspection was conclusive on this platform/environment. -func isLikelyGatewayProcess(pid int) (bool, bool) { - if pid <= 0 { - return false, true - } - - if runtime.GOOS == "windows" { - psCmd := fmt.Sprintf( - `$p=Get-CimInstance Win32_Process -Filter "ProcessId = %d"; if ($null -eq $p) { "" } else { $p.CommandLine }`, - pid, - ) - out, err := launcherExecCommand("powershell", "-NoProfile", "-NonInteractive", "-Command", psCmd).Output() - if err == nil { - cmdline := strings.TrimSpace(string(out)) - if cmdline != "" { - return looksLikeGatewayCommandLine(cmdline), true - } - } - - // Fallback: determine only whether the process still exists. - out, err = launcherExecCommand("tasklist", "/FI", "PID eq "+strconv.Itoa(pid), "/FO", "CSV", "/NH").Output() - if err != nil { - return false, false - } - line := strings.ToLower(strings.TrimSpace(string(out))) - if line == "" { - return false, true - } - // A CSV row means the process exists, but may have a custom executable - // name we cannot classify here. - if strings.HasPrefix(line, "\"") { - if strings.Contains(line, "\"picoclaw.exe\"") { - return true, true - } - return false, true - } - if strings.Contains(line, "no tasks are running") { - return false, true - } - return false, true - } - - out, err := launcherExecCommand("ps", "-o", "command=", "-p", strconv.Itoa(pid)).Output() - if err != nil { - return false, false - } - cmdline := strings.ToLower(strings.TrimSpace(string(out))) - if cmdline == "" { - return false, true - } - return looksLikeGatewayCommandLine(cmdline), true -} - -// looksLikeGatewayCommandLine checks whether a process command line likely -// represents "picoclaw gateway ..." regardless of executable filename. -func looksLikeGatewayCommandLine(cmdline string) bool { - fields := strings.Fields(strings.ToLower(strings.TrimSpace(cmdline))) - if len(fields) == 0 { - return false - } - for _, f := range fields { - token := strings.Trim(f, `"'`) - if token == "gateway" || strings.HasSuffix(token, "/gateway") || strings.HasSuffix(token, `\gateway`) { - return true - } - } - return false -} - -func (h *Handler) getGatewayHealthForPidData( - pidData *ppid.PidFileData, - cfg *config.Config, - timeout time.Duration, -) (*health.StatusResponse, int, error) { - if pidData == nil { - return nil, 0, errors.New("nil pid data") - } - - port := pidData.Port - if port == 0 { - port = 18790 - if cfg != nil && cfg.Gateway.Port != 0 { - port = cfg.Gateway.Port - } - } - - host := gatewayProbeHost(strings.TrimSpace(pidData.Host)) - if host == "" { - host = gatewayProbeHost(h.effectiveGatewayBindHost(cfg)) - } - if host == "" { - host = netbind.ResolveAdaptiveLoopbackHost() - } - - url := "http://" + net.JoinHostPort(host, strconv.Itoa(port)) + "/health" - return getGatewayHealthByURL(url, timeout) -} - -func (h *Handler) validateGatewayPidData( - pidData *ppid.PidFileData, - cfg *config.Config, -) (ok bool, decisive bool, reason string) { - if pidData == nil || pidData.PID <= 0 { - return false, true, "invalid pid data" - } - - if gatewayProcess, inspected := gatewayProcessMatcher(pidData.PID); inspected { - if !gatewayProcess { - return false, true, "pid process command is not picoclaw gateway" - } - return true, true, "" - } - - healthResp, statusCode, err := h.getGatewayHealthForPidData(pidData, cfg, 800*time.Millisecond) - if err != nil { - return false, false, fmt.Sprintf("health probe failed: %v", err) - } - if statusCode != http.StatusOK { - return false, false, fmt.Sprintf("health endpoint returned status %d", statusCode) - } - if healthResp.PID > 0 && healthResp.PID != pidData.PID { - return false, true, fmt.Sprintf("health pid mismatch: pidFile=%d, health=%d", pidData.PID, healthResp.PID) - } - return true, true, "" -} - -func (h *Handler) sanitizeGatewayPidData(pidData *ppid.PidFileData, cfg *config.Config) *ppid.PidFileData { - if pidData == nil { - return nil - } - - ok, decisive, reason := h.validateGatewayPidData(pidData, cfg) - if ok { - return pidData - } - - logger.Warnf("ignore pid file for PID %d: %s", pidData.PID, reason) - if decisive && ppid.RemovePidFileIfPID(globalConfigDir(), pidData.PID) { - logger.Warnf("removed stale pid file for PID %d", pidData.PID) - } - return nil -} - -// registerGatewayRoutes binds gateway lifecycle endpoints to the ServeMux. -func (h *Handler) registerGatewayRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/gateway/status", h.handleGatewayStatus) - mux.HandleFunc("GET /api/gateway/logs", h.handleGatewayLogs) - mux.HandleFunc("POST /api/gateway/logs/clear", h.handleGatewayClearLogs) - mux.HandleFunc("POST /api/gateway/start", h.handleGatewayStart) - mux.HandleFunc("POST /api/gateway/stop", h.handleGatewayStop) - mux.HandleFunc("POST /api/gateway/restart", h.handleGatewayRestart) -} - -// TryAutoStartGateway checks whether gateway start preconditions are met and -// starts it when possible. Intended to be called by the backend at startup. -func (h *Handler) TryAutoStartGateway() { - // Check PID file first to detect an already-running gateway. - pidData := h.sanitizeGatewayPidData(ppid.ReadPidFileWithCheck(globalConfigDir()), nil) - if pidData != nil { - gateway.mu.Lock() - ready, reason, err := h.gatewayStartReady() - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Skip auto-starting gateway: %v", err)) - gateway.mu.Unlock() - return - } - logger.Infof("ready: %v, reason: %s", ready, reason) - if !ready { - logger.InfoC("gateway", fmt.Sprintf("Skip auto-starting gateway: %s", reason)) - gateway.mu.Unlock() - return - } - pid := pidData.PID - _, err = h.startGatewayLocked("starting", pid) - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Failed to attach to running gateway (PID: %d): %v", pid, err)) - } else { - gateway.pidData = pidData - refreshPicoTokensLocked(h.configPath) - logger.InfoC("gateway", fmt.Sprintf("Attached to running gateway via PID file (PID: %d)", pid)) - } - gateway.mu.Unlock() - return - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - - if gateway.cmd != nil && gateway.cmd.Process != nil { - gateway.cmd = nil - } - - ready, reason, err := h.gatewayStartReady() - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Skip auto-starting gateway: %v", err)) - return - } - if !ready { - logger.InfoC("gateway", fmt.Sprintf("Skip auto-starting gateway: %s", reason)) - return - } - - pid, err := h.startGatewayLocked("starting", 0) - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Failed to auto-start gateway: %v", err)) - return - } - logger.InfoC("gateway", fmt.Sprintf("Gateway auto-started (PID: %d)", pid)) -} - -// gatewayStartReady validates whether current config can start the gateway. -func (h *Handler) gatewayStartReady() (bool, string, error) { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return false, "", fmt.Errorf("failed to load config: %w", err) - } - normalizeStoredModelNames(cfg) - - modelName := strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - if modelName == "" { - return false, "no default model configured", nil - } - if aliasModels := modelConfigsByName(cfg)[modelName]; len(aliasModels) > 1 { - if err := validateDefaultChainModelSet( - modelName, - aliasModels, - true, - defaultChainProvider(cfg), - ); err != nil { - // Validation failures are readiness reasons, not handler errors. - //nolint:nilerr - return false, err.Error(), nil - } - } - - modelCfg := lookupModelConfig(cfg, modelName) - if modelCfg == nil { - return false, fmt.Sprintf("default model %q is invalid", modelName), nil - } - if !defaultModelAllowedForModelConfig(modelCfg, defaultChainProvider(cfg)) { - return false, fmt.Sprintf("default model %q is not usable for chat", modelName), nil - } - - if !rawTemplateHasConfiguration(modelCfg) { - return false, fmt.Sprintf("default model %q has no credentials configured", modelName), nil - } - if requiresRuntimeProbe(modelCfg) && !probeLocalModelAvailability(modelCfg) { - return false, fmt.Sprintf("default model %q is not reachable", modelName), nil - } - - return true, "", nil -} - -func lookupModelConfig(cfg *config.Config, modelName string) *config.ModelConfig { - modelCfg, err := providers.ResolveModelConfig(cfg, modelName) - if err != nil { - return nil - } - return modelCfg -} - -func computeConfigSignature(cfg *config.Config) string { - if cfg == nil { - return "" - } - var parts []string - parts = append(parts, "default_provider:"+defaultChainProvider(cfg)) - defaultModel := strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - if defaultModel != "" { - parts = append(parts, "model:"+defaultModel) - } - modelStreamingSignatures := computeModelStreamingSignatures(cfg) - if len(modelStreamingSignatures) > 0 { - parts = append(parts, "model_streaming:"+strings.Join(modelStreamingSignatures, ",")) - } - toolSignatures := []string{} - if cfg.Tools.ReadFile.Enabled { - toolSignatures = append(toolSignatures, "read_file") - } - if cfg.Tools.WriteFile.Enabled { - toolSignatures = append(toolSignatures, "write_file") - } - if cfg.Tools.ListDir.Enabled { - toolSignatures = append(toolSignatures, "list_dir") - } - if cfg.Tools.EditFile.Enabled { - toolSignatures = append(toolSignatures, "edit_file") - } - if cfg.Tools.AppendFile.Enabled { - toolSignatures = append(toolSignatures, "append_file") - } - if cfg.Tools.Exec.Enabled { - toolSignatures = append(toolSignatures, "exec") - } - if cfg.Tools.Cron.Enabled { - toolSignatures = append(toolSignatures, "cron") - } - if cfg.Tools.Web.Enabled { - toolSignatures = append(toolSignatures, "web") - webConfig, err := json.Marshal(canonicalizeSignatureValue(reflect.ValueOf(cfg.Tools.Web))) - if err == nil { - parts = append(parts, "webcfg:"+string(webConfig)) - } - } - if cfg.Tools.WebFetch.Enabled { - toolSignatures = append(toolSignatures, "web_fetch") - } - if cfg.Tools.Message.Enabled { - toolSignatures = append(toolSignatures, "message") - } - if cfg.Tools.SendFile.Enabled { - toolSignatures = append(toolSignatures, "send_file") - } - if cfg.Tools.FindSkills.Enabled { - toolSignatures = append(toolSignatures, "find_skills") - } - if cfg.Tools.InstallSkill.Enabled { - toolSignatures = append(toolSignatures, "install_skill") - } - if cfg.Tools.Spawn.Enabled { - toolSignatures = append(toolSignatures, "spawn") - } - if cfg.Tools.SpawnStatus.Enabled { - toolSignatures = append(toolSignatures, "spawn_status") - } - if cfg.Tools.I2C.Enabled { - toolSignatures = append(toolSignatures, "i2c") - } - if cfg.Tools.SPI.Enabled { - toolSignatures = append(toolSignatures, "spi") - } - if cfg.Tools.MCP.Enabled { - toolSignatures = append(toolSignatures, "mcp") - } - if cfg.Tools.MCP.Discovery.Enabled { - toolSignatures = append(toolSignatures, "mcp_discovery") - } - if cfg.Tools.MCP.Discovery.UseRegex { - toolSignatures = append(toolSignatures, "mcp_discovery_regex") - } - if cfg.Tools.MCP.Discovery.UseBM25 { - toolSignatures = append(toolSignatures, "mcp_discovery_bm25") - } - if len(toolSignatures) > 0 { - parts = append(parts, "tools:"+strings.Join(toolSignatures, ",")) - } - channelSignatures := computeChannelSignatures(cfg.Channels) - if len(channelSignatures) > 0 { - parts = append(parts, "channels:"+strings.Join(channelSignatures, ",")) - } - return strings.Join(parts, ";") -} - -func computeModelStreamingSignatures(cfg *config.Config) []string { - if cfg == nil { - return nil - } - defaultProvider := strings.TrimSpace(cfg.Agents.Defaults.Provider) - if defaultProvider == "" { - defaultProvider = "openai" - } - type streamingRef struct { - scope string - name string - } - - refs := []streamingRef{{ - scope: "defaults.primary", - name: strings.TrimSpace(cfg.Agents.Defaults.GetModelName()), - }} - for i, name := range cfg.Agents.Defaults.ModelFallbacks { - refs = append(refs, streamingRef{ - scope: "defaults.fallback:" + strconv.Itoa(i), - name: name, - }) - } - if cfg.Agents.Defaults.Routing != nil { - refs = append(refs, streamingRef{ - scope: "defaults.routing.light", - name: cfg.Agents.Defaults.Routing.LightModel, - }) - } - for agentIndex, agent := range cfg.Agents.List { - if agent.Model == nil { - continue - } - refs = append(refs, streamingRef{ - scope: "agent:" + strconv.Itoa(agentIndex) + ".primary", - name: agent.Model.Primary, - }) - for i, name := range agent.Model.Fallbacks { - refs = append(refs, streamingRef{ - scope: "agent:" + strconv.Itoa(agentIndex) + ".fallback:" + strconv.Itoa(i), - name: name, - }) - } - } - - seenEntries := make(map[string]bool) - signatures := make([]string, 0, len(refs)) - for _, ref := range refs { - ref.name = strings.TrimSpace(ref.name) - if ref.name == "" { - continue - } - referenceEntry := strings.Join([]string{ref.scope, ref.name}, ":") - if !seenEntries[referenceEntry] { - seenEntries[referenceEntry] = true - signatures = append(signatures, referenceEntry) - } - for _, match := range modelConfigsMatchingSignatureRef(cfg.ModelList, ref.name, defaultProvider) { - mc := match.model - entry := strings.Join([]string{ - ref.scope, - ref.name, - strconv.Itoa(match.index), - strings.TrimSpace(mc.Provider), - strings.TrimSpace(mc.Model), - strconv.FormatBool(mc.Streaming.Enabled), - }, ":") - if seenEntries[entry] { - continue - } - seenEntries[entry] = true - signatures = append(signatures, entry) - } - } - sort.Strings(signatures) - return signatures -} - -type signatureModelConfigMatch struct { - index int - model *config.ModelConfig -} - -func modelConfigsMatchingSignatureRef( - modelList []*config.ModelConfig, - raw string, - defaultProvider string, -) []signatureModelConfigMatch { - raw = strings.TrimSpace(raw) - if raw == "" { - return nil - } - matches := make([]signatureModelConfigMatch, 0, 1) - for i, mc := range modelList { - if mc == nil || strings.TrimSpace(mc.ModelName) != raw { - continue - } - matches = append(matches, signatureModelConfigMatch{index: i, model: mc}) - } - if len(matches) > 0 { - return matches - } - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{Provider: defaultProvider}, - }, - ModelList: modelList, - } - resolved, err := providers.ResolveModelConfig(cfg, raw) - if err != nil { - return nil - } - for i, modelCfg := range modelList { - if modelConfigsMatchResolvedEntry(modelCfg, resolved, defaultProvider) { - return []signatureModelConfigMatch{{index: i, model: modelCfg}} - } - } - return nil -} - -func modelConfigsMatchResolvedEntry( - left, - right *config.ModelConfig, - defaultProvider string, -) bool { - if left == nil || right == nil || left.IsVirtual() { - return false - } - leftProvider, leftModel := modelConfigProviderAndID(left, defaultProvider) - rightProvider, rightModel := providers.ExtractProtocol(right) - return left.ModelName == right.ModelName && - providers.ModelKey(leftProvider, leftModel) == providers.ModelKey(rightProvider, rightModel) && - left.APIBase == right.APIBase && - left.APIKey() == right.APIKey() && - left.Enabled == right.Enabled && - left.AuthMethod == right.AuthMethod && - left.ConnectMode == right.ConnectMode -} - -func modelConfigProviderAndID(mc *config.ModelConfig, defaultProvider string) (string, string) { - if mc == nil { - return "", "" - } - if strings.TrimSpace(mc.Provider) != "" { - return providers.ExtractProtocol(mc) - } - return providers.SplitModelProviderAndID(mc.Model, defaultProvider) -} - -func computeChannelSignatures(channels config.ChannelsConfig) []string { - if len(channels) == 0 { - return nil - } - - keys := make([]string, 0, len(channels)) - for name := range channels { - keys = append(keys, name) - } - sort.Strings(keys) - - signatures := make([]string, 0, len(keys)) - for _, name := range keys { - channel := channels[name] - if channel == nil { - signatures = append(signatures, name+":") - continue - } - - payload := struct { - Enabled bool `json:"enabled"` - Type string `json:"type"` - AllowFrom config.FlexibleStringSlice `json:"allow_from,omitempty"` - ReasoningChannelID string `json:"reasoning_channel_id,omitempty"` - GroupTrigger config.GroupTriggerConfig `json:"group_trigger,omitempty"` - Typing config.TypingConfig `json:"typing,omitempty"` - Placeholder config.PlaceholderConfig `json:"placeholder,omitempty"` - Settings json.RawMessage `json:"settings,omitempty"` - }{ - Enabled: channel.Enabled, - Type: channel.Type, - AllowFrom: channel.AllowFrom, - ReasoningChannelID: channel.ReasoningChannelID, - GroupTrigger: channel.GroupTrigger, - Typing: channel.Typing, - Placeholder: channel.Placeholder, - Settings: normalizeChannelSettings(channel), - } - - encoded, err := json.Marshal(payload) - if err != nil { - signatures = append(signatures, name+":") - continue - } - signatures = append(signatures, name+":"+string(encoded)) - } - - return signatures -} - -func normalizeChannelSettings(channel *config.Channel) json.RawMessage { - if channel == nil { - return nil - } - - decoded, err := channel.GetDecoded() - if err == nil && decoded != nil { - normalized, err := json.Marshal(canonicalizeSignatureValue(reflect.ValueOf(decoded))) - if err == nil { - return normalized - } - } - - return normalizeRawJSON(channel.Settings) -} - -func normalizeRawJSON(raw config.RawNode) json.RawMessage { - if len(raw) == 0 { - return nil - } - - var value any - if err := json.Unmarshal(raw, &value); err != nil { - return bytes.TrimSpace(raw) - } - - normalized, err := json.Marshal(value) - if err != nil { - return bytes.TrimSpace(raw) - } - return normalized -} - -func canonicalizeSignatureValue(value reflect.Value) any { - if !value.IsValid() { - return nil - } - - if value.CanInterface() { - switch typed := value.Interface().(type) { - case config.SecureString: - return typed.String() - case *config.SecureString: - if typed == nil { - return "" - } - return typed.String() - case config.SecureStrings: - return typed.Values() - case *config.SecureStrings: - if typed == nil { - return nil - } - return typed.Values() - } - } - - switch value.Kind() { - case reflect.Interface, reflect.Pointer: - if value.IsNil() { - return nil - } - return canonicalizeSignatureValue(value.Elem()) - case reflect.Struct: - result := make(map[string]any) - valueType := value.Type() - for i := 0; i < value.NumField(); i++ { - field := valueType.Field(i) - if field.PkgPath != "" { - continue - } - tag := field.Tag.Get("json") - name := field.Name - if tag != "" { - if comma := strings.Index(tag, ","); comma >= 0 { - tag = tag[:comma] - } - if tag == "-" { - continue - } - if tag != "" { - name = tag - } - } - result[name] = canonicalizeSignatureValue(value.Field(i)) - } - return result - case reflect.Slice, reflect.Array: - length := value.Len() - result := make([]any, 0, length) - for i := 0; i < length; i++ { - result = append(result, canonicalizeSignatureValue(value.Index(i))) - } - return result - case reflect.Map: - if value.Type().Key().Kind() != reflect.String { - return value.Interface() - } - result := make(map[string]any, value.Len()) - iter := value.MapRange() - for iter.Next() { - result[iter.Key().String()] = canonicalizeSignatureValue(iter.Value()) - } - return result - default: - if value.CanInterface() { - return value.Interface() - } - return nil - } -} - -func gatewayRestartRequiredBySignature(bootSignature, currentSignature, gatewayStatus string) bool { - if gatewayStatus != "running" { - return false - } - if bootSignature == "" || currentSignature == "" { - return false - } - return bootSignature != currentSignature -} - -func isCmdProcessAliveLocked(cmd *exec.Cmd) bool { - if cmd == nil || cmd.Process == nil { - return false - } - - // Wait() sets ProcessState when the process exits; use it when available. - if cmd.ProcessState != nil && cmd.ProcessState.Exited() { - return false - } - - // Windows does not support Signal(0) probing. If we still own cmd and it - // has not reported exit, treat it as alive. - if runtime.GOOS == "windows" { - return true - } - - err := cmd.Process.Signal(syscall.Signal(0)) - if err == nil { - return true - } - var errno syscall.Errno - // EPERM means the process exists but cannot be signaled by this user. - return errors.As(err, &errno) && errno == syscall.EPERM -} - -func setGatewayRuntimeStatusLocked(status string) { - gateway.runtimeStatus = status - if status == "starting" || status == "restarting" { - gateway.startupDeadline = time.Now().Add(gatewayStartupWindow) - return - } - gateway.startupDeadline = time.Time{} -} - -// attachToGatewayProcess attaches to an existing gateway process by PID -// and updates the gateway state accordingly. -// Assumes gateway.mu is held by the caller. -func attachToGatewayProcessLocked(pid int, cfg *config.Config) error { - process, err := os.FindProcess(pid) - if err != nil { - return fmt.Errorf("failed to find process for PID %d: %w", pid, err) - } - - gateway.cmd = &exec.Cmd{Process: process} - gateway.owned = false // We didn't start this process - setGatewayRuntimeStatusLocked("running") - - // Update bootDefaultModel and bootConfigSignature from config - if cfg != nil { - defaultModelName := strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - gateway.bootDefaultModel = defaultModelName - gateway.bootConfigSignature = computeConfigSignature(cfg) - } - - logger.InfoC("gateway", fmt.Sprintf("Attached to gateway process (PID: %d)", pid)) - return nil -} - -func gatewayStatusWithoutHealthLocked() string { - if gateway.runtimeStatus == "starting" || gateway.runtimeStatus == "restarting" { - if gateway.startupDeadline.IsZero() || time.Now().Before(gateway.startupDeadline) { - return gateway.runtimeStatus - } - return "error" - } - if gateway.runtimeStatus == "running" { - // For attached processes there is no waiter goroutine; degrade stale - // running state once the tracked process exits. - if !isCmdProcessAliveLocked(gateway.cmd) { - gateway.cmd = nil - gateway.owned = false - gateway.bootDefaultModel = "" - gateway.bootConfigSignature = "" - return "stopped" - } - return "running" - } - if gateway.runtimeStatus == "error" { - return "error" - } - return "stopped" -} - -func waitForGatewayProcessExit(cmd *exec.Cmd, timeout time.Duration) bool { - if cmd == nil || cmd.Process == nil { - return true - } - - deadline := time.Now().Add(timeout) - for { - if !isCmdProcessAliveLocked(cmd) { - return true - } - if time.Now().After(deadline) { - return false - } - time.Sleep(gatewayRestartPollInterval) - } -} - -// StopGateway stops the gateway process if it was started by this handler. -// This method is called during application shutdown to ensure the gateway subprocess -// is properly terminated. It only stops processes that were started by this handler, -// not processes that were attached to from existing instances. -func (h *Handler) StopGateway() { - gateway.mu.Lock() - defer gateway.mu.Unlock() - - // Only stop if we own the process (started it ourselves) - if !gateway.owned || gateway.cmd == nil || gateway.cmd.Process == nil { - return - } - - pid, err := stopGatewayLocked() - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Failed to stop gateway (PID %d): %v", pid, err)) - return - } - - logger.InfoC("gateway", fmt.Sprintf("Gateway stopped (PID: %d)", pid)) -} - -// stopGatewayLocked sends a stop signal to the gateway process. -// Assumes gateway.mu is held by the caller. -// Returns the PID of the stopped process and any error encountered. -func stopGatewayLocked() (int, error) { - if gateway.cmd == nil || gateway.cmd.Process == nil { - return 0, nil - } - - pid := gateway.cmd.Process.Pid - if !gateway.owned { - if isGateway, inspected := gatewayProcessMatcher(pid); inspected && !isGateway { - return pid, fmt.Errorf("refuse to stop non-gateway process (PID %d)", pid) - } - } - - // Send SIGTERM for graceful shutdown (SIGKILL on Windows) - var sigErr error - if runtime.GOOS == "windows" { - sigErr = gateway.cmd.Process.Kill() - } else { - sigErr = gateway.cmd.Process.Signal(syscall.SIGTERM) - } - - if sigErr != nil { - return pid, sigErr - } - - logger.InfoC("gateway", fmt.Sprintf("Sent stop signal to gateway (PID: %d)", pid)) - gateway.cmd = nil - gateway.owned = false - gateway.bootDefaultModel = "" - gateway.pidData = nil - setGatewayRuntimeStatusLocked("stopped") - - return pid, nil -} - -func stopGatewayProcessForRestart(cmd *exec.Cmd) error { - if cmd == nil || cmd.Process == nil || !isCmdProcessAliveLocked(cmd) { - return nil - } - - var stopErr error - if runtime.GOOS == "windows" { - stopErr = cmd.Process.Kill() - } else { - stopErr = cmd.Process.Signal(syscall.SIGTERM) - } - if stopErr != nil && isCmdProcessAliveLocked(cmd) { - return fmt.Errorf("failed to stop existing gateway: %w", stopErr) - } - - if waitForGatewayProcessExit(cmd, gatewayRestartGracePeriod) { - return nil - } - - if runtime.GOOS != "windows" { - killErr := cmd.Process.Signal(syscall.SIGKILL) - if killErr != nil && isCmdProcessAliveLocked(cmd) { - return fmt.Errorf("failed to force-stop existing gateway: %w", killErr) - } - if waitForGatewayProcessExit(cmd, gatewayRestartForceKillWindow) { - return nil - } - } - - return fmt.Errorf("existing gateway did not exit before restart") -} - -func (h *Handler) startGatewayLocked(initialStatus string, existingPid int) (int, error) { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return 0, fmt.Errorf("failed to load config: %w", err) - } - defaultModelName := strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - - var cmd *exec.Cmd - var pid int - - if existingPid > 0 { - // Attach to existing process - pid = existingPid - gateway.cmd = nil // Clear first to ensure clean state - if err = attachToGatewayProcessLocked(pid, cfg); err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Failed to attach to existing gateway (PID %d): %v", pid, err)) - return 0, err - } - - return pid, nil - } - - // Start new process - // Locate the picoclaw executable - execPath := utils.FindPicoclawBinary() - logger.InfoC("gateway", fmt.Sprintf("Starting gateway process (%s)", execPath)) - - cmd = gatewayExecCommand(execPath, h.gatewayCommandArgs()...) - applyLauncherProcAttrs(cmd) - cmd.Env = os.Environ() - // Forward the launcher's config path via the environment variable that - // GetConfigPath() already reads, so the gateway sub-process uses the same - // config file without requiring a --config flag on the gateway subcommand. - if h.configPath != "" { - cmd.Env = append(cmd.Env, config.EnvConfig+"="+h.configPath) - } - gatewayHostOverride := h.gatewayHostOverride() - if gatewayHostOverride != "" { - cmd.Env = append(cmd.Env, config.EnvGatewayHost+"="+gatewayHostOverride) - } - - stdoutPipe, err := cmd.StdoutPipe() - if err != nil { - return 0, fmt.Errorf("failed to create stdout pipe: %w", err) - } - - stderrPipe, err := cmd.StderrPipe() - if err != nil { - return 0, fmt.Errorf("failed to create stderr pipe: %w", err) - } - - // Clear old logs for this new run - gateway.logs.Reset() - - // Ensure Pico Channel is configured before starting gateway - changed, err := h.EnsurePicoChannel() - if err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Warning: failed to ensure pico channel: %v", err)) - // Non-fatal: gateway can still start without pico channel - } - // Refresh cached pico token in case EnsurePicoChannel generated a new one. - // Already holding gateway.mu from caller. - if changed { - refreshPicoTokensLocked(h.configPath) - cfg, err = config.LoadConfig(h.configPath) - if err != nil { - return 0, fmt.Errorf("failed to reload config after ensuring pico channel: %w", err) - } - defaultModelName = strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - } - - if err := cmd.Start(); err != nil { - return 0, fmt.Errorf("failed to start gateway: %w", err) - } - - gateway.cmd = cmd - gateway.owned = true // We started this process - gateway.bootDefaultModel = defaultModelName - gateway.bootConfigSignature = computeConfigSignature(cfg) - setGatewayRuntimeStatusLocked(initialStatus) - pid = cmd.Process.Pid - logger.InfoC("gateway", fmt.Sprintf("Started picoclaw gateway (PID: %d) from %s", pid, execPath)) - - // Capture stdout/stderr in background - go scanPipe(stdoutPipe, gateway.logs) - go scanPipe(stderrPipe, gateway.logs) - - // Wait for exit in background and clean up - go func() { - if err := cmd.Wait(); err != nil { - logger.ErrorC("gateway", fmt.Sprintf("Gateway process exited: %v", err)) - } else { - logger.InfoC("gateway", "Gateway process exited normally") - } - - gateway.mu.Lock() - if gateway.cmd == cmd { - gateway.cmd = nil - gateway.bootDefaultModel = "" - gateway.bootConfigSignature = "" - if gateway.runtimeStatus != "restarting" { - setGatewayRuntimeStatusLocked("stopped") - } - } - gateway.mu.Unlock() - }() - - // Start a goroutine to probe pidFile and health, update runtime state once ready. - go func() { - healthConfirmed := false - for i := 0; i < 30; i++ { // try for up to 15 seconds - time.Sleep(500 * time.Millisecond) - gateway.mu.Lock() - stillOurs := gateway.cmd == cmd - gateway.mu.Unlock() - if !stillOurs { - return - } - - // Poll for pidFile first — once available we have port/host/token. - if pd := ppid.ReadPidFileWithCheck(globalConfigDir()); pd != nil && pd.PID == pid { - gateway.mu.Lock() - if gateway.cmd == cmd { - gateway.pidData = pd - var picoCfg config.PicoSettings - if bc := cfg.Channels.GetByType(config.ChannelPico); bc != nil { - decoded, err := bc.GetDecoded() - if err == nil && decoded != nil { - if p, ok := decoded.(*config.PicoSettings); ok { - picoCfg = *p - } - } - } - gateway.picoToken = picoCfg.Token.String() - setGatewayRuntimeStatusLocked("running") - } - gateway.mu.Unlock() - logger.InfoC("gateway", fmt.Sprintf("Gateway pidFile detected (PID: %d, port: %d)", pd.PID, pd.Port)) - return - } - - // Fallback: probe health endpoint to confirm liveness. - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - continue - } - _, statusCode, err := h.getGatewayHealth(cfg, 1*time.Second) - if err == nil && statusCode == http.StatusOK { - gateway.mu.Lock() - if gateway.cmd == cmd { - setGatewayRuntimeStatusLocked("running") - } - gateway.mu.Unlock() - if !healthConfirmed { - healthConfirmed = true - logger.InfoC("gateway", "Gateway health endpoint reachable; waiting for pid file") - } - continue - } - } - }() - - return pid, nil -} - -// handleGatewayStart starts the picoclaw gateway subprocess. -// -// POST /api/gateway/start -func (h *Handler) handleGatewayStart(w http.ResponseWriter, r *http.Request) { - // Check PID file first to detect an already-running gateway. - pidData := h.sanitizeGatewayPidData(ppid.ReadPidFileWithCheck(globalConfigDir()), nil) - if pidData != nil { - pid := pidData.PID - gateway.mu.Lock() - ready, reason, err := h.gatewayStartReady() - if err != nil { - gateway.mu.Unlock() - http.Error( - w, - fmt.Sprintf("Failed to validate gateway start conditions: %v", err), - http.StatusInternalServerError, - ) - return - } - if !ready { - gateway.mu.Unlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(map[string]any{ - "status": "precondition_failed", - "message": reason, - }) - return - } - _, err = h.startGatewayLocked("starting", pid) - if err != nil { - gateway.mu.Unlock() - logger.ErrorC("gateway", fmt.Sprintf("Failed to attach to running gateway (PID: %d): %v", pid, err)) - http.Error(w, fmt.Sprintf("Failed to attach to gateway: %v", err), http.StatusInternalServerError) - return - } - gateway.pidData = pidData - gateway.mu.Unlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ - "status": "ok", - "pid": pid, - }) - return - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - - if gateway.cmd != nil && gateway.cmd.Process != nil { - gateway.cmd = nil - setGatewayRuntimeStatusLocked("stopped") - } - - ready, reason, err := h.gatewayStartReady() - if err != nil { - http.Error( - w, - fmt.Sprintf("Failed to validate gateway start conditions: %v", err), - http.StatusInternalServerError, - ) - return - } - if !ready { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(map[string]any{ - "status": "precondition_failed", - "message": reason, - }) - return - } - - pid, err := h.startGatewayLocked("starting", 0) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to start gateway: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "ok", - "pid": pid, - }) -} - -// handleGatewayStop stops the running gateway subprocess gracefully. -// Note: Unlike StopGateway (which only stops self-started processes), this API endpoint -// stops any gateway process, including attached ones. This is intentional for user control. -// -// POST /api/gateway/stop -func (h *Handler) handleGatewayStop(w http.ResponseWriter, r *http.Request) { - gateway.mu.Lock() - defer gateway.mu.Unlock() - - if gateway.cmd == nil || gateway.cmd.Process == nil { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "not_running", - }) - return - } - - pid, err := stopGatewayLocked() - if err != nil { - http.Error(w, fmt.Sprintf("Failed to stop gateway (PID %d): %v", pid, err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "ok", - "pid": pid, - }) -} - -// RestartGateway restarts the gateway process. This is a non-blocking operation -// that stops the current gateway (if running) and starts a new one. -// Returns the PID of the new gateway process or an error. -func (h *Handler) RestartGateway() (int, error) { - ready, reason, err := h.gatewayStartReady() - if err != nil { - return 0, fmt.Errorf("failed to validate gateway start conditions: %w", err) - } - if !ready { - return 0, &preconditionFailedError{reason: reason} - } - - gateway.mu.Lock() - previousCmd := gateway.cmd - previousOwned := gateway.owned - setGatewayRuntimeStatusLocked("restarting") - gateway.mu.Unlock() - - if previousCmd != nil && previousCmd.Process != nil && !previousOwned { - if isGateway, inspected := gatewayProcessMatcher(previousCmd.Process.Pid); inspected && !isGateway { - logger.Warnf("refuse restarting non-gateway process (PID: %d)", previousCmd.Process.Pid) - gateway.mu.Lock() - if gateway.cmd == previousCmd { - setGatewayRuntimeStatusLocked("running") - } - gateway.mu.Unlock() - return 0, fmt.Errorf("refuse to restart non-gateway process (PID %d)", previousCmd.Process.Pid) - } - } - - if err = stopGatewayProcessForRestart(previousCmd); err != nil { - gateway.mu.Lock() - if gateway.cmd == previousCmd { - if isCmdProcessAliveLocked(previousCmd) { - setGatewayRuntimeStatusLocked("running") - } else { - gateway.cmd = nil - gateway.bootDefaultModel = "" - setGatewayRuntimeStatusLocked("error") - } - } - gateway.mu.Unlock() - return 0, fmt.Errorf("failed to stop gateway: %w", err) - } - - gateway.mu.Lock() - if gateway.cmd == previousCmd { - gateway.cmd = nil - gateway.bootDefaultModel = "" - } - pid, err := h.startGatewayLocked("restarting", 0) - if err != nil { - gateway.cmd = nil - gateway.bootDefaultModel = "" - setGatewayRuntimeStatusLocked("error") - } - gateway.mu.Unlock() - if err != nil { - return 0, fmt.Errorf("failed to start gateway: %w", err) - } - - return pid, nil -} - -// preconditionFailedError is returned when gateway restart preconditions are not met -type preconditionFailedError struct { - reason string -} - -func (e *preconditionFailedError) Error() string { - return e.reason -} - -// IsBadRequest returns true if the error should result in a 400 Bad Request status -func (e *preconditionFailedError) IsBadRequest() bool { - return true -} - -// handleGatewayRestart stops the gateway (if running) and starts a new instance. -// -// POST /api/gateway/restart -func (h *Handler) handleGatewayRestart(w http.ResponseWriter, r *http.Request) { - pid, err := h.RestartGateway() - if err != nil { - // Check if it's a precondition failed error - var precondErr *preconditionFailedError - if errors.As(err, &precondErr) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(map[string]any{ - "status": "precondition_failed", - "message": precondErr.reason, - }) - return - } - http.Error(w, fmt.Sprintf("Failed to restart gateway: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "ok", - "pid": pid, - }) -} - -// handleGatewayClearLogs clears the in-memory gateway log buffer. -// -// POST /api/gateway/logs/clear -func (h *Handler) handleGatewayClearLogs(w http.ResponseWriter, r *http.Request) { - gateway.logs.Clear() - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "cleared", - "log_total": 0, - "log_run_id": gateway.logs.RunID(), - }) -} - -// handleGatewayStatus returns the gateway run status and health info. -// -// GET /api/gateway/status -func (h *Handler) handleGatewayStatus(w http.ResponseWriter, r *http.Request) { - data := h.gatewayStatusData() - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(data) -} - -func (h *Handler) gatewayStatusData() map[string]any { - data := map[string]any{} - var configDefaultModel string - cfg, cfgErr := config.LoadConfig(h.configPath) - if cfgErr == nil && cfg != nil { - configDefaultModel = strings.TrimSpace(cfg.Agents.Defaults.GetModelName()) - if configDefaultModel != "" { - data["config_default_model"] = configDefaultModel - } - } - - // Primary detection: read PID file and check if process is alive. - pidData := h.sanitizeGatewayPidData(ppid.ReadPidFileWithCheck(globalConfigDir()), cfg) - if pidData != nil { - gateway.mu.Lock() - gateway.pidData = pidData - if pidData.Version != "" { - data["gateway_version"] = pidData.Version - } - setGatewayRuntimeStatusLocked("running") - - // Attach if we don't already track this PID. - if gateway.cmd == nil || gateway.cmd.Process == nil || gateway.cmd.Process.Pid != pidData.PID { - _ = attachToGatewayProcessLocked(pidData.PID, cfg) - } - - bootDefaultModel := gateway.bootDefaultModel - if bootDefaultModel != "" { - data["boot_default_model"] = bootDefaultModel - } - data["gateway_status"] = "running" - data["pid"] = pidData.PID - gateway.mu.Unlock() - } else { - // Intentionally skip health probe here; the startup goroutine - // (startGatewayLocked) already handles liveness detection via - // pidFile polling and health fallback. - gateway.mu.Lock() - status := gatewayStatusWithoutHealthLocked() - data["gateway_status"] = status - // Keep last known pidData while gateway is still in a transient - // running state; otherwise websocket proxy may lose auth token - // during short pid-file races. - if status == "stopped" || status == "error" { - gateway.pidData = nil - } - gateway.mu.Unlock() - } - - gatewayStatus, _ := data["gateway_status"].(string) - currentConfigSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - bootConfigSignature := gateway.bootConfigSignature - gateway.mu.Unlock() - data["gateway_restart_required"] = gatewayRestartRequiredBySignature( - bootConfigSignature, - currentConfigSignature, - gatewayStatus, - ) - - ready, reason, readyErr := h.gatewayStartReady() - if readyErr != nil { - data["gateway_start_allowed"] = false - data["gateway_start_reason"] = readyErr.Error() - } else { - data["gateway_start_allowed"] = ready - if !ready { - data["gateway_start_reason"] = reason - } - } - - return data -} - -// handleGatewayLogs returns buffered gateway logs, optionally incrementally. -// -// GET /api/gateway/logs -func (h *Handler) handleGatewayLogs(w http.ResponseWriter, r *http.Request) { - data := gatewayLogsData(r) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(data) -} - -// gatewayLogsData reads log_offset and log_run_id query params from the request -// and returns incremental log lines. -func gatewayLogsData(r *http.Request) map[string]any { - data := map[string]any{} - clientOffset := 0 - clientRunID := -1 - - if v := r.URL.Query().Get("log_offset"); v != "" { - if n, err := strconv.Atoi(v); err == nil { - clientOffset = n - } - } - - if v := r.URL.Query().Get("log_run_id"); v != "" { - if n, err := strconv.Atoi(v); err == nil { - clientRunID = n - } - } - - runID := gateway.logs.RunID() - - if runID == 0 { - data["logs"] = []string{} - data["log_total"] = 0 - data["log_run_id"] = 0 - return data - } - - // If runID changed, reset offset to get all logs from new run - offset := clientOffset - if clientRunID != runID { - offset = 0 - } - - lines, total, runID := gateway.logs.LinesSince(offset) - if lines == nil { - lines = []string{} - } - - data["logs"] = lines - data["log_total"] = total - data["log_run_id"] = runID - return data -} - -// scanPipe reads lines from r and appends them to buf. Returns when r reaches EOF. -func scanPipe(r io.Reader, buf *LogBuffer) { - scanner := bufio.NewScanner(r) - scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) - for scanner.Scan() { - buf.Append(scanner.Text()) - } -} diff --git a/web/backend/api/gateway_host.go b/web/backend/api/gateway_host.go deleted file mode 100644 index 03af7a9d..00000000 --- a/web/backend/api/gateway_host.go +++ /dev/null @@ -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" -} diff --git a/web/backend/api/gateway_host_test.go b/web/backend/api/gateway_host_test.go deleted file mode 100644 index 54d1010d..00000000 --- a/web/backend/api/gateway_host_test.go +++ /dev/null @@ -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) - } -} diff --git a/web/backend/api/gateway_test.go b/web/backend/api/gateway_test.go deleted file mode 100644 index f0cac9a0..00000000 --- a/web/backend/api/gateway_test.go +++ /dev/null @@ -1,2594 +0,0 @@ -package api - -import ( - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/auth" - "github.com/sipeed/picoclaw/pkg/config" - ppid "github.com/sipeed/picoclaw/pkg/pid" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -func startLongRunningProcess(t *testing.T) *exec.Cmd { - t.Helper() - - var cmd *exec.Cmd - if runtime.GOOS == "windows" { - cmd = exec.Command("powershell", "-NoProfile", "-Command", "Start-Sleep -Seconds 30") - } else { - cmd = exec.Command("sleep", "30") - } - - if err := cmd.Start(); err != nil { - t.Fatalf("Start() error = %v", err) - } - - return cmd -} - -func startGatewayLikeProcess(t *testing.T) *exec.Cmd { - t.Helper() - - var cmd *exec.Cmd - if runtime.GOOS == "windows" { - t.Skip("gateway-like process commandline check is not deterministic on Windows tests") - } - cmd = exec.Command("sh", "-c", "sleep 30 # picoclaw gateway") - - if err := cmd.Start(); err != nil { - t.Fatalf("Start() error = %v", err) - } - - return cmd -} - -func writeTestPidFile(t *testing.T, data ppid.PidFileData) string { - t.Helper() - - path := filepath.Join(globalConfigDir(), ".picoclaw.pid") - raw, err := json.MarshalIndent(data, "", " ") - if err != nil { - t.Fatalf("marshal pid file: %v", err) - } - if err := os.WriteFile(path, raw, 0o600); err != nil { - t.Fatalf("write pid file: %v", err) - } - return path -} - -func mockGatewayHealthResponse(statusCode, pid int) *http.Response { - return &http.Response{ - StatusCode: statusCode, - Body: io.NopCloser(strings.NewReader( - `{"status":"ok","uptime":"1s","pid":` + strconv.Itoa(pid) + `}`, - )), - } -} - -func startIgnoringTermProcess(t *testing.T) *exec.Cmd { - t.Helper() - - if runtime.GOOS == "windows" { - t.Skip("TERM handling differs on Windows") - } - - cmd := exec.Command("sh", "-c", "trap '' TERM; sleep 30") - if err := cmd.Start(); err != nil { - t.Fatalf("Start() error = %v", err) - } - - return cmd -} - -func resetGatewayTestState(t *testing.T) { - t.Helper() - - originalHealthGet := gatewayHealthGet - originalProcessMatcher := gatewayProcessMatcher - originalExecCommand := gatewayExecCommand - originalRestartGracePeriod := gatewayRestartGracePeriod - originalRestartForceKillWindow := gatewayRestartForceKillWindow - originalRestartPollInterval := gatewayRestartPollInterval - t.Setenv("PICOCLAW_HOME", t.TempDir()) - t.Cleanup(func() { - gatewayHealthGet = originalHealthGet - gatewayProcessMatcher = originalProcessMatcher - gatewayExecCommand = originalExecCommand - gatewayRestartGracePeriod = originalRestartGracePeriod - gatewayRestartForceKillWindow = originalRestartForceKillWindow - gatewayRestartPollInterval = originalRestartPollInterval - - gateway.mu.Lock() - gateway.cmd = nil - gateway.pidData = nil - gateway.owned = false - gateway.bootDefaultModel = "" - gateway.bootConfigSignature = "" - setGatewayRuntimeStatusLocked("stopped") - gateway.mu.Unlock() - }) -} - -func TestPicoGatewayProtocol(t *testing.T) { - resetGatewayTestState(t) - - gateway.mu.Lock() - gateway.picoToken = "ui-token" - gateway.mu.Unlock() - - if got := picoGatewayProtocol(); got != tokenPrefix+"ui-token" { - t.Fatalf("picoGatewayProtocol() = %q, want %q", got, tokenPrefix+"ui-token") - } -} - -type gatewayStartEnvSnapshot struct { - GatewayHost string `json:"gateway_host"` - GatewayHostSet bool `json:"gateway_host_set"` - ConfigPath string `json:"config_path"` -} - -func TestGatewayStartHelperProcess(t *testing.T) { - var envPath string - for i, arg := range os.Args { - if arg == "--" && i+2 < len(os.Args) && os.Args[i+1] == "gateway-env-helper" { - envPath = os.Args[i+2] - break - } - } - if envPath == "" { - t.Skip("helper process") - } - - host, ok := os.LookupEnv(config.EnvGatewayHost) - raw, err := json.Marshal(gatewayStartEnvSnapshot{ - GatewayHost: host, - GatewayHostSet: ok, - ConfigPath: os.Getenv(config.EnvConfig), - }) - if err != nil { - _, _ = io.WriteString(os.Stderr, err.Error()) - os.Exit(2) - } - if err := os.WriteFile(envPath, raw, 0o600); err != nil { - _, _ = io.WriteString(os.Stderr, err.Error()) - os.Exit(2) - } - os.Exit(0) -} - -func unsetGatewayStartEnvForTest(t *testing.T, key string) { - t.Helper() - - prev, hadPrev := os.LookupEnv(key) - if err := os.Unsetenv(key); err != nil { - t.Fatalf("Unsetenv(%q) error = %v", key, err) - } - t.Cleanup(func() { - if hadPrev { - _ = os.Setenv(key, prev) - return - } - _ = os.Unsetenv(key) - }) -} - -func newGatewayStartTestHandler(t *testing.T) *Handler { - t.Helper() - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - h.SetServerOptions(18800, false, false, nil) - return h -} - -func startGatewayAndCaptureEnv(t *testing.T, h *Handler) gatewayStartEnvSnapshot { - t.Helper() - - unsetGatewayStartEnvForTest(t, config.EnvGatewayHost) - - envPath := filepath.Join(t.TempDir(), "gateway-child-env.json") - gatewayExecCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command( - os.Args[0], - "-test.run=TestGatewayStartHelperProcess", - "--", - "gateway-env-helper", - envPath, - ) - } - - pid, err := h.startGatewayLocked("starting", 0) - if err != nil { - t.Fatalf("startGatewayLocked() error = %v", err) - } - if pid <= 0 { - t.Fatalf("startGatewayLocked() pid = %d, want > 0", pid) - } - - deadline := time.Now().Add(3 * time.Second) - for { - raw, err := os.ReadFile(envPath) - if err == nil { - var snapshot gatewayStartEnvSnapshot - err = json.Unmarshal(raw, &snapshot) - if err != nil { - t.Fatalf("Unmarshal(child env) error = %v", err) - } - return snapshot - } - if !os.IsNotExist(err) { - t.Fatalf("ReadFile(%q) error = %v", envPath, err) - } - if time.Now().After(deadline) { - t.Fatalf("timed out waiting for gateway child env snapshot %q", envPath) - } - time.Sleep(20 * time.Millisecond) - } -} - -func TestStartGatewayLocked_ForwardsLauncherHostOverrideToGatewayEnv(t *testing.T) { - h := newGatewayStartTestHandler(t) - h.SetServerBindHost("127.0.0.1,::1", true) - - snapshot := startGatewayAndCaptureEnv(t, h) - if !snapshot.GatewayHostSet { - t.Fatal("gateway host env was not set") - } - if snapshot.GatewayHost != "127.0.0.1,::1" { - t.Fatalf("gateway host env = %q, want %q", snapshot.GatewayHost, "127.0.0.1,::1") - } - if snapshot.ConfigPath != h.configPath { - t.Fatalf("config env = %q, want %q", snapshot.ConfigPath, h.configPath) - } -} - -func TestStartGatewayLocked_ForwardsLauncherHostFromEnvironmentToGatewayEnv(t *testing.T) { - h := newGatewayStartTestHandler(t) - h.SetServerBindHost("::", true) - - snapshot := startGatewayAndCaptureEnv(t, h) - if !snapshot.GatewayHostSet { - t.Fatal("gateway host env was not set") - } - if snapshot.GatewayHost != "::" { - t.Fatalf("gateway host env = %q, want %q", snapshot.GatewayHost, "::") - } -} - -func TestStartGatewayLocked_ForwardsWildcardHostForPublicLauncher(t *testing.T) { - h := newGatewayStartTestHandler(t) - h.SetServerOptions(18800, true, true, nil) - - snapshot := startGatewayAndCaptureEnv(t, h) - if !snapshot.GatewayHostSet { - t.Fatal("gateway host env was not set") - } - if snapshot.GatewayHost != "*" { - t.Fatalf("gateway host env = %q, want %q", snapshot.GatewayHost, "*") - } -} - -func TestStartGatewayLocked_UsesReloadedConfigForBootSignature(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("sleep command differs on Windows") - } - - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - delete(cfg.Channels, "pico") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - h.SetServerOptions(18800, false, false, nil) - gatewayExecCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command("sleep", "30") - } - - originalSignature := computeConfigSignature(cfg) - pid, err := h.startGatewayLocked("starting", 0) - if err != nil { - t.Fatalf("startGatewayLocked() error = %v", err) - } - if pid <= 0 { - t.Fatalf("startGatewayLocked() pid = %d, want > 0", pid) - } - - gateway.mu.Lock() - cmd := gateway.cmd - bootSignature := gateway.bootConfigSignature - gateway.mu.Unlock() - t.Cleanup(func() { - if cmd != nil && cmd.Process != nil { - _ = cmd.Process.Kill() - } - if cmd != nil { - _ = cmd.Wait() - } - }) - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - expectedSignature := computeConfigSignature(updatedCfg) - if expectedSignature == originalSignature { - t.Fatal("expected EnsurePicoChannel() to change the config signature during gateway start") - } - if bootSignature != expectedSignature { - t.Fatalf("bootConfigSignature = %q, want %q", bootSignature, expectedSignature) - } -} - -func TestGatewayStartReady_NoDefaultModel(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatalf("gatewayStartReady() ready = true, want false") - } - if reason != "no default model configured" { - t.Fatalf("gatewayStartReady() reason = %q, want %q", reason, "no default model configured") - } -} - -func TestGatewayStartReady_RejectsASROnlyDefaultModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - cfg.Agents.Defaults.ModelName = "elevenlabs-asr" - - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatal("gatewayStartReady() ready = true, want false") - } - if reason != `default model "elevenlabs-asr" is not usable for chat` { - t.Fatalf( - "gatewayStartReady() reason = %q, want %q", - reason, - `default model "elevenlabs-asr" is not usable for chat`, - ) - } -} - -func TestLooksLikeGatewayCommandLine(t *testing.T) { - cases := []struct { - name string - cmdline string - want bool - }{ - { - name: "default picoclaw gateway", - cmdline: "/usr/local/bin/picoclaw gateway -E", - want: true, - }, - { - name: "renamed binary with gateway subcommand", - cmdline: "/opt/bin/custom-claw gateway -E -d", - want: true, - }, - { - name: "standalone gateway binary path", - cmdline: "/opt/bin/gateway -E", - want: true, - }, - { - name: "non gateway process", - cmdline: "/bin/sleep 30", - want: false, - }, - { - name: "gateway substring only", - cmdline: "/opt/bin/gatewayd --serve", - want: false, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := looksLikeGatewayCommandLine(tc.cmdline) - if got != tc.want { - t.Fatalf("looksLikeGatewayCommandLine(%q) = %v, want %v", tc.cmdline, got, tc.want) - } - }) - } -} - -func TestValidateGatewayPidDataAcceptsHealthWhenMatcherInconclusive(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - const testPID = 34567 - pidData := &ppid.PidFileData{ - PID: testPID, - Host: "127.0.0.1", - Port: 18790, - } - - gatewayProcessMatcher = func(int) (bool, bool) { return false, false } - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, testPID), nil - } - - ok, decisive, reason := h.validateGatewayPidData(pidData, nil) - if !ok { - t.Fatalf("validateGatewayPidData() ok = false, want true (reason=%q)", reason) - } - if !decisive { - t.Fatalf("validateGatewayPidData() decisive = false, want true") - } -} - -func TestValidateGatewayPidDataRejectsHealthPidMismatchWhenMatcherInconclusive(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - pidData := &ppid.PidFileData{ - PID: 34567, - Host: "127.0.0.1", - Port: 18790, - } - - gatewayProcessMatcher = func(int) (bool, bool) { return false, false } - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, 99999), nil - } - - ok, decisive, reason := h.validateGatewayPidData(pidData, nil) - if ok { - t.Fatalf("validateGatewayPidData() ok = true, want false") - } - if !decisive { - t.Fatalf("validateGatewayPidData() decisive = false, want true") - } - if !strings.Contains(reason, "health pid mismatch") { - t.Fatalf("validateGatewayPidData() reason = %q, want contains %q", reason, "health pid mismatch") - } -} - -func TestGatewayStartReady_InvalidDefaultModel(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "missing-model" - err := config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatalf("gatewayStartReady() ready = true, want false") - } - if reason == "" { - t.Fatalf("gatewayStartReady() reason is empty") - } -} - -func TestGatewayStartReady_ValidDefaultModel(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - err := config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true (reason=%q)", reason) - } -} - -func TestGatewayStartReady_RejectsInvalidDuplicateAliasEntry(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "shared" - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "shared", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("test-key"), - }, - { - ModelName: "shared", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("audio-key"), - }, - } - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatal("gatewayStartReady() ready = true, want false") - } - if !strings.Contains(reason, "cannot be used as the default chat model") { - t.Fatalf("gatewayStartReady() reason = %q, want duplicate alias rejection", reason) - } -} - -func TestGatewayStartReady_RawDefaultModelUsesProviderTemplate(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "openrouter/deepseek/deepseek-v3.2" - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "openrouter-template", - Model: "openrouter/auto", - APIBase: "https://openrouter.ai/api/v1", - }} - cfg.ModelList[0].SetAPIKey("test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true (reason=%q)", reason) - } -} - -func TestGatewayStartReady_DefaultModelWithoutCredential(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("") - cfg.ModelList[0].AuthMethod = "" - err := config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatalf("gatewayStartReady() ready = true, want false") - } - if !strings.Contains(reason, "no credentials configured") { - t.Fatalf("gatewayStartReady() reason = %q, want contains %q", reason, "no credentials configured") - } -} - -func TestGatewayCommandArgsIncludesDebugFlagWhenEnabled(t *testing.T) { - h := NewHandler(filepath.Join(t.TempDir(), "config.json")) - h.SetDebug(true) - - args := h.gatewayCommandArgs() - want := []string{"gateway", "-E", "-d"} - if strings.Join(args, " ") != strings.Join(want, " ") { - t.Fatalf("gatewayCommandArgs() = %v, want %v", args, want) - } -} - -func TestGatewayStartReady_LocalModelWithoutAPIKey(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetModelProbeHooks(t) - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - return false - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "local-vllm", - Model: "vllm/custom-model", - APIBase: "http://localhost:8000/v1", - }} - cfg.Agents.Defaults.ModelName = "local-vllm" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatalf("gatewayStartReady() ready = true, want false without a running local service") - } - if !strings.Contains(reason, "not reachable") { - t.Fatalf("gatewayStartReady() reason = %q, want contains %q", reason, "not reachable") - } -} - -func TestGatewayStartReady_LocalModelWithRunningService(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetModelProbeHooks(t) - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - return apiBase == "http://127.0.0.1:8000/v1" && modelID == "custom-model" && apiKey == "" - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "local-vllm", - Model: "vllm/custom-model", - APIBase: "http://127.0.0.1:8000/v1", - }} - cfg.Agents.Defaults.ModelName = "local-vllm" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true with a running local service (reason=%q)", reason) - } -} - -func TestGatewayStartReady_RemoteVLLMWithAPIKeyDoesNotProbe(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetModelProbeHooks(t) - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - t.Fatalf("unexpected OpenAI-compatible probe for %q (%q)", apiBase, modelID) - return false - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "remote-vllm", - Model: "vllm/custom-model", - APIBase: "https://models.example.com/v1", - }} - cfg.ModelList[0o0].SetAPIKey("remote-key") - cfg.Agents.Defaults.ModelName = "remote-vllm" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true for remote vllm with api key (reason=%q)", reason) - } -} - -func TestGatewayStartReady_LocalOllamaUsesDefaultProbeBase(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetModelProbeHooks(t) - - probeOllamaModelFunc = func(apiBase, modelID string) bool { - return apiBase == "http://localhost:11434/v1" && modelID == "llama3" - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "local-ollama", - Model: "ollama/llama3", - }} - cfg.Agents.Defaults.ModelName = "local-ollama" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true with default Ollama probe base (reason=%q)", reason) - } -} - -func TestGatewayStartReady_OAuthModelRequiresStoredCredential(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "openai-oauth", - Model: "openai/gpt-5.4", - AuthMethod: "oauth", - }} - cfg.Agents.Defaults.ModelName = "openai-oauth" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - ready, reason, err := h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if ready { - t.Fatalf("gatewayStartReady() ready = true, want false without stored credential") - } - if !strings.Contains(reason, "no credentials configured") { - t.Fatalf("gatewayStartReady() reason = %q, want contains %q", reason, "no credentials configured") - } - - err = auth.SetCredential(oauthProviderOpenAI, &auth.AuthCredential{ - AccessToken: "openai-token", - Provider: oauthProviderOpenAI, - AuthMethod: "oauth", - }) - if err != nil { - t.Fatalf("SetCredential() error = %v", err) - } - - ready, reason, err = h.gatewayStartReady() - if err != nil { - t.Fatalf("gatewayStartReady() error = %v", err) - } - if !ready { - t.Fatalf("gatewayStartReady() ready = false, want true with stored credential (reason=%q)", reason) - } -} - -func TestGatewayStatusIncludesStartConditionWhenNotReady(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.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - allowed, ok := body["gateway_start_allowed"].(bool) - if !ok { - t.Fatalf("gateway_start_allowed missing or not bool: %#v", body["gateway_start_allowed"]) - } - if allowed { - t.Fatalf("gateway_start_allowed = true, want false") - } - if _, ok := body["gateway_start_reason"].(string); !ok { - t.Fatalf("gateway_start_reason missing or not string: %#v", body["gateway_start_reason"]) - } -} - -func TestGatewayStatusKeepsRunningWhenHealthProbeFailsAfterRunning(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.bootDefaultModel = "existing-model" - // Simulate a process that has already reached the running state. - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return nil, errors.New("probe failed") - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } -} - -func TestGatewayStatusKeepsPidDataWhileTrackedProcessAliveWhenPidFileUnavailable(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.pidData = &ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "existing-token", - } - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.pidData == nil { - t.Fatal("gateway.pidData was cleared while runtime status remained running") - } -} - -func TestGatewayStatusDowngradesRunningWhenTrackedProcessExitedAndPidFileMissing(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.pidData = &ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "stale-token", - } - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - if got := body["gateway_status"]; got != "stopped" { - t.Fatalf("gateway_status = %#v, want %q", got, "stopped") - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.pidData != nil { - t.Fatal("gateway.pidData should be cleared when tracked process has exited") - } -} - -func TestGatewayStatusIgnoresAndRemovesPidFileForNonGatewayProcess(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - pidPath := writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "stale-token", - Host: "127.0.0.1", - Port: 18790, - }) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - if got := body["gateway_status"]; got != "stopped" { - t.Fatalf("gateway_status = %#v, want %q", got, "stopped") - } - if _, err := os.Stat(pidPath); !os.IsNotExist(err) { - t.Fatal("stale pid file should be removed for non-gateway process") - } -} - -func TestGatewayStopRefusesNonGatewayAttachedProcess(t *testing.T) { - resetGatewayTestState(t) - if runtime.GOOS == "windows" { - t.Skip("commandline-based process type check is best-effort on Windows") - } - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.owned = false - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/gateway/stop", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError) - } - if !isCmdProcessAliveLocked(cmd) { - t.Fatal("non-gateway process should not be terminated by /api/gateway/stop") - } -} - -func TestGatewayStatusReportsRunningFromPidProbe(t *testing.T) { - resetGatewayTestState(t) - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - setGatewayRuntimeStatusLocked("stopped") - gateway.mu.Unlock() - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, cmd.Process.Pid), nil - } - - writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: "127.0.0.1", - Port: 18790, - }) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != false { - t.Fatalf("gateway_restart_required = %#v, want false", got) - } -} - -func TestGatewayStatusRequiresRestartAfterDefaultModelChange(t *testing.T) { - resetGatewayTestState(t) - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - cfg.ModelList = append(cfg.ModelList, &config.ModelConfig{ - ModelName: "second-model", - Model: "openai/gpt-4.1", - }) - cfg.ModelList[len(cfg.ModelList)-1].SetAPIKey("second-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: "127.0.0.1", - Port: 18790, - }) - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = cmd - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Agents.Defaults.ModelName = "second-model" - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["boot_default_model"]; got != cfg.ModelList[0].ModelName { - t.Fatalf("boot_default_model = %#v, want %q", got, cfg.ModelList[0].ModelName) - } - if got := body["config_default_model"]; got != "second-model" { - t.Fatalf("config_default_model = %#v, want %q", got, "second-model") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestGatewayStatusRequiresRestartAfterFallbackOrderChange(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "primary", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-primary"), - }, - { - ModelName: "backup-a", - Provider: "anthropic", - Model: "claude-sonnet-4.6", - APIKeys: config.SimpleSecureStrings("sk-backup-a"), - }, - { - ModelName: "backup-b", - Provider: "gemini", - Model: "gemini-2.5-pro", - APIKeys: config.SimpleSecureStrings("sk-backup-b"), - }, - } - cfg.Agents.Defaults.ModelName = "primary" - cfg.Agents.Defaults.ModelFallbacks = []string{"backup-a", "backup-b"} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Agents.Defaults.ModelFallbacks = []string{"backup-b", "backup-a"} - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestModelStreamingSignaturesIncludeRawFallbackOrder(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{openAIModelConfig("primary")} - cfg.Agents.Defaults.ModelName = "primary" - cfg.Agents.Defaults.ModelFallbacks = []string{ - "openrouter/fallback-a", - "anthropic/fallback-b", - } - - before := strings.Join(computeModelStreamingSignatures(cfg), "\n") - cfg.Agents.Defaults.ModelFallbacks = []string{ - "anthropic/fallback-b", - "openrouter/fallback-a", - } - after := strings.Join(computeModelStreamingSignatures(cfg), "\n") - - if before == after { - t.Fatalf("raw fallback reorder did not change signatures:\n%s", before) - } -} - -func TestGatewayStatusRequiresRestartAfterToolChange(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - cfg.Tools.WriteFile.Enabled = true - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Tools.WriteFile.Enabled = false - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestGatewayStatusRequiresRestartAfterChannelChange(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - telegram := updatedCfg.Channels.Get("telegram") - if telegram == nil { - t.Fatalf("expected default telegram channel config") - } - telegram.Enabled = !telegram.Enabled - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestGatewayStatusRequiresRestartAfterDefaultModelStreamingChange(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: false} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestConfigSignatureIncludesModelStreamingForDefaultModelRef(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList[0].ModelName = "friendly-alias" - cfg.ModelList[0].Provider = "" - cfg.ModelList[0].Model = "openai/gpt-4o-ref" - cfg.Agents.Defaults.ModelName = "openai/gpt-4o-ref" - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: false} - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change when streaming changes for a default model referenced by model ref") - } -} - -func TestConfigSignatureIncludesModelStreamingForLoadBalancedAliasEntries(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "lb-alias", - Model: "openai/gpt-4o-primary", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - { - ModelName: "lb-alias", - Model: "openai/gpt-4o-secondary", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.ModelName = "lb-alias" - - before := computeConfigSignature(cfg) - - cfg.ModelList[1].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change when streaming changes for a load-balanced alias entry") - } -} - -func TestConfigSignatureIncludesSlashModelIDForDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "nvidia-model", - Provider: "nvidia", - Model: "z-ai/glm-5.1", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "z-ai/glm-5.1" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for a slash-containing model id on the default provider", - ) - } -} - -func TestConfigSignatureIncludesSupportedPrefixSlashModelIDForDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "openrouter-openai", - Provider: "openrouter", - Model: "openai/gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "openrouter" - cfg.Agents.Defaults.ModelName = "openai/gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for a supported-prefix slash model id on the default provider", - ) - } -} - -func TestConfigSignatureIncludesLegacyDefaultProviderPrefixedSlashModelID(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "legacy-openrouter-openai", - Model: "openrouter/openai/gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "openrouter" - cfg.Agents.Defaults.ModelName = "openai/gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for a legacy default-provider prefixed slash model id", - ) - } -} - -func TestConfigSignatureIncludesSlashModelIDWithoutProviderFieldForDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "nvidia-model", - Model: "z-ai/glm-5.1", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "z-ai/glm-5.1" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for a default-provider slash model id without provider field", - ) - } -} - -func TestConfigSignatureIncludesUnknownSlashPrefixModelIDWithoutProviderFieldForDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "nvidia-meta", - Model: "meta/llama-3.1-8b", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "meta/llama-3.1-8b" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for unknown-prefix default-provider slash model id", - ) - } -} - -func TestConfigSignatureDashAliasSlashModelIDMatchesProviderAlias(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "zai-model", - Provider: "zai", - Model: "glm-5.1", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "z-ai/glm-5.1" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change when a dash-alias slash ref matches a provider alias") - } -} - -func TestConfigSignatureDashAliasSlashModelIDMatchesProviderAliasWithOpenAIDefault(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "zai-model", - Provider: "zai", - Model: "glm-5.1", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "openai" - cfg.Agents.Defaults.ModelName = "z-ai/glm-5.1" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when a dash-alias slash ref matches a provider alias with OpenAI default", - ) - } -} - -func TestConfigSignatureProviderAliasRefIgnoresDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "openai-gpt", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "gpt/gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change for a provider alias ref even when default provider differs") - } -} - -func TestConfigSignatureExplicitProviderRefIgnoresDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "openai-gpt", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "openai/gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change for an explicit provider ref even when default provider differs") - } -} - -func TestConfigSignatureExactModelNameTakesPrecedenceOverResolvedRefs(t *testing.T) { - tests := []struct { - name string - defaultProvider string - defaultModelName string - models []*config.ModelConfig - shadowedEntryIndex int - exactModelNameIndex int - shadowedChangeMessage string - exactChangeMessage string - }{ - { - name: "slash model name shadows explicit provider ref", - defaultProvider: "nvidia", - defaultModelName: "openai/gpt-4o", - models: []*config.ModelConfig{ - { - ModelName: "openai/gpt-4o", - Provider: "nvidia", - Model: "openai/gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - { - ModelName: "openai-gpt", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - }, - shadowedEntryIndex: 1, - exactModelNameIndex: 0, - shadowedChangeMessage: "config signature should not change when an exact slash model_name shadows an explicit provider ref", - exactChangeMessage: "config signature should change when the exact slash model_name entry changes", - }, - { - name: "bare model name shadows default provider model id", - defaultProvider: "openai", - defaultModelName: "gpt-4o", - models: []*config.ModelConfig{ - { - ModelName: "gpt-4o", - Provider: "anthropic", - Model: "claude-sonnet", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - { - ModelName: "openai-gpt", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - }, - shadowedEntryIndex: 1, - exactModelNameIndex: 0, - shadowedChangeMessage: "config signature should not change when an exact bare model_name shadows a default-provider model id", - exactChangeMessage: "config signature should change when the exact bare model_name entry changes", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = tt.models - cfg.Agents.Defaults.Provider = tt.defaultProvider - cfg.Agents.Defaults.ModelName = tt.defaultModelName - - before := computeConfigSignature(cfg) - - cfg.ModelList[tt.shadowedEntryIndex].Streaming = config.ModelStreamingConfig{Enabled: true} - afterShadowedChange := computeConfigSignature(cfg) - - if before != afterShadowedChange { - t.Fatal(tt.shadowedChangeMessage) - } - - cfg.ModelList[tt.exactModelNameIndex].Streaming = config.ModelStreamingConfig{Enabled: true} - afterExactModelNameChange := computeConfigSignature(cfg) - - if before == afterExactModelNameChange { - t.Fatal(tt.exactChangeMessage) - } - }) - } -} - -func TestConfigSignatureIncludesLoadBalancedDuplicateEntryIndex(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "lb-alias", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - { - ModelName: "lb-alias", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: true}, - }, - } - cfg.Agents.Defaults.ModelName = "lb-alias" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming.Enabled = true - cfg.ModelList[1].Streaming.Enabled = false - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal("config signature should change when duplicate load-balanced entries swap streaming state") - } -} - -func TestConfigSignatureProviderDotAliasRefIgnoresDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "zai-model", - Provider: "zai", - Model: "glm-5.1", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "nvidia" - cfg.Agents.Defaults.ModelName = "z.ai/glm-5.1" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change for an explicit dot-alias provider ref even when default provider differs", - ) - } -} - -func TestConfigSignatureIncludesDefaultProviderPrefixedRefWithSplitConfig(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "openai-split", - Provider: "openai", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "openai" - cfg.Agents.Defaults.ModelName = "openai/gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - after := computeConfigSignature(cfg) - - if before == after { - t.Fatal( - "config signature should change when streaming changes for default-provider prefixed ref with split config", - ) - } -} - -func TestConfigSignatureBareModelRefUsesDefaultProviderModelID(t *testing.T) { - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "azure-alias", - Provider: "azure", - Model: "gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - { - ModelName: "openai-alias", - Model: "openai/gpt-4o", - Streaming: config.ModelStreamingConfig{Enabled: false}, - }, - } - cfg.Agents.Defaults.Provider = "openai" - cfg.Agents.Defaults.ModelName = "gpt-4o" - - before := computeConfigSignature(cfg) - - cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true} - afterExactModelChange := computeConfigSignature(cfg) - - if before != afterExactModelChange { - t.Fatal("config signature should not change for a bare model entry on another provider") - } - - cfg.ModelList[1].Streaming = config.ModelStreamingConfig{Enabled: true} - afterDefaultProviderModelChange := computeConfigSignature(cfg) - - if afterExactModelChange == afterDefaultProviderModelChange { - t.Fatal("config signature should change when the default-provider model id changes streaming") - } -} - -func TestConfigSignatureChangesWithDefaultProvider(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Agents.Defaults.Provider = "openai" - cfg.Agents.Defaults.ModelName = "gpt-4o" - cfg.ModelList = []*config.ModelConfig{{ModelName: "legacy", Model: "gpt-4o"}} - before := computeConfigSignature(cfg) - - cfg.Agents.Defaults.Provider = "openrouter" - after := computeConfigSignature(cfg) - if before == after { - t.Fatal("config signature should change when the effective default provider changes") - } -} - -func TestGatewayStatusRequiresRestartAfterWebSearchConfigChange(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - cfg.Tools.Web.Enabled = true - cfg.Tools.Web.Provider = "sogou" - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Tools.Web.Provider = "duckduckgo" - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != true { - t.Fatalf("gateway_restart_required = %#v, want true", got) - } -} - -func TestGatewayStatusNoRestartRequiredForNonSensitiveChanges(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - cfg.Agents.Defaults.MaxTokens = 1000 - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - process, err := os.FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("FindProcess() error = %v", err) - } - - bootSignature := computeConfigSignature(cfg) - gateway.mu.Lock() - gateway.cmd = &exec.Cmd{Process: process} - gateway.bootDefaultModel = cfg.ModelList[0].ModelName - gateway.bootConfigSignature = bootSignature - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Agents.Defaults.MaxTokens = 2000 - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "running" { - t.Fatalf("gateway_status = %#v, want %q", got, "running") - } - if got := body["gateway_restart_required"]; got != false { - t.Fatalf("gateway_restart_required = %#v, want false", got) - } -} - -func TestGatewayStatusNoRestartRequiredWhenNotRunning(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - gateway.mu.Lock() - gateway.cmd = nil - gateway.bootDefaultModel = "" - gateway.bootConfigSignature = "" - setGatewayRuntimeStatusLocked("stopped") - gateway.mu.Unlock() - - updatedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - updatedCfg.Agents.Defaults.ModelName = "different-model" - if err := config.SaveConfig(configPath, updatedCfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return nil, errors.New("no gateway running") - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "stopped" { - t.Fatalf("gateway_status = %#v, want %q", got, "stopped") - } - if got := body["gateway_restart_required"]; got != false { - t.Fatalf("gateway_restart_required = %#v, want false", got) - } -} - -func TestGatewayStatusReturnsErrorAfterStartupWindowExpires(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.bootDefaultModel = "existing-model" - setGatewayRuntimeStatusLocked("starting") - gateway.startupDeadline = time.Now().Add(-time.Second) - gateway.mu.Unlock() - - gatewayHealthGet = func(string, time.Duration) (*http.Response, error) { - return nil, errors.New("probe failed") - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "error" { - t.Fatalf("gateway_status = %#v, want %q", got, "error") - } -} - -func TestGatewayStatusReturnsRestartingDuringRestartGap(t *testing.T) { - resetGatewayTestState(t) - - // Mock health check to return error, so it won't override our "restarting" status - gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) { - return nil, errors.New("mock health check error") - } - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - gateway.mu.Lock() - setGatewayRuntimeStatusLocked("restarting") - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "restarting" { - t.Fatalf("gateway_status = %#v, want %q", got, "restarting") - } -} - -func TestGatewayRestartKeepsRunningProcessWhenPreconditionsFail(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("") - cfg.ModelList[0].AuthMethod = "" - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startLongRunningProcess(t) - t.Cleanup(func() { - gateway.mu.Lock() - if gateway.cmd == cmd { - gateway.cmd = nil - gateway.bootDefaultModel = "" - } - gateway.mu.Unlock() - - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.bootDefaultModel = "existing-model" - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/gateway/restart", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest) - } - - gateway.mu.Lock() - stillRunning := gateway.cmd == cmd && isCmdProcessAliveLocked(cmd) - gateway.mu.Unlock() - - if !stillRunning { - t.Fatalf("gateway process was stopped when restart preconditions failed") - } -} - -func TestGatewayRestartKeepsOldProcessWhenItDoesNotExitInTime(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - cmd := startIgnoringTermProcess(t) - t.Cleanup(func() { - gateway.mu.Lock() - if gateway.cmd == cmd { - gateway.cmd = nil - gateway.bootDefaultModel = "" - } - gateway.mu.Unlock() - - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - gatewayRestartGracePeriod = 150 * time.Millisecond - gatewayRestartForceKillWindow = 150 * time.Millisecond - gatewayRestartPollInterval = 10 * time.Millisecond - - gateway.mu.Lock() - gateway.cmd = cmd - gateway.bootDefaultModel = "existing-model" - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/gateway/restart", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError) - } - - gateway.mu.Lock() - stillRunning := gateway.cmd == cmd && isCmdProcessAliveLocked(cmd) - status := gateway.runtimeStatus - gateway.mu.Unlock() - - if !stillRunning { - t.Fatalf("gateway process was replaced before the old process exited") - } - if status != "running" { - t.Fatalf("runtimeStatus = %q, want %q", status, "running") - } -} - -func TestGatewayRestartReturnsErrorStatusWhenReplacementFailsToStart(t *testing.T) { - resetGatewayTestState(t) - - // Mock health check to return error, so it won't override our "error" status - gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) { - return nil, errors.New("mock health check error") - } - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = cfg.ModelList[0].ModelName - cfg.ModelList[0].SetAPIKey("test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - invalidBinaryPath := filepath.Join(t.TempDir(), "fake-picoclaw") - if err := os.WriteFile(invalidBinaryPath, []byte("#!/bin/sh\n"), 0o644); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - t.Setenv("PICOCLAW_BINARY", invalidBinaryPath) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/gateway/restart", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("restart status = %d, want %d", rec.Code, http.StatusInternalServerError) - } - - statusRec := httptest.NewRecorder() - statusReq := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(statusRec, statusReq) - - if statusRec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", statusRec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(statusRec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got := body["gateway_status"]; got != "error" { - t.Fatalf("gateway_status = %#v, want %q", got, "error") - } -} - -func TestGatewayStatusExcludesLogsFields(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.MethodGet, "/api/gateway/status", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if _, ok := body["logs"]; ok { - t.Fatalf("logs unexpectedly present in status response: %#v", body["logs"]) - } - if _, ok := body["log_total"]; ok { - t.Fatalf("log_total unexpectedly present in status response: %#v", body["log_total"]) - } - if _, ok := body["log_run_id"]; ok { - t.Fatalf("log_run_id unexpectedly present in status response: %#v", body["log_run_id"]) - } -} - -func TestGatewayLogsReturnsIncrementalHistory(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - gateway.logs.Clear() - gateway.logs.Append("first line") - gateway.logs.Append("second line") - runID := gateway.logs.RunID() - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodGet, - "/api/gateway/logs?log_offset=1&log_run_id="+strconv.Itoa(runID), - nil, - ) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("logs status = %d, want %d", rec.Code, http.StatusOK) - } - - var body map[string]any - if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { - t.Fatalf("unmarshal logs response: %v", err) - } - - logs, ok := body["logs"].([]any) - if !ok { - t.Fatalf("logs missing or not array: %#v", body["logs"]) - } - if len(logs) != 1 || logs[0] != "second line" { - t.Fatalf("logs = %#v, want [\"second line\"]", logs) - } - if got := body["log_total"]; got != float64(2) { - t.Fatalf("log_total = %#v, want 2", got) - } - if got := body["log_run_id"]; got != float64(runID) { - t.Fatalf("log_run_id = %#v, want %d", got, runID) - } -} - -func TestGatewayClearLogsResetsBufferedHistory(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - gateway.logs.Clear() - gateway.logs.Append("first line") - gateway.logs.Append("second line") - previousRunID := gateway.logs.RunID() - - clearRec := httptest.NewRecorder() - clearReq := httptest.NewRequest(http.MethodPost, "/api/gateway/logs/clear", nil) - mux.ServeHTTP(clearRec, clearReq) - - if clearRec.Code != http.StatusOK { - t.Fatalf("clear status = %d, want %d", clearRec.Code, http.StatusOK) - } - - var clearBody map[string]any - if err := json.Unmarshal(clearRec.Body.Bytes(), &clearBody); err != nil { - t.Fatalf("unmarshal clear response: %v", err) - } - - if got := clearBody["status"]; got != "cleared" { - t.Fatalf("clear status body = %#v, want %q", got, "cleared") - } - - clearRunID, ok := clearBody["log_run_id"].(float64) - if !ok { - t.Fatalf("log_run_id missing or not number: %#v", clearBody["log_run_id"]) - } - if int(clearRunID) <= previousRunID { - t.Fatalf("log_run_id = %d, want > %d", int(clearRunID), previousRunID) - } - - logsRec := httptest.NewRecorder() - logsReq := httptest.NewRequest( - http.MethodGet, - "/api/gateway/logs?log_offset=0&log_run_id="+strconv.Itoa(previousRunID), - nil, - ) - mux.ServeHTTP(logsRec, logsReq) - - if logsRec.Code != http.StatusOK { - t.Fatalf("logs code = %d, want %d", logsRec.Code, http.StatusOK) - } - - var logsBody map[string]any - if err := json.Unmarshal(logsRec.Body.Bytes(), &logsBody); err != nil { - t.Fatalf("unmarshal logs response: %v", err) - } - - logs, ok := logsBody["logs"].([]any) - if !ok { - t.Fatalf("logs missing or not array: %#v", logsBody["logs"]) - } - if len(logs) != 0 { - t.Fatalf("logs len = %d, want 0", len(logs)) - } - if got := logsBody["log_total"]; got != float64(0) { - t.Fatalf("log_total = %#v, want 0", got) - } - if got := logsBody["log_run_id"]; got != clearBody["log_run_id"] { - t.Fatalf("log_run_id = %#v, want %#v", got, clearBody["log_run_id"]) - } -} - -func TestFindPicoclawBinary_EnvOverride(t *testing.T) { - // Create a temporary file to act as the mock binary - tmpDir := t.TempDir() - mockBinary := filepath.Join(tmpDir, "picoclaw-mock") - if err := os.WriteFile(mockBinary, []byte("mock"), 0o755); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - t.Setenv("PICOCLAW_BINARY", mockBinary) - - got := utils.FindPicoclawBinary() - if got != mockBinary { - t.Errorf("FindPicoclawBinary() = %q, want %q", got, mockBinary) - } -} - -func TestFindPicoclawBinary_EnvOverride_InvalidPath(t *testing.T) { - // When PICOCLAW_BINARY points to a non-existent path, fall through to next strategy - t.Setenv("PICOCLAW_BINARY", "/nonexistent/picoclaw-binary") - - got := utils.FindPicoclawBinary() - // Should not return the invalid path; falls back to "picoclaw" or another found path - if got == "/nonexistent/picoclaw-binary" { - t.Errorf("FindPicoclawBinary() returned invalid env path %q, expected fallback", got) - } -} - -func TestModelConfigsMatchingSignatureRef_BareUsesDefaultProvider(t *testing.T) { - models := []*config.ModelConfig{ - {ModelName: "openrouter-model", Provider: "openrouter", Model: "gpt-4o"}, - {ModelName: "openai-model", Provider: "openai", Model: "gpt-4o"}, - } - - matches := modelConfigsMatchingSignatureRef(models, "gpt-4o", "openai") - if len(matches) != 1 || matches[0].model.ModelName != "openai-model" { - t.Fatalf("matches = %#v, want openai-model", matches) - } -} - -func TestModelConfigsMatchingSignatureRefUsesResolverScore(t *testing.T) { - models := []*config.ModelConfig{ - { - ModelName: "disabled", - Provider: "openrouter", - Model: "target", - }, - { - ModelName: "enabled", - Provider: "openrouter", - Model: "target", - Enabled: true, - }, - } - - matches := modelConfigsMatchingSignatureRef(models, "openrouter/target", "openai") - if len(matches) != 1 || matches[0].index != 1 { - t.Fatalf("matches = %#v, want resolver-selected index 1", matches) - } -} diff --git a/web/backend/api/launcher_config.go b/web/backend/api/launcher_config.go deleted file mode 100644 index 1e1de9f6..00000000 --- a/web/backend/api/launcher_config.go +++ /dev/null @@ -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...), - }) -} diff --git a/web/backend/api/launcher_config_test.go b/web/backend/api/launcher_config_test.go deleted file mode 100644 index 43af6068..00000000 --- a/web/backend/api/launcher_config_test.go +++ /dev/null @@ -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()) - } -} diff --git a/web/backend/api/log.go b/web/backend/api/log.go deleted file mode 100644 index f83f6f34..00000000 --- a/web/backend/api/log.go +++ /dev/null @@ -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 -} diff --git a/web/backend/api/model_catalog.go b/web/backend/api/model_catalog.go deleted file mode 100644 index edce03cf..00000000 --- a/web/backend/api/model_catalog.go +++ /dev/null @@ -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"}) -} diff --git a/web/backend/api/model_catalog_test.go b/web/backend/api/model_catalog_test.go deleted file mode 100644 index 76138fdc..00000000 --- a/web/backend/api/model_catalog_test.go +++ /dev/null @@ -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)), - ) - } - } - } - }) - } -} diff --git a/web/backend/api/model_status.go b/web/backend/api/model_status.go deleted file mode 100644 index 2ebd9a3c..00000000 --- a/web/backend/api/model_status.go +++ /dev/null @@ -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< 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) -} diff --git a/web/backend/api/model_status_test.go b/web/backend/api/model_status_test.go deleted file mode 100644 index 7a8155e4..00000000 --- a/web/backend/api/model_status_test.go +++ /dev/null @@ -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)") - } -} diff --git a/web/backend/api/models.go b/web/backend/api/models.go deleted file mode 100644 index a2782644..00000000 --- a/web/backend/api/models.go +++ /dev/null @@ -1,1612 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/sipeed/picoclaw/pkg/audio/asr" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/providers" -) - -// registerModelRoutes binds model list management endpoints to the ServeMux. -func (h *Handler) registerModelRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/models", h.handleListModels) - mux.HandleFunc("GET /api/models/default-chain", h.handleGetDefaultChain) - mux.HandleFunc("POST /api/models/fetch", h.handleFetchModels) - mux.HandleFunc("GET /api/models/catalog", h.handleListCatalogs) - mux.HandleFunc("DELETE /api/models/catalog/{id}", h.handleDeleteCatalog) - mux.HandleFunc("POST /api/models", h.handleAddModel) - mux.HandleFunc("POST /api/models/default", h.handleSetDefaultModel) - mux.HandleFunc("PUT /api/models/default-chain", h.handleUpdateDefaultChain) - mux.HandleFunc("PUT /api/models/{index}", h.handleUpdateModel) - mux.HandleFunc("DELETE /api/models/{index}", h.handleDeleteModel) - mux.HandleFunc("POST /api/models/{index}/test", h.handleTestModel) - mux.HandleFunc("POST /api/models/test-inline", h.handleTestInlineModel) -} - -// modelResponse is the JSON structure returned for each model in the list. -// All ModelConfig fields are included so the frontend can display and edit them. -type modelResponse struct { - Index int `json:"index"` - ModelName string `json:"model_name"` - Provider string `json:"provider,omitempty"` - Model string `json:"model"` - APIBase string `json:"api_base,omitempty"` - APIKey string `json:"api_key"` - Proxy string `json:"proxy,omitempty"` - AuthMethod string `json:"auth_method,omitempty"` - // Advanced fields - ConnectMode string `json:"connect_mode,omitempty"` - Workspace string `json:"workspace,omitempty"` - RPM int `json:"rpm,omitempty"` - MaxTokensField string `json:"max_tokens_field,omitempty"` - RequestTimeout int `json:"request_timeout,omitempty"` - ThinkingLevel string `json:"thinking_level,omitempty"` - ToolSchemaTransform string `json:"tool_schema_transform,omitempty"` - Streaming config.ModelStreamingConfig `json:"streaming,omitempty"` - ExtraBody map[string]any `json:"extra_body,omitempty"` - CustomHeaders map[string]string `json:"custom_headers,omitempty"` - // Meta - Enabled bool `json:"enabled"` - Available bool `json:"available"` - Status string `json:"status"` - IsDefault bool `json:"is_default"` - IsVirtual bool `json:"is_virtual"` - DefaultModelAllowed bool `json:"default_model_allowed"` -} - -type defaultChainResponse struct { - DefaultModel string `json:"default_model"` - FallbackChain []string `json:"fallback_chain"` -} - -type defaultChainRequest struct { - DefaultModel string `json:"default_model"` - FallbackChain []string `json:"fallback_chain"` -} - -func normalizeStoredModelConfig(mc *config.ModelConfig, defaultProvider string) bool { - if mc == nil { - return false - } - - changed := false - modelName := strings.TrimSpace(mc.ModelName) - if modelName != mc.ModelName { - mc.ModelName = modelName - changed = true - } - model := strings.TrimSpace(mc.Model) - if model != mc.Model { - mc.Model = model - changed = true - } - provider := strings.TrimSpace(mc.Provider) - if provider != mc.Provider { - mc.Provider = provider - changed = true - } - authMethod := strings.ToLower(strings.TrimSpace(mc.AuthMethod)) - if authMethod != mc.AuthMethod { - mc.AuthMethod = authMethod - changed = true - } - - if provider != "" { - normalizedProvider := providers.NormalizeProvider(provider) - if providers.IsSupportedModelProvider(normalizedProvider) && normalizedProvider != provider { - mc.Provider = normalizedProvider - changed = true - } - if mc.Provider == "elevenlabs" { - if _, strippedModel, found := strings.Cut( - model, - "/", - ); found && - providers.NormalizeProvider(strings.TrimSpace(provider)) == "elevenlabs" { - strippedModel = strings.TrimSpace(strippedModel) - if strippedModel != "" && strippedModel != mc.Model { - mc.Model = strippedModel - changed = true - } - } - if strings.TrimSpace(mc.Model) != asr.ElevenLabsSupportedModelID() { - mc.Model = asr.ElevenLabsSupportedModelID() - changed = true - } - } - return changed - } - - effectiveProvider, modelID := providers.SplitModelProviderAndID(model, defaultProvider) - if effectiveProvider == "" { - return changed - } - if mc.Provider != effectiveProvider { - mc.Provider = effectiveProvider - changed = true - } - if mc.Model != modelID { - mc.Model = modelID - changed = true - } - return changed -} - -func normalizeIncomingModelConfig(mc *config.ModelConfig, defaultProvider string) { - if mc == nil { - return - } - - mc.ModelName = strings.TrimSpace(mc.ModelName) - mc.Model = strings.TrimSpace(mc.Model) - mc.Provider = strings.TrimSpace(mc.Provider) - mc.AuthMethod = strings.ToLower(strings.TrimSpace(mc.AuthMethod)) - if mc.Provider == "" { - mc.Provider, mc.Model = providers.SplitModelProviderAndID(mc.Model, defaultProvider) - } else { - mc.Provider = providers.NormalizeProvider(mc.Provider) - if mc.Provider == "elevenlabs" { - if _, strippedModel, found := strings.Cut(mc.Model, "/"); found { - strippedModel = strings.TrimSpace(strippedModel) - if strippedModel != "" { - mc.Model = strippedModel - } - } - } - } - if mc.Provider == "antigravity" && mc.AuthMethod == "" { - mc.AuthMethod = "oauth" - } -} - -func createAllowedForProvider(provider string) bool { - normalized := providers.NormalizeProvider(provider) - switch normalized { - case "bedrock": - // Bedrock currently authenticates through the AWS SDK credential chain - // (env vars, shared profiles, IAM roles, etc.), and this Web layer does - // not yet have a reliable preflight check for those credential sources. - // Keep it creatable in the catalog and let provider construction/runtime - // return the concrete AWS error when the environment is incomplete. - return true - case "claude-cli", "codex-cli": - return cliProviderCreateAllowedFromCurrentStatus(normalized) - default: - return providers.IsCreatableModelProvider(normalized) - } -} - -// cliProviderCreateAllowedFromCurrentStatus intentionally reuses the existing -// local model status pipeline so provider catalog gating follows the same CLI -// executable probe used by launcher readiness. -func cliProviderCreateAllowedFromCurrentStatus(provider string) bool { - status := modelConfigurationStatus(&config.ModelConfig{ - Provider: provider, - Model: provider, - }) - return status.Available -} - -func modelProviderOptionsForResponse() []providers.ModelProviderOption { - options := providers.ModelProviderOptions() - for i := range options { - options[i].CreateAllowed = createAllowedForProvider(options[i].ID) - } - return options -} - -func defaultModelAllowedForModelConfig(mc *config.ModelConfig, defaultProvider string) bool { - provider, _ := modelConfigProviderAndID(mc, defaultProvider) - return providers.IsDefaultModelProvider(provider) -} - -func validateIncomingModelConfig(mc *config.ModelConfig, existing *config.ModelConfig) error { - if mc == nil { - return fmt.Errorf("model config is required") - } - if err := mc.Validate(); err != nil { - return err - } - if strings.TrimSpace(mc.Provider) == "" { - return fmt.Errorf("provider is required") - } - if !providers.IsSupportedModelProvider(mc.Provider) { - return fmt.Errorf("provider %q is not supported", mc.Provider) - } - if mc.Provider == "elevenlabs" && strings.TrimSpace(mc.Model) != asr.ElevenLabsSupportedModelID() { - return fmt.Errorf("provider %q only supports model %q", mc.Provider, asr.ElevenLabsSupportedModelID()) - } - if !createAllowedForProvider(mc.Provider) { - if existing == nil { - return fmt.Errorf("provider %q is not available for new models", mc.Provider) - } - existingProvider, _ := providers.ExtractProtocol(existing) - if providers.NormalizeProvider(existingProvider) != mc.Provider { - return fmt.Errorf("provider %q is not available for selection", mc.Provider) - } - } - return nil -} - -func normalizeStoredModelProviders(cfg *config.Config) bool { - if cfg == nil { - return false - } - - changed := false - defaultProvider := defaultChainProvider(cfg) - for _, model := range cfg.ModelList { - if normalizeStoredModelConfig(model, defaultProvider) { - changed = true - } - } - return changed -} - -func normalizeStoredModelNames(cfg *config.Config) bool { - if cfg == nil { - return false - } - changed := false - for _, model := range cfg.ModelList { - if model == nil { - continue - } - modelName := strings.TrimSpace(model.ModelName) - if modelName != model.ModelName { - model.ModelName = modelName - changed = true - } - } - return changed -} - -func trimModelNameList(names []string) []string { - trimmed := make([]string, 0, len(names)) - for _, name := range names { - name = strings.TrimSpace(name) - if name == "" { - continue - } - trimmed = append(trimmed, name) - } - return trimmed -} - -func dedupeModelNameList(names []string) []string { - if len(names) == 0 { - return nil - } - seen := make(map[string]struct{}, len(names)) - deduped := make([]string, 0, len(names)) - for _, name := range names { - if _, ok := seen[name]; ok { - continue - } - seen[name] = struct{}{} - deduped = append(deduped, name) - } - return deduped -} - -func modelConfigsByName(cfg *config.Config) map[string][]*config.ModelConfig { - models := make(map[string][]*config.ModelConfig, len(cfg.ModelList)) - for _, model := range cfg.ModelList { - if model == nil { - continue - } - name := strings.TrimSpace(model.ModelName) - if name == "" { - continue - } - models[name] = append(models[name], model) - } - return models -} - -func modelConfigsByNameExceptIndex( - cfg *config.Config, - modelName string, - exceptIndex int, -) []*config.ModelConfig { - modelName = strings.TrimSpace(modelName) - if cfg == nil || modelName == "" { - return nil - } - models := make([]*config.ModelConfig, 0, 1) - for i, model := range cfg.ModelList { - if i == exceptIndex || model == nil { - continue - } - if strings.TrimSpace(model.ModelName) == modelName { - models = append(models, model) - } - } - return models -} - -func validateDefaultChainModelSet( - modelName string, - models []*config.ModelConfig, - defaultContext bool, - defaultProvider string, -) error { - if len(models) == 0 { - if defaultContext { - return fmt.Errorf("default model %q not found in model_list", modelName) - } - return fmt.Errorf("fallback model %q not found in model_list", modelName) - } - for _, modelCfg := range models { - if modelCfg.IsVirtual() { - if defaultContext { - return fmt.Errorf("cannot set virtual model %q as default", modelName) - } - return fmt.Errorf("cannot add virtual model %q to fallback_chain", modelName) - } - if !defaultModelAllowedForModelConfig(modelCfg, defaultProvider) { - if defaultContext { - return fmt.Errorf("model %q cannot be used as the default chat model", modelName) - } - return fmt.Errorf("model %q cannot be used in the fallback chain", modelName) - } - effectiveModelCfg := modelCfg - if strings.TrimSpace(modelCfg.Provider) == "" { - clone := *modelCfg - normalizeStoredModelConfig(&clone, defaultProvider) - effectiveModelCfg = &clone - } - if !hasModelConfiguration(effectiveModelCfg) { - return rawModelConfigurationError(modelName, defaultContext) - } - } - return nil -} - -func validateDefaultChainReference( - cfg *config.Config, - modelName string, - models []*config.ModelConfig, - defaultContext bool, -) error { - if len(models) > 0 { - return validateDefaultChainModelSet( - modelName, - models, - defaultContext, - defaultChainProvider(cfg), - ) - } - - resolved, err := providers.ResolveModelConfig(cfg, modelName) - if err != nil || resolved == nil { - ref := providers.ParseModelRef(modelName, defaultChainProvider(cfg)) - if ref != nil && - strings.TrimSpace(ref.Provider) != "" && - strings.TrimSpace(ref.Model) != "" && - !providers.IsDefaultModelProvider(ref.Provider) { - if defaultContext { - return fmt.Errorf("model %q cannot be used as the default chat model", modelName) - } - return fmt.Errorf("model %q cannot be used in the fallback chain", modelName) - } - if ref != nil && - strings.TrimSpace(ref.Provider) != "" && - strings.TrimSpace(ref.Model) != "" && - providers.IsDefaultModelProvider(ref.Provider) { - return rawModelConfigurationError(modelName, defaultContext) - } - return validateDefaultChainModelSet( - modelName, - nil, - defaultContext, - defaultChainProvider(cfg), - ) - } - if err := validateDefaultChainModelSet( - modelName, - []*config.ModelConfig{resolved}, - defaultContext, - defaultChainProvider(cfg), - ); err != nil { - return err - } - if !rawTemplateHasConfiguration(resolved) { - return rawModelConfigurationError(modelName, defaultContext) - } - return nil -} - -func rawTemplateHasConfiguration(modelCfg *config.ModelConfig) bool { - return hasModelConfiguration(modelCfg) -} - -func rawModelConfigurationError(modelName string, defaultContext bool) error { - if defaultContext { - return fmt.Errorf("default model %q has no configured provider", modelName) - } - return fmt.Errorf("fallback model %q has no configured provider", modelName) -} - -func defaultChainProvider(cfg *config.Config) string { - if cfg != nil && strings.TrimSpace(cfg.Agents.Defaults.Provider) != "" { - return providers.NormalizeProvider(cfg.Agents.Defaults.Provider) - } - return "openai" -} - -func defaultChainReferenceIdentity(cfg *config.Config, modelName string) string { - modelName = strings.TrimSpace(modelName) - if modelName == "" { - return "" - } - - defaultProvider := defaultChainProvider(cfg) - var modelList []*config.ModelConfig - if cfg != nil { - modelList = cfg.ModelList - } - matches := modelConfigsMatchingSignatureRef(modelList, modelName, defaultProvider) - if len(matches) > 0 { - modelCfg := matches[0].model - if alias := strings.TrimSpace(modelCfg.ModelName); alias != "" { - return "model_name:" + alias - } - provider, modelID := providers.ExtractProtocol(modelCfg) - return providers.ModelKey(provider, modelID) - } - - ref := providers.ParseModelRef(modelName, defaultProvider) - if ref == nil { - return "" - } - return providers.ModelKey(ref.Provider, ref.Model) -} - -func validateDefaultModelChain( - cfg *config.Config, - defaultModel string, - fallbacks []string, -) ([]string, error) { - defaultModel = strings.TrimSpace(defaultModel) - fallbacks = dedupeModelNameList(trimModelNameList(fallbacks)) - - if cfg == nil { - return nil, fmt.Errorf("config is required") - } - if defaultModel == "" && len(fallbacks) > 0 { - return nil, fmt.Errorf("default_model is required when fallback_chain is not empty") - } - - modelsByName := modelConfigsByName(cfg) - defaultIdentity := "" - if defaultModel != "" { - if err := validateDefaultChainReference( - cfg, - defaultModel, - modelsByName[defaultModel], - true, - ); err != nil { - return nil, err - } - defaultIdentity = defaultChainReferenceIdentity(cfg, defaultModel) - } - - seenIdentities := make(map[string]struct{}, len(fallbacks)) - validated := make([]string, 0, len(fallbacks)) - for _, fallback := range fallbacks { - if fallback == defaultModel { - return nil, fmt.Errorf("default model %q cannot also appear in fallback_chain", defaultModel) - } - if err := validateDefaultChainReference(cfg, fallback, modelsByName[fallback], false); err != nil { - return nil, err - } - identity := defaultChainReferenceIdentity(cfg, fallback) - if identity != "" && identity == defaultIdentity { - return nil, fmt.Errorf( - "fallback model %q resolves to the same runtime model as default model %q", - fallback, - defaultModel, - ) - } - if _, exists := seenIdentities[identity]; identity != "" && exists { - continue - } - if identity != "" { - seenIdentities[identity] = struct{}{} - } - validated = append(validated, fallback) - } - - return validated, nil -} - -func normalizeDefaultChainReferences(cfg *config.Config) { - if cfg == nil { - return - } - - defaultModel := strings.TrimSpace(cfg.Agents.Defaults.ModelName) - fallbacks := dedupeModelNameList(trimModelNameList(cfg.Agents.Defaults.ModelFallbacks)) - modelsByName := modelConfigsByName(cfg) - defaultIdentity := "" - - if defaultModel != "" { - if err := validateDefaultChainReference( - cfg, - defaultModel, - modelsByName[defaultModel], - true, - ); err != nil { - defaultModel = "" - } - defaultIdentity = defaultChainReferenceIdentity(cfg, defaultModel) - } - if defaultModel == "" { - cfg.Agents.Defaults.ModelName = "" - cfg.Agents.Defaults.ModelFallbacks = nil - return - } - - seenIdentities := make(map[string]struct{}, len(fallbacks)) - validated := make([]string, 0, len(fallbacks)) - for _, fallback := range fallbacks { - if fallback == defaultModel { - continue - } - if err := validateDefaultChainReference(cfg, fallback, modelsByName[fallback], false); err != nil { - continue - } - identity := defaultChainReferenceIdentity(cfg, fallback) - if identity != "" && identity == defaultIdentity { - continue - } - if _, exists := seenIdentities[identity]; identity != "" && exists { - continue - } - if identity != "" { - seenIdentities[identity] = struct{}{} - } - validated = append(validated, fallback) - } - - cfg.Agents.Defaults.ModelName = defaultModel - cfg.Agents.Defaults.ModelFallbacks = validated -} - -// handleListModels returns all model_list entries with masked API keys. -// -// GET /api/models -func (h *Handler) handleListModels(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 - } - - // Normalize legacy provider/model storage in memory so GET can round-trip - // through the current API shape without mutating the on-disk config. - normalizeStoredModelProviders(cfg) - normalizeDefaultChainReferences(cfg) - - defaultModel := cfg.Agents.Defaults.GetModelName() - fallbackChain := cfg.Agents.Defaults.ModelFallbacks - modelStatuses := make([]modelConfigurationSummary, len(cfg.ModelList)) - - var wg sync.WaitGroup - wg.Add(len(cfg.ModelList)) - for i, m := range cfg.ModelList { - go func(i int, m *config.ModelConfig) { - defer wg.Done() - modelStatuses[i] = modelConfigurationStatus(m) - }(i, m) - } - wg.Wait() - - models := make([]modelResponse, 0, len(cfg.ModelList)) - for i, m := range cfg.ModelList { - provider, modelID := providers.ExtractProtocol(m) - models = append(models, modelResponse{ - Index: i, - ModelName: m.ModelName, - Provider: provider, - Model: modelID, - APIBase: m.APIBase, - APIKey: maskAPIKey(m.APIKey()), - Proxy: m.Proxy, - AuthMethod: m.AuthMethod, - ConnectMode: m.ConnectMode, - Workspace: m.Workspace, - RPM: m.RPM, - MaxTokensField: m.MaxTokensField, - RequestTimeout: m.RequestTimeout, - ThinkingLevel: m.ThinkingLevel, - ToolSchemaTransform: m.ToolSchemaTransform, - Streaming: m.Streaming, - ExtraBody: m.ExtraBody, - CustomHeaders: m.CustomHeaders, - Enabled: m.Enabled, - Available: modelStatuses[i].Available, - Status: modelStatuses[i].Status, - IsDefault: m.ModelName == defaultModel, - IsVirtual: m.IsVirtual(), - DefaultModelAllowed: defaultModelAllowedForModelConfig(m, defaultChainProvider(cfg)), - }) - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "models": models, - "total": len(models), - "default_model": defaultModel, - "default_provider": defaultChainProvider(cfg), - "fallback_chain": fallbackChain, - "provider_options": modelProviderOptionsForResponse(), - }) -} - -// handleGetDefaultChain returns the persisted default model and fallback chain. -// -// GET /api/models/default-chain -func (h *Handler) handleGetDefaultChain(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 - } - normalizeStoredModelProviders(cfg) - normalizeDefaultChainReferences(cfg) - - resp := defaultChainResponse{ - DefaultModel: strings.TrimSpace(cfg.Agents.Defaults.GetModelName()), - FallbackChain: trimModelNameList(cfg.Agents.Defaults.ModelFallbacks), - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) -} - -// handleAddModel appends a new model configuration entry. -// -// POST /api/models -func (h *Handler) handleAddModel(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() - - type custom struct { - config.ModelConfig - APIKey string `json:"api_key"` - } - - var mc custom - if err = json.Unmarshal(body, &mc); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - if mc.APIKey != "" { - mc.ModelConfig.SetAPIKey(mc.APIKey) - } - - h.configMu.Lock() - defer h.configMu.Unlock() - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - normalizeIncomingModelConfig(&mc.ModelConfig, defaultChainProvider(cfg)) - if err = validateIncomingModelConfig(&mc.ModelConfig, nil); err != nil { - http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest) - return - } - - cfg.ModelList = append(cfg.ModelList, &mc.ModelConfig) - normalizeStoredModelProviders(cfg) - normalizeDefaultChainReferences(cfg) - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "status": "ok", - "index": len(cfg.ModelList) - 1, - }) -} - -// handleUpdateModel replaces a model configuration entry at the given index. -// If the request body omits api_key (or sends an empty string), the existing -// stored key is preserved so callers can update only api_base / proxy without -// exposing or clearing the secret. -// -// PUT /api/models/{index} -func (h *Handler) handleUpdateModel(w http.ResponseWriter, r *http.Request) { - idx, err := strconv.Atoi(r.PathValue("index")) - if err != nil { - http.Error(w, "Invalid index", http.StatusBadRequest) - return - } - - 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 rawFields map[string]json.RawMessage - if err = json.Unmarshal(body, &rawFields); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - type custom struct { - config.ModelConfig - APIKey string `json:"api_key"` - } - - var mc custom - if err = json.Unmarshal(body, &mc); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - h.configMu.Lock() - defer h.configMu.Unlock() - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - normalizeStoredModelProviders(cfg) - - if idx < 0 || idx >= len(cfg.ModelList) { - http.Error(w, fmt.Sprintf("Index %d out of range (0-%d)", idx, len(cfg.ModelList)-1), http.StatusNotFound) - return - } - oldModelName := strings.TrimSpace(cfg.ModelList[idx].ModelName) - - // Preserve the existing API key when the caller omits it (empty string). - // This lets the UI update api_base / proxy without clearing the stored secret. - if mc.APIKey == "" { - mc.ModelConfig.SetAPIKey(cfg.ModelList[idx].APIKey()) - } else { - mc.ModelConfig.SetAPIKey(mc.APIKey) - } - // Preserve existing ExtraBody when omitted (nil), but clear it when - // the frontend sends an empty object {} to indicate the field should - // be removed. - if mc.ExtraBody == nil { - mc.ExtraBody = cfg.ModelList[idx].ExtraBody - } else if len(mc.ExtraBody) == 0 { - mc.ExtraBody = nil - } - // Preserve existing CustomHeaders when omitted (nil), but clear it when - // the frontend sends an empty object {} to indicate the field should - // be removed. - if mc.CustomHeaders == nil { - mc.CustomHeaders = cfg.ModelList[idx].CustomHeaders - } else if len(mc.CustomHeaders) == 0 { - mc.CustomHeaders = nil - } - if _, ok := rawFields["tool_schema_transform"]; !ok { - mc.ToolSchemaTransform = cfg.ModelList[idx].ToolSchemaTransform - } - if _, ok := rawFields["streaming"]; !ok { - mc.Streaming = cfg.ModelList[idx].Streaming - } - // Preserve the existing Provider when the caller omits it. This keeps the - // update API backward-compatible for clients that haven't started sending - // the new field yet, while still allowing explicit clearing via "". - if _, ok := rawFields["provider"]; !ok { - mc.Provider = cfg.ModelList[idx].Provider - // Older clients still round-trip the legacy model field only. When the - // stored config encodes provider/model in Model and has no explicit - // Provider field yet, continue preserving that hidden provider prefix. - // This keeps provider-omitted updates backward-compatible even when an - // older client edits the visible model ID. - if strings.TrimSpace(cfg.ModelList[idx].Provider) == "" { - existingRawModel := strings.TrimSpace(cfg.ModelList[idx].Model) - incomingModel := strings.TrimSpace(mc.Model) - existingProtocol, existingModelID := providers.ExtractProtocol(cfg.ModelList[idx]) - if existingRawModel != "" && existingRawModel != existingModelID && incomingModel != "" { - if incomingModel == existingModelID { - mc.Model = existingRawModel - } else if strings.Contains(incomingModel, "/") && !strings.Contains(existingModelID, "/") { - // Older clients never saw the hidden provider prefix for simple - // legacy entries such as "openai/gpt-4o". If they now send an - // explicit provider/model string, treat it as the caller's full - // intent instead of re-applying the old hidden prefix. - mc.Model = incomingModel - } else if !strings.HasPrefix(incomingModel, existingProtocol+"/") { - mc.Model = existingProtocol + "/" + incomingModel - } - } - } - } - - normalizeIncomingModelConfig(&mc.ModelConfig, defaultChainProvider(cfg)) - if err = validateIncomingModelConfig(&mc.ModelConfig, cfg.ModelList[idx]); err != nil { - http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest) - return - } - newModelName := strings.TrimSpace(mc.ModelConfig.ModelName) - defaultReferenceRenamed := false - fallbackReferenceRenamed := false - if oldModelName != "" && newModelName != "" && oldModelName != newModelName { - remainingOldNameModels := modelConfigsByNameExceptIndex(cfg, oldModelName, idx) - if err := validateDefaultChainModelSet( - oldModelName, - remainingOldNameModels, - true, - defaultChainProvider(cfg), - ); err != nil { - defaultReferenceRenamed = true - if strings.TrimSpace(cfg.Agents.Defaults.ModelName) == oldModelName { - cfg.Agents.Defaults.ModelName = newModelName - } - } - if err := validateDefaultChainModelSet( - oldModelName, - remainingOldNameModels, - false, - defaultChainProvider(cfg), - ); err != nil { - fallbackReferenceRenamed = true - cfg.Agents.Defaults.ModelFallbacks = replaceModelName( - cfg.Agents.Defaults.ModelFallbacks, - oldModelName, - newModelName, - ) - } - } - cfg.ModelList[idx] = &mc.ModelConfig - normalizeStoredModelProviders(cfg) - normalizeDefaultChainReferences(cfg) - - logger.Debugf("update model config: %#v", mc.ModelConfig) - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - response := map[string]any{"status": "ok"} - if oldModelName != "" && newModelName != "" && oldModelName != newModelName { - response["reference_rename"] = map[string]any{ - "from": oldModelName, - "to": newModelName, - "default": defaultReferenceRenamed, - "fallback": fallbackReferenceRenamed, - } - } - json.NewEncoder(w).Encode(response) -} - -// handleDeleteModel removes a model configuration entry at the given index. -// -// DELETE /api/models/{index} -func (h *Handler) handleDeleteModel(w http.ResponseWriter, r *http.Request) { - idx, err := strconv.Atoi(r.PathValue("index")) - if err != nil { - http.Error(w, "Invalid index", http.StatusBadRequest) - return - } - - h.configMu.Lock() - defer h.configMu.Unlock() - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - normalizeStoredModelNames(cfg) - - if idx < 0 || idx >= len(cfg.ModelList) { - http.Error(w, fmt.Sprintf("Index %d out of range (0-%d)", idx, len(cfg.ModelList)-1), http.StatusNotFound) - return - } - - deletedModelName := strings.TrimSpace(cfg.ModelList[idx].ModelName) - - cfg.ModelList = append(cfg.ModelList[:idx], cfg.ModelList[idx+1:]...) - - if deletedModelName != "" { - remainingModels := modelConfigsByName(cfg)[deletedModelName] - if strings.TrimSpace(cfg.Agents.Defaults.ModelName) == deletedModelName { - if err := validateDefaultChainModelSet( - deletedModelName, - remainingModels, - true, - defaultChainProvider(cfg), - ); err != nil { - cfg.Agents.Defaults.ModelName = "" - } - } - if err := validateDefaultChainModelSet( - deletedModelName, - remainingModels, - false, - defaultChainProvider(cfg), - ); err != nil { - cfg.Agents.Defaults.ModelFallbacks = removeModelName( - cfg.Agents.Defaults.ModelFallbacks, - deletedModelName, - ) - } - } - normalizeDefaultChainReferences(cfg) - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) -} - -func removeModelName(names []string, target string) []string { - target = strings.TrimSpace(target) - if target == "" || len(names) == 0 { - return names - } - filtered := make([]string, 0, len(names)) - for _, name := range names { - if strings.TrimSpace(name) == target { - continue - } - filtered = append(filtered, name) - } - return filtered -} - -func replaceModelName(names []string, oldName string, newName string) []string { - oldName = strings.TrimSpace(oldName) - newName = strings.TrimSpace(newName) - if oldName == "" || oldName == newName || len(names) == 0 { - return names - } - replaced := make([]string, 0, len(names)) - for _, name := range names { - if strings.TrimSpace(name) == oldName { - replaced = append(replaced, newName) - continue - } - replaced = append(replaced, name) - } - return replaced -} - -// handleSetDefaultModel sets the default model for all agents. -// -// POST /api/models/default -func (h *Handler) handleSetDefaultModel(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 { - ModelName string `json:"model_name"` - } - if err = json.Unmarshal(body, &req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - modelName := strings.TrimSpace(req.ModelName) - if modelName == "" { - http.Error(w, "model_name is required", http.StatusBadRequest) - return - } - - h.configMu.Lock() - defer h.configMu.Unlock() - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - normalizeStoredModelNames(cfg) - - // Keep this legacy endpoint alias-only. Raw references are managed by the - // default-chain endpoint and may already exist in persisted configuration. - if err := validateDefaultChainModelSet( - modelName, - modelConfigsByName(cfg)[modelName], - true, - defaultChainProvider(cfg), - ); err != nil { - status := http.StatusBadRequest - if strings.Contains(err.Error(), "not found in model_list") { - status = http.StatusNotFound - } - http.Error(w, err.Error(), status) - return - } - - cfg.Agents.Defaults.ModelName = modelName - cfg.Agents.Defaults.ModelFallbacks = removeModelName(cfg.Agents.Defaults.ModelFallbacks, modelName) - normalizeDefaultChainReferences(cfg) - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{ - "status": "ok", - "default_model": modelName, - }) -} - -// handleUpdateDefaultChain updates the persisted default model and fallback chain. -// -// PUT /api/models/default-chain -func (h *Handler) handleUpdateDefaultChain(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 defaultChainRequest - if err = json.Unmarshal(body, &req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - h.configMu.Lock() - defer h.configMu.Unlock() - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - normalizeStoredModelNames(cfg) - - defaultModel := strings.TrimSpace(req.DefaultModel) - fallbacks, err := validateDefaultModelChain(cfg, defaultModel, req.FallbackChain) - if err != nil { - http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest) - return - } - - cfg.Agents.Defaults.ModelName = defaultModel - cfg.Agents.Defaults.ModelFallbacks = fallbacks - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(defaultChainResponse{ - DefaultModel: defaultModel, - FallbackChain: fallbacks, - }) -} - -// maskAPIKey returns a masked version of an API key for safe 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 maskAPIKey(key string) string { - if key == "" { - return "" - } - - if len(key) <= 8 { - return "****" - } - - // Show first 3 chars and last 2 chars - if len(key) <= 12 { - return key[:3] + "****" + key[len(key)-2:] - } - - // Show first 3 chars and last 4 chars - return key[:3] + "****" + key[len(key)-4:] -} - -// handleFetchModels fetches available models from an upstream provider. -// -// POST /api/models/fetch -func (h *Handler) handleFetchModels(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"` - APIKey string `json:"api_key"` - APIBase string `json:"api_base"` - ModelIndex *int `json:"model_index,omitempty"` - } - if err = json.Unmarshal(body, &req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - if req.Provider == "" { - http.Error(w, "provider is required", http.StatusBadRequest) - return - } - - if !providers.IsModelProviderFetchable(req.Provider) { - http.Error(w, fmt.Sprintf("provider %q does not support model listing", req.Provider), http.StatusBadRequest) - return - } - - apiKey := strings.TrimSpace(req.APIKey) - apiBase := strings.TrimSpace(req.APIBase) - - if apiKey == "" && req.ModelIndex != nil { - if stored := h.lookupStoredAPIKey(*req.ModelIndex, req.Provider, apiBase); stored != "" { - apiKey = stored - } - } - - if apiBase == "" { - apiBase = providers.DefaultAPIBaseForProtocol(req.Provider) - } - if apiBase == "" { - http.Error(w, fmt.Sprintf("No default API base for provider %q", req.Provider), http.StatusBadRequest) - return - } - - ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) - defer cancel() - - models, err := fetchUpstreamModels(ctx, req.Provider, apiBase, apiKey) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to fetch models: %v", err), http.StatusBadGateway) - return - } - - // Auto-save fetched models to catalog - catalogModels := make([]CatalogModel, len(models)) - for i, m := range models { - catalogModels[i] = CatalogModel{ID: m.ID, OwnedBy: m.OwnedBy} - } - if saveErr := SaveCatalog(req.Provider, apiBase, apiKey, catalogModels); saveErr != nil { - // Log but don't fail the request — saving catalog is non-critical - logger.Warnf("Failed to save model catalog: %v", saveErr) - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "models": models, - "total": len(models), - }) -} - -func (h *Handler) lookupStoredAPIKey(index int, reqProvider, reqAPIBase string) string { - cfg, err := config.LoadConfig(h.configPath) - if err != nil || index < 0 || index >= len(cfg.ModelList) { - return "" - } - stored := cfg.ModelList[index] - storedProvider, _ := providers.ExtractProtocol(stored) - if providers.NormalizeProvider(reqProvider) != providers.NormalizeProvider(storedProvider) { - return "" - } - effectiveReqBase := strings.TrimSpace(reqAPIBase) - if effectiveReqBase == "" { - effectiveReqBase = providers.DefaultAPIBaseForProtocol(reqProvider) - } - effectiveStoredBase := strings.TrimSpace(stored.APIBase) - if effectiveStoredBase == "" { - effectiveStoredBase = providers.DefaultAPIBaseForProtocol(storedProvider) - } - if normalizeAPIBaseForCompare(effectiveReqBase) != normalizeAPIBaseForCompare(effectiveStoredBase) { - return "" - } - return stored.APIKey() -} - -type upstreamModel struct { - ID string `json:"id"` - OwnedBy string `json:"owned_by,omitempty"` -} - -func fetchUpstreamModels(ctx context.Context, provider, apiBase, apiKey string) ([]upstreamModel, error) { - apiBase = strings.TrimRight(strings.TrimSpace(apiBase), "/") - provider = providers.NormalizeProvider(provider) - - var fetchURL string - switch provider { - case "ollama": - // Strip /v1 suffix if present to get the Ollama root - root := apiBase - if strings.HasSuffix(root, "/v1") { - root = root[:len(root)-3] - } - root = strings.TrimRight(root, "/") - fetchURL = root + "/api/tags" - return fetchOllamaModels(ctx, fetchURL) - case "nearai": - fetchURL = apiBase + "/model/list" - return fetchNearAIModels(ctx, fetchURL, apiKey) - default: - // OpenAI-compatible: /v1/models - fetchURL = apiBase + "/models" - return fetchOpenAICompatibleModels(ctx, fetchURL, apiKey) - } -} - -func fetchNearAIModels(ctx context.Context, fetchURL, apiKey string) ([]upstreamModel, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, fetchURL, nil) - if err != nil { - return nil, err - } - if apiKey = strings.TrimSpace(apiKey); apiKey != "" { - req.Header.Set("Authorization", "Bearer "+apiKey) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("nearai returned status %d", resp.StatusCode) - } - - var parsed struct { - Models []struct { - ModelID string `json:"modelId"` - OwnedBy string `json:"ownedBy"` - Metadata struct { - OwnedBy string `json:"ownedBy"` - } `json:"metadata"` - } `json:"models"` - } - if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, err - } - - models := make([]upstreamModel, 0, len(parsed.Models)) - for _, m := range parsed.Models { - id := strings.TrimSpace(m.ModelID) - if id == "" { - continue - } - ownedBy := strings.TrimSpace(m.OwnedBy) - if ownedBy == "" { - ownedBy = strings.TrimSpace(m.Metadata.OwnedBy) - } - models = append(models, upstreamModel{ID: id, OwnedBy: ownedBy}) - } - return models, nil -} - -func fetchOpenAICompatibleModels(ctx context.Context, fetchURL, apiKey string) ([]upstreamModel, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, fetchURL, nil) - if err != nil { - return nil, err - } - if apiKey = strings.TrimSpace(apiKey); apiKey != "" { - req.Header.Set("Authorization", "Bearer "+apiKey) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("upstream returned status %d", resp.StatusCode) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("read response: %w", err) - } - - type modelItem struct { - ID string `json:"id"` - OwnedBy string `json:"owned_by"` - } - - // {"data": [...]} envelope. Distinguish "envelope shape with empty list" - // from "object without a data key" via Data being non-nil after unmarshal: - // json.Unmarshal sets Data to []modelItem{} for `{"data":[]}` but leaves - // it as nil when "data" is absent or null. - var envelope struct { - Data []modelItem `json:"data"` - } - if err := json.Unmarshal(body, &envelope); err == nil && envelope.Data != nil { - models := make([]upstreamModel, 0, len(envelope.Data)) - for _, m := range envelope.Data { - if m.ID != "" { - models = append(models, upstreamModel{ID: m.ID, OwnedBy: m.OwnedBy}) - } - } - return models, nil - } - - // Bare-array shape, including `[]`. - var arr []modelItem - if err := json.Unmarshal(body, &arr); err == nil { - models := make([]upstreamModel, 0, len(arr)) - for _, m := range arr { - if m.ID != "" { - models = append(models, upstreamModel{ID: m.ID, OwnedBy: m.OwnedBy}) - } - } - return models, nil - } - - preview := body - if len(preview) > 256 { - preview = preview[:256] - } - return nil, fmt.Errorf("decode response: unrecognized shape: %s", strings.TrimSpace(string(preview))) -} - -func fetchOllamaModels(ctx context.Context, fetchURL string) ([]upstreamModel, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, fetchURL, nil) - if err != nil { - return nil, err - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("ollama returned status %d", resp.StatusCode) - } - - var parsed struct { - Models []struct { - Name string `json:"name"` - Model string `json:"model"` - } `json:"models"` - } - if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, err - } - - models := make([]upstreamModel, 0, len(parsed.Models)) - for _, m := range parsed.Models { - id := m.Name - if id == "" { - id = m.Model - } - if id != "" { - models = append(models, upstreamModel{ID: id}) - } - } - return models, nil -} - -// normalizeAPIBaseForCompare normalizes an API base URL for equality comparison -// by trimming trailing slashes and lowering the scheme/host. -func normalizeAPIBaseForCompare(raw string) string { - raw = strings.TrimSpace(raw) - if raw == "" { - return "" - } - raw = strings.TrimRight(raw, "/") - u, err := url.Parse(raw) - if err != nil { - return strings.ToLower(raw) - } - if u.Host == "" { - u, err = url.Parse("//" + raw) - if err != nil { - return strings.ToLower(raw) - } - } - return strings.ToLower(u.Scheme) + "://" + strings.ToLower(u.Host) + strings.TrimRight(u.Path, "/") -} - -// handleTestModel tests connectivity to a model endpoint. -// -// POST /api/models/{index}/test -func (h *Handler) handleTestModel(w http.ResponseWriter, r *http.Request) { - idx, err := strconv.Atoi(r.PathValue("index")) - if err != nil { - http.Error(w, "Invalid index", http.StatusBadRequest) - return - } - - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError) - return - } - - if idx < 0 || idx >= len(cfg.ModelList) { - http.Error(w, fmt.Sprintf("Index %d out of range (0-%d)", idx, len(cfg.ModelList)-1), http.StatusNotFound) - return - } - - m := cfg.ModelList[idx] - start := time.Now() - summary := modelConfigurationStatus(m) - latency := time.Since(start).Milliseconds() - - result := map[string]any{ - "success": summary.Available, - "latency_ms": latency, - "status": summary.Status, - } - - if !summary.Available { - if summary.Status == modelStatusUnconfigured { - result["error"] = "API key not configured" - } else { - result["error"] = "Endpoint unreachable" - } - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(result) -} - -// handleTestInlineModel tests connectivity using inline (unsaved) parameters. -// Unlike handleTestModel which only checks saved config, this endpoint performs -// a real network probe (e.g. GET /models) to verify the endpoint is reachable. -// -// POST /api/models/test-inline -func (h *Handler) handleTestInlineModel(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 - } - - var req struct { - Provider string `json:"provider"` - Model string `json:"model"` - APIBase string `json:"api_base"` - APIKey string `json:"api_key"` - AuthMethod string `json:"auth_method"` - ModelIndex *int `json:"model_index"` - } - if err := json.Unmarshal(body, &req); err != nil { - http.Error(w, "Invalid JSON", http.StatusBadRequest) - return - } - - m := &config.ModelConfig{ - Provider: strings.TrimSpace(req.Provider), - Model: strings.TrimSpace(req.Model), - APIBase: strings.TrimSpace(req.APIBase), - AuthMethod: strings.TrimSpace(req.AuthMethod), - } - if req.APIKey != "" { - m.SetAPIKey(req.APIKey) - } - - // When api_key is empty and model_index is provided, fall back to stored credentials. - // This lets the edit form test unsaved field changes while using the saved key. - // Only reuse the stored key when the provider and effective API base match - // the saved model, to prevent attaching a credential to a different endpoint. - if req.APIKey == "" && req.ModelIndex != nil { - cfg, err := config.LoadConfig(h.configPath) - if err == nil && *req.ModelIndex >= 0 && *req.ModelIndex < len(cfg.ModelList) { - stored := cfg.ModelList[*req.ModelIndex] - storedProvider, _ := providers.ExtractProtocol(stored) - reqProvider := providers.NormalizeProvider(m.Provider) - providerMatch := reqProvider == "" || reqProvider == providers.NormalizeProvider(storedProvider) - - effectiveReqBase := strings.TrimSpace(m.APIBase) - if effectiveReqBase == "" { - effectiveReqBase = providers.DefaultAPIBaseForProtocol(reqProvider) - } - effectiveStoredBase := strings.TrimSpace(stored.APIBase) - if effectiveStoredBase == "" { - effectiveStoredBase = providers.DefaultAPIBaseForProtocol(storedProvider) - } - baseMatch := normalizeAPIBaseForCompare(effectiveReqBase) == normalizeAPIBaseForCompare(effectiveStoredBase) - - if providerMatch && baseMatch { - if stored.APIKey() != "" { - m.SetAPIKey(stored.APIKey()) - } - if m.APIBase == "" && stored.APIBase != "" { - m.APIBase = stored.APIBase - } - } - } - } - - // Check if configuration exists - if !hasModelConfiguration(m) { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "success": false, - "latency_ms": 0, - "status": modelStatusUnconfigured, - "error": "API key not configured", - }) - return - } - - // Perform a real network probe - start := time.Now() - available := probeModelConnectivity(m) - latency := time.Since(start).Milliseconds() - - result := map[string]any{ - "success": available, - "latency_ms": latency, - } - if available { - result["status"] = modelStatusAvailable - } else { - result["status"] = modelStatusUnreachable - result["error"] = "Endpoint unreachable" - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(result) -} - -// probeModelConnectivity performs a real network probe to verify model endpoint reachability. -func probeModelConnectivity(m *config.ModelConfig) bool { - apiBase := modelProbeAPIBase(m) - protocol, modelID := splitModel(m) - - switch protocol { - case "ollama": - return probeOllamaModel(apiBase, modelID) - case "vllm", "lmstudio", "gpt4free": - return probeOpenAICompatibleModel(apiBase, modelID, m.APIKey()) - case "github-copilot": - return probeTCPService(apiBase) - case "claude-cli": - return probeCommandAvailable("claude") - case "codex-cli": - return probeCommandAvailable("codex") - default: - // For remote providers (OpenAI, Anthropic, Gemini, DeepSeek, etc.), - // make a real GET /models request to verify connectivity and credentials. - if apiBase != "" { - return probeOpenAICompatibleModel(apiBase, modelID, m.APIKey()) - } - return false - } -} diff --git a/web/backend/api/models_test.go b/web/backend/api/models_test.go deleted file mode 100644 index 9e73157a..00000000 --- a/web/backend/api/models_test.go +++ /dev/null @@ -1,4103 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "slices" - "strings" - "sync" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/auth" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/providers" -) - -func resetModelProbeHooks(t *testing.T) { - t.Helper() - - origTCPProbe := probeTCPServiceFunc - origOllamaProbe := probeOllamaModelFunc - origOpenAIProbe := probeOpenAICompatibleModelFunc - origCommandProbe := probeCommandAvailableFunc - origNow := modelProbeNowFunc - resetModelProbeCache() - t.Cleanup(func() { - probeTCPServiceFunc = origTCPProbe - probeOllamaModelFunc = origOllamaProbe - probeOpenAICompatibleModelFunc = origOpenAIProbe - probeCommandAvailableFunc = origCommandProbe - modelProbeNowFunc = origNow - resetModelProbeCache() - }) -} - -func addModelAndLoadLatest(t *testing.T, configPath string, body string) *config.ModelConfig { - t.Helper() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(body)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if len(cfg.ModelList) == 0 { - t.Fatal("model_list should contain the newly added model") - } - - return cfg.ModelList[len(cfg.ModelList)-1] -} - -func writeDuplicateAliasDefaultChainConfig(t *testing.T, configPath string) { - t.Helper() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "shared-alias", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-openai"), - }, - { - ModelName: "shared-alias", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk-elevenlabs"), - }, - } - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } -} - -func writeModelChainConfig( - t *testing.T, - configPath string, - models []*config.ModelConfig, - defaultModel string, - fallbacks []string, -) { - t.Helper() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = models - cfg.Agents.Defaults.ModelName = defaultModel - cfg.Agents.Defaults.ModelFallbacks = fallbacks - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } -} - -func updateModelAndLoadConfig( - t *testing.T, - configPath string, - index int, - body string, -) *config.Config { - t.Helper() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - fmt.Sprintf("/api/models/%d", index), - bytes.NewBufferString(body), - ) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - return cfg -} - -func deleteModelAndLoadConfig(t *testing.T, configPath string, index int) *config.Config { - t.Helper() - - h := NewHandler(configPath) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, fmt.Sprintf("/api/models/%d", index), nil) - req.SetPathValue("index", fmt.Sprintf("%d", index)) - h.handleDeleteModel(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - return cfg -} - -func setDefaultModelAndLoadConfig(t *testing.T, configPath string, modelName string) *config.Config { - t.Helper() - - h := NewHandler(configPath) - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPost, - "/api/models/default", - bytes.NewBufferString(fmt.Sprintf(`{"model_name":%q}`, modelName)), - ) - req.Header.Set("Content-Type", "application/json") - h.handleSetDefaultModel(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - return cfg -} - -func assertDefaultChain( - t *testing.T, - cfg *config.Config, - wantDefault string, - wantFallbacks []string, -) { - t.Helper() - - if got := cfg.Agents.Defaults.ModelName; got != wantDefault { - t.Fatalf("default model = %q, want %q", got, wantDefault) - } - if !slices.Equal(cfg.Agents.Defaults.ModelFallbacks, wantFallbacks) { - t.Fatalf("fallback_chain = %#v, want %#v", cfg.Agents.Defaults.ModelFallbacks, wantFallbacks) - } -} - -func openAIModelConfig(alias string) *config.ModelConfig { - return &config.ModelConfig{ - ModelName: alias, - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-openai"), - } -} - -func anthropicModelConfig(alias string) *config.ModelConfig { - return &config.ModelConfig{ - ModelName: alias, - Provider: "anthropic", - Model: "claude-sonnet-4.6", - APIKeys: config.SimpleSecureStrings("sk-anthropic"), - } -} - -func geminiModelConfig(alias string) *config.ModelConfig { - return &config.ModelConfig{ - ModelName: alias, - Provider: "gemini", - Model: "gemini-2.5-pro", - APIKeys: config.SimpleSecureStrings("sk-gemini"), - } -} - -func elevenLabsModelConfig(alias string) *config.ModelConfig { - return &config.ModelConfig{ - ModelName: alias, - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk-elevenlabs"), - } -} - -func TestHandleListModels_AvailabilityUsesRuntimeProbesForLocalModels(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - var mu sync.Mutex - var openAIProbes []string - var ollamaProbes []string - var tcpProbes []string - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - mu.Lock() - openAIProbes = append(openAIProbes, apiBase+"|"+modelID+"|"+apiKey) - mu.Unlock() - return apiBase == "http://127.0.0.1:8000/v1" && modelID == "custom-model" && apiKey == "" - } - probeOllamaModelFunc = func(apiBase, modelID string) bool { - mu.Lock() - ollamaProbes = append(ollamaProbes, apiBase+"|"+modelID) - mu.Unlock() - return apiBase == "http://localhost:11434/v1" && modelID == "llama3" - } - probeTCPServiceFunc = func(apiBase string) bool { - mu.Lock() - tcpProbes = append(tcpProbes, apiBase) - mu.Unlock() - return apiBase == "http://127.0.0.1:4321" - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "openai-oauth", - Model: "openai/gpt-5.4", - AuthMethod: "oauth", - }, - { - ModelName: "vllm-local", - Model: "vllm/custom-model", - APIBase: "http://127.0.0.1:8000/v1", - }, - { - ModelName: "ollama-default", - Model: "ollama/llama3", - }, - { - ModelName: "vllm-remote", - Model: "vllm/custom-model", - APIBase: "https://models.example.com/v1", - APIKeys: config.SimpleSecureStrings("remote-key"), - }, - { - ModelName: "copilot-gpt-5.4", - Model: "github-copilot/gpt-5.4", - APIBase: "http://127.0.0.1:4321", - AuthMethod: "oauth", - }, - } - cfg.Agents.Defaults.ModelName = "openai-oauth" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - gotAvailable := make(map[string]bool, len(resp.Models)) - gotStatus := make(map[string]string, len(resp.Models)) - for _, model := range resp.Models { - gotAvailable[model.ModelName] = model.Available - gotStatus[model.ModelName] = model.Status - } - - if gotAvailable["openai-oauth"] { - t.Fatalf("openai oauth model available = true, want false without stored credential") - } - if !gotAvailable["vllm-local"] { - t.Fatalf("vllm local model available = false, want true when local probe succeeds") - } - if !gotAvailable["ollama-default"] { - t.Fatalf("ollama default model available = false, want true when default local probe succeeds") - } - if !gotAvailable["vllm-remote"] { - t.Fatalf("remote vllm model available = false, want true with api_key") - } - if !gotAvailable["copilot-gpt-5.4"] { - t.Fatalf("copilot model available = false, want true when local bridge probe succeeds") - } - if gotStatus["openai-oauth"] != modelStatusUnconfigured { - t.Fatalf("openai oauth model status = %q, want %q", gotStatus["openai-oauth"], modelStatusUnconfigured) - } - if gotStatus["vllm-local"] != modelStatusAvailable { - t.Fatalf("vllm local model status = %q, want %q", gotStatus["vllm-local"], modelStatusAvailable) - } - if gotStatus["ollama-default"] != modelStatusAvailable { - t.Fatalf("ollama default model status = %q, want %q", gotStatus["ollama-default"], modelStatusAvailable) - } - if gotStatus["vllm-remote"] != modelStatusAvailable { - t.Fatalf("remote vllm model status = %q, want %q", gotStatus["vllm-remote"], modelStatusAvailable) - } - if gotStatus["copilot-gpt-5.4"] != modelStatusAvailable { - t.Fatalf("copilot model status = %q, want %q", gotStatus["copilot-gpt-5.4"], modelStatusAvailable) - } - if len(openAIProbes) != 1 || openAIProbes[0] != "http://127.0.0.1:8000/v1|custom-model|" { - t.Fatalf("openAI probes = %#v, want only local vllm probe", openAIProbes) - } - if len(ollamaProbes) != 1 || ollamaProbes[0] != "http://localhost:11434/v1|llama3" { - t.Fatalf("ollama probes = %#v, want default local probe", ollamaProbes) - } - if len(tcpProbes) != 1 || tcpProbes[0] != "http://127.0.0.1:4321" { - t.Fatalf("tcp probes = %#v, want only local copilot probe", tcpProbes) - } -} - -func TestHandleListModels_AvailabilityForOAuthModelWithCredential(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "claude-oauth", - Model: "anthropic/claude-sonnet-4.6", - AuthMethod: "oauth", - }} - cfg.Agents.Defaults.ModelName = "claude-oauth" - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - if setCredentialErr := auth.SetCredential(oauthProviderAnthropic, &auth.AuthCredential{ - AccessToken: "anthropic-token", - Provider: oauthProviderAnthropic, - AuthMethod: "oauth", - }); setCredentialErr != nil { - t.Fatalf("SetCredential() error = %v", setCredentialErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if !resp.Models[0].Available { - t.Fatalf("oauth model available = false, want true with stored credential") - } -} - -func TestHasModelConfiguration_OAuthWithoutMappedCredentialFallsBackToAPIKey(t *testing.T) { - noKey := &config.ModelConfig{ - Provider: "gemini", - Model: "gemini-2.5-flash", - AuthMethod: "oauth", - } - if hasModelConfiguration(noKey) { - t.Fatal("oauth model without credential mapping and api key should be unconfigured") - } - - withKey := &config.ModelConfig{ - Provider: "gemini", - Model: "gemini-2.5-flash", - AuthMethod: "oauth", - APIKeys: config.SimpleSecureStrings("gemini-key"), - } - if !hasModelConfiguration(withKey) { - t.Fatal("oauth model without credential mapping should fall back to api key configuration") - } -} - -func TestHandleListModels_AntigravityImplicitOAuthAvailability(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "gemini-flash", - Provider: "antigravity", - Model: "gemini-3-flash", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - err = auth.SetCredential(oauthProviderGoogleAntigravity, &auth.AuthCredential{ - AccessToken: "antigravity-token", - Provider: oauthProviderGoogleAntigravity, - AuthMethod: "oauth", - }) - if err != nil { - t.Fatalf("SetCredential() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if !resp.Models[0].Available { - t.Fatal("antigravity model available = false, want true with stored credential even without auth_method") - } -} - -func TestHandleListModels_BedrockUsesAmbientCredentialStatus(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "bedrock-claude", - Provider: "bedrock", - Model: "us.anthropic.claude-sonnet-4-20250514-v1:0", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if !resp.Models[0].Available { - t.Fatal("bedrock model available = false, want true because Bedrock uses ambient AWS credentials") - } - if resp.Models[0].Status != modelStatusAvailable { - t.Fatalf("bedrock model status = %q, want %q", resp.Models[0].Status, modelStatusAvailable) - } -} - -func TestHandleListModels_CLIProvidersRequireInstalledCommands(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - probeCommandAvailableFunc = func(command string) bool { - switch command { - case "claude": - return false - case "codex": - return true - default: - return false - } - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "claude-cli-model", - Provider: "claude-cli", - Model: "claude-cli", - }, - { - ModelName: "codex-cli-model", - Provider: "codex-cli", - Model: "codex-cli", - }, - } - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - ProviderOptions []providers.ModelProviderOption `json:"provider_options"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - modelsByName := make(map[string]modelResponse, len(resp.Models)) - for _, model := range resp.Models { - modelsByName[model.ModelName] = model - } - if model := modelsByName["claude-cli-model"]; model.Available || model.Status != modelStatusUnreachable { - t.Fatalf( - "claude-cli status = (%t, %q), want (%t, %q)", - model.Available, - model.Status, - false, - modelStatusUnreachable, - ) - } - if model := modelsByName["codex-cli-model"]; !model.Available || model.Status != modelStatusAvailable { - t.Fatalf( - "codex-cli status = (%t, %q), want (%t, %q)", - model.Available, - model.Status, - true, - modelStatusAvailable, - ) - } - - optionsByID := make(map[string]providers.ModelProviderOption, len(resp.ProviderOptions)) - for _, option := range resp.ProviderOptions { - optionsByID[option.ID] = option - } - if option, ok := optionsByID["claude-cli"]; !ok { - t.Fatal("claude-cli provider option missing") - } else if option.CreateAllowed { - t.Fatal("claude-cli should not be creatable when the claude command is missing") - } - if option, ok := optionsByID["codex-cli"]; !ok { - t.Fatal("codex-cli provider option missing") - } else if !option.CreateAllowed { - t.Fatal("codex-cli should be creatable when the codex command is available") - } -} - -func TestHandleListModels_ProbesLocalModelsConcurrently(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - started := make(chan string, 2) - release := make(chan struct{}) - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - started <- apiBase + "|" + modelID - <-release - return true - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "local-vllm-a", - Model: "vllm/custom-a", - APIBase: "http://127.0.0.1:8000/v1", - }, - { - ModelName: "local-vllm-b", - Model: "vllm/custom-b", - APIBase: "http://127.0.0.1:8001/v1", - }, - } - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - recCh := make(chan *httptest.ResponseRecorder, 1) - go func() { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", nil) - mux.ServeHTTP(rec, req) - recCh <- rec - }() - - for i := 0; i < 2; i++ { - select { - case <-started: - case <-time.After(200 * time.Millisecond): - t.Fatal("expected both local probes to start before the first one completed") - } - } - close(release) - - rec := <-recCh - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } -} - -func TestHandleListModels_NormalizesWildcardLocalAPIBaseForProbe(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - var gotProbe string - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - gotProbe = apiBase + "|" + modelID + "|" + apiKey - return apiBase == "http://127.0.0.1:8000/v1" && modelID == "custom-model" && apiKey == "" - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "vllm-local", - Model: "vllm/custom-model", - APIBase: "http://0.0.0.0:8000/v1", - }} - - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if !resp.Models[0].Available { - t.Fatal("wildcard-bound local model available = false, want true after probe host normalization") - } - if gotProbe != "http://127.0.0.1:8000/v1|custom-model|" { - t.Fatalf("probe api base = %q, want %q", gotProbe, "http://127.0.0.1:8000/v1|custom-model|") - } -} - -func TestHandleListModels_StatusMarksUnreachableLocalModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - return false - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "vllm-local-down", - Model: "vllm/custom-model", - APIBase: "http://127.0.0.1:8000/v1", - APIKeys: config.SimpleSecureStrings("test-key"), - }} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - - if resp.Models[0].Available { - t.Fatal("unreachable local model available = true, want false") - } - if resp.Models[0].Status != modelStatusUnreachable { - t.Fatalf("unreachable local model status = %q, want %q", resp.Models[0].Status, modelStatusUnreachable) - } - if resp.Models[0].APIKey == "" { - t.Fatal("masked API key preview should still be returned when API key is configured") - } -} - -func TestHandleListModels_RuntimeProbeUsesExplicitProviderField(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - var gotProbe string - probeOpenAICompatibleModelFunc = func(apiBase, modelID, apiKey string) bool { - gotProbe = apiBase + "|" + modelID + "|" + apiKey - return true - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "vllm-local", - Provider: "vllm", - Model: "custom-model", - APIBase: "http://127.0.0.1:8000/v1", - }} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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()) - } - - if gotProbe != "http://127.0.0.1:8000/v1|custom-model|" { - t.Fatalf("probe = %q, want %q", gotProbe, "http://127.0.0.1:8000/v1|custom-model|") - } -} - -func TestHandleAddModel_PersistsAPIKey(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"new-model", - "model":"openai/gpt-4o-mini", - "api_key":"sk-new-model-key" - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if len(cfg.ModelList) != 2 { - t.Fatalf("len(model_list) = %d, want 2", len(cfg.ModelList)) - } - - added := cfg.ModelList[1] - if added.ModelName != "new-model" { - t.Fatalf("model_name = %q, want %q", added.ModelName, "new-model") - } - if added.APIKey() != "sk-new-model-key" { - t.Fatalf("api_key = %q, want %q", added.APIKey(), "sk-new-model-key") - } -} - -func TestHandleAddModel_PersistsProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"nvidia-glm", - "provider":"nvidia", - "model":"z-ai/glm-5.1", - "api_key":"nv-key" - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - added := cfg.ModelList[len(cfg.ModelList)-1] - if added.Provider != "nvidia" { - t.Fatalf("provider = %q, want %q", added.Provider, "nvidia") - } - if added.Model != "z-ai/glm-5.1" { - t.Fatalf("model = %q, want %q", added.Model, "z-ai/glm-5.1") - } -} - -func TestHandleAddModel_TrimsModelName(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":" trimmed-alias ", - "provider":"openai", - "model":"gpt-4o", - "api_key":"test-key" - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := cfg.ModelList[len(cfg.ModelList)-1].ModelName; got != "trimmed-alias" { - t.Fatalf("model_name = %q, want trimmed-alias", got) - } -} - -func TestHandleAddModel_NormalizesDefaultChainWhenDuplicateAliasUnsupported(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - geminiModelConfig("backup-b"), - }, "primary", []string{"backup-b"}) - - addModelAndLoadLatest(t, configPath, `{ - "model_name":"primary", - "provider":"elevenlabs", - "model":"scribe_v1", - "api_key":"sk-elevenlabs" - }`) - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - assertDefaultChain(t, updated, "", nil) -} - -func TestModelWriteHandlers_PreserveRawDefaultChain(t *testing.T) { - tests := []struct { - name string - mutate func(t *testing.T, configPath string) *config.Config - }{ - { - name: "add", - mutate: func(t *testing.T, configPath string) *config.Config { - addModelAndLoadLatest(t, configPath, `{ - "model_name":"added", - "provider":"anthropic", - "model":"claude-sonnet-4.6", - "api_key":"sk-added" - }`) - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - return cfg - }, - }, - { - name: "update", - mutate: func(t *testing.T, configPath string) *config.Config { - return updateModelAndLoadConfig(t, configPath, 1, `{ - "model_name":"other", - "provider":"anthropic", - "model":"claude-haiku-4.5", - "api_key":"sk-unrelated" - }`) - }, - }, - { - name: "delete", - mutate: func(t *testing.T, configPath string) *config.Config { - return deleteModelAndLoadConfig(t, configPath, 1) - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - geminiModelConfig("unrelated"), - anthropicModelConfig("other"), - openAIModelConfig("openai-template"), - { - ModelName: "openrouter-template", - Model: "openrouter/auto", - APIKeys: config.SimpleSecureStrings("sk-or-test"), - }, - }, "openrouter/primary-model", []string{ - "gpt-4o-mini", - "openai/gpt-4o-mini", - "openrouter/fallback-model", - }) - - updated := tt.mutate(t, configPath) - assertDefaultChain(t, updated, "openrouter/primary-model", []string{ - "gpt-4o-mini", - "openrouter/fallback-model", - }) - }) - } -} - -func TestHandleListModels_ReturnsStreamingConfig(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "streaming-model", - Provider: "openai", - Model: "gpt-4o-mini", - APIKeys: config.SimpleSecureStrings("sk-existing"), - Streaming: config.ModelStreamingConfig{Enabled: true}, - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - if err = json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if !resp.Models[0].Streaming.Enabled { - t.Fatal("streaming.enabled = false, want true") - } -} - -func TestHandleAddModel_RejectsUnsupportedProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"bad-provider", - "provider":"not-supported", - "model":"gpt-4o-mini" - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), `provider "not-supported" is not supported`) { - t.Fatalf("body = %q, want unsupported provider error", rec.Body.String()) - } -} - -func TestHandleAddModel_AllowsBedrockProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"bedrock-claude", - "provider":"bedrock", - "model":"us.anthropic.claude-sonnet-4-20250514-v1:0" - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - added := cfg.ModelList[len(cfg.ModelList)-1] - if got := added.Provider; got != "bedrock" { - t.Fatalf("provider = %q, want %q", got, "bedrock") - } - if got := added.Model; got != "us.anthropic.claude-sonnet-4-20250514-v1:0" { - t.Fatalf("model = %q, want bedrock model ID", got) - } -} - -func TestHandleAddModel_NormalizesLegacyElevenLabsASRConfig(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Model: "elevenlabs/scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"new-model", - "provider":"openai", - "model":"gpt-4o-mini", - "api_key":"sk-new-model-key" - }`)) - 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 len(updated.ModelList) != 2 { - t.Fatalf("len(model_list) = %d, want 2", len(updated.ModelList)) - } - if got := updated.ModelList[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q after normalization", got, "elevenlabs") - } - if got := updated.ModelList[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q after normalization", got, "scribe_v1") - } -} - -func TestHandleAddModel_NormalizesExplicitElevenLabsUnsupportedModelID(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Provider: "elevenlabs", - Model: "scribe_v2", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"new-model", - "provider":"openai", - "model":"gpt-4o-mini", - "api_key":"sk-new-model-key" - }`)) - 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[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q after normalization", got, "elevenlabs") - } - if got := updated.ModelList[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q after normalization", got, "scribe_v1") - } -} - -func TestHandleAddModel_RejectsMissingCLIProviderCommand(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - resetOAuthHooks(t) - resetModelProbeHooks(t) - - probeCommandAvailableFunc = func(command string) bool { - return false - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"claude-cli-model", - "provider":"claude-cli", - "model":"claude-cli" - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), `provider "claude-cli" is not available for new models`) { - t.Fatalf("body = %q, want missing cli command error", rec.Body.String()) - } -} - -func TestHandleAddModel_DefaultsAntigravityToOAuth(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - added := addModelAndLoadLatest(t, configPath, `{ - "model_name":"gemini-flash", - "provider":"antigravity", - "model":"gemini-3-flash" - }`) - if got := added.AuthMethod; got != "oauth" { - t.Fatalf("auth_method = %q, want %q", got, "oauth") - } -} - -func TestHandleAddModel_NormalizesMixedCaseAuthMethod(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - added := addModelAndLoadLatest(t, configPath, `{ - "model_name":"openai-oauth", - "provider":"openai", - "model":"gpt-5.4", - "auth_method":"OAuth" - }`) - if got := added.AuthMethod; got != "oauth" { - t.Fatalf("auth_method = %q, want %q", got, "oauth") - } -} - -func TestHandleAddModel_PreservesExplicitProviderPrefixedModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"openai-gpt", - "provider":"openai", - "model":"openai/gpt-4o-mini", - "api_key":"sk-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()) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - added := cfg.ModelList[len(cfg.ModelList)-1] - if got := added.Provider; got != "openai" { - t.Fatalf("provider = %q, want %q", got, "openai") - } - if got := added.Model; got != "openai/gpt-4o-mini" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-4o-mini") - } -} - -func TestHandleAddModel_PersistsCustomHeaders(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"new-model-headers", - "model":"openai/gpt-4o-mini", - "custom_headers":{"X-Source":"coding-plan","X-Agent":"openclaw"} - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if len(cfg.ModelList) != 2 { - t.Fatalf("len(model_list) = %d, want 2", len(cfg.ModelList)) - } - - added := cfg.ModelList[1] - if added.CustomHeaders == nil { - t.Fatal("custom_headers should not be nil") - } - if got := added.CustomHeaders["X-Source"]; got != "coding-plan" { - t.Fatalf("custom_headers[X-Source] = %q, want %q", got, "coding-plan") - } - if got := added.CustomHeaders["X-Agent"]; got != "openclaw" { - t.Fatalf("custom_headers[X-Agent] = %q, want %q", got, "openclaw") - } -} - -func TestHandleAddModel_PersistsToolSchemaTransform(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"new-model-transform", - "model":"openai/gpt-4o-mini", - "tool_schema_transform":"simple" - }`)) - 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 := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - added := cfg.ModelList[len(cfg.ModelList)-1] - if got := added.ToolSchemaTransform; got != "simple" { - t.Fatalf("tool_schema_transform = %q, want %q", got, "simple") - } -} - -func TestHandleUpdateModel_CustomHeadersPreserveAndClear(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "editable", - Model: "openai/gpt-4o-mini", - APIKeys: config.SimpleSecureStrings("sk-existing"), - CustomHeaders: map[string]string{"X-Source": "coding-plan"}, - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - // Omitted custom_headers should preserve existing value. - recPreserve := httptest.NewRecorder() - reqPreserve := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "model":"openai/gpt-4o-mini" - }`)) - reqPreserve.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recPreserve, reqPreserve) - if recPreserve.Code != http.StatusOK { - t.Fatalf("preserve status = %d, want %d, body=%s", recPreserve.Code, http.StatusOK, recPreserve.Body.String()) - } - - afterPreserve, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after preserve error = %v", err) - } - if got := afterPreserve.ModelList[0].CustomHeaders["X-Source"]; got != "coding-plan" { - t.Fatalf("preserved custom_headers[X-Source] = %q, want %q", got, "coding-plan") - } - - // Empty object should clear custom_headers. - recClear := httptest.NewRecorder() - reqClear := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "model":"openai/gpt-4o-mini", - "custom_headers":{} - }`)) - reqClear.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recClear, reqClear) - if recClear.Code != http.StatusOK { - t.Fatalf("clear status = %d, want %d, body=%s", recClear.Code, http.StatusOK, recClear.Body.String()) - } - - afterClear, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after clear error = %v", err) - } - if afterClear.ModelList[0].CustomHeaders != nil { - t.Fatalf("custom_headers = %#v, want nil", afterClear.ModelList[0].CustomHeaders) - } -} - -func TestHandleUpdateModel_ToolSchemaTransformPreserveAndClear(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "editable", - Model: "openai/gpt-4o-mini", - APIKeys: config.SimpleSecureStrings("sk-existing"), - ToolSchemaTransform: "simple", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - recPreserve := httptest.NewRecorder() - reqPreserve := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "model":"openai/gpt-4o-mini" - }`)) - reqPreserve.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recPreserve, reqPreserve) - if recPreserve.Code != http.StatusOK { - t.Fatalf("preserve status = %d, want %d, body=%s", recPreserve.Code, http.StatusOK, recPreserve.Body.String()) - } - - afterPreserve, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after preserve error = %v", err) - } - if got := afterPreserve.ModelList[0].ToolSchemaTransform; got != "simple" { - t.Fatalf("preserved tool_schema_transform = %q, want %q", got, "simple") - } - - recClear := httptest.NewRecorder() - reqClear := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "model":"openai/gpt-4o-mini", - "tool_schema_transform":"" - }`)) - reqClear.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recClear, reqClear) - if recClear.Code != http.StatusOK { - t.Fatalf("clear status = %d, want %d, body=%s", recClear.Code, http.StatusOK, recClear.Body.String()) - } - - afterClear, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after clear error = %v", err) - } - if afterClear.ModelList[0].ToolSchemaTransform != "" { - t.Fatalf("tool_schema_transform = %q, want empty", afterClear.ModelList[0].ToolSchemaTransform) - } -} - -func TestHandleUpdateModel_StreamingPreserveAndChange(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "editable", - Provider: "openai", - Model: "gpt-4o-mini", - APIKeys: config.SimpleSecureStrings("sk-existing"), - Streaming: config.ModelStreamingConfig{Enabled: true}, - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - recPreserve := httptest.NewRecorder() - reqPreserve := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "provider":"openai", - "model":"gpt-4o-mini" - }`)) - reqPreserve.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recPreserve, reqPreserve) - if recPreserve.Code != http.StatusOK { - t.Fatalf("preserve status = %d, want %d, body=%s", recPreserve.Code, http.StatusOK, recPreserve.Body.String()) - } - - afterPreserve, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after preserve error = %v", err) - } - if !afterPreserve.ModelList[0].Streaming.Enabled { - t.Fatal("preserved streaming.enabled = false, want true") - } - - recChange := httptest.NewRecorder() - reqChange := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "provider":"openai", - "model":"gpt-4o-mini", - "streaming":{"enabled":false} - }`)) - reqChange.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recChange, reqChange) - if recChange.Code != http.StatusOK { - t.Fatalf("change status = %d, want %d, body=%s", recChange.Code, http.StatusOK, recChange.Body.String()) - } - - afterChange, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() after change error = %v", err) - } - if afterChange.ModelList[0].Streaming.Enabled { - t.Fatal("streaming.enabled = true, want false after explicit update") - } -} - -func TestHandleUpdateModel_PersistsProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "editable", - Model: "gpt-4o", - Provider: "openai", - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "provider":"openrouter", - "model":"openai/gpt-4o" - }`)) - 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[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } -} - -func TestHandleUpdateModel_PreservesExplicitProviderPrefixedModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "editable", - Model: "gpt-4o", - Provider: "openai", - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"editable", - "provider":"openai", - "model":"openai/gpt-5.4" - }`)) - 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[0].Provider; got != "openai" { - t.Fatalf("provider = %q, want %q", got, "openai") - } - if got := updated.ModelList[0].Model; got != "openai/gpt-5.4" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-5.4") - } -} - -func TestHandleListModels_PreservesExplicitProviderPrefixedModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "openrouter-auto-explicit", - Provider: "openrouter", - Model: "openrouter/auto", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if got := resp.Models[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } - if got := resp.Models[0].Model; got != "openrouter/auto" { - t.Fatalf("model = %q, want %q", got, "openrouter/auto") - } -} - -func TestHandleListModels_ExposesElevenLabsASRProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Model: "elevenlabs/scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - if err = json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if got := resp.Models[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q", got, "elevenlabs") - } - if got := resp.Models[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q", got, "scribe_v1") - } - if resp.Models[0].DefaultModelAllowed { - t.Fatal("elevenlabs ASR model should not be allowed as the default chat model") - } -} - -func TestHandleUpdateModel_PreservesLegacyModelPrefixWhenProviderOmitted(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "legacy-openrouter", - Model: "openrouter/openai/gpt-5.4", - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - // Simulate an older client: it reads GET /api/models, ignores the new - // provider field, then PUTs the visible model string back unchanged. - recList := httptest.NewRecorder() - reqList := httptest.NewRequest(http.MethodGet, "/api/models", nil) - mux.ServeHTTP(recList, reqList) - - if recList.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", recList.Code, http.StatusOK, recList.Body.String()) - } - - var listResp struct { - Models []modelResponse `json:"models"` - } - if err = json.Unmarshal(recList.Body.Bytes(), &listResp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(listResp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(listResp.Models)) - } - if got := listResp.Models[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } - if got := listResp.Models[0].Model; got != "openai/gpt-5.4" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-5.4") - } - - recUpdate := httptest.NewRecorder() - reqUpdate := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"legacy-openrouter", - "model":"openai/gpt-5.4" - }`)) - reqUpdate.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recUpdate, reqUpdate) - - if recUpdate.Code != http.StatusOK { - t.Fatalf("update status = %d, want %d, body=%s", recUpdate.Code, http.StatusOK, recUpdate.Body.String()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.ModelList[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } - if got := updated.ModelList[0].Model; got != "openai/gpt-5.4" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-5.4") - } -} - -func TestHandleUpdateModel_MigratesLegacyElevenLabsASRWhenProviderOmitted(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Model: "elevenlabs/scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - recList := httptest.NewRecorder() - reqList := httptest.NewRequest(http.MethodGet, "/api/models", nil) - mux.ServeHTTP(recList, reqList) - - if recList.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", recList.Code, http.StatusOK, recList.Body.String()) - } - - var listResp struct { - Models []modelResponse `json:"models"` - } - if err = json.Unmarshal(recList.Body.Bytes(), &listResp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(listResp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(listResp.Models)) - } - if got := listResp.Models[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q", got, "elevenlabs") - } - if got := listResp.Models[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q", got, "scribe_v1") - } - - recUpdate := httptest.NewRecorder() - reqUpdate := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"elevenlabs-asr", - "model":"scribe_v1", - "api_base":"https://api.elevenlabs.io" - }`)) - reqUpdate.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recUpdate, reqUpdate) - - if recUpdate.Code != http.StatusOK { - t.Fatalf("update status = %d, want %d, body=%s", recUpdate.Code, http.StatusOK, recUpdate.Body.String()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.ModelList[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q", got, "elevenlabs") - } - if got := updated.ModelList[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q", got, "scribe_v1") - } - if got := updated.ModelList[0].APIBase; got != "https://api.elevenlabs.io" { - t.Fatalf("api_base = %q, want %q", got, "https://api.elevenlabs.io") - } -} - -func TestHandleUpdateModel_RoundTripsExplicitLegacyElevenLabsModelID(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Provider: "elevenlabs", - Model: "scribe_v2", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - recList := httptest.NewRecorder() - reqList := httptest.NewRequest(http.MethodGet, "/api/models", nil) - mux.ServeHTTP(recList, reqList) - - if recList.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", recList.Code, http.StatusOK, recList.Body.String()) - } - - var listResp struct { - Models []modelResponse `json:"models"` - } - if err = json.Unmarshal(recList.Body.Bytes(), &listResp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(listResp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(listResp.Models)) - } - if got := listResp.Models[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q", got, "elevenlabs") - } - if got := listResp.Models[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q after GET normalization", got, "scribe_v1") - } - - recUpdate := httptest.NewRecorder() - reqUpdate := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"elevenlabs-asr", - "provider":"elevenlabs", - "model":"scribe_v1", - "api_base":"https://api.elevenlabs.io" - }`)) - reqUpdate.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(recUpdate, reqUpdate) - - if recUpdate.Code != http.StatusOK { - t.Fatalf("update status = %d, want %d, body=%s", recUpdate.Code, http.StatusOK, recUpdate.Body.String()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.ModelList[0].Provider; got != "elevenlabs" { - t.Fatalf("provider = %q, want %q", got, "elevenlabs") - } - if got := updated.ModelList[0].Model; got != "scribe_v1" { - t.Fatalf("model = %q, want %q", got, "scribe_v1") - } - if got := updated.ModelList[0].APIBase; got != "https://api.elevenlabs.io" { - t.Fatalf("api_base = %q, want %q", got, "https://api.elevenlabs.io") - } -} - -func TestHandleUpdateModel_ClearsDefaultWhenSavingASROnlyModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "elevenlabs-asr", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - cfg.Agents.Defaults.ModelName = "elevenlabs-asr" - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"elevenlabs-asr", - "provider":"elevenlabs", - "model":"scribe_v1", - "api_base":"https://api.elevenlabs.io" - }`)) - 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.Agents.Defaults.ModelName; got != "" { - t.Fatalf("default model = %q, want cleared default", got) - } -} - -func TestHandleAddModel_RejectsUnsupportedElevenLabsModelID(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models", bytes.NewBufferString(`{ - "model_name":"elevenlabs-asr", - "provider":"elevenlabs", - "model":"scribe_v2" - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), `provider "elevenlabs" only supports model "scribe_v1"`) { - t.Fatalf("body = %q, want elevenlabs model validation error", rec.Body.String()) - } -} - -func TestHandleUpdateModel_PreservesLegacyModelPrefixWhenProviderOmittedAndModelChanges(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "legacy-openrouter", - Model: "openrouter/openai/gpt-5.4", - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"legacy-openrouter", - "model":"openai/gpt-5.5" - }`)) - 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[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } - if got := updated.ModelList[0].Model; got != "openai/gpt-5.5" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-5.5") - } -} - -func TestHandleListModels_ReturnsProviderOptionsWithoutPersistingLegacyMigration(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "legacy-openrouter", - Model: "openrouter/openai/gpt-5.4", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - ProviderOptions []providers.ModelProviderOption `json:"provider_options"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if got := resp.Models[0].Provider; got != "openrouter" { - t.Fatalf("provider = %q, want %q", got, "openrouter") - } - if got := resp.Models[0].Model; got != "openai/gpt-5.4" { - t.Fatalf("model = %q, want %q", got, "openai/gpt-5.4") - } - - optionsByID := make(map[string]providers.ModelProviderOption, len(resp.ProviderOptions)) - for _, option := range resp.ProviderOptions { - optionsByID[option.ID] = option - } - if len(optionsByID) == 0 { - t.Fatal("provider_options should not be empty") - } - if option, ok := optionsByID["openai"]; !ok { - t.Fatal("openai provider option missing") - } else if option.DefaultAPIBase != "https://api.openai.com/v1" { - t.Fatalf("openai default_api_base = %q, want %q", option.DefaultAPIBase, "https://api.openai.com/v1") - } else if !option.SupportsFetch { - t.Fatal("openai provider option should report supports_fetch") - } 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 := optionsByID["anthropic"]; !ok { - t.Fatal("anthropic provider 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") - } - if _, ok := optionsByID["azure"]; !ok { - t.Fatal("azure provider option missing") - } - if option, ok := optionsByID["github-copilot"]; !ok { - t.Fatal("github-copilot provider 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 := optionsByID["elevenlabs"]; !ok { - t.Fatal("elevenlabs provider 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 marked as not allowed for default chat model selection") - } - } - if option, ok := optionsByID["lmstudio"]; !ok { - t.Fatal("lmstudio provider option missing") - } else if !option.EmptyAPIKeyAllowed { - t.Fatal("lmstudio should allow empty api keys") - } - if option, ok := optionsByID["gpt4free"]; !ok { - t.Fatal("gpt4free provider 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 provider option should report supports_fetch") - } - } - if option, ok := optionsByID["siliconflow"]; !ok { - t.Fatal("siliconflow provider 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 := optionsByID["nearai"]; !ok { - t.Fatal("nearai provider option missing") - } else 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") - } else if !option.SupportsFetch { - t.Fatal("nearai provider option should report supports_fetch") - } - if option, ok := optionsByID["bedrock"]; !ok { - t.Fatal("bedrock provider option missing") - } else if !option.CreateAllowed { - t.Fatal("bedrock should stay creatable and defer AWS credential failures to runtime") - } - if option, ok := optionsByID["antigravity"]; !ok { - t.Fatal("antigravity provider option missing") - } else { - 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 := optionsByID["qwen-portal"]; !ok { - t.Fatal("qwen-portal provider option missing") - } else if len(option.Aliases) == 0 || option.Aliases[0] != "qwen" { - t.Fatalf("qwen-portal aliases = %#v, want to include qwen", option.Aliases) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.ModelList[0].Provider; got != "" { - t.Fatalf("persisted provider = %q, want unchanged empty provider", got) - } - if got := updated.ModelList[0].Model; got != "openrouter/openai/gpt-5.4" { - t.Fatalf("persisted model = %q, want unchanged legacy model", got) - } -} - -func TestHandleListModels_ReturnsProviderField(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "nvidia-glm", - Provider: "nvidia", - Model: "z-ai/glm-5.1", - APIKeys: config.SimpleSecureStrings("nv-key"), - }} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if got := resp.Models[0].Provider; got != "nvidia" { - t.Fatalf("provider = %q, want %q", got, "nvidia") - } -} - -func TestHandleListModels_PreservesKnownProviderInCatalog(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "bedrock-claude", - Model: "bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0", - }} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - ProviderOptions []providers.ModelProviderOption `json:"provider_options"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Models) != 1 { - t.Fatalf("len(models) = %d, want 1", len(resp.Models)) - } - if got := resp.Models[0].Provider; got != "bedrock" { - t.Fatalf("provider = %q, want %q", got, "bedrock") - } - if got := resp.Models[0].Model; got != "us.anthropic.claude-sonnet-4-20250514-v1:0" { - t.Fatalf("model = %q, want %q", got, "us.anthropic.claude-sonnet-4-20250514-v1:0") - } - foundBedrock := false - for _, option := range resp.ProviderOptions { - if option.ID == "bedrock" { - foundBedrock = true - if !option.CreateAllowed { - t.Fatal("bedrock should stay creatable in provider_options") - } - } - } - if !foundBedrock { - t.Fatal("bedrock should be included in provider_options for compatibility") - } -} - -func TestHandleUpdateModel_AllowsExistingBedrockProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "bedrock-claude", - Provider: "bedrock", - Model: "us.anthropic.claude-sonnet-4-20250514-v1:0", - APIBase: "us-west-2", - }} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"bedrock-claude", - "provider":"bedrock", - "model":"us.anthropic.claude-3-7-sonnet-20250219-v1:0", - "api_base":"us-east-1" - }`)) - 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[0].Provider; got != "bedrock" { - t.Fatalf("provider = %q, want %q", got, "bedrock") - } - if got := updated.ModelList[0].Model; got != "us.anthropic.claude-3-7-sonnet-20250219-v1:0" { - t.Fatalf("model = %q, want updated bedrock model", got) - } - if got := updated.ModelList[0].APIBase; got != "us-east-1" { - t.Fatalf("api_base = %q, want %q", got, "us-east-1") - } -} - -func TestHandleListModels_ReturnsEffectiveProviderField(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "plain-openai", - Model: "gpt-4o", - }, - { - ModelName: "explicit-google", - Provider: "google", - Model: "gemini-2.5-pro", - }, - { - ModelName: "explicit-qwen-intl", - Provider: "qwen-international", - Model: "qwen3-coder-plus", - }, - } - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models", 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 resp struct { - Models []modelResponse `json:"models"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - if len(resp.Models) != 3 { - t.Fatalf("len(models) = %d, want 3", len(resp.Models)) - } - - if got := resp.Models[0].Provider; got != "openai" { - t.Fatalf("provider[0] = %q, want %q", got, "openai") - } - if got := resp.Models[0].Model; got != "gpt-4o" { - t.Fatalf("model[0] = %q, want %q", got, "gpt-4o") - } - if got := resp.Models[1].Provider; got != "gemini" { - t.Fatalf("provider[1] = %q, want %q", got, "gemini") - } - if got := resp.Models[1].Model; got != "gemini-2.5-pro" { - t.Fatalf("model[1] = %q, want %q", got, "gemini-2.5-pro") - } - if got := resp.Models[2].Provider; got != "qwen-intl" { - t.Fatalf("provider[2] = %q, want %q", got, "qwen-intl") - } - if got := resp.Models[2].Model; got != "qwen3-coder-plus" { - t.Fatalf("model[2] = %q, want %q", got, "qwen3-coder-plus") - } -} - -func TestHandleSetDefaultModel_RejectsUnknownModelName(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - // First save a valid config with a primary model - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - {ModelName: "gpt-4", Model: "openai/gpt-4o"}, - } - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name": "gpt-4o-mini" - }`)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusNotFound, rec.Body.String()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.Agents.Defaults.ModelName; got == "gpt-4o-mini" { - t.Fatalf("default model = %q, want request to leave it unchanged", got) - } -} - -func TestNormalizeIncomingModelConfigUsesConfiguredDefaultProvider(t *testing.T) { - modelCfg := &config.ModelConfig{ModelName: "legacy", Model: "gpt-4o"} - normalizeIncomingModelConfig(modelCfg, "openrouter") - if modelCfg.Provider != "openrouter" || modelCfg.Model != "gpt-4o" { - t.Fatalf("normalized model = %#v, want openrouter/gpt-4o", modelCfg) - } -} - -func TestHandleSetDefaultModel_RejectsElevenLabsASRProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "elevenlabs-asr", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }, - } - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name": "elevenlabs-asr" - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used as the default chat model") { - t.Fatalf("body = %q, want default chat model rejection", rec.Body.String()) - } -} - -func TestHandleSetDefaultModel_RejectsLegacyAliasUsingUnsupportedDefaultProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Agents.Defaults.Provider = "elevenlabs" - cfg.ModelList = []*config.ModelConfig{{ - ModelName: "legacy-audio", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name":"legacy-audio" - }`)) - 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 TestHandleSetDefaultModel_RejectsUnknownExplicitRawModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - }, "primary", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name":"elevenlabs/scribe_v1" - }`)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusNotFound { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusNotFound, rec.Body.String()) - } - if !strings.Contains(rec.Body.String(), "not found in model_list") { - t.Fatalf("body = %q, want unknown model rejection", rec.Body.String()) - } -} - -func TestHandleSetDefaultModel_RemovesDefaultFromFallbackChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - geminiModelConfig("backup-b"), - } - cfg.Agents.Defaults.ModelName = "primary" - cfg.Agents.Defaults.ModelFallbacks = []string{"backup-a", "backup-b"} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name": "backup-a" - }`)) - 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.Agents.Defaults.ModelName; got != "backup-a" { - t.Fatalf("default model = %q, want %q", got, "backup-a") - } - if len(updated.Agents.Defaults.ModelFallbacks) != 1 || updated.Agents.Defaults.ModelFallbacks[0] != "backup-b" { - t.Fatalf("fallback_chain = %#v, want [backup-b]", updated.Agents.Defaults.ModelFallbacks) - } -} - -func TestHandleSetDefaultModel_NormalizesExistingFallbackChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - geminiModelConfig("backup-b"), - elevenLabsModelConfig("audio-only"), - }, "primary", []string{"missing", "audio-only", "backup-b", "primary"}) - - updated := setDefaultModelAndLoadConfig(t, configPath, "backup-b") - - assertDefaultChain(t, updated, "backup-b", []string{"missing", "primary"}) -} - -func TestHandleGetDefaultChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - geminiModelConfig("backup-b"), - } - cfg.Agents.Defaults.ModelName = "primary" - cfg.Agents.Defaults.ModelFallbacks = []string{"backup-a", "backup-b"} - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/models/default-chain", 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 resp defaultChainResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.DefaultModel != "primary" { - t.Fatalf("default_model = %q, want %q", resp.DefaultModel, "primary") - } - if len(resp.FallbackChain) != 2 || resp.FallbackChain[0] != "backup-a" || resp.FallbackChain[1] != "backup-b" { - t.Fatalf("fallback_chain = %#v, want [backup-a backup-b]", resp.FallbackChain) - } -} - -func TestModelGetHandlers_NormalizeDefaultChainSnapshot(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - geminiModelConfig("backup-b"), - elevenLabsModelConfig("audio-only"), - }, "primary", []string{"audio-only", "elevenlabs/scribe_v1", "backup-b"}) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - for _, path := range []string{"/api/models", "/api/models/default-chain"} { - t.Run(path, func(t *testing.T) { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, path, 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 response defaultChainResponse - if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if response.DefaultModel != "primary" { - t.Fatalf("default_model = %q, want primary", response.DefaultModel) - } - if !slices.Equal(response.FallbackChain, []string{"backup-b"}) { - t.Fatalf("fallback_chain = %#v, want [backup-b]", response.FallbackChain) - } - }) - } -} - -func TestHandleUpdateDefaultChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - geminiModelConfig("backup-b"), - } - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"primary", - "fallback_chain":["backup-a","backup-b","backup-a"] - }`)) - 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 resp defaultChainResponse - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.DefaultModel != "primary" { - t.Fatalf("default_model = %q, want %q", resp.DefaultModel, "primary") - } - if len(resp.FallbackChain) != 2 || resp.FallbackChain[0] != "backup-a" || resp.FallbackChain[1] != "backup-b" { - t.Fatalf("fallback_chain = %#v, want [backup-a backup-b]", resp.FallbackChain) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if updated.Agents.Defaults.ModelName != "primary" { - t.Fatalf("saved default model = %q, want %q", updated.Agents.Defaults.ModelName, "primary") - } - if len(updated.Agents.Defaults.ModelFallbacks) != 2 || - updated.Agents.Defaults.ModelFallbacks[0] != "backup-a" || - updated.Agents.Defaults.ModelFallbacks[1] != "backup-b" { - t.Fatalf("saved fallback_chain = %#v, want [backup-a backup-b]", updated.Agents.Defaults.ModelFallbacks) - } -} - -func TestHandleUpdateDefaultChain_AllowsRawFallbackReference(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("unrelated"), - { - ModelName: "openrouter-template", - Model: "openrouter/auto", - APIKeys: config.SimpleSecureStrings("sk-or-test"), - }, - }, "openrouter/primary-model", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"openrouter/primary-model", - "fallback_chain":[" gpt-4o-mini ","openrouter/fallback-model","gpt-4o-mini"] - }`)) - 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) - } - assertDefaultChain(t, updated, "openrouter/primary-model", []string{ - "gpt-4o-mini", - "openrouter/fallback-model", - }) -} - -func TestHandleUpdateDefaultChain_RejectsRuntimeIdentityMatchingDefault(t *testing.T) { - tests := []struct { - name string - models []*config.ModelConfig - defaultModel string - fallback string - }{ - { - name: "raw references", - models: []*config.ModelConfig{ - geminiModelConfig("unrelated"), - openAIModelConfig("openai-template"), - }, - defaultModel: "openai/gpt-4o", - fallback: "gpt-4o", - }, - { - name: "alias and raw reference", - models: []*config.ModelConfig{openAIModelConfig("primary")}, - defaultModel: "primary", - fallback: "openai/gpt-4o", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeModelChainConfig(t, configPath, tt.models, tt.defaultModel, nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - body := fmt.Sprintf( - `{"default_model":%q,"fallback_chain":[%q]}`, - tt.defaultModel, - tt.fallback, - ) - req := httptest.NewRequest( - http.MethodPut, - "/api/models/default-chain", - bytes.NewBufferString(body), - ) - 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()) - } - if !strings.Contains(rec.Body.String(), "same runtime model") { - t.Fatalf("body = %q, want runtime identity rejection", rec.Body.String()) - } - }) - } -} - -func TestHandleUpdateDefaultChain_DedupesFallbackRuntimeIdentity(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - geminiModelConfig("unrelated"), - openAIModelConfig("openai-template"), - { - ModelName: "openrouter-template", - Model: "openrouter/auto", - APIKeys: config.SimpleSecureStrings("sk-or-test"), - }, - }, "openrouter/primary-model", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"openrouter/primary-model", - "fallback_chain":["gpt-4o","openai/gpt-4o"] - }`)) - 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) - } - assertDefaultChain(t, updated, "openrouter/primary-model", []string{"gpt-4o"}) -} - -func TestHandleUpdateDefaultChain_RejectsUnsupportedFallbackModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - openAIModelConfig("primary"), - { - ModelName: "audio-only", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk_elevenlabs_test"), - }, - } - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"primary", - "fallback_chain":["audio-only"] - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used in the fallback chain") { - t.Fatalf("body = %q, want fallback chain rejection", rec.Body.String()) - } -} - -func TestHandleUpdateDefaultChain_DoesNotTreatUnsupportedAliasAsRawFallback(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - { - ModelName: "openrouter/fallback-model", - Provider: "elevenlabs", - Model: "scribe_v1", - APIKeys: config.SimpleSecureStrings("sk-elevenlabs"), - }, - }, "primary", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"primary", - "fallback_chain":["openrouter/fallback-model"] - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used in the fallback chain") { - t.Fatalf("body = %q, want fallback chain rejection", rec.Body.String()) - } -} - -func TestHandleUpdateDefaultChain_RejectsUnsupportedRawFallbackReference(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - }, "primary", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"primary", - "fallback_chain":["elevenlabs/scribe_v1"] - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used in the fallback chain") { - t.Fatalf("body = %q, want fallback chain rejection", rec.Body.String()) - } -} - -func TestHandleUpdateDefaultChain_TrimsStoredLegacyAlias(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{{ - ModelName: " primary ", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("test-key"), - }}, "", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - "/api/models/default-chain", - bytes.NewBufferString(`{"default_model":"primary","fallback_chain":[]}`), - ) - 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[0].ModelName; got != "primary" { - t.Fatalf("model_name = %q, want primary", got) - } -} - -func TestHandleUpdateDefaultChain_ValidatesRawMatchUsingConfiguredProvider(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - { - ModelName: "misconfigured-audio", - Provider: "elevenlabs", - Model: "openai/gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-elevenlabs"), - }, - }, "primary", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - for _, body := range []string{ - "{\"default_model\":\"openai/gpt-4o\",\"fallback_chain\":[]}", - "{\"default_model\":\"primary\",\"fallback_chain\":[\"openai/gpt-4o\"]}", - } { - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - "/api/models/default-chain", - bytes.NewBufferString(body), - ) - 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 TestValidateDefaultChainReference_RejectsRawWithoutProviderTemplate(t *testing.T) { - cfg := &config.Config{ - Agents: config.AgentsConfig{ - Defaults: config.AgentDefaults{Provider: "openai"}, - }, - ModelList: []*config.ModelConfig{{ - ModelName: "openai-template", - Model: "openai/gpt-4o-mini", - }}, - } - - err := validateDefaultChainReference(cfg, "openrouter/new-model", nil, false) - if err == nil || !strings.Contains(err.Error(), "has no configured provider") { - t.Fatalf("error = %v, want missing configured provider error", err) - } -} - -func TestValidateDefaultChainReference_RejectsUnconfiguredProviderTemplate(t *testing.T) { - cfg := &config.Config{ModelList: []*config.ModelConfig{{ - ModelName: "openrouter-template", - Model: "openrouter/auto", - }}} - - err := validateDefaultChainReference(cfg, "openrouter/new-model", nil, false) - if err == nil || !strings.Contains(err.Error(), "has no configured provider") { - t.Fatalf("error = %v, want unconfigured provider error", err) - } -} - -func TestValidateDefaultChainReferenceRejectsUnconfiguredAlias(t *testing.T) { - cfg := &config.Config{ - Agents: config.AgentsConfig{Defaults: config.AgentDefaults{Provider: "openai"}}, - ModelList: []*config.ModelConfig{{ - ModelName: "unconfigured", - Provider: "openai", - Model: "gpt-4o", - }}, - } - err := validateDefaultChainReference(cfg, "unconfigured", cfg.ModelList, true) - if err == nil || !strings.Contains(err.Error(), "has no configured provider") { - t.Fatalf("error = %v, want unconfigured alias rejection", err) - } -} - -func TestValidateDefaultChainReferenceRejectsUnconfiguredLegacyAliasUsingDefaultProvider(t *testing.T) { - cfg := &config.Config{ - Agents: config.AgentsConfig{Defaults: config.AgentDefaults{Provider: "openrouter"}}, - ModelList: []*config.ModelConfig{{ - ModelName: "unconfigured", - Model: "auto", - APIBase: providers.DefaultAPIBaseForProtocol("openrouter"), - }}, - } - - err := validateDefaultChainReference(cfg, "unconfigured", cfg.ModelList, true) - if err == nil || !strings.Contains(err.Error(), "has no configured provider") { - t.Fatalf("error = %v, want unconfigured legacy alias rejection", err) - } -} - -func TestHandleListModels_PreservesRawDefaultWithMultiKeyModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeModelChainConfig(t, configPath, []*config.ModelConfig{{ - ModelName: "primary", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-one", "sk-two"), - }}, "openai/gpt-4o", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/models", nil)) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200, body=%s", rec.Code, rec.Body.String()) - } - var response struct { - DefaultModel string `json:"default_model"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if response.DefaultModel != "openai/gpt-4o" { - t.Fatalf("default_model = %q, want openai/gpt-4o", response.DefaultModel) - } -} - -func TestHandleUpdateDefaultChain_RejectsDuplicateAliasWithUnsupportedEntry(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeDuplicateAliasDefaultChainConfig(t, configPath) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/default-chain", bytes.NewBufferString(`{ - "default_model":"shared-alias", - "fallback_chain":[] - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used as the default chat model") { - t.Fatalf("body = %q, want duplicated alias default rejection", rec.Body.String()) - } -} - -func TestHandleSetDefaultModel_RejectsDuplicateAliasWithUnsupportedEntry(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeDuplicateAliasDefaultChainConfig(t, configPath) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/default", bytes.NewBufferString(`{ - "model_name":"shared-alias" - }`)) - 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()) - } - if !strings.Contains(rec.Body.String(), "cannot be used as the default chat model") { - t.Fatalf("body = %q, want duplicated alias default rejection", rec.Body.String()) - } -} - -func TestHandleDeleteModel_RemovesDeletedModelFromDefaultChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - geminiModelConfig("backup-b"), - } - cfg.Agents.Defaults.ModelName = "primary" - cfg.Agents.Defaults.ModelFallbacks = []string{"backup-a", "backup-b"} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/models/1", 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()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if updated.Agents.Defaults.ModelName != "primary" { - t.Fatalf("saved default model = %q, want %q", updated.Agents.Defaults.ModelName, "primary") - } - if len(updated.Agents.Defaults.ModelFallbacks) != 1 || updated.Agents.Defaults.ModelFallbacks[0] != "backup-b" { - t.Fatalf("saved fallback_chain = %#v, want [backup-b]", updated.Agents.Defaults.ModelFallbacks) - } -} - -func TestHandleDeleteModel_ClearsFallbackChainWhenDefaultDeleted(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - }, "primary", []string{"backup-a"}) - - updated := deleteModelAndLoadConfig(t, configPath, 0) - - assertDefaultChain(t, updated, "", nil) -} - -func TestHandleDeleteModel_PreservesDefaultChainReferenceWhenAliasStillExists(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "shared-alias", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-openai"), - }, - { - ModelName: "shared-alias", - Provider: "anthropic", - Model: "claude-sonnet-4.6", - APIKeys: config.SimpleSecureStrings("sk-anthropic"), - }, - { - ModelName: "backup-b", - Provider: "gemini", - Model: "gemini-2.5-pro", - APIKeys: config.SimpleSecureStrings("sk-backup-b"), - }, - } - cfg.Agents.Defaults.ModelName = "shared-alias" - cfg.Agents.Defaults.ModelFallbacks = []string{"backup-b"} - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/models/1", 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()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - if got := updated.Agents.Defaults.ModelName; got != "shared-alias" { - t.Fatalf("default model = %q, want %q", got, "shared-alias") - } - if len(updated.Agents.Defaults.ModelFallbacks) != 1 || - updated.Agents.Defaults.ModelFallbacks[0] != "backup-b" { - t.Fatalf("fallback_chain = %#v, want [backup-b]", updated.Agents.Defaults.ModelFallbacks) - } -} - -func TestHandleUpdateModel_ReturnsReferenceRenameRoles(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("old-name"), - }, "openrouter/primary-model", nil) - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPut, "/api/models/0", bytes.NewBufferString(`{ - "model_name":"new-name", - "provider":"openai", - "model":"gpt-4o", - "api_key":"sk-primary" - }`)) - 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 response struct { - ReferenceRename struct { - From string `json:"from"` - To string `json:"to"` - Default bool `json:"default"` - Fallback bool `json:"fallback"` - } `json:"reference_rename"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if response.ReferenceRename.From != "old-name" || response.ReferenceRename.To != "new-name" { - t.Fatalf("reference_rename = %#v, want old-name -> new-name", response.ReferenceRename) - } - if !response.ReferenceRename.Default || !response.ReferenceRename.Fallback { - t.Fatalf("reference_rename roles = %#v, want both roles", response.ReferenceRename) - } -} - -func TestHandleUpdateModel_RenamesDefaultModelReference(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - }, "primary", []string{"backup-a"}) - - updated := updateModelAndLoadConfig(t, configPath, 0, `{ - "model_name":"primary-renamed", - "provider":"openai", - "model":"gpt-4o", - "api_key":"sk-primary" - }`) - - assertDefaultChain(t, updated, "primary-renamed", []string{"backup-a"}) -} - -func TestHandleUpdateModel_RenamesFallbackModelReference(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - geminiModelConfig("backup-b"), - }, "primary", []string{"backup-a", "backup-b"}) - - updated := updateModelAndLoadConfig(t, configPath, 1, `{ - "model_name":"backup-a-renamed", - "provider":"anthropic", - "model":"claude-sonnet-4.6", - "api_key":"sk-backup-a" - }`) - - assertDefaultChain(t, updated, "primary", []string{"backup-a-renamed", "backup-b"}) -} - -func TestHandleUpdateModel_RemovesFallbackWhenRenamedToDefaultModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - }, "primary", []string{"backup-a"}) - - updated := updateModelAndLoadConfig(t, configPath, 1, `{ - "model_name":"primary", - "provider":"anthropic", - "model":"claude-sonnet-4.6", - "api_key":"sk-backup-a" - }`) - - assertDefaultChain(t, updated, "primary", nil) -} - -func TestHandleUpdateModel_RemovesFallbackWhenDefaultRenamedToFallbackModel(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - }, "primary", []string{"backup-a"}) - - updated := updateModelAndLoadConfig(t, configPath, 0, `{ - "model_name":"backup-a", - "provider":"openai", - "model":"gpt-4o", - "api_key":"sk-primary" - }`) - - assertDefaultChain(t, updated, "backup-a", nil) -} - -func TestHandleUpdateModel_DoesNotRenameDefaultChainReferenceWhenAliasStillExists(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("shared-alias"), - anthropicModelConfig("shared-alias"), - geminiModelConfig("backup-b"), - }, "shared-alias", []string{"backup-b"}) - - updated := updateModelAndLoadConfig(t, configPath, 1, `{ - "model_name":"renamed-alias", - "provider":"anthropic", - "model":"claude-sonnet-4.6", - "api_key":"sk-anthropic" - }`) - - assertDefaultChain(t, updated, "shared-alias", []string{"backup-b"}) -} - -func TestHandleUpdateModel_ClearsDefaultWhenRenamedAliasGroupUnsupported(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("source-alias"), - elevenLabsModelConfig("target-alias"), - geminiModelConfig("backup-b"), - }, "source-alias", []string{"backup-b"}) - - updated := updateModelAndLoadConfig(t, configPath, 0, `{ - "model_name":"target-alias", - "provider":"openai", - "model":"gpt-4o", - "api_key":"sk-openai" - }`) - - assertDefaultChain(t, updated, "", nil) -} - -func TestHandleUpdateModel_RenamesDefaultChainReferenceWhenRemainingAliasUnsupported(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("shared-alias"), - elevenLabsModelConfig("shared-alias"), - geminiModelConfig("backup-b"), - }, "shared-alias", []string{"backup-b"}) - - updated := updateModelAndLoadConfig(t, configPath, 0, `{ - "model_name":"renamed-alias", - "provider":"openai", - "model":"gpt-4o", - "api_key":"sk-openai" - }`) - - assertDefaultChain(t, updated, "renamed-alias", []string{"backup-b"}) -} - -func TestHandleUpdateModel_RemovesRenamedUnsupportedModelFromDefaultChain(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - writeModelChainConfig(t, configPath, []*config.ModelConfig{ - openAIModelConfig("primary"), - anthropicModelConfig("backup-a"), - }, "primary", []string{"backup-a"}) - - updated := updateModelAndLoadConfig(t, configPath, 1, `{ - "model_name":"audio-only", - "provider":"elevenlabs", - "model":"scribe_v1", - "api_key":"sk-elevenlabs" - }`) - - assertDefaultChain(t, updated, "primary", nil) -} - -func TestMaskAPIKey(t *testing.T) { - tests := []struct { - name string - key string - want string - }{ - { - name: "empty key", - 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 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 := maskAPIKey(tc.key) - if got != tc.want { - t.Fatalf("maskAPIKey(%q) = %q, want %q", tc.key, got, tc.want) - } - - if tc.key != "" { - displayed := strings.Replace(tc.want, "****", "", 1) - if len(tc.key) <= 8 { - if displayed != "" { - t.Fatalf("maskAPIKey(%q) displayed part = %q, want empty", tc.key, displayed) - } - } else { - if len(displayed)*10 > len(tc.key)*6 { - t.Fatalf( - "maskAPIKey(%q) displayed length = %d, want at most 60%% of %d", - tc.key, - len(displayed), - len(tc.key), - ) - } - } - } - }) - } -} - -func TestFetchOpenAICompatibleModels_ResponseShapes(t *testing.T) { - tests := []struct { - name string - response string - apiKey string - wantLen int - wantFirst struct { - id, ownedBy string - } - wantSecond struct { - id, ownedBy string - } - }{ - { - name: "envelope shape", - response: `{"data":[{"id":"gpt-4o","owned_by":"openai"},{"id":"gpt-4o-mini","owned_by":"openai"}]}`, - apiKey: "test-key", - wantLen: 2, - wantFirst: struct { - id, ownedBy string - }{id: "gpt-4o", ownedBy: "openai"}, - wantSecond: struct { - id, ownedBy string - }{id: "gpt-4o-mini", ownedBy: "openai"}, - }, - { - name: "bare array shape", - response: `[{"id":"qwen-max","owned_by":"qwen"},{"id":"qwen-plus","owned_by":"qwen"}]`, - apiKey: "", - wantLen: 2, - wantFirst: struct { - id, ownedBy string - }{id: "qwen-max", ownedBy: "qwen"}, - wantSecond: struct { - id, ownedBy string - }{id: "qwen-plus", ownedBy: "qwen"}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, tt.response) - })) - defer srv.Close() - - models, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", tt.apiKey) - if err != nil { - t.Fatalf("error = %v", err) - } - if len(models) != tt.wantLen { - t.Fatalf("len(models) = %d, want %d", len(models), tt.wantLen) - } - if models[0].ID != tt.wantFirst.id || models[0].OwnedBy != tt.wantFirst.ownedBy { - t.Fatalf("models[0] = %+v, want {ID:%s OwnedBy:%s}", models[0], tt.wantFirst.id, tt.wantFirst.ownedBy) - } - if models[1].ID != tt.wantSecond.id || models[1].OwnedBy != tt.wantSecond.ownedBy { - t.Fatalf("models[1] = %+v, want {ID:%s OwnedBy:%s}", models[1], tt.wantSecond.id, tt.wantSecond.ownedBy) - } - }) - } -} - -func TestFetchOpenAICompatibleModels_EmptyEnvelopeReturnsEmptySlice(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[]}`) - })) - defer srv.Close() - - models, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", "k") - if err != nil { - t.Fatalf("error = %v", err) - } - if len(models) != 0 { - t.Fatalf("len(models) = %d, want 0", len(models)) - } -} - -func TestFetchOpenAICompatibleModels_EmptyBareArrayReturnsEmptySlice(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `[]`) - })) - defer srv.Close() - - models, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", "k") - if err != nil { - t.Fatalf("error = %v", err) - } - if len(models) != 0 { - t.Fatalf("len(models) = %d, want 0", len(models)) - } -} - -func TestFetchOpenAICompatibleModels_UnrecognizedShape(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"models":[],"error":"unsupported"}`) - })) - defer srv.Close() - - _, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", "k") - if err == nil { - t.Fatal("error = nil, want unrecognized shape error") - } - if !strings.Contains(err.Error(), "unrecognized shape") { - t.Fatalf("error = %q, want it to contain 'unrecognized shape'", err.Error()) - } -} - -func TestFetchOpenAICompatibleModels_FiltersEmptyIDs(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[`+ - `{"id":"gpt-4o","owned_by":"openai"},`+ - `{"id":"","owned_by":"openai"},`+ - `{"id":"gpt-4o-mini"}]}`) - })) - defer srv.Close() - - models, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", "k") - if err != nil { - t.Fatalf("error = %v", err) - } - if len(models) != 2 { - t.Fatalf("len(models) = %d, want 2 (empty IDs should be filtered)", len(models)) - } - if models[0].ID != "gpt-4o" { - t.Fatalf("models[0].ID = %q, want %q", models[0].ID, "gpt-4o") - } - if models[1].ID != "gpt-4o-mini" { - t.Fatalf("models[1].ID = %q, want %q", models[1].ID, "gpt-4o-mini") - } -} - -func TestFetchOpenAICompatibleModels_SetsAuthorizationHeader(t *testing.T) { - var gotAuth string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[{"id":"m1"}]}`) - })) - defer srv.Close() - - if _, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", "my-secret-key"); err != nil { - t.Fatalf("error = %v", err) - } - if gotAuth != "Bearer my-secret-key" { - t.Fatalf("Authorization = %q, want %q", gotAuth, "Bearer my-secret-key") - } -} - -func TestFetchOpenAICompatibleModels_NoAuthHeaderWhenKeyEmpty(t *testing.T) { - var gotAuth string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `[{"id":"m1"}]`) - })) - defer srv.Close() - - if _, err := fetchOpenAICompatibleModels(t.Context(), srv.URL+"/models", ""); err != nil { - t.Fatalf("error = %v", err) - } - if gotAuth != "" { - t.Fatalf("Authorization = %q, want empty", gotAuth) - } -} - -func TestHandleFetchModels_SiliconFlowUsesOpenAICompatibleEndpoint(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - var gotPath string - var gotAuth string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotPath = r.URL.Path - gotAuth = r.Header.Get("Authorization") - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[{"id":"deepseek-ai/DeepSeek-V3","owned_by":"siliconflow"}]}`) - })) - defer srv.Close() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/fetch", bytes.NewBufferString(fmt.Sprintf(`{ - "provider":"siliconflow", - "api_key":"sk-siliconflow", - "api_base":"%s" - }`, srv.URL))) - 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()) - } - - if gotPath != "/models" { - t.Fatalf("path = %q, want %q", gotPath, "/models") - } - if gotAuth != "Bearer sk-siliconflow" { - t.Fatalf("Authorization = %q, want %q", gotAuth, "Bearer sk-siliconflow") - } - - var resp struct { - Models []upstreamModel `json:"models"` - Total int `json:"total"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Total != 1 || len(resp.Models) != 1 { - t.Fatalf("response = %+v, want one fetched model", resp) - } - if resp.Models[0].ID != "deepseek-ai/DeepSeek-V3" { - t.Fatalf("model id = %q, want %q", resp.Models[0].ID, "deepseek-ai/DeepSeek-V3") - } -} - -func TestHandleFetchModels_NearAIUsesPublicModelListEndpoint(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - var gotPath string - var gotAuth string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotPath = r.URL.Path - gotAuth = r.Header.Get("Authorization") - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"models":[`+ - `{"modelId":"zai-org/GLM-5.1-FP8","metadata":{"ownedBy":"nearai"}},`+ - `{"modelId":"openai/gpt-oss-120b","metadata":{"ownedBy":"nearai"}},`+ - `{"modelId":""}]}`) - })) - defer srv.Close() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/fetch", bytes.NewBufferString(fmt.Sprintf(`{ - "provider":"nearai", - "api_key":"nearai-key", - "api_base":"%s" - }`, srv.URL))) - 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()) - } - - if gotPath != "/model/list" { - t.Fatalf("path = %q, want %q", gotPath, "/model/list") - } - if gotAuth != "Bearer nearai-key" { - t.Fatalf("Authorization = %q, want %q", gotAuth, "Bearer nearai-key") - } - - var resp struct { - Models []upstreamModel `json:"models"` - Total int `json:"total"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Total != 2 || len(resp.Models) != 2 { - t.Fatalf("response = %+v, want two fetched models", resp) - } - if resp.Models[0].ID != "zai-org/GLM-5.1-FP8" || resp.Models[0].OwnedBy != "nearai" { - t.Fatalf("models[0] = %+v, want GLM model owned by nearai", resp.Models[0]) - } - if resp.Models[1].ID != "openai/gpt-oss-120b" || resp.Models[1].OwnedBy != "nearai" { - t.Fatalf("models[1] = %+v, want GPT OSS model owned by nearai", resp.Models[1]) - } -} - -func TestHandleFetchModels_ModelIndexUsesStoredKey(t *testing.T) { - var gotAuth string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotAuth = r.Header.Get("Authorization") - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[{"id":"gpt-4o","owned_by":"openai"}]}`) - })) - defer srv.Close() - - tmp := t.TempDir() - oldHome := os.Getenv("PICOCLAW_HOME") - t.Setenv("PICOCLAW_HOME", filepath.Join(tmp, ".picoclaw")) - defer func() { - if oldHome != "" { - os.Setenv("PICOCLAW_HOME", oldHome) - } else { - os.Unsetenv("PICOCLAW_HOME") - } - }() - - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "my-openai", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-stored-secret"), - APIBase: srv.URL, - }, - } - configPath := filepath.Join(tmp, "config.json") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig error: %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - idx := 0 - body := fmt.Sprintf(`{"provider":"openai","api_base":"%s","model_index":%d}`, srv.URL, idx) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/fetch", bytes.NewBufferString(body)) - 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()) - } - if gotAuth != "Bearer sk-stored-secret" { - t.Fatalf("Authorization = %q, want stored key to be used", gotAuth) - } - - var resp struct { - Models []upstreamModel `json:"models"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal error: %v", err) - } - if len(resp.Models) != 1 || resp.Models[0].ID != "gpt-4o" { - t.Fatalf("unexpected response: %+v", resp) - } -} - -func TestHandleFetchModels_ModelIndexProviderMismatchRejectsKey(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "" { - t.Error("stored key should NOT be sent to mismatched provider") - } - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"data":[]}`) - })) - defer srv.Close() - - tmp := t.TempDir() - t.Setenv("PICOCLAW_HOME", filepath.Join(tmp, ".picoclaw")) - - cfg := config.DefaultConfig() - cfg.ModelList = []*config.ModelConfig{ - { - ModelName: "my-openai", - Provider: "openai", - Model: "gpt-4o", - APIKeys: config.SimpleSecureStrings("sk-openai-secret"), - APIBase: "https://api.openai.com/v1", - }, - } - configPath := filepath.Join(tmp, "config.json") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig error: %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body := fmt.Sprintf(`{"provider":"siliconflow","api_base":"%s","model_index":0}`, srv.URL) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/models/fetch", bytes.NewBufferString(body)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) -} diff --git a/web/backend/api/oauth.go b/web/backend/api/oauth.go deleted file mode 100644 index 7586a45b..00000000 --- a/web/backend/api/oauth.go +++ /dev/null @@ -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, - "PicoClaw OAuth

%s

%s

You can close this window.

", - 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 -} diff --git a/web/backend/api/oauth_test.go b/web/backend/api/oauth_test.go deleted file mode 100644 index 9468c887..00000000 --- a/web/backend/api/oauth_test.go +++ /dev/null @@ -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 - }) -} diff --git a/web/backend/api/pico.go b/web/backend/api/pico.go deleted file mode 100644 index 8eeff404..00000000 --- a/web/backend/api/pico.go +++ /dev/null @@ -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) -} diff --git a/web/backend/api/pico_test.go b/web/backend/api/pico_test.go deleted file mode 100644 index 6f7cefd4..00000000 --- a/web/backend/api/pico_test.go +++ /dev/null @@ -1,977 +0,0 @@ -package api - -import ( - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "net/url" - "os" - "path/filepath" - "strconv" - "strings" - "testing" - - "github.com/sipeed/picoclaw/pkg/config" - ppid "github.com/sipeed/picoclaw/pkg/pid" -) - -func newPicoProxyRequest(method, path string) *http.Request { - req := httptest.NewRequest(method, "http://launcher.local:18800"+path, nil) - req.Header.Set("Origin", "http://launcher.local:18800") - return req -} - -func TestEnsurePicoChannel_FreshConfig(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - changed, err := h.EnsurePicoChannel() - if err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - if !changed { - t.Fatal("EnsurePicoChannel() should report changed on a fresh config") - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if !bc.Enabled { - t.Error("expected Pico to be enabled after setup") - } - if picoCfg.Token.String() == "" { - t.Error("expected a non-empty token after setup") - } -} - -func TestEnsurePicoChannel_DoesNotEnableTokenQuery(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if picoCfg.AllowTokenQuery { - t.Error("setup must not enable allow_token_query by default") - } -} - -func TestEnsurePicoChannel_LeavesAllowOriginsEmptyByDefault(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if len(picoCfg.AllowOrigins) != 0 { - t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins) - } -} - -func TestEnsurePicoChannel_NoOriginConfigurationRequired(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if len(picoCfg.AllowOrigins) != 0 { - t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins) - } -} - -func TestEnsurePicoChannel_PreservesUserSettings(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - - // Pre-configure with custom user settings - cfg := config.DefaultConfig() - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - bc.Enabled = true - picoCfg.SetToken("user-custom-token") - picoCfg.AllowTokenQuery = true - picoCfg.AllowOrigins = []string{"https://myapp.example.com"} - if err = config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - - changed, err := h.EnsurePicoChannel() - if err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - if changed { - t.Error("EnsurePicoChannel() should not change a fully configured config") - } - - cfg, err = config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc = cfg.Channels["pico"] - decoded, err = bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg = decoded.(*config.PicoSettings) - if picoCfg.Token.String() != "user-custom-token" { - t.Errorf("token = %q, want %q", picoCfg.Token.String(), "user-custom-token") - } - if !picoCfg.AllowTokenQuery { - t.Error("user's allow_token_query=true must be preserved") - } - if len(picoCfg.AllowOrigins) != 1 || picoCfg.AllowOrigins[0] != "https://myapp.example.com" { - t.Errorf("allow_origins = %v, want [https://myapp.example.com]", picoCfg.AllowOrigins) - } -} - -func TestEnsurePicoChannel_ExistingConfigWithoutSecurityFile(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - - cfg := config.DefaultConfig() - raw, err := json.Marshal(cfg) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - if err = os.WriteFile(configPath, raw, 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - h := NewHandler(configPath) - - changed, err := h.EnsurePicoChannel() - if err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - if !changed { - t.Fatal("EnsurePicoChannel() should report changed when pico is missing") - } - - cfg, err = config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if !bc.Enabled { - t.Error("expected Pico to be enabled after setup") - } - if picoCfg.Token.String() == "" { - t.Error("expected a non-empty token after setup") - } - if _, err := os.Stat(filepath.Join(filepath.Dir(configPath), config.SecurityConfigFile)); err != nil { - t.Fatalf("expected .security.yml to be created: %v", err) - } -} - -func TestEnsurePicoChannel_ConfiguresPicoWithoutGateway(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - - cfg := config.DefaultConfig() - cfg.Agents.Defaults.ModelName = "" - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if !bc.Enabled { - t.Error("expected Pico to be enabled after launcher startup setup") - } - if picoCfg.Token.String() == "" { - t.Error("expected a non-empty token after launcher startup setup") - } -} - -func TestEnsurePicoChannel_Idempotent(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - // First call sets things up - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("first EnsurePicoChannel() error = %v", err) - } - - cfg1, _ := config.LoadConfig(configPath) - bc := cfg1.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - token1 := picoCfg.Token.String() - - // Second call should be a no-op - changed, err := h.EnsurePicoChannel() - if err != nil { - t.Fatalf("second EnsurePicoChannel() error = %v", err) - } - if changed { - t.Error("second EnsurePicoChannel() should not report changed") - } - - cfg2, _ := config.LoadConfig(configPath) - bc = cfg2.Channels["pico"] - decoded, err = bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg = decoded.(*config.PicoSettings) - if picoCfg.Token.String() != token1 { - t.Error("token should not change on subsequent calls") - } -} - -func TestHandlePicoSetup_DoesNotPersistRequestOrigin(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - req := httptest.NewRequest("POST", "/api/pico/setup", nil) - req.Header.Set("Origin", "http://10.0.0.5:3000") - rec := httptest.NewRecorder() - - h.handlePicoSetup(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - if len(picoCfg.AllowOrigins) != 0 { - t.Errorf("allow_origins = %v, want empty", picoCfg.AllowOrigins) - } -} - -func TestHandlePicoSetup_Response(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - req := httptest.NewRequest("POST", "/api/pico/setup", nil) - rec := httptest.NewRecorder() - - h.handlePicoSetup(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var resp map[string]any - if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { - t.Fatalf("failed to decode response: %v", err) - } - - if _, ok := resp["token"]; ok { - t.Error("response must not expose the raw pico token") - } - if resp["ws_url"] == nil || resp["ws_url"] == "" { - t.Error("response should contain ws_url") - } - if resp["enabled"] != true { - t.Error("response should have enabled=true") - } - if resp["changed"] != true { - t.Error("response should have changed=true on first setup") - } - if resp["configured"] != true { - t.Error("response should have configured=true") - } -} - -func TestHandleGetPicoInfo_OmitsToken(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - req := httptest.NewRequest(http.MethodGet, "http://launcher.local/api/pico/info", nil) - rec := httptest.NewRecorder() - - h.handleGetPicoInfo(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - var resp map[string]any - if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { - t.Fatalf("failed to decode response: %v", err) - } - - if _, ok := resp["token"]; ok { - t.Fatal("info response must not expose the raw pico token") - } - if resp["enabled"] != true { - t.Fatalf("enabled = %#v, want true", resp["enabled"]) - } - if resp["configured"] != true { - t.Fatalf("configured = %#v, want true", resp["configured"]) - } - if resp["ws_url"] == nil || resp["ws_url"] == "" { - t.Fatal("response should contain ws_url") - } -} - -func TestHandleRegenPicoToken_RefreshesGatewayTokenCache(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - if _, err := h.EnsurePicoChannel(); err != nil { - t.Fatalf("EnsurePicoChannel() error = %v", err) - } - - origPicoToken := gateway.picoToken - t.Cleanup(func() { - gateway.mu.Lock() - gateway.picoToken = origPicoToken - gateway.mu.Unlock() - }) - - gateway.mu.Lock() - gateway.picoToken = "stale-token" - gateway.mu.Unlock() - - req := httptest.NewRequest(http.MethodPost, "http://launcher.local/api/pico/token", nil) - rec := httptest.NewRecorder() - h.handleRegenPicoToken(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - token := decoded.(*config.PicoSettings).Token.String() - if token == "" { - t.Fatal("expected regenerated pico token to be persisted") - } - if token == "stale-token" { - t.Fatal("expected regenerated pico token to differ from stale cache") - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.picoToken != token { - t.Fatalf("gateway.picoToken = %q, want %q", gateway.picoToken, token) - } -} - -func TestHandleWebSocketProxyReloadsGatewayTargetFromConfig(t *testing.T) { - origMatcher := gatewayProcessMatcher - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - t.Cleanup(func() { gatewayProcessMatcher = origMatcher }) - - home := t.TempDir() - t.Setenv("PICOCLAW_HOME", home) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - handler := h.handleWebSocketProxy() - - server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/ws" { - t.Fatalf("server1 path = %q, want %q", r.URL.Path, "/pico/ws") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, "server1") - })) - defer server1.Close() - - server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/ws" { - t.Fatalf("server2 path = %q, want %q", r.URL.Path, "/pico/ws") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, "server2") - })) - defer server2.Close() - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = mustGatewayTestPort(t, server1.URL) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: cfg.Gateway.Host, - Port: cfg.Gateway.Port, - }) - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - t.Cleanup(func() { - ppid.RemovePidFile(globalConfigDir()) - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - }) - - gateway.pidData = &ppid.PidFileData{} - gateway.picoToken = "pico" - req1 := newPicoProxyRequest(http.MethodGet, "/pico/ws") - rec1 := httptest.NewRecorder() - handler(rec1, req1) - - if rec1.Code != http.StatusOK { - t.Fatalf("first status = %d, want %d", rec1.Code, http.StatusOK) - } - if body := rec1.Body.String(); body != "server1" { - t.Fatalf("first body = %q, want %q", body, "server1") - } - - cfg.Gateway.Port = mustGatewayTestPort(t, server2.URL) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - req2 := newPicoProxyRequest(http.MethodGet, "/pico/ws") - rec2 := httptest.NewRecorder() - handler(rec2, req2) - - if rec2.Code != http.StatusOK { - t.Fatalf("second status = %d, want %d", rec2.Code, http.StatusOK) - } - if body := rec2.Body.String(); body != "server2" { - t.Fatalf("second body = %q, want %q", body, "server2") - } -} - -func TestHandleWebSocketProxyLoadsCachedPicoTokenWhenMissing(t *testing.T) { - origMatcher := gatewayProcessMatcher - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - t.Cleanup(func() { gatewayProcessMatcher = origMatcher }) - - home := t.TempDir() - t.Setenv("PICOCLAW_HOME", home) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - handler := h.handleWebSocketProxy() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/ws" { - t.Fatalf("path = %q, want %q", r.URL.Path, "/pico/ws") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, "proxied") - })) - defer server.Close() - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = mustGatewayTestPort(t, server.URL) - bc := cfg.Channels["pico"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - picoCfg := decoded.(*config.PicoSettings) - bc.Enabled = true - picoCfg.SetToken("cached-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: cfg.Gateway.Host, - Port: cfg.Gateway.Port, - }) - t.Cleanup(func() { - ppid.RemovePidFile(globalConfigDir()) - }) - - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - t.Cleanup(func() { - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - }) - - gateway.pidData = &ppid.PidFileData{} - gateway.picoToken = "" - - req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session") - rec := httptest.NewRecorder() - handler(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - if body := rec.Body.String(); body != "proxied" { - t.Fatalf("body = %q, want %q", body, "proxied") - } - if gateway.picoToken != "cached-token" { - t.Fatalf("gateway.picoToken = %q, want %q", gateway.picoToken, "cached-token") - } -} - -func TestHandleWebSocketProxyLoadsPidDataOnDemand(t *testing.T) { - origMatcher := gatewayProcessMatcher - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - t.Cleanup(func() { gatewayProcessMatcher = origMatcher }) - - home := t.TempDir() - t.Setenv("PICOCLAW_HOME", home) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - handler := h.handleWebSocketProxy() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/ws" { - t.Fatalf("path = %q, want %q", r.URL.Path, "/pico/ws") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, r.Header.Get(protocolKey)) - })) - defer server.Close() - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = mustGatewayTestPort(t, server.URL) - bc := cfg.Channels["pico"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - decoded.(*config.PicoSettings).SetToken("ui-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - pidData := ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: cfg.Gateway.Host, - Port: cfg.Gateway.Port, - } - writeTestPidFile(t, pidData) - t.Cleanup(func() { - ppid.RemovePidFile(globalConfigDir()) - }) - - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - origStatus := gateway.runtimeStatus - t.Cleanup(func() { - gateway.mu.Lock() - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - gateway.runtimeStatus = origStatus - gateway.mu.Unlock() - }) - - gateway.mu.Lock() - gateway.pidData = nil - gateway.picoToken = "" - setGatewayRuntimeStatusLocked("stopped") - gateway.mu.Unlock() - - req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session") - rec := httptest.NewRecorder() - handler(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - - expected := tokenPrefix + "ui-token" - if got := rec.Body.String(); got != expected { - t.Fatalf("forwarded protocol = %q, want %q", got, expected) - } - - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.pidData == nil { - t.Fatal("gateway.pidData should be loaded from pid file") - } - if gateway.runtimeStatus != "running" { - t.Fatalf("runtimeStatus = %q, want %q", gateway.runtimeStatus, "running") - } -} - -func TestCreatePicoHTTPProxyInjectsGatewayAuth(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = 18790 - bc := cfg.Channels["pico"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - decoded.(*config.PicoSettings).SetToken("ui-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - proxy := h.createPicoHTTPProxy("ui-token") - var capturedPath string - var capturedAuth string - proxy.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { - capturedPath = req.URL.Path - capturedAuth = req.Header.Get("Authorization") - return &http.Response{ - StatusCode: http.StatusOK, - Header: make(http.Header), - Body: io.NopCloser(strings.NewReader("proxied")), - Request: req, - }, nil - }) - - req := httptest.NewRequest(http.MethodGet, "/pico/media/attachment-1", nil) - rec := httptest.NewRecorder() - proxy.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - if capturedPath != "/pico/media/attachment-1" { - t.Fatalf("capturedPath = %q, want %q", capturedPath, "/pico/media/attachment-1") - } - expected := "Bearer ui-token" - if capturedAuth != expected { - t.Fatalf("Authorization = %q, want %q", capturedAuth, expected) - } -} - -func TestHandlePicoMediaProxyUsesRawBearerToken(t *testing.T) { - home := t.TempDir() - t.Setenv("PICOCLAW_HOME", home) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - handler := h.handlePicoMediaProxy() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/media/attachment-1" { - t.Fatalf("path = %q, want %q", r.URL.Path, "/pico/media/attachment-1") - } - if got := r.Header.Get("Authorization"); got != "Bearer ui-token" { - t.Fatalf("Authorization = %q, want %q", got, "Bearer ui-token") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, "proxied-media") - })) - defer server.Close() - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = mustGatewayTestPort(t, server.URL) - bc := cfg.Channels["pico"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - decoded.(*config.PicoSettings).SetToken("ui-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - origCmd := gateway.cmd - t.Cleanup(func() { - gateway.mu.Lock() - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - gateway.cmd = origCmd - gateway.mu.Unlock() - }) - - gateway.mu.Lock() - gateway.pidData = &ppid.PidFileData{PID: cmd.Process.Pid} - gateway.picoToken = "ui-token" - gateway.cmd = cmd - gateway.mu.Unlock() - - req := newPicoProxyRequest(http.MethodGet, "/pico/media/attachment-1") - rec := httptest.NewRecorder() - handler(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } - if body := rec.Body.String(); body != "proxied-media" { - t.Fatalf("body = %q, want %q", body, "proxied-media") - } -} - -func TestHandleWebSocketProxyRejectsStalePidDataAfterProcessExit(t *testing.T) { - tmpDir := t.TempDir() - t.Setenv("HOME", tmpDir) - t.Setenv("PICOCLAW_HOME", filepath.Join(tmpDir, ".picoclaw")) - - configPath := filepath.Join(tmpDir, "config.json") - h := NewHandler(configPath) - handler := h.handleWebSocketProxy() - - cfg := config.DefaultConfig() - bc := cfg.Channels["pico"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - decoded.(*config.PicoSettings).SetToken("ui-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - cmd := startLongRunningProcess(t) - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - origCmd := gateway.cmd - origStatus := gateway.runtimeStatus - t.Cleanup(func() { - gateway.mu.Lock() - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - gateway.cmd = origCmd - gateway.runtimeStatus = origStatus - gateway.mu.Unlock() - }) - - gateway.mu.Lock() - gateway.pidData = &ppid.PidFileData{PID: cmd.Process.Pid, Token: "stale-token"} - gateway.picoToken = "ui-token" - gateway.cmd = cmd - setGatewayRuntimeStatusLocked("running") - gateway.mu.Unlock() - - req := newPicoProxyRequest(http.MethodGet, "/pico/ws?session_id=test-session") - rec := httptest.NewRecorder() - handler(rec, req) - - if rec.Code != http.StatusServiceUnavailable { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable) - } - gateway.mu.Lock() - defer gateway.mu.Unlock() - if gateway.pidData != nil { - t.Fatal("gateway.pidData should be cleared after stale process exit is detected") - } -} - -func TestHandleWebSocketProxy_AllowsArbitraryOrigin(t *testing.T) { - origMatcher := gatewayProcessMatcher - gatewayProcessMatcher = func(int) (bool, bool) { return true, true } - t.Cleanup(func() { gatewayProcessMatcher = origMatcher }) - - home := t.TempDir() - t.Setenv("PICOCLAW_HOME", home) - - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - handler := h.handleWebSocketProxy() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/pico/ws" { - t.Fatalf("path = %q, want %q", r.URL.Path, "/pico/ws") - } - w.WriteHeader(http.StatusOK) - _, _ = io.WriteString(w, "proxied") - })) - defer server.Close() - - cfg := config.DefaultConfig() - cfg.Gateway.Host = "127.0.0.1" - cfg.Gateway.Port = mustGatewayTestPort(t, server.URL) - bc := cfg.Channels["pico"] - bc.Enabled = true - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - decoded.(*config.PicoSettings).SetToken("ui-token") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - cmd := startGatewayLikeProcess(t) - t.Cleanup(func() { - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - _ = cmd.Wait() - }) - writeTestPidFile(t, ppid.PidFileData{ - PID: cmd.Process.Pid, - Token: "test-token", - Host: cfg.Gateway.Host, - Port: cfg.Gateway.Port, - }) - t.Cleanup(func() { - ppid.RemovePidFile(globalConfigDir()) - }) - - origPidData := gateway.pidData - origPicoToken := gateway.picoToken - t.Cleanup(func() { - gateway.pidData = origPidData - gateway.picoToken = origPicoToken - }) - - gateway.pidData = &ppid.PidFileData{} - gateway.picoToken = "ui-token" - - req := httptest.NewRequest(http.MethodGet, "http://launcher.local/pico/ws?session_id=test-session", nil) - req.Header.Set("Origin", "http://evil.example") - rec := httptest.NewRecorder() - handler(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func mustGatewayTestPort(t *testing.T, rawURL string) int { - t.Helper() - - parsed, err := url.Parse(rawURL) - if err != nil { - t.Fatalf("url.Parse() error = %v", err) - } - - port, err := strconv.Atoi(parsed.Port()) - if err != nil { - t.Fatalf("Atoi(%q) error = %v", parsed.Port(), err) - } - - return port -} - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return fn(req) -} diff --git a/web/backend/api/router.go b/web/backend/api/router.go deleted file mode 100644 index aeeb01fc..00000000 --- a/web/backend/api/router.go +++ /dev/null @@ -1,126 +0,0 @@ -package api - -import ( - "net/http" - "strings" - "sync" - - "github.com/sipeed/picoclaw/web/backend/launcherconfig" -) - -// Handler serves HTTP API requests. -type Handler struct { - configPath string - serverPort int - serverPublic bool - serverPublicExplicit bool - serverHostInput string - serverHostExplicit bool - serverCIDRs []string - serverAllowLocalhostBypass bool - serverTrustedProxyCIDRs []string - debug bool - // Serializes model-related config writes. Other config endpoints still - // coordinate their own load-modify-save cycles. - configMu sync.Mutex - oauthMu sync.Mutex - oauthFlows map[string]*oauthFlow - oauthState map[string]string - weixinMu sync.Mutex - weixinFlows map[string]*weixinFlow - wecomMu sync.Mutex - wecomFlows map[string]*wecomFlow -} - -// NewHandler creates an instance of the API handler. -func NewHandler(configPath string) *Handler { - return &Handler{ - configPath: configPath, - serverPort: launcherconfig.DefaultPort, - serverAllowLocalhostBypass: launcherconfig.Default().AllowLocalhostBypass, - oauthFlows: make(map[string]*oauthFlow), - oauthState: make(map[string]string), - weixinFlows: make(map[string]*weixinFlow), - wecomFlows: make(map[string]*wecomFlow), - } -} - -// SetServerOptions stores current backend listen options for fallback behavior. -func (h *Handler) SetServerOptions(port int, public bool, publicExplicit bool, allowedCIDRs []string) { - h.serverPort = port - h.serverPublic = public - h.serverPublicExplicit = publicExplicit - h.serverHostInput = "" - h.serverHostExplicit = false - h.serverCIDRs = append([]string(nil), allowedCIDRs...) -} - -func (h *Handler) SetServerAccessOptions(allowLocalhostBypass bool, trustedProxyCIDRs []string) { - h.serverAllowLocalhostBypass = allowLocalhostBypass - h.serverTrustedProxyCIDRs = append([]string(nil), trustedProxyCIDRs...) -} - -// SetServerBindHost stores the launcher's effective bind host. -// When explicit is true, hostInput is the normalized -host / PICOCLAW_LAUNCHER_HOST value. -func (h *Handler) SetServerBindHost(hostInput string, explicit bool) { - h.serverHostInput = strings.TrimSpace(hostInput) - if !explicit { - h.serverHostInput = "" - } - h.serverHostExplicit = explicit -} - -func (h *Handler) SetDebug(debug bool) { - h.debug = debug -} - -// RegisterRoutes binds all API endpoint handlers to the ServeMux. -func (h *Handler) RegisterRoutes(mux *http.ServeMux) { - // Config CRUD - h.registerConfigRoutes(mux) - - // Pico Channel (WebSocket chat) - h.registerPicoRoutes(mux) - - // Gateway process lifecycle - h.registerGatewayRoutes(mux) - - // Session history - h.registerSessionRoutes(mux) - - // OAuth login and credential management - h.registerOAuthRoutes(mux) - - // Model list management - h.registerModelRoutes(mux) - - // Channel catalog (for frontend navigation/config pages) - h.registerChannelRoutes(mux) - - // Skills and tools support/actions - h.registerSkillRoutes(mux) - h.registerToolRoutes(mux) - - // OS startup / launch-at-login - h.registerStartupRoutes(mux) - - // Launcher service parameters (port/public) - h.registerLauncherConfigRoutes(mux) - - // Self-update endpoint (requires dashboard auth) - h.registerUpdateRoutes(mux) - - // Runtime build/version metadata - h.registerVersionRoutes(mux) - - // WeChat QR login flow - h.registerWeixinRoutes(mux) - - // WeCom QR login flow - h.registerWecomRoutes(mux) -} - -// Shutdown gracefully shuts down the handler, stopping the gateway if it was started by this handler. -func (h *Handler) Shutdown() { - h.StopGateway() -} diff --git a/web/backend/api/session.go b/web/backend/api/session.go deleted file mode 100644 index bab4ef79..00000000 --- a/web/backend/api/session.go +++ /dev/null @@ -1,1006 +0,0 @@ -package api - -import ( - "bufio" - "encoding/json" - "errors" - "net/http" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/memory" - "github.com/sipeed/picoclaw/pkg/providers" - "github.com/sipeed/picoclaw/pkg/providers/messageutil" - "github.com/sipeed/picoclaw/pkg/session" - "github.com/sipeed/picoclaw/pkg/utils" -) - -// registerSessionRoutes binds session list and detail endpoints to the ServeMux. -func (h *Handler) registerSessionRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/sessions", h.handleListSessions) - mux.HandleFunc("GET /api/sessions/{id}", h.handleGetSession) - mux.HandleFunc("DELETE /api/sessions/{id}", h.handleDeleteSession) -} - -// sessionFile mirrors the on-disk session JSON structure from pkg/session. -type sessionFile struct { - Key string `json:"key"` - Messages []providers.Message `json:"messages"` - Summary string `json:"summary,omitempty"` - Created time.Time `json:"created"` - Updated time.Time `json:"updated"` -} - -// sessionListItem is a lightweight summary returned by GET /api/sessions. -type sessionListItem struct { - ID string `json:"id"` - Title string `json:"title"` - Preview string `json:"preview"` - MessageCount int `json:"message_count"` - Created string `json:"created"` - Updated string `json:"updated"` -} - -type sessionChatMessage struct { - Role string `json:"role"` - Content string `json:"content"` - Kind string `json:"kind,omitempty"` - ModelName string `json:"model_name,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - Media []string `json:"media,omitempty"` - Attachments []sessionChatAttachment `json:"attachments,omitempty"` - ToolCalls []utils.VisibleToolCall `json:"tool_calls,omitempty"` -} - -type sessionChatAttachment struct { - Type string `json:"type,omitempty"` - URL string `json:"url,omitempty"` - Filename string `json:"filename,omitempty"` - ContentType string `json:"content_type,omitempty"` -} - -// legacyPicoSessionPrefix is the legacy key prefix used by older Pico JSON/JSONL -// sessions before structured scope metadata existed. -const ( - legacyPicoSessionPrefix = "agent:main:pico:direct:pico:" - picoSessionPrefix = legacyPicoSessionPrefix - - // Keep the session API aligned with the shared JSONL store reader limit in - // pkg/memory/jsonl.go so oversized lines fail consistently everywhere. - maxSessionJSONLLineSize = 10 * 1024 * 1024 - maxSessionTitleRunes = 60 - - handledToolResponseSummaryText = "Requested output delivered via tool attachment." -) - -func defaultToolFeedbackMaxArgsLength() int { - defaults := config.AgentDefaults{} - return defaults.GetToolFeedbackMaxArgsLength() -} - -// extractLegacyPicoSessionID extracts the session UUID from an old Pico key. -// Returns the UUID and true if the key matches the Pico session pattern. -func extractLegacyPicoSessionID(key string) (string, bool) { - if strings.HasPrefix(key, legacyPicoSessionPrefix) { - return strings.TrimPrefix(key, legacyPicoSessionPrefix), true - } - return "", false -} - -func sanitizeSessionKey(key string) string { - key = strings.ReplaceAll(key, ":", "_") - key = strings.ReplaceAll(key, "/", "_") - key = strings.ReplaceAll(key, "\\", "_") - return key -} - -func (h *Handler) readLegacySession(path string) (sessionFile, error) { - data, err := os.ReadFile(path) - if err != nil { - return sessionFile{}, err - } - - var sess sessionFile - if err := json.Unmarshal(data, &sess); err != nil { - return sessionFile{}, err - } - return sess, nil -} - -func (h *Handler) readSessionMeta(path, sessionKey string) (memory.SessionMeta, error) { - data, err := os.ReadFile(path) - if os.IsNotExist(err) { - return memory.SessionMeta{Key: sessionKey}, nil - } - if err != nil { - return memory.SessionMeta{}, err - } - - var meta memory.SessionMeta - if err := json.Unmarshal(data, &meta); err != nil { - return memory.SessionMeta{}, err - } - if meta.Key == "" { - meta.Key = sessionKey - } - return meta, nil -} - -func (h *Handler) readSessionMessages(path string, skip int) ([]providers.Message, error) { - f, err := os.Open(path) - if err != nil { - return nil, err - } - defer f.Close() - - msgs := make([]providers.Message, 0) - scanner := bufio.NewScanner(f) - scanner.Buffer(make([]byte, 0, 64*1024), maxSessionJSONLLineSize) - - seen := 0 - for scanner.Scan() { - line := scanner.Bytes() - if len(line) == 0 { - continue - } - - seen++ - if seen <= skip { - continue - } - - var msg providers.Message - if err := json.Unmarshal(line, &msg); err != nil { - continue - } - if messageutil.IsTransientAssistantThoughtMessage(msg) { - continue - } - msgs = append(msgs, msg) - } - if err := scanner.Err(); err != nil { - return nil, err - } - return msgs, nil -} - -func (h *Handler) readJSONLSession(dir, sessionKey string) (sessionFile, error) { - base := filepath.Join(dir, sanitizeSessionKey(sessionKey)) - jsonlPath := base + ".jsonl" - metaPath := base + ".meta.json" - - meta, err := h.readSessionMeta(metaPath, sessionKey) - if err != nil { - return sessionFile{}, err - } - - messages, err := h.readSessionMessages(jsonlPath, meta.Skip) - if err != nil { - return sessionFile{}, err - } - - updated := meta.UpdatedAt - created := meta.CreatedAt - if created.IsZero() || updated.IsZero() { - if info, statErr := os.Stat(jsonlPath); statErr == nil { - if created.IsZero() { - created = info.ModTime() - } - if updated.IsZero() { - updated = info.ModTime() - } - } - } - - return sessionFile{ - Key: meta.Key, - Messages: messages, - Summary: meta.Summary, - Created: created, - Updated: updated, - }, nil -} - -type picoJSONLSessionRef struct { - ID string - Key string -} - -type picoLegacySessionRef struct { - ID string - Path string -} - -func extractPicoSessionIDFromScope(scope session.SessionScope) (string, bool) { - if !strings.EqualFold(strings.TrimSpace(scope.Channel), "pico") { - return "", false - } - - candidates := []string{ - strings.TrimSpace(scope.Values["sender"]), - strings.TrimSpace(scope.Values["chat"]), - } - for _, candidate := range candidates { - if candidate == "" { - continue - } - if idx := strings.Index(candidate, "pico:"); idx >= 0 { - sessionID := strings.TrimSpace(candidate[idx+len("pico:"):]) - if sessionID != "" { - return sessionID, true - } - } - } - return "", false -} - -func sessionRefFromMeta(meta memory.SessionMeta) (picoJSONLSessionRef, bool) { - if len(meta.Scope) == 0 { - if sessionID, ok := extractLegacyPicoSessionID(meta.Key); ok { - return picoJSONLSessionRef{ID: sessionID, Key: meta.Key}, true - } - for _, alias := range meta.Aliases { - if sessionID, ok := extractLegacyPicoSessionID(alias); ok { - return picoJSONLSessionRef{ID: sessionID, Key: meta.Key}, true - } - } - return picoJSONLSessionRef{}, false - } - var scope session.SessionScope - if err := json.Unmarshal(meta.Scope, &scope); err != nil { - return picoJSONLSessionRef{}, false - } - sessionID, ok := extractPicoSessionIDFromScope(scope) - if !ok { - if legacySessionID, ok := extractLegacyPicoSessionID(meta.Key); ok { - return picoJSONLSessionRef{ID: legacySessionID, Key: meta.Key}, true - } - for _, alias := range meta.Aliases { - if legacySessionID, ok := extractLegacyPicoSessionID(alias); ok { - return picoJSONLSessionRef{ID: legacySessionID, Key: meta.Key}, true - } - } - return picoJSONLSessionRef{}, false - } - return picoJSONLSessionRef{ID: sessionID, Key: meta.Key}, true -} - -func (h *Handler) findPicoJSONLSessions(dir string) ([]picoJSONLSessionRef, error) { - entries, err := os.ReadDir(dir) - if err != nil { - return nil, err - } - - refs := make([]picoJSONLSessionRef, 0) - seen := make(map[string]struct{}) - metaBackedBases := make(map[string]struct{}) - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".meta.json") { - continue - } - name := entry.Name() - metaPath := filepath.Join(dir, name) - meta, err := h.readSessionMeta(metaPath, "") - if err != nil { - continue - } - ref, ok := sessionRefFromMeta(meta) - if !ok || ref.Key == "" || ref.ID == "" { - continue - } - metaBackedBases[strings.TrimSuffix(name, ".meta.json")] = struct{}{} - if _, exists := seen[ref.ID]; exists { - continue - } - seen[ref.ID] = struct{}{} - refs = append(refs, ref) - } - - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".jsonl") { - continue - } - name := entry.Name() - base := strings.TrimSuffix(name, ".jsonl") - if _, ok := metaBackedBases[base]; ok { - continue - } - ref, ok := jsonlSessionRefFromFilename(name) - if !ok || ref.Key == "" || ref.ID == "" { - continue - } - if _, exists := seen[ref.ID]; exists { - continue - } - seen[ref.ID] = struct{}{} - refs = append(refs, ref) - } - return refs, nil -} - -func (h *Handler) findPicoJSONLSession(dir, sessionID string) (picoJSONLSessionRef, error) { - refs, err := h.findPicoJSONLSessions(dir) - if err != nil { - return picoJSONLSessionRef{}, err - } - for _, ref := range refs { - if ref.ID == sessionID { - return ref, nil - } - } - return picoJSONLSessionRef{}, os.ErrNotExist -} - -func (h *Handler) findLegacyPicoSessions(dir string) ([]picoLegacySessionRef, error) { - entries, err := os.ReadDir(dir) - if err != nil { - return nil, err - } - - refs := make([]picoLegacySessionRef, 0) - seen := make(map[string]struct{}) - for _, entry := range entries { - name := entry.Name() - if entry.IsDir() || filepath.Ext(name) != ".json" || strings.HasSuffix(name, ".meta.json") { - continue - } - - path := filepath.Join(dir, entry.Name()) - sess, err := h.readLegacySession(path) - if err != nil || isEmptySession(sess) { - continue - } - - sessionID, ok := extractLegacyPicoSessionID(sess.Key) - if !ok || sessionID == "" { - continue - } - if _, exists := seen[sessionID]; exists { - continue - } - seen[sessionID] = struct{}{} - refs = append(refs, picoLegacySessionRef{ID: sessionID, Path: path}) - } - return refs, nil -} - -func jsonlSessionRefFromFilename(name string) (picoJSONLSessionRef, bool) { - if !strings.HasSuffix(name, ".jsonl") { - return picoJSONLSessionRef{}, false - } - base := strings.TrimSuffix(name, ".jsonl") - if base == "" { - return picoJSONLSessionRef{}, false - } - - legacyPrefix := sanitizeSessionKey(legacyPicoSessionPrefix) - if strings.HasPrefix(base, legacyPrefix) { - sessionID := strings.TrimPrefix(base, legacyPrefix) - if sessionID == "" { - return picoJSONLSessionRef{}, false - } - return picoJSONLSessionRef{ - ID: sessionID, - Key: legacyPicoSessionPrefix + sessionID, - }, true - } - - if session.IsOpaqueSessionKey(base) { - return picoJSONLSessionRef{ - ID: base, - Key: base, - }, true - } - - return picoJSONLSessionRef{}, false -} - -func (h *Handler) findLegacyPicoSession(dir, sessionID string) (picoLegacySessionRef, error) { - refs, err := h.findLegacyPicoSessions(dir) - if err != nil { - return picoLegacySessionRef{}, err - } - for _, ref := range refs { - if ref.ID == sessionID { - return ref, nil - } - } - return picoLegacySessionRef{}, os.ErrNotExist -} - -func buildSessionListItem(sessionID string, sess sessionFile, toolFeedbackMaxArgsLength int) sessionListItem { - transcript := visibleSessionMessages(sess.Messages, toolFeedbackMaxArgsLength) - - preview := "" - for _, msg := range transcript { - if msg.Role == "user" { - preview = sessionChatMessagePreview(msg) - } - if preview != "" { - break - } - } - preview = truncateRunes(preview, maxSessionTitleRunes) - - if preview == "" { - preview = "(empty)" - } - title := preview - - return sessionListItem{ - ID: sessionID, - Title: title, - Preview: preview, - MessageCount: len(transcript), - Created: sess.Created.Format(time.RFC3339), - Updated: sess.Updated.Format(time.RFC3339), - } -} - -func isEmptySession(sess sessionFile) bool { - return len(sess.Messages) == 0 && strings.TrimSpace(sess.Summary) == "" -} - -func truncateRunes(s string, maxLen int) string { - if maxLen <= 0 { - return "" - } - runes := []rune(strings.TrimSpace(s)) - if len(runes) <= maxLen { - return string(runes) - } - return string(runes[:maxLen]) + "..." -} - -func sessionChatMessageVisible(msg sessionChatMessage) bool { - return strings.TrimSpace(msg.Content) != "" || - len(msg.Media) > 0 || - len(msg.Attachments) > 0 || - len(msg.ToolCalls) > 0 -} - -func sessionChatMessagePreview(msg sessionChatMessage) string { - if content := strings.TrimSpace(msg.Content); content != "" { - return content - } - if len(msg.Attachments) > 0 { - if strings.EqualFold(strings.TrimSpace(msg.Attachments[0].Type), "image") { - return "[image]" - } - return "[attachment]" - } - if len(msg.Media) > 0 { - if strings.HasPrefix(strings.TrimSpace(msg.Media[0]), "data:image/") { - return "[image]" - } - return "[attachment]" - } - if len(msg.ToolCalls) > 0 { - return "[tool call]" - } - return "" -} - -func visibleSessionMessages(messages []providers.Message, toolFeedbackMaxArgsLength int) []sessionChatMessage { - return sessionTranscriptMessages(messages, toolFeedbackMaxArgsLength, false) -} - -func detailSessionMessages(messages []providers.Message, toolFeedbackMaxArgsLength int) []sessionChatMessage { - return sessionTranscriptMessages(messages, toolFeedbackMaxArgsLength, true) -} - -func sessionTranscriptMessages( - messages []providers.Message, - toolFeedbackMaxArgsLength int, - includeThoughts bool, -) []sessionChatMessage { - transcript := make([]sessionChatMessage, 0, len(messages)) - - for _, msg := range messages { - attachments := sessionAttachments(msg) - - switch msg.Role { - case "tool": - continue - - case "user": - chatMsg := sessionChatMessage{ - Role: "user", - Content: msg.Content, - ModelName: msg.ModelName, - CreatedAt: msg.CreatedAt, - Media: append([]string(nil), msg.Media...), - Attachments: attachments, - } - if sessionChatMessageVisible(chatMsg) { - transcript = append(transcript, chatMsg) - } - - case "assistant": - if messageutil.IsTransientAssistantThoughtMessage(msg) { - continue - } - if includeThoughts { - if thoughtMsg, ok := assistantThoughtMessage(msg); ok { - transcript = append(transcript, thoughtMsg) - } - } - - toolCallsMsg, hasToolCallsMsg := assistantToolCallsMessage( - msg.ToolCalls, - msg.ModelName, - toolFeedbackMaxArgsLength, - msg.CreatedAt, - ) - visibleToolMessages := visibleAssistantToolMessages(msg.ToolCalls, msg.ModelName, msg.CreatedAt) - - // Pico web chat can persist both visible `message` tool output and a - // later plain assistant reply in the same turn. Hide only the fixed - // internal summary that marks handled tool delivery. - content := msg.Content - if assistantMessageInternalOnly(msg) { - if len(attachments) == 0 { - if hasToolCallsMsg { - transcript = append(transcript, toolCallsMsg) - } - if len(visibleToolMessages) > 0 { - transcript = append(transcript, visibleToolMessages...) - } - continue - } - content = "" - } - if hasToolCallsMsg && utils.ToolCallExplanationDuplicatesContent(content, msg.ToolCalls) { - content = "" - } - - chatMsg := sessionChatMessage{ - Role: "assistant", - Content: content, - ModelName: msg.ModelName, - CreatedAt: msg.CreatedAt, - Media: append([]string(nil), msg.Media...), - Attachments: attachments, - } - if !sessionChatMessageVisible(chatMsg) { - if hasToolCallsMsg { - transcript = append(transcript, toolCallsMsg) - } - if len(visibleToolMessages) > 0 { - transcript = append(transcript, visibleToolMessages...) - } - continue - } - - transcript = append(transcript, chatMsg) - if hasToolCallsMsg { - transcript = append(transcript, toolCallsMsg) - } - if len(visibleToolMessages) > 0 { - transcript = append(transcript, visibleToolMessages...) - } - } - } - - return filterSessionChatMessages(transcript) -} - -func filterSessionChatMessages(messages []sessionChatMessage) []sessionChatMessage { - filtered := messages[:0] - for _, msg := range messages { - if msg.Role != "user" && msg.Role != "assistant" { - continue - } - filtered = append(filtered, msg) - } - return filtered -} - -func sessionAttachments(msg providers.Message) []sessionChatAttachment { - if len(msg.Attachments) == 0 { - return nil - } - - attachments := make([]sessionChatAttachment, 0, len(msg.Attachments)) - for _, attachment := range msg.Attachments { - urlValue, ok := sessionAttachmentURL(attachment) - if !ok { - continue - } - attachmentType := strings.TrimSpace(attachment.Type) - if attachmentType == "" { - attachmentType = sessionAttachmentType(attachment) - } - attachments = append(attachments, sessionChatAttachment{ - Type: attachmentType, - URL: urlValue, - Filename: strings.TrimSpace(attachment.Filename), - ContentType: strings.TrimSpace(attachment.ContentType), - }) - } - - if len(attachments) == 0 { - return nil - } - return attachments -} - -func sessionAttachmentURL(attachment providers.Attachment) (string, bool) { - if rawURL := strings.TrimSpace(attachment.URL); rawURL != "" { - return rawURL, true - } - - ref := strings.TrimSpace(attachment.Ref) - if ref == "" { - return "", false - } - if strings.HasPrefix(ref, "media://") { - // Persisted session history must only expose durable attachment locations. - // media:// refs depend on the live in-memory MediaStore and may stop - // resolving after a restart or cleanup, so omit them from reopened history. - return "", false - } - return ref, true -} - -func sessionAttachmentType(attachment providers.Attachment) string { - contentType := strings.ToLower(strings.TrimSpace(attachment.ContentType)) - filename := strings.ToLower(strings.TrimSpace(attachment.Filename)) - rawRef := strings.ToLower(strings.TrimSpace(attachment.Ref)) - rawURL := strings.ToLower(strings.TrimSpace(attachment.URL)) - - switch { - case strings.HasPrefix(contentType, "image/"), - strings.HasPrefix(rawRef, "data:image/"), - strings.HasPrefix(rawURL, "data:image/"): - return "image" - case strings.HasPrefix(contentType, "audio/"): - return "audio" - case strings.HasPrefix(contentType, "video/"): - return "video" - } - - switch ext := filepath.Ext(filename); ext { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg": - return "image" - case ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".wma", ".opus": - return "audio" - case ".mp4", ".avi", ".mov", ".webm", ".mkv": - return "video" - default: - return "file" - } -} - -func assistantMessageInternalOnly(msg providers.Message) bool { - return strings.TrimSpace(msg.Content) == handledToolResponseSummaryText -} - -func assistantThoughtMessage(msg providers.Message) (sessionChatMessage, bool) { - reasoning := strings.TrimSpace(msg.ReasoningContent) - if reasoning == "" { - return sessionChatMessage{}, false - } - if reasoning == strings.TrimSpace(msg.Content) { - return sessionChatMessage{}, false - } - return sessionChatMessage{ - Role: "assistant", - Content: reasoning, - Kind: "thought", - ModelName: msg.ModelName, - CreatedAt: msg.CreatedAt, - }, true -} - -func assistantToolCallsMessage( - toolCalls []providers.ToolCall, - modelName string, - toolFeedbackMaxArgsLength int, - createdAt *time.Time, -) (sessionChatMessage, bool) { - if len(toolCalls) == 0 { - return sessionChatMessage{}, false - } - if toolFeedbackMaxArgsLength <= 0 { - toolFeedbackMaxArgsLength = defaultToolFeedbackMaxArgsLength() - } - - visibleToolCalls := utils.BuildVisibleToolCalls(toolCalls, toolFeedbackMaxArgsLength) - if len(visibleToolCalls) == 0 { - return sessionChatMessage{}, false - } - - return sessionChatMessage{ - Role: "assistant", - Kind: "tool_calls", - ModelName: modelName, - CreatedAt: createdAt, - ToolCalls: visibleToolCalls, - }, true -} - -func visibleAssistantToolArgsPreview( - tc providers.ToolCall, - toolFeedbackMaxArgsLength int, -) string { - return utils.VisibleToolCallArgumentsPreview(tc, toolFeedbackMaxArgsLength) -} - -func visibleAssistantToolMessages( - toolCalls []providers.ToolCall, - modelName string, - createdAt *time.Time, -) []sessionChatMessage { - if len(toolCalls) == 0 { - return nil - } - - messages := make([]sessionChatMessage, 0, len(toolCalls)) - for _, tc := range toolCalls { - name, argsJSON := utils.VisibleToolCallNameAndArguments(tc) - if name != "message" { - continue - } - content, ok := parseMessageToolContent(argsJSON) - if !ok { - continue - } - messages = append(messages, sessionChatMessage{ - Role: "assistant", - Content: content, - ModelName: modelName, - CreatedAt: createdAt, - }) - } - - return messages -} - -func parseMessageToolContent(argsJSON string) (string, bool) { - var args struct { - Content string `json:"content"` - } - if err := json.Unmarshal([]byte(argsJSON), &args); err != nil { - return "", false - } - if strings.TrimSpace(args.Content) == "" { - return "", false - } - return args.Content, true -} - -// sessionsDir resolves the path to the gateway's session storage directory. -// It reads the workspace from config, falling back to ~/.picoclaw/workspace. -func (h *Handler) sessionsDir() (string, error) { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return "", err - } - - return resolveSessionsDir(cfg.Agents.Defaults.Workspace), nil -} - -func (h *Handler) sessionRuntimeSettings() (string, int, error) { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return "", 0, err - } - - return resolveSessionsDir(cfg.Agents.Defaults.Workspace), cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength(), nil -} - -func resolveSessionsDir(workspace string) string { - if workspace == "" { - home, _ := os.UserHomeDir() - workspace = filepath.Join(home, ".picoclaw", "workspace") - } - - // Expand ~ prefix - if len(workspace) > 0 && workspace[0] == '~' { - home, _ := os.UserHomeDir() - if len(workspace) > 1 && workspace[1] == '/' { - workspace = home + workspace[1:] - } else { - workspace = home - } - } - - return filepath.Join(workspace, "sessions") -} - -// handleListSessions returns a list of Pico session summaries. -// -// GET /api/sessions -func (h *Handler) handleListSessions(w http.ResponseWriter, r *http.Request) { - dir, toolFeedbackMaxArgsLength, err := h.sessionRuntimeSettings() - if err != nil { - http.Error(w, "failed to resolve sessions directory", http.StatusInternalServerError) - return - } - - if _, err := os.ReadDir(dir); err != nil { - // Directory doesn't exist yet = no sessions - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode([]sessionListItem{}) - return - } - - items := []sessionListItem{} - seen := make(map[string]struct{}) - - if refs, findErr := h.findPicoJSONLSessions(dir); findErr == nil { - for _, ref := range refs { - sess, loadErr := h.readJSONLSession(dir, ref.Key) - if loadErr != nil || isEmptySession(sess) { - continue - } - seen[ref.ID] = struct{}{} - items = append(items, buildSessionListItem(ref.ID, sess, toolFeedbackMaxArgsLength)) - } - } - - if legacyRefs, findErr := h.findLegacyPicoSessions(dir); findErr == nil { - for _, ref := range legacyRefs { - if _, exists := seen[ref.ID]; exists { - continue - } - sess, loadErr := h.readLegacySession(ref.Path) - if loadErr != nil || isEmptySession(sess) { - continue - } - seen[ref.ID] = struct{}{} - items = append(items, buildSessionListItem(ref.ID, sess, toolFeedbackMaxArgsLength)) - } - } - - // Sort by updated descending (most recent first) - sort.Slice(items, func(i, j int) bool { - return items[i].Updated > items[j].Updated - }) - - // Pagination parameters - offsetStr := r.URL.Query().Get("offset") - limitStr := r.URL.Query().Get("limit") - - offset := 0 - limit := 20 // Default limit - - if val, err := strconv.Atoi(offsetStr); err == nil && val >= 0 { - offset = val - } - if val, err := strconv.Atoi(limitStr); err == nil && val > 0 { - limit = val - } - - totalItems := len(items) - - end := offset + limit - if offset >= totalItems { - items = []sessionListItem{} // Out of bounds, return empty - } else { - if end > totalItems { - end = totalItems - } - items = items[offset:end] - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(items) -} - -// handleGetSession returns the full message history for a specific session. -// -// GET /api/sessions/{id} -func (h *Handler) handleGetSession(w http.ResponseWriter, r *http.Request) { - sessionID := r.PathValue("id") - if sessionID == "" { - http.Error(w, "missing session id", http.StatusBadRequest) - return - } - - dir, toolFeedbackMaxArgsLength, err := h.sessionRuntimeSettings() - if err != nil { - http.Error(w, "failed to resolve sessions directory", http.StatusInternalServerError) - return - } - - ref, refErr := h.findPicoJSONLSession(dir, sessionID) - var sess sessionFile - err = refErr - if refErr == nil { - sess, err = h.readJSONLSession(dir, ref.Key) - } - if err == nil && isEmptySession(sess) { - err = os.ErrNotExist - } - if err != nil { - if errors.Is(err, os.ErrNotExist) { - if legacyRef, legacyErr := h.findLegacyPicoSession(dir, sessionID); legacyErr == nil { - sess, err = h.readLegacySession(legacyRef.Path) - } - if err == nil && isEmptySession(sess) { - err = os.ErrNotExist - } - } - if err != nil { - if errors.Is(err, os.ErrNotExist) { - http.Error(w, "session not found", http.StatusNotFound) - } else { - http.Error(w, "failed to parse session", http.StatusInternalServerError) - } - return - } - } - - for i := range sess.Messages { - if sess.Messages[i].CreatedAt == nil { - sess.Messages[i].CreatedAt = &sess.Updated - } - } - messages := detailSessionMessages(sess.Messages, toolFeedbackMaxArgsLength) - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{ - "id": sessionID, - "messages": messages, - "summary": sess.Summary, - "created": sess.Created.Format(time.RFC3339), - "updated": sess.Updated.Format(time.RFC3339), - }) -} - -// handleDeleteSession deletes a specific session. -// -// DELETE /api/sessions/{id} -func (h *Handler) handleDeleteSession(w http.ResponseWriter, r *http.Request) { - sessionID := r.PathValue("id") - if sessionID == "" { - http.Error(w, "missing session id", http.StatusBadRequest) - return - } - - dir, err := h.sessionsDir() - if err != nil { - http.Error(w, "failed to resolve sessions directory", http.StatusInternalServerError) - return - } - - removed := false - if ref, err := h.findPicoJSONLSession(dir, sessionID); err == nil { - base := filepath.Join(dir, sanitizeSessionKey(ref.Key)) - for _, path := range []string{base + ".jsonl", base + ".meta.json"} { - if err := os.Remove(path); err != nil { - if os.IsNotExist(err) { - continue - } - http.Error(w, "failed to delete session", http.StatusInternalServerError) - return - } - removed = true - } - } - - if legacyRef, err := h.findLegacyPicoSession(dir, sessionID); err == nil { - if err := os.Remove(legacyRef.Path); err != nil { - if !os.IsNotExist(err) { - http.Error(w, "failed to delete session", http.StatusInternalServerError) - return - } - } else { - removed = true - } - } - - if !removed { - http.Error(w, "session not found", http.StatusNotFound) - return - } - - w.WriteHeader(http.StatusNoContent) -} diff --git a/web/backend/api/session_test.go b/web/backend/api/session_test.go deleted file mode 100644 index 8604f1df..00000000 --- a/web/backend/api/session_test.go +++ /dev/null @@ -1,1764 +0,0 @@ -package api - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/memory" - "github.com/sipeed/picoclaw/pkg/providers" - "github.com/sipeed/picoclaw/pkg/session" - "github.com/sipeed/picoclaw/pkg/utils" -) - -func sessionsTestDir(t *testing.T, configPath string) string { - t.Helper() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - dir := filepath.Join(cfg.Agents.Defaults.Workspace, "sessions") - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - return dir -} - -func assertVisibleToolCallMessage( - t *testing.T, - msg sessionChatMessage, - toolName string, -) utils.VisibleToolCall { - t.Helper() - - if msg.Role != "assistant" || msg.Kind != "tool_calls" { - t.Fatalf("message = %#v, want assistant/tool_calls", msg) - } - if len(msg.ToolCalls) != 1 { - t.Fatalf("len(message.ToolCalls) = %d, want 1", len(msg.ToolCalls)) - } - if got := msg.ToolCalls[0].Function; got == nil || got.Name != toolName { - t.Fatalf("tool call = %#v, want function %q", msg.ToolCalls[0], toolName) - } - return msg.ToolCalls[0] -} - -func TestHandleListSessions_JSONLStorage(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, storeErr := memory.NewJSONLStore(dir) - if storeErr != nil { - t.Fatalf("NewJSONLStore() error = %v", storeErr) - } - - sessionKey := legacyPicoSessionPrefix + "history-jsonl" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Content: "Explain why the history API is empty after migration.", - }); err != nil { - t.Fatalf("AddFullMessage(user) error = %v", err) - } - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "assistant", - Content: "Because the API still reads only legacy JSON session files.", - }); err != nil { - t.Fatalf("AddFullMessage(assistant) error = %v", err) - } - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "tool", - Content: "ignored", - }); err != nil { - t.Fatalf("AddFullMessage(tool) error = %v", err) - } - if err := store.SetSummary(nil, sessionKey, "JSONL-backed session"); err != nil { - t.Fatalf("SetSummary() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].ID != "history-jsonl" { - t.Fatalf("items[0].ID = %q, want %q", items[0].ID, "history-jsonl") - } - if items[0].MessageCount != 2 { - t.Fatalf("items[0].MessageCount = %d, want 2", items[0].MessageCount) - } - if items[0].Title != "Explain why the history API is empty after migration." { - t.Fatalf( - "items[0].Title = %q, want %q", - items[0].Title, - "Explain why the history API is empty after migration.", - ) - } - if items[0].Preview != "Explain why the history API is empty after migration." { - t.Fatalf("items[0].Preview = %q", items[0].Preview) - } -} - -func TestHandleListSessions_TransientThoughtDoesNotInflateMessageCount(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - sessionKey := legacyPicoSessionPrefix + "history-jsonl-transient" - base := filepath.Join(dir, sanitizeSessionKey(sessionKey)) - now := time.Now().UTC() - - rawJSONL := strings.Join([]string{ - `{"role":"user","content":"keep me"}`, - `{"role":"assistant","content":"","reasoning_content":"dangling thought"}`, - `{"role":"assistant","content":"and me"}`, - }, "\n") + "\n" - if err := os.WriteFile(base+".jsonl", []byte(rawJSONL), 0o644); err != nil { - t.Fatalf("WriteFile(jsonl) error = %v", err) - } - metaData, err := json.Marshal(memory.SessionMeta{ - Key: sessionKey, - Count: 3, - Skip: 0, - CreatedAt: now, - UpdatedAt: now, - }) - if err != nil { - t.Fatalf("Marshal(meta) error = %v", err) - } - if err := os.WriteFile(base+".meta.json", metaData, 0o644); err != nil { - t.Fatalf("WriteFile(meta) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].ID != "history-jsonl-transient" { - t.Fatalf("items[0].ID = %q, want %q", items[0].ID, "history-jsonl-transient") - } - if items[0].MessageCount != 2 { - t.Fatalf("items[0].MessageCount = %d, want 2 after dropping transient thought", items[0].MessageCount) - } -} - -func TestHandleListSessions_TitleUsesFirstUserMessage(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, storeErr := memory.NewJSONLStore(dir) - if storeErr != nil { - t.Fatalf("NewJSONLStore() error = %v", storeErr) - } - - sessionKey := legacyPicoSessionPrefix + "summary-title" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Content: "fallback preview", - }); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - if err := store.SetSummary( - nil, - sessionKey, - " This summary is intentionally longer than sixty characters so it must be truncated in the history menu. ", - ); err != nil { - t.Fatalf("SetSummary() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - expectedTitle := truncateRunes("fallback preview", maxSessionTitleRunes) - if items[0].Title != expectedTitle { - t.Fatalf("items[0].Title = %q", items[0].Title) - } - if items[0].Preview != "fallback preview" { - t.Fatalf("items[0].Preview = %q, want %q", items[0].Preview, "fallback preview") - } -} - -func TestHandleGetSession_JSONLStorage(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := legacyPicoSessionPrefix + "detail-jsonl" - for _, msg := range []providers.Message{ - {Role: "user", Content: "first"}, - {Role: "assistant", Content: "second"}, - {Role: "tool", Content: "ignored"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - if err := store.SetSummary(nil, sessionKey, "detail summary"); err != nil { - t.Fatalf("SetSummary() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-jsonl", 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 resp struct { - ID string `json:"id"` - Summary string `json:"summary"` - Messages []struct { - Role string `json:"role"` - Content string `json:"content"` - } `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.ID != "detail-jsonl" { - t.Fatalf("resp.ID = %q, want %q", resp.ID, "detail-jsonl") - } - if resp.Summary != "detail summary" { - t.Fatalf("resp.Summary = %q, want %q", resp.Summary, "detail summary") - } - if len(resp.Messages) != 2 { - t.Fatalf("len(resp.Messages) = %d, want 2", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "first" { - t.Fatalf("first message = %#v, want user/first", resp.Messages[0]) - } - if resp.Messages[1].Role != "assistant" || resp.Messages[1].Content != "second" { - t.Fatalf("second message = %#v, want assistant/second", resp.Messages[1]) - } -} - -func TestHandleGetSession_HidesHandledToolAttachmentsBackedByMediaRefs(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := legacyPicoSessionPrefix + "attachment-history" - for _, msg := range []providers.Message{ - {Role: "user", Content: "send me the report"}, - { - Role: "assistant", - Content: handledToolResponseSummaryText, - Attachments: []providers.Attachment{{ - Type: "file", - Ref: "media://attachment-1", - Filename: "report.txt", - ContentType: "text/plain", - }}, - }, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/attachment-history", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - if len(resp.Messages) != 1 { - t.Fatalf("len(resp.Messages) = %d, want 1", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "send me the report" { - t.Fatalf("message = %#v, want only user request", resp.Messages[0]) - } -} - -func TestHandleGetSession_ExposesHandledToolAttachmentsWithDurableURL(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := legacyPicoSessionPrefix + "attachment-history-durable" - for _, msg := range []providers.Message{ - {Role: "user", Content: "send me the report"}, - { - Role: "assistant", - Content: handledToolResponseSummaryText, - Attachments: []providers.Attachment{{ - Type: "file", - URL: "https://example.com/report.txt", - Filename: "report.txt", - ContentType: "text/plain", - }}, - }, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/attachment-history-durable", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - if len(resp.Messages) != 2 { - t.Fatalf("len(resp.Messages) = %d, want 2", len(resp.Messages)) - } - - assistant := resp.Messages[1] - if assistant.Role != "assistant" { - t.Fatalf("assistant role = %q, want assistant", assistant.Role) - } - if assistant.Content != "" { - t.Fatalf("assistant content = %q, want empty string", assistant.Content) - } - if len(assistant.Attachments) != 1 { - t.Fatalf("len(assistant.Attachments) = %d, want 1", len(assistant.Attachments)) - } - if assistant.Attachments[0].URL != "https://example.com/report.txt" { - t.Fatalf( - "attachment url = %q, want %q", - assistant.Attachments[0].URL, - "https://example.com/report.txt", - ) - } - if assistant.Attachments[0].Filename != "report.txt" { - t.Fatalf("attachment filename = %q, want %q", assistant.Attachments[0].Filename, "report.txt") - } -} - -func TestHandleSessions_JSONLScopeDiscovery(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, storeErr := memory.NewJSONLStore(dir) - if storeErr != nil { - t.Fatalf("NewJSONLStore() error = %v", storeErr) - } - - sessionKey := "sk_v1_scope_discovery" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Content: "scope discovered session", - }); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - if err := store.SetSummary(nil, sessionKey, "scope summary"); err != nil { - t.Fatalf("SetSummary() error = %v", err) - } - - scopeData, err := json.Marshal(session.SessionScope{ - Version: session.ScopeVersionV1, - AgentID: "main", - Channel: "pico", - Account: "default", - Dimensions: []string{"sender"}, - Values: map[string]string{ - "sender": "pico:scope-jsonl", - }, - }) - if err != nil { - t.Fatalf("Marshal(scope) error = %v", err) - } - if err := store.UpsertSessionMeta(nil, sessionKey, scopeData, nil); err != nil { - t.Fatalf("UpsertSessionMeta() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - listRec := httptest.NewRecorder() - listReq := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) - mux.ServeHTTP(listRec, listReq) - if listRec.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", listRec.Code, http.StatusOK, listRec.Body.String()) - } - - var items []sessionListItem - if err := json.Unmarshal(listRec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal(list) error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].ID != "scope-jsonl" { - t.Fatalf("items[0].ID = %q, want %q", items[0].ID, "scope-jsonl") - } - - detailRec := httptest.NewRecorder() - detailReq := httptest.NewRequest(http.MethodGet, "/api/sessions/scope-jsonl", nil) - mux.ServeHTTP(detailRec, detailReq) - if detailRec.Code != http.StatusOK { - t.Fatalf("detail status = %d, want %d, body=%s", detailRec.Code, http.StatusOK, detailRec.Body.String()) - } - - deleteRec := httptest.NewRecorder() - deleteReq := httptest.NewRequest(http.MethodDelete, "/api/sessions/scope-jsonl", nil) - mux.ServeHTTP(deleteRec, deleteReq) - if deleteRec.Code != http.StatusNoContent { - t.Fatalf("delete status = %d, want %d, body=%s", deleteRec.Code, http.StatusNoContent, deleteRec.Body.String()) - } -} - -func TestHandleGetSession_SkipsTransientThoughtMessages(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-transient-thought" - for _, msg := range []providers.Message{ - {Role: "user", Content: "hello"}, - {Role: "assistant", ReasoningContent: "internal chain of thought"}, - {Role: "assistant", Content: "final visible answer"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-transient-thought", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 2 { - t.Fatalf("len(resp.Messages) = %d, want 2", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "hello" { - t.Fatalf("first message = %#v, want user/hello", resp.Messages[0]) - } - if resp.Messages[1].Role != "assistant" || resp.Messages[1].Content != "final visible answer" { - t.Fatalf("second message = %#v, want assistant/final visible answer", resp.Messages[1]) - } -} - -func TestHandleGetSession_ReconstructsThoughtFromAssistantReasoningContent(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-reasoning-content" - for _, msg := range []providers.Message{ - {Role: "user", Content: "hello"}, - {Role: "assistant", Content: "final visible answer", ModelName: "gpt-5.4", ReasoningContent: "internal chain of thought"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-reasoning-content", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 3 { - t.Fatalf("len(resp.Messages) = %d, want 3", len(resp.Messages)) - } - if resp.Messages[1].Role != "assistant" || - resp.Messages[1].Content != "internal chain of thought" || - resp.Messages[1].Kind != "thought" { - t.Fatalf("thought message = %#v, want assistant thought/internal chain of thought", resp.Messages[1]) - } - if resp.Messages[1].ModelName != "gpt-5.4" { - t.Fatalf("thought model_name = %q, want %q", resp.Messages[1].ModelName, "gpt-5.4") - } - if resp.Messages[2].Role != "assistant" || resp.Messages[2].Content != "final visible answer" { - t.Fatalf("final message = %#v, want assistant/final visible answer", resp.Messages[2]) - } - if resp.Messages[2].ModelName != "gpt-5.4" { - t.Fatalf("final model_name = %q, want %q", resp.Messages[2].ModelName, "gpt-5.4") - } -} - -func TestHandleGetSession_ReconstructsRefreshMatrixForThoughtAndToolSummary(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-refresh-matrix" - for _, msg := range []providers.Message{ - {Role: "user", Content: "turn1"}, - {Role: "assistant", Content: "plain visible", ReasoningContent: "plain thought"}, - {Role: "user", Content: "turn2"}, - { - Role: "assistant", - ReasoningContent: "tool thought", - ToolCalls: []providers.ToolCall{{ - ID: "call_read_file", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md"}`, - }, - }}, - }, - {Role: "tool", ToolCallID: "call_read_file", Content: "file result"}, - {Role: "user", Content: "turn3"}, - { - Role: "assistant", - Content: "tool visible only", - ToolCalls: []providers.ToolCall{{ - ID: "call_list_dir", - Type: "function", - Function: &providers.FunctionCall{ - Name: "list_dir", - Arguments: `{"path":"."}`, - }, - }}, - }, - {Role: "tool", ToolCallID: "call_list_dir", Content: "dir result"}, - {Role: "user", Content: "turn4"}, - { - Role: "assistant", - Content: "tool visible and thought", - ReasoningContent: "tool mixed thought", - ToolCalls: []providers.ToolCall{{ - ID: "call_exec", - Type: "function", - Function: &providers.FunctionCall{ - Name: "exec", - Arguments: `{"command":"pwd"}`, - }, - }}, - }, - {Role: "tool", ToolCallID: "call_exec", Content: "pwd result"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-refresh-matrix", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - if len(resp.Messages) != 13 { - t.Fatalf("len(resp.Messages) = %d, want 13", len(resp.Messages)) - } - - assertMessage := func(index int, role, kind, content string) { - t.Helper() - msg := resp.Messages[index] - if msg.Role != role || msg.Kind != kind || msg.Content != content { - t.Fatalf("messages[%d] = %#v, want role=%q kind=%q content=%q", index, msg, role, kind, content) - } - } - - assertMessage(0, "user", "", "turn1") - assertMessage(1, "assistant", "thought", "plain thought") - assertMessage(2, "assistant", "", "plain visible") - assertMessage(3, "user", "", "turn2") - assertMessage(4, "assistant", "thought", "tool thought") - assertVisibleToolCallMessage(t, resp.Messages[5], "read_file") - assertMessage(6, "user", "", "turn3") - assertMessage(7, "assistant", "", "tool visible only") - assertVisibleToolCallMessage(t, resp.Messages[8], "list_dir") - assertMessage(9, "user", "", "turn4") - assertMessage(10, "assistant", "thought", "tool mixed thought") - assertMessage(11, "assistant", "", "tool visible and thought") - assertVisibleToolCallMessage(t, resp.Messages[12], "exec") -} - -func TestHandleGetSession_ReconstructsVisibleMessageToolOutputWithoutDuplicateSummary(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-message-tool" - for _, msg := range []providers.Message{ - {Role: "user", Content: "test"}, - { - Role: "assistant", - Content: "", - ModelName: "gpt-5.4-mini", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "message", - Arguments: `{"content":"visible tool output"}`, - }, - }, - }, - }, - {Role: "tool", Content: "Message sent to pico:pico:detail-message-tool", ToolCallID: "call_1"}, - {Role: "assistant", Content: handledToolResponseSummaryText}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-message-tool", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 3 { - t.Fatalf("len(resp.Messages) = %d, want 3", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "test" { - t.Fatalf("first message = %#v, want user/test", resp.Messages[0]) - } - assertVisibleToolCallMessage(t, resp.Messages[1], "message") - if resp.Messages[1].ModelName != "gpt-5.4-mini" { - t.Fatalf("tool_calls model_name = %q, want %q", resp.Messages[1].ModelName, "gpt-5.4-mini") - } - if resp.Messages[2].Role != "assistant" || resp.Messages[2].Content != "visible tool output" { - t.Fatalf("assistant message = %#v, want visible tool output", resp.Messages[2]) - } - if resp.Messages[2].ModelName != "gpt-5.4-mini" { - t.Fatalf("visible tool output model_name = %q, want %q", resp.Messages[2].ModelName, "gpt-5.4-mini") - } -} - -func TestHandleGetSession_PreservesFinalAssistantReplyAfterMessageToolOutput(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-message-tool-final-reply" - for _, msg := range []providers.Message{ - {Role: "user", Content: "test"}, - { - Role: "assistant", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "message", - Arguments: `{"content":"visible tool output"}`, - }, - }, - }, - }, - {Role: "tool", Content: "Message sent to pico:pico:detail-message-tool-final-reply", ToolCallID: "call_1"}, - {Role: "assistant", Content: "final assistant reply"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-message-tool-final-reply", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 4 { - t.Fatalf("len(resp.Messages) = %d, want 4", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "test" { - t.Fatalf("first message = %#v, want user/test", resp.Messages[0]) - } - assertVisibleToolCallMessage(t, resp.Messages[1], "message") - if resp.Messages[2].Role != "assistant" || resp.Messages[2].Content != "visible tool output" { - t.Fatalf("interim assistant message = %#v, want visible tool output", resp.Messages[2]) - } - if resp.Messages[3].Role != "assistant" || resp.Messages[3].Content != "final assistant reply" { - t.Fatalf("final assistant message = %#v, want final assistant reply", resp.Messages[3]) - } -} - -func TestHandleListSessions_MessageCountUsesVisibleTranscript(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "list-visible-count" - for _, msg := range []providers.Message{ - {Role: "user", Content: "test"}, - { - Role: "assistant", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "message", - Arguments: `{"content":"visible tool output"}`, - }, - }, - }, - }, - {Role: "tool", Content: "Message sent to pico:pico:list-visible-count", ToolCallID: "call_1"}, - {Role: "assistant", Content: handledToolResponseSummaryText}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].MessageCount != 3 { - t.Fatalf("items[0].MessageCount = %d, want 3", items[0].MessageCount) - } -} - -func TestHandleListSessions_DeduplicatesAssistantToolCallContentFromVisibleTranscript(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "list-deduped-tool-content" - for _, msg := range []providers.Message{ - {Role: "user", Content: "check file"}, - { - Role: "assistant", - Content: "Read the file before replying.", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md"}`, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Read the file before replying.", - }, - }, - }, - }, - {Role: "tool", Content: "raw read_file result", ToolCallID: "call_1"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].MessageCount != 2 { - t.Fatalf("items[0].MessageCount = %d, want 2", items[0].MessageCount) - } -} - -func TestHandleGetSession_DoesNotDuplicateAssistantToolCallContent(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-tool-summary-and-content" - for _, msg := range []providers.Message{ - {Role: "user", Content: "check file"}, - { - Role: "assistant", - Content: "Read the file before replying.", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md","start_line":1,"end_line":10}`, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Read the file before replying.", - }, - }, - }, - }, - {Role: "tool", Content: "raw read_file result", ToolCallID: "call_1"}, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-tool-summary-and-content", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 2 { - t.Fatalf("len(resp.Messages) = %d, want 2", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || resp.Messages[0].Content != "check file" { - t.Fatalf("first message = %#v, want user/check file", resp.Messages[0]) - } - toolCall := assertVisibleToolCallMessage(t, resp.Messages[1], "read_file") - if toolCall.ExtraContent == nil || - toolCall.ExtraContent.ToolFeedbackExplanation != "Read the file before replying." { - t.Fatalf("tool call = %#v, want explanation", toolCall) - } -} - -func TestHandleGetSession_PreservesDistinctAssistantToolCallContent(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-tool-summary-distinct-content" - for _, msg := range []providers.Message{ - {Role: "user", Content: "check file"}, - { - Role: "assistant", - Content: "I will summarize the findings after reading the file.", - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"README.md","start_line":1,"end_line":10}`, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Read the file before replying.", - }, - }, - }, - }, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-tool-summary-distinct-content", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 3 { - t.Fatalf("len(resp.Messages) = %d, want 3", len(resp.Messages)) - } - if resp.Messages[1].Role != "assistant" || - resp.Messages[1].Content != "I will summarize the findings after reading the file." { - t.Fatalf("assistant content = %#v, want preserved distinct content", resp.Messages[1]) - } - assertVisibleToolCallMessage(t, resp.Messages[2], "read_file") -} - -func TestHandleGetSession_PreservesMediaWhenAssistantToolCallContentDuplicatesSummary(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-tool-summary-duplicate-content-with-media" - for _, msg := range []providers.Message{ - {Role: "user", Content: "check screenshot"}, - { - Role: "assistant", - Content: "Reviewing the generated screenshot.", - Media: []string{"data:image/png;base64,abc123"}, - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "view_image", - Arguments: `{"path":"artifact.png"}`, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Reviewing the generated screenshot.", - }, - }, - }, - }, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-tool-summary-duplicate-content-with-media", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 3 { - t.Fatalf("len(resp.Messages) = %d, want 3", len(resp.Messages)) - } - if resp.Messages[1].Role != "assistant" { - t.Fatalf("assistant message role = %q, want assistant", resp.Messages[1].Role) - } - if resp.Messages[1].Content != "" { - t.Fatalf("assistant content = %q, want duplicate content suppressed", resp.Messages[1].Content) - } - if len(resp.Messages[1].Media) != 1 || resp.Messages[1].Media[0] != "data:image/png;base64,abc123" { - t.Fatalf("assistant media = %#v, want preserved media", resp.Messages[1].Media) - } - assertVisibleToolCallMessage(t, resp.Messages[2], "view_image") -} - -func TestHandleGetSession_PreservesAttachmentsWhenAssistantToolCallContentDuplicatesSummary(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-tool-summary-duplicate-content-with-attachments" - for _, msg := range []providers.Message{ - {Role: "user", Content: "check report"}, - { - Role: "assistant", - Content: "Reviewing the generated report.", - Attachments: []providers.Attachment{{ - Type: "file", - URL: "https://example.com/report.txt", - Filename: "report.txt", - ContentType: "text/plain", - }}, - ToolCalls: []providers.ToolCall{ - { - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: `{"path":"report.txt"}`, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: "Reviewing the generated report.", - }, - }, - }, - }, - } { - if err := store.AddFullMessage(nil, sessionKey, msg); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodGet, - "/api/sessions/detail-tool-summary-duplicate-content-with-attachments", - 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 3 { - t.Fatalf("len(resp.Messages) = %d, want 3", len(resp.Messages)) - } - if resp.Messages[1].Role != "assistant" { - t.Fatalf("assistant message role = %q, want assistant", resp.Messages[1].Role) - } - if resp.Messages[1].Content != "" { - t.Fatalf("assistant content = %q, want duplicate content suppressed", resp.Messages[1].Content) - } - if len(resp.Messages[1].Attachments) != 1 { - t.Fatalf("len(assistant.Attachments) = %d, want 1", len(resp.Messages[1].Attachments)) - } - if resp.Messages[1].Attachments[0].URL != "https://example.com/report.txt" { - t.Fatalf("attachment url = %q, want report URL", resp.Messages[1].Attachments[0].URL) - } - assertVisibleToolCallMessage(t, resp.Messages[2], "read_file") -} - -func TestHandleGetSession_UsesConfiguredToolFeedbackMaxArgsLength(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Agents.Defaults.ToolFeedback.MaxArgsLength = 20 - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - argsJSON := `{"path":"README.md","start_line":1,"end_line":10,"extra":"abcdefghijklmnopqrstuvwxyz"}` - explanation := "Read README.md first to confirm the current project structure before editing the config example." - sessionKey := picoSessionPrefix + "detail-tool-summary-max-args" - err = store.AddFullMessage(nil, sessionKey, providers.Message{Role: "user", Content: "check file"}) - if err != nil { - t.Fatalf("AddFullMessage(user) error = %v", err) - } - err = store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "assistant", - ToolCalls: []providers.ToolCall{{ - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: argsJSON, - }, - ExtraContent: &providers.ExtraContent{ - ToolFeedbackExplanation: explanation, - }, - }}, - }) - if err != nil { - t.Fatalf("AddFullMessage(assistant) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-tool-summary-max-args", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - err = json.Unmarshal(rec.Body.Bytes(), &resp) - if err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) < 2 { - t.Fatalf("len(resp.Messages) = %d, want at least 2", len(resp.Messages)) - } - - wantArgsPreview := visibleAssistantToolArgsPreview(providers.ToolCall{ - Function: &providers.FunctionCall{Arguments: argsJSON}, - }, 20) - toolCall := assertVisibleToolCallMessage(t, resp.Messages[1], "read_file") - if toolCall.ExtraContent == nil || toolCall.ExtraContent.ToolFeedbackExplanation != explanation { - t.Fatalf("tool call = %#v, want full explanation %q", toolCall, explanation) - } - if toolCall.Function == nil || toolCall.Function.Arguments != wantArgsPreview { - t.Fatalf("tool call = %#v, want args preview %q", toolCall, wantArgsPreview) - } -} - -func TestHandleGetSession_FallsBackToLegacyToolArgumentsWhenExplanationMissing(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Agents.Defaults.ToolFeedback.MaxArgsLength = 20 - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - argsJSON := `{"path":"README.md","start_line":1,"end_line":10,"extra":"abcdefghijklmnopqrstuvwxyz"}` - sessionKey := picoSessionPrefix + "detail-tool-summary-legacy-args" - if err := store.AddFullMessage( - nil, - sessionKey, - providers.Message{Role: "user", Content: "check file"}, - ); err != nil { - t.Fatalf("AddFullMessage(user) error = %v", err) - } - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "assistant", - ToolCalls: []providers.ToolCall{{ - ID: "call_1", - Type: "function", - Function: &providers.FunctionCall{ - Name: "read_file", - Arguments: argsJSON, - }, - }}, - }); err != nil { - t.Fatalf("AddFullMessage(assistant) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-tool-summary-legacy-args", 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 resp struct { - Messages []sessionChatMessage `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) < 2 { - t.Fatalf("len(resp.Messages) = %d, want at least 2", len(resp.Messages)) - } - - wantPreview := visibleAssistantToolArgsPreview(providers.ToolCall{ - Function: &providers.FunctionCall{Arguments: argsJSON}, - }, 20) - toolCall := assertVisibleToolCallMessage(t, resp.Messages[1], "read_file") - if toolCall.Function == nil || toolCall.Function.Arguments != wantPreview { - t.Fatalf("tool call = %#v, want legacy args preview %q", toolCall, wantPreview) - } -} - -func TestHandleGetSession_IncludesMediaOnlyMessages(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-media-only" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Media: []string{"data:image/png;base64,abc123"}, - }); err != nil { - t.Fatalf("AddFullMessage(user) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-media-only", 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 resp struct { - Messages []struct { - Role string `json:"role"` - Content string `json:"content"` - Media []string `json:"media"` - } `json:"messages"` - } - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Messages) != 1 { - t.Fatalf("len(resp.Messages) = %d, want 1", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" || len(resp.Messages[0].Media) != 1 { - t.Fatalf("message = %#v, want user message with media", resp.Messages[0]) - } -} - -func TestHandleSessions_SupportsJSONLMessagesUpToStoreCap(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "detail-large-jsonl" - largeContent := strings.Repeat("x", 9*1024*1024) - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Content: largeContent, - }); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - listRec := httptest.NewRecorder() - listReq := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) - mux.ServeHTTP(listRec, listReq) - - if listRec.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", listRec.Code, http.StatusOK, listRec.Body.String()) - } - - var items []sessionListItem - if err := json.Unmarshal(listRec.Body.Bytes(), &items); err != nil { - t.Fatalf("list Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - - detailRec := httptest.NewRecorder() - detailReq := httptest.NewRequest(http.MethodGet, "/api/sessions/detail-large-jsonl", nil) - mux.ServeHTTP(detailRec, detailReq) - - if detailRec.Code != http.StatusOK { - t.Fatalf( - "detail status = %d, want %d, body=%s", - detailRec.Code, - http.StatusOK, - detailRec.Body.String(), - ) - } - - var resp struct { - Messages []struct { - Role string `json:"role"` - Content string `json:"content"` - } `json:"messages"` - } - if err := json.Unmarshal(detailRec.Body.Bytes(), &resp); err != nil { - t.Fatalf("detail Unmarshal() error = %v", err) - } - if len(resp.Messages) != 1 { - t.Fatalf("len(resp.Messages) = %d, want 1", len(resp.Messages)) - } - if resp.Messages[0].Role != "user" { - t.Fatalf("resp.Messages[0].Role = %q, want %q", resp.Messages[0].Role, "user") - } - if got := len(resp.Messages[0].Content); got != len(largeContent) { - t.Fatalf("len(resp.Messages[0].Content) = %d, want %d", got, len(largeContent)) - } -} - -func TestHandleListSessions_UsesImagePreviewForMediaOnlyMessage(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := picoSessionPrefix + "preview-media-only" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Media: []string{"data:image/png;base64,abc123"}, - }); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions", 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 items []sessionListItem - if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].Preview != "[image]" { - t.Fatalf("items[0].Preview = %q, want %q", items[0].Preview, "[image]") - } - if items[0].MessageCount != 1 { - t.Fatalf("items[0].MessageCount = %d, want 1", items[0].MessageCount) - } -} - -func TestHandleDeleteSession_JSONLStorage(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - store, err := memory.NewJSONLStore(dir) - if err != nil { - t.Fatalf("NewJSONLStore() error = %v", err) - } - - sessionKey := legacyPicoSessionPrefix + "delete-jsonl" - if err := store.AddFullMessage(nil, sessionKey, providers.Message{ - Role: "user", - Content: "delete me", - }); err != nil { - t.Fatalf("AddFullMessage() error = %v", err) - } - if err := store.SetSummary(nil, sessionKey, "delete summary"); err != nil { - t.Fatalf("SetSummary() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/sessions/delete-jsonl", nil) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusNoContent { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusNoContent, rec.Body.String()) - } - - base := filepath.Join(dir, sanitizeSessionKey(sessionKey)) - for _, path := range []string{base + ".jsonl", base + ".meta.json"} { - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Fatalf("expected %s to be removed, stat err = %v", path, err) - } - } -} - -func TestHandleGetSession_LegacyJSONFallback(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - manager := session.NewSessionManager(dir) - sessionKey := legacyPicoSessionPrefix + "legacy-json" - manager.AddMessage(sessionKey, "user", "legacy user") - manager.AddMessage(sessionKey, "assistant", "legacy assistant") - if err := manager.Save(sessionKey); err != nil { - t.Fatalf("Save() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/sessions/legacy-json", 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()) - } -} - -func TestHandleSessions_FiltersEmptyJSONLFiles(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - base := filepath.Join(dir, sanitizeSessionKey(legacyPicoSessionPrefix+"empty-jsonl")) - if err := os.WriteFile(base+".jsonl", []byte{}, 0o644); err != nil { - t.Fatalf("WriteFile(jsonl) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - listRec := httptest.NewRecorder() - listReq := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) - mux.ServeHTTP(listRec, listReq) - - if listRec.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", listRec.Code, http.StatusOK, listRec.Body.String()) - } - - var items []sessionListItem - if err := json.Unmarshal(listRec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal(list) error = %v", err) - } - if len(items) != 0 { - t.Fatalf("len(items) = %d, want 0", len(items)) - } - - detailRec := httptest.NewRecorder() - detailReq := httptest.NewRequest(http.MethodGet, "/api/sessions/empty-jsonl", nil) - mux.ServeHTTP(detailRec, detailReq) - - if detailRec.Code != http.StatusNotFound { - t.Fatalf("detail status = %d, want %d, body=%s", detailRec.Code, http.StatusNotFound, detailRec.Body.String()) - } -} - -func TestHandleSessions_ListsLegacyJSONLWithoutMeta(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - sessionKey := legacyPicoSessionPrefix + "missing-meta" - base := filepath.Join(dir, sanitizeSessionKey(sessionKey)) - line, err := json.Marshal(providers.Message{Role: "user", Content: "recover me"}) - if err != nil { - t.Fatalf("Marshal(message) error = %v", err) - } - if err := os.WriteFile(base+".jsonl", append(line, '\n'), 0o644); err != nil { - t.Fatalf("WriteFile(jsonl) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - listRec := httptest.NewRecorder() - listReq := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) - mux.ServeHTTP(listRec, listReq) - - if listRec.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", listRec.Code, http.StatusOK, listRec.Body.String()) - } - - var items []sessionListItem - if err := json.Unmarshal(listRec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal(list) error = %v", err) - } - if len(items) != 1 { - t.Fatalf("len(items) = %d, want 1", len(items)) - } - if items[0].ID != "missing-meta" { - t.Fatalf("items[0].ID = %q, want %q", items[0].ID, "missing-meta") - } - - detailRec := httptest.NewRecorder() - detailReq := httptest.NewRequest(http.MethodGet, "/api/sessions/missing-meta", nil) - mux.ServeHTTP(detailRec, detailReq) - - if detailRec.Code != http.StatusOK { - t.Fatalf("detail status = %d, want %d, body=%s", detailRec.Code, http.StatusOK, detailRec.Body.String()) - } -} - -func TestHandleSessions_IgnoresMetaJSONInLegacyFallback(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - dir := sessionsTestDir(t, configPath) - metaOnly := filepath.Join(dir, "agent_main_pico_direct_pico_meta-only.meta.json") - metaOnlyContent := []byte(`{"key":"agent:main:pico:direct:pico:meta-only","summary":"meta only"}`) - if err := os.WriteFile(metaOnly, metaOnlyContent, 0o644); err != nil { - t.Fatalf("WriteFile(meta) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - listRec := httptest.NewRecorder() - listReq := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) - mux.ServeHTTP(listRec, listReq) - - if listRec.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", listRec.Code, http.StatusOK, listRec.Body.String()) - } - - var items []sessionListItem - if err := json.Unmarshal(listRec.Body.Bytes(), &items); err != nil { - t.Fatalf("Unmarshal(list) error = %v", err) - } - if len(items) != 0 { - t.Fatalf("len(items) = %d, want 0", len(items)) - } -} diff --git a/web/backend/api/skills.go b/web/backend/api/skills.go deleted file mode 100644 index e89ff7c3..00000000 --- a/web/backend/api/skills.go +++ /dev/null @@ -1,1108 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/fs" - "net/http" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "sync" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/fileutil" - "github.com/sipeed/picoclaw/pkg/skills" - "github.com/sipeed/picoclaw/pkg/utils" -) - -const defaultInstallSkillRegistry = "github" - -type skillSupportResponse struct { - Skills []skillSupportItem `json:"skills"` -} - -type skillSupportItem struct { - Name string `json:"name"` - Path string `json:"path"` - Source string `json:"source"` - Description string `json:"description"` - OriginKind string `json:"origin_kind"` - RegistryName string `json:"registry_name,omitempty"` - RegistryURL string `json:"registry_url,omitempty"` - InstalledVersion string `json:"installed_version,omitempty"` - InstalledAt int64 `json:"installed_at,omitempty"` -} - -type skillDetailResponse struct { - skillSupportItem - Content string `json:"content"` -} - -type skillSearchResultItem struct { - Score float64 `json:"score"` - Slug string `json:"slug"` - DisplayName string `json:"display_name"` - Summary string `json:"summary"` - Version string `json:"version"` - RegistryName string `json:"registry_name"` - URL string `json:"url,omitempty"` - Installed bool `json:"installed"` - InstalledName string `json:"installed_name,omitempty"` -} - -type skillSearchResponse struct { - Results []skillSearchResultItem `json:"results"` - Limit int `json:"limit"` - Offset int `json:"offset"` - NextOffset int `json:"next_offset,omitempty"` - HasMore bool `json:"has_more"` -} - -type installSkillRequest struct { - Slug string `json:"slug"` - Registry string `json:"registry"` - Version string `json:"version,omitempty"` - Force bool `json:"force,omitempty"` -} - -type installSkillResponse struct { - Status string `json:"status"` - Slug string `json:"slug"` - Registry string `json:"registry"` - Version string `json:"version"` - Summary string `json:"summary,omitempty"` - IsSuspicious bool `json:"is_suspicious,omitempty"` - InstalledSkill *skillSupportItem `json:"skill,omitempty"` -} - -type installedSkillOriginMeta struct { - Version int `json:"version"` - OriginKind string `json:"origin_kind,omitempty"` - Registry string `json:"registry,omitempty"` - Slug string `json:"slug,omitempty"` - RegistryURL string `json:"registry_url,omitempty"` - InstalledVersion string `json:"installed_version,omitempty"` - InstalledAt int64 `json:"installed_at"` -} - -var ( - skillNameSanitizer = regexp.MustCompile(`[^a-z0-9-]+`) - importedSkillFrontmatter = regexp.MustCompile(`(?s)^---(?:\r\n|\n|\r)(.*?)(?:\r\n|\n|\r)---(?:\r\n|\n|\r)*`) - skillFrontmatterStripper = regexp.MustCompile(`(?s)^---(?:\r\n|\n|\r)(.*?)(?:\r\n|\n|\r)---(?:\r\n|\n|\r)*`) - persistSkillOriginMeta = writeSkillOriginMeta - workspaceSkillWriteMu sync.Mutex - errImportedSkillExists = errors.New("skill already exists") -) - -const ( - maxImportedSkillSize = 1 << 20 - maxRegistrySearchFanout = 1000 -) - -func (h *Handler) registerSkillRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/skills", h.handleListSkills) - mux.HandleFunc("GET /api/skills/{name}", h.handleGetSkill) - mux.HandleFunc("GET /api/skills/search", h.handleSearchSkills) - mux.HandleFunc("POST /api/skills/install", h.handleInstallSkill) - mux.HandleFunc("POST /api/skills/import", h.handleImportSkill) - mux.HandleFunc("DELETE /api/skills/{name}", h.handleDeleteSkill) -} - -func (h *Handler) handleListSkills(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 - } - - items, err := buildSkillSupportItems(cfg) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to build skill list: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(skillSupportResponse{ - Skills: items, - }) -} - -func (h *Handler) handleGetSkill(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 - } - - skillItems, err := buildSkillSupportItems(cfg) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to build skill list: %v", err), http.StatusInternalServerError) - return - } - name := r.PathValue("name") - for _, skillItem := range skillItems { - if skillItem.Name != name { - continue - } - - content, err := loadSkillContent(skillItem.Path) - if err != nil { - http.Error(w, "Skill content not found", http.StatusNotFound) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(skillDetailResponse{ - skillSupportItem: skillItem, - Content: content, - }) - return - } - - http.Error(w, "Skill not found", http.StatusNotFound) -} - -func (h *Handler) handleSearchSkills(w http.ResponseWriter, r *http.Request) { - cfg, loadErr := config.LoadConfig(h.configPath) - if loadErr != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", loadErr), http.StatusInternalServerError) - return - } - if registryErr := ensureSkillRegistryToolEnabled(cfg, "find_skills"); registryErr != nil { - http.Error(w, registryErr.Error(), http.StatusBadRequest) - return - } - - query := strings.TrimSpace(r.URL.Query().Get("q")) - - limit := 20 - if rawLimit := strings.TrimSpace(r.URL.Query().Get("limit")); rawLimit != "" { - parsedLimit, parseErr := strconv.Atoi(rawLimit) - if parseErr != nil || parsedLimit < 1 || parsedLimit > 50 { - http.Error(w, "limit must be between 1 and 50", http.StatusBadRequest) - return - } - limit = parsedLimit - } - offset := 0 - if rawOffset := strings.TrimSpace(r.URL.Query().Get("offset")); rawOffset != "" { - parsedOffset, parseErr := strconv.Atoi(rawOffset) - if parseErr != nil || parsedOffset < 0 { - http.Error(w, "offset must be 0 or greater", http.StatusBadRequest) - return - } - offset = parsedOffset - } - - installedSkills, err := buildOccupiedWorkspaceSkillsByDirectory(cfg) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to inspect installed skills: %v", err), http.StatusInternalServerError) - return - } - - if query == "" { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(skillSearchResponse{ - Results: []skillSearchResultItem{}, - Limit: limit, - Offset: offset, - HasMore: false, - }) - return - } - - registryMgr := newSkillsRegistryManager(cfg) - searchLimit := offset + limit + 1 - if searchLimit > maxRegistrySearchFanout { - searchLimit = maxRegistrySearchFanout - } - results, err := registryMgr.SearchAll(r.Context(), query, searchLimit) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to search skills: %v", err), http.StatusBadGateway) - return - } - - if offset > len(results) { - offset = len(results) - } - - end := offset + limit - if end > len(results) { - end = len(results) - } - - pageResults := results[offset:end] - response := make([]skillSearchResultItem, 0, len(pageResults)) - for _, result := range pageResults { - installedSkill, installed := installedSkills[result.Slug] - if !installed { - registry := registryMgr.GetRegistry(result.RegistryName) - if registry != nil { - dirName, err := registry.ResolveInstallDirName(result.Slug) - if err == nil { - installedSkill, installed = installedSkills[dirName] - } - } - } - item := skillSearchResultItem{ - Score: result.Score, - Slug: result.Slug, - DisplayName: result.DisplayName, - Summary: result.Summary, - Version: result.Version, - RegistryName: result.RegistryName, - URL: registrySkillURL(cfg, result.RegistryName, result.Slug, result.Version), - Installed: installed, - } - if installed { - item.InstalledName = installedSkill.Name - } - response = append(response, item) - } - - w.Header().Set("Content-Type", "application/json") - nextOffset := 0 - hasMore := len(results) > end - if hasMore { - nextOffset = end - } - json.NewEncoder(w).Encode(skillSearchResponse{ - Results: response, - Limit: limit, - Offset: offset, - NextOffset: nextOffset, - HasMore: hasMore, - }) -} - -func (h *Handler) handleInstallSkill(w http.ResponseWriter, r *http.Request) { - cfg, loadErr := config.LoadConfig(h.configPath) - if loadErr != nil { - http.Error(w, fmt.Sprintf("Failed to load config: %v", loadErr), http.StatusInternalServerError) - return - } - if registryErr := ensureSkillRegistryToolEnabled(cfg, "install_skill"); registryErr != nil { - http.Error(w, registryErr.Error(), http.StatusBadRequest) - return - } - - var req installSkillRequest - if decodeErr := json.NewDecoder(r.Body).Decode(&req); decodeErr != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", decodeErr), http.StatusBadRequest) - return - } - - req.Slug = strings.TrimSpace(req.Slug) - req.Registry = strings.TrimSpace(req.Registry) - req.Version = strings.TrimSpace(req.Version) - if req.Registry == "" { - req.Registry = defaultInstallSkillRegistry - } - - if validateErr := utils.ValidateSkillIdentifier(req.Registry); validateErr != nil { - http.Error( - w, - fmt.Sprintf("invalid registry %q: error: %s", req.Registry, validateErr.Error()), - http.StatusBadRequest, - ) - return - } - - registryMgr := newSkillsRegistryManager(cfg) - registry := registryMgr.GetRegistry(req.Registry) - if registry == nil { - http.Error(w, fmt.Sprintf("registry %q not found", req.Registry), http.StatusBadRequest) - return - } - dirName, err := registry.ResolveInstallDirName(req.Slug) - if err != nil { - http.Error(w, fmt.Sprintf("invalid slug %q: error: %s", req.Slug, err.Error()), http.StatusBadRequest) - return - } - - workspace := cfg.WorkspacePath() - skillsRoot := filepath.Join(workspace, "skills") - targetDir := filepath.Join(workspace, "skills", dirName) - workspaceSkillWriteMu.Lock() - defer workspaceSkillWriteMu.Unlock() - - targetExists := false - if _, statErr := os.Stat(targetDir); statErr == nil { - targetExists = true - } else if !os.IsNotExist(statErr) { - http.Error(w, fmt.Sprintf("Failed to inspect install target: %v", statErr), http.StatusInternalServerError) - return - } - - if !req.Force && targetExists { - http.Error(w, fmt.Sprintf("skill %q already installed at %s", dirName, targetDir), http.StatusConflict) - return - } - if mkdirErr := os.MkdirAll(skillsRoot, 0o755); mkdirErr != nil { - http.Error(w, fmt.Sprintf("Failed to create skills directory: %v", mkdirErr), http.StatusInternalServerError) - return - } - - stagedWorkspaceRoot, stagedTargetDir, err := createStagedSkillInstall(skillsRoot, dirName) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to prepare staged install: %v", err), http.StatusInternalServerError) - return - } - defer os.RemoveAll(stagedWorkspaceRoot) - - result, err := registry.DownloadAndInstall(r.Context(), req.Slug, req.Version, stagedTargetDir) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to install skill: %v", err), http.StatusBadGateway) - return - } - if result.IsMalwareBlocked { - http.Error( - w, - fmt.Sprintf("skill %q is flagged as malicious and cannot be installed", req.Slug), - http.StatusForbidden, - ) - return - } - - if findWorkspaceSkillInfoByDirectory(stagedWorkspaceRoot, dirName) == nil { - http.Error( - w, - fmt.Sprintf("Failed to install skill: registry archive for %q is not a valid skill", req.Slug), - http.StatusBadGateway, - ) - return - } - - installedAt := time.Now().UnixMilli() - normalizedSlug, registryURL := skills.BuildInstallMetadataForRegistryInstance(registry, req.Slug, result.Version) - if err := persistSkillOriginMeta(stagedTargetDir, installedSkillOriginMeta{ - Version: 1, - OriginKind: "third_party", - Registry: registry.Name(), - Slug: normalizedSlug, - RegistryURL: registryURL, - InstalledVersion: result.Version, - InstalledAt: installedAt, - }); err != nil { - http.Error(w, fmt.Sprintf("Failed to persist skill metadata: %v", err), http.StatusInternalServerError) - return - } - - if err := commitStagedSkillInstall( - stagedWorkspaceRoot, - stagedTargetDir, - targetDir, - req.Force && targetExists, - ); err != nil { - http.Error(w, fmt.Sprintf("Failed to activate installed skill: %v", err), http.StatusInternalServerError) - return - } - - validatedSkill := findWorkspaceSkillByDirectory(cfg, dirName) - if validatedSkill == nil { - http.Error( - w, - fmt.Sprintf("Failed to install skill: activated archive for %q is not a valid skill", req.Slug), - http.StatusBadGateway, - ) - return - } - - installedSkill := &skillSupportItem{ - Name: validatedSkill.Name, - Path: validatedSkill.Path, - Source: validatedSkill.Source, - Description: validatedSkill.Description, - OriginKind: "third_party", - RegistryName: registry.Name(), - RegistryURL: registryURL, - InstalledVersion: result.Version, - InstalledAt: installedAt, - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(installSkillResponse{ - Status: "ok", - Slug: req.Slug, - Registry: registry.Name(), - Version: result.Version, - Summary: result.Summary, - IsSuspicious: result.IsSuspicious, - InstalledSkill: installedSkill, - }) -} - -func (h *Handler) handleImportSkill(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 - } - - err = r.ParseMultipartForm(2 << 20) - if err != nil { - http.Error(w, fmt.Sprintf("Invalid multipart form: %v", err), http.StatusBadRequest) - return - } - - uploadedFile, fileHeader, err := r.FormFile("file") - if err != nil { - http.Error(w, "file is required", http.StatusBadRequest) - return - } - defer uploadedFile.Close() - - content, err := io.ReadAll(io.LimitReader(uploadedFile, maxImportedSkillSize+1)) - if err != nil { - http.Error(w, fmt.Sprintf("Failed to read file: %v", err), http.StatusBadRequest) - return - } - if len(content) > maxImportedSkillSize { - http.Error(w, "file exceeds 1MB limit", http.StatusBadRequest) - return - } - workspaceSkillWriteMu.Lock() - defer workspaceSkillWriteMu.Unlock() - - importedSkill, statusCode, err := importUploadedSkill(cfg, fileHeader.Filename, content) - if err != nil { - http.Error(w, err.Error(), statusCode) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(importedSkill) -} - -func (h *Handler) handleDeleteSkill(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 - } - - loader := newSkillsLoader(cfg.WorkspacePath()) - name := r.PathValue("name") - workspaceSkillWriteMu.Lock() - defer workspaceSkillWriteMu.Unlock() - - var matchedNonWorkspace bool - for _, skill := range loader.ListSkills() { - if skill.Name != name { - continue - } - if skill.Source != "workspace" { - matchedNonWorkspace = true - continue - } - if err := os.RemoveAll(filepath.Dir(skill.Path)); err != nil { - http.Error(w, fmt.Sprintf("Failed to delete skill: %v", err), http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) - return - } - if matchedNonWorkspace { - http.Error(w, "only workspace skills can be deleted", http.StatusBadRequest) - return - } - - http.Error(w, "Skill not found", http.StatusNotFound) -} - -func newSkillsLoader(workspace string) *skills.SkillsLoader { - return skills.NewSkillsLoader( - workspace, - filepath.Join(globalConfigDir(), "skills"), - builtinSkillsDir(), - ) -} - -func newSkillsRegistryManager(cfg *config.Config) *skills.RegistryManager { - return skills.NewRegistryManagerFromToolsConfig(cfg.Tools.Skills) -} - -func ensureSkillRegistryToolEnabled(cfg *config.Config, toolName string) error { - if !cfg.Tools.IsToolEnabled("skills") { - return fmt.Errorf("tools.skills is disabled") - } - if !cfg.Tools.IsToolEnabled(toolName) { - return fmt.Errorf("%s is disabled", toolName) - } - return nil -} - -func buildSkillSupportItems(cfg *config.Config) ([]skillSupportItem, error) { - rawSkills := newSkillsLoader(cfg.WorkspacePath()).ListSkills() - items := make([]skillSupportItem, 0, len(rawSkills)) - for _, skill := range rawSkills { - item, err := enrichSkillInfo(cfg, skill) - if err != nil { - return nil, err - } - items = append(items, item) - } - return items, nil -} - -func buildWorkspaceSkillItemsByDirectory(cfg *config.Config) (map[string]skillSupportItem, error) { - result := make(map[string]skillSupportItem) - items, err := buildSkillSupportItems(cfg) - if err != nil { - return nil, err - } - for _, skill := range items { - if skill.Source != "workspace" { - continue - } - dir := filepath.Base(filepath.Dir(skill.Path)) - if dir == "" { - continue - } - result[dir] = skill - } - return result, nil -} - -func buildOccupiedWorkspaceSkillsByDirectory(cfg *config.Config) (map[string]skillSupportItem, error) { - result := make(map[string]skillSupportItem) - items, err := buildSkillSupportItems(cfg) - if err != nil { - return nil, err - } - for _, skill := range items { - if skill.Source != "workspace" { - continue - } - - dirName := filepath.Base(filepath.Dir(skill.Path)) - if dirName != "" { - result[dirName] = skill - } - if meta, err := readInstalledSkillOriginMeta(skill.Path); err == nil && meta != nil && meta.Slug != "" { - key := skills.NormalizeInstallTargetForRegistry(cfg.Tools.Skills, meta.Registry, meta.Slug) - if key == "" { - key = meta.Slug - } - if key != "" { - result[key] = skill - } - } - } - return result, nil -} - -func findWorkspaceSkillByDirectory(cfg *config.Config, directory string) *skillSupportItem { - items, err := buildWorkspaceSkillItemsByDirectory(cfg) - if err != nil { - return nil - } - skill, ok := items[directory] - if !ok { - return nil - } - return &skill -} - -func findWorkspaceSkillInfoByDirectory(workspace, directory string) *skills.SkillInfo { - loader := skills.NewSkillsLoader(workspace, "", "") - for _, skill := range loader.ListSkills() { - if skill.Source != "workspace" { - continue - } - if filepath.Base(filepath.Dir(skill.Path)) != directory { - continue - } - skillCopy := skill - return &skillCopy - } - return nil -} - -func createStagedSkillInstall(skillsRoot, slug string) (string, string, error) { - stagedWorkspaceRoot, err := os.MkdirTemp(skillsRoot, "."+slug+"-install-*") - if err != nil { - return "", "", err - } - stagedTargetDir := filepath.Join(stagedWorkspaceRoot, "skills", slug) - return stagedWorkspaceRoot, stagedTargetDir, nil -} - -func commitStagedSkillInstall(stagedWorkspaceRoot, stagedTargetDir, targetDir string, replaceExisting bool) error { - if !replaceExisting { - return os.Rename(stagedTargetDir, targetDir) - } - - backupDir, err := reserveTempDirPath(filepath.Dir(targetDir), "."+filepath.Base(targetDir)+"-backup-*") - if err != nil { - return err - } - - if err := os.Rename(targetDir, backupDir); err != nil { - return fmt.Errorf("failed to move existing skill aside: %w", err) - } - - if err := os.Rename(stagedTargetDir, targetDir); err != nil { - if rollbackErr := os.Rename(backupDir, targetDir); rollbackErr != nil { - return fmt.Errorf("failed to activate replacement: %w (rollback failed: %v)", err, rollbackErr) - } - return fmt.Errorf("failed to activate replacement: %w", err) - } - - _ = os.RemoveAll(backupDir) - _ = os.RemoveAll(stagedWorkspaceRoot) - return nil -} - -func reserveTempDirPath(parent, pattern string) (string, error) { - tempDir, err := os.MkdirTemp(parent, pattern) - if err != nil { - return "", err - } - if err := os.Remove(tempDir); err != nil { - return "", err - } - return tempDir, nil -} - -func enrichSkillInfo(cfg *config.Config, skill skills.SkillInfo) (skillSupportItem, error) { - item := skillSupportItem{ - Name: skill.Name, - Path: skill.Path, - Source: skill.Source, - Description: skill.Description, - OriginKind: "builtin", - } - - switch skill.Source { - case "builtin": - item.OriginKind = "builtin" - case "global": - item.OriginKind = "builtin" - case "workspace": - meta, err := readInstalledSkillOriginMeta(skill.Path) - if err == nil && meta != nil { - switch meta.OriginKind { - case "manual": - item.OriginKind = "manual" - item.InstalledAt = meta.InstalledAt - case "third_party": - item.OriginKind = "third_party" - item.RegistryName = meta.Registry - item.RegistryURL = registrySkillURLFromMeta(cfg, meta) - item.InstalledVersion = meta.InstalledVersion - item.InstalledAt = meta.InstalledAt - default: - if meta.Registry != "" || meta.Slug != "" || meta.InstalledVersion != "" { - item.OriginKind = "third_party" - item.RegistryName = meta.Registry - item.RegistryURL = registrySkillURLFromMeta(cfg, meta) - item.InstalledVersion = meta.InstalledVersion - item.InstalledAt = meta.InstalledAt - } else { - item.OriginKind = "builtin" - item.InstalledAt = meta.InstalledAt - } - } - } else { - item.OriginKind = "builtin" - } - default: - item.OriginKind = "builtin" - } - - return item, nil -} - -func readInstalledSkillOriginMeta(skillPath string) (*installedSkillOriginMeta, error) { - metaPath := filepath.Join(filepath.Dir(skillPath), ".skill-origin.json") - data, err := os.ReadFile(metaPath) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, err - } - var meta installedSkillOriginMeta - if err := json.Unmarshal(data, &meta); err != nil { - return nil, err - } - return &meta, nil -} - -func writeSkillOriginMeta(targetDir string, meta installedSkillOriginMeta) error { - data, err := json.MarshalIndent(meta, "", " ") - if err != nil { - return err - } - return fileutil.WriteFileAtomic(filepath.Join(targetDir, ".skill-origin.json"), data, 0o600) -} - -func registrySkillURL(cfg *config.Config, registryName, slug, version string) string { - if cfg == nil || registryName == "" || slug == "" { - return "" - } - registry := skills.LookupRegistryFromToolsConfig(cfg.Tools.Skills, registryName) - if registry == nil { - return "" - } - return registry.SkillURL(slug, version) -} - -func registrySkillURLFromMeta(cfg *config.Config, meta *installedSkillOriginMeta) string { - if meta == nil || meta.Slug == "" { - return "" - } - if meta.RegistryURL != "" { - return meta.RegistryURL - } - if cfg == nil || meta.Registry == "" { - return "" - } - return registrySkillURL(cfg, meta.Registry, meta.Slug, meta.InstalledVersion) -} - -func normalizeImportedSkillName(filename string, content []byte) (string, error) { - return normalizeImportedSkillNameWithHint(filename, "", content) -} - -func normalizeImportedSkillNameWithHint(filename, directoryHint string, content []byte) (string, error) { - rawContent := strings.ReplaceAll(string(content), "\r\n", "\n") - rawContent = strings.ReplaceAll(rawContent, "\r", "\n") - metadata, _ := extractImportedSkillMetadata(rawContent) - - raw := strings.TrimSpace(metadata["name"]) - if raw == "" { - raw = strings.TrimSpace(directoryHint) - } - if raw == "" { - raw = strings.TrimSpace(strings.TrimSuffix(filepath.Base(filename), filepath.Ext(filename))) - } - raw = strings.ToLower(raw) - raw = strings.ReplaceAll(raw, "_", "-") - raw = strings.ReplaceAll(raw, " ", "-") - raw = skillNameSanitizer.ReplaceAllString(raw, "-") - raw = strings.Trim(raw, "-") - raw = strings.Join(strings.FieldsFunc(raw, func(r rune) bool { return r == '-' }), "-") - - if raw == "" { - return "", fmt.Errorf("skill name is required in frontmatter or filename") - } - if len(raw) > 64 { - return "", fmt.Errorf("skill name exceeds 64 characters") - } - matched, err := regexp.MatchString(`^[a-z0-9]+(-[a-z0-9]+)*$`, raw) - if err != nil || !matched { - return "", fmt.Errorf("skill name must be alphanumeric with hyphens") - } - return raw, nil -} - -func normalizeImportedSkillContent(content []byte, skillName string) []byte { - raw := strings.ReplaceAll(string(content), "\r\n", "\n") - raw = strings.ReplaceAll(raw, "\r", "\n") - - metadata, body := extractImportedSkillMetadata(raw) - description := strings.TrimSpace(metadata["description"]) - if description == "" { - description = inferImportedSkillDescription(body) - } - if description == "" { - description = "Imported skill" - } - if len(description) > 1024 { - description = strings.TrimSpace(description[:1024]) - } - - body = strings.TrimLeft(body, "\n") - var builder strings.Builder - builder.WriteString("---\n") - builder.WriteString("name: ") - builder.WriteString(skillName) - builder.WriteString("\n") - builder.WriteString("description: ") - builder.WriteString(description) - builder.WriteString("\n") - builder.WriteString("---\n\n") - builder.WriteString(body) - if !strings.HasSuffix(builder.String(), "\n") { - builder.WriteString("\n") - } - return []byte(builder.String()) -} - -func importUploadedSkill(cfg *config.Config, filename string, content []byte) (*skillSupportItem, int, error) { - if isImportedSkillArchive(filename, content) { - return importUploadedSkillArchive(cfg, filename, content) - } - return importUploadedMarkdownSkill(cfg, filename, content) -} - -func importUploadedMarkdownSkill(cfg *config.Config, filename string, content []byte) (*skillSupportItem, int, error) { - skillName, err := normalizeImportedSkillName(filename, content) - if err != nil { - return nil, http.StatusBadRequest, err - } - - normalizedContent := normalizeImportedSkillContent(content, skillName) - workspace := cfg.WorkspacePath() - skillDir := filepath.Join(workspace, "skills", skillName) - skillFile := filepath.Join(skillDir, "SKILL.md") - - if err := ensureWorkspaceSkillDoesNotExist(skillDir); err != nil { - return nil, statusCodeForImportedSkillWriteError(err), err - } - if err := os.MkdirAll(skillDir, 0o755); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to create skill directory: %v", err) - } - if err := fileutil.WriteFileAtomic(skillFile, normalizedContent, 0o644); err != nil { - _ = os.RemoveAll(skillDir) - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to save skill: %v", err) - } - - return finalizeImportedSkill(cfg, skillDir, skillName, false) -} - -func importUploadedSkillArchive(cfg *config.Config, filename string, content []byte) (*skillSupportItem, int, error) { - tmpDir, tempDirErr := os.MkdirTemp("", "picoclaw-skill-import-*") - if tempDirErr != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to create temp directory: %v", tempDirErr) - } - defer os.RemoveAll(tmpDir) - - archivePath := filepath.Join(tmpDir, "import.zip") - if writeErr := fileutil.WriteFileAtomic(archivePath, content, 0o600); writeErr != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to stage uploaded archive: %v", writeErr) - } - - extractDir := filepath.Join(tmpDir, "extract") - if extractErr := utils.ExtractZipFile(archivePath, extractDir); extractErr != nil { - return nil, http.StatusBadRequest, fmt.Errorf("invalid ZIP archive: %w", extractErr) - } - - skillRoot, err := findImportedSkillRoot(extractDir) - if err != nil { - return nil, http.StatusBadRequest, err - } - - skillFile := filepath.Join(skillRoot, "SKILL.md") - skillContent, err := os.ReadFile(skillFile) - if err != nil { - return nil, http.StatusBadRequest, fmt.Errorf("failed to read SKILL.md from archive: %w", err) - } - - directoryHint := "" - if filepath.Clean(skillRoot) != filepath.Clean(extractDir) { - directoryHint = filepath.Base(skillRoot) - } - skillName, err := normalizeImportedSkillNameWithHint(filename, directoryHint, skillContent) - if err != nil { - return nil, http.StatusBadRequest, err - } - - workspace := cfg.WorkspacePath() - skillDir := filepath.Join(workspace, "skills", skillName) - if err := ensureWorkspaceSkillDoesNotExist(skillDir); err != nil { - return nil, statusCodeForImportedSkillWriteError(err), err - } - if err := copyImportedSkillTree(skillRoot, skillDir); err != nil { - _ = os.RemoveAll(skillDir) - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to save skill: %v", err) - } - - normalizedContent := normalizeImportedSkillContent(skillContent, skillName) - if err := fileutil.WriteFileAtomic(filepath.Join(skillDir, "SKILL.md"), normalizedContent, 0o644); err != nil { - _ = os.RemoveAll(skillDir) - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to normalize skill: %v", err) - } - - return finalizeImportedSkill(cfg, skillDir, skillName, true) -} - -func isImportedSkillArchive(filename string, content []byte) bool { - if strings.EqualFold(filepath.Ext(filename), ".zip") { - return true - } - return len(content) >= 4 && bytes.HasPrefix(content, []byte("PK\x03\x04")) -} - -func ensureWorkspaceSkillDoesNotExist(skillDir string) error { - if _, err := os.Stat(skillDir); err == nil { - return errImportedSkillExists - } else if !os.IsNotExist(err) { - return fmt.Errorf("failed to inspect skill directory: %w", err) - } - return nil -} - -func statusCodeForImportedSkillWriteError(err error) int { - if err == nil { - return http.StatusOK - } - if errors.Is(err, errImportedSkillExists) { - return http.StatusConflict - } - return http.StatusInternalServerError -} - -func finalizeImportedSkill( - cfg *config.Config, - skillDir string, - skillName string, - requireValidatedSkill bool, -) (*skillSupportItem, int, error) { - if err := persistSkillOriginMeta(skillDir, installedSkillOriginMeta{ - Version: 1, - OriginKind: "manual", - InstalledAt: time.Now().UnixMilli(), - }); err != nil { - _ = os.RemoveAll(skillDir) - return nil, http.StatusInternalServerError, fmt.Errorf("Failed to persist skill metadata: %v", err) - } - - if importedSkill := findWorkspaceSkillByDirectory(cfg, skillName); importedSkill != nil { - return importedSkill, http.StatusOK, nil - } - - if requireValidatedSkill { - _ = os.RemoveAll(skillDir) - return nil, http.StatusBadRequest, fmt.Errorf("imported archive is not a valid skill") - } - - return &skillSupportItem{ - Name: skillName, - Path: filepath.Join(skillDir, "SKILL.md"), - Source: "workspace", - Description: "Imported skill", - OriginKind: "manual", - }, http.StatusOK, nil -} - -func findImportedSkillRoot(extractDir string) (string, error) { - skillFiles := make([]string, 0, 1) - err := filepath.WalkDir(extractDir, func(path string, d fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if d.IsDir() { - return nil - } - if d.Name() == "SKILL.md" { - skillFiles = append(skillFiles, path) - } - return nil - }) - if err != nil { - return "", fmt.Errorf("failed to inspect ZIP archive: %w", err) - } - - switch len(skillFiles) { - case 0: - return "", fmt.Errorf("ZIP archive must contain a SKILL.md file") - case 1: - return filepath.Dir(skillFiles[0]), nil - default: - return "", fmt.Errorf("ZIP archive must contain exactly one SKILL.md file") - } -} - -func copyImportedSkillTree(srcDir, destDir string) error { - return filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - - relPath, err := filepath.Rel(srcDir, path) - if err != nil { - return err - } - if relPath == "." { - return os.MkdirAll(destDir, 0o755) - } - - destPath := filepath.Join(destDir, relPath) - info, err := d.Info() - if err != nil { - return err - } - if d.IsDir() { - return os.MkdirAll(destPath, 0o755) - } - if !info.Mode().IsRegular() { - return fmt.Errorf("archive contains unsupported file %q", relPath) - } - return fileutil.CopyFile(path, destPath, info.Mode().Perm()) - }) -} - -func extractImportedSkillMetadata(raw string) (map[string]string, string) { - matches := importedSkillFrontmatter.FindStringSubmatch(raw) - if len(matches) != 2 { - return map[string]string{}, raw - } - meta := parseImportedSkillYAML(matches[1]) - body := importedSkillFrontmatter.ReplaceAllString(raw, "") - return meta, body -} - -func parseImportedSkillYAML(frontmatter string) map[string]string { - result := make(map[string]string) - for _, line := range strings.Split(frontmatter, "\n") { - line = strings.TrimSpace(line) - if line == "" || strings.HasPrefix(line, "#") { - continue - } - key, value, ok := strings.Cut(line, ":") - if !ok { - continue - } - result[strings.TrimSpace(key)] = strings.Trim(strings.TrimSpace(value), `"'`) - } - return result -} - -func inferImportedSkillDescription(body string) string { - for _, line := range strings.Split(body, "\n") { - line = strings.TrimSpace(line) - if line == "" { - continue - } - line = strings.TrimLeft(line, "#-*0123456789. ") - line = strings.TrimSpace(line) - if line != "" { - return line - } - } - return "" -} - -func loadSkillContent(path string) (string, error) { - content, err := os.ReadFile(path) - if err != nil { - return "", err - } - return skillFrontmatterStripper.ReplaceAllString(string(content), ""), nil -} - -func globalConfigDir() string { - return config.GetHome() -} - -func builtinSkillsDir() string { - if path := os.Getenv(config.EnvBuiltinSkills); path != "" { - return path - } - wd, err := os.Getwd() - if err != nil { - return "" - } - return filepath.Join(wd, "skills") -} diff --git a/web/backend/api/skills_test.go b/web/backend/api/skills_test.go deleted file mode 100644 index 977ec693..00000000 --- a/web/backend/api/skills_test.go +++ /dev/null @@ -1,1863 +0,0 @@ -package api - -import ( - "archive/zip" - "bytes" - "encoding/json" - "errors" - "io" - "mime/multipart" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strconv" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/sipeed/picoclaw/pkg/config" -) - -func setClawHubBaseURL(cfg *config.Config, baseURL string) { - registryCfg, _ := cfg.Tools.Skills.Registries.Get("clawhub") - registryCfg.BaseURL = baseURL - cfg.Tools.Skills.Registries.Set("clawhub", registryCfg) -} - -func setGithubBaseURL(cfg *config.Config, baseURL string) { - registryCfg, ok := cfg.Tools.Skills.Registries.Get("github") - if !ok { - return - } - registryCfg.BaseURL = baseURL - cfg.Tools.Skills.Registries.Set("github", registryCfg) -} - -func TestHandleListSkills(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - if err := os.MkdirAll(filepath.Join(workspace, "skills", "workspace-skill"), 0o755); err != nil { - t.Fatalf("MkdirAll(workspace skill) error = %v", err) - } - if err := os.WriteFile( - filepath.Join(workspace, "skills", "workspace-skill", "SKILL.md"), - []byte("---\nname: workspace-skill\ndescription: Workspace skill\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(workspace skill) error = %v", err) - } - - globalSkillDir := filepath.Join(globalConfigDir(), "skills", "global-skill") - if err := os.MkdirAll(globalSkillDir, 0o755); err != nil { - t.Fatalf("MkdirAll(global skill) error = %v", err) - } - if err := os.WriteFile( - filepath.Join(globalSkillDir, "SKILL.md"), - []byte("---\nname: global-skill\ndescription: Global skill\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(global skill) error = %v", err) - } - - builtinRoot := filepath.Join(t.TempDir(), "builtin-skills") - oldBuiltin := os.Getenv("PICOCLAW_BUILTIN_SKILLS") - if err := os.Setenv("PICOCLAW_BUILTIN_SKILLS", builtinRoot); err != nil { - t.Fatalf("Setenv(PICOCLAW_BUILTIN_SKILLS) error = %v", err) - } - defer func() { - if oldBuiltin == "" { - _ = os.Unsetenv("PICOCLAW_BUILTIN_SKILLS") - } else { - _ = os.Setenv("PICOCLAW_BUILTIN_SKILLS", oldBuiltin) - } - }() - - builtinSkillDir := filepath.Join(builtinRoot, "builtin-skill") - if err := os.MkdirAll(builtinSkillDir, 0o755); err != nil { - t.Fatalf("MkdirAll(builtin skill) error = %v", err) - } - if err := os.WriteFile( - filepath.Join(builtinSkillDir, "SKILL.md"), - []byte("---\nname: builtin-skill\ndescription: Builtin skill\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(builtin skill) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills", 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 resp skillSupportResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Skills) != 3 { - t.Fatalf("skills count = %d, want 3", len(resp.Skills)) - } - - gotSkills := make(map[string]string, len(resp.Skills)) - gotOriginKinds := make(map[string]string, len(resp.Skills)) - for _, skill := range resp.Skills { - gotSkills[skill.Name] = skill.Source - gotOriginKinds[skill.Name] = skill.OriginKind - } - if gotSkills["workspace-skill"] != "workspace" { - t.Fatalf("workspace-skill source = %q, want workspace", gotSkills["workspace-skill"]) - } - if gotSkills["global-skill"] != "global" { - t.Fatalf("global-skill source = %q, want global", gotSkills["global-skill"]) - } - if gotSkills["builtin-skill"] != "builtin" { - t.Fatalf("builtin-skill source = %q, want builtin", gotSkills["builtin-skill"]) - } - if gotOriginKinds["workspace-skill"] != "builtin" { - t.Fatalf("workspace-skill origin_kind = %q, want builtin", gotOriginKinds["workspace-skill"]) - } - if gotOriginKinds["global-skill"] != "builtin" { - t.Fatalf("global-skill origin_kind = %q, want builtin", gotOriginKinds["global-skill"]) - } - if gotOriginKinds["builtin-skill"] != "builtin" { - t.Fatalf("builtin-skill origin_kind = %q, want builtin", gotOriginKinds["builtin-skill"]) - } -} - -func TestHandleGetSkill(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - skillDir := filepath.Join(workspace, "skills", "viewer-skill") - if err := os.MkdirAll(skillDir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - if err := os.WriteFile( - filepath.Join(skillDir, "SKILL.md"), - []byte( - "---\nname: viewer-skill\ndescription: Viewable skill\n---\n# Viewer Skill\n\nThis is visible content.\n", - ), - 0o644, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/viewer-skill", 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 resp skillDetailResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Name != "viewer-skill" || resp.Source != "workspace" || resp.Description != "Viewable skill" { - t.Fatalf("unexpected response: %#v", resp) - } - if resp.OriginKind != "builtin" { - t.Fatalf("resp.OriginKind = %q, want builtin", resp.OriginKind) - } - if resp.Content != "# Viewer Skill\n\nThis is visible content.\n" { - t.Fatalf("content = %q", resp.Content) - } -} - -func TestHandleGetSkillUsesResolvedPath(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - skillDir := filepath.Join(workspace, "skills", "folder-name") - if err := os.MkdirAll(skillDir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - if err := os.WriteFile( - filepath.Join(skillDir, "SKILL.md"), - []byte("---\nname: display-name\ndescription: Mismatched path skill\n---\n# Display Name\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/display-name", 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 resp skillDetailResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Name != "display-name" { - t.Fatalf("resp.Name = %q, want display-name", resp.Name) - } - if resp.Content != "# Display Name\n" { - t.Fatalf("content = %q", resp.Content) - } -} - -func TestHandleImportSkill(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - var body bytes.Buffer - writer := multipart.NewWriter(&body) - part, err := writer.CreateFormFile("file", "Plain Skill.md") - if err != nil { - t.Fatalf("CreateFormFile() error = %v", err) - } - _, err = io.WriteString(part, "# Plain Skill\n\nUse this skill to test imports.\n") - if err != nil { - t.Fatalf("WriteString() error = %v", err) - } - err = writer.Close() - if err != nil { - t.Fatalf("Close() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - - skillFile := filepath.Join(workspace, "skills", "plain-skill", "SKILL.md") - content, err := os.ReadFile(skillFile) - if err != nil { - t.Fatalf("ReadFile() error = %v", err) - } - expected := "---\nname: plain-skill\ndescription: Plain Skill\n---\n\n# Plain Skill\n\nUse this skill to test imports.\n" - if string(content) != expected { - t.Fatalf("saved skill content mismatch:\n%s", string(content)) - } - metaContent, err := os.ReadFile(filepath.Join(workspace, "skills", "plain-skill", ".skill-origin.json")) - if err != nil { - t.Fatalf("ReadFile(origin metadata) error = %v", err) - } - var originMeta installedSkillOriginMeta - if err := json.Unmarshal(metaContent, &originMeta); err != nil { - t.Fatalf("Unmarshal(origin metadata) error = %v", err) - } - if originMeta.OriginKind != "manual" { - t.Fatalf("originMeta.OriginKind = %q, want manual", originMeta.OriginKind) - } - - rec2 := httptest.NewRecorder() - req2 := httptest.NewRequest(http.MethodGet, "/api/skills", nil) - mux.ServeHTTP(rec2, req2) - if rec2.Code != http.StatusOK { - t.Fatalf("list status = %d, want %d, body=%s", rec2.Code, http.StatusOK, rec2.Body.String()) - } - var listResp skillSupportResponse - if err := json.Unmarshal(rec2.Body.Bytes(), &listResp); err != nil { - t.Fatalf("Unmarshal list response error = %v", err) - } - found := false - for _, skill := range listResp.Skills { - if skill.Name == "plain-skill" && skill.Source == "workspace" && skill.Description == "Plain Skill" { - found = true - } - } - if !found { - t.Fatalf("plain-skill should be listed after import, got %#v", listResp.Skills) - } -} - -func TestHandleImportSkillZip(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - zipContent := buildSkillZip(t, map[string]string{ - "Wrapped Skill/SKILL.md": "---\nname: wrapped-skill\ndescription: Wrapped skill\n---\n# Wrapped Skill\n\nUse this skill from zip.\n", - "Wrapped Skill/docs/README.md": "# Extra file\n", - }) - - var body bytes.Buffer - writer := multipart.NewWriter(&body) - part, createErr := writer.CreateFormFile("file", "Wrapped Skill.zip") - if createErr != nil { - t.Fatalf("CreateFormFile() error = %v", createErr) - } - if _, writeErr := part.Write(zipContent); writeErr != nil { - t.Fatalf("Write(zipContent) error = %v", writeErr) - } - if closeErr := writer.Close(); closeErr != nil { - t.Fatalf("Close() error = %v", closeErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - - skillDir := filepath.Join(workspace, "skills", "wrapped-skill") - skillFile := filepath.Join(skillDir, "SKILL.md") - content, err := os.ReadFile(skillFile) - if err != nil { - t.Fatalf("ReadFile() error = %v", err) - } - expected := "---\nname: wrapped-skill\ndescription: Wrapped skill\n---\n\n# Wrapped Skill\n\nUse this skill from zip.\n" - if string(content) != expected { - t.Fatalf("saved skill content mismatch:\n%s", string(content)) - } - - extraFile := filepath.Join(skillDir, "docs", "README.md") - extraContent, err := os.ReadFile(extraFile) - if err != nil { - t.Fatalf("ReadFile(extra file) error = %v", err) - } - if string(extraContent) != "# Extra file\n" { - t.Fatalf("extra file content = %q", string(extraContent)) - } -} - -func TestHandleImportSkillZipRejectsArchiveWithoutSkill(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - zipContent := buildSkillZip(t, map[string]string{ - "README.md": "# Not a skill\n", - }) - - var body bytes.Buffer - writer := multipart.NewWriter(&body) - part, err := writer.CreateFormFile("file", "invalid.zip") - if err != nil { - t.Fatalf("CreateFormFile() error = %v", err) - } - if _, err := part.Write(zipContent); err != nil { - t.Fatalf("Write(zipContent) error = %v", err) - } - if err := writer.Close(); err != nil { - t.Fatalf("Close() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String()) - } - if _, err := os.Stat(filepath.Join(workspace, "skills", "invalid")); !os.IsNotExist(err) { - t.Fatalf("invalid archive should not leave behind a skill dir, stat err=%v", err) - } -} - -func TestHandleImportSkillRollsBackOnOriginMetadataWriteFailure(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - previousPersist := persistSkillOriginMeta - persistSkillOriginMeta = func(targetDir string, meta installedSkillOriginMeta) error { - return errors.New("forced metadata failure") - } - defer func() { - persistSkillOriginMeta = previousPersist - }() - - var body bytes.Buffer - writer := multipart.NewWriter(&body) - part, err := writer.CreateFormFile("file", "Rollback Skill.md") - if err != nil { - t.Fatalf("CreateFormFile() error = %v", err) - } - if _, err := io.WriteString(part, "# Rollback Skill\n"); err != nil { - t.Fatalf("WriteString() error = %v", err) - } - if err := writer.Close(); err != nil { - t.Fatalf("Close() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) - } - - skillDir := filepath.Join(workspace, "skills", "rollback-skill") - if _, err := os.Stat(skillDir); !os.IsNotExist(err) { - t.Fatalf("skill directory should be removed after metadata write failure, stat err=%v", err) - } -} - -func TestHandleDeleteSkill(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - skillDir := filepath.Join(workspace, "skills", "delete-me") - if err := os.MkdirAll(skillDir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - if err := os.WriteFile( - filepath.Join(skillDir, "SKILL.md"), - []byte("---\nname: delete-me\ndescription: delete me\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/skills/delete-me", 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()) - } - if _, err := os.Stat(skillDir); !os.IsNotExist(err) { - t.Fatalf("skill directory should be removed, stat err=%v", err) - } -} - -func TestHandleDeleteSkillPrefersWorkspaceMatch(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - homeDir := t.TempDir() - t.Setenv(config.EnvHome, homeDir) - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - workspaceSkillDir := filepath.Join(workspace, "skills", "delete-me-workspace") - if err := os.MkdirAll(workspaceSkillDir, 0o755); err != nil { - t.Fatalf("MkdirAll(workspace) error = %v", err) - } - if err := os.WriteFile( - filepath.Join(workspaceSkillDir, "SKILL.md"), - []byte("---\nname: delete-me\ndescription: workspace delete me\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(workspace) error = %v", err) - } - - globalSkillDir := filepath.Join(homeDir, "skills", "delete-me-global") - if err := os.MkdirAll(globalSkillDir, 0o755); err != nil { - t.Fatalf("MkdirAll(global) error = %v", err) - } - if err := os.WriteFile( - filepath.Join(globalSkillDir, "SKILL.md"), - []byte("---\nname: delete-me\ndescription: global delete me\n---\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(global) error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodDelete, "/api/skills/delete-me", 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()) - } - if _, err := os.Stat(workspaceSkillDir); !os.IsNotExist(err) { - t.Fatalf("workspace skill directory should be removed, stat err=%v", err) - } - if _, err := os.Stat(globalSkillDir); err != nil { - t.Fatalf("global skill directory should remain, stat err=%v", err) - } -} - -func TestHandleSearchSkills(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - if err := os.MkdirAll(filepath.Join(workspace, "skills", "github"), 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - if err := os.WriteFile( - filepath.Join(workspace, "skills", "github", "SKILL.md"), - []byte("---\nname: github\ndescription: Installed GitHub skill\n---\n# GitHub\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v1/search" { - http.NotFound(w, r) - return - } - if got := r.URL.Query().Get("q"); got != "github" { - t.Fatalf("query = %q, want github", got) - } - json.NewEncoder(w).Encode(map[string]any{ - "results": []map[string]any{ - { - "score": 0.95, - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub integration skill", - "version": "1.2.3", - }, - { - "score": 0.87, - "slug": "jira", - "displayName": "Jira", - "summary": "Issue tracker skill", - "version": "0.9.0", - }, - }, - }) - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=github&limit=5", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Limit != 5 { - t.Fatalf("limit = %d, want 5", resp.Limit) - } - if resp.Offset != 0 { - t.Fatalf("offset = %d, want 0", resp.Offset) - } - if resp.HasMore { - t.Fatalf("has_more = true, want false") - } - if len(resp.Results) != 2 { - t.Fatalf("results count = %d, want 2", len(resp.Results)) - } - if resp.Results[0].URL != server.URL+"/skills/github" { - t.Fatalf("first result URL = %q, want %q", resp.Results[0].URL, server.URL+"/skills/github") - } - if !resp.Results[0].Installed || resp.Results[0].InstalledName != "github" { - t.Fatalf("first result should be treated as occupying the workspace slug, got %#v", resp.Results[0]) - } - if resp.Results[1].Installed { - t.Fatalf("second result should not be installed, got %#v", resp.Results[1]) - } -} - -func TestHandleSearchSkillsUsesGitHubResultVersionInURL(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v3/search/code" { - http.NotFound(w, r) - return - } - json.NewEncoder(w).Encode(map[string]any{ - "items": []map[string]any{ - { - "path": "skills/pr-review/SKILL.md", - "score": 10, - "repository": map[string]any{ - "full_name": "foo/bar", - "name": "bar", - "description": "Review pull requests", - "default_branch": "master", - }, - }, - }, - }) - })) - defer server.Close() - - setGithubBaseURL(cfg, server.URL) - clawHubRegistry, _ := cfg.Tools.Skills.Registries.Get("clawhub") - clawHubRegistry.Enabled = false - cfg.Tools.Skills.Registries.Set("clawhub", clawHubRegistry) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=pr+review&limit=5", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Results) != 1 { - t.Fatalf("results count = %d, want 1", len(resp.Results)) - } - if resp.Results[0].URL != server.URL+"/foo/bar/tree/master/skills/pr-review" { - t.Fatalf("result URL = %q", resp.Results[0].URL) - } -} - -func TestHandleSearchSkillsGitHubRateLimitDegradesGracefully(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v3/search/code" { - http.NotFound(w, r) - return - } - w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"message":"API rate limit exceeded for 1.2.3.4"}`)) - })) - defer server.Close() - - setGithubBaseURL(cfg, server.URL) - clawHubRegistry, _ := cfg.Tools.Skills.Registries.Get("clawhub") - clawHubRegistry.Enabled = false - cfg.Tools.Skills.Registries.Set("clawhub", clawHubRegistry) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=pr+review&limit=5", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Results) != 0 { - t.Fatalf("results count = %d, want 0", len(resp.Results)) - } -} - -func TestHandleSearchSkillsPagination(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v1/search" { - http.NotFound(w, r) - return - } - if got := r.URL.Query().Get("limit"); got != "5" { - t.Fatalf("limit = %q, want 5", got) - } - json.NewEncoder(w).Encode(map[string]any{ - "results": []map[string]any{ - { - "score": 0.99, - "slug": "skill-1", - "displayName": "Skill 1", - "summary": "Summary 1", - "version": "1.0.0", - }, - { - "score": 0.98, - "slug": "skill-2", - "displayName": "Skill 2", - "summary": "Summary 2", - "version": "1.0.0", - }, - { - "score": 0.97, - "slug": "skill-3", - "displayName": "Skill 3", - "summary": "Summary 3", - "version": "1.0.0", - }, - { - "score": 0.96, - "slug": "skill-4", - "displayName": "Skill 4", - "summary": "Summary 4", - "version": "1.0.0", - }, - }, - }) - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=github&limit=2&offset=2", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Limit != 2 { - t.Fatalf("limit = %d, want 2", resp.Limit) - } - if resp.Offset != 2 { - t.Fatalf("offset = %d, want 2", resp.Offset) - } - if resp.HasMore { - t.Fatalf("has_more = true, want false") - } - if len(resp.Results) != 2 { - t.Fatalf("results count = %d, want 2", len(resp.Results)) - } - if resp.Results[0].Slug != "skill-3" || resp.Results[1].Slug != "skill-4" { - t.Fatalf("unexpected paged results: %#v", resp.Results) - } - if resp.NextOffset != 0 { - t.Fatalf("next_offset = %d, want 0", resp.NextOffset) - } -} - -func TestHandleSearchSkillsClampsRegistryFanout(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v1/search" { - http.NotFound(w, r) - return - } - if got := r.URL.Query().Get("limit"); got != strconv.Itoa(maxRegistrySearchFanout) { - t.Fatalf("limit = %q, want %d", got, maxRegistrySearchFanout) - } - json.NewEncoder(w).Encode(map[string]any{ - "results": []map[string]any{ - { - "score": 0.99, - "slug": "skill-1", - "displayName": "Skill 1", - "summary": "Summary 1", - "version": "1.0.0", - }, - }, - }) - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=github&limit=20&offset=100000", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Results) != 0 { - t.Fatalf("results count = %d, want 0", len(resp.Results)) - } -} - -func TestHandleInstallSkill(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - zipContent := buildSkillZip(t, map[string]string{ - "SKILL.md": "---\nname: github\ndescription: GitHub registry skill\n---\n# GitHub\n\nUse this skill.\n", - }) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/search": - json.NewEncoder(w).Encode(map[string]any{ - "results": []map[string]any{ - { - "score": 0.95, - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "version": "1.2.3", - }, - }, - }) - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - if got := r.URL.Query().Get("slug"); got != "github" { - t.Fatalf("slug = %q, want github", got) - } - if got := r.URL.Query().Get("version"); got != "1.2.3" { - t.Fatalf("version = %q, want 1.2.3", got) - } - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(zipContent) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - 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 resp installSkillResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Status != "ok" || resp.Version != "1.2.3" || resp.InstalledSkill == nil { - t.Fatalf("unexpected response: %#v", resp) - } - if resp.InstalledSkill.OriginKind != "third_party" { - t.Fatalf("resp.InstalledSkill.OriginKind = %q, want third_party", resp.InstalledSkill.OriginKind) - } - if resp.InstalledSkill.RegistryURL != server.URL+"/skills/github" { - t.Fatalf( - "resp.InstalledSkill.RegistryURL = %q, want %q", - resp.InstalledSkill.RegistryURL, - server.URL+"/skills/github", - ) - } - - skillFile := filepath.Join(workspace, "skills", "github", "SKILL.md") - if _, err := os.Stat(skillFile); err != nil { - t.Fatalf("installed skill file missing: %v", err) - } - if _, err := os.Stat(filepath.Join(workspace, "skills", "github", ".skill-origin.json")); err != nil { - t.Fatalf("origin metadata missing: %v", err) - } - - detailRec := httptest.NewRecorder() - detailReq := httptest.NewRequest(http.MethodGet, "/api/skills/github", nil) - mux.ServeHTTP(detailRec, detailReq) - - if detailRec.Code != http.StatusOK { - t.Fatalf("detail status = %d, want %d, body=%s", detailRec.Code, http.StatusOK, detailRec.Body.String()) - } - - var detailResp skillDetailResponse - if err := json.Unmarshal(detailRec.Body.Bytes(), &detailResp); err != nil { - t.Fatalf("Unmarshal(detail response) error = %v", err) - } - if detailResp.RegistryURL != server.URL+"/skills/github" { - t.Fatalf("detailResp.RegistryURL = %q, want %q", detailResp.RegistryURL, server.URL+"/skills/github") - } - - searchRec := httptest.NewRecorder() - searchReq := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=github&limit=5", nil) - mux.ServeHTTP(searchRec, searchReq) - - if searchRec.Code != http.StatusOK { - t.Fatalf("search status = %d, want %d, body=%s", searchRec.Code, http.StatusOK, searchRec.Body.String()) - } - - var searchResp skillSearchResponse - if err := json.Unmarshal(searchRec.Body.Bytes(), &searchResp); err != nil { - t.Fatalf("Unmarshal(search response) error = %v", err) - } - if len(searchResp.Results) != 1 { - t.Fatalf("search results count = %d, want 1", len(searchResp.Results)) - } - if !searchResp.Results[0].Installed || searchResp.Results[0].InstalledName != "github" { - t.Fatalf("search result should be treated as installed after registry install, got %#v", searchResp.Results[0]) - } -} - -func TestHandleInstallSkillForcePreservesExistingSkillOnFailure(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - skillDir := filepath.Join(workspace, "skills", "github") - if err := os.MkdirAll(skillDir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - oldContent := []byte("---\nname: github\ndescription: Existing skill\n---\n# Existing\n") - if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), oldContent, 0o644); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - http.Error(w, "upstream download failed", http.StatusBadGateway) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - Force: true, - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusBadGateway { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadGateway, rec.Body.String()) - } - - gotContent, err := os.ReadFile(filepath.Join(skillDir, "SKILL.md")) - if err != nil { - t.Fatalf("ReadFile() error = %v", err) - } - if !bytes.Equal(gotContent, oldContent) { - t.Fatalf("existing skill should remain unchanged, got:\n%s", string(gotContent)) - } -} - -func TestHandleInstallSkillDefaultsRegistryToGitHub(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v3/repos/foo/bar": - json.NewEncoder(w).Encode(map[string]any{"default_branch": "master"}) - case "/api/v3/repos/foo/bar/contents/.agents/skills/pr-review": - assert.Equal(t, "ref=master", r.URL.RawQuery) - json.NewEncoder(w).Encode([]map[string]any{ - { - "type": "file", - "name": "SKILL.md", - "download_url": server.URL + "/raw/foo/bar/master/.agents/skills/pr-review/SKILL.md", - }, - }) - case "/raw/foo/bar/master/.agents/skills/pr-review/SKILL.md": - _, _ = w.Write([]byte("---\nname: pr-review\ndescription: PR review skill\n---\n# PR Review\n")) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - githubRegistry, ok := cfg.Tools.Skills.Registries.Get("github") - if !ok { - t.Fatalf("github registry missing from default config") - } - githubRegistry.BaseURL = server.URL - cfg.Tools.Skills.Registries.Set("github", githubRegistry) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "foo/bar/.agents/skills/pr-review", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - 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 resp installSkillResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Registry != "github" { - t.Fatalf("resp.Registry = %q, want github", resp.Registry) - } -} - -func TestHandleInstallSkillTracksGitHubURLInstallsAsInstalled(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - var server *httptest.Server - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v3/repos/foo/bar": - json.NewEncoder(w).Encode(map[string]any{"default_branch": "master"}) - case "/api/v3/repos/foo/bar/contents/.agents/skills/pr-review": - assert.Equal(t, "ref=master", r.URL.RawQuery) - json.NewEncoder(w).Encode([]map[string]any{{ - "type": "file", - "name": "SKILL.md", - "download_url": server.URL + "/raw/foo/bar/master/.agents/skills/pr-review/SKILL.md", - }}) - case "/api/v3/search/code": - json.NewEncoder(w).Encode(map[string]any{ - "items": []map[string]any{{ - "path": ".agents/skills/pr-review/SKILL.md", - "score": 10, - "repository": map[string]any{ - "full_name": "foo/bar", - "name": "bar", - "description": "PR review skill", - "default_branch": "master", - }, - }}, - }) - case "/raw/foo/bar/master/.agents/skills/pr-review/SKILL.md": - _, _ = w.Write([]byte("---\nname: pr-review\ndescription: PR review skill\n---\n# PR Review\n")) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setGithubBaseURL(cfg, server.URL) - clawHubRegistry, _ := cfg.Tools.Skills.Registries.Get("clawhub") - clawHubRegistry.Enabled = false - cfg.Tools.Skills.Registries.Set("clawhub", clawHubRegistry) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - installBody, err := json.Marshal(installSkillRequest{ - Slug: server.URL + "/foo/bar/tree/master/.agents/skills/pr-review", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - installRec := httptest.NewRecorder() - installReq := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(installBody)) - installReq.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(installRec, installReq) - - if installRec.Code != http.StatusOK { - t.Fatalf("install status = %d, want %d, body=%s", installRec.Code, http.StatusOK, installRec.Body.String()) - } - - searchRec := httptest.NewRecorder() - searchReq := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=pr+review&limit=5", nil) - mux.ServeHTTP(searchRec, searchReq) - - if searchRec.Code != http.StatusOK { - t.Fatalf("search status = %d, want %d, body=%s", searchRec.Code, http.StatusOK, searchRec.Body.String()) - } - - var searchResp skillSearchResponse - if err := json.Unmarshal(searchRec.Body.Bytes(), &searchResp); err != nil { - t.Fatalf("Unmarshal(search response) error = %v", err) - } - if len(searchResp.Results) != 1 { - t.Fatalf("search results count = %d, want 1", len(searchResp.Results)) - } - if !searchResp.Results[0].Installed || searchResp.Results[0].InstalledName != "pr-review" { - t.Fatalf("search result should be treated as installed after URL install, got %#v", searchResp.Results[0]) - } -} - -func TestHandleSearchSkillsMarksDirectoryCollisionAsInstalled(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - skillDir := filepath.Join(workspace, "skills", "pr-review") - if err := os.MkdirAll(skillDir, 0o755); err != nil { - t.Fatalf("MkdirAll() error = %v", err) - } - if err := os.WriteFile( - filepath.Join(skillDir, "SKILL.md"), - []byte("---\nname: pr-review\ndescription: Workspace PR review skill\n---\n# PR Review\n"), - 0o644, - ); err != nil { - t.Fatalf("WriteFile(SKILL.md) error = %v", err) - } - if err := writeSkillOriginMeta(skillDir, installedSkillOriginMeta{ - Version: 1, - OriginKind: "third_party", - Registry: "github", - Slug: "foo/bar/.agents/skills/pr-review", - RegistryURL: "https://github.com/foo/bar/tree/master/.agents/skills/pr-review", - InstalledVersion: "master", - InstalledAt: time.Now().UnixMilli(), - }); err != nil { - t.Fatalf("writeSkillOriginMeta() error = %v", err) - } - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/search": - json.NewEncoder(w).Encode(map[string]any{ - "results": []map[string]any{{ - "slug": "pr-review", - "displayName": "PR Review", - "summary": "ClawHub PR review skill", - "version": "1.2.3", - }}, - }) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - githubRegistry, _ := cfg.Tools.Skills.Registries.Get("github") - githubRegistry.Enabled = false - cfg.Tools.Skills.Registries.Set("github", githubRegistry) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/skills/search?q=pr+review&limit=5", 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 resp skillSearchResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if len(resp.Results) != 1 { - t.Fatalf("results count = %d, want 1", len(resp.Results)) - } - if !resp.Results[0].Installed || resp.Results[0].InstalledName != "pr-review" { - t.Fatalf("search result should be treated as installed when directory is occupied, got %#v", resp.Results[0]) - } -} - -func TestHandleInstallSkillRollsBackOnOriginMetadataWriteFailure(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - zipContent := buildSkillZip(t, map[string]string{ - "SKILL.md": "---\nname: github\ndescription: GitHub registry skill\n---\n# GitHub\n", - }) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(zipContent) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - previousPersist := persistSkillOriginMeta - persistSkillOriginMeta = func(targetDir string, meta installedSkillOriginMeta) error { - return errors.New("forced metadata failure") - } - defer func() { - persistSkillOriginMeta = previousPersist - }() - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) - } - - skillDir := filepath.Join(workspace, "skills", "github") - if _, err := os.Stat(skillDir); !os.IsNotExist(err) { - t.Fatalf("skill directory should be removed after metadata write failure, stat err=%v", err) - } -} - -func TestHandleInstallSkillSerializesConcurrentRequests(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - zipContent := buildSkillZip(t, map[string]string{ - "SKILL.md": "---\nname: github\ndescription: GitHub registry skill\n---\n# GitHub\n", - }) - - downloadStarted := make(chan struct{}, 2) - releaseFirstDownload := make(chan struct{}) - downloadCount := 0 - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - downloadCount++ - downloadStarted <- struct{}{} - if downloadCount == 1 { - <-releaseFirstDownload - } - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(zipContent) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - type installResult struct { - code int - body string - } - results := make(chan installResult, 2) - startInstall := func() { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - results <- installResult{ - code: rec.Code, - body: rec.Body.String(), - } - } - - go startInstall() - - select { - case <-downloadStarted: - case <-time.After(time.Second): - t.Fatal("timed out waiting for first install download to start") - } - - go startInstall() - - select { - case <-downloadStarted: - t.Fatal("second install should not reach registry download before the first request completes") - case <-time.After(200 * time.Millisecond): - } - - close(releaseFirstDownload) - - firstResult := <-results - secondResult := <-results - - codes := map[int]int{ - firstResult.code: 1, - secondResult.code: 1, - } - if codes[http.StatusOK] != 1 || codes[http.StatusConflict] != 1 { - t.Fatalf( - "unexpected install results: first=(%d, %q) second=(%d, %q)", - firstResult.code, - firstResult.body, - secondResult.code, - secondResult.body, - ) - } -} - -func TestHandleImportSkillWaitsForConcurrentInstall(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - zipContent := buildSkillZip(t, map[string]string{ - "SKILL.md": "---\nname: github\ndescription: GitHub registry skill\n---\n# GitHub\n", - }) - - downloadStarted := make(chan struct{}, 1) - releaseDownload := make(chan struct{}) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - downloadStarted <- struct{}{} - <-releaseDownload - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(zipContent) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - installBody, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - type result struct { - code int - body string - } - installResults := make(chan result, 1) - importResults := make(chan result, 1) - - go func() { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(installBody)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - installResults <- result{code: rec.Code, body: rec.Body.String()} - }() - - select { - case <-downloadStarted: - case <-time.After(time.Second): - t.Fatal("timed out waiting for install download to start") - } - - var importBody bytes.Buffer - writer := multipart.NewWriter(&importBody) - part, err := writer.CreateFormFile("file", "github.md") - if err != nil { - t.Fatalf("CreateFormFile() error = %v", err) - } - if _, err := io.WriteString(part, "# GitHub\n"); err != nil { - t.Fatalf("WriteString() error = %v", err) - } - if err := writer.Close(); err != nil { - t.Fatalf("Close() error = %v", err) - } - - go func() { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &importBody) - req.Header.Set("Content-Type", writer.FormDataContentType()) - mux.ServeHTTP(rec, req) - importResults <- result{code: rec.Code, body: rec.Body.String()} - }() - - select { - case got := <-importResults: - t.Fatalf("import should wait for the install lock, got early response (%d, %q)", got.code, got.body) - case <-time.After(200 * time.Millisecond): - } - - close(releaseDownload) - - installResult := <-installResults - importResult := <-importResults - - if installResult.code != http.StatusOK { - t.Fatalf("install status = %d, want %d, body=%s", installResult.code, http.StatusOK, installResult.body) - } - if importResult.code != http.StatusConflict { - t.Fatalf("import status = %d, want %d, body=%s", importResult.code, http.StatusConflict, importResult.body) - } -} - -func TestHandleInstallSkillRejectsInvalidArchive(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, loadErr := config.LoadConfig(configPath) - if loadErr != nil { - t.Fatalf("LoadConfig() error = %v", loadErr) - } - workspace := filepath.Join(t.TempDir(), "workspace") - cfg.Agents.Defaults.Workspace = workspace - - zipContent := buildSkillZip(t, map[string]string{ - "README.md": "# Not a skill\n", - }) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/api/v1/skills/github": - json.NewEncoder(w).Encode(map[string]any{ - "slug": "github", - "displayName": "GitHub", - "summary": "GitHub registry skill", - "latestVersion": map[string]any{ - "version": "1.2.3", - }, - "moderation": map[string]any{ - "isMalwareBlocked": false, - "isSuspicious": false, - }, - }) - case "/api/v1/download": - w.Header().Set("Content-Type", "application/zip") - _, _ = w.Write(zipContent) - default: - http.NotFound(w, r) - } - })) - defer server.Close() - - setClawHubBaseURL(cfg, server.URL) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - body, err := json.Marshal(installSkillRequest{ - Slug: "github", - Registry: "clawhub", - }) - if err != nil { - t.Fatalf("Marshal() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/skills/install", bytes.NewReader(body)) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - - if rec.Code != http.StatusBadGateway { - t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadGateway, rec.Body.String()) - } - - skillDir := filepath.Join(workspace, "skills", "github") - if _, err := os.Stat(skillDir); !os.IsNotExist(err) { - t.Fatalf("invalid installed archive should be removed, stat err=%v", err) - } -} - -func buildSkillZip(t *testing.T, files map[string]string) []byte { - t.Helper() - - var buf bytes.Buffer - zipWriter := zip.NewWriter(&buf) - for name, content := range files { - writer, err := zipWriter.Create(name) - if err != nil { - t.Fatalf("Create(%q) error = %v", name, err) - } - if _, err := io.WriteString(writer, content); err != nil { - t.Fatalf("WriteString(%q) error = %v", name, err) - } - } - if err := zipWriter.Close(); err != nil { - t.Fatalf("Close() error = %v", err) - } - return buf.Bytes() -} diff --git a/web/backend/api/startup.go b/web/backend/api/startup.go deleted file mode 100644 index bc71e49d..00000000 --- a/web/backend/api/startup.go +++ /dev/null @@ -1,316 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" -) - -const ( - autoStartEntryName = "PicoClawLauncher" - launchAgentLabel = "io.picoclaw.launcher" -) - -type autoStartRequest struct { - Enabled bool `json:"enabled"` -} - -type autoStartResponse struct { - Enabled bool `json:"enabled"` - Supported bool `json:"supported"` - Platform string `json:"platform"` - Message string `json:"message,omitempty"` -} - -var errAutoStartUnsupported = errors.New("autostart is not supported on this platform") - -func (h *Handler) registerStartupRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/system/autostart", h.handleGetAutoStart) - mux.HandleFunc("PUT /api/system/autostart", h.handleSetAutoStart) -} - -func (h *Handler) handleGetAutoStart(w http.ResponseWriter, r *http.Request) { - enabled, supported, message, err := h.getAutoStartStatus() - if err != nil { - http.Error(w, fmt.Sprintf("Failed to read startup setting: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(autoStartResponse{ - Enabled: enabled, - Supported: supported, - Platform: runtime.GOOS, - Message: message, - }) -} - -func (h *Handler) handleSetAutoStart(w http.ResponseWriter, r *http.Request) { - var req autoStartRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - if err := h.setAutoStart(req.Enabled); err != nil { - if errors.Is(err, errAutoStartUnsupported) { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - http.Error(w, fmt.Sprintf("Failed to update startup setting: %v", err), http.StatusInternalServerError) - return - } - - enabled, supported, message, err := h.getAutoStartStatus() - if err != nil { - http.Error(w, fmt.Sprintf("Failed to verify startup setting: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(autoStartResponse{ - Enabled: enabled, - Supported: supported, - Platform: runtime.GOOS, - Message: message, - }) -} - -func (h *Handler) resolveLaunchCommand() (string, []string, error) { - exePath, err := os.Executable() - if err != nil { - return "", nil, err - } - - args := []string{"-no-browser"} - if h.debug { - args = append(args, "-d") - } - if h.configPath != "" { - args = append(args, h.configPath) - } - - return exePath, args, nil -} - -func (h *Handler) getAutoStartStatus() (enabled bool, supported bool, message string, err error) { - switch runtime.GOOS { - case "darwin": - exists, err := fileExists(macLaunchAgentPath()) - return exists, true, "Changes apply on next login.", err - case "linux": - exists, err := fileExists(linuxAutoStartPath()) - return exists, true, "Changes apply on next login.", err - case "windows": - exists, err := windowsRunKeyExists() - return exists, true, "Changes apply on next login.", err - default: - return false, false, "Current platform does not support launch at login.", nil - } -} - -func (h *Handler) setAutoStart(enabled bool) error { - exePath, args, err := h.resolveLaunchCommand() - if err != nil { - return err - } - - switch runtime.GOOS { - case "darwin": - return setDarwinAutoStart(enabled, exePath, args) - case "linux": - return setLinuxAutoStart(enabled, exePath, args) - case "windows": - return setWindowsAutoStart(enabled, exePath, args) - default: - return errAutoStartUnsupported - } -} - -func fileExists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -func macLaunchAgentPath() string { - home, _ := os.UserHomeDir() - return filepath.Join(home, "Library", "LaunchAgents", launchAgentLabel+".plist") -} - -func setDarwinAutoStart(enabled bool, exePath string, args []string) error { - plistPath := macLaunchAgentPath() - if enabled { - if err := os.MkdirAll(filepath.Dir(plistPath), 0o755); err != nil { - return err - } - content := buildDarwinPlist(exePath, args) - return os.WriteFile(plistPath, []byte(content), 0o644) - } - - if err := os.Remove(plistPath); err != nil && !os.IsNotExist(err) { - return err - } - return nil -} - -func xmlEscape(s string) string { - var b bytes.Buffer - for _, r := range s { - switch r { - case '&': - b.WriteString("&") - case '<': - b.WriteString("<") - case '>': - b.WriteString(">") - case '"': - b.WriteString(""") - case '\'': - b.WriteString("'") - default: - b.WriteRune(r) - } - } - return b.String() -} - -func buildDarwinPlist(exePath string, args []string) string { - programArgs := make([]string, 0, len(args)+1) - programArgs = append(programArgs, exePath) - programArgs = append(programArgs, args...) - - var b strings.Builder - b.WriteString(`` + "\n") - b.WriteString( - `` + "\n", - ) - b.WriteString(`` + "\n") - b.WriteString(`` + "\n") - b.WriteString(` Label` + "\n") - b.WriteString(` ` + launchAgentLabel + `` + "\n") - b.WriteString(` ProgramArguments` + "\n") - b.WriteString(` ` + "\n") - for _, arg := range programArgs { - b.WriteString(` ` + xmlEscape(arg) + `` + "\n") - } - b.WriteString(` ` + "\n") - b.WriteString(` RunAtLoad` + "\n") - b.WriteString(` ` + "\n") - b.WriteString(` ProcessType` + "\n") - b.WriteString(` Background` + "\n") - b.WriteString(`` + "\n") - b.WriteString(`` + "\n") - return b.String() -} - -func linuxAutoStartPath() string { - home, _ := os.UserHomeDir() - return filepath.Join(home, ".config", "autostart", "picoclaw-web.desktop") -} - -func shellQuote(s string) string { - if s == "" { - return "''" - } - if !strings.ContainsAny(s, " \t\n'\"\\$`") { - return s - } - return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" -} - -func buildLinuxExecLine(exePath string, args []string) string { - parts := make([]string, 0, len(args)+1) - parts = append(parts, shellQuote(exePath)) - for _, arg := range args { - parts = append(parts, shellQuote(arg)) - } - return strings.Join(parts, " ") -} - -func setLinuxAutoStart(enabled bool, exePath string, args []string) error { - desktopPath := linuxAutoStartPath() - if enabled { - if err := os.MkdirAll(filepath.Dir(desktopPath), 0o755); err != nil { - return err - } - content := strings.Join([]string{ - "[Desktop Entry]", - "Type=Application", - "Version=1.0", - "Name=PicoClaw Web", - "Comment=Start PicoClaw Web on login", - "Exec=" + buildLinuxExecLine(exePath, args), - "Terminal=false", - "X-GNOME-Autostart-enabled=true", - "NoDisplay=true", - "", - }, "\n") - return os.WriteFile(desktopPath, []byte(content), 0o644) - } - - if err := os.Remove(desktopPath); err != nil && !os.IsNotExist(err) { - return err - } - return nil -} - -func windowsCommandLine(exePath string, args []string) string { - parts := make([]string, 0, len(args)+1) - parts = append(parts, fmt.Sprintf("%q", exePath)) - for _, arg := range args { - parts = append(parts, fmt.Sprintf("%q", arg)) - } - return strings.Join(parts, " ") -} - -func windowsRunKeyExists() (bool, error) { - cmd := launcherExecCommand( - "reg", "query", - `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, - "/v", autoStartEntryName, - ) - if err := cmd.Run(); err != nil { - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { - return false, nil - } - return false, err - } - return true, nil -} - -func setWindowsAutoStart(enabled bool, exePath string, args []string) error { - key := `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` - if enabled { - commandLine := windowsCommandLine(exePath, args) - cmd := launcherExecCommand( - "reg", "add", key, - "/v", autoStartEntryName, - "/t", "REG_SZ", "/d", commandLine, "/f", - ) - return cmd.Run() - } - - cmd := launcherExecCommand("reg", "delete", key, "/v", autoStartEntryName, "/f") - if err := cmd.Run(); err != nil { - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { - return nil - } - return err - } - return nil -} diff --git a/web/backend/api/startup_test.go b/web/backend/api/startup_test.go deleted file mode 100644 index c224d36e..00000000 --- a/web/backend/api/startup_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package api - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/sipeed/picoclaw/web/backend/launcherconfig" -) - -func TestResolveLaunchCommandUsesConfigFileDefaults(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - - // Persist non-default launcher options to ensure resolveLaunchCommand does not - // pin them into autostart args. - launcherPath := launcherconfig.PathForAppConfig(configPath) - if err := launcherconfig.Save(launcherPath, launcherconfig.Config{ - Port: 19999, - Public: true, - }); err != nil { - t.Fatalf("launcherconfig.Save() error = %v", err) - } - - exePath, args, err := h.resolveLaunchCommand() - if err != nil { - t.Fatalf("resolveLaunchCommand() error = %v", err) - } - if exePath == "" { - t.Fatal("resolveLaunchCommand() returned empty executable path") - } - if len(args) != 2 { - t.Fatalf("args len = %d, want 2 (got %v)", len(args), args) - } - if args[0] != "-no-browser" { - t.Fatalf("args[0] = %q, want %q", args[0], "-no-browser") - } - if args[1] != configPath { - t.Fatalf("args[1] = %q, want %q", args[1], configPath) - } - for _, arg := range args { - if arg == "-port" || arg == "-public" { - t.Fatalf("autostart args should not pin network flags, got %v", args) - } - } -} - -func TestResolveLaunchCommandIncludesDebugFlagWhenEnabled(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - h := NewHandler(configPath) - h.SetDebug(true) - - _, args, err := h.resolveLaunchCommand() - if err != nil { - t.Fatalf("resolveLaunchCommand() error = %v", err) - } - if len(args) != 3 { - t.Fatalf("args len = %d, want 3 (got %v)", len(args), args) - } - if args[0] != "-no-browser" { - t.Fatalf("args[0] = %q, want %q", args[0], "-no-browser") - } - if args[1] != "-d" { - t.Fatalf("args[1] = %q, want %q", args[1], "-d") - } - if args[2] != configPath { - t.Fatalf("args[2] = %q, want %q", args[2], configPath) - } -} - -func TestBuildDarwinPlistIncludesRunAtLoad(t *testing.T) { - plist := buildDarwinPlist("/tmp/picoclaw-web", []string{"-no-browser", "/tmp/config.json"}) - if !strings.Contains(plist, "RunAtLoad") { - t.Fatalf("plist missing RunAtLoad key:\n%s", plist) - } - if !strings.Contains(plist, "") { - t.Fatalf("plist missing RunAtLoad true value:\n%s", plist) - } -} diff --git a/web/backend/api/tools.go b/web/backend/api/tools.go deleted file mode 100644 index f7519259..00000000 --- a/web/backend/api/tools.go +++ /dev/null @@ -1,726 +0,0 @@ -package api - -import ( - "encoding/json" - "fmt" - "net/http" - "runtime" - "strings" - - "github.com/sipeed/picoclaw/pkg/config" - picotools "github.com/sipeed/picoclaw/pkg/tools" -) - -type toolCatalogEntry struct { - Name string - Description string - Category string - ConfigKey string -} - -type toolSupportItem struct { - Name string `json:"name"` - Description string `json:"description"` - Category string `json:"category"` - ConfigKey string `json:"config_key"` - Status string `json:"status"` - ReasonCode string `json:"reason_code,omitempty"` -} - -type toolSupportResponse struct { - Tools []toolSupportItem `json:"tools"` -} - -type toolStateRequest struct { - Enabled bool `json:"enabled"` -} - -type webSearchProviderOption struct { - ID string `json:"id"` - Label string `json:"label"` - Configured bool `json:"configured"` - Current bool `json:"current"` - RequiresAuth bool `json:"requires_auth"` -} - -type webSearchProviderConfig struct { - Enabled bool `json:"enabled"` - MaxResults int `json:"max_results"` - BaseURL string `json:"base_url,omitempty"` - APIKey string `json:"api_key,omitempty"` - APIKeys []string `json:"api_keys,omitempty"` - Model string `json:"model,omitempty"` - APIKeySet bool `json:"api_key_set,omitempty"` -} - -type webSearchConfigResponse struct { - Provider string `json:"provider"` - CurrentService string `json:"current_service"` - PreferNative bool `json:"prefer_native"` - Proxy string `json:"proxy,omitempty"` - Providers []webSearchProviderOption `json:"providers"` - Settings map[string]webSearchProviderConfig `json:"settings"` -} - -type webSearchConfigRequest struct { - Provider string `json:"provider"` - PreferNative bool `json:"prefer_native"` - Proxy string `json:"proxy"` - Settings map[string]webSearchProviderConfig `json:"settings"` -} - -var toolCatalog = []toolCatalogEntry{ - { - Name: "read_file", - Description: "Read file content from the workspace or explicitly allowed paths.", - Category: "filesystem", - ConfigKey: "read_file", - }, - { - Name: "write_file", - Description: "Create or overwrite files within the writable workspace scope.", - Category: "filesystem", - ConfigKey: "write_file", - }, - { - Name: "list_dir", - Description: "Inspect directories and enumerate files available to the agent.", - Category: "filesystem", - ConfigKey: "list_dir", - }, - { - Name: "edit_file", - Description: "Apply targeted edits to existing files without rewriting everything.", - Category: "filesystem", - ConfigKey: "edit_file", - }, - { - Name: "append_file", - Description: "Append content to the end of an existing file.", - Category: "filesystem", - ConfigKey: "append_file", - }, - { - Name: "exec", - Description: "Run shell commands inside the configured workspace sandbox.", - Category: "filesystem", - ConfigKey: "exec", - }, - { - Name: "cron", - Description: "Schedule one-time or recurring reminders, jobs, and shell commands.", - Category: "automation", - ConfigKey: "cron", - }, - { - Name: "web_search", - Description: "Search the web using the configured providers.", - Category: "web", - ConfigKey: "web", - }, - { - Name: "web_fetch", - Description: "Fetch and summarize the contents of a webpage.", - Category: "web", - ConfigKey: "web_fetch", - }, - { - Name: "message", - Description: "Send a follow-up message back to the active user or chat.", - Category: "communication", - ConfigKey: "message", - }, - { - Name: "send_file", - Description: "Send an outbound file or media attachment to the active chat.", - Category: "communication", - ConfigKey: "send_file", - }, - { - Name: "find_skills", - Description: "Search external skill registries for installable skills.", - Category: "skills", - ConfigKey: "find_skills", - }, - { - Name: "install_skill", - Description: "Install a skill into the current workspace from a registry.", - Category: "skills", - ConfigKey: "install_skill", - }, - { - Name: "spawn", - Description: "Launch a background subagent for long-running or delegated work.", - Category: "agents", - ConfigKey: "spawn", - }, - { - Name: "spawn_status", - Description: "Query the status of spawned subagents.", - Category: "agents", - ConfigKey: "spawn_status", - }, - { - Name: "i2c", - Description: "Interact with I2C hardware devices exposed on the host.", - Category: "hardware", - ConfigKey: "i2c", - }, - { - Name: "spi", - Description: "Interact with SPI hardware devices exposed on the host.", - Category: "hardware", - ConfigKey: "spi", - }, - { - Name: "serial", - Description: "Interact with serial ports exposed on the host.", - Category: "hardware", - ConfigKey: "serial", - }, - { - Name: "tool_search_tool_regex", - Description: "Discover hidden MCP tools by regex search when tool discovery is enabled.", - Category: "discovery", - ConfigKey: "mcp.discovery.use_regex", - }, - { - Name: "tool_search_tool_bm25", - Description: "Discover hidden MCP tools by semantic ranking when tool discovery is enabled.", - Category: "discovery", - ConfigKey: "mcp.discovery.use_bm25", - }, -} - -func (h *Handler) registerToolRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/tools", h.handleListTools) - mux.HandleFunc("PUT /api/tools/{name}/state", h.handleUpdateToolState) - mux.HandleFunc("GET /api/tools/web-search-config", h.handleGetWebSearchConfig) - mux.HandleFunc("PUT /api/tools/web-search-config", h.handleUpdateWebSearchConfig) -} - -func (h *Handler) handleListTools(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") - json.NewEncoder(w).Encode(toolSupportResponse{ - Tools: buildToolSupport(cfg), - }) -} - -func (h *Handler) handleUpdateToolState(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 - } - - var req toolStateRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - if err := applyToolState(cfg, r.PathValue("name"), req.Enabled); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) -} - -func buildToolSupport(cfg *config.Config) []toolSupportItem { - items := make([]toolSupportItem, 0, len(toolCatalog)) - for _, entry := range toolCatalog { - status := "disabled" - reasonCode := "" - - switch entry.Name { - case "find_skills", "install_skill": - if cfg.Tools.IsToolEnabled(entry.ConfigKey) { - if cfg.Tools.IsToolEnabled("skills") { - status = "enabled" - } else { - status = "blocked" - reasonCode = "requires_skills" - } - } - case "spawn", "spawn_status": - if cfg.Tools.IsToolEnabled(entry.ConfigKey) { - if cfg.Tools.IsToolEnabled("subagent") { - status = "enabled" - } else { - status = "blocked" - reasonCode = "requires_subagent" - } - } - case "tool_search_tool_regex": - status, reasonCode = resolveDiscoveryToolSupport(cfg, cfg.Tools.MCP.Discovery.UseRegex) - case "tool_search_tool_bm25": - status, reasonCode = resolveDiscoveryToolSupport(cfg, cfg.Tools.MCP.Discovery.UseBM25) - case "web_search": - status, reasonCode = resolveWebSearchToolSupport(cfg) - case "i2c", "spi": - status, reasonCode = resolveHardwareToolSupport(cfg.Tools.IsToolEnabled(entry.ConfigKey)) - case "serial": - status, reasonCode = resolveSerialToolSupport(cfg.Tools.IsToolEnabled(entry.ConfigKey)) - default: - if cfg.Tools.IsToolEnabled(entry.ConfigKey) { - status = "enabled" - } - } - - items = append(items, toolSupportItem{ - Name: entry.Name, - Description: entry.Description, - Category: entry.Category, - ConfigKey: entry.ConfigKey, - Status: status, - ReasonCode: reasonCode, - }) - } - return items -} - -func resolveHardwareToolSupport(enabled bool) (string, string) { - if !enabled { - return "disabled", "" - } - if runtime.GOOS != "linux" { - return "blocked", "requires_linux" - } - return "enabled", "" -} - -func resolveSerialToolSupport(enabled bool) (string, string) { - if !enabled { - return "disabled", "" - } - switch runtime.GOOS { - case "linux", "darwin", "windows": - return "enabled", "" - default: - return "blocked", "requires_serial_platform" - } -} - -func resolveDiscoveryToolSupport(cfg *config.Config, methodEnabled bool) (string, string) { - if !cfg.Tools.IsToolEnabled("mcp") { - return "disabled", "" - } - if !cfg.Tools.MCP.Discovery.Enabled { - return "blocked", "requires_mcp_discovery" - } - if !methodEnabled { - return "disabled", "" - } - return "enabled", "" -} - -func resolveWebSearchToolSupport(cfg *config.Config) (string, string) { - if !cfg.Tools.IsToolEnabled("web") { - return "disabled", "" - } - return "enabled", "" -} - -func applyToolState(cfg *config.Config, toolName string, enabled bool) error { - switch toolName { - case "read_file": - cfg.Tools.ReadFile.Enabled = enabled - case "write_file": - cfg.Tools.WriteFile.Enabled = enabled - case "list_dir": - cfg.Tools.ListDir.Enabled = enabled - case "edit_file": - cfg.Tools.EditFile.Enabled = enabled - case "append_file": - cfg.Tools.AppendFile.Enabled = enabled - case "exec": - cfg.Tools.Exec.Enabled = enabled - case "cron": - cfg.Tools.Cron.Enabled = enabled - case "web_search": - cfg.Tools.Web.Enabled = enabled - case "web_fetch": - cfg.Tools.WebFetch.Enabled = enabled - case "message": - cfg.Tools.Message.Enabled = enabled - case "send_file": - cfg.Tools.SendFile.Enabled = enabled - case "find_skills": - cfg.Tools.FindSkills.Enabled = enabled - if enabled { - cfg.Tools.Skills.Enabled = true - } - case "install_skill": - cfg.Tools.InstallSkill.Enabled = enabled - if enabled { - cfg.Tools.Skills.Enabled = true - } - case "spawn": - cfg.Tools.Spawn.Enabled = enabled - if enabled { - cfg.Tools.Subagent.Enabled = true - } - case "spawn_status": - cfg.Tools.SpawnStatus.Enabled = enabled - if enabled { - cfg.Tools.Spawn.Enabled = true - cfg.Tools.Subagent.Enabled = true - } - case "i2c": - cfg.Tools.I2C.Enabled = enabled - case "spi": - cfg.Tools.SPI.Enabled = enabled - case "serial": - cfg.Tools.Serial.Enabled = enabled - case "tool_search_tool_regex": - cfg.Tools.MCP.Discovery.UseRegex = enabled - if enabled { - cfg.Tools.MCP.Enabled = true - cfg.Tools.MCP.Discovery.Enabled = true - } - case "tool_search_tool_bm25": - cfg.Tools.MCP.Discovery.UseBM25 = enabled - if enabled { - cfg.Tools.MCP.Enabled = true - cfg.Tools.MCP.Discovery.Enabled = true - } - default: - return fmt.Errorf("tool %q cannot be updated", toolName) - } - return nil -} - -func (h *Handler) handleGetWebSearchConfig(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(buildWebSearchConfigResponse(cfg)); err != nil { - http.Error(w, "Failed to encode response", http.StatusInternalServerError) - } -} - -func (h *Handler) handleUpdateWebSearchConfig(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 - } - - var req webSearchConfigRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest) - return - } - - provider := normalizeWebSearchProvider(req.Provider) - if provider == "" { - http.Error(w, "invalid web search provider", http.StatusBadRequest) - return - } - - cfg.Tools.Web.Provider = provider - cfg.Tools.Web.PreferNative = req.PreferNative - cfg.Tools.Web.Proxy = strings.TrimSpace(req.Proxy) - - if settings, ok := req.Settings["sogou"]; ok { - cfg.Tools.Web.Sogou.Enabled = settings.Enabled - cfg.Tools.Web.Sogou.MaxResults = settings.MaxResults - } - if settings, ok := req.Settings["duckduckgo"]; ok { - cfg.Tools.Web.DuckDuckGo.Enabled = settings.Enabled - cfg.Tools.Web.DuckDuckGo.MaxResults = settings.MaxResults - } - if settings, ok := req.Settings["gemini"]; ok { - cfg.Tools.Web.Gemini.Enabled = settings.Enabled - cfg.Tools.Web.Gemini.MaxResults = settings.MaxResults - cfg.Tools.Web.Gemini.Model = strings.TrimSpace(settings.Model) - if key := strings.TrimSpace(settings.APIKey); key != "" { - cfg.Tools.Web.Gemini.APIKey = *config.NewSecureString(key) - } - } - if settings, ok := req.Settings["brave"]; ok { - cfg.Tools.Web.Brave.Enabled = settings.Enabled - cfg.Tools.Web.Brave.MaxResults = settings.MaxResults - if keys, ok := normalizeWebSearchAPIKeys(settings.APIKeys, settings.APIKey); ok { - cfg.Tools.Web.Brave.SetAPIKeys(keys) - } - } - if settings, ok := req.Settings["tavily"]; ok { - cfg.Tools.Web.Tavily.Enabled = settings.Enabled - cfg.Tools.Web.Tavily.MaxResults = settings.MaxResults - cfg.Tools.Web.Tavily.BaseURL = strings.TrimSpace(settings.BaseURL) - if keys, ok := normalizeWebSearchAPIKeys(settings.APIKeys, settings.APIKey); ok { - cfg.Tools.Web.Tavily.SetAPIKeys(keys) - } - } - if settings, ok := req.Settings["kagi"]; ok { - cfg.Tools.Web.Kagi.Enabled = settings.Enabled - cfg.Tools.Web.Kagi.MaxResults = settings.MaxResults - cfg.Tools.Web.Kagi.BaseURL = strings.TrimSpace(settings.BaseURL) - if keys, ok := normalizeWebSearchAPIKeys(settings.APIKeys, settings.APIKey); ok { - cfg.Tools.Web.Kagi.SetAPIKeys(keys) - } - } - if settings, ok := req.Settings["perplexity"]; ok { - cfg.Tools.Web.Perplexity.Enabled = settings.Enabled - cfg.Tools.Web.Perplexity.MaxResults = settings.MaxResults - if keys, ok := normalizeWebSearchAPIKeys(settings.APIKeys, settings.APIKey); ok { - cfg.Tools.Web.Perplexity.APIKeys = config.SimpleSecureStrings(keys...) - } - } - if settings, ok := req.Settings["searxng"]; ok { - cfg.Tools.Web.SearXNG.Enabled = settings.Enabled - cfg.Tools.Web.SearXNG.MaxResults = settings.MaxResults - cfg.Tools.Web.SearXNG.BaseURL = strings.TrimSpace(settings.BaseURL) - } - if settings, ok := req.Settings["glm_search"]; ok { - cfg.Tools.Web.GLMSearch.Enabled = settings.Enabled - cfg.Tools.Web.GLMSearch.MaxResults = settings.MaxResults - cfg.Tools.Web.GLMSearch.BaseURL = strings.TrimSpace(settings.BaseURL) - if key := strings.TrimSpace(settings.APIKey); key != "" { - cfg.Tools.Web.GLMSearch.APIKey = *config.NewSecureString(key) - } - } - if settings, ok := req.Settings["baidu_search"]; ok { - cfg.Tools.Web.BaiduSearch.Enabled = settings.Enabled - cfg.Tools.Web.BaiduSearch.MaxResults = settings.MaxResults - cfg.Tools.Web.BaiduSearch.BaseURL = strings.TrimSpace(settings.BaseURL) - if key := strings.TrimSpace(settings.APIKey); key != "" { - cfg.Tools.Web.BaiduSearch.APIKey = *config.NewSecureString(key) - } - } - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(buildWebSearchConfigResponse(cfg)); err != nil { - http.Error(w, "Failed to encode response", http.StatusInternalServerError) - } -} - -func normalizeWebSearchProvider(provider string) string { - switch strings.ToLower(strings.TrimSpace(provider)) { - case "", "auto": - return "auto" - case "sogou", - "brave", - "tavily", - "kagi", - "duckduckgo", - "gemini", - "perplexity", - "searxng", - "glm_search", - "baidu_search": - return strings.ToLower(strings.TrimSpace(provider)) - default: - return "" - } -} - -func normalizeWebSearchAPIKeys(apiKeys []string, apiKey string) ([]string, bool) { - if apiKeys != nil { - keys := make([]string, 0, len(apiKeys)) - seen := make(map[string]struct{}, len(apiKeys)) - for _, key := range apiKeys { - trimmed := strings.TrimSpace(key) - if trimmed == "" { - continue - } - if _, ok := seen[trimmed]; ok { - continue - } - seen[trimmed] = struct{}{} - keys = append(keys, trimmed) - } - return keys, true - } - - if trimmed := strings.TrimSpace(apiKey); trimmed != "" { - return []string{trimmed}, true - } - - return nil, false -} - -func buildWebSearchConfigResponse(cfg *config.Config) webSearchConfigResponse { - opts := picotools.WebSearchToolOptionsFromConfig(cfg) - current := resolveCurrentWebSearchProvider(cfg) - settings := map[string]webSearchProviderConfig{ - "sogou": { - Enabled: cfg.Tools.Web.Sogou.Enabled, - MaxResults: cfg.Tools.Web.Sogou.MaxResults, - }, - "duckduckgo": { - Enabled: cfg.Tools.Web.DuckDuckGo.Enabled, - MaxResults: cfg.Tools.Web.DuckDuckGo.MaxResults, - }, - "gemini": { - Enabled: cfg.Tools.Web.Gemini.Enabled, - MaxResults: cfg.Tools.Web.Gemini.MaxResults, - Model: cfg.Tools.Web.Gemini.Model, - APIKeySet: cfg.Tools.Web.Gemini.APIKey.String() != "", - }, - "brave": { - Enabled: cfg.Tools.Web.Brave.Enabled, - MaxResults: cfg.Tools.Web.Brave.MaxResults, - APIKeySet: len(cfg.Tools.Web.Brave.APIKeys.Values()) > 0, - }, - "tavily": { - Enabled: cfg.Tools.Web.Tavily.Enabled, - MaxResults: cfg.Tools.Web.Tavily.MaxResults, - BaseURL: cfg.Tools.Web.Tavily.BaseURL, - APIKeySet: len(cfg.Tools.Web.Tavily.APIKeys.Values()) > 0, - }, - "kagi": { - Enabled: cfg.Tools.Web.Kagi.Enabled, - MaxResults: cfg.Tools.Web.Kagi.MaxResults, - BaseURL: cfg.Tools.Web.Kagi.BaseURL, - APIKeySet: len(cfg.Tools.Web.Kagi.APIKeys.Values()) > 0, - }, - "perplexity": { - Enabled: cfg.Tools.Web.Perplexity.Enabled, - MaxResults: cfg.Tools.Web.Perplexity.MaxResults, - APIKeySet: len(cfg.Tools.Web.Perplexity.APIKeys.Values()) > 0, - }, - "searxng": { - Enabled: cfg.Tools.Web.SearXNG.Enabled, - MaxResults: cfg.Tools.Web.SearXNG.MaxResults, - BaseURL: cfg.Tools.Web.SearXNG.BaseURL, - }, - "glm_search": { - Enabled: cfg.Tools.Web.GLMSearch.Enabled, - MaxResults: cfg.Tools.Web.GLMSearch.MaxResults, - BaseURL: cfg.Tools.Web.GLMSearch.BaseURL, - APIKeySet: cfg.Tools.Web.GLMSearch.APIKey.String() != "", - }, - "baidu_search": { - Enabled: cfg.Tools.Web.BaiduSearch.Enabled, - MaxResults: cfg.Tools.Web.BaiduSearch.MaxResults, - BaseURL: cfg.Tools.Web.BaiduSearch.BaseURL, - APIKeySet: cfg.Tools.Web.BaiduSearch.APIKey.String() != "", - }, - } - - providers := []webSearchProviderOption{ - { - ID: "auto", - Label: "Auto", - Configured: current != "", - Current: cfg.Tools.Web.Provider == "" || - cfg.Tools.Web.Provider == "auto", - }, - { - ID: "sogou", - Label: "Sogou", - Configured: picotools.WebSearchProviderReady(opts, "sogou"), - Current: current == "sogou", - }, - { - ID: "duckduckgo", - Label: "DuckDuckGo", - Configured: picotools.WebSearchProviderReady(opts, "duckduckgo"), - Current: current == "duckduckgo", - }, - { - ID: "gemini", - Label: "Gemini (Google Search)", - Configured: picotools.WebSearchProviderReady(opts, "gemini"), - Current: current == "gemini", - RequiresAuth: true, - }, - { - ID: "brave", - Label: "Brave Search", - Configured: picotools.WebSearchProviderReady(opts, "brave"), - Current: current == "brave", - RequiresAuth: true, - }, - { - ID: "tavily", - Label: "Tavily", - Configured: picotools.WebSearchProviderReady(opts, "tavily"), - Current: current == "tavily", - RequiresAuth: true, - }, - { - ID: "kagi", - Label: "Kagi Search", - Configured: picotools.WebSearchProviderReady(opts, "kagi"), - Current: current == "kagi", - RequiresAuth: true, - }, - { - ID: "perplexity", - Label: "Perplexity", - Configured: picotools.WebSearchProviderReady(opts, "perplexity"), - Current: current == "perplexity", - RequiresAuth: true, - }, - { - ID: "searxng", - Label: "SearXNG", - Configured: picotools.WebSearchProviderReady(opts, "searxng"), - Current: current == "searxng", - }, - { - ID: "glm_search", - Label: "GLM Search", - Configured: picotools.WebSearchProviderReady(opts, "glm_search"), - Current: current == "glm_search", - RequiresAuth: true, - }, - { - ID: "baidu_search", - Label: "Baidu Search", - Configured: picotools.WebSearchProviderReady(opts, "baidu_search"), - Current: current == "baidu_search", - RequiresAuth: true, - }, - } - - provider := cfg.Tools.Web.Provider - if provider == "" { - provider = "auto" - } - - return webSearchConfigResponse{ - Provider: provider, - CurrentService: current, - PreferNative: cfg.Tools.Web.PreferNative, - Proxy: cfg.Tools.Web.Proxy, - Providers: providers, - Settings: settings, - } -} - -func resolveCurrentWebSearchProvider(cfg *config.Config) string { - if cfg == nil || !cfg.Tools.IsToolEnabled("web") { - return "" - } - selected, err := picotools.ResolveWebSearchProviderName(picotools.WebSearchToolOptionsFromConfig(cfg), "") - if err != nil { - return "" - } - return selected -} diff --git a/web/backend/api/tools_test.go b/web/backend/api/tools_test.go deleted file mode 100644 index 520847be..00000000 --- a/web/backend/api/tools_test.go +++ /dev/null @@ -1,604 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "runtime" - "testing" - - "github.com/sipeed/picoclaw/pkg/config" -) - -func TestHandleListTools(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.ReadFile.Enabled = true - cfg.Tools.WriteFile.Enabled = false - cfg.Tools.Cron.Enabled = true - cfg.Tools.FindSkills.Enabled = true - cfg.Tools.Skills.Enabled = true - cfg.Tools.Spawn.Enabled = true - cfg.Tools.Subagent.Enabled = false - cfg.Tools.MCP.Enabled = true - cfg.Tools.MCP.Discovery.Enabled = true - cfg.Tools.MCP.Discovery.UseRegex = true - cfg.Tools.MCP.Discovery.UseBM25 = false - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/tools", 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 resp toolSupportResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - gotTools := make(map[string]toolSupportItem, len(resp.Tools)) - for _, tool := range resp.Tools { - gotTools[tool.Name] = tool - } - if gotTools["read_file"].Status != "enabled" { - t.Fatalf("read_file status = %q, want enabled", gotTools["read_file"].Status) - } - if gotTools["write_file"].Status != "disabled" { - t.Fatalf("write_file status = %q, want disabled", gotTools["write_file"].Status) - } - if gotTools["cron"].Status != "enabled" { - t.Fatalf("cron status = %q, want enabled", gotTools["cron"].Status) - } - if gotTools["spawn"].Status != "blocked" || gotTools["spawn"].ReasonCode != "requires_subagent" { - t.Fatalf("spawn = %#v, want blocked/requires_subagent", gotTools["spawn"]) - } - if gotTools["find_skills"].Status != "enabled" { - t.Fatalf("find_skills status = %q, want enabled", gotTools["find_skills"].Status) - } - if gotTools["tool_search_tool_regex"].Status != "enabled" { - t.Fatalf("tool_search_tool_regex status = %q, want enabled", gotTools["tool_search_tool_regex"].Status) - } - if gotTools["tool_search_tool_regex"].ConfigKey != "mcp.discovery.use_regex" { - t.Fatalf( - "tool_search_tool_regex config_key = %q, want mcp.discovery.use_regex", - gotTools["tool_search_tool_regex"].ConfigKey, - ) - } - if gotTools["tool_search_tool_bm25"].Status != "disabled" { - t.Fatalf("tool_search_tool_bm25 status = %q, want disabled", gotTools["tool_search_tool_bm25"].Status) - } - if gotTools["tool_search_tool_bm25"].ConfigKey != "mcp.discovery.use_bm25" { - t.Fatalf( - "tool_search_tool_bm25 config_key = %q, want mcp.discovery.use_bm25", - gotTools["tool_search_tool_bm25"].ConfigKey, - ) - } - if runtime.GOOS == "linux" { - if gotTools["i2c"].Status != "disabled" { - t.Fatalf("i2c status = %q, want disabled on linux when config is off", gotTools["i2c"].Status) - } - if gotTools["serial"].Status != "disabled" { - t.Fatalf("serial status = %q, want disabled when config is off", gotTools["serial"].Status) - } - - cfg.Tools.Serial.Enabled = true - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, "/api/tools", 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()) - } - - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - gotTools = make(map[string]toolSupportItem, len(resp.Tools)) - for _, tool := range resp.Tools { - gotTools[tool.Name] = tool - } - if gotTools["serial"].Status != "enabled" { - t.Fatalf("serial = %#v, want enabled on linux when config is on", gotTools["serial"]) - } - } else { - cfg.Tools.I2C.Enabled = true - cfg.Tools.SPI.Enabled = true - cfg.Tools.Serial.Enabled = true - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, "/api/tools", 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()) - } - - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - gotTools = make(map[string]toolSupportItem, len(resp.Tools)) - for _, tool := range resp.Tools { - gotTools[tool.Name] = tool - } - - if gotTools["i2c"].Status != "blocked" || gotTools["i2c"].ReasonCode != "requires_linux" { - t.Fatalf("i2c = %#v, want blocked/requires_linux", gotTools["i2c"]) - } - if gotTools["spi"].Status != "blocked" || gotTools["spi"].ReasonCode != "requires_linux" { - t.Fatalf("spi = %#v, want blocked/requires_linux", gotTools["spi"]) - } - switch runtime.GOOS { - case "darwin", "windows": - if gotTools["serial"].Status != "enabled" { - t.Fatalf("serial = %#v, want enabled on supported host", gotTools["serial"]) - } - default: - if gotTools["serial"].Status != "blocked" || gotTools["serial"].ReasonCode != "requires_serial_platform" { - t.Fatalf("serial = %#v, want blocked/requires_serial_platform", gotTools["serial"]) - } - } - } -} - -func TestHandleUpdateToolState(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Spawn.Enabled = false - cfg.Tools.Subagent.Enabled = false - cfg.Tools.Cron.Enabled = false - cfg.Tools.MCP.Enabled = false - cfg.Tools.MCP.Discovery.Enabled = false - cfg.Tools.MCP.Discovery.UseRegex = false - err = config.SaveConfig(configPath, cfg) - if err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - "/api/tools/spawn/state", - bytes.NewBufferString(`{"enabled":true}`), - ) - req.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("spawn status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String()) - } - - rec2 := httptest.NewRecorder() - req2 := httptest.NewRequest( - http.MethodPut, - "/api/tools/tool_search_tool_regex/state", - bytes.NewBufferString(`{"enabled":true}`), - ) - req2.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec2, req2) - if rec2.Code != http.StatusOK { - t.Fatalf("regex status = %d, want %d, body=%s", rec2.Code, http.StatusOK, rec2.Body.String()) - } - - rec3 := httptest.NewRecorder() - req3 := httptest.NewRequest( - http.MethodPut, - "/api/tools/cron/state", - bytes.NewBufferString(`{"enabled":true}`), - ) - req3.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec3, req3) - if rec3.Code != http.StatusOK { - t.Fatalf("cron status = %d, want %d, body=%s", rec3.Code, http.StatusOK, rec3.Body.String()) - } - - updated, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig(updated) error = %v", err) - } - if !updated.Tools.Spawn.Enabled || !updated.Tools.Subagent.Enabled { - t.Fatalf("spawn/subagent should both be enabled: %#v", updated.Tools) - } - if !updated.Tools.MCP.Enabled || !updated.Tools.MCP.Discovery.Enabled || !updated.Tools.MCP.Discovery.UseRegex { - t.Fatalf("mcp regex discovery should be enabled: %#v", updated.Tools.MCP) - } - if !updated.Tools.Cron.Enabled { - t.Fatalf("cron should be enabled: %#v", updated.Tools.Cron) - } - - rec4 := httptest.NewRecorder() - req4 := httptest.NewRequest( - http.MethodPut, - "/api/tools/serial/state", - bytes.NewBufferString(`{"enabled":true}`), - ) - req4.Header.Set("Content-Type", "application/json") - mux.ServeHTTP(rec4, req4) - if rec4.Code != http.StatusOK { - t.Fatalf("serial status = %d, want %d, body=%s", rec4.Code, http.StatusOK, rec4.Body.String()) - } - - updated, err = config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig(updated serial) error = %v", err) - } - if !updated.Tools.Serial.Enabled { - t.Fatalf("serial should be enabled: %#v", updated.Tools.Serial) - } -} - -func TestHandleListTools_ReportsWebSearchEnabledWhenToolIsOn(t *testing.T) { - tests := []struct { - name string - preferNative bool - }{ - {name: "without prefer_native", preferNative: false}, - {name: "with prefer_native", preferNative: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Web.PreferNative = tt.preferNative - cfg.Tools.Web.Provider = "brave" - cfg.Tools.Web.Sogou.Enabled = false - cfg.Tools.Web.DuckDuckGo.Enabled = false - cfg.Tools.Web.Brave.Enabled = true - cfg.Tools.Web.Brave.SetAPIKeys(nil) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/tools", 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 resp toolSupportResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - - for _, tool := range resp.Tools { - if tool.Name != "web_search" { - continue - } - if tool.Status != "enabled" || tool.ReasonCode != "" { - t.Fatalf("web_search = %#v, want enabled with no reason code", tool) - } - return - } - - t.Fatal("expected web_search in response") - }) - } -} - -func TestHandleGetWebSearchConfig(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Web.PreferNative = false - cfg.Tools.Web.Provider = "sogou" - cfg.Tools.Web.Sogou.Enabled = true - cfg.Tools.Web.Sogou.MaxResults = 6 - cfg.Tools.Web.Brave.Enabled = true - cfg.Tools.Web.Brave.SetAPIKey("brave-test-key") - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/tools/web-search-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 resp webSearchConfigResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if resp.Provider != "sogou" { - t.Fatalf("provider = %q, want sogou", resp.Provider) - } - if resp.CurrentService != "sogou" { - t.Fatalf("current_service = %q, want sogou", resp.CurrentService) - } - if !resp.Settings["brave"].APIKeySet { - t.Fatalf("brave api_key_set should be true: %#v", resp.Settings["brave"]) - } -} - -func TestHandleGetWebSearchConfig_DoesNotExposeNativeAsCurrentService(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Web.PreferNative = true - cfg.Tools.Web.Provider = "brave" - cfg.Tools.Web.Sogou.Enabled = false - cfg.Tools.Web.DuckDuckGo.Enabled = false - cfg.Tools.Web.Brave.Enabled = true - cfg.Tools.Web.Brave.SetAPIKeys(nil) - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/tools/web-search-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 resp webSearchConfigResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal() error = %v", err) - } - if !resp.PreferNative { - t.Fatal("prefer_native should remain true in response") - } - if resp.CurrentService != "" { - t.Fatalf("current_service = %q, want empty when no external provider is ready", resp.CurrentService) - } -} - -func TestHandleUpdateWebSearchConfig(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Web.Brave.SetAPIKeys([]string{"brave-old-1", "brave-old-2"}) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - "/api/tools/web-search-config", - bytes.NewBufferString(`{ - "provider":"brave", - "prefer_native":false, - "proxy":"http://127.0.0.1:7890", - "settings":{ - "sogou":{"enabled":true,"max_results":4}, - "brave":{"enabled":true,"max_results":7,"api_key":"brave-new-key"}, - "duckduckgo":{"enabled":false,"max_results":3} - } - }`), - ) - 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 updated.Tools.Web.Provider != "brave" { - t.Fatalf("provider = %q, want brave", updated.Tools.Web.Provider) - } - if updated.Tools.Web.PreferNative { - t.Fatal("prefer_native should be false after update") - } - if updated.Tools.Web.Proxy != "http://127.0.0.1:7890" { - t.Fatalf("proxy = %q", updated.Tools.Web.Proxy) - } - if !updated.Tools.Web.Sogou.Enabled || updated.Tools.Web.Sogou.MaxResults != 4 { - t.Fatalf("sogou config not updated: %#v", updated.Tools.Web.Sogou) - } - if !updated.Tools.Web.Brave.Enabled || updated.Tools.Web.Brave.MaxResults != 7 { - t.Fatalf("brave config not updated: %#v", updated.Tools.Web.Brave) - } - if updated.Tools.Web.Brave.APIKey() != "brave-new-key" { - t.Fatalf("brave api key not updated") - } -} - -func TestHandleUpdateWebSearchConfig_PreservesAndReplacesMultiKeys(t *testing.T) { - configPath, cleanup := setupOAuthTestEnv(t) - defer cleanup() - - cfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - cfg.Tools.Web.Brave.SetAPIKeys([]string{"brave-old-1", "brave-old-2"}) - if saveErr := config.SaveConfig(configPath, cfg); saveErr != nil { - t.Fatalf("SaveConfig() error = %v", saveErr) - } - - h := NewHandler(configPath) - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest( - http.MethodPut, - "/api/tools/web-search-config", - bytes.NewBufferString(`{ - "provider":"auto", - "prefer_native":true, - "proxy":"", - "settings":{ - "brave":{"enabled":true,"max_results":7} - } - }`), - ) - 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.Tools.Web.Brave.APIKeys.Values(); len(got) != 2 || - got[0] != "brave-old-1" || got[1] != "brave-old-2" { - t.Fatalf("brave api keys should be preserved, got %#v", got) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest( - http.MethodPut, - "/api/tools/web-search-config", - bytes.NewBufferString(`{ - "provider":"auto", - "prefer_native":true, - "proxy":"", - "settings":{ - "brave":{"enabled":true,"max_results":7,"api_keys":["brave-new-1","brave-new-2","brave-new-1"]} - } - }`), - ) - 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.Tools.Web.Brave.APIKeys.Values(); len(got) != 2 || - got[0] != "brave-new-1" || got[1] != "brave-new-2" { - t.Fatalf("brave api keys should be replaced by api_keys, got %#v", got) - } -} - -func TestResolveCurrentWebSearchProvider_PrefersConfiguredProvidersInAutoMode(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Tools.Web.Provider = "auto" - cfg.Tools.Web.Sogou.Enabled = true - cfg.Tools.Web.Brave.Enabled = true - cfg.Tools.Web.Brave.SetAPIKey("brave-test-key") - - if got := resolveCurrentWebSearchProvider(cfg); got != "brave" { - t.Fatalf("resolveCurrentWebSearchProvider() = %q, want brave", got) - } -} - -func TestResolveCurrentWebSearchProvider_FallsBackWhenExplicitProviderUnavailable(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Tools.Web.Provider = "brave" - cfg.Tools.Web.Brave.Enabled = true - cfg.Tools.Web.Sogou.Enabled = true - - if got := resolveCurrentWebSearchProvider(cfg); got != "sogou" { - t.Fatalf("resolveCurrentWebSearchProvider() = %q, want sogou", got) - } -} - -func TestResolveCurrentWebSearchProvider_FallsBackWhenProviderIsUnknown(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Tools.Web.Provider = "totally_unknown" - cfg.Tools.Web.Sogou.Enabled = true - - if got := resolveCurrentWebSearchProvider(cfg); got != "sogou" { - t.Fatalf("resolveCurrentWebSearchProvider() = %q, want sogou", got) - } -} - -func TestResolveCurrentWebSearchProvider_PrefersStableDefaultForSogouAndDuckDuckGo(t *testing.T) { - cfg := config.DefaultConfig() - cfg.Tools.Web.Provider = "auto" - cfg.Tools.Web.Sogou.Enabled = true - cfg.Tools.Web.DuckDuckGo.Enabled = true - - if got := resolveCurrentWebSearchProvider(cfg); got != "sogou" { - t.Fatalf("resolveCurrentWebSearchProvider() = %q, want sogou", got) - } -} - -func TestResolveCurrentWebSearchProvider_IgnoresPreferNativeInConfigView(t *testing.T) { - 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" - cfg.Tools.Web.PreferNative = true - cfg.Tools.Web.Provider = "brave" - cfg.Tools.Web.Sogou.Enabled = false - cfg.Tools.Web.DuckDuckGo.Enabled = false - cfg.Tools.Web.Brave.Enabled = true - - if got := resolveCurrentWebSearchProvider(cfg); got != "" { - t.Fatalf("resolveCurrentWebSearchProvider() = %q, want empty when only native search would be available", got) - } -} diff --git a/web/backend/api/update.go b/web/backend/api/update.go deleted file mode 100644 index 2ba86263..00000000 --- a/web/backend/api/update.go +++ /dev/null @@ -1,52 +0,0 @@ -package api - -import ( - "encoding/json" - "net/http" - - "github.com/sipeed/picoclaw/pkg/updater" -) - -// registerUpdateRoutes registers the self-update endpoint. -func (h *Handler) registerUpdateRoutes(mux *http.ServeMux) { - mux.HandleFunc("/api/update", h.handleUpdate) -} - -type updateRequest struct { - URL string `json:"url,omitempty"` - Binary string `json:"binary,omitempty"` -} - -type updateResponse struct { - Status string `json:"status"` - Message string `json:"message,omitempty"` -} - -func (h *Handler) handleUpdate(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - w.WriteHeader(http.StatusMethodNotAllowed) - _ = json.NewEncoder(w).Encode(updateResponse{Status: "error", Message: "method not allowed"}) - return - } - - dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)) - var req updateRequest - if err := dec.Decode(&req); err != nil { - w.WriteHeader(http.StatusBadRequest) - _ = json.NewEncoder(w).Encode(updateResponse{Status: "error", Message: "invalid request body"}) - return - } - - binary := req.Binary - if binary == "" { - binary = "picoclaw-launcher" - } - - if err := updater.UpdateSelfFromRelease(req.URL, "", "", binary); err != nil { - w.WriteHeader(http.StatusInternalServerError) - _ = json.NewEncoder(w).Encode(updateResponse{Status: "error", Message: err.Error()}) - return - } - - _ = json.NewEncoder(w).Encode(updateResponse{Status: "ok", Message: "update applied; restart to use new version"}) -} diff --git a/web/backend/api/version.go b/web/backend/api/version.go deleted file mode 100644 index 1994e420..00000000 --- a/web/backend/api/version.go +++ /dev/null @@ -1,347 +0,0 @@ -package api - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "net/http" - "os/exec" - "regexp" - "runtime" - "strings" - "sync" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -type systemVersionResponse struct { - Version string `json:"version"` - GitCommit string `json:"git_commit,omitempty"` - BuildTime string `json:"build_time,omitempty"` - GoVersion string `json:"go_version"` -} - -type cachedSystemVersion struct { - value systemVersionResponse - gatewayPID int -} - -type systemVersionCache struct { - mu sync.Mutex - current cachedSystemVersion - hasCurrent bool - inflightCh chan struct{} -} - -func newSystemVersionCache() *systemVersionCache { - return &systemVersionCache{} -} - -var ( - // 15 seconds matches the gateway startup window used elsewhere in launcher flow, - // giving slow/embedded hosts enough time for first command invocation while - // staying independent from cross-file init ordering. - versionCmdTimeout = 15 * time.Second - maxVersionResolveAttempts = 3 - findPicoclawBinaryForInfo = resolveGatewayBinaryForVersionInfo - runPicoclawVersionOutput = executePicoclawVersion - currentGatewayVersionState = gatewayVersionState - launcherBuildInfoForVersion = fallbackSystemVersionInfoFromConfig - versionInfoCache = newSystemVersionCache() - ansiEscapePattern = regexp.MustCompile(`\x1b\[[0-9;]*m`) - versionLinePattern = regexp.MustCompile( - `^(?:[^A-Za-z0-9]*\s*)?picoclaw(?:\.exe)?\s+([^\s(]+)` + - `(?:\s+\(git:\s*([^)]+)\))?\s*$`, - ) -) - -func (h *Handler) registerVersionRoutes(mux *http.ServeMux) { - mux.HandleFunc("GET /api/system/version", h.handleGetVersion) -} - -// handleGetVersion returns runtime version information for web clients. -func (h *Handler) handleGetVersion(w http.ResponseWriter, r *http.Request) { - versionInfo := h.resolveSystemVersionInfo(r.Context()) - - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(versionInfo); err != nil { - http.Error(w, "Failed to encode response", http.StatusInternalServerError) - return - } -} - -// resolveSystemVersionInfo prefers the actual picoclaw binary version output, -// and falls back to launcher build metadata when command execution fails. -func (h *Handler) resolveSystemVersionInfo(ctx context.Context) systemVersionResponse { - for range maxVersionResolveAttempts { - gatewayPID, gatewayAlive := currentGatewayVersionState() - if cached, ok := versionInfoCache.get(gatewayPID, gatewayAlive); ok { - return cached - } - - leader, ok := versionInfoCache.waitOrStart(ctx) - if !ok { - return fallbackSystemVersionInfo() - } - if !leader { - continue - } - - resolved := h.resolveSystemVersionInfoUncached(ctx) - gatewayPID, gatewayAlive = currentGatewayVersionState() - versionInfoCache.finishResolve(resolved, gatewayPID, gatewayAlive) - return resolved - } - - return fallbackSystemVersionInfo() -} - -func (h *Handler) resolveSystemVersionInfoUncached(ctx context.Context) systemVersionResponse { - if ctx == nil { - ctx = context.Background() - } - - fallback := fallbackSystemVersionInfo() - - execPath := strings.TrimSpace(findPicoclawBinaryForInfo()) - if execPath == "" { - return fallback - } - - cmdCtx, cancel := context.WithTimeout(ctx, versionCmdTimeout) - defer cancel() - - output, err := runPicoclawVersionOutput(cmdCtx, execPath) - if err != nil { - return fallback - } - - parsed, ok := parsePicoclawVersionOutput(output) - if !ok { - return fallback - } - - if parsed.GoVersion == "" { - parsed.GoVersion = fallback.GoVersion - if parsed.GoVersion == "" { - parsed.GoVersion = runtime.Version() - } - } - - return parsed -} - -func fallbackSystemVersionInfo() systemVersionResponse { - return launcherBuildInfoForVersion() -} - -func fallbackSystemVersionInfoFromConfig() systemVersionResponse { - buildTime, goVer := config.FormatBuildInfo() - return systemVersionResponse{ - Version: config.GetVersion(), - GitCommit: config.GitCommit, - BuildTime: buildTime, - GoVersion: goVer, - } -} - -// resolveGatewayBinaryForVersionInfo uses the same executable as the launcher -// gateway start path when available, then falls back to launcher binary lookup. -// This keeps version probing aligned with the actual gateway startup behavior, -// so web and gateway do not drift onto different binaries. -func resolveGatewayBinaryForVersionInfo() string { - gateway.mu.Lock() - cmd := gateway.cmd - gateway.mu.Unlock() - - if cmd != nil { - if execPath := strings.TrimSpace(cmd.Path); execPath != "" { - return execPath - } - } - - return utils.FindPicoclawBinary() -} - -func gatewayVersionState() (int, bool) { - gateway.mu.Lock() - defer gateway.mu.Unlock() - - if gateway.cmd == nil || gateway.cmd.Process == nil { - return 0, false - } - pid := gateway.cmd.Process.Pid - if pid <= 0 { - return 0, false - } - - return pid, isCmdProcessAliveLocked(gateway.cmd) -} - -func (c *systemVersionCache) get(gatewayPID int, gatewayAlive bool) (systemVersionResponse, bool) { - c.mu.Lock() - defer c.mu.Unlock() - - if c.hasCurrent && (!gatewayAlive || gatewayPID <= 0 || gatewayPID != c.current.gatewayPID) { - c.clearCurrentLocked() - } - - if c.hasCurrent { - return c.current.value, true - } - - return systemVersionResponse{}, false -} - -func (c *systemVersionCache) waitOrStart(ctx context.Context) (bool, bool) { - if ctx == nil { - ctx = context.Background() - } - if ctx.Err() != nil { - return false, false - } - - c.mu.Lock() - if c.inflightCh == nil { - c.inflightCh = make(chan struct{}) - c.mu.Unlock() - return true, true - } - waitCh := c.inflightCh - c.mu.Unlock() - - select { - case <-waitCh: - return false, true - case <-ctx.Done(): - return false, false - } -} - -func (c *systemVersionCache) finishResolve(value systemVersionResponse, gatewayPID int, gatewayAlive bool) { - c.mu.Lock() - if gatewayAlive && gatewayPID > 0 { - c.current = cachedSystemVersion{value: value, gatewayPID: gatewayPID} - c.hasCurrent = true - } else { - c.clearCurrentLocked() - } - - inflightCh := c.inflightCh - c.inflightCh = nil - c.mu.Unlock() - - if inflightCh != nil { - close(inflightCh) - } -} - -func (c *systemVersionCache) clearCurrentLocked() { - c.hasCurrent = false - c.current = cachedSystemVersion{} -} - -func (c *systemVersionCache) resetForTest() { - c.mu.Lock() - defer c.mu.Unlock() - - c.current = cachedSystemVersion{} - c.hasCurrent = false - if c.inflightCh != nil { - close(c.inflightCh) - c.inflightCh = nil - } -} - -// executePicoclawVersion runs the version subcommand against the -// discovered picoclaw executable. -func executePicoclawVersion(ctx context.Context, execPath string) (string, error) { - cmd := exec.CommandContext(ctx, execPath, "version") - applyLauncherProcAttrs(cmd) - out, err := cmd.CombinedOutput() - if err == nil { - return string(out), nil - } - - return string(out), fmt.Errorf("failed to execute version command: %w", err) -} - -// parsePicoclawVersionOutput extracts version/build/go fields from CLI output. -// It accepts banner/ANSI-decorated output and only requires the version line. -func parsePicoclawVersionOutput(raw string) (systemVersionResponse, bool) { - var result systemVersionResponse - - scanner := bufio.NewScanner(strings.NewReader(raw)) - for scanner.Scan() { - line := strings.TrimSpace(ansiEscapePattern.ReplaceAllString(scanner.Text(), "")) - if line == "" { - continue - } - - if match := versionLinePattern.FindStringSubmatch(line); len(match) > 0 { - candidateVersion := strings.TrimSpace(match[1]) - if !isLikelyVersionValue(candidateVersion) { - continue - } - result.Version = candidateVersion - if len(match) > 2 { - result.GitCommit = strings.TrimSpace(match[2]) - } - continue - } - - if buildValue, ok := strings.CutPrefix(line, "Build:"); ok { - result.BuildTime = strings.TrimSpace(buildValue) - continue - } - - if goValue, ok := strings.CutPrefix(line, "Go:"); ok { - result.GoVersion = strings.TrimSpace(goValue) - } - } - - if err := scanner.Err(); err != nil { - return systemVersionResponse{}, false - } - - if result.Version == "" { - return systemVersionResponse{}, false - } - - return result, true -} - -func isLikelyVersionValue(value string) bool { - v := strings.TrimSpace(strings.ToLower(value)) - if v == "" { - return false - } - if v == "dev" { - return true - } - - // Accept git-like short/long hashes even when they contain only letters (a-f). - if len(v) >= 7 && len(v) <= 40 { - allHex := true - for _, ch := range v { - if (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') { - continue - } - allHex = false - break - } - if allHex { - return true - } - } - - for _, ch := range v { - if ch >= '0' && ch <= '9' { - return true - } - } - return false -} diff --git a/web/backend/api/version_test.go b/web/backend/api/version_test.go deleted file mode 100644 index 31c5366a..00000000 --- a/web/backend/api/version_test.go +++ /dev/null @@ -1,317 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "os/exec" - "runtime" - "testing" -) - -func setupVersionTestIsolation(t *testing.T) { - t.Helper() - - originalGatewayState := currentGatewayVersionState - originalFinder := findPicoclawBinaryForInfo - originalRunner := runPicoclawVersionOutput - originalFallback := launcherBuildInfoForVersion - t.Cleanup(func() { - currentGatewayVersionState = originalGatewayState - findPicoclawBinaryForInfo = originalFinder - runPicoclawVersionOutput = originalRunner - launcherBuildInfoForVersion = originalFallback - versionInfoCache.resetForTest() - }) - - currentGatewayVersionState = func() (int, bool) { return 0, false } - versionInfoCache.resetForTest() -} - -func TestGetSystemVersionUsesPicoclawBinaryInfo(t *testing.T) { - setupVersionTestIsolation(t) - - launcherBuildInfoForVersion = func() systemVersionResponse { - return systemVersionResponse{Version: "fallback", GoVersion: "go-fallback"} - } - - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - return "🦞 picoclaw v1.2.3 (git: deadbeef)\n Build: 2026-03-27T12:34:56Z\n Go: go1.25.8\n", nil - } - - h := NewHandler("") - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/system/version", 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 systemVersionResponse - if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got.Version != "v1.2.3" { - t.Fatalf("version = %q, want %q", got.Version, "v1.2.3") - } - if got.GitCommit != "deadbeef" { - t.Fatalf("git_commit = %q, want %q", got.GitCommit, "deadbeef") - } - if got.BuildTime != "2026-03-27T12:34:56Z" { - t.Fatalf("build_time = %q, want %q", got.BuildTime, "2026-03-27T12:34:56Z") - } - if got.GoVersion != "go1.25.8" { - t.Fatalf("go_version = %q, want %q", got.GoVersion, "go1.25.8") - } -} - -func TestGetSystemVersionFallsBackToLauncherInfoWhenCommandFails(t *testing.T) { - setupVersionTestIsolation(t) - - expected := systemVersionResponse{ - Version: "v9.9.9", - GitCommit: "cafebabe", - BuildTime: "2026-03-27T10:43:34+0000", - GoVersion: "go1.25.8", - } - launcherBuildInfoForVersion = func() systemVersionResponse { return expected } - - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - return "", errors.New("binary unavailable") - } - - h := NewHandler("") - mux := http.NewServeMux() - h.RegisterRoutes(mux) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/system/version", 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 systemVersionResponse - if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { - t.Fatalf("unmarshal response: %v", err) - } - - if got.Version != expected.Version { - t.Fatalf("version = %q, want %q", got.Version, expected.Version) - } - if got.GitCommit != expected.GitCommit { - t.Fatalf("git_commit = %q, want %q", got.GitCommit, expected.GitCommit) - } - if got.BuildTime != expected.BuildTime { - t.Fatalf("build_time = %q, want %q", got.BuildTime, expected.BuildTime) - } - if got.GoVersion != expected.GoVersion { - t.Fatalf("go_version = %q, want %q", got.GoVersion, expected.GoVersion) - } -} - -func TestParsePicoclawVersionOutput(t *testing.T) { - setupVersionTestIsolation(t) - - raw := "\u001b[1;31m████\u001b[0m\n🦞 picoclaw 18ec263 (git: 18ec2631)\n Build: 2026-03-27T10:43:34+0000\n Go: go1.25.8\n" - got, ok := parsePicoclawVersionOutput(raw) - if !ok { - t.Fatal("parsePicoclawVersionOutput() should parse valid output") - } - if got.Version != "18ec263" { - t.Fatalf("version = %q, want %q", got.Version, "18ec263") - } - if got.GitCommit != "18ec2631" { - t.Fatalf("git_commit = %q, want %q", got.GitCommit, "18ec2631") - } - if got.BuildTime != "2026-03-27T10:43:34+0000" { - t.Fatalf("build_time = %q, want %q", got.BuildTime, "2026-03-27T10:43:34+0000") - } - if got.GoVersion != "go1.25.8" { - t.Fatalf("go_version = %q, want %q", got.GoVersion, "go1.25.8") - } -} - -func TestParsePicoclawVersionOutputIgnoresUsageLine(t *testing.T) { - setupVersionTestIsolation(t) - - raw := "Usage: picoclaw version [flags]\n" - got, ok := parsePicoclawVersionOutput(raw) - if ok { - t.Fatalf("parsePicoclawVersionOutput() parsed usage line unexpectedly: %#v", got) - } -} - -func TestParsePicoclawVersionOutputAcceptsLetterOnlyHashVersion(t *testing.T) { - setupVersionTestIsolation(t) - - raw := "picoclaw abcdefa (git: abcdefabcdefabcdefabcdefabcdefabcdefabcd)\n" - got, ok := parsePicoclawVersionOutput(raw) - if !ok { - t.Fatal("parsePicoclawVersionOutput() should parse letter-only hash version") - } - if got.Version != "abcdefa" { - t.Fatalf("version = %q, want %q", got.Version, "abcdefa") - } - if got.GitCommit != "abcdefabcdefabcdefabcdefabcdefabcdefabcd" { - t.Fatalf("git_commit = %q, want %q", got.GitCommit, "abcdefabcdefabcdefabcdefabcdefabcdefabcd") - } -} - -func TestResolveSystemVersionInfoFallsBackRuntimeGoVersion(t *testing.T) { - setupVersionTestIsolation(t) - - launcherBuildInfoForVersion = func() systemVersionResponse { - return systemVersionResponse{Version: "dev", GoVersion: ""} - } - - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - return "picoclaw v1.0.0\n", nil - } - - h := NewHandler("") - got := h.resolveSystemVersionInfo(context.Background()) - if got.GoVersion != runtime.Version() { - t.Fatalf("go_version = %q, want runtime version %q", got.GoVersion, runtime.Version()) - } -} - -func TestResolveSystemVersionInfoCachesWhileGatewayAlive(t *testing.T) { - setupVersionTestIsolation(t) - - launcherBuildInfoForVersion = func() systemVersionResponse { - return systemVersionResponse{Version: "dev", GoVersion: "go-fallback"} - } - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - - pid := 4321 - currentGatewayVersionState = func() (int, bool) { return pid, true } - - runCount := 0 - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - runCount++ - return fmt.Sprintf("picoclaw v1.2.%d\n", runCount), nil - } - - h := NewHandler("") - first := h.resolveSystemVersionInfo(context.Background()) - second := h.resolveSystemVersionInfo(context.Background()) - - if first.Version != "v1.2.1" { - t.Fatalf("first version = %q, want %q", first.Version, "v1.2.1") - } - if second.Version != "v1.2.1" { - t.Fatalf("second version = %q, want cached %q", second.Version, "v1.2.1") - } - if runCount != 1 { - t.Fatalf("run count = %d, want %d", runCount, 1) - } -} - -func TestResolveSystemVersionInfoInvalidatesCacheWhenGatewayStops(t *testing.T) { - setupVersionTestIsolation(t) - - launcherBuildInfoForVersion = func() systemVersionResponse { - return systemVersionResponse{Version: "dev", GoVersion: "go-fallback"} - } - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - - alive := true - pid := 9876 - currentGatewayVersionState = func() (int, bool) { - if !alive { - return 0, false - } - return pid, true - } - - runCount := 0 - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - runCount++ - return fmt.Sprintf("picoclaw v2.0.%d\n", runCount), nil - } - - h := NewHandler("") - first := h.resolveSystemVersionInfo(context.Background()) - second := h.resolveSystemVersionInfo(context.Background()) - - if first.Version != "v2.0.1" || second.Version != "v2.0.1" { - t.Fatalf("expected cached version v2.0.1, got first=%q second=%q", first.Version, second.Version) - } - if runCount != 1 { - t.Fatalf("run count after cache hit = %d, want %d", runCount, 1) - } - - alive = false - third := h.resolveSystemVersionInfo(context.Background()) - if third.Version != "v2.0.2" { - t.Fatalf("third version = %q, want refreshed %q", third.Version, "v2.0.2") - } - if runCount != 2 { - t.Fatalf("run count after invalidation = %d, want %d", runCount, 2) - } -} - -func TestResolveSystemVersionInfoSkipsCommandWhenContextCanceled(t *testing.T) { - setupVersionTestIsolation(t) - - launcherBuildInfoForVersion = func() systemVersionResponse { - return systemVersionResponse{Version: "v3.0.0", GoVersion: "go-fallback"} - } - findPicoclawBinaryForInfo = func() string { return "picoclaw" } - - runCount := 0 - runPicoclawVersionOutput = func(_ context.Context, _ string) (string, error) { - runCount++ - return "picoclaw v9.9.9\n", nil - } - - canceledCtx, cancel := context.WithCancel(context.Background()) - cancel() - - h := NewHandler("") - got := h.resolveSystemVersionInfo(canceledCtx) - - if runCount != 0 { - t.Fatalf("run count = %d, want %d", runCount, 0) - } - if got.Version != "v3.0.0" { - t.Fatalf("version = %q, want fallback %q", got.Version, "v3.0.0") - } -} - -func TestResolveGatewayBinaryForVersionInfoPrefersGatewayCommandPath(t *testing.T) { - setupVersionTestIsolation(t) - - originalFinder := findPicoclawBinaryForInfo - t.Cleanup(func() { - findPicoclawBinaryForInfo = originalFinder - }) - - gateway.mu.Lock() - originalCmd := gateway.cmd - gateway.cmd = &exec.Cmd{Path: "/tmp/picoclaw-from-gateway"} - gateway.mu.Unlock() - t.Cleanup(func() { - gateway.mu.Lock() - gateway.cmd = originalCmd - gateway.mu.Unlock() - }) - - got := resolveGatewayBinaryForVersionInfo() - if got != "/tmp/picoclaw-from-gateway" { - t.Fatalf("exec path = %q, want %q", got, "/tmp/picoclaw-from-gateway") - } -} diff --git a/web/backend/api/wecom.go b/web/backend/api/wecom.go deleted file mode 100644 index 74e5d8e8..00000000 --- a/web/backend/api/wecom.go +++ /dev/null @@ -1,432 +0,0 @@ -package api - -import ( - "context" - "crypto/rand" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "runtime" - "strconv" - "strings" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -const ( - wecomFlowTTL = 5 * time.Minute - wecomFlowGCAge = 30 * time.Minute - wecomQRSourceID = "picoclaw" - wecomQRGenerateEndpoint = "https://work.weixin.qq.com/ai/qc/generate" - wecomQRQueryEndpoint = "https://work.weixin.qq.com/ai/qc/query_result" - wecomQRHTTPTimeout = 15 * time.Second - wecomDefaultWebSocketURL = "wss://openws.work.weixin.qq.com" - wecomPollStartTimeout = 15 * time.Second - wecomPollStatusTimeout = 10 * time.Second -) - -const ( - wecomStatusWait = "wait" - wecomStatusScanned = "scaned" - wecomStatusConfirmed = "confirmed" - wecomStatusExpired = "expired" - wecomStatusError = "error" -) - -type wecomFlow struct { - ID string - SCode string - QRDataURI string - BotID string - Status string - Error string - CreatedAt time.Time - UpdatedAt time.Time - ExpiresAt time.Time -} - -type wecomFlowResponse struct { - FlowID string `json:"flow_id"` - Status string `json:"status"` - QRDataURI string `json:"qr_data_uri,omitempty"` - BotID string `json:"bot_id,omitempty"` - Error string `json:"error,omitempty"` -} - -type wecomQRGenerateResponse struct { - ErrCode int `json:"errcode,omitempty"` - ErrMsg string `json:"errmsg,omitempty"` - Data struct { - SCode string `json:"scode"` - AuthURL string `json:"auth_url"` - } `json:"data"` -} - -type wecomQRQueryResponse struct { - ErrCode int `json:"errcode,omitempty"` - ErrMsg string `json:"errmsg,omitempty"` - Data struct { - Status string `json:"status"` - BotInfo struct { - BotID string `json:"botid"` - Secret string `json:"secret"` - } `json:"bot_info"` - } `json:"data"` -} - -// registerWecomRoutes binds WeCom QR login endpoints to the ServeMux. -func (h *Handler) registerWecomRoutes(mux *http.ServeMux) { - mux.HandleFunc("POST /api/wecom/flows", h.handleStartWecomFlow) - mux.HandleFunc("GET /api/wecom/flows/{id}", h.handlePollWecomFlow) -} - -// handleStartWecomFlow starts a new WeCom QR login flow. -// -// POST /api/wecom/flows -func (h *Handler) handleStartWecomFlow(w http.ResponseWriter, r *http.Request) { - ctx, cancel := context.WithTimeout(r.Context(), wecomPollStartTimeout) - defer cancel() - - session, err := fetchWecomQRCode(ctx) - if err != nil { - http.Error(w, fmt.Sprintf("failed to get QR code: %v", err), http.StatusInternalServerError) - return - } - - dataURI, err := generateQRDataURI(session.Data.AuthURL) - if err != nil { - http.Error(w, fmt.Sprintf("failed to generate QR image: %v", err), http.StatusInternalServerError) - return - } - - now := time.Now() - flow := &wecomFlow{ - ID: newWecomFlowID(), - SCode: session.Data.SCode, - QRDataURI: dataURI, - Status: wecomStatusWait, - CreatedAt: now, - UpdatedAt: now, - ExpiresAt: now.Add(wecomFlowTTL), - } - h.storeWecomFlow(flow) - - logger.InfoCF("wecom", "QR flow started", map[string]any{"flow_id": flow.ID}) - - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(wecomFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - QRDataURI: flow.QRDataURI, - }) -} - -// handlePollWecomFlow polls the WeCom API for QR code status and updates the flow. -// -// GET /api/wecom/flows/{id} -func (h *Handler) handlePollWecomFlow(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.getWecomFlow(flowID) - if !ok { - http.Error(w, "flow not found", http.StatusNotFound) - return - } - - if flow.Status == wecomStatusConfirmed || - flow.Status == wecomStatusExpired || - flow.Status == wecomStatusError { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(wecomFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - BotID: flow.BotID, - Error: flow.Error, - }) - return - } - - ctx, cancel := context.WithTimeout(r.Context(), wecomPollStatusTimeout) - defer cancel() - - statusResp, err := queryWecomQRCodeStatus(ctx, flow.SCode) - if err != nil { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(wecomFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - QRDataURI: flow.QRDataURI, - }) - return - } - - switch strings.ToLower(statusResp.Data.Status) { - case wecomStatusWait: - // no-op - case wecomStatusScanned, "scanned": - h.updateWecomFlowStatus(flowID, wecomStatusScanned) - case "success": - if statusResp.Data.BotInfo.BotID == "" || statusResp.Data.BotInfo.Secret == "" { - h.setWecomFlowError(flowID, "login confirmed but missing bot credentials") - break - } - if saveErr := h.saveWecomBinding( - statusResp.Data.BotInfo.BotID, - statusResp.Data.BotInfo.Secret, - ); saveErr != nil { - h.setWecomFlowError(flowID, fmt.Sprintf("failed to save credentials: %v", saveErr)) - logger.ErrorCF("wecom", "failed to save credentials", map[string]any{"error": saveErr.Error()}) - break - } - h.setWecomFlowConfirmed(flowID, statusResp.Data.BotInfo.BotID) - logger.InfoCF("wecom", "QR login confirmed, credentials saved", map[string]any{ - "flow_id": flowID, - "bot_id": statusResp.Data.BotInfo.BotID, - }) - case wecomStatusExpired: - h.updateWecomFlowStatus(flowID, wecomStatusExpired) - } - - flow, _ = h.getWecomFlow(flowID) - w.Header().Set("Content-Type", "application/json") - resp := wecomFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - BotID: flow.BotID, - Error: flow.Error, - } - if flow.Status == wecomStatusWait || flow.Status == wecomStatusScanned { - resp.QRDataURI = flow.QRDataURI - } - _ = json.NewEncoder(w).Encode(resp) -} - -func (h *Handler) saveWecomBinding(botID, secret string) error { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return fmt.Errorf("load config: %w", err) - } - - bc := cfg.Channels.Get(config.ChannelWeCom) - if bc == nil { - bc = &config.Channel{Type: config.ChannelWeCom} - cfg.Channels["wecom"] = bc - } - bc.Enabled = true - - var wecomCfg config.WeComSettings - bc.Decode(&wecomCfg) - wecomCfg.BotID = botID - wecomCfg.Secret = *config.NewSecureString(secret) - if strings.TrimSpace(wecomCfg.WebSocketURL) == "" { - wecomCfg.WebSocketURL = wecomDefaultWebSocketURL - } - if err := config.SaveConfig(h.configPath, cfg); err != nil { - return err - } - - status := h.gatewayStatusData() - gatewayStatus, _ := status["gateway_status"].(string) - if gatewayStatus != "running" { - return nil - } - - if _, err := h.RestartGateway(); err != nil { - logger.ErrorCF("wecom", "failed to restart gateway after saving binding", map[string]any{ - "error": err.Error(), - }) - } - return nil -} - -func fetchWecomQRCode(ctx context.Context) (wecomQRGenerateResponse, error) { - targetURL, err := buildWecomQRGenerateURL(wecomQRGenerateEndpoint, wecomQRSourceID, wecomPlatformCode()) - if err != nil { - return wecomQRGenerateResponse{}, err - } - - var resp wecomQRGenerateResponse - if err := doWecomJSONGet(ctx, targetURL, &resp); err != nil { - return wecomQRGenerateResponse{}, err - } - if resp.ErrCode != 0 { - return wecomQRGenerateResponse{}, fmt.Errorf( - "errcode=%d errmsg=%s", - resp.ErrCode, - resp.ErrMsg, - ) - } - if resp.Data.SCode == "" || resp.Data.AuthURL == "" { - return wecomQRGenerateResponse{}, fmt.Errorf("response missing scode or auth_url") - } - return resp, nil -} - -func queryWecomQRCodeStatus(ctx context.Context, scode string) (wecomQRQueryResponse, error) { - targetURL, err := buildWecomQRQueryURL(wecomQRQueryEndpoint, scode) - if err != nil { - return wecomQRQueryResponse{}, err - } - - var resp wecomQRQueryResponse - if err := doWecomJSONGet(ctx, targetURL, &resp); err != nil { - return wecomQRQueryResponse{}, err - } - if resp.ErrCode != 0 { - return wecomQRQueryResponse{}, fmt.Errorf( - "errcode=%d errmsg=%s", - resp.ErrCode, - resp.ErrMsg, - ) - } - return resp, nil -} - -func buildWecomQRGenerateURL(baseURL, sourceID string, platformCode int) (string, error) { - u, err := url.Parse(baseURL) - if err != nil { - return "", fmt.Errorf("invalid WeCom QR generate URL: %w", err) - } - - query := u.Query() - query.Set("source", sourceID) - query.Set("sourceID", sourceID) - query.Set("plat", strconv.Itoa(platformCode)) - u.RawQuery = query.Encode() - - return u.String(), nil -} - -func buildWecomQRQueryURL(baseURL, scode string) (string, error) { - u, err := url.Parse(baseURL) - if err != nil { - return "", fmt.Errorf("invalid WeCom QR query URL: %w", err) - } - - query := u.Query() - query.Set("scode", scode) - u.RawQuery = query.Encode() - - return u.String(), nil -} - -func doWecomJSONGet(ctx context.Context, targetURL string, out any) error { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil) - if err != nil { - return err - } - - client := &http.Client{Timeout: wecomQRHTTPTimeout} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - body, readErr := io.ReadAll(io.LimitReader(resp.Body, 8192)) - if readErr != nil { - return fmt.Errorf("unexpected status %s", resp.Status) - } - return fmt.Errorf("unexpected status %s: %s", resp.Status, strings.TrimSpace(string(body))) - } - - if err := json.NewDecoder(resp.Body).Decode(out); err != nil { - return fmt.Errorf("decode JSON response: %w", err) - } - return nil -} - -func wecomPlatformCode() int { - switch runtime.GOOS { - case "darwin": - return 1 - case "windows": - return 2 - case "linux": - return 3 - default: - return 0 - } -} - -func newWecomFlowID() string { - buf := make([]byte, 12) - if _, err := rand.Read(buf); err != nil { - return fmt.Sprintf("wc_%d", time.Now().UnixNano()) - } - return "wc_" + hex.EncodeToString(buf) -} - -func (h *Handler) storeWecomFlow(flow *wecomFlow) { - h.wecomMu.Lock() - defer h.wecomMu.Unlock() - h.gcWecomFlowsLocked(time.Now()) - h.wecomFlows[flow.ID] = flow -} - -func (h *Handler) getWecomFlow(flowID string) (*wecomFlow, bool) { - h.wecomMu.Lock() - defer h.wecomMu.Unlock() - h.gcWecomFlowsLocked(time.Now()) - flow, ok := h.wecomFlows[flowID] - if !ok { - return nil, false - } - cp := *flow - return &cp, true -} - -func (h *Handler) updateWecomFlowStatus(flowID, status string) { - h.wecomMu.Lock() - defer h.wecomMu.Unlock() - if flow, ok := h.wecomFlows[flowID]; ok { - flow.Status = status - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) setWecomFlowConfirmed(flowID, botID string) { - h.wecomMu.Lock() - defer h.wecomMu.Unlock() - if flow, ok := h.wecomFlows[flowID]; ok { - flow.Status = wecomStatusConfirmed - flow.BotID = botID - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) setWecomFlowError(flowID, errMsg string) { - h.wecomMu.Lock() - defer h.wecomMu.Unlock() - if flow, ok := h.wecomFlows[flowID]; ok { - flow.Status = wecomStatusError - flow.Error = errMsg - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) gcWecomFlowsLocked(now time.Time) { - for id, flow := range h.wecomFlows { - if flow.Status == wecomStatusWait || flow.Status == wecomStatusScanned { - if !flow.ExpiresAt.IsZero() && now.After(flow.ExpiresAt) { - flow.Status = wecomStatusExpired - flow.UpdatedAt = now - } - } - if flow.Status != wecomStatusWait && - flow.Status != wecomStatusScanned && - now.Sub(flow.UpdatedAt) > wecomFlowGCAge { - delete(h.wecomFlows, id) - } - } -} diff --git a/web/backend/api/weixin.go b/web/backend/api/weixin.go deleted file mode 100644 index 888789f8..00000000 --- a/web/backend/api/weixin.go +++ /dev/null @@ -1,332 +0,0 @@ -package api - -import ( - "context" - "crypto/rand" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "rsc.io/qr" - - "github.com/sipeed/picoclaw/pkg/channels/weixin" - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -const ( - weixinFlowTTL = 5 * time.Minute - weixinFlowGCAge = 30 * time.Minute - weixinBaseURL = "https://ilinkai.weixin.qq.com/" - weixinBotType = "3" -) - -const ( - weixinStatusWait = "wait" - weixinStatusScanned = "scaned" - weixinStatusConfirmed = "confirmed" - weixinStatusExpired = "expired" - weixinStatusError = "error" -) - -type weixinFlow struct { - ID string - Qrcode string // qrcode token from WeChat API (used for status polling) - QRDataURI string // base64 PNG data URI for display - AccountID string // IlinkBotID returned on confirmed - Status string // wait / scaned / confirmed / expired / error - Error string - CreatedAt time.Time - UpdatedAt time.Time - ExpiresAt time.Time -} - -type weixinFlowResponse struct { - FlowID string `json:"flow_id"` - Status string `json:"status"` - QRDataURI string `json:"qr_data_uri,omitempty"` - AccountID string `json:"account_id,omitempty"` - Error string `json:"error,omitempty"` -} - -// registerWeixinRoutes binds WeChat QR login endpoints to the ServeMux. -func (h *Handler) registerWeixinRoutes(mux *http.ServeMux) { - mux.HandleFunc("POST /api/weixin/flows", h.handleStartWeixinFlow) - mux.HandleFunc("GET /api/weixin/flows/{id}", h.handlePollWeixinFlow) -} - -// handleStartWeixinFlow starts a new WeChat QR login flow. -// -// POST /api/weixin/flows -func (h *Handler) handleStartWeixinFlow(w http.ResponseWriter, r *http.Request) { - ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) - defer cancel() - - api, err := weixin.NewApiClient(weixinBaseURL, "", "") - if err != nil { - http.Error(w, fmt.Sprintf("failed to create weixin client: %v", err), http.StatusInternalServerError) - return - } - - qrResp, err := api.GetQRCode(ctx, weixinBotType) - if err != nil { - http.Error(w, fmt.Sprintf("failed to get QR code: %v", err), http.StatusInternalServerError) - return - } - - dataURI, err := generateQRDataURI(qrResp.QrcodeImgContent) - if err != nil { - http.Error(w, fmt.Sprintf("failed to generate QR image: %v", err), http.StatusInternalServerError) - return - } - - now := time.Now() - flow := &weixinFlow{ - ID: newWeixinFlowID(), - Qrcode: qrResp.Qrcode, - QRDataURI: dataURI, - Status: weixinStatusWait, - CreatedAt: now, - UpdatedAt: now, - ExpiresAt: now.Add(weixinFlowTTL), - } - h.storeWeixinFlow(flow) - - logger.InfoCF("weixin", "QR flow started", map[string]any{"flow_id": flow.ID}) - - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(weixinFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - QRDataURI: flow.QRDataURI, - }) -} - -// handlePollWeixinFlow polls the WeChat API for QR code status and updates the flow. -// -// GET /api/weixin/flows/{id} -func (h *Handler) handlePollWeixinFlow(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.getWeixinFlow(flowID) - if !ok { - http.Error(w, "flow not found", http.StatusNotFound) - return - } - - // Return terminal states directly without polling WeChat again - if flow.Status == weixinStatusConfirmed || - flow.Status == weixinStatusExpired || - flow.Status == weixinStatusError { - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(weixinFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - Error: flow.Error, - }) - return - } - - ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) - defer cancel() - - api, err := weixin.NewApiClient(weixinBaseURL, "", "") - if err != nil { - h.setWeixinFlowError(flowID, fmt.Sprintf("client error: %v", err)) - flow, _ = h.getWeixinFlow(flowID) - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(weixinFlowResponse{FlowID: flow.ID, Status: flow.Status, Error: flow.Error}) - return - } - - statusResp, err := api.GetQRCodeStatus(ctx, flow.Qrcode) - if err != nil { - // Transient error — keep current status, return it - w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(weixinFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - QRDataURI: flow.QRDataURI, - }) - return - } - - switch statusResp.Status { - case weixinStatusWait: - // no change - - case weixinStatusScanned: - h.updateWeixinFlowStatus(flowID, weixinStatusScanned) - - case weixinStatusConfirmed: - if statusResp.BotToken == "" { - h.setWeixinFlowError(flowID, "login confirmed but missing bot_token") - break - } - if saveErr := h.saveWeixinBinding(statusResp.BotToken, statusResp.IlinkBotID); saveErr != nil { - h.setWeixinFlowError(flowID, fmt.Sprintf("failed to save token: %v", saveErr)) - logger.ErrorCF("weixin", "failed to save token", map[string]any{"error": saveErr.Error()}) - break - } - h.setWeixinFlowConfirmed(flowID, statusResp.IlinkBotID) - logger.InfoCF("weixin", "QR login confirmed, token saved", map[string]any{ - "flow_id": flowID, - "account_id": statusResp.IlinkBotID, - }) - - case weixinStatusExpired: - h.updateWeixinFlowStatus(flowID, weixinStatusExpired) - - default: - // unknown status, keep as-is - } - - flow, _ = h.getWeixinFlow(flowID) - w.Header().Set("Content-Type", "application/json") - resp := weixinFlowResponse{ - FlowID: flow.ID, - Status: flow.Status, - AccountID: flow.AccountID, - Error: flow.Error, - } - if flow.Status == weixinStatusWait || flow.Status == weixinStatusScanned { - resp.QRDataURI = flow.QRDataURI - } - _ = json.NewEncoder(w).Encode(resp) -} - -// saveWeixinBinding writes the token/account ID, enables the Weixin channel, -// and best-effort restarts the gateway when it is currently running. -func (h *Handler) saveWeixinBinding(token, accountID string) error { - cfg, err := config.LoadConfig(h.configPath) - if err != nil { - return fmt.Errorf("load config: %w", err) - } - - bc := cfg.Channels.Get(config.ChannelWeixin) - if bc == nil { - bc = &config.Channel{Type: config.ChannelWeixin} - cfg.Channels[config.ChannelWeixin] = bc - } - bc.Enabled = true - - var weixinCfg config.WeixinSettings - if err := bc.Decode(&weixinCfg); err != nil { - logger.ErrorCF("weixin", "failed to decode weixin settings", map[string]any{ - "error": err.Error(), - }) - return fmt.Errorf("decode weixin settings: %w", err) - } - weixinCfg.Token = *config.NewSecureString(token) - if accountID != "" { - weixinCfg.AccountID = accountID - } - - if err := config.SaveConfig(h.configPath, cfg); err != nil { - return err - } - - status := h.gatewayStatusData() - gatewayStatus, _ := status["gateway_status"].(string) - if gatewayStatus != "running" { - return nil - } - - if _, err := h.RestartGateway(); err != nil { - logger.ErrorCF("weixin", "failed to restart gateway after saving binding", map[string]any{ - "error": err.Error(), - }) - } - return nil -} - -// generateQRDataURI encodes content as a QR code PNG and returns a data URI. -func generateQRDataURI(content string) (string, error) { - code, err := qr.Encode(content, qr.L) - if err != nil { - return "", fmt.Errorf("qr encode: %w", err) - } - pngBytes := code.PNG() - encoded := base64.StdEncoding.EncodeToString(pngBytes) - return "data:image/png;base64," + encoded, nil -} - -func newWeixinFlowID() string { - buf := make([]byte, 12) - if _, err := rand.Read(buf); err != nil { - return fmt.Sprintf("wx_%d", time.Now().UnixNano()) - } - return "wx_" + hex.EncodeToString(buf) -} - -func (h *Handler) storeWeixinFlow(flow *weixinFlow) { - h.weixinMu.Lock() - defer h.weixinMu.Unlock() - h.gcWeixinFlowsLocked(time.Now()) - h.weixinFlows[flow.ID] = flow -} - -func (h *Handler) getWeixinFlow(flowID string) (*weixinFlow, bool) { - h.weixinMu.Lock() - defer h.weixinMu.Unlock() - h.gcWeixinFlowsLocked(time.Now()) - flow, ok := h.weixinFlows[flowID] - if !ok { - return nil, false - } - cp := *flow - return &cp, true -} - -func (h *Handler) updateWeixinFlowStatus(flowID, status string) { - h.weixinMu.Lock() - defer h.weixinMu.Unlock() - if flow, ok := h.weixinFlows[flowID]; ok { - flow.Status = status - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) setWeixinFlowConfirmed(flowID, accountID string) { - h.weixinMu.Lock() - defer h.weixinMu.Unlock() - if flow, ok := h.weixinFlows[flowID]; ok { - flow.Status = weixinStatusConfirmed - flow.AccountID = accountID - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) setWeixinFlowError(flowID, errMsg string) { - h.weixinMu.Lock() - defer h.weixinMu.Unlock() - if flow, ok := h.weixinFlows[flowID]; ok { - flow.Status = weixinStatusError - flow.Error = errMsg - flow.UpdatedAt = time.Now() - } -} - -func (h *Handler) gcWeixinFlowsLocked(now time.Time) { - for id, flow := range h.weixinFlows { - if flow.Status == weixinStatusWait || flow.Status == weixinStatusScanned { - if !flow.ExpiresAt.IsZero() && now.After(flow.ExpiresAt) { - flow.Status = weixinStatusExpired - flow.UpdatedAt = now - } - } - if flow.Status != weixinStatusWait && - flow.Status != weixinStatusScanned && - now.Sub(flow.UpdatedAt) > weixinFlowGCAge { - delete(h.weixinFlows, id) - } - } -} diff --git a/web/backend/api/weixin_test.go b/web/backend/api/weixin_test.go deleted file mode 100644 index 575de7b9..00000000 --- a/web/backend/api/weixin_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package api - -import ( - "io" - "net/http" - "os" - "path/filepath" - "strconv" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/config" -) - -func TestSaveWeixinBindingReturnsSuccessWhenRestartFails(t *testing.T) { - resetGatewayTestState(t) - - configPath := filepath.Join(t.TempDir(), "config.json") - cfg := config.DefaultConfig() - if err := config.SaveConfig(configPath, cfg); err != nil { - t.Fatalf("SaveConfig() error = %v", err) - } - - originalHealthGet := gatewayHealthGet - gatewayHealthGet = func(url string, timeout time.Duration) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(strings.NewReader( - `{"status":"ok","uptime":"1s","pid":` + strconv.Itoa(os.Getpid()) + `}`, - )), - }, nil - } - t.Cleanup(func() { - gatewayHealthGet = originalHealthGet - }) - - h := NewHandler(configPath) - if err := h.saveWeixinBinding("bot-token", "bot-account"); err != nil { - t.Fatalf("saveWeixinBinding() error = %v, want nil after config save succeeds", err) - } - - savedCfg, err := config.LoadConfig(configPath) - if err != nil { - t.Fatalf("LoadConfig() error = %v", err) - } - bc := savedCfg.Channels["weixin"] - decoded, err := bc.GetDecoded() - if err != nil { - t.Fatalf("GetDecoded() error = %v", err) - } - wxCfg := decoded.(*config.WeixinSettings) - if got := wxCfg.Token.String(); got != "bot-token" { - t.Fatalf("Weixin.Token() = %q, want %q", got, "bot-token") - } - if got := wxCfg.AccountID; got != "bot-account" { - t.Fatalf("Weixin.AccountID = %q, want %q", got, "bot-account") - } - if !bc.Enabled { - t.Fatalf("Weixin.Enabled = false, want true") - } -} diff --git a/web/backend/app_runtime.go b/web/backend/app_runtime.go deleted file mode 100644 index a0639652..00000000 --- a/web/backend/app_runtime.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -const ( - browserDelay = 500 * time.Millisecond - shutdownTimeout = 15 * time.Second -) - -// shutdownApp gracefully shuts down all server components and resources. -// It performs the following shutdown sequence: -// - Shuts down the API handler to close all active SSE (Server-Sent Events) connections -// - Disables HTTP keep-alive to prevent new connections during shutdown -// - Attempts graceful HTTP server shutdown with timeout -// - Logs shutdown status at appropriate log levels -// -// The function handles timeout errors gracefully by logging them at info level -// since context.DeadlineExceeded is expected when there are active long-running -// connections (such as SSE streams). -// -// This function should be called during application termination to ensure -// clean resource cleanup and proper connection closure. -func shutdownApp() { - // First, shutdown API handler to close all SSE connections - if apiHandler != nil { - apiHandler.Shutdown() - } - - if len(servers) > 0 { - for _, srv := range servers { - if srv == nil { - continue - } - - // Disable keep-alive to allow graceful shutdown - srv.SetKeepAlivesEnabled(false) - - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - err := srv.Shutdown(ctx) - cancel() - - if err != nil { - // Context deadline exceeded is expected if there are active connections - // This is not necessarily an error, so log it at info level - if errors.Is(err, context.DeadlineExceeded) { - logger.Infof("Server shutdown timeout after %v, forcing close", shutdownTimeout) - } else { - logger.Errorf("Server shutdown error: %v", err) - } - } else { - logger.Infof("Server shutdown completed successfully") - } - } - } -} - -func openBrowser() error { - target := browserLaunchURL - if target == "" { - target = serverAddr - } - if target == "" { - return fmt.Errorf("server address not set") - } - return utils.OpenBrowser(target) -} diff --git a/web/backend/dashboardauth/platform.go b/web/backend/dashboardauth/platform.go deleted file mode 100644 index 25ba5da0..00000000 --- a/web/backend/dashboardauth/platform.go +++ /dev/null @@ -1,7 +0,0 @@ -package dashboardauth - -import "errors" - -// ErrUnsupportedPlatform reports that the SQLite-backed password store is not -// available for the current target platform. -var ErrUnsupportedPlatform = errors.New("dashboard password store is unavailable on this platform") diff --git a/web/backend/dashboardauth/sql.go b/web/backend/dashboardauth/sql.go deleted file mode 100644 index 94886072..00000000 --- a/web/backend/dashboardauth/sql.go +++ /dev/null @@ -1,24 +0,0 @@ -package dashboardauth - -const ( - // DBFilename is the SQLite database file stored under the PicoClaw home directory. - DBFilename = "launcher-auth.db" - - sqliteDriver = "sqlite" - // bcryptCost is deliberately high enough to slow brute-force attempts. - bcryptCost = 12 - - sqlCreateTable = ` - CREATE TABLE IF NOT EXISTS dashboard_credentials ( - id INTEGER PRIMARY KEY CHECK (id = 1), - bcrypt_hash TEXT NOT NULL - )` - - sqlCountCredentials = `SELECT COUNT(*) FROM dashboard_credentials WHERE id = 1` - - sqlUpsertHash = ` - INSERT INTO dashboard_credentials (id, bcrypt_hash) VALUES (1, ?) - ON CONFLICT(id) DO UPDATE SET bcrypt_hash = excluded.bcrypt_hash` - - sqlSelectHash = `SELECT bcrypt_hash FROM dashboard_credentials WHERE id = 1` -) diff --git a/web/backend/dashboardauth/store.go b/web/backend/dashboardauth/store.go deleted file mode 100644 index 870796bb..00000000 --- a/web/backend/dashboardauth/store.go +++ /dev/null @@ -1,96 +0,0 @@ -//go:build !mipsle && !netbsd && !(freebsd && arm) - -// Package dashboardauth provides a bcrypt-backed SQLite store for the -// launcher dashboard password. The database contains a single row (id=1) -// with the bcrypt hash; no plaintext is ever persisted. -package dashboardauth - -import ( - "context" - "database/sql" - "errors" - "fmt" - "path/filepath" - - "golang.org/x/crypto/bcrypt" - _ "modernc.org/sqlite" // register "sqlite" driver -) - -// Store holds a handle to the SQLite database that stores the bcrypt hash. -type Store struct { - db *sql.DB - path string // absolute path to the SQLite file -} - -// New opens (or creates) the database inside dir, using the package's -// canonical filename. This is the preferred constructor for most callers. -// Any error is wrapped with the resolved path so callers get actionable output. -func New(dir string) (*Store, error) { - path := filepath.Join(dir, DBFilename) - s, err := Open(path) - if err != nil { - return nil, fmt.Errorf("open %q: %w", path, err) - } - return s, nil -} - -// Open opens (or creates) the SQLite database at path and migrates the schema. -func Open(path string) (*Store, error) { - db, err := sql.Open(sqliteDriver, path) - if err != nil { - return nil, err - } - if _, err = db.Exec(sqlCreateTable); err != nil { - _ = db.Close() - return nil, err - } - return &Store{db: db, path: path}, nil -} - -// Close releases the database handle. -func (s *Store) Close() error { return s.db.Close() } - -// DBPath returns the absolute path to the SQLite database file. -func (s *Store) DBPath() string { return s.path } - -// IsInitialized reports whether a password hash has been stored. -func (s *Store) IsInitialized(ctx context.Context) (bool, error) { - var n int - err := s.db.QueryRowContext(ctx, sqlCountCredentials).Scan(&n) - if err != nil { - return false, err - } - return n > 0, nil -} - -// SetPassword hashes plain with bcrypt (cost 12) and stores (or replaces) it. -// The plaintext is never written to disk. -func (s *Store) SetPassword(ctx context.Context, plain string) error { - if len([]rune(plain)) == 0 { - return errors.New("password must not be empty") - } - hash, err := bcrypt.GenerateFromPassword([]byte(plain), bcryptCost) - if err != nil { - return err - } - _, err = s.db.ExecContext(ctx, sqlUpsertHash, string(hash)) - return err -} - -// VerifyPassword returns true iff plain matches the stored bcrypt hash. -// Returns (false, nil) when no password has been set yet. -func (s *Store) VerifyPassword(ctx context.Context, plain string) (bool, error) { - var hash string - err := s.db.QueryRowContext(ctx, sqlSelectHash).Scan(&hash) - if errors.Is(err, sql.ErrNoRows) { - return false, nil - } - if err != nil { - return false, err - } - err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) - if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { - return false, nil - } - return err == nil, err -} diff --git a/web/backend/dashboardauth/store_unsupported.go b/web/backend/dashboardauth/store_unsupported.go deleted file mode 100644 index 20468202..00000000 --- a/web/backend/dashboardauth/store_unsupported.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build mipsle || netbsd || (freebsd && arm) - -package dashboardauth - -import ( - "context" - "fmt" - "path/filepath" - "runtime" -) - -// Store is unavailable on platforms where modernc sqlite/libc does not build. -type Store struct { - path string -} - -// New reports that the password store is unavailable on this platform. -func New(dir string) (*Store, error) { - path := filepath.Join(dir, DBFilename) - s, err := Open(path) - if err != nil { - return nil, fmt.Errorf("open %q: %w", path, err) - } - return s, nil -} - -// Open reports that the password store is unavailable on this platform. -func Open(path string) (*Store, error) { - return nil, unsupportedPlatformError() -} - -// Close is a no-op for unsupported platforms. -func (s *Store) Close() error { return nil } - -// DBPath returns the configured path, if any. -func (s *Store) DBPath() string { - if s == nil { - return "" - } - return s.path -} - -// IsInitialized reports that the store is unavailable on this platform. -func (s *Store) IsInitialized(context.Context) (bool, error) { - return false, unsupportedPlatformError() -} - -// SetPassword reports that the store is unavailable on this platform. -func (s *Store) SetPassword(context.Context, string) error { - return unsupportedPlatformError() -} - -// VerifyPassword reports that the store is unavailable on this platform. -func (s *Store) VerifyPassword(context.Context, string) (bool, error) { - return false, unsupportedPlatformError() -} - -func unsupportedPlatformError() error { - return fmt.Errorf("%w (%s/%s)", ErrUnsupportedPlatform, runtime.GOOS, runtime.GOARCH) -} diff --git a/web/backend/dist/.gitkeep b/web/backend/dist/.gitkeep deleted file mode 100644 index 4b533f03..00000000 --- a/web/backend/dist/.gitkeep +++ /dev/null @@ -1 +0,0 @@ -# Keep the embedded web backend dist directory in version control. diff --git a/web/backend/embed.go b/web/backend/embed.go deleted file mode 100644 index cf0c76bc..00000000 --- a/web/backend/embed.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import ( - "embed" - "fmt" - "io/fs" - "mime" - "net/http" - "path" - "strings" - - "github.com/sipeed/picoclaw/pkg/logger" -) - -//go:embed all:dist -var frontendFS embed.FS - -// registerEmbedRoutes sets up the HTTP handler to serve the embedded frontend files -func registerEmbedRoutes(mux *http.ServeMux) { - // Register correct MIME type for SVG files - // Go's built-in mime.TypeByExtension returns "image/svg" which is incorrect - // The correct MIME type per RFC 6838 is "image/svg+xml" - if err := mime.AddExtensionType(".svg", "image/svg+xml"); err != nil { - logger.ErrorC("web", fmt.Sprintf("Warning: failed to register SVG MIME type: %v", err)) - } - - // Attempt to get the subdirectory 'dist' where Vite usually builds - subFS, err := fs.Sub(frontendFS, "dist") - if err != nil { - // Log a warning if dist doesn't exist yet (e.g., during development before a frontend build) - logger.WarnC("web", - "Warning: no 'dist' folder found in embedded frontend. "+ - "Ensure you run `pnpm build:backend` in the frontend directory "+ - "before building the Go backend.", - ) - return - } - - fileServer := http.FileServer(http.FS(subFS)) - - // Serve static assets and fallback to index.html for SPA routes. - mux.Handle( - "/", - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet && r.Method != http.MethodHead { - http.NotFound(w, r) - return - } - - // Keep unknown API paths as 404 instead of falling back to SPA entry. - if r.URL.Path == "/api" || strings.HasPrefix(r.URL.Path, "/api/") { - http.NotFound(w, r) - return - } - - cleanPath := path.Clean(strings.TrimPrefix(r.URL.Path, "/")) - if cleanPath == "." { - cleanPath = "" - } - - // Existing static files/directories should be served directly. - if cleanPath != "" { - if _, statErr := fs.Stat(subFS, cleanPath); statErr == nil { - fileServer.ServeHTTP(w, r) - return - } - // Missing asset-like paths should remain 404. - if strings.Contains(path.Base(cleanPath), ".") { - fileServer.ServeHTTP(w, r) - return - } - } - - indexReq := r.Clone(r.Context()) - indexReq.URL.Path = "/" - fileServer.ServeHTTP(w, indexReq) - }), - ) -} diff --git a/web/backend/embed_test.go b/web/backend/embed_test.go deleted file mode 100644 index c0365488..00000000 --- a/web/backend/embed_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestUnknownAPIPathStays404(t *testing.T) { - mux := http.NewServeMux() - registerEmbedRoutes(mux) - - req := httptest.NewRequest(http.MethodGet, "/api/not-found", nil) - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, req) - - if rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want %d", rr.Code, http.StatusNotFound) - } -} - -func TestMissingAssetStays404(t *testing.T) { - mux := http.NewServeMux() - registerEmbedRoutes(mux) - - req := httptest.NewRequest(http.MethodGet, "/assets/not-found.js", nil) - rr := httptest.NewRecorder() - mux.ServeHTTP(rr, req) - - if rr.Code != http.StatusNotFound { - t.Fatalf("status = %d, want %d", rr.Code, http.StatusNotFound) - } -} diff --git a/web/backend/i18n.go b/web/backend/i18n.go deleted file mode 100644 index 9cda9e5d..00000000 --- a/web/backend/i18n.go +++ /dev/null @@ -1,120 +0,0 @@ -package main - -import ( - "fmt" - "os" - "strings" -) - -// Language represents the supported languages -type Language string - -const ( - LanguageEnglish Language = "en" - LanguageChinese Language = "zh" -) - -// current language (default: English) -var currentLang Language = LanguageEnglish - -// TranslationKey represents a translation key used for i18n -type TranslationKey string - -const ( - AppTooltip TranslationKey = "AppTooltip" - MenuOpen TranslationKey = "MenuOpen" - MenuOpenTooltip TranslationKey = "MenuOpenTooltip" - MenuAbout TranslationKey = "MenuAbout" - MenuAboutTooltip TranslationKey = "MenuAboutTooltip" - MenuVersion TranslationKey = "MenuVersion" - MenuVersionTooltip TranslationKey = "MenuVersionTooltip" - MenuGitHub TranslationKey = "MenuGitHub" - MenuDocs TranslationKey = "MenuDocs" - MenuRestart TranslationKey = "MenuRestart" - MenuRestartTooltip TranslationKey = "MenuRestartTooltip" - MenuQuit TranslationKey = "MenuQuit" - MenuQuitTooltip TranslationKey = "MenuQuitTooltip" - Exiting TranslationKey = "Exiting" - DocUrl TranslationKey = "DocUrl" -) - -// Translation tables -// Chinese translations intentionally contain Han script -// -//nolint:gosmopolitan -var translations = map[Language]map[TranslationKey]string{ - LanguageEnglish: { - AppTooltip: "%s - Web Console", - MenuOpen: "Open Console", - MenuOpenTooltip: "Open PicoClaw console in browser", - MenuAbout: "About", - MenuAboutTooltip: "About PicoClaw", - MenuVersion: "Version: %s", - MenuVersionTooltip: "Current version number", - MenuGitHub: "GitHub", - MenuDocs: "Documentation", - MenuRestart: "Restart Service", - MenuRestartTooltip: "Restart Gateway service", - MenuQuit: "Quit", - MenuQuitTooltip: "Exit PicoClaw", - Exiting: "Exiting PicoClaw...", - DocUrl: "https://docs.picoclaw.io/docs/", - }, - LanguageChinese: { - AppTooltip: "%s - Web Console", - MenuOpen: "打开控制台", - MenuOpenTooltip: "在浏览器中打开 PicoClaw 控制台", - MenuAbout: "关于", - MenuAboutTooltip: "关于 PicoClaw", - MenuVersion: "版本: %s", - MenuVersionTooltip: "当前版本号", - MenuGitHub: "GitHub", - MenuDocs: "文档", - MenuRestart: "重启服务", - MenuRestartTooltip: "重启核心服务", - MenuQuit: "退出", - MenuQuitTooltip: "退出 PicoClaw", - Exiting: "正在退出 PicoClaw...", - DocUrl: "https://docs.picoclaw.io/zh-Hans/docs/", - }, -} - -// SetLanguage sets the current language -func SetLanguage(lang string) { - lang = strings.ToLower(strings.TrimSpace(lang)) - - // Extract language code before first underscore or dot - // e.g., "en_US.UTF-8" -> "en", "zh_CN" -> "zh" - if idx := strings.IndexAny(lang, "_."); idx > 0 { - lang = lang[:idx] - } - - if lang == "zh" || lang == "zh-cn" || lang == "chinese" { - currentLang = LanguageChinese - } else { - currentLang = LanguageEnglish - } -} - -// GetLanguage returns the current language -func GetLanguage() Language { - return currentLang -} - -// T translates a key to the current language -func T(key TranslationKey, args ...any) string { - if trans, ok := translations[currentLang][key]; ok { - if len(args) > 0 { - return fmt.Sprintf(trans, args...) - } - return trans - } - return string(key) -} - -// Initialize i18n from environment variable -func init() { - if lang := os.Getenv("LANG"); lang != "" { - SetLanguage(lang) - } -} diff --git a/web/backend/icon.ico b/web/backend/icon.ico deleted file mode 100644 index 4f653941..00000000 Binary files a/web/backend/icon.ico and /dev/null differ diff --git a/web/backend/icon.png b/web/backend/icon.png deleted file mode 100644 index e0b4aab9..00000000 Binary files a/web/backend/icon.png and /dev/null differ diff --git a/web/backend/launcherconfig/config.go b/web/backend/launcherconfig/config.go deleted file mode 100644 index 692136f8..00000000 --- a/web/backend/launcherconfig/config.go +++ /dev/null @@ -1,162 +0,0 @@ -package launcherconfig - -import ( - "encoding/json" - "fmt" - "net" - "os" - "path/filepath" - "strings" -) - -const ( - // FileName is the launcher-specific settings file name. - FileName = "launcher-config.json" - // DefaultPort is the default port for the web launcher. - DefaultPort = 18800 - // EnvLauncherHost overrides launcher listen host. - EnvLauncherHost = "PICOCLAW_LAUNCHER_HOST" -) - -// Config stores launch parameters for the web backend service. -type Config struct { - Port int `json:"port"` - Public bool `json:"public"` - AllowedCIDRs []string `json:"allowed_cidrs,omitempty"` - AllowLocalhostBypass bool `json:"allow_localhost_bypass"` - AllowLocalhostBypassSource BoolFieldSource `json:"-"` - TrustedProxyCIDRs []string `json:"trusted_proxy_cidrs,omitempty"` - DashboardPasswordHash string `json:"dashboard_password_hash,omitempty"` - // LegacyLauncherToken is read only for one-time migration from the removed - // token login flow. Save always clears it so new configs do not persist it. - LegacyLauncherToken string `json:"launcher_token,omitempty"` -} - -// BoolFieldSource tracks whether a JSON boolean field was omitted, explicitly -// provided, or explicitly set to null. This is only used for diagnostics. -type BoolFieldSource uint8 - -const ( - BoolFieldAbsent BoolFieldSource = iota - BoolFieldPresent - BoolFieldNull -) - -// Default returns default launcher settings. -func Default() Config { - return Config{Port: DefaultPort, Public: false, AllowLocalhostBypass: true} -} - -// Validate checks if launcher settings are valid. -func Validate(cfg Config) error { - if cfg.Port < 1 || cfg.Port > 65535 { - return fmt.Errorf("port %d is out of range (1-65535)", cfg.Port) - } - for _, cidr := range cfg.AllowedCIDRs { - if _, _, err := net.ParseCIDR(cidr); err != nil { - return fmt.Errorf("invalid CIDR %q", cidr) - } - } - for _, cidr := range cfg.TrustedProxyCIDRs { - if _, _, err := net.ParseCIDR(cidr); err != nil { - return fmt.Errorf("invalid trusted proxy CIDR %q", cidr) - } - } - return nil -} - -// NormalizeCIDRs trims entries, removes empty values, and deduplicates CIDRs. -func NormalizeCIDRs(cidrs []string) []string { - if len(cidrs) == 0 { - return nil - } - out := make([]string, 0, len(cidrs)) - seen := make(map[string]struct{}, len(cidrs)) - for _, raw := range cidrs { - trimmed := strings.TrimSpace(raw) - if trimmed == "" { - continue - } - if _, ok := seen[trimmed]; ok { - continue - } - seen[trimmed] = struct{}{} - out = append(out, trimmed) - } - if len(out) == 0 { - return nil - } - return out -} - -// PathForAppConfig returns launcher-config path near the app config file. -func PathForAppConfig(appConfigPath string) string { - dir := filepath.Dir(appConfigPath) - if dir == "" || dir == "." { - dir = "." - } - return filepath.Join(dir, FileName) -} - -// Load reads launcher settings; fallback is returned when file does not exist. -func Load(path string, fallback Config) (Config, error) { - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - return fallback, nil - } - return Config{}, err - } - - cfg := fallback - cfg.AllowLocalhostBypassSource = detectBoolFieldSource(data, "allow_localhost_bypass") - if err := json.Unmarshal(data, &cfg); err != nil { - return Config{}, err - } - cfg.AllowedCIDRs = NormalizeCIDRs(cfg.AllowedCIDRs) - cfg.TrustedProxyCIDRs = NormalizeCIDRs(cfg.TrustedProxyCIDRs) - cfg.DashboardPasswordHash = strings.TrimSpace(cfg.DashboardPasswordHash) - cfg.LegacyLauncherToken = strings.TrimSpace(cfg.LegacyLauncherToken) - if err := Validate(cfg); err != nil { - return Config{}, err - } - return cfg, nil -} - -func detectBoolFieldSource(data []byte, field string) BoolFieldSource { - var raw map[string]json.RawMessage - if err := json.Unmarshal(data, &raw); err != nil { - return BoolFieldAbsent - } - - value, ok := raw[field] - if !ok { - return BoolFieldAbsent - } - - if string(value) == "null" { - return BoolFieldNull - } - - return BoolFieldPresent -} - -// Save writes launcher settings to disk. -func Save(path string, cfg Config) error { - cfg.AllowedCIDRs = NormalizeCIDRs(cfg.AllowedCIDRs) - cfg.TrustedProxyCIDRs = NormalizeCIDRs(cfg.TrustedProxyCIDRs) - cfg.DashboardPasswordHash = strings.TrimSpace(cfg.DashboardPasswordHash) - cfg.LegacyLauncherToken = "" - if err := Validate(cfg); err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return err - } - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return err - } - data = append(data, '\n') - return os.WriteFile(path, data, 0o600) -} diff --git a/web/backend/launcherconfig/config_test.go b/web/backend/launcherconfig/config_test.go deleted file mode 100644 index 090aaa6f..00000000 --- a/web/backend/launcherconfig/config_test.go +++ /dev/null @@ -1,257 +0,0 @@ -package launcherconfig - -import ( - "context" - "os" - "path/filepath" - "runtime" - "testing" -) - -func TestLoadReturnsFallbackWhenMissing(t *testing.T) { - path := filepath.Join(t.TempDir(), "launcher-config.json") - fallback := Default() - fallback.Port = 19999 - fallback.Public = true - - got, err := Load(path, fallback) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if got.Port != fallback.Port || got.Public != fallback.Public { - t.Fatalf("Load() = %+v, want %+v", got, fallback) - } - if !got.AllowLocalhostBypass { - t.Fatal("allow_localhost_bypass = false, want true") - } -} - -func TestSaveAndLoadRoundTrip(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "launcher-config.json") - want := Config{ - Port: 18080, - Public: true, - AllowedCIDRs: []string{"192.168.1.0/24", "10.0.0.0/8"}, - AllowLocalhostBypass: false, - TrustedProxyCIDRs: []string{"172.16.0.0/12"}, - DashboardPasswordHash: "$2a$12$saved-dashboard-password-hash", - LegacyLauncherToken: "legacy-token-should-not-persist", - } - - if err := Save(path, want); err != nil { - t.Fatalf("Save() error = %v", err) - } - got, err := Load(path, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if got.Port != want.Port || got.Public != want.Public { - t.Fatalf("Load() = %+v, want %+v", got, want) - } - if got.AllowLocalhostBypass != want.AllowLocalhostBypass { - t.Fatalf("allow_localhost_bypass = %t, want %t", got.AllowLocalhostBypass, want.AllowLocalhostBypass) - } - if got.DashboardPasswordHash != want.DashboardPasswordHash { - t.Fatalf("dashboard_password_hash = %q, want %q", got.DashboardPasswordHash, want.DashboardPasswordHash) - } - if got.LegacyLauncherToken != "" { - t.Fatalf("legacy launcher_token = %q, want empty after Save", got.LegacyLauncherToken) - } - if len(got.AllowedCIDRs) != len(want.AllowedCIDRs) { - t.Fatalf("allowed_cidrs len = %d, want %d", len(got.AllowedCIDRs), len(want.AllowedCIDRs)) - } - for i := range want.AllowedCIDRs { - if got.AllowedCIDRs[i] != want.AllowedCIDRs[i] { - t.Fatalf("allowed_cidrs[%d] = %q, want %q", i, got.AllowedCIDRs[i], want.AllowedCIDRs[i]) - } - } - if len(got.TrustedProxyCIDRs) != len(want.TrustedProxyCIDRs) { - t.Fatalf("trusted_proxy_cidrs len = %d, want %d", len(got.TrustedProxyCIDRs), len(want.TrustedProxyCIDRs)) - } - for i := range want.TrustedProxyCIDRs { - if got.TrustedProxyCIDRs[i] != want.TrustedProxyCIDRs[i] { - t.Fatalf("trusted_proxy_cidrs[%d] = %q, want %q", i, got.TrustedProxyCIDRs[i], want.TrustedProxyCIDRs[i]) - } - } - - stat, err := os.Stat(path) - if err != nil { - t.Fatalf("Stat() error = %v", err) - } - if perm := stat.Mode().Perm(); runtime.GOOS == "windows" { - if perm&0o200 == 0 { - t.Fatalf("file perm = %o, want owner-writable on Windows", perm) - } - } else if perm != 0o600 { - t.Fatalf("file perm = %o, want 600", perm) - } -} - -func TestLoadReadsLegacyLauncherTokenForMigration(t *testing.T) { - path := filepath.Join(t.TempDir(), "launcher-config.json") - if err := os.WriteFile(path, []byte(`{"port":18800,"launcher_token":"legacy-token"}`), 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - got, err := Load(path, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if got.LegacyLauncherToken != "legacy-token" { - t.Fatalf("legacy launcher_token = %q, want legacy-token", got.LegacyLauncherToken) - } -} - -func TestLoadDefaultsAllowLocalhostBypassForLegacyConfig(t *testing.T) { - path := filepath.Join(t.TempDir(), "launcher-config.json") - if err := os.WriteFile(path, []byte(`{"port":18800,"allowed_cidrs":["10.0.0.0/8"]}`), 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - got, err := Load(path, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if !got.AllowLocalhostBypass { - t.Fatal("allow_localhost_bypass = false, want true for legacy config") - } - if got.AllowLocalhostBypassSource != BoolFieldAbsent { - t.Fatalf("allow_localhost_bypass source = %v, want %v", got.AllowLocalhostBypassSource, BoolFieldAbsent) - } -} - -func TestLoadTracksAllowLocalhostBypassSource(t *testing.T) { - tests := []struct { - name string - body string - wantValue bool - wantSource BoolFieldSource - }{ - { - name: "explicit true", - body: `{"port":18800,"allow_localhost_bypass":true}`, - wantValue: true, - wantSource: BoolFieldPresent, - }, - { - name: "explicit false", - body: `{"port":18800,"allow_localhost_bypass":false}`, - wantValue: false, - wantSource: BoolFieldPresent, - }, - { - name: "explicit null keeps fallback behavior", - body: `{"port":18800,"allow_localhost_bypass":null}`, - wantValue: true, - wantSource: BoolFieldNull, - }, - { - name: "omitted uses fallback", - body: `{"port":18800}`, - wantValue: true, - wantSource: BoolFieldAbsent, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "launcher-config.json") - if err := os.WriteFile(path, []byte(tt.body), 0o600); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - got, err := Load(path, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if got.AllowLocalhostBypass != tt.wantValue { - t.Fatalf("allow_localhost_bypass = %t, want %t", got.AllowLocalhostBypass, tt.wantValue) - } - if got.AllowLocalhostBypassSource != tt.wantSource { - t.Fatalf("allow_localhost_bypass source = %v, want %v", got.AllowLocalhostBypassSource, tt.wantSource) - } - }) - } -} - -func TestValidateRejectsInvalidPort(t *testing.T) { - if err := Validate(Config{Port: 0, Public: false}); err == nil { - t.Fatal("Validate() expected error for port 0") - } - if err := Validate(Config{Port: 65536, Public: false}); err == nil { - t.Fatal("Validate() expected error for port 65536") - } -} - -func TestValidateRejectsInvalidCIDR(t *testing.T) { - err := Validate(Config{ - Port: 18800, - AllowedCIDRs: []string{"192.168.1.0/24", "not-a-cidr"}, - }) - if err == nil { - t.Fatal("Validate() expected error for invalid CIDR") - } -} - -func TestValidateRejectsInvalidTrustedProxyCIDR(t *testing.T) { - err := Validate(Config{ - Port: 18800, - TrustedProxyCIDRs: []string{"not-a-cidr"}, - }) - if err == nil { - t.Fatal("Validate() expected error for invalid trusted proxy CIDR") - } -} - -func TestNormalizeCIDRs(t *testing.T) { - got := NormalizeCIDRs([]string{" 192.168.1.0/24 ", "", "10.0.0.0/8", "192.168.1.0/24"}) - want := []string{"192.168.1.0/24", "10.0.0.0/8"} - if len(got) != len(want) { - t.Fatalf("len(got) = %d, want %d", len(got), len(want)) - } - for i := range want { - if got[i] != want[i] { - t.Fatalf("got[%d] = %q, want %q", i, got[i], want[i]) - } - } -} - -func TestPasswordStoreSetAndVerify(t *testing.T) { - path := filepath.Join(t.TempDir(), "launcher-config.json") - store := NewPasswordStore(path, Default()) - ctx := context.Background() - - initialized, err := store.IsInitialized(ctx) - if err != nil { - t.Fatalf("IsInitialized() error = %v", err) - } - if initialized { - t.Fatal("IsInitialized() = true, want false before SetPassword") - } - - if err = store.SetPassword(ctx, "dashboard-password"); err != nil { - t.Fatalf("SetPassword() error = %v", err) - } - initialized, err = store.IsInitialized(ctx) - if err != nil { - t.Fatalf("IsInitialized() after SetPassword error = %v", err) - } - if !initialized { - t.Fatal("IsInitialized() = false, want true after SetPassword") - } - ok, err := store.VerifyPassword(ctx, "dashboard-password") - if err != nil { - t.Fatalf("VerifyPassword() error = %v", err) - } - if !ok { - t.Fatal("VerifyPassword(correct) = false, want true") - } - ok, err = store.VerifyPassword(ctx, "wrong-password") - if err != nil { - t.Fatalf("VerifyPassword(wrong) error = %v", err) - } - if ok { - t.Fatal("VerifyPassword(wrong) = true, want false") - } -} diff --git a/web/backend/launcherconfig/migration.go b/web/backend/launcherconfig/migration.go deleted file mode 100644 index 66caa73a..00000000 --- a/web/backend/launcherconfig/migration.go +++ /dev/null @@ -1,62 +0,0 @@ -package launcherconfig - -import ( - "context" - "strings" -) - -var ( - loadConfigForMigration = Load - saveConfigForMigration = Save -) - -type dashboardPasswordStore interface { - IsInitialized(ctx context.Context) (bool, error) - SetPassword(ctx context.Context, plain string) error -} - -// LegacyLauncherTokenMigrationResult reports the outcome of converting a -// removed launcher_token value into the current password-based auth flow. -type LegacyLauncherTokenMigrationResult struct { - Migrated bool - // CleanupErr is non-nil when password migration succeeded (or was already in - // place) but removing launcher_token from launcher-config.json failed. - CleanupErr error -} - -// MigrateLegacyLauncherToken converts the removed launcher_token setting into -// the current password-login store, then removes launcher_token from config. -func MigrateLegacyLauncherToken( - ctx context.Context, - store dashboardPasswordStore, - launcherPath string, - fallback Config, -) (LegacyLauncherTokenMigrationResult, error) { - legacyToken := strings.TrimSpace(fallback.LegacyLauncherToken) - if legacyToken == "" || store == nil { - return LegacyLauncherTokenMigrationResult{}, nil - } - - result := LegacyLauncherTokenMigrationResult{} - initialized, err := store.IsInitialized(ctx) - if err != nil { - return result, err - } - if !initialized { - if err = store.SetPassword(ctx, legacyToken); err != nil { - return result, err - } - result.Migrated = true - } - result.CleanupErr = cleanupLegacyLauncherTokenConfig(launcherPath, fallback) - return result, nil -} - -func cleanupLegacyLauncherTokenConfig(launcherPath string, fallback Config) error { - cfg, err := loadConfigForMigration(launcherPath, fallback) - if err != nil { - return err - } - cfg.LegacyLauncherToken = "" - return saveConfigForMigration(launcherPath, cfg) -} diff --git a/web/backend/launcherconfig/migration_test.go b/web/backend/launcherconfig/migration_test.go deleted file mode 100644 index c5c5fa2c..00000000 --- a/web/backend/launcherconfig/migration_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package launcherconfig - -import ( - "context" - "errors" - "os" - "path/filepath" - "testing" -) - -type stubMigrationPasswordStore struct { - initialized bool - password string -} - -func (s *stubMigrationPasswordStore) IsInitialized(context.Context) (bool, error) { - return s.initialized, nil -} - -func (s *stubMigrationPasswordStore) SetPassword(_ context.Context, plain string) error { - s.password = plain - s.initialized = true - return nil -} - -func TestMigrateLegacyLauncherToken(t *testing.T) { - dir := t.TempDir() - launcherPath := filepath.Join(dir, FileName) - cfg := Config{ - Port: DefaultPort, - LegacyLauncherToken: "legacy-password", - } - if err := os.WriteFile( - launcherPath, - []byte("{\n \"port\": 18800,\n \"launcher_token\": \"legacy-password\"\n}\n"), - 0o600, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - store := NewPasswordStore(launcherPath, Default()) - result, err := MigrateLegacyLauncherToken(context.Background(), store, launcherPath, cfg) - if err != nil { - t.Fatalf("MigrateLegacyLauncherToken() error = %v", err) - } - if !result.Migrated { - t.Fatal("MigrateLegacyLauncherToken().Migrated = false, want true") - } - if result.CleanupErr != nil { - t.Fatalf("MigrateLegacyLauncherToken().CleanupErr = %v, want nil", result.CleanupErr) - } - - loaded, err := Load(launcherPath, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if loaded.LegacyLauncherToken != "" { - t.Fatalf("legacy launcher token = %q, want empty", loaded.LegacyLauncherToken) - } - if loaded.DashboardPasswordHash == "" { - t.Fatal("dashboard password hash should be set after migration") - } - ok, err := store.VerifyPassword(context.Background(), "legacy-password") - if err != nil { - t.Fatalf("VerifyPassword() error = %v", err) - } - if !ok { - t.Fatal("VerifyPassword() = false, want true") - } -} - -func TestMigrateLegacyLauncherTokenCleanupFailureIsNonFatal(t *testing.T) { - dir := t.TempDir() - launcherPath := filepath.Join(dir, FileName) - cfg := Config{ - Port: DefaultPort, - LegacyLauncherToken: "legacy-password", - } - if err := os.WriteFile( - launcherPath, - []byte("{\n \"port\": 18800,\n \"launcher_token\": \"legacy-password\"\n}\n"), - 0o600, - ); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - store := &stubMigrationPasswordStore{} - origSave := saveConfigForMigration - saveConfigForMigration = func(string, Config) error { - return errors.New("write launcher config") - } - t.Cleanup(func() { - saveConfigForMigration = origSave - }) - - result, err := MigrateLegacyLauncherToken(context.Background(), store, launcherPath, cfg) - if err != nil { - t.Fatalf("MigrateLegacyLauncherToken() error = %v, want nil", err) - } - if !result.Migrated { - t.Fatal("MigrateLegacyLauncherToken().Migrated = false, want true") - } - if result.CleanupErr == nil { - t.Fatal("MigrateLegacyLauncherToken().CleanupErr = nil, want non-nil") - } - if store.password != "legacy-password" { - t.Fatalf("password = %q, want legacy-password", store.password) - } - - loaded, err := Load(launcherPath, Default()) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if loaded.LegacyLauncherToken != "legacy-password" { - t.Fatalf( - "legacy launcher token = %q, want legacy-password after cleanup failure", - loaded.LegacyLauncherToken, - ) - } -} - -func TestMigrateLegacyLauncherTokenNoopWithoutToken(t *testing.T) { - launcherPath := filepath.Join(t.TempDir(), FileName) - store := NewPasswordStore(launcherPath, Default()) - result, err := MigrateLegacyLauncherToken(context.Background(), store, launcherPath, Default()) - if err != nil { - t.Fatalf("MigrateLegacyLauncherToken() error = %v", err) - } - if result.Migrated { - t.Fatal("MigrateLegacyLauncherToken().Migrated = true, want false") - } - if result.CleanupErr != nil { - t.Fatalf("MigrateLegacyLauncherToken().CleanupErr = %v, want nil", result.CleanupErr) - } -} diff --git a/web/backend/launcherconfig/password_store.go b/web/backend/launcherconfig/password_store.go deleted file mode 100644 index 3813384b..00000000 --- a/web/backend/launcherconfig/password_store.go +++ /dev/null @@ -1,92 +0,0 @@ -package launcherconfig - -import ( - "context" - "errors" - "strings" - "sync" - - "golang.org/x/crypto/bcrypt" -) - -const passwordBcryptCost = 12 - -// PasswordStore keeps the dashboard bcrypt hash in launcher-config.json. -// It is used on platforms where the SQLite-backed dashboard auth store is not -// available. -type PasswordStore struct { - path string - fallback Config - mu sync.Mutex -} - -// NewPasswordStore returns a config-backed password store. -func NewPasswordStore(path string, fallback Config) *PasswordStore { - return &PasswordStore{ - path: path, - fallback: fallback, - } -} - -// IsInitialized reports whether a dashboard password hash exists in config. -func (s *PasswordStore) IsInitialized(ctx context.Context) (bool, error) { - if err := ctx.Err(); err != nil { - return false, err - } - cfg, err := s.load() - if err != nil { - return false, err - } - return strings.TrimSpace(cfg.DashboardPasswordHash) != "", nil -} - -// SetPassword hashes plain with bcrypt and writes it to launcher-config.json. -func (s *PasswordStore) SetPassword(ctx context.Context, plain string) error { - if err := ctx.Err(); err != nil { - return err - } - if len([]rune(plain)) == 0 { - return errors.New("password must not be empty") - } - hash, err := bcrypt.GenerateFromPassword([]byte(plain), passwordBcryptCost) - if err != nil { - return err - } - - s.mu.Lock() - defer s.mu.Unlock() - - cfg, err := Load(s.path, s.fallback) - if err != nil { - return err - } - cfg.DashboardPasswordHash = string(hash) - cfg.LegacyLauncherToken = "" - return Save(s.path, cfg) -} - -// VerifyPassword returns true iff plain matches the stored bcrypt hash. -func (s *PasswordStore) VerifyPassword(ctx context.Context, plain string) (bool, error) { - if err := ctx.Err(); err != nil { - return false, err - } - cfg, err := s.load() - if err != nil { - return false, err - } - hash := strings.TrimSpace(cfg.DashboardPasswordHash) - if hash == "" { - return false, nil - } - err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) - if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { - return false, nil - } - return err == nil, err -} - -func (s *PasswordStore) load() (Config, error) { - s.mu.Lock() - defer s.mu.Unlock() - return Load(s.path, s.fallback) -} diff --git a/web/backend/main.go b/web/backend/main.go deleted file mode 100644 index 698e582e..00000000 --- a/web/backend/main.go +++ /dev/null @@ -1,774 +0,0 @@ -// PicoClaw Web Console - Web-based chat and management interface -// -// Provides a web UI for chatting with PicoClaw via the Pico Channel WebSocket, -// with configuration management and gateway process control. -// -// Usage: -// -// go build -o picoclaw-web ./web/backend/ -// ./picoclaw-web [config.json] -// ./picoclaw-web -public config.json - -package main - -import ( - "context" - "errors" - "flag" - "fmt" - "net" - "net/http" - "os" - "os/signal" - "path/filepath" - "strconv" - "strings" - "syscall" - "time" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/netbind" - "github.com/sipeed/picoclaw/web/backend/api" - "github.com/sipeed/picoclaw/web/backend/dashboardauth" - "github.com/sipeed/picoclaw/web/backend/launcherconfig" - "github.com/sipeed/picoclaw/web/backend/middleware" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -const ( - appName = "PicoClaw" - - logPath = "logs" - panicFile = "launcher_panic.log" - logFile = "launcher.log" -) - -var ( - appVersion = config.Version - - servers []*http.Server - serverAddr string - // browserLaunchURL is opened by openBrowser() (auto-open + tray "open console"). - browserLaunchURL string - apiHandler *api.Handler - - noBrowser *bool -) - -func shouldEnableLauncherFileLogging(enableConsole, debug bool) bool { - return !enableConsole || debug -} - -func shouldEnableLocalAutoLogin(noBrowser bool, probeHost string) bool { - return !noBrowser && isLoopbackLaunchHost(probeHost) -} - -func isLoopbackLaunchHost(host string) bool { - host = strings.TrimSpace(host) - if strings.EqualFold(host, "localhost") { - return true - } - host = strings.Trim(host, "[]") - if i := strings.LastIndex(host, "%"); i >= 0 { - host = host[:i] - } - ip := net.ParseIP(host) - return ip != nil && ip.IsLoopback() -} - -func launcherBrowserLaunchSuffix( - needsSetup bool, - localAutoLogin *middleware.LauncherDashboardLocalAutoLogin, -) string { - if needsSetup { - return middleware.LauncherDashboardSetupPath - } - if localAutoLogin != nil { - return localAutoLogin.URLPath() - } - return "" -} - -func resolveLauncherHostInput(flagHost string, explicitFlag bool, envHost string) (string, bool, error) { - if explicitFlag { - normalized, err := netbind.NormalizeHostInput(flagHost) - if err != nil { - return "", false, err - } - return normalized, true, nil - } - - envHost = strings.TrimSpace(envHost) - if envHost == "" { - return "", false, nil - } - - normalized, err := netbind.NormalizeHostInput(envHost) - if err != nil { - return "", false, err - } - return normalized, true, nil -} - -func openLauncherListeners(hostInput string, public bool, port string) (netbind.OpenResult, error) { - defaultMode := netbind.DefaultLoopback - if strings.TrimSpace(hostInput) == "" && public { - defaultMode = netbind.DefaultAny - } - - plan, err := netbind.BuildPlan(hostInput, defaultMode) - if err != nil { - return netbind.OpenResult{}, err - } - return netbind.OpenPlan(plan, port) -} - -func appendUniqueHost(hosts []string, seen map[string]struct{}, host string) []string { - host = strings.TrimSpace(host) - if host == "" { - return hosts - } - key := strings.ToLower(host) - if _, ok := seen[key]; ok { - return hosts - } - seen[key] = struct{}{} - return append(hosts, host) -} - -func hasWildcardBindHosts(bindHosts []string) bool { - for _, bindHost := range bindHosts { - if netbind.IsUnspecifiedHost(bindHost) { - return true - } - } - return false -} - -func wildcardBindHostFamilies(bindHosts []string) (hasIPv4, hasIPv6 bool) { - for _, bindHost := range bindHosts { - host := strings.TrimSpace(bindHost) - if host == "" { - continue - } - - if !netbind.IsUnspecifiedHost(host) { - continue - } - - ip := net.ParseIP(strings.Trim(host, "[]")) - if ip == nil { - continue - } - if ip.To4() != nil { - hasIPv4 = true - continue - } - hasIPv6 = true - } - - return hasIPv4, hasIPv6 -} - -func wildcardAdvertiseIP(bindHosts []string, ipv4, ipv6 string) string { - hasIPv4Wildcard, hasIPv6Wildcard := wildcardBindHostFamilies(bindHosts) - v4 := strings.TrimSpace(ipv4) - v6 := strings.TrimSpace(ipv6) - - switch { - case hasIPv4Wildcard && hasIPv6Wildcard: - if v6 != "" { - return v6 - } - return v4 - case hasIPv6Wildcard: - return v6 - case hasIPv4Wildcard: - return v4 - default: - return "" - } -} - -func advertiseIPForWildcardBindHosts(bindHosts []string) string { - return wildcardAdvertiseIP(bindHosts, utils.GetLocalIPv4(), utils.GetLocalIPv6()) -} - -func appendLauncherConsoleHostList(hosts []string, seen map[string]struct{}, values []string) []string { - for _, value := range values { - hosts = appendUniqueHost(hosts, seen, value) - } - return hosts -} - -func shouldShowLocalhostConsoleEntry(hostInput string) bool { - normalizedHostInput := strings.TrimSpace(hostInput) - if normalizedHostInput == "" { - return true - } - - for token := range strings.SplitSeq(normalizedHostInput, ",") { - token = strings.TrimSpace(token) - if token == "" { - continue - } - if token == "*" || strings.EqualFold(token, "localhost") { - return true - } - - ip := net.ParseIP(strings.Trim(token, "[]")) - if ip == nil { - continue - } - if ip4 := ip.To4(); ip4 != nil { - if ip4.String() == "127.0.0.1" || ip4.String() == "0.0.0.0" { - return true - } - continue - } - if ip.String() == "::1" || ip.String() == "::" { - return true - } - } - - return false -} - -func isConsoleDisplayGlobalIPv6(ip net.IP) bool { - if ip == nil || ip.IsLoopback() || ip.To4() != nil { - return false - } - ip = ip.To16() - if ip == nil { - return false - } - return ip[0]&0xe0 == 0x20 -} - -func launcherConsoleHostsWithLocalAddrs( - hostInput string, - public bool, - ipv4s []string, - globalIPv6s []string, -) []string { - hosts := make([]string, 0, 8) - seen := make(map[string]struct{}, 8) - - if shouldShowLocalhostConsoleEntry(hostInput) { - hosts = appendUniqueHost(hosts, seen, "localhost") - } - - normalizedHostInput := strings.TrimSpace(hostInput) - if normalizedHostInput == "" { - if public { - hosts = appendLauncherConsoleHostList(hosts, seen, globalIPv6s) - hosts = appendLauncherConsoleHostList(hosts, seen, ipv4s) - } - return hosts - } - - hasStar := false - hasIPv4Any := false - hasIPv6Any := false - for _, token := range strings.Split(normalizedHostInput, ",") { - switch strings.TrimSpace(token) { - case "*": - hasStar = true - case "0.0.0.0": - hasIPv4Any = true - case "::": - hasIPv6Any = true - } - } - - if hasStar { - hosts = appendLauncherConsoleHostList(hosts, seen, globalIPv6s) - hosts = appendLauncherConsoleHostList(hosts, seen, ipv4s) - return hosts - } - - for _, token := range strings.Split(normalizedHostInput, ",") { - token = strings.TrimSpace(token) - if token == "" || strings.EqualFold(token, "localhost") || netbind.IsLoopbackHost(token) { - continue - } - - ip := net.ParseIP(strings.Trim(token, "[]")) - switch { - case token == "::": - hosts = appendLauncherConsoleHostList(hosts, seen, globalIPv6s) - case token == "0.0.0.0": - hosts = appendLauncherConsoleHostList(hosts, seen, ipv4s) - case ip != nil && ip.To4() != nil: - if hasIPv4Any { - continue - } - hosts = appendUniqueHost(hosts, seen, ip.String()) - case ip != nil: - if hasIPv6Any { - continue - } - if isConsoleDisplayGlobalIPv6(ip) { - hosts = appendUniqueHost(hosts, seen, ip.String()) - } - default: - hosts = appendUniqueHost(hosts, seen, token) - } - } - - return hosts -} - -func launcherConsoleHosts(hostInput string, public bool) []string { - return launcherConsoleHostsWithLocalAddrs( - hostInput, - public, - utils.GetLocalIPv4s(), - utils.GetGlobalIPv6s(), - ) -} - -func firstNonEmpty(values ...string) string { - for _, value := range values { - value = strings.TrimSpace(value) - if value != "" { - return value - } - } - return "" -} - -type launcherAllowlistBypassLogDecision struct { - level logger.LogLevel - message string - emit bool -} - -func launcherBindMayExposeBeyondLoopback(hostInput string, public bool) bool { - normalizedHostInput := strings.TrimSpace(hostInput) - if normalizedHostInput == "" { - return public - } - - for token := range strings.SplitSeq(normalizedHostInput, ",") { - token = strings.TrimSpace(token) - if token == "" { - continue - } - if token == "*" || netbind.IsUnspecifiedHost(token) { - return true - } - if strings.EqualFold(token, "localhost") || netbind.IsLoopbackHost(token) { - continue - } - return true - } - - return false -} - -func launcherAllowlistBypassLogPolicy( - hostInput string, - public bool, - cfg launcherconfig.Config, -) launcherAllowlistBypassLogDecision { - if !launcherBindMayExposeBeyondLoopback(hostInput, public) || len(cfg.AllowedCIDRs) == 0 { - return launcherAllowlistBypassLogDecision{} - } - - switch cfg.AllowLocalhostBypassSource { - case launcherconfig.BoolFieldPresent: - if cfg.AllowLocalhostBypass { - return launcherAllowlistBypassLogDecision{ - level: logger.INFO, - emit: true, - message: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=true; same-host proxies or tunnels can bypass CIDR restrictions", - } - } - case launcherconfig.BoolFieldNull: - return launcherAllowlistBypassLogDecision{ - level: logger.WARN, - emit: true, - message: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=null; default localhost bypass remains enabled, so same-host proxies or tunnels can bypass CIDR restrictions", - } - } - - return launcherAllowlistBypassLogDecision{} -} - -func main() { - port := flag.String("port", "18800", "Port to listen on") - host := flag.String("host", "", "Host to listen on (overrides -public when set)") - public := flag.Bool("public", false, "Listen on all interfaces (dual-stack) instead of localhost only") - noBrowser = flag.Bool("no-browser", false, "Do not auto-open browser on startup") - lang := flag.String("lang", "", "Language: en (English) or zh (Chinese). Default: auto-detect from system locale") - console := flag.Bool("console", false, "Console mode, no GUI") - - var debug bool - flag.BoolVar(&debug, "d", false, "Enable debug logging") - flag.BoolVar(&debug, "debug", false, "Enable debug logging") - - flag.Usage = func() { - fmt.Fprintf(os.Stderr, "%s Launcher - Web console and gateway manager\n\n", appName) - fmt.Fprintf(os.Stderr, "Usage: %s [options] [config.json]\n\n", os.Args[0]) - fmt.Fprintf(os.Stderr, "Arguments:\n") - fmt.Fprintf(os.Stderr, " config.json Path to the configuration file (default: ~/.picoclaw/config.json)\n\n") - fmt.Fprintf(os.Stderr, "Options:\n") - flag.PrintDefaults() - fmt.Fprintf(os.Stderr, "\nExamples:\n") - fmt.Fprintf(os.Stderr, " %s\n", os.Args[0]) - fmt.Fprintf(os.Stderr, " Use default config path in GUI mode\n") - fmt.Fprintf(os.Stderr, " %s ./config.json\n", os.Args[0]) - fmt.Fprintf(os.Stderr, " Specify a config file\n") - fmt.Fprintf( - os.Stderr, - " %s -public ./config.json\n", - os.Args[0], - ) - fmt.Fprintf(os.Stderr, " Allow access from other devices on the local network\n") - fmt.Fprintf(os.Stderr, " %s -host :: ./config.json\n", os.Args[0]) - fmt.Fprintf(os.Stderr, " Bind launcher host explicitly with exact host semantics\n") - fmt.Fprintf(os.Stderr, " %s -console -d ./config.json\n", os.Args[0]) - fmt.Fprintf(os.Stderr, " Run in the terminal with debug logs enabled\n") - } - flag.Parse() - - // Initialize logger - picoHome := utils.GetPicoclawHome() - - f := filepath.Join(picoHome, logPath, panicFile) - panicFunc, err := logger.InitPanic(f) - if err != nil { - panic(fmt.Sprintf("error initializing panic log: %v", err)) - } - defer panicFunc() - - enableConsole := *console - fileLoggingEnabled := shouldEnableLauncherFileLogging(enableConsole, debug) - if fileLoggingEnabled { - // GUI mode writes launcher logs to file. Debug mode keeps file logging enabled in console mode too. - if !debug { - logger.DisableConsole() - } - - f := filepath.Join(picoHome, logPath, logFile) - if err = logger.EnableFileLogging(f); err != nil { - panic(fmt.Sprintf("error enabling file logging: %v", err)) - } - defer logger.DisableFileLogging() - } - if debug { - logger.SetLevel(logger.DEBUG) - } - - // Set language from command line or auto-detect - if *lang != "" { - SetLanguage(*lang) - } - - // Resolve config path - configPath := utils.GetDefaultConfigPath() - if flag.NArg() > 0 { - configPath = flag.Arg(0) - } - - absPath, err := filepath.Abs(configPath) - if err != nil { - logger.Fatalf("Failed to resolve config path: %v", err) - } - err = utils.EnsureOnboarded(absPath) - if err != nil { - logger.Errorf("Warning: Failed to initialize %s config automatically: %v", appName, err) - } - if !debug { - logger.SetLevelFromString(config.ResolveGatewayLogLevel(absPath)) - } - - logger.InfoC("web", fmt.Sprintf("%s launcher starting (version %s)...", appName, appVersion)) - logger.InfoC("web", fmt.Sprintf("%s Home: %s", appName, picoHome)) - if debug { - logger.InfoC("web", "Debug mode enabled") - logger.DebugC( - "web", - fmt.Sprintf( - "Launcher flags: console=%t host=%q public=%t no_browser=%t config=%s", - enableConsole, - *host, - *public, - *noBrowser, - absPath, - ), - ) - } - - var explicitPort bool - var explicitPublic bool - var explicitHost bool - flag.Visit(func(f *flag.Flag) { - switch f.Name { - case "port": - explicitPort = true - case "host": - explicitHost = true - case "public": - explicitPublic = true - } - }) - - launcherPath := launcherconfig.PathForAppConfig(absPath) - launcherCfg, err := launcherconfig.Load(launcherPath, launcherconfig.Default()) - if err != nil { - logger.ErrorC("web", fmt.Sprintf("Warning: Failed to load %s: %v", launcherPath, err)) - launcherCfg = launcherconfig.Default() - } - - effectivePort := *port - effectivePublic := *public - if !explicitPort { - effectivePort = strconv.Itoa(launcherCfg.Port) - } - if !explicitPublic { - effectivePublic = launcherCfg.Public - } - envHost := strings.TrimSpace(os.Getenv(launcherconfig.EnvLauncherHost)) - - hostInput, hostOverrideActive, err := resolveLauncherHostInput(*host, explicitHost, envHost) - if err != nil { - logger.Fatalf("Invalid host %q: %v", firstNonEmpty(strings.TrimSpace(*host), envHost), err) - } - if hostOverrideActive { - effectivePublic = false - } - - if !explicitHost && hostOverrideActive { - logger.InfoC("web", "Using launcher host from environment PICOCLAW_LAUNCHER_HOST") - } - - if hostOverrideActive && explicitPublic { - logger.InfoC("web", "Ignoring -public because launcher host was explicitly set") - } - - if decision := launcherAllowlistBypassLogPolicy(hostInput, effectivePublic, launcherCfg); decision.emit { - switch decision.level { - case logger.WARN: - logger.WarnC("web", decision.message) - default: - logger.InfoC("web", decision.message) - } - } - - portNum, err := strconv.Atoi(effectivePort) - if err != nil || portNum < 1 || portNum > 65535 { - if err == nil { - err = errors.New("must be in range 1-65535") - } - logger.Fatalf("Invalid port %q: %v", effectivePort, err) - } - - openResult, err := openLauncherListeners(hostInput, effectivePublic, effectivePort) - if err != nil { - logger.Fatalf("Failed to open launcher listener(s): %v", err) - } - listeners := openResult.Listeners - - dashboardSessionCookie, dashErr := middleware.NewLauncherDashboardSessionCookie() - if dashErr != nil { - logger.Fatalf("Dashboard auth setup failed: %v", dashErr) - } - - // Open the bcrypt password store (creates the DB file on first run). - authStore, authStoreErr := dashboardauth.New(picoHome) - var passwordStore api.PasswordStore - if authStoreErr == nil { - passwordStore = authStore - defer authStore.Close() - } else if errors.Is(authStoreErr, dashboardauth.ErrUnsupportedPlatform) { - logger.InfoC( - "web", - fmt.Sprintf( - "Dashboard SQLite password store unavailable on this platform; using launcher-config password storage: %v", - authStoreErr, - ), - ) - passwordStore = launcherconfig.NewPasswordStore(launcherPath, launcherCfg) - authStoreErr = nil - } else { - logger.ErrorC("web", fmt.Sprintf("Warning: could not open auth store: %v", authStoreErr)) - } - - migrationResult, migrationErr := launcherconfig.MigrateLegacyLauncherToken( - context.Background(), - passwordStore, - launcherPath, - launcherCfg, - ) - if migrationErr != nil { - logger.Fatalf("Failed to migrate legacy launcher token to password login: %v", migrationErr) - } - if migrationResult.Migrated { - logger.InfoC("web", "Migrated legacy launcher token to dashboard password login") - } - if migrationResult.CleanupErr != nil { - logger.WarnC( - "web", - fmt.Sprintf( - "Legacy launcher token password migration succeeded, but failed to remove launcher_token from %s: %v", - launcherPath, - migrationResult.CleanupErr, - ), - ) - } - - var localAutoLogin *middleware.LauncherDashboardLocalAutoLogin - needsInitialSetup := false - if passwordStore != nil { - initialized, initErr := passwordStore.IsInitialized(context.Background()) - if initErr != nil { - logger.ErrorC("web", fmt.Sprintf("Warning: could not check dashboard password state: %v", initErr)) - } else if !initialized { - needsInitialSetup = true - } else if shouldEnableLocalAutoLogin(*noBrowser, openResult.ProbeHost) { - localAutoLogin, err = middleware.NewLauncherDashboardLocalAutoLogin(5 * time.Minute) - if err != nil { - logger.Fatalf("Failed to create local auto-login grant: %v", err) - } - } - } - - // Initialize Server components - mux := http.NewServeMux() - - api.RegisterLauncherAuthRoutes(mux, api.LauncherAuthRouteOpts{ - SessionCookie: dashboardSessionCookie, - PasswordStore: passwordStore, - StoreError: authStoreErr, - }) - - // API Routes (e.g. /api/status) - apiHandler = api.NewHandler(absPath) - apiHandler.SetDebug(debug) - if _, err = apiHandler.EnsurePicoChannel(); err != nil { - logger.ErrorC("web", fmt.Sprintf("Warning: failed to ensure pico channel on startup: %v", err)) - } - apiHandler.SetServerOptions(portNum, effectivePublic, explicitPublic, launcherCfg.AllowedCIDRs) - apiHandler.SetServerAccessOptions( - launcherCfg.AllowLocalhostBypass, - launcherCfg.TrustedProxyCIDRs, - ) - apiHandler.SetServerBindHost(hostInput, hostOverrideActive) - apiHandler.RegisterRoutes(mux) - - // Frontend Embedded Assets - registerEmbedRoutes(mux) - - accessControlledMux, err := middleware.IPAllowlist(middleware.IPAllowlistConfig{ - AllowedCIDRs: launcherCfg.AllowedCIDRs, - AllowLocalhostBypass: launcherCfg.AllowLocalhostBypass, - TrustedProxyCIDRs: launcherCfg.TrustedProxyCIDRs, - }, mux) - if err != nil { - logger.Fatalf("Invalid allowed CIDR configuration: %v", err) - } - - dashAuth := middleware.LauncherDashboardAuth(middleware.LauncherDashboardAuthConfig{ - ExpectedCookie: dashboardSessionCookie, - LocalAutoLogin: localAutoLogin, - }, accessControlledMux) - - // Apply middleware stack - handler := middleware.Recoverer( - middleware.Logger( - middleware.ReferrerPolicyNoReferrer( - middleware.JSONContentType(dashAuth), - ), - ), - ) - - // Print startup banner (console mode only). - if enableConsole || debug { - consoleHosts := launcherConsoleHosts(hostInput, effectivePublic) - - fmt.Print(utils.Banner) - fmt.Println() - if needsInitialSetup { - if *noBrowser { - fmt.Println(" First-time setup: open /launcher-setup to create the dashboard password.") - } else { - fmt.Println(" Launcher will open /launcher-setup automatically.") - } - fmt.Println() - } - fmt.Println(" Dashboard address:") - fmt.Println() - for _, host := range consoleHosts { - fmt.Printf(" >> http://%s <<\n", net.JoinHostPort(host, effectivePort)) - } - fmt.Println() - } - - // Log startup info to file - for _, ln := range listeners { - logger.InfoC("web", fmt.Sprintf("Server will listen on http://%s", ln.Addr().String())) - } - if hasWildcardBindHosts(openResult.BindHosts) { - if ip := advertiseIPForWildcardBindHosts(openResult.BindHosts); ip != "" { - logger.InfoC("web", fmt.Sprintf("Public access enabled at http://%s", net.JoinHostPort(ip, effectivePort))) - } - } - - // Share the local URL with the launcher runtime. - serverAddr = fmt.Sprintf("http://%s", net.JoinHostPort(openResult.ProbeHost, effectivePort)) - browserLaunchURL = serverAddr + launcherBrowserLaunchSuffix(needsInitialSetup, localAutoLogin) - - // Auto-open browser will be handled by the launcher runtime. - - // Auto-start gateway after backend starts listening. - go func() { - time.Sleep(1 * time.Second) - apiHandler.TryAutoStartGateway() - }() - - // Start the server(s) in goroutines. - servers = make([]*http.Server, 0, len(listeners)) - for _, ln := range listeners { - srv := &http.Server{Handler: handler} - servers = append(servers, srv) - - go func(s *http.Server, l net.Listener) { - logger.InfoC("web", fmt.Sprintf("Server listening on %s", l.Addr().String())) - if serveErr := s.Serve(l); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) { - logger.Fatalf("Server failed to start on %s: %v", l.Addr().String(), serveErr) - } - }(srv, ln) - } - - defer shutdownApp() - - // Start system tray or run in console mode - if enableConsole { - if !*noBrowser { - // Auto-open browser after systray is ready (if not disabled) - // Check no-browser flag via environment or pass as parameter if needed - if err := openBrowser(); err != nil { - logger.Errorf("Warning: Failed to auto-open browser: %v", err) - } - } - - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) - - // Main event loop - wait for signals or config changes - for { - select { - case <-sigChan: - logger.Info("Shutting down...") - - return - } - } - } else { - // GUI mode: start system tray - runTray() - } -} diff --git a/web/backend/main_test.go b/web/backend/main_test.go deleted file mode 100644 index 5795a46e..00000000 --- a/web/backend/main_test.go +++ /dev/null @@ -1,603 +0,0 @@ -package main - -import ( - "context" - "errors" - "io" - "net" - "net/http" - "strconv" - "strings" - "testing" - "time" - - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/pkg/netbind" - "github.com/sipeed/picoclaw/web/backend/launcherconfig" - "github.com/sipeed/picoclaw/web/backend/middleware" -) - -func TestShouldEnableLauncherFileLogging(t *testing.T) { - tests := []struct { - name string - enableConsole bool - debug bool - want bool - }{ - {name: "gui mode", enableConsole: false, debug: false, want: true}, - {name: "console mode", enableConsole: true, debug: false, want: false}, - {name: "debug gui mode", enableConsole: false, debug: true, want: true}, - {name: "debug console mode", enableConsole: true, debug: true, want: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := shouldEnableLauncherFileLogging(tt.enableConsole, tt.debug); got != tt.want { - t.Fatalf( - "shouldEnableLauncherFileLogging(%t, %t) = %t, want %t", - tt.enableConsole, - tt.debug, - got, - tt.want, - ) - } - }) - } -} - -func TestShouldEnableLocalAutoLogin(t *testing.T) { - tests := []struct { - name string - noBrowser bool - probeHost string - wantEnable bool - }{ - {name: "loopback localhost", probeHost: "localhost", wantEnable: true}, - {name: "loopback ipv4", probeHost: "127.0.0.1", wantEnable: true}, - {name: "loopback ipv6", probeHost: "::1", wantEnable: true}, - {name: "browser disabled", noBrowser: true, probeHost: "localhost", wantEnable: false}, - {name: "non-loopback host", probeHost: "192.168.1.50", wantEnable: false}, - {name: "non-loopback hostname", probeHost: "example.com", wantEnable: false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := shouldEnableLocalAutoLogin(tt.noBrowser, tt.probeHost); got != tt.wantEnable { - t.Fatalf( - "shouldEnableLocalAutoLogin(%t, %q) = %t, want %t", - tt.noBrowser, - tt.probeHost, - got, - tt.wantEnable, - ) - } - }) - } -} - -func TestLauncherBrowserLaunchSuffix(t *testing.T) { - autoLogin, err := middleware.NewLauncherDashboardLocalAutoLogin(time.Minute) - if err != nil { - t.Fatalf("NewLauncherDashboardLocalAutoLogin() error = %v", err) - } - - if got := launcherBrowserLaunchSuffix(true, autoLogin); got != middleware.LauncherDashboardSetupPath { - t.Fatalf("setup suffix = %q", got) - } - if got := launcherBrowserLaunchSuffix(false, autoLogin); !strings.HasPrefix(got, "/launcher-auto-login?nonce=") { - t.Fatalf("auto-login suffix = %q", got) - } - if got := launcherBrowserLaunchSuffix(false, nil); got != "" { - t.Fatalf("empty suffix = %q, want empty", got) - } -} - -func TestResolveLauncherHostInput(t *testing.T) { - tests := []struct { - name string - flagHost string - explicitFlag bool - envHost string - wantHost string - wantActive bool - wantErr bool - }{ - { - name: "flag host wins", - flagHost: "127.0.0.1", - explicitFlag: true, - envHost: "::", - wantHost: "127.0.0.1", - wantActive: true, - }, - {name: "env host used when flag absent", envHost: "127.0.0.1,::1", wantHost: "127.0.0.1,::1", wantActive: true}, - {name: "blank env ignored", envHost: " ", wantHost: "", wantActive: false}, - {name: "invalid flag rejected", flagHost: "127.0.0.1, ", explicitFlag: true, wantErr: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - gotHost, gotActive, err := resolveLauncherHostInput(tt.flagHost, tt.explicitFlag, tt.envHost) - if (err != nil) != tt.wantErr { - t.Fatalf("resolveLauncherHostInput() err = %v, wantErr %t", err, tt.wantErr) - } - if tt.wantErr { - return - } - if gotHost != tt.wantHost { - t.Fatalf("resolveLauncherHostInput() host = %q, want %q", gotHost, tt.wantHost) - } - if gotActive != tt.wantActive { - t.Fatalf("resolveLauncherHostInput() active = %t, want %t", gotActive, tt.wantActive) - } - }) - } -} - -func TestLauncherAllowlistBypassLogPolicy(t *testing.T) { - tests := []struct { - name string - hostInput string - public bool - cfg launcherconfig.Config - wantEmit bool - wantLevel logger.LogLevel - wantMessage string - }{ - { - name: "explicit true logs info", - public: true, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: true, - wantLevel: logger.INFO, - wantMessage: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=true; same-host proxies or tunnels can bypass CIDR restrictions", - }, - { - name: "explicit null logs warn", - public: true, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldNull, - }, - wantEmit: true, - wantLevel: logger.WARN, - wantMessage: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=null; default localhost bypass remains enabled, so same-host proxies or tunnels can bypass CIDR restrictions", - }, - { - name: "omitted field does not log", - public: true, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldAbsent, - }, - wantEmit: false, - }, - { - name: "not public does not log", - public: false, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: false, - }, - { - name: "empty cidrs does not log", - public: true, - cfg: launcherconfig.Config{ - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: false, - }, - { - name: "explicit false does not log", - public: true, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: false, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: false, - }, - { - name: "explicit any-host override still logs", - hostInput: "0.0.0.0", - public: false, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: true, - wantLevel: logger.INFO, - wantMessage: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=true; same-host proxies or tunnels can bypass CIDR restrictions", - }, - { - name: "explicit ipv6 any-host override still logs", - hostInput: "::", - public: false, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: true, - wantLevel: logger.INFO, - wantMessage: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=true; same-host proxies or tunnels can bypass CIDR restrictions", - }, - { - name: "explicit hostname override logs", - hostInput: "example.com", - public: false, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: true, - wantLevel: logger.INFO, - wantMessage: "Launcher public access uses allowed_cidrs with allow_localhost_bypass=true; same-host proxies or tunnels can bypass CIDR restrictions", - }, - { - name: "explicit loopback override does not log", - hostInput: "127.0.0.1", - public: false, - cfg: launcherconfig.Config{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - AllowLocalhostBypassSource: launcherconfig.BoolFieldPresent, - }, - wantEmit: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := launcherAllowlistBypassLogPolicy(tt.hostInput, tt.public, tt.cfg) - if got.emit != tt.wantEmit { - t.Fatalf("emit = %t, want %t", got.emit, tt.wantEmit) - } - if !tt.wantEmit { - return - } - if got.level != tt.wantLevel { - t.Fatalf("level = %v, want %v", got.level, tt.wantLevel) - } - if got.message != tt.wantMessage { - t.Fatalf("message = %q, want %q", got.message, tt.wantMessage) - } - }) - } -} - -func TestLauncherBindMayExposeBeyondLoopback(t *testing.T) { - tests := []struct { - name string - hostInput string - public bool - want bool - }{ - {name: "default loopback bind", public: false, want: false}, - {name: "default public bind", public: true, want: true}, - {name: "localhost override", hostInput: "localhost", want: false}, - {name: "ipv4 loopback override", hostInput: "127.0.0.1", want: false}, - {name: "ipv6 loopback override", hostInput: "::1", want: false}, - {name: "ipv4 wildcard override", hostInput: "0.0.0.0", want: true}, - {name: "ipv6 wildcard override", hostInput: "::", want: true}, - {name: "star override", hostInput: "*", want: true}, - {name: "hostname override", hostInput: "example.com", want: true}, - {name: "lan ip override", hostInput: "192.168.1.2", want: true}, - {name: "mixed hosts with non-loopback", hostInput: "127.0.0.1,192.168.1.2", want: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := launcherBindMayExposeBeyondLoopback(tt.hostInput, tt.public); got != tt.want { - t.Fatalf( - "launcherBindMayExposeBeyondLoopback(%q, %t) = %t, want %t", - tt.hostInput, - tt.public, - got, - tt.want, - ) - } - }) - } -} - -func TestLauncherConsoleHosts(t *testing.T) { - t.Run("default loopback shows localhost only", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "", - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) - - t.Run("explicit loopback hosts collapse to localhost", func(t *testing.T) { - tests := []struct { - name string - hostInput string - }{ - {name: "ipv6 loopback", hostInput: "::1"}, - {name: "ipv4 loopback", hostInput: "127.0.0.1"}, - {name: "localhost", hostInput: "localhost"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - tt.hostInput, - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) - } - }) - - t.Run("public wildcard shows localhost then ipv6 and ipv4", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "", - true, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost", "2001:db8::1", "2001:db8::2", "192.168.1.2", "10.0.0.8"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) - - t.Run("explicit ipv6 any shows localhost then ipv6 variants", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "::", - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost", "2001:db8::1", "2001:db8::2"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - - for _, host := range hosts { - if host == "::1" || host == "127.0.0.1" || strings.HasPrefix(strings.ToLower(host), "fe80:") { - t.Fatalf("hosts = %#v, loopback IPs must not be displayed", hosts) - } - } - }) - - t.Run("explicit ipv4 any shows localhost then lan ipv4", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "0.0.0.0", - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost", "192.168.1.2", "10.0.0.8"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) - - t.Run("explicit wildcard star shows localhost first", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "*", - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"localhost", "2001:db8::1", "2001:db8::2", "192.168.1.2", "10.0.0.8"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) - - t.Run("explicit multi-address binding without local tokens hides localhost", func(t *testing.T) { - hosts := launcherConsoleHostsWithLocalAddrs( - "192.168.1.2,10.0.0.8,2001:db8::1,2001:db8::2,fe80::1", - false, - []string{"192.168.1.2", "10.0.0.8"}, - []string{"2001:db8::1", "2001:db8::2"}, - ) - want := []string{"192.168.1.2", "10.0.0.8", "2001:db8::1", "2001:db8::2"} - if strings.Join(hosts, ",") != strings.Join(want, ",") { - t.Fatalf("hosts = %#v, want %#v", hosts, want) - } - }) -} - -func TestWildcardAdvertiseIP(t *testing.T) { - tests := []struct { - name string - bindHosts []string - ipv4 string - ipv6 string - want string - }{ - { - name: "ipv4 wildcard uses ipv4", - bindHosts: []string{"0.0.0.0"}, - ipv4: "192.168.1.2", - ipv6: "2001:db8::1", - want: "192.168.1.2", - }, - { - name: "dual wildcard prefers ipv6", - bindHosts: []string{"0.0.0.0", "::"}, - ipv4: "192.168.1.2", - ipv6: "2001:db8::1", - want: "2001:db8::1", - }, - { - name: "ipv6 wildcard uses ipv6", - bindHosts: []string{"::"}, - ipv4: "192.168.1.2", - ipv6: "2001:db8::1", - want: "2001:db8::1", - }, - { - name: "dual wildcard falls back to ipv4 when ipv6 missing", - bindHosts: []string{"0.0.0.0", "::"}, - ipv4: "192.168.1.2", - ipv6: "", - want: "192.168.1.2", - }, - { - name: "ipv6 wildcard without ipv6 does not advertise ipv4", - bindHosts: []string{"::"}, - ipv4: "192.168.1.2", - ipv6: "", - want: "", - }, - { - name: "non wildcard does not advertise", - bindHosts: []string{"127.0.0.1"}, - ipv4: "192.168.1.2", - ipv6: "2001:db8::1", - want: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := wildcardAdvertiseIP(tt.bindHosts, tt.ipv4, tt.ipv6); got != tt.want { - t.Fatalf("wildcardAdvertiseIP(%#v, %q, %q) = %q, want %q", tt.bindHosts, tt.ipv4, tt.ipv6, got, tt.want) - } - }) - } -} - -func TestOpenLauncherListeners_HonorsIPv6OnlyHost(t *testing.T) { - hasIPv4, hasIPv6 := netbind.DetectIPFamilies() - if !hasIPv6 { - t.Skip("IPv6 is unavailable in this environment") - } - - result, err := openLauncherListeners("::", false, "0") - if err != nil { - t.Fatalf("openLauncherListeners() error = %v", err) - } - startLauncherTestHTTPServer(t, result.Listeners) - port := mustAtoi(t, result.Port) - - requireLauncherHTTPReachable(t, "::1", port) - if hasIPv4 { - requireLauncherHTTPUnreachable(t, "127.0.0.1", port) - } -} - -func TestOpenLauncherListeners_SupportsExplicitMultiHost(t *testing.T) { - hasIPv4, hasIPv6 := netbind.DetectIPFamilies() - if !hasIPv4 || !hasIPv6 { - t.Skip("dual-stack loopback is unavailable in this environment") - } - - result, err := openLauncherListeners("127.0.0.1,::1", false, "0") - if err != nil { - t.Fatalf("openLauncherListeners() error = %v", err) - } - startLauncherTestHTTPServer(t, result.Listeners) - port := mustAtoi(t, result.Port) - - requireLauncherHTTPReachable(t, "127.0.0.1", port) - requireLauncherHTTPReachable(t, "::1", port) -} - -func startLauncherTestHTTPServer(t *testing.T, listeners []net.Listener) { - t.Helper() - - server := &http.Server{ - Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = io.WriteString(w, "ok") - }), - } - - errCh := make(chan error, len(listeners)) - for _, listener := range listeners { - ln := listener - go func() { - errCh <- server.Serve(ln) - }() - } - - t.Cleanup(func() { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - _ = server.Shutdown(ctx) - for range listeners { - err := <-errCh - if err != nil && !errors.Is(err, http.ErrServerClosed) { - t.Fatalf("server.Serve() error = %v", err) - } - } - }) -} - -func requireLauncherHTTPReachable(t *testing.T, host string, port int) { - t.Helper() - deadline := time.Now().Add(2 * time.Second) - for { - err := launcherHTTPGet(host, port) - if err == nil { - return - } - if time.Now().After(deadline) { - t.Fatalf("expected %s:%d to be reachable: %v", host, port, err) - } - time.Sleep(50 * time.Millisecond) - } -} - -func requireLauncherHTTPUnreachable(t *testing.T, host string, port int) { - t.Helper() - if err := launcherHTTPGet(host, port); err == nil { - t.Fatalf("expected %s:%d to be unreachable", host, port) - } -} - -func launcherHTTPGet(host string, port int) error { - client := &http.Client{ - Timeout: 300 * time.Millisecond, - Transport: &http.Transport{ - Proxy: nil, - }, - } - - resp, err := client.Get("http://" + net.JoinHostPort(host, strconv.Itoa(port))) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return errors.New(resp.Status) - } - return nil -} - -func mustAtoi(t *testing.T, value string) int { - t.Helper() - n, err := strconv.Atoi(value) - if err != nil { - t.Fatalf("Atoi(%q) error = %v", value, err) - } - return n -} diff --git a/web/backend/middleware/access_control.go b/web/backend/middleware/access_control.go deleted file mode 100644 index 13f68f0d..00000000 --- a/web/backend/middleware/access_control.go +++ /dev/null @@ -1,130 +0,0 @@ -package middleware - -import ( - "fmt" - "net" - "net/http" - "strings" -) - -// IPAllowlistConfig controls launcher network access decisions. -type IPAllowlistConfig struct { - AllowedCIDRs []string - AllowLocalhostBypass bool - TrustedProxyCIDRs []string -} - -// IPAllowlist restricts access to requests from configured CIDR ranges. -// Loopback addresses can optionally bypass CIDR checks for local administration. -// X-Forwarded-For is only trusted when the immediate peer is in a trusted CIDR. -// Empty CIDR list means no restriction. -func IPAllowlist(cfg IPAllowlistConfig, next http.Handler) (http.Handler, error) { - allowedNets, err := parseCIDRNets(cfg.AllowedCIDRs) - if err != nil { - return nil, err - } - trustedProxyNets, err := parseCIDRNets(cfg.TrustedProxyCIDRs) - if err != nil { - return nil, err - } - - if len(allowedNets) == 0 { - return next, nil - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - peerIP := clientIPFromRemoteAddr(r.RemoteAddr) - if peerIP == nil { - rejectByPolicy(w, r) - return - } - - ip := peerIP - if containsIP(trustedProxyNets, peerIP) { - ip = clientIPFromXForwardedFor(r.Header.Get("X-Forwarded-For"), trustedProxyNets, peerIP) - } - - if cfg.AllowLocalhostBypass && ip.IsLoopback() { - next.ServeHTTP(w, r) - return - } - if containsIP(allowedNets, ip) { - next.ServeHTTP(w, r) - return - } - - rejectByPolicy(w, r) - }), nil -} - -func parseCIDRNets(cidrs []string) ([]*net.IPNet, error) { - nets := make([]*net.IPNet, 0, len(cidrs)) - for _, cidr := range cidrs { - _, ipNet, err := net.ParseCIDR(cidr) - if err != nil { - return nil, fmt.Errorf("invalid CIDR %q: %w", cidr, err) - } - nets = append(nets, ipNet) - } - return nets, nil -} - -func containsIP(nets []*net.IPNet, ip net.IP) bool { - for _, ipNet := range nets { - if ipNet.Contains(ip) { - return true - } - } - return false -} - -func clientIPFromRemoteAddr(remoteAddr string) net.IP { - host := remoteAddr - if h, _, err := net.SplitHostPort(remoteAddr); err == nil { - host = h - } - return net.ParseIP(host) -} - -func clientIPFromXForwardedFor(header string, trustedProxyNets []*net.IPNet, fallback net.IP) net.IP { - parts := strings.Split(header, ",") - ips := make([]net.IP, 0, len(parts)) - for _, part := range parts { - if ip := parseIPToken(part); ip != nil { - ips = append(ips, ip) - } - } - if len(ips) == 0 { - return fallback - } - for i := len(ips) - 1; i >= 0; i-- { - if !containsIP(trustedProxyNets, ips[i]) { - return ips[i] - } - } - return ips[0] -} - -func parseIPToken(raw string) net.IP { - token := strings.Trim(strings.TrimSpace(raw), `"`) - if token == "" { - return nil - } - if ip := net.ParseIP(token); ip != nil { - return ip - } - if host, _, err := net.SplitHostPort(token); err == nil { - return net.ParseIP(host) - } - return nil -} - -func rejectByPolicy(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.URL.Path, "/api/") { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"error":"access denied by network policy"}`)) - return - } - http.Error(w, "Forbidden", http.StatusForbidden) -} diff --git a/web/backend/middleware/access_control_test.go b/web/backend/middleware/access_control_test.go deleted file mode 100644 index f046c783..00000000 --- a/web/backend/middleware/access_control_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestIPAllowlist_EmptyCIDRsAllowsAll(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "203.0.113.5:1234" - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func TestIPAllowlist_RejectsOutsideCIDR(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/api/config", nil) - req.RemoteAddr = "10.0.0.8:1234" - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) - } -} - -func TestIPAllowlist_AllowsInsideCIDR(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "192.168.1.88:1234" - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func TestIPAllowlist_AllowsLoopbackWhenBypassEnabled(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "127.0.0.1:1234" - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func TestIPAllowlist_RejectsLoopbackWhenBypassDisabled(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "127.0.0.1:1234" - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) - } -} - -func TestIPAllowlist_IgnoresXForwardedForFromUntrustedPeer(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - TrustedProxyCIDRs: []string{"10.0.0.0/8"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "203.0.113.5:1234" - req.Header.Set("X-Forwarded-For", "192.168.1.88") - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) - } -} - -func TestIPAllowlist_UsesRightmostUntrustedXForwardedForIPFromTrustedPeer(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - TrustedProxyCIDRs: []string{"10.0.0.0/8"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "10.0.0.8:1234" - req.Header.Set("X-Forwarded-For", "203.0.113.5, 192.168.1.88, 10.0.0.9") - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func TestIPAllowlist_UsesRightmostUntrustedIPFromTrustedProxyChain(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - TrustedProxyCIDRs: []string{"10.0.0.0/8"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "10.0.0.8:1234" - req.Header.Set("X-Forwarded-For", "192.168.1.88, 10.0.0.9, 10.0.0.10") - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) - } -} - -func TestIPAllowlist_DoesNotTrustSpoofedLeftmostLoopbackInXForwardedFor(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - AllowLocalhostBypass: true, - TrustedProxyCIDRs: []string{"10.0.0.0/8"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "10.0.0.8:1234" - req.Header.Set("X-Forwarded-For", "127.0.0.1, 203.0.113.5") - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) - } -} - -func TestIPAllowlist_AllTrustedProxyChainFallsBackToLeftmostIP(t *testing.T) { - h, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - TrustedProxyCIDRs: []string{"10.0.0.0/8"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - })) - if err != nil { - t.Fatalf("IPAllowlist() error = %v", err) - } - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.RemoteAddr = "10.0.0.8:1234" - req.Header.Set("X-Forwarded-For", "10.0.0.9, 10.0.0.10") - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusForbidden { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) - } -} - -func TestIPAllowlist_InvalidCIDR(t *testing.T) { - _, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"bad-cidr"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - if err == nil { - t.Fatal("IPAllowlist() expected error for invalid CIDR") - } -} - -func TestIPAllowlist_InvalidTrustedProxyCIDR(t *testing.T) { - _, err := IPAllowlist(IPAllowlistConfig{ - AllowedCIDRs: []string{"192.168.1.0/24"}, - TrustedProxyCIDRs: []string{"bad-cidr"}, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - if err == nil { - t.Fatal("IPAllowlist() expected error for invalid trusted proxy CIDR") - } -} diff --git a/web/backend/middleware/launcher_dashboard_auth.go b/web/backend/middleware/launcher_dashboard_auth.go deleted file mode 100644 index fd59958a..00000000 --- a/web/backend/middleware/launcher_dashboard_auth.go +++ /dev/null @@ -1,311 +0,0 @@ -package middleware - -import ( - "crypto/rand" - "crypto/subtle" - "encoding/base64" - "errors" - "net/http" - "net/url" - "path" - "strings" - "sync" - "time" -) - -// LauncherDashboardCookieName is the HttpOnly cookie set after a successful password login. -const LauncherDashboardCookieName = "picoclaw_launcher_auth" - -// launcherDashboardSessionMaxAgeSec is the dashboard session cookie lifetime (31 days). -const launcherDashboardSessionMaxAgeSec = 31 * 24 * 3600 - -const ( - launcherSessionCookieBytes = 32 - launcherGrantNonceBytes = 32 - // LauncherDashboardLocalAutoLoginPath is the one-shot local browser - // bootstrap endpoint used by the launcher-managed auto-open flow. - LauncherDashboardLocalAutoLoginPath = "/launcher-auto-login" - // LauncherDashboardSetupPath is the setup page used before the dashboard - // password is initialized. - LauncherDashboardSetupPath = "/launcher-setup" -) - -// NewLauncherDashboardSessionCookie creates the per-process session cookie value. -func NewLauncherDashboardSessionCookie() (string, error) { - return randomURLToken(launcherSessionCookieBytes) -} - -func randomURLToken(n int) (string, error) { - buf := make([]byte, n) - if _, err := rand.Read(buf); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(buf), nil -} - -// LauncherDashboardAuthConfig holds runtime material for dashboard access checks. -type LauncherDashboardAuthConfig struct { - ExpectedCookie string - // LocalAutoLogin enables one-shot startup auto-login. - LocalAutoLogin *LauncherDashboardLocalAutoLogin - // SecureCookie sets the session cookie's Secure flag. If nil, DefaultLauncherDashboardSecureCookie is used. - SecureCookie func(*http.Request) bool -} - -// LauncherDashboardLocalAutoLogin is an in-memory, one-shot startup grant. -// It is not a reusable credential; it only lets the launcher-opened browser -// receive the current process session cookie. -type LauncherDashboardLocalAutoLogin struct { - grant *launcherDashboardOneTimeGrant -} - -type launcherDashboardOneTimeGrant struct { - mu sync.Mutex - expires time.Time - consumed bool - nonce string - now func() time.Time -} - -// NewLauncherDashboardLocalAutoLogin creates a one-shot local auto-login grant. -func NewLauncherDashboardLocalAutoLogin(ttl time.Duration) (*LauncherDashboardLocalAutoLogin, error) { - grant, err := newLauncherDashboardOneTimeGrant(ttl) - if err != nil { - return nil, err - } - return &LauncherDashboardLocalAutoLogin{ - grant: grant, - }, nil -} - -// URLPath returns the one-shot local auto-login URL path including its nonce. -func (a *LauncherDashboardLocalAutoLogin) URLPath() string { - return launcherGrantQueryPath(LauncherDashboardLocalAutoLoginPath, a.grant) -} - -// DefaultLauncherDashboardSecureCookie mirrors typical production HTTPS detection (TLS or X-Forwarded-Proto). -func DefaultLauncherDashboardSecureCookie(r *http.Request) bool { - if r.TLS != nil { - return true - } - return strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") -} - -// SetLauncherDashboardSessionCookie writes the HttpOnly session cookie after successful dashboard password login. -func SetLauncherDashboardSessionCookie( - w http.ResponseWriter, - r *http.Request, - sessionValue string, - secure func(*http.Request) bool, -) { - if secure == nil { - secure = DefaultLauncherDashboardSecureCookie - } - http.SetCookie(w, &http.Cookie{ - Name: LauncherDashboardCookieName, - Value: sessionValue, - Path: "/", - MaxAge: launcherDashboardSessionMaxAgeSec, - HttpOnly: true, - SameSite: http.SameSiteLaxMode, - Secure: secure(r), - }) -} - -// ClearLauncherDashboardSessionCookie clears the dashboard session (e.g. logout). -func ClearLauncherDashboardSessionCookie(w http.ResponseWriter, r *http.Request, secure func(*http.Request) bool) { - if secure == nil { - secure = DefaultLauncherDashboardSecureCookie - } - http.SetCookie(w, &http.Cookie{ - Name: LauncherDashboardCookieName, - Value: "", - Path: "/", - MaxAge: -1, - HttpOnly: true, - SameSite: http.SameSiteLaxMode, - Secure: secure(r), - Expires: time.Unix(0, 0), - }) -} - -// LauncherDashboardAuth requires a valid session cookie before calling next. -// Public paths are login/setup pages and /api/auth/* handlers. -func LauncherDashboardAuth(cfg LauncherDashboardAuthConfig, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - p := canonicalAuthPath(r.URL.Path) - if p == LauncherDashboardLocalAutoLoginPath { - handleLauncherLocalAutoLogin(w, r, cfg) - return - } - if isPublicLauncherDashboardPath(r.Method, p) { - next.ServeHTTP(w, r) - return - } - if validLauncherDashboardAuth(r, cfg) { - next.ServeHTTP(w, r) - return - } - rejectLauncherDashboardAuth(w, r, p) - }) -} - -// canonicalAuthPath matches path cleaning used for routing decisions so -// prefixes like /assets/../ cannot bypass auth (CVE-class traversal). - -func handleLauncherLocalAutoLogin(w http.ResponseWriter, r *http.Request, cfg LauncherDashboardAuthConfig) { - if validLauncherDashboardAuth(r, cfg) { - http.Redirect(w, r, "/", http.StatusSeeOther) - return - } - if r.Method != http.MethodGet && r.Method != http.MethodHead { - w.WriteHeader(http.StatusMethodNotAllowed) - _, _ = w.Write([]byte("method not allowed")) - return - } - if r.Method == http.MethodHead { - rejectLauncherDashboardAuth(w, r, LauncherDashboardLocalAutoLoginPath) - return - } - if cfg.LocalAutoLogin != nil && cfg.LocalAutoLogin.consume(r.URL.Query().Get("nonce")) { - SetLauncherDashboardSessionCookie(w, r, cfg.ExpectedCookie, cfg.SecureCookie) - http.Redirect(w, r, "/", http.StatusSeeOther) - return - } - rejectLauncherDashboardAuth(w, r, LauncherDashboardLocalAutoLoginPath) -} - -func (a *LauncherDashboardLocalAutoLogin) consume(nonce string) bool { - if a == nil || a.grant == nil { - return false - } - return a.grant.use(nonce, nil) == nil -} - -func newLauncherDashboardOneTimeGrant(ttl time.Duration) (*launcherDashboardOneTimeGrant, error) { - nonce, err := randomURLToken(launcherGrantNonceBytes) - if err != nil { - return nil, err - } - return &launcherDashboardOneTimeGrant{ - expires: time.Now().Add(ttl), - nonce: nonce, - now: time.Now, - }, nil -} - -func launcherGrantQueryPath(basePath string, grant *launcherDashboardOneTimeGrant) string { - if grant == nil { - return basePath - } - return basePath + "?nonce=" + url.QueryEscape(grant.nonce) -} - -// ErrInvalidLauncherDashboardGrant reports that an auto-login grant is missing, -// expired, already consumed, or otherwise invalid. -var ErrInvalidLauncherDashboardGrant = errors.New("invalid launcher dashboard grant") - -func (g *launcherDashboardOneTimeGrant) use(nonce string, fn func() error) error { - if g == nil { - return ErrInvalidLauncherDashboardGrant - } - if len(nonce) != len(g.nonce) || - subtle.ConstantTimeCompare([]byte(nonce), []byte(g.nonce)) != 1 { - return ErrInvalidLauncherDashboardGrant - } - - g.mu.Lock() - defer g.mu.Unlock() - - now := time.Now - if g.now != nil { - now = g.now - } - if g.consumed || !now().Before(g.expires) { - return ErrInvalidLauncherDashboardGrant - } - if fn != nil { - if err := fn(); err != nil { - return err - } - } - g.consumed = true - return nil -} - -func canonicalAuthPath(raw string) string { - if raw == "" { - return "/" - } - c := path.Clean(raw) - switch c { - case ".", "": - return "/" - default: - if c[0] != '/' { - return "/" + c - } - return c - } -} - -func isPublicLauncherDashboardPath(method, p string) bool { - if isPublicLauncherDashboardStatic(method, p) { - return true - } - switch p { - case "/api/auth/login": - return method == http.MethodPost - case "/api/auth/logout": - return method == http.MethodPost - case "/api/auth/status": - return method == http.MethodGet - case "/api/auth/setup": - return method == http.MethodPost - } - return false -} - -// isPublicLauncherDashboardStatic allows the SPA login route and embedded -// frontend assets without a session (GET/HEAD only). -func isPublicLauncherDashboardStatic(method, p string) bool { - if method != http.MethodGet && method != http.MethodHead { - return false - } - if p == "/launcher-login" || p == "/launcher-setup" { - return true - } - if strings.HasPrefix(p, "/assets/") { - return true - } - switch p { - case "/favicon.ico", "/favicon.svg", "/favicon-96x96.png", - "/apple-touch-icon.png", "/site.webmanifest", "/robots.txt": - return true - default: - return false - } -} - -func validLauncherDashboardAuth(r *http.Request, cfg LauncherDashboardAuthConfig) bool { - if c, err := r.Cookie(LauncherDashboardCookieName); err == nil { - if subtle.ConstantTimeCompare([]byte(c.Value), []byte(cfg.ExpectedCookie)) == 1 { - return true - } - } - return false -} - -func rejectLauncherDashboardAuth(w http.ResponseWriter, r *http.Request, canonicalPath string) { - if canonicalPath == "/pico/ws" { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - if strings.HasPrefix(canonicalPath, "/api/") { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusUnauthorized) - _, _ = w.Write([]byte(`{"error":"unauthorized"}`)) - return - } - http.Redirect(w, r, "/launcher-login", http.StatusFound) -} diff --git a/web/backend/middleware/launcher_dashboard_auth_test.go b/web/backend/middleware/launcher_dashboard_auth_test.go deleted file mode 100644 index 871b6f60..00000000 --- a/web/backend/middleware/launcher_dashboard_auth_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -func TestNewLauncherDashboardSessionCookie(t *testing.T) { - a, err := NewLauncherDashboardSessionCookie() - if err != nil { - t.Fatalf("NewLauncherDashboardSessionCookie() error = %v", err) - } - b, err := NewLauncherDashboardSessionCookie() - if err != nil { - t.Fatalf("NewLauncherDashboardSessionCookie() second error = %v", err) - } - if a == "" || b == "" { - t.Fatalf("session cookie values should be non-empty: %q %q", a, b) - } - if a == b { - t.Fatal("session cookie values should be random") - } -} - -func mustLocalAutoLogin(t *testing.T, ttl time.Duration) *LauncherDashboardLocalAutoLogin { - t.Helper() - autoLogin, err := NewLauncherDashboardLocalAutoLogin(ttl) - if err != nil { - t.Fatalf("NewLauncherDashboardLocalAutoLogin() error = %v", err) - } - return autoLogin -} - -func TestLauncherDashboardAuth_AllowsPublicPaths(t *testing.T) { - cfg := LauncherDashboardAuthConfig{ExpectedCookie: "deadbeef"} - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - }) - h := LauncherDashboardAuth(cfg, next) - - for _, tc := range []struct { - method, path string - want int - }{ - {http.MethodGet, "/launcher-login", http.StatusTeapot}, - {http.MethodGet, "/launcher-setup", http.StatusTeapot}, - {http.MethodGet, "/assets/index.js", http.StatusTeapot}, - {http.MethodPost, "/api/auth/login", http.StatusTeapot}, - {http.MethodGet, "/api/auth/status", http.StatusTeapot}, - {http.MethodPost, "/api/auth/setup", http.StatusTeapot}, - {http.MethodPost, "/api/auth/logout", http.StatusTeapot}, - {http.MethodGet, "/api/auth/logout", http.StatusUnauthorized}, - {http.MethodGet, "/api/config", http.StatusUnauthorized}, - {http.MethodGet, "/pico/ws", http.StatusUnauthorized}, - } { - rec := httptest.NewRecorder() - req := httptest.NewRequest(tc.method, tc.path, nil) - h.ServeHTTP(rec, req) - if rec.Code != tc.want { - t.Fatalf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.want) - } - } -} - -func TestLauncherDashboardAuth_QueryTokenDoesNotAuthenticate(t *testing.T) { - cfg := LauncherDashboardAuthConfig{ExpectedCookie: "deadbeef"} - next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - t.Fatal("next handler should not run without session cookie") - }) - h := LauncherDashboardAuth(cfg, next) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/?token=secret", nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/launcher-login" { - t.Fatalf("GET /?token=secret: code=%d loc=%q", rec.Code, rec.Header().Get("Location")) - } -} - -func TestLauncherDashboardAuth_LocalAutoLogin(t *testing.T) { - const cookieVal = "session-cookie-value" - autoLogin := mustLocalAutoLogin(t, time.Minute) - cfg := LauncherDashboardAuthConfig{ - ExpectedCookie: cookieVal, - LocalAutoLogin: autoLogin, - } - next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - }) - h := LauncherDashboardAuth(cfg, next) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, LauncherDashboardLocalAutoLoginPath, nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/launcher-login" || - len(rec.Result().Cookies()) != 0 { - t.Fatalf( - "auto-login without nonce code=%d loc=%q cookies=%#v", - rec.Code, - rec.Header().Get("Location"), - rec.Result().Cookies(), - ) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, LauncherDashboardLocalAutoLoginPath+"?nonce=wrong", nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/launcher-login" || - len(rec.Result().Cookies()) != 0 { - t.Fatalf( - "auto-login with wrong nonce code=%d loc=%q cookies=%#v", - rec.Code, - rec.Header().Get("Location"), - rec.Result().Cookies(), - ) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodHead, autoLogin.URLPath(), nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/launcher-login" || - len(rec.Result().Cookies()) != 0 { - t.Fatalf( - "auto-login HEAD code=%d loc=%q cookies=%#v", - rec.Code, - rec.Header().Get("Location"), - rec.Result().Cookies(), - ) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, autoLogin.URLPath(), nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/" { - t.Fatalf("local auto-login code=%d loc=%q", rec.Code, rec.Header().Get("Location")) - } - cookies := rec.Result().Cookies() - if len(cookies) != 1 || cookies[0].Name != LauncherDashboardCookieName || cookies[0].Value != cookieVal { - t.Fatalf("cookies = %#v", cookies) - } - if cookies[0].MaxAge != 31*24*3600 { - t.Fatalf("session cookie MaxAge = %d, want 31 days", cookies[0].MaxAge) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, "/", nil) - req.AddCookie(&http.Cookie{Name: LauncherDashboardCookieName, Value: cookieVal}) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("cookie auth after auto-login status = %d", rec.Code) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, autoLogin.URLPath(), nil) - req.AddCookie(&http.Cookie{Name: LauncherDashboardCookieName, Value: cookieVal}) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/" { - t.Fatalf("auto-login path with existing session code=%d loc=%q", rec.Code, rec.Header().Get("Location")) - } - - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, autoLogin.URLPath(), nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/launcher-login" { - t.Fatalf("consumed auto-login code=%d loc=%q", rec.Code, rec.Header().Get("Location")) - } -} - -func TestLauncherDashboardAuth_LocalAutoLoginRequiresValidNonceAndUnexpired(t *testing.T) { - const cookieVal = "session-cookie-value" - newHandler := func(autoLogin *LauncherDashboardLocalAutoLogin) http.Handler { - return LauncherDashboardAuth(LauncherDashboardAuthConfig{ - ExpectedCookie: cookieVal, - LocalAutoLogin: autoLogin, - }, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - })) - } - - autoLogin := mustLocalAutoLogin(t, time.Minute) - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, autoLogin.URLPath(), nil) - req.RemoteAddr = "192.168.1.50:12345" - req.Host = "192.168.1.50:18800" - newHandler(autoLogin).ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther || len(rec.Result().Cookies()) != 1 { - t.Fatalf("capability auto-login code=%d cookies=%#v", rec.Code, rec.Result().Cookies()) - } - - expired := mustLocalAutoLogin(t, -time.Second) - h := newHandler(expired) - rec = httptest.NewRecorder() - req = httptest.NewRequest(http.MethodGet, expired.URLPath(), nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusFound || len(rec.Result().Cookies()) != 0 { - t.Fatalf("expired auto-login code=%d cookies=%#v", rec.Code, rec.Result().Cookies()) - } -} - -func TestLauncherDashboardAuth_DotDotCannotBypass(t *testing.T) { - cfg := LauncherDashboardAuthConfig{ExpectedCookie: "deadbeef"} - next := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { - t.Fatal("next handler should not run without auth") - }) - h := LauncherDashboardAuth(cfg, next) - - for _, p := range []string{ - "/assets/../api/config", - "/launcher-login/../api/config", - "/./api/config", - } { - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, p, nil) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusUnauthorized { - t.Fatalf("%q: status = %d, want %d", p, rec.Code, http.StatusUnauthorized) - } - } -} - -func TestLauncherDashboardAuth_CookieOnly(t *testing.T) { - cookieVal := "session-cookie-value" - cfg := LauncherDashboardAuthConfig{ExpectedCookie: cookieVal} - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - h := LauncherDashboardAuth(cfg, next) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/", nil) - req.AddCookie(&http.Cookie{Name: LauncherDashboardCookieName, Value: cookieVal}) - h.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("cookie auth: status = %d", rec.Code) - } - - rec2 := httptest.NewRecorder() - req2 := httptest.NewRequest(http.MethodGet, "/api/config", nil) - req2.Header.Set("Authorization", "Bearer dashboard-secret-9") - h.ServeHTTP(rec2, req2) - if rec2.Code != http.StatusUnauthorized { - t.Fatalf("bearer auth should not be accepted: status = %d", rec2.Code) - } -} - -func TestLauncherDashboardAuth_WebSocketUnauthorizedDoesNotRedirect(t *testing.T) { - cfg := LauncherDashboardAuthConfig{ExpectedCookie: "deadbeef"} - next := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { - t.Fatal("next handler should not run without auth") - }) - h := LauncherDashboardAuth(cfg, next) - - rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/pico/ws", nil) - h.ServeHTTP(rec, req) - - if rec.Code != http.StatusUnauthorized { - t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized) - } - if got := rec.Header().Get("Location"); got != "" { - t.Fatalf("Location = %q, want empty", got) - } -} diff --git a/web/backend/middleware/middleware.go b/web/backend/middleware/middleware.go deleted file mode 100644 index f9eb3149..00000000 --- a/web/backend/middleware/middleware.go +++ /dev/null @@ -1,81 +0,0 @@ -package middleware - -import ( - "bufio" - "fmt" - "net" - "net/http" - "runtime/debug" - "time" - - "github.com/sipeed/picoclaw/pkg/logger" -) - -// JSONContentType sets the Content-Type header to application/json for -// API requests handled by the wrapped handler. -func JSONContentType(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if len(r.URL.Path) >= 5 && r.URL.Path[:5] == "/api/" { - w.Header().Set("Content-Type", "application/json") - } - next.ServeHTTP(w, r) - }) -} - -// responseRecorder wraps http.ResponseWriter to capture the status code. -type responseRecorder struct { - http.ResponseWriter - statusCode int -} - -func (rr *responseRecorder) WriteHeader(code int) { - rr.statusCode = code - rr.ResponseWriter.WriteHeader(code) -} - -// Flush delegates to the underlying ResponseWriter if it implements http.Flusher. -func (rr *responseRecorder) Flush() { - if f, ok := rr.ResponseWriter.(http.Flusher); ok { - f.Flush() - } -} - -// Unwrap returns the underlying ResponseWriter so that http.ResponseController -// and interface checks (like http.Flusher) can see through the wrapper. -func (rr *responseRecorder) Unwrap() http.ResponseWriter { - return rr.ResponseWriter -} - -// Hijack implements http.Hijacker so that WebSocket upgrades work through -// the middleware layer. -func (rr *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if hj, ok := rr.ResponseWriter.(http.Hijacker); ok { - return hj.Hijack() - } - return nil, nil, http.ErrNotSupported -} - -// Logger logs each HTTP request with method, path, status code, and duration. -func Logger(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - start := time.Now() - rec := &responseRecorder{ResponseWriter: w, statusCode: http.StatusOK} - next.ServeHTTP(rec, r) - logger.DebugC("http", fmt.Sprintf("%s %s %d %s", r.Method, r.URL.Path, rec.statusCode, time.Since(start))) - }) -} - -// Recoverer recovers from panics in downstream handlers and returns a 500 -// Internal Server Error response. -func Recoverer(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer func() { - if err := recover(); err != nil { - logger.RecoverPanicNoExit(err) - logger.ErrorC("http", fmt.Sprintf("panic recovered: %v\n%s", err, debug.Stack())) - http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError) - } - }() - next.ServeHTTP(w, r) - }) -} diff --git a/web/backend/middleware/referrer_policy.go b/web/backend/middleware/referrer_policy.go deleted file mode 100644 index 6cb14669..00000000 --- a/web/backend/middleware/referrer_policy.go +++ /dev/null @@ -1,12 +0,0 @@ -package middleware - -import "net/http" - -// ReferrerPolicyNoReferrer sets Referrer-Policy: no-referrer on every response -// so sensitive paths and query parameters are not leaked via the Referer header. -func ReferrerPolicyNoReferrer(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Referrer-Policy", "no-referrer") - next.ServeHTTP(w, r) - }) -} diff --git a/web/backend/model/status.go b/web/backend/model/status.go deleted file mode 100644 index 32598150..00000000 --- a/web/backend/model/status.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -// StatusResponse represents the response payload for the GET /api/status endpoint. -type StatusResponse struct { - Status string `json:"status"` - Version string `json:"version"` - Uptime string `json:"uptime"` -} diff --git a/web/backend/systray.go b/web/backend/systray.go deleted file mode 100644 index 41fea1fb..00000000 --- a/web/backend/systray.go +++ /dev/null @@ -1,94 +0,0 @@ -//go:build !android && ((!darwin && !freebsd) || cgo) - -package main - -import ( - "fmt" - - "fyne.io/systray" - - "github.com/sipeed/picoclaw/pkg/logger" - "github.com/sipeed/picoclaw/web/backend/utils" -) - -func runTray() { - systray.Run(onReady, onExit) -} - -// onReady is called when the system tray is ready -func onReady() { - // Set icon and tooltip - systray.SetIcon(getIcon()) - systray.SetTooltip(fmt.Sprintf(T(AppTooltip), appName)) - - // Create menu items - mOpen := systray.AddMenuItem(T(MenuOpen), T(MenuOpenTooltip)) - mAbout := systray.AddMenuItem(T(MenuAbout), T(MenuAboutTooltip)) - - // Add version info under About menu - mVersion := mAbout.AddSubMenuItem(fmt.Sprintf(T(MenuVersion), appVersion), T(MenuVersionTooltip)) - mVersion.Disable() - mRepo := mAbout.AddSubMenuItem(T(MenuGitHub), "") - mDocs := mAbout.AddSubMenuItem(T(MenuDocs), "") - - systray.AddSeparator() - - // Add restart option - mRestart := systray.AddMenuItem(T(MenuRestart), T(MenuRestartTooltip)) - - systray.AddSeparator() - - // Quit option - mQuit := systray.AddMenuItem(T(MenuQuit), T(MenuQuitTooltip)) - - // Handle menu clicks - go func() { - for { - select { - case <-mOpen.ClickedCh: - if err := openBrowser(); err != nil { - logger.Errorf("Failed to open browser: %v", err) - } - - case <-mVersion.ClickedCh: - // Version info - do nothing, just shows current version - - case <-mRepo.ClickedCh: - if err := utils.OpenBrowser("https://github.com/sipeed/picoclaw"); err != nil { - logger.Errorf("Failed to open GitHub: %v", err) - } - - case <-mDocs.ClickedCh: - if err := utils.OpenBrowser(T(DocUrl)); err != nil { - logger.Errorf("Failed to open docs: %v", err) - } - - case <-mRestart.ClickedCh: - fmt.Println("Restart request received...") - if apiHandler != nil { - if pid, err := apiHandler.RestartGateway(); err != nil { - logger.Errorf("Failed to restart gateway: %v", err) - } else { - logger.Infof("Gateway restarted (PID: %d)", pid) - } - } - - case <-mQuit.ClickedCh: - systray.Quit() - } - } - }() - - if !*noBrowser { - // Auto-open browser after systray is ready (if not disabled) - // Check no-browser flag via environment or pass as parameter if needed - if err := openBrowser(); err != nil { - logger.Errorf("Warning: Failed to auto-open browser: %v", err) - } - } -} - -// onExit is called when the system tray is exiting -func onExit() { - logger.Info(T(Exiting)) -} diff --git a/web/backend/systray_icon_nonwindows.go b/web/backend/systray_icon_nonwindows.go deleted file mode 100644 index 0117a9ae..00000000 --- a/web/backend/systray_icon_nonwindows.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !windows && ((!darwin && !freebsd) || cgo) - -package main - -import _ "embed" - -//go:embed icon.png -var iconPNG []byte - -func getIcon() []byte { - return iconPNG -} diff --git a/web/backend/systray_icon_windows.go b/web/backend/systray_icon_windows.go deleted file mode 100644 index c265e2f9..00000000 --- a/web/backend/systray_icon_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build windows - -package main - -import _ "embed" - -//go:embed icon.ico -var iconICO []byte - -func getIcon() []byte { - return iconICO -} diff --git a/web/backend/systray_stub_nocgo.go b/web/backend/systray_stub_nocgo.go deleted file mode 100644 index 41514fee..00000000 --- a/web/backend/systray_stub_nocgo.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build (darwin || freebsd || android) && !cgo - -package main - -import ( - "context" - "os" - "os/signal" - "runtime" - "syscall" - "time" - - "github.com/sipeed/picoclaw/pkg/logger" -) - -// runTray falls back to a headless mode on platforms where systray requires cgo. -func runTray() { - logger.Infof("System tray is unavailable in %s builds without cgo; running without tray", runtime.GOOS) - - if !*noBrowser { - go func() { - time.Sleep(browserDelay) - if err := openBrowser(); err != nil { - logger.Errorf("Warning: Failed to auto-open browser: %v", err) - } - }() - } - - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - - <-ctx.Done() - shutdownApp() -} diff --git a/web/backend/utils/banner.go b/web/backend/utils/banner.go deleted file mode 100644 index a64ea639..00000000 --- a/web/backend/utils/banner.go +++ /dev/null @@ -1,15 +0,0 @@ -package utils - -const ( - colorBlue = "\x1b[38;2;62;93;185m" - colorRed = "\x1b[38;2;213;70;70m" - colorReset = "\x1b[0m" - Banner = "\r\n" + - colorBlue + "██████╗ ██╗ ██████╗ ██████╗ " + colorRed + " ██████╗██╗ █████╗ ██╗ ██╗\n" + - colorBlue + "██╔══██╗██║██╔════╝██╔═══██╗" + colorRed + "██╔════╝██║ ██╔══██╗██║ ██║\n" + - colorBlue + "██████╔╝██║██║ ██║ ██║" + colorRed + "██║ ██║ ███████║██║ █╗ ██║\n" + - colorBlue + "██╔═══╝ ██║██║ ██║ ██║" + colorRed + "██║ ██║ ██╔══██║██║███╗██║\n" + - colorBlue + "██║ ██║╚██████╗╚██████╔╝" + colorRed + "╚██████╗███████╗██║ ██║╚███╔███╔╝\n" + - colorBlue + "╚═╝ ╚═╝ ╚═════╝ ╚═════╝ " + colorRed + " ╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝\n" + - colorReset -) diff --git a/web/backend/utils/exec_nonwindows.go b/web/backend/utils/exec_nonwindows.go deleted file mode 100644 index b5bcb702..00000000 --- a/web/backend/utils/exec_nonwindows.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows - -package utils - -import "os/exec" - -// LauncherExecCommand creates an exec.Cmd. On non-Windows platforms, this is -// a simple wrapper around exec.Command. -func LauncherExecCommand(name string, args ...string) *exec.Cmd { - return exec.Command(name, args...) -} - -// ApplyLauncherProcAttrs is a no-op on non-Windows platforms. -func ApplyLauncherProcAttrs(_ *exec.Cmd) {} diff --git a/web/backend/utils/exec_windows.go b/web/backend/utils/exec_windows.go deleted file mode 100644 index 079887df..00000000 --- a/web/backend/utils/exec_windows.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build windows - -package utils - -import ( - "os/exec" - "syscall" -) - -// LauncherExecCommand creates an exec.Cmd with the HideWindow attribute set -// to prevent console window flashes on Windows. -func LauncherExecCommand(name string, args ...string) *exec.Cmd { - cmd := exec.Command(name, args...) - ApplyLauncherProcAttrs(cmd) - return cmd -} - -// ApplyLauncherProcAttrs applies Windows-specific process attributes to hide -// the console window. It is safe to call with a nil cmd. -func ApplyLauncherProcAttrs(cmd *exec.Cmd) { - if cmd == nil { - return - } - if cmd.SysProcAttr == nil { - cmd.SysProcAttr = &syscall.SysProcAttr{} - } - cmd.SysProcAttr.HideWindow = true -} diff --git a/web/backend/utils/onboard.go b/web/backend/utils/onboard.go deleted file mode 100644 index 6f37b862..00000000 --- a/web/backend/utils/onboard.go +++ /dev/null @@ -1,43 +0,0 @@ -package utils - -import ( - "fmt" - "os" - "strings" - - "github.com/sipeed/picoclaw/pkg/config" -) - -var execCommand = LauncherExecCommand - -func EnsureOnboarded(configPath string) error { - _, err := os.Stat(configPath) - if err == nil { - return nil - } - if !os.IsNotExist(err) { - return fmt.Errorf("stat config: %w", err) - } - - cmd := execCommand(FindPicoclawBinary(), "onboard") - cmd.Env = append(os.Environ(), config.EnvConfig+"="+configPath) - cmd.Stdin = strings.NewReader("n\n") - - output, err := cmd.CombinedOutput() - if err != nil { - trimmed := strings.TrimSpace(string(output)) - if trimmed == "" { - return fmt.Errorf("run onboard: %w", err) - } - return fmt.Errorf("run onboard: %w: %s", err, trimmed) - } - - if _, err := os.Stat(configPath); err != nil { - if os.IsNotExist(err) { - return fmt.Errorf("onboard completed but did not create config %s", configPath) - } - return fmt.Errorf("verify config after onboard: %w", err) - } - - return nil -} diff --git a/web/backend/utils/onboard_test.go b/web/backend/utils/onboard_test.go deleted file mode 100644 index 06f967e7..00000000 --- a/web/backend/utils/onboard_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package utils - -import ( - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func TestEnsureOnboardedSkipsWhenConfigExists(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - if err := os.WriteFile(configPath, []byte(`{}`), 0o644); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - - origExecCommand := execCommand - defer func() { execCommand = origExecCommand }() - - called := false - execCommand = func(name string, args ...string) *exec.Cmd { - called = true - return exec.Command("sh", "-c", "exit 1") - } - - if err := EnsureOnboarded(configPath); err != nil { - t.Fatalf("EnsureOnboarded() error = %v", err) - } - if called { - t.Fatal("expected onboard command not to run when config already exists") - } -} - -func TestEnsureOnboardedRunsOnboardWhenConfigMissing(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - t.Setenv("EXPECTED_CONFIG_PATH", configPath) - - origExecCommand := execCommand - defer func() { execCommand = origExecCommand }() - - var gotName string - var gotArgs []string - execCommand = func(name string, args ...string) *exec.Cmd { - gotName = name - gotArgs = append([]string(nil), args...) - return exec.Command( - "sh", - "-c", - `test "$PICOCLAW_CONFIG" = "$EXPECTED_CONFIG_PATH" && -mkdir -p "$(dirname "$PICOCLAW_CONFIG")" && -printf '{}' > "$PICOCLAW_CONFIG"`, - ) - } - - if err := EnsureOnboarded(configPath); err != nil { - t.Fatalf("EnsureOnboarded() error = %v", err) - } - if gotName == "" { - t.Fatal("expected onboard command to run") - } - if len(gotArgs) != 1 || gotArgs[0] != "onboard" { - t.Fatalf("command args = %#v, want []string{\"onboard\"}", gotArgs) - } - if _, err := os.Stat(configPath); err != nil { - t.Fatalf("expected config to be created: %v", err) - } -} - -func TestEnsureOnboardedFailsWhenOnboardDoesNotCreateConfig(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - - origExecCommand := execCommand - defer func() { execCommand = origExecCommand }() - - execCommand = func(name string, args ...string) *exec.Cmd { - return exec.Command("sh", "-c", "exit 0") - } - - if err := EnsureOnboarded(configPath); err == nil { - t.Fatal("EnsureOnboarded() error = nil, want failure when onboard does not create config") - } -} - -func TestEnsureOnboardedIncludesOnboardOutputOnFailure(t *testing.T) { - configPath := filepath.Join(t.TempDir(), "config.json") - - origExecCommand := execCommand - defer func() { execCommand = origExecCommand }() - - execCommand = func(name string, args ...string) *exec.Cmd { - return exec.Command("sh", "-c", "echo onboarding failed >&2; exit 2") - } - - err := EnsureOnboarded(configPath) - if err == nil { - t.Fatal("EnsureOnboarded() error = nil, want failure") - } - if !strings.Contains(err.Error(), "onboarding failed") { - t.Fatalf("error = %q, want onboard output included", err) - } -} diff --git a/web/backend/utils/runtime.go b/web/backend/utils/runtime.go deleted file mode 100644 index d4aee0b8..00000000 --- a/web/backend/utils/runtime.go +++ /dev/null @@ -1,159 +0,0 @@ -package utils - -import ( - "fmt" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - - "github.com/sipeed/picoclaw/pkg/config" - "github.com/sipeed/picoclaw/pkg/logger" -) - -// GetPicoclawHome returns the picoclaw home directory. -// Priority: $PICOCLAW_HOME > ~/.picoclaw -func GetPicoclawHome() string { - return config.GetHome() -} - -// GetDefaultConfigPath returns the default path to the picoclaw config file. -func GetDefaultConfigPath() string { - if configPath := os.Getenv(config.EnvConfig); configPath != "" { - return configPath - } - return filepath.Join(GetPicoclawHome(), "config.json") -} - -// FindPicoclawBinary locates the picoclaw executable. -// Search order: -// 1. PICOCLAW_BINARY environment variable (explicit override) -// 2. Same directory as the current executable -// 3. Falls back to "picoclaw" and relies on $PATH -func FindPicoclawBinary() string { - binaryName := "picoclaw" - if runtime.GOOS == "windows" { - binaryName = "picoclaw.exe" - } - - if p := os.Getenv(config.EnvBinary); p != "" { - if info, _ := os.Stat(p); info != nil && !info.IsDir() { - return p - } - } - - if exe, err := os.Executable(); err == nil { - logger.Debugf("Trying to find picoclaw binary in %s", exe) - candidate := filepath.Join(filepath.Dir(exe), binaryName) - if info, err := os.Stat(candidate); err == nil && !info.IsDir() { - return candidate - } - } - - return "picoclaw" -} - -func appendUniqueIP(addrs []string, seen map[string]struct{}, value string) []string { - value = strings.TrimSpace(value) - if value == "" { - return addrs - } - if _, ok := seen[value]; ok { - return addrs - } - seen[value] = struct{}{} - return append(addrs, value) -} - -// GetLocalIPv4s returns all non-loopback local IPv4 addresses. -func GetLocalIPv4s() []string { - addrs, err := net.InterfaceAddrs() - if err != nil { - return nil - } - results := make([]string, 0, 4) - seen := make(map[string]struct{}, 4) - for _, a := range addrs { - ipnet, ok := a.(*net.IPNet) - if !ok || ipnet.IP == nil || ipnet.IP.IsLoopback() { - continue - } - if ip4 := ipnet.IP.To4(); ip4 != nil { - results = appendUniqueIP(results, seen, ip4.String()) - } - } - return results -} - -func isDisplayGlobalIPv6(ip net.IP) bool { - if ip == nil || ip.IsLoopback() || ip.To4() != nil { - return false - } - ip = ip.To16() - if ip == nil { - return false - } - // Only show IPv6 global unicast addresses in 2000::/3. - return ip[0]&0xe0 == 0x20 -} - -// GetGlobalIPv6s returns all IPv6 global unicast addresses. -func GetGlobalIPv6s() []string { - addrs, err := net.InterfaceAddrs() - if err != nil { - return nil - } - results := make([]string, 0, 4) - seen := make(map[string]struct{}, 4) - for _, a := range addrs { - ipnet, ok := a.(*net.IPNet) - if !ok || ipnet.IP == nil { - continue - } - ip := ipnet.IP - if !isDisplayGlobalIPv6(ip) { - continue - } - results = appendUniqueIP(results, seen, ip.String()) - } - return results -} - -// GetLocalIPv4 returns the first non-loopback local IPv4 address. -func GetLocalIPv4() string { - addrs := GetLocalIPv4s() - if len(addrs) == 0 { - return "" - } - return addrs[0] -} - -// GetLocalIPv6 returns the first IPv6 global unicast address. -func GetLocalIPv6() string { - addrs := GetGlobalIPv6s() - if len(addrs) == 0 { - return "" - } - return addrs[0] -} - -// GetLocalIP returns a non-loopback local IPv4 address for backward compatibility. -func GetLocalIP() string { - return GetLocalIPv4() -} - -// OpenBrowser automatically opens the given URL in the default browser. -func OpenBrowser(url string) error { - switch runtime.GOOS { - case "linux": - return exec.Command("xdg-open", url).Start() - case "windows": - return LauncherExecCommand("rundll32", "url.dll,FileProtocolHandler", url).Start() - case "darwin": - return exec.Command("open", url).Start() - default: - return fmt.Errorf("unsupported platform") - } -} diff --git a/web/backend/winres/winres.json b/web/backend/winres/winres.json deleted file mode 100644 index 01ea7364..00000000 --- a/web/backend/winres/winres.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "RT_GROUP_ICON": { - "APP": { - "0000": "../icon.ico" - } - }, - "RT_MANIFEST": { - "#1": { - "0409": { - "identity": { - "name": "PicoClaw Launcher", - "version": "0.0.0.0" - }, - "description": "PicoClaw Launcher - Web-based configuration editor", - "minimum-os": "win7", - "execution-level": "asInvoker", - "dpi-awareness": "system", - "use-common-controls-v6": true - } - } - } -} diff --git a/web/frontend/.editorconfig b/web/frontend/.editorconfig deleted file mode 100644 index a8c0f1ec..00000000 --- a/web/frontend/.editorconfig +++ /dev/null @@ -1,7 +0,0 @@ -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -end_of_line = lf \ No newline at end of file diff --git a/web/frontend/.gitignore b/web/frontend/.gitignore deleted file mode 100644 index 72e68ffb..00000000 --- a/web/frontend/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? - -.tanstack diff --git a/web/frontend/.prettierignore b/web/frontend/.prettierignore deleted file mode 100644 index 7040bf59..00000000 --- a/web/frontend/.prettierignore +++ /dev/null @@ -1,5 +0,0 @@ -package-lock.json -pnpm-lock.yaml -yarn.lock -routeTree.gen.ts -src/components/ui \ No newline at end of file diff --git a/web/frontend/components.json b/web/frontend/components.json deleted file mode 100644 index 9d532969..00000000 --- a/web/frontend/components.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "radix-vega", - "rsc": false, - "tsx": true, - "tailwind": { - "config": "", - "css": "src/index.css", - "baseColor": "neutral", - "cssVariables": true, - "prefix": "" - }, - "iconLibrary": "tabler", - "rtl": false, - "aliases": { - "components": "@/components", - "utils": "@/lib/utils", - "ui": "@/components/ui", - "lib": "@/lib", - "hooks": "@/hooks" - }, - "menuColor": "default", - "menuAccent": "subtle", - "registries": {} -} diff --git a/web/frontend/eslint.config.js b/web/frontend/eslint.config.js deleted file mode 100644 index 884649e4..00000000 --- a/web/frontend/eslint.config.js +++ /dev/null @@ -1,40 +0,0 @@ -import js from "@eslint/js" -import eslintConfigPrettier from "eslint-config-prettier" -import reactHooks from "eslint-plugin-react-hooks" -import reactRefresh from "eslint-plugin-react-refresh" -import { defineConfig, globalIgnores } from "eslint/config" -import globals from "globals" -import tseslint from "typescript-eslint" - -export default defineConfig([ - globalIgnores(["dist", "src/components/ui", "src/routeTree.gen.ts"]), - { - files: ["**/*.{ts,tsx}"], - extends: [ - js.configs.recommended, - tseslint.configs.recommended, - reactHooks.configs.flat.recommended, - reactRefresh.configs.vite, - eslintConfigPrettier, - ], - languageOptions: { - ecmaVersion: "latest", - globals: globals.browser, - }, - rules: { - "react-hooks/set-state-in-effect": "off", - "react-refresh/only-export-components": [ - "warn", - { allowConstantExport: true }, - ], - }, - }, - { - files: ["src/routes/**/*.{ts,tsx}"], - rules: { - // TanStack Router route modules must export Route objects, so this rule - // produces false positives for framework-managed files. - "react-refresh/only-export-components": "off", - }, - }, -]) diff --git a/web/frontend/index.html b/web/frontend/index.html deleted file mode 100644 index d3bdd90f..00000000 --- a/web/frontend/index.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - PicoClaw - - - -
- - - diff --git a/web/frontend/package.json b/web/frontend/package.json deleted file mode 100644 index 76161228..00000000 --- a/web/frontend/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "picoclaw-web", - "private": true, - "version": "0.0.0", - "type": "module", - "packageManager": "pnpm@10.33.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "scripts": { - "dev": "vite", - "build": "tsc -b && vite build", - "build:backend": "tsc -b && vite build --outDir ../backend/dist --emptyOutDir && node ./scripts/ensure-backend-gitkeep.cjs", - "lint": "eslint .", - "preview": "vite preview", - "format": "prettier --check .", - "check": "prettier --write . && eslint --fix" - }, - "dependencies": { - "@fontsource-variable/inter": "^5.2.8", - "@radix-ui/react-popover": "^1.1.15", - "@tabler/icons-react": "^3.43.0", - "@tailwindcss/vite": "^4.3.0", - "@tanstack/react-query": "^5.99.0", - "@tanstack/react-router": "^1.169.2", - "@tanstack/react-router-devtools": "^1.166.13", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "cmdk": "^1.1.1", - "dayjs": "^1.11.20", - "highlight.js": "^11.11.1", - "i18next": "^26.0.10", - "i18next-browser-languagedetector": "^8.2.1", - "jotai": "^2.20.0", - "radix-ui": "^1.4.3", - "react": "19.2.5", - "react-dom": "19.2.5", - "react-i18next": "^17.0.7", - "react-markdown": "^10.1.0", - "react-textarea-autosize": "^8.5.9", - "rehype-highlight": "^7.0.2", - "rehype-raw": "^7.0.0", - "rehype-sanitize": "^6.0.0", - "remark-gfm": "^4.0.1", - "shadcn": "^4.12.0", - "sonner": "^2.0.7", - "tailwind-merge": "^3.5.0", - "tailwindcss": "^4.3.0", - "tw-animate-css": "^1.4.0", - "wrap-ansi": "^10.0.0" - }, - "devDependencies": { - "@eslint/js": "^10.0.1", - "@tailwindcss/typography": "^0.5.19", - "@tanstack/router-plugin": "^1.164.0", - "@trivago/prettier-plugin-sort-imports": "^6.0.2", - "@types/node": "^25.6.0", - "@types/react": "^19.2.7", - "@types/react-dom": "^19.2.3", - "@typescript-eslint/eslint-plugin": "^8.58.2", - "@vitejs/plugin-react": "^6.0.3", - "eslint": "^10.4.1", - "eslint-config-prettier": "^10.1.8", - "eslint-plugin-react-hooks": "^7.1.1", - "eslint-plugin-react-refresh": "^0.5.2", - "globals": "^17.6.0", - "prettier": "^3.8.3", - "prettier-plugin-tailwindcss": "^0.8.0", - "typescript": "~5.9.3", - "typescript-eslint": "^8.62.1", - "vite": "^8.0.16" - } -} diff --git a/web/frontend/pnpm-lock.yaml b/web/frontend/pnpm-lock.yaml deleted file mode 100644 index 16fb6b1c..00000000 --- a/web/frontend/pnpm-lock.yaml +++ /dev/null @@ -1,8185 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - dependencies: - '@fontsource-variable/inter': - specifier: ^5.2.8 - version: 5.2.8 - '@radix-ui/react-popover': - specifier: ^1.1.15 - version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@tabler/icons-react': - specifier: ^3.43.0 - version: 3.43.0(react@19.2.5) - '@tailwindcss/vite': - specifier: ^4.3.0 - version: 4.3.0(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0)) - '@tanstack/react-query': - specifier: ^5.99.0 - version: 5.99.0(react@19.2.5) - '@tanstack/react-router': - specifier: ^1.169.2 - version: 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@tanstack/react-router-devtools': - specifier: ^1.166.13 - version: 1.166.13(@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.169.2)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - class-variance-authority: - specifier: ^0.7.1 - version: 0.7.1 - clsx: - specifier: ^2.1.1 - version: 2.1.1 - cmdk: - specifier: ^1.1.1 - version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - dayjs: - specifier: ^1.11.20 - version: 1.11.20 - highlight.js: - specifier: ^11.11.1 - version: 11.11.1 - i18next: - specifier: ^26.0.10 - version: 26.0.10(typescript@5.9.3) - i18next-browser-languagedetector: - specifier: ^8.2.1 - version: 8.2.1 - jotai: - specifier: ^2.20.0 - version: 2.20.0(@babel/core@7.29.7)(@babel/template@7.29.7)(@types/react@19.2.14)(react@19.2.5) - radix-ui: - specifier: ^1.4.3 - version: 1.4.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: - specifier: 19.2.5 - version: 19.2.5 - react-dom: - specifier: 19.2.5 - version: 19.2.5(react@19.2.5) - react-i18next: - specifier: ^17.0.7 - version: 17.0.7(i18next@26.0.10(typescript@5.9.3))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@5.9.3) - react-markdown: - specifier: ^10.1.0 - version: 10.1.0(@types/react@19.2.14)(react@19.2.5) - react-textarea-autosize: - specifier: ^8.5.9 - version: 8.5.9(@types/react@19.2.14)(react@19.2.5) - rehype-highlight: - specifier: ^7.0.2 - version: 7.0.2 - rehype-raw: - specifier: ^7.0.0 - version: 7.0.0 - rehype-sanitize: - specifier: ^6.0.0 - version: 6.0.0 - remark-gfm: - specifier: ^4.0.1 - version: 4.0.1 - shadcn: - specifier: ^4.12.0 - version: 4.12.0(typescript@5.9.3) - sonner: - specifier: ^2.0.7 - version: 2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - tailwind-merge: - specifier: ^3.5.0 - version: 3.5.0 - tailwindcss: - specifier: ^4.3.0 - version: 4.3.0 - tw-animate-css: - specifier: ^1.4.0 - version: 1.4.0 - wrap-ansi: - specifier: ^10.0.0 - version: 10.0.0 - devDependencies: - '@eslint/js': - specifier: ^10.0.1 - version: 10.0.1(eslint@10.4.1(jiti@2.7.0)) - '@tailwindcss/typography': - specifier: ^0.5.19 - version: 0.5.19(tailwindcss@4.3.0) - '@tanstack/router-plugin': - specifier: ^1.164.0 - version: 1.167.9(@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0)) - '@trivago/prettier-plugin-sort-imports': - specifier: ^6.0.2 - version: 6.0.2(prettier@3.8.3) - '@types/node': - specifier: ^25.6.0 - version: 25.6.0 - '@types/react': - specifier: ^19.2.7 - version: 19.2.14 - '@types/react-dom': - specifier: ^19.2.3 - version: 19.2.3(@types/react@19.2.14) - '@typescript-eslint/eslint-plugin': - specifier: ^8.58.2 - version: 8.58.2(@typescript-eslint/parser@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3))(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@vitejs/plugin-react': - specifier: ^6.0.3 - version: 6.0.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0)) - eslint: - specifier: ^10.4.1 - version: 10.4.1(jiti@2.7.0) - eslint-config-prettier: - specifier: ^10.1.8 - version: 10.1.8(eslint@10.4.1(jiti@2.7.0)) - eslint-plugin-react-hooks: - specifier: ^7.1.1 - version: 7.1.1(eslint@10.4.1(jiti@2.7.0)) - eslint-plugin-react-refresh: - specifier: ^0.5.2 - version: 0.5.2(eslint@10.4.1(jiti@2.7.0)) - globals: - specifier: ^17.6.0 - version: 17.6.0 - prettier: - specifier: ^3.8.3 - version: 3.8.3 - prettier-plugin-tailwindcss: - specifier: ^0.8.0 - version: 0.8.0(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3))(prettier@3.8.3) - typescript: - specifier: ~5.9.3 - version: 5.9.3 - typescript-eslint: - specifier: ^8.62.1 - version: 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - vite: - specifier: ^8.0.16 - version: 8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0) - -packages: - - '@babel/code-frame@7.29.0': - resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} - engines: {node: '>=6.9.0'} - - '@babel/code-frame@7.29.7': - resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} - engines: {node: '>=6.9.0'} - - '@babel/compat-data@7.29.3': - resolution: {integrity: sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==} - engines: {node: '>=6.9.0'} - - '@babel/compat-data@7.29.7': - resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} - engines: {node: '>=6.9.0'} - - '@babel/core@7.29.0': - resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==} - engines: {node: '>=6.9.0'} - - '@babel/core@7.29.7': - resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} - engines: {node: '>=6.9.0'} - - '@babel/generator@7.29.1': - resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==} - engines: {node: '>=6.9.0'} - - '@babel/generator@7.29.7': - resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==} - engines: {node: '>=6.9.0'} - - '@babel/helper-annotate-as-pure@7.29.7': - resolution: {integrity: sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-compilation-targets@7.28.6': - resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==} - engines: {node: '>=6.9.0'} - - '@babel/helper-compilation-targets@7.29.7': - resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} - engines: {node: '>=6.9.0'} - - '@babel/helper-create-class-features-plugin@7.29.7': - resolution: {integrity: sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0 - - '@babel/helper-globals@7.28.0': - resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-globals@7.29.7': - resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} - engines: {node: '>=6.9.0'} - - '@babel/helper-member-expression-to-functions@7.29.7': - resolution: {integrity: sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==} - engines: {node: '>=6.9.0'} - - '@babel/helper-module-imports@7.28.6': - resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-module-imports@7.29.7': - resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} - engines: {node: '>=6.9.0'} - - '@babel/helper-module-transforms@7.28.6': - resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0 - - '@babel/helper-module-transforms@7.29.7': - resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0 - - '@babel/helper-optimise-call-expression@7.29.7': - resolution: {integrity: sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==} - engines: {node: '>=6.9.0'} - - '@babel/helper-plugin-utils@7.28.6': - resolution: {integrity: sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==} - engines: {node: '>=6.9.0'} - - '@babel/helper-plugin-utils@7.29.7': - resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-replace-supers@7.29.7': - resolution: {integrity: sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0 - - '@babel/helper-skip-transparent-expression-wrappers@7.29.7': - resolution: {integrity: sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==} - engines: {node: '>=6.9.0'} - - '@babel/helper-string-parser@7.27.1': - resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} - engines: {node: '>=6.9.0'} - - '@babel/helper-string-parser@7.29.7': - resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-validator-identifier@7.28.5': - resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} - engines: {node: '>=6.9.0'} - - '@babel/helper-validator-identifier@7.29.7': - resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} - engines: {node: '>=6.9.0'} - - '@babel/helper-validator-option@7.29.7': - resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} - engines: {node: '>=6.9.0'} - - '@babel/helpers@7.29.2': - resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==} - engines: {node: '>=6.9.0'} - - '@babel/helpers@7.29.7': - resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} - engines: {node: '>=6.9.0'} - - '@babel/parser@7.29.2': - resolution: {integrity: sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==} - engines: {node: '>=6.0.0'} - hasBin: true - - '@babel/parser@7.29.7': - resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==} - engines: {node: '>=6.0.0'} - hasBin: true - - '@babel/plugin-syntax-jsx@7.28.6': - resolution: {integrity: sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/plugin-syntax-jsx@7.29.7': - resolution: {integrity: sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/plugin-syntax-typescript@7.28.6': - resolution: {integrity: sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/plugin-syntax-typescript@7.29.7': - resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/plugin-transform-modules-commonjs@7.29.7': - resolution: {integrity: sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/plugin-transform-typescript@7.29.7': - resolution: {integrity: sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/preset-typescript@7.29.7': - resolution: {integrity: sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': ^7.0.0-0 - - '@babel/runtime@7.29.2': - resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==} - engines: {node: '>=6.9.0'} - - '@babel/runtime@7.29.7': - resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} - engines: {node: '>=6.9.0'} - - '@babel/template@7.28.6': - resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==} - engines: {node: '>=6.9.0'} - - '@babel/template@7.29.7': - resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} - engines: {node: '>=6.9.0'} - - '@babel/traverse@7.29.0': - resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==} - engines: {node: '>=6.9.0'} - - '@babel/traverse@7.29.7': - resolution: {integrity: sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==} - engines: {node: '>=6.9.0'} - - '@babel/types@7.29.0': - resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} - engines: {node: '>=6.9.0'} - - '@babel/types@7.29.7': - resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==} - engines: {node: '>=6.9.0'} - - '@dotenvx/dotenvx@1.75.1': - resolution: {integrity: sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ==} - hasBin: true - - '@dotenvx/primitives@0.8.0': - resolution: {integrity: sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg==} - - '@emnapi/core@1.10.0': - resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} - - '@emnapi/runtime@1.10.0': - resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} - - '@emnapi/wasi-threads@1.2.1': - resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} - - '@esbuild/aix-ppc64@0.27.4': - resolution: {integrity: sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - - '@esbuild/android-arm64@0.27.4': - resolution: {integrity: sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - - '@esbuild/android-arm@0.27.4': - resolution: {integrity: sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - - '@esbuild/android-x64@0.27.4': - resolution: {integrity: sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - - '@esbuild/darwin-arm64@0.27.4': - resolution: {integrity: sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - - '@esbuild/darwin-x64@0.27.4': - resolution: {integrity: sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - - '@esbuild/freebsd-arm64@0.27.4': - resolution: {integrity: sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - - '@esbuild/freebsd-x64@0.27.4': - resolution: {integrity: sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - - '@esbuild/linux-arm64@0.27.4': - resolution: {integrity: sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - - '@esbuild/linux-arm@0.27.4': - resolution: {integrity: sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - - '@esbuild/linux-ia32@0.27.4': - resolution: {integrity: sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - - '@esbuild/linux-loong64@0.27.4': - resolution: {integrity: sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - - '@esbuild/linux-mips64el@0.27.4': - resolution: {integrity: sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - - '@esbuild/linux-ppc64@0.27.4': - resolution: {integrity: sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - - '@esbuild/linux-riscv64@0.27.4': - resolution: {integrity: sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - - '@esbuild/linux-s390x@0.27.4': - resolution: {integrity: sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - - '@esbuild/linux-x64@0.27.4': - resolution: {integrity: sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - - '@esbuild/netbsd-arm64@0.27.4': - resolution: {integrity: sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - - '@esbuild/netbsd-x64@0.27.4': - resolution: {integrity: sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - - '@esbuild/openbsd-arm64@0.27.4': - resolution: {integrity: sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - - '@esbuild/openbsd-x64@0.27.4': - resolution: {integrity: sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - - '@esbuild/openharmony-arm64@0.27.4': - resolution: {integrity: sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - - '@esbuild/sunos-x64@0.27.4': - resolution: {integrity: sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - - '@esbuild/win32-arm64@0.27.4': - resolution: {integrity: sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - - '@esbuild/win32-ia32@0.27.4': - resolution: {integrity: sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - - '@esbuild/win32-x64@0.27.4': - resolution: {integrity: sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - - '@eslint-community/eslint-utils@4.9.1': - resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - peerDependencies: - eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 - - '@eslint-community/regexpp@4.12.2': - resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - - '@eslint/config-array@0.23.5': - resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - '@eslint/config-helpers@0.6.0': - resolution: {integrity: sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - '@eslint/core@1.2.1': - resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - '@eslint/js@10.0.1': - resolution: {integrity: sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - peerDependencies: - eslint: ^10.0.0 - peerDependenciesMeta: - eslint: - optional: true - - '@eslint/object-schema@3.0.5': - resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - '@eslint/plugin-kit@0.7.2': - resolution: {integrity: sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - '@floating-ui/core@1.7.5': - resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==} - - '@floating-ui/dom@1.7.6': - resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==} - - '@floating-ui/react-dom@2.1.8': - resolution: {integrity: sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==} - peerDependencies: - react: '>=16.8.0' - react-dom: '>=16.8.0' - - '@floating-ui/utils@0.2.11': - resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} - - '@fontsource-variable/inter@5.2.8': - resolution: {integrity: sha512-kOfP2D+ykbcX/P3IFnokOhVRNoTozo5/JxhAIVYLpea/UBmCQ/YWPBfWIDuBImXX/15KH+eKh4xpEUyS2sQQGQ==} - - '@hono/node-server@1.19.14': - resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==} - engines: {node: '>=18.14.1'} - peerDependencies: - hono: ^4 - - '@humanfs/core@0.19.2': - resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} - engines: {node: '>=18.18.0'} - - '@humanfs/node@0.16.8': - resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} - engines: {node: '>=18.18.0'} - - '@humanfs/types@0.15.0': - resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} - engines: {node: '>=18.18.0'} - - '@humanwhocodes/module-importer@1.0.1': - resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} - engines: {node: '>=12.22'} - - '@humanwhocodes/retry@0.4.3': - resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} - engines: {node: '>=18.18'} - - '@jridgewell/gen-mapping@0.3.13': - resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} - - '@jridgewell/remapping@2.3.5': - resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} - - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - - '@jridgewell/sourcemap-codec@1.5.5': - resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - - '@jridgewell/trace-mapping@0.3.31': - resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - - '@modelcontextprotocol/sdk@1.29.0': - resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==} - engines: {node: '>=18'} - peerDependencies: - '@cfworker/json-schema': ^4.1.1 - zod: ^3.25 || ^4.0 - peerDependenciesMeta: - '@cfworker/json-schema': - optional: true - - '@napi-rs/wasm-runtime@1.1.5': - resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==} - peerDependencies: - '@emnapi/core': ^1.7.1 - '@emnapi/runtime': ^1.7.1 - - '@nodelib/fs.scandir@2.1.5': - resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} - engines: {node: '>= 8'} - - '@nodelib/fs.stat@2.0.5': - resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} - engines: {node: '>= 8'} - - '@nodelib/fs.walk@1.2.8': - resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} - engines: {node: '>= 8'} - - '@oxc-project/types@0.133.0': - resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} - - '@radix-ui/number@1.1.1': - resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} - - '@radix-ui/primitive@1.1.3': - resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==} - - '@radix-ui/react-accessible-icon@1.1.7': - resolution: {integrity: sha512-XM+E4WXl0OqUJFovy6GjmxxFyx9opfCAIUku4dlKRd5YEPqt4kALOkQOp0Of6reHuUkJuiPBEc5k0o4z4lTC8A==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-accordion@1.2.12': - resolution: {integrity: sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-alert-dialog@1.1.15': - resolution: {integrity: sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-arrow@1.1.7': - resolution: {integrity: sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-aspect-ratio@1.1.7': - resolution: {integrity: sha512-Yq6lvO9HQyPwev1onK1daHCHqXVLzPhSVjmsNjCa2Zcxy2f7uJD2itDtxknv6FzAKCwD1qQkeVDmX/cev13n/g==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-avatar@1.1.10': - resolution: {integrity: sha512-V8piFfWapM5OmNCXTzVQY+E1rDa53zY+MQ4Y7356v4fFz6vqCyUtIz2rUD44ZEdwg78/jKmMJHj07+C/Z/rcog==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-checkbox@1.3.3': - resolution: {integrity: sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-collapsible@1.1.12': - resolution: {integrity: sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-collection@1.1.7': - resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-compose-refs@1.1.2': - resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-context-menu@2.2.16': - resolution: {integrity: sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-context@1.1.2': - resolution: {integrity: sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-dialog@1.1.15': - resolution: {integrity: sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-direction@1.1.1': - resolution: {integrity: sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-dismissable-layer@1.1.11': - resolution: {integrity: sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-dropdown-menu@2.1.16': - resolution: {integrity: sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-focus-guards@1.1.3': - resolution: {integrity: sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-focus-scope@1.1.7': - resolution: {integrity: sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-form@0.1.8': - resolution: {integrity: sha512-QM70k4Zwjttifr5a4sZFts9fn8FzHYvQ5PiB19O2HsYibaHSVt9fH9rzB0XZo/YcM+b7t/p7lYCT/F5eOeF5yQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-hover-card@1.1.15': - resolution: {integrity: sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-id@1.1.1': - resolution: {integrity: sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-label@2.1.7': - resolution: {integrity: sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-menu@2.1.16': - resolution: {integrity: sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-menubar@1.1.16': - resolution: {integrity: sha512-EB1FktTz5xRRi2Er974AUQZWg2yVBb1yjip38/lgwtCVRd3a+maUoGHN/xs9Yv8SY8QwbSEb+YrxGadVWbEutA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-navigation-menu@1.2.14': - resolution: {integrity: sha512-YB9mTFQvCOAQMHU+C/jVl96WmuWeltyUEpRJJky51huhds5W2FQr1J8D/16sQlf0ozxkPK8uF3niQMdUwZPv5w==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-one-time-password-field@0.1.8': - resolution: {integrity: sha512-ycS4rbwURavDPVjCb5iS3aG4lURFDILi6sKI/WITUMZ13gMmn/xGjpLoqBAalhJaDk8I3UbCM5GzKHrnzwHbvg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-password-toggle-field@0.1.3': - resolution: {integrity: sha512-/UuCrDBWravcaMix4TdT+qlNdVwOM1Nck9kWx/vafXsdfj1ChfhOdfi3cy9SGBpWgTXwYCuboT/oYpJy3clqfw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-popover@1.1.15': - resolution: {integrity: sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-popper@1.2.8': - resolution: {integrity: sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-portal@1.1.9': - resolution: {integrity: sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-presence@1.1.5': - resolution: {integrity: sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-primitive@2.1.3': - resolution: {integrity: sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-progress@1.1.7': - resolution: {integrity: sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-radio-group@1.3.8': - resolution: {integrity: sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-roving-focus@1.1.11': - resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-scroll-area@1.2.10': - resolution: {integrity: sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-select@2.2.6': - resolution: {integrity: sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-separator@1.1.7': - resolution: {integrity: sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-slider@1.3.6': - resolution: {integrity: sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-slot@1.2.3': - resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-switch@1.2.6': - resolution: {integrity: sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-tabs@1.1.13': - resolution: {integrity: sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-toast@1.2.15': - resolution: {integrity: sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-toggle-group@1.1.11': - resolution: {integrity: sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-toggle@1.1.10': - resolution: {integrity: sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-toolbar@1.1.11': - resolution: {integrity: sha512-4ol06/1bLoFu1nwUqzdD4Y5RZ9oDdKeiHIsntug54Hcr1pgaHiPqHFEaXI1IFP/EsOfROQZ8Mig9VTIRza6Tjg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-tooltip@1.2.8': - resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/react-use-callback-ref@1.1.1': - resolution: {integrity: sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-controllable-state@1.2.2': - resolution: {integrity: sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-effect-event@0.0.2': - resolution: {integrity: sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-escape-keydown@1.1.1': - resolution: {integrity: sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-is-hydrated@0.1.0': - resolution: {integrity: sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-layout-effect@1.1.1': - resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-previous@1.1.1': - resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-rect@1.1.1': - resolution: {integrity: sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-use-size@1.1.1': - resolution: {integrity: sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==} - peerDependencies: - '@types/react': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - '@radix-ui/react-visually-hidden@1.2.3': - resolution: {integrity: sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@radix-ui/rect@1.1.1': - resolution: {integrity: sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==} - - '@rolldown/binding-android-arm64@1.0.3': - resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.0.3': - resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.0.3': - resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.0.3': - resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': - resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.0.3': - resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-arm64-musl@1.0.3': - resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rolldown/binding-linux-ppc64-gnu@1.0.3': - resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-s390x-gnu@1.0.3': - resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-gnu@1.0.3': - resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-musl@1.0.3': - resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rolldown/binding-openharmony-arm64@1.0.3': - resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-wasm32-wasi@1.0.3': - resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [wasm32] - - '@rolldown/binding-win32-arm64-msvc@1.0.3': - resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.0.3': - resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - - '@sec-ant/readable-stream@0.4.1': - resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==} - - '@sindresorhus/merge-streams@4.0.0': - resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==} - engines: {node: '>=18'} - - '@tabler/icons-react@3.43.0': - resolution: {integrity: sha512-rXUuCQEeRbEk3lJxs3gwzdtaaITSwc/JUbp+AkqsGff5uBpzZw7eKPDk53xKoKLyjrbj82Ai4GuVG0kO89Jf5g==} - peerDependencies: - react: '>= 16' - - '@tabler/icons@3.43.0': - resolution: {integrity: sha512-qXwS17Op9jqr3Asvu31fejyw8+OnRDKH7oR8nQXyUgW1pI44ET8OKG9kssy+XIvvAIyej6gZdGmviNUn1VMfPw==} - - '@tailwindcss/node@4.3.0': - resolution: {integrity: sha512-aFb4gUhFOgdh9AXo4IzBEOzBkkAxm9VigwDJnMIYv3lcfXCJVesNfbEaBl4BNgVRyid92AmdviqwBUBRKSeY3g==} - - '@tailwindcss/oxide-android-arm64@4.3.0': - resolution: {integrity: sha512-TJPiq67tKlLuObP6RkwvVGDoxCMBVtDgKkLfa/uyj7/FyxvQwHS+UOnVrXXgbEsfUaMgiVvC4KbJnRr26ho4Ng==} - engines: {node: '>= 20'} - cpu: [arm64] - os: [android] - - '@tailwindcss/oxide-darwin-arm64@4.3.0': - resolution: {integrity: sha512-oMN/WZRb+SO37BmUElEgeEWuU8E/HXRkiODxJxLe1UTHVXLrdVSgfaJV7pSlhRGMSOiXLuxTIjfsF3wYvz8cgQ==} - engines: {node: '>= 20'} - cpu: [arm64] - os: [darwin] - - '@tailwindcss/oxide-darwin-x64@4.3.0': - resolution: {integrity: sha512-N6CUmu4a6bKVADfw77p+iw6Yd9Q3OBhe0veaDX+QazfuVYlQsHfDgxBrsjQ/IW+zywL8mTrNd0SdJT/zgtvMdA==} - engines: {node: '>= 20'} - cpu: [x64] - os: [darwin] - - '@tailwindcss/oxide-freebsd-x64@4.3.0': - resolution: {integrity: sha512-zDL5hBkQdH5C6MpqbK3gQAgP80tsMwSI26vjOzjJtNCMUo0lFgOItzHKBIupOZNQxt3ouPH7RPhvNhiTfCe5CQ==} - engines: {node: '>= 20'} - cpu: [x64] - os: [freebsd] - - '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.0': - resolution: {integrity: sha512-R06HdNi7A7OEoMsf6d4tjZ71RCWnZQPHj2mnotSFURjNLdBC+cIgXQ7l81CqeoiQftjf6OOblxXMInMgN2VzMA==} - engines: {node: '>= 20'} - cpu: [arm] - os: [linux] - - '@tailwindcss/oxide-linux-arm64-gnu@4.3.0': - resolution: {integrity: sha512-qTJHELX8jetjhRQHCLilkVLmybpzNQAtaI/gaoVoidn/ufbNDbAo8KlK2J+yPoc8wQxvDxCmh/5lr8nC1+lTbg==} - engines: {node: '>= 20'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@tailwindcss/oxide-linux-arm64-musl@4.3.0': - resolution: {integrity: sha512-Z6sukiQsngnWO+l39X4pPbiWT81IC+PLKF+PHxIlyZbGNb9MODfYlXEVlFvej5BOZInWX01kVyzeLvHsXhfczQ==} - engines: {node: '>= 20'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@tailwindcss/oxide-linux-x64-gnu@4.3.0': - resolution: {integrity: sha512-DRNdQRpSGzRGfARVuVkxvM8Q12nh19l4BF/G7zGA1oe+9wcC6saFBHTISrpIcKzhiXtSrlSrluCfvMuledoCTQ==} - engines: {node: '>= 20'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@tailwindcss/oxide-linux-x64-musl@4.3.0': - resolution: {integrity: sha512-Z0IADbDo8bh6I7h2IQMx601AdXBLfFpEdUotft86evd/8ZPflZe9COPO8Q1vw+pfLWIUo9zN/JGZvwuAJqduqg==} - engines: {node: '>= 20'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@tailwindcss/oxide-wasm32-wasi@4.3.0': - resolution: {integrity: sha512-HNZGOUxEmElksYR7S6sC5jTeNGpobAsy9u7Gu0AskJ8/20FR9GqebUyB+HBcU/ax6BHuiuJi+Oda4B+YX6H1yA==} - engines: {node: '>=14.0.0'} - cpu: [wasm32] - bundledDependencies: - - '@napi-rs/wasm-runtime' - - '@emnapi/core' - - '@emnapi/runtime' - - '@tybys/wasm-util' - - '@emnapi/wasi-threads' - - tslib - - '@tailwindcss/oxide-win32-arm64-msvc@4.3.0': - resolution: {integrity: sha512-Pe+RPVTi1T+qymuuRpcdvwSVZjnll/f7n8gBxMMh3xLTctMDKqpdfGimbMyioqtLhUYZxdJ9wGNhV7MKHvgZsQ==} - engines: {node: '>= 20'} - cpu: [arm64] - os: [win32] - - '@tailwindcss/oxide-win32-x64-msvc@4.3.0': - resolution: {integrity: sha512-Mvrf2kXW/yeW/OTezZlCGOirXRcUuLIBx/5Y12BaPM7wJoryG6dfS/NJL8aBPqtTEx/Vm4T4vKzFUcKDT+TKUA==} - engines: {node: '>= 20'} - cpu: [x64] - os: [win32] - - '@tailwindcss/oxide@4.3.0': - resolution: {integrity: sha512-F7HZGBeN9I0/AuuJS5PwcD8xayx5ri5GhjYUDBEVYUkexyA/giwbDNjRVrxSezE3T250OU2K/wp/ltWx3UOefg==} - engines: {node: '>= 20'} - - '@tailwindcss/typography@0.5.19': - resolution: {integrity: sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==} - peerDependencies: - tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1' - - '@tailwindcss/vite@4.3.0': - resolution: {integrity: sha512-t6J3OrB5Fc0ExuhohouH0fWUGMYL6PTLhW+E7zIk/pdbnJARZDCwjBznFnkh5ynRnIRSI4YjtTH0t6USjJISrw==} - peerDependencies: - vite: ^5.2.0 || ^6 || ^7 || ^8 - - '@tanstack/history@1.161.6': - resolution: {integrity: sha512-NaOGLRrddszbQj9upGat6HG/4TKvXLvu+osAIgfxPYA+eIvYKv8GKDJOrY2D3/U9MRnKfMWD7bU4jeD4xmqyIg==} - engines: {node: '>=20.19'} - - '@tanstack/query-core@5.99.0': - resolution: {integrity: sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==} - - '@tanstack/react-query@5.99.0': - resolution: {integrity: sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==} - peerDependencies: - react: ^18 || ^19 - - '@tanstack/react-router-devtools@1.166.13': - resolution: {integrity: sha512-6yKRFFJrEEOiGp5RAAuGCYsl81M4XAhJmLcu9PKj+HZle4A3dsP60lwHoqQYWHMK9nKKFkdXR+D8qxzxqtQbEA==} - engines: {node: '>=20.19'} - peerDependencies: - '@tanstack/react-router': ^1.168.15 - '@tanstack/router-core': ^1.168.11 - react: '>=18.0.0 || >=19.0.0' - react-dom: '>=18.0.0 || >=19.0.0' - peerDependenciesMeta: - '@tanstack/router-core': - optional: true - - '@tanstack/react-router@1.169.2': - resolution: {integrity: sha512-OJM7Kguc7ERnweaNRWsyWgIKcl3z23rD1B4jaxjzd9RGdnzpt2HfrWa9rggbT0Hfzhfo4D2ZmsfoTme035tniQ==} - engines: {node: '>=20.19'} - peerDependencies: - react: '>=18.0.0 || >=19.0.0' - react-dom: '>=18.0.0 || >=19.0.0' - - '@tanstack/react-store@0.9.3': - resolution: {integrity: sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==} - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - - '@tanstack/router-core@1.168.7': - resolution: {integrity: sha512-z4UEdlzMrFaKBsG4OIxlZEm+wsYBtEp//fnX6kW18jhQpETNcM6u2SXNdX+bcIYp6AaR7ERS3SBENzjC/xxwQQ==} - engines: {node: '>=20.19'} - hasBin: true - - '@tanstack/router-core@1.169.2': - resolution: {integrity: sha512-5sm0DJF1A7Mz+9gy4Gz/lLovNailK3yot4vYvz9MkBUPw26uLnhQiR8hSCYxucjE0wD6Mdlc5l+Z0/XTlZ7xHw==} - engines: {node: '>=20.19'} - - '@tanstack/router-devtools-core@1.167.3': - resolution: {integrity: sha512-fJ1VMhyQgnoashTrP763c2HRc9kofgF61L7Jb3F6eTHAmCKtGVx8BRtiFt37sr3U0P0jmaaiiSPGP6nT5JtVNg==} - engines: {node: '>=20.19'} - peerDependencies: - '@tanstack/router-core': ^1.168.11 - csstype: ^3.0.10 - peerDependenciesMeta: - csstype: - optional: true - - '@tanstack/router-generator@1.166.22': - resolution: {integrity: sha512-wQ7H8/Q2rmSPuaxWnurJ3DATNnqWV2tajxri9TSiW4QHsG7cWPD34+goeIinKG+GajJyEdfVpz6w/gRJXfbAPw==} - engines: {node: '>=20.19'} - - '@tanstack/router-plugin@1.167.9': - resolution: {integrity: sha512-h/VV05FEHd4PVyc5Zy8B3trWLcdLt/Pmp+mfifmBKGRw+MUtvdQKbBHhmy4ouOf67s5zDJMc+n8R3xgU7bDwFA==} - engines: {node: '>=20.19'} - hasBin: true - peerDependencies: - '@rsbuild/core': '>=1.0.2' - '@tanstack/react-router': ^1.168.8 - vite: '>=5.0.0 || >=6.0.0 || >=7.0.0' - vite-plugin-solid: ^2.11.10 - webpack: '>=5.92.0' - peerDependenciesMeta: - '@rsbuild/core': - optional: true - '@tanstack/react-router': - optional: true - vite: - optional: true - vite-plugin-solid: - optional: true - webpack: - optional: true - - '@tanstack/router-utils@1.161.6': - resolution: {integrity: sha512-nRcYw+w2OEgK6VfjirYvGyPLOK+tZQz1jkYcmH5AjMamQ9PycnlxZF2aEZtPpNoUsaceX2bHptn6Ub5hGXqNvw==} - engines: {node: '>=20.19'} - - '@tanstack/store@0.9.3': - resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==} - - '@tanstack/virtual-file-routes@1.161.7': - resolution: {integrity: sha512-olW33+Cn+bsCsZKPwEGhlkqS6w3M2slFv11JIobdnCFKMLG97oAI2kWKdx5/zsywTL8flpnoIgaZZPlQTFYhdQ==} - engines: {node: '>=20.19'} - hasBin: true - - '@trivago/prettier-plugin-sort-imports@6.0.2': - resolution: {integrity: sha512-3DgfkukFyC/sE/VuYjaUUWoFfuVjPK55vOFDsxD56XXynFMCZDYFogH2l/hDfOsQAm1myoU/1xByJ3tWqtulXA==} - engines: {node: '>= 20'} - peerDependencies: - '@vue/compiler-sfc': 3.x - prettier: 2.x - 3.x - prettier-plugin-ember-template-tag: '>= 2.0.0' - prettier-plugin-svelte: 3.x - svelte: 4.x || 5.x - peerDependenciesMeta: - '@vue/compiler-sfc': - optional: true - prettier-plugin-ember-template-tag: - optional: true - prettier-plugin-svelte: - optional: true - svelte: - optional: true - - '@ts-morph/common@0.27.0': - resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==} - - '@tybys/wasm-util@0.10.2': - resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} - - '@types/debug@4.1.13': - resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} - - '@types/esrecurse@4.3.1': - resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} - - '@types/estree-jsx@1.0.5': - resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==} - - '@types/estree@1.0.9': - resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} - - '@types/hast@3.0.4': - resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} - - '@types/json-schema@7.0.15': - resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - - '@types/mdast@4.0.4': - resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==} - - '@types/ms@2.1.0': - resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} - - '@types/node@25.6.0': - resolution: {integrity: sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==} - - '@types/react-dom@19.2.3': - resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} - peerDependencies: - '@types/react': ^19.2.0 - - '@types/react@19.2.14': - resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} - - '@types/unist@2.0.11': - resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==} - - '@types/unist@3.0.3': - resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} - - '@types/validate-npm-package-name@4.0.2': - resolution: {integrity: sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==} - - '@typescript-eslint/eslint-plugin@8.58.2': - resolution: {integrity: sha512-aC2qc5thQahutKjP+cl8cgN9DWe3ZUqVko30CMSZHnFEHyhOYoZSzkGtAI2mcwZ38xeImDucI4dnqsHiOYuuCw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - '@typescript-eslint/parser': ^8.58.2 - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/eslint-plugin@8.62.1': - resolution: {integrity: sha512-4EQM77WgVNxj7OkL/5b/D/xZsw00G577+UriYTC7JF5opcF3T2AuoeY7ueLaZgSVjSgCS6yOAJB5bRGLPSJUzA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - '@typescript-eslint/parser': ^8.62.1 - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/parser@8.62.1': - resolution: {integrity: sha512-sPhE4iHuJDSvoAiec+Ro8JyXw8f0ql13HFR82P99nCm9GwTEKG0KYLvDe6REk8BCXuit6vJAv/Yxg5ABaNS2rA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/project-service@8.58.2': - resolution: {integrity: sha512-Cq6UfpZZk15+r87BkIh5rDpi38W4b+Sjnb8wQCPPDDweS/LRCFjCyViEbzHk5Ck3f2QDfgmlxqSa7S7clDtlfg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/project-service@8.62.1': - resolution: {integrity: sha512-yQ3RgY5RkSBpsNS1Bx/JQEcA24FOSdfGktoyprAr5u18390UQdtVcfnEv4nIrIshNnavlVyZBKxQwT1fIAE6cg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/scope-manager@8.58.2': - resolution: {integrity: sha512-SgmyvDPexWETQek+qzZnrG6844IaO02UVyOLhI4wpo82dpZJY9+6YZCKAMFzXb7qhx37mFK1QcPQ18tud+vo6Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/scope-manager@8.62.1': - resolution: {integrity: sha512-r4d249KbQ1SFdpeStvob8Ih6aPPIzfqllPVOtvhve6ZcpuVcYo5/7zUWckKpHE7StASX4kTKZTLf0WQm/wPkcg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/tsconfig-utils@8.58.2': - resolution: {integrity: sha512-3SR+RukipDvkkKp/d0jP0dyzuls3DbGmwDpVEc5wqk5f38KFThakqAAO0XMirWAE+kT00oTauTbzMFGPoAzB0A==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/tsconfig-utils@8.62.1': - resolution: {integrity: sha512-xadytJqX9vJVQ2fdQjkcIVigwaOJNWkpjdLt6cEQ+xPnrI1fkp+/jZE/I97k9KUjqtpd25i0HeyZf3T6dutv2g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/type-utils@8.58.2': - resolution: {integrity: sha512-Z7EloNR/B389FvabdGeTo2XMs4W9TjtPiO9DAsmT0yom0bwlPyRjkJ1uCdW1DvrrrYP50AJZ9Xc3sByZA9+dcg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/type-utils@8.62.1': - resolution: {integrity: sha512-aXM5xlqXiTxPibXB93cLAURfT3rlizf7uMXISCXy66Isr/9hISJx3yDsKl0L7lKa51b8JpFuNKby0/O0pEm9jg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/types@8.58.2': - resolution: {integrity: sha512-9TukXyATBQf/Jq9AMQXfvurk+G5R2MwfqQGDR2GzGz28HvY/lXNKGhkY+6IOubwcquikWk5cjlgPvD2uAA7htQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/types@8.62.1': - resolution: {integrity: sha512-ooCzJFaf+Hg+uG6fA3NRFGuFjlfNlDhBthbv4ZPU/0elCAFUfnyXUvf/WOpHz/jYwSmvU2GkR2LtyUfy1AxZ1Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/typescript-estree@8.58.2': - resolution: {integrity: sha512-ELGuoofuhhoCvNbQjFFiobFcGgcDCEm0ThWdmO4Z0UzLqPXS3KFvnEZ+SHewwOYHjM09tkzOWXNTv9u6Gqtyuw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/typescript-estree@8.62.1': - resolution: {integrity: sha512-xMcW9oP9u7fAMXYs9A65CVmtLQe2r//oXINHfi8HV+oiqhih17sbLdhXr4540YWlgpDKQdY854OL5ZrdCiQsAA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/utils@8.58.2': - resolution: {integrity: sha512-QZfjHNEzPY8+l0+fIXMvuQ2sJlplB4zgDZvA+NmvZsZv3EQwOcc1DuIU1VJUTWZ/RKouBMhDyNaBMx4sWvrzRA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/utils@8.62.1': - resolution: {integrity: sha512-sHtbPfuKNZCG+ih8SyjjucqRntSVmp8XgL5u6o9mAhiSn8ds5o/M/XdM0abweme2Tln3szOstOrZ9OXitvPh0g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - '@typescript-eslint/visitor-keys@8.58.2': - resolution: {integrity: sha512-f1WO2Lx8a9t8DARmcWAUPJbu0G20bJlj8L4z72K00TMeJAoyLr/tHhI/pzYBLrR4dXWkcxO1cWYZEOX8DKHTqA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/visitor-keys@8.62.1': - resolution: {integrity: sha512-4g3BLxfdTMy8iZG0MaBkadnlRrCJ74cQiFbyEVMrkwIoqdyaXXQM22cotDvrl4x28wgIZ9rEJRoM+mmhSJpJ1g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@ungap/structured-clone@1.3.0': - resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} - deprecated: Potential CWE-502 - Update to 1.3.1 or higher - - '@vitejs/plugin-react@6.0.3': - resolution: {integrity: sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg==} - engines: {node: ^20.19.0 || >=22.12.0} - peerDependencies: - '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 - babel-plugin-react-compiler: ^1.0.0 - vite: ^8.0.0 - peerDependenciesMeta: - '@rolldown/plugin-babel': - optional: true - babel-plugin-react-compiler: - optional: true - - accepts@2.0.0: - resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} - engines: {node: '>= 0.6'} - - acorn-jsx@5.3.2: - resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} - peerDependencies: - acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 - - acorn@8.16.0: - resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} - engines: {node: '>=0.4.0'} - hasBin: true - - acorn@8.17.0: - resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==} - engines: {node: '>=0.4.0'} - hasBin: true - - ajv-formats@2.1.1: - resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} - peerDependencies: - ajv: ^8.0.0 - peerDependenciesMeta: - ajv: - optional: true - - ajv-formats@3.0.1: - resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} - peerDependencies: - ajv: ^8.0.0 - peerDependenciesMeta: - ajv: - optional: true - - ajv@6.15.0: - resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} - - ajv@8.20.0: - resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} - - ansi-colors@4.1.3: - resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} - engines: {node: '>=6'} - - ansi-regex@5.0.1: - resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} - engines: {node: '>=8'} - - ansi-regex@6.2.2: - resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} - engines: {node: '>=12'} - - ansi-styles@6.2.3: - resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} - engines: {node: '>=12'} - - ansis@4.2.0: - resolution: {integrity: sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig==} - engines: {node: '>=14'} - - anymatch@3.1.3: - resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} - engines: {node: '>= 8'} - - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - - aria-hidden@1.2.6: - resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} - engines: {node: '>=10'} - - ast-types@0.16.1: - resolution: {integrity: sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==} - engines: {node: '>=4'} - - atomically@1.7.0: - resolution: {integrity: sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==} - engines: {node: '>=10.12.0'} - - babel-dead-code-elimination@1.0.12: - resolution: {integrity: sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig==} - - bail@2.0.2: - resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} - - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - - balanced-match@4.0.4: - resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} - engines: {node: 18 || 20 || >=22} - - baseline-browser-mapping@2.10.41: - resolution: {integrity: sha512-WwS7MHhqGHHlaVsqRZnhvCEMS0owDX+SxRlve7JkuH7My1Ara3ZriTmCQupPfYjxMZ8I/tgxtJYr2t7taHaH4A==} - engines: {node: '>=6.0.0'} - hasBin: true - - binary-extensions@2.3.0: - resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} - engines: {node: '>=8'} - - body-parser@2.3.0: - resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} - engines: {node: '>=18'} - - brace-expansion@2.0.3: - resolution: {integrity: sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==} - - brace-expansion@5.0.6: - resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} - engines: {node: 18 || 20 || >=22} - - braces@3.0.3: - resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} - engines: {node: '>=8'} - - browserslist@4.28.4: - resolution: {integrity: sha512-MTc8i/x9jBQd1iMw2CFGS+rwMa07eYjLR0CCTLDACl9xhxy+nIs3KeML/biicXtk9JrZ6dnnTatmc7ErPXIxqw==} - engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} - hasBin: true - - bundle-name@4.1.0: - resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==} - engines: {node: '>=18'} - - bytes@3.1.2: - resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} - engines: {node: '>= 0.8'} - - call-bind-apply-helpers@1.0.2: - resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} - engines: {node: '>= 0.4'} - - call-bound@1.0.4: - resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} - engines: {node: '>= 0.4'} - - callsites@3.1.0: - resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} - engines: {node: '>=6'} - - caniuse-lite@1.0.30001800: - resolution: {integrity: sha512-MMHtuAz9Ys840zAY5F4k6fV5GaivZ9sPk+nz0mY+GYVzRBnYkN0mpqkSR92oWRQ19yQWo4HvBV/FnC16AJX8MA==} - - ccount@2.0.1: - resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} - - chalk@5.6.2: - resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} - engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} - - character-entities-html4@2.1.0: - resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} - - character-entities-legacy@3.0.0: - resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==} - - character-entities@2.0.2: - resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==} - - character-reference-invalid@2.0.1: - resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==} - - chokidar@3.6.0: - resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} - engines: {node: '>= 8.10.0'} - - class-variance-authority@0.7.1: - resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} - - cli-cursor@5.0.0: - resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==} - engines: {node: '>=18'} - - cli-spinners@2.9.2: - resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==} - engines: {node: '>=6'} - - clsx@2.1.1: - resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} - engines: {node: '>=6'} - - cmdk@1.1.1: - resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==} - peerDependencies: - react: ^18 || ^19 || ^19.0.0-rc - react-dom: ^18 || ^19 || ^19.0.0-rc - - code-block-writer@13.0.3: - resolution: {integrity: sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==} - - comma-separated-tokens@2.0.3: - resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} - - commander@11.1.0: - resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} - engines: {node: '>=16'} - - commander@14.0.3: - resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} - engines: {node: '>=20'} - - conf@10.2.0: - resolution: {integrity: sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg==} - engines: {node: '>=12'} - - content-disposition@1.1.0: - resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==} - engines: {node: '>=18'} - - content-type@1.0.5: - resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} - engines: {node: '>= 0.6'} - - content-type@2.0.0: - resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==} - engines: {node: '>=18'} - - convert-source-map@2.0.0: - resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} - - cookie-es@2.0.0: - resolution: {integrity: sha512-RAj4E421UYRgqokKUmotqAwuplYw15qtdXfY+hGzgCJ/MBjCVZcSoHK/kH9kocfjRjcDME7IiDWR/1WX1TM2Pg==} - - cookie-es@3.1.1: - resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==} - - cookie-signature@1.2.2: - resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} - engines: {node: '>=6.6.0'} - - cookie@0.7.2: - resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} - engines: {node: '>= 0.6'} - - cors@2.8.6: - resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} - engines: {node: '>= 0.10'} - - cosmiconfig@9.0.2: - resolution: {integrity: sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==} - engines: {node: '>=14'} - peerDependencies: - typescript: '>=4.9.5' - peerDependenciesMeta: - typescript: - optional: true - - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} - engines: {node: '>= 8'} - - cssesc@3.0.0: - resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} - engines: {node: '>=4'} - hasBin: true - - csstype@3.2.3: - resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} - - dayjs@1.11.20: - resolution: {integrity: sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==} - - debounce-fn@4.0.0: - resolution: {integrity: sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==} - engines: {node: '>=10'} - - debug@4.4.3: - resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - - decode-named-character-reference@1.3.0: - resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==} - - dedent@1.7.2: - resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==} - peerDependencies: - babel-plugin-macros: ^3.1.0 - peerDependenciesMeta: - babel-plugin-macros: - optional: true - - deep-is@0.1.4: - resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - - deepmerge@4.3.1: - resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} - engines: {node: '>=0.10.0'} - - default-browser-id@5.0.1: - resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} - engines: {node: '>=18'} - - default-browser@5.5.0: - resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==} - engines: {node: '>=18'} - - define-lazy-prop@2.0.0: - resolution: {integrity: sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==} - engines: {node: '>=8'} - - define-lazy-prop@3.0.0: - resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==} - engines: {node: '>=12'} - - depd@2.0.0: - resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} - engines: {node: '>= 0.8'} - - dequal@2.0.3: - resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} - engines: {node: '>=6'} - - detect-libc@2.1.2: - resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} - engines: {node: '>=8'} - - detect-node-es@1.1.0: - resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} - - devlop@1.1.0: - resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} - - diff@8.0.4: - resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} - engines: {node: '>=0.3.1'} - - dot-prop@6.0.1: - resolution: {integrity: sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==} - engines: {node: '>=10'} - - dotenv@17.4.2: - resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} - engines: {node: '>=12'} - - dunder-proto@1.0.1: - resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} - engines: {node: '>= 0.4'} - - ee-first@1.1.1: - resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - - electron-to-chromium@1.5.384: - resolution: {integrity: sha512-g6KAKY1vkYsADvSPWvdJsuYT0ixdcu6lUtD9P/wJKGBEDlZVXh2AX42j1mPqqaQPDluWjara9ziQ7xqAeXCt5A==} - - emoji-regex@10.6.0: - resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} - - encodeurl@2.0.0: - resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} - engines: {node: '>= 0.8'} - - enhanced-resolve@5.21.0: - resolution: {integrity: sha512-otxSQPw4lkOZWkHpB3zaEQs6gWYEsmX4xQF68ElXC/TWvGxGMSGOvoNbaLXm6/cS/fSfHtsEdw90y20PCd+sCA==} - engines: {node: '>=10.13.0'} - - enquirer@2.4.1: - resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==} - engines: {node: '>=8.6'} - - entities@6.0.1: - resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} - engines: {node: '>=0.12'} - - env-paths@2.2.1: - resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} - engines: {node: '>=6'} - - error-ex@1.3.4: - resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} - - es-define-property@1.0.1: - resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} - engines: {node: '>= 0.4'} - - es-errors@1.3.0: - resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} - engines: {node: '>= 0.4'} - - es-object-atoms@1.1.2: - resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} - engines: {node: '>= 0.4'} - - esbuild@0.27.4: - resolution: {integrity: sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==} - engines: {node: '>=18'} - hasBin: true - - escalade@3.2.0: - resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} - engines: {node: '>=6'} - - escape-html@1.0.3: - resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} - - escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} - engines: {node: '>=10'} - - escape-string-regexp@5.0.0: - resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} - engines: {node: '>=12'} - - eslint-config-prettier@10.1.8: - resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==} - hasBin: true - peerDependencies: - eslint: '>=7.0.0' - - eslint-plugin-react-hooks@7.1.1: - resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==} - engines: {node: '>=18'} - peerDependencies: - eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0 - - eslint-plugin-react-refresh@0.5.2: - resolution: {integrity: sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==} - peerDependencies: - eslint: ^9 || ^10 - - eslint-scope@9.1.2: - resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - eslint-visitor-keys@3.4.3: - resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - eslint-visitor-keys@5.0.1: - resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - eslint@10.4.1: - resolution: {integrity: sha512-AyIKhnOBuOAdueD7RB3xB+YeAWScb9jHsJBgH2Hcde8InP5JYhqrRR6iTMHyTEwgENK54Cp44e4v8BwNhsuHuw==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - hasBin: true - peerDependencies: - jiti: '*' - peerDependenciesMeta: - jiti: - optional: true - - espree@11.2.0: - resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} - - esprima@4.0.1: - resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} - engines: {node: '>=4'} - hasBin: true - - esquery@1.7.0: - resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} - engines: {node: '>=0.10'} - - esrecurse@4.3.0: - resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} - engines: {node: '>=4.0'} - - estraverse@5.3.0: - resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} - engines: {node: '>=4.0'} - - estree-util-is-identifier-name@3.0.0: - resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==} - - esutils@2.0.3: - resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} - engines: {node: '>=0.10.0'} - - etag@1.8.1: - resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} - engines: {node: '>= 0.6'} - - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - - eventsource@3.0.7: - resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} - engines: {node: '>=18.0.0'} - - execa@5.1.1: - resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} - engines: {node: '>=10'} - - execa@9.6.1: - resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==} - engines: {node: ^18.19.0 || >=20.5.0} - - express-rate-limit@8.5.2: - resolution: {integrity: sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==} - engines: {node: '>= 16'} - peerDependencies: - express: '>= 4.11' - - express@5.2.1: - resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==} - engines: {node: '>= 18'} - - extend@3.0.2: - resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} - - fast-deep-equal@3.1.3: - resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} - - fast-glob@3.3.3: - resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} - engines: {node: '>=8.6.0'} - - fast-json-stable-stringify@2.1.0: - resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} - - fast-levenshtein@2.0.6: - resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - - fast-uri@3.1.3: - resolution: {integrity: sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==} - - fastq@1.20.1: - resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} - - fdir@6.5.0: - resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} - engines: {node: '>=12.0.0'} - peerDependencies: - picomatch: ^3 || ^4 - peerDependenciesMeta: - picomatch: - optional: true - - figures@6.1.0: - resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==} - engines: {node: '>=18'} - - file-entry-cache@8.0.0: - resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} - engines: {node: '>=16.0.0'} - - fill-range@7.1.1: - resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} - engines: {node: '>=8'} - - finalhandler@2.1.1: - resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} - engines: {node: '>= 18.0.0'} - - find-up@3.0.0: - resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==} - engines: {node: '>=6'} - - find-up@5.0.0: - resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} - engines: {node: '>=10'} - - flat-cache@4.0.1: - resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} - engines: {node: '>=16'} - - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} - - forwarded@0.2.0: - resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} - engines: {node: '>= 0.6'} - - fresh@2.0.0: - resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} - engines: {node: '>= 0.8'} - - fs-extra@11.3.6: - resolution: {integrity: sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==} - engines: {node: '>=14.14'} - - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - - fuzzysort@3.1.0: - resolution: {integrity: sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ==} - - gensync@1.0.0-beta.2: - resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} - engines: {node: '>=6.9.0'} - - get-east-asian-width@1.5.0: - resolution: {integrity: sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==} - engines: {node: '>=18'} - - get-east-asian-width@1.6.0: - resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==} - engines: {node: '>=18'} - - get-intrinsic@1.3.0: - resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} - engines: {node: '>= 0.4'} - - get-nonce@1.0.1: - resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} - engines: {node: '>=6'} - - get-own-enumerable-keys@1.0.0: - resolution: {integrity: sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA==} - engines: {node: '>=14.16'} - - get-proto@1.0.1: - resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} - engines: {node: '>= 0.4'} - - get-stream@6.0.1: - resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} - engines: {node: '>=10'} - - get-stream@9.0.1: - resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==} - engines: {node: '>=18'} - - get-tsconfig@4.13.7: - resolution: {integrity: sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==} - - glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - - glob-parent@6.0.2: - resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} - engines: {node: '>=10.13.0'} - - globals@17.6.0: - resolution: {integrity: sha512-sepffkT8stwnIYbsMBpoCHJuJM5l98FUF2AnE07hfvE0m/qp3R586hw4jF4uadbhvg1ooIdzuu7CsfD2jzCaNA==} - engines: {node: '>=18'} - - goober@2.1.18: - resolution: {integrity: sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==} - peerDependencies: - csstype: ^3.0.10 - - gopd@1.2.0: - resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} - engines: {node: '>= 0.4'} - - graceful-fs@4.2.11: - resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - - has-symbols@1.1.0: - resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} - engines: {node: '>= 0.4'} - - hasown@2.0.4: - resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} - engines: {node: '>= 0.4'} - - hast-util-from-parse5@8.0.3: - resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==} - - hast-util-is-element@3.0.0: - resolution: {integrity: sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==} - - hast-util-parse-selector@4.0.0: - resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==} - - hast-util-raw@9.1.0: - resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==} - - hast-util-sanitize@5.0.2: - resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==} - - hast-util-to-jsx-runtime@2.3.6: - resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==} - - hast-util-to-parse5@8.0.1: - resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==} - - hast-util-to-text@4.0.2: - resolution: {integrity: sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==} - - hast-util-whitespace@3.0.0: - resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==} - - hastscript@9.0.1: - resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==} - - hermes-estree@0.25.1: - resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==} - - hermes-parser@0.25.1: - resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==} - - highlight.js@11.11.1: - resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==} - engines: {node: '>=12.0.0'} - - hono@4.12.27: - resolution: {integrity: sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==} - engines: {node: '>=16.9.0'} - - html-parse-stringify@3.0.1: - resolution: {integrity: sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==} - - html-url-attributes@3.0.1: - resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==} - - html-void-elements@3.0.0: - resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} - - http-errors@2.0.1: - resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} - engines: {node: '>= 0.8'} - - human-signals@2.1.0: - resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} - engines: {node: '>=10.17.0'} - - human-signals@8.0.1: - resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==} - engines: {node: '>=18.18.0'} - - i18next-browser-languagedetector@8.2.1: - resolution: {integrity: sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw==} - - i18next@26.0.10: - resolution: {integrity: sha512-k3yGPAlWR2RdMYoVXJoDZDT87qeHIWKH7gVksdZMpRty7QX/D9QZeYGvN08KGbKHke9wn01eYT+EEsrqX/YTlw==} - peerDependencies: - typescript: ^5 || ^6 - peerDependenciesMeta: - typescript: - optional: true - - iconv-lite@0.7.2: - resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==} - engines: {node: '>=0.10.0'} - - ignore@5.3.2: - resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} - engines: {node: '>= 4'} - - ignore@7.0.5: - resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} - engines: {node: '>= 4'} - - import-fresh@3.3.1: - resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} - engines: {node: '>=6'} - - imurmurhash@0.1.4: - resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} - engines: {node: '>=0.8.19'} - - inherits@2.0.4: - resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - - inline-style-parser@0.2.7: - resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==} - - ip-address@10.2.0: - resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} - engines: {node: '>= 12'} - - ipaddr.js@1.9.1: - resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} - engines: {node: '>= 0.10'} - - is-alphabetical@2.0.1: - resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==} - - is-alphanumerical@2.0.1: - resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==} - - is-arrayish@0.2.1: - resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} - - is-binary-path@2.1.0: - resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} - engines: {node: '>=8'} - - is-decimal@2.0.1: - resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==} - - is-docker@2.2.1: - resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==} - engines: {node: '>=8'} - hasBin: true - - is-docker@3.0.0: - resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - hasBin: true - - is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} - - is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} - - is-hexadecimal@2.0.1: - resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==} - - is-in-ssh@1.0.0: - resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==} - engines: {node: '>=20'} - - is-inside-container@1.0.0: - resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==} - engines: {node: '>=14.16'} - hasBin: true - - is-interactive@2.0.0: - resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==} - engines: {node: '>=12'} - - is-number@7.0.0: - resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} - engines: {node: '>=0.12.0'} - - is-obj@2.0.0: - resolution: {integrity: sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==} - engines: {node: '>=8'} - - is-obj@3.0.0: - resolution: {integrity: sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ==} - engines: {node: '>=12'} - - is-plain-obj@4.1.0: - resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} - engines: {node: '>=12'} - - is-promise@4.0.0: - resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} - - is-regexp@3.1.0: - resolution: {integrity: sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA==} - engines: {node: '>=12'} - - is-stream@2.0.1: - resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} - engines: {node: '>=8'} - - is-stream@4.0.1: - resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==} - engines: {node: '>=18'} - - is-unicode-supported@1.3.0: - resolution: {integrity: sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==} - engines: {node: '>=12'} - - is-unicode-supported@2.1.0: - resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} - engines: {node: '>=18'} - - is-wsl@2.2.0: - resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} - engines: {node: '>=8'} - - is-wsl@3.1.1: - resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==} - engines: {node: '>=16'} - - isbot@5.1.40: - resolution: {integrity: sha512-yNeeynhhtIVRBk12tBV4eHNxwB42HzR4Q3Ea7vCOiJhImGaAIdIMrbJtacQlBizGLjUPw+akkFI5Dn9T70XoVQ==} - engines: {node: '>=18'} - - isexe@2.0.0: - resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} - - isexe@3.1.5: - resolution: {integrity: sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==} - engines: {node: '>=18'} - - javascript-natural-sort@0.7.1: - resolution: {integrity: sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==} - - jiti@2.7.0: - resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} - hasBin: true - - jose@6.2.3: - resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==} - - jotai@2.20.0: - resolution: {integrity: sha512-b5GAqgmXmXzB4WPaTH26ppk9Sl7AA9WSQX7yfdM+gJ1rFROiWcVbi97gFuN/yVCojOcbcvop2sfLL+fjxW0JVg==} - engines: {node: '>=12.20.0'} - peerDependencies: - '@babel/core': '>=7.0.0' - '@babel/template': '>=7.0.0' - '@types/react': '>=17.0.0' - react: '>=17.0.0' - peerDependenciesMeta: - '@babel/core': - optional: true - '@babel/template': - optional: true - '@types/react': - optional: true - react: - optional: true - - js-tokens@4.0.0: - resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - - js-yaml@4.3.0: - resolution: {integrity: sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==} - hasBin: true - - jsesc@3.1.0: - resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} - engines: {node: '>=6'} - hasBin: true - - json-buffer@3.0.1: - resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} - - json-parse-even-better-errors@2.3.1: - resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} - - json-schema-traverse@0.4.1: - resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} - - json-schema-traverse@1.0.0: - resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} - - json-schema-typed@7.0.3: - resolution: {integrity: sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A==} - - json-schema-typed@8.0.2: - resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} - - json-stable-stringify-without-jsonify@1.0.1: - resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} - - json5@2.2.3: - resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} - engines: {node: '>=6'} - hasBin: true - - jsonfile@6.2.1: - resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} - - keyv@4.5.4: - resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - - kleur@3.0.3: - resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} - engines: {node: '>=6'} - - kleur@4.1.5: - resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} - engines: {node: '>=6'} - - levn@0.4.1: - resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} - engines: {node: '>= 0.8.0'} - - lightningcss-android-arm64@1.32.0: - resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [android] - - lightningcss-darwin-arm64@1.32.0: - resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [darwin] - - lightningcss-darwin-x64@1.32.0: - resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [darwin] - - lightningcss-freebsd-x64@1.32.0: - resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [freebsd] - - lightningcss-linux-arm-gnueabihf@1.32.0: - resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} - engines: {node: '>= 12.0.0'} - cpu: [arm] - os: [linux] - - lightningcss-linux-arm64-gnu@1.32.0: - resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - lightningcss-linux-arm64-musl@1.32.0: - resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [musl] - - lightningcss-linux-x64-gnu@1.32.0: - resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [glibc] - - lightningcss-linux-x64-musl@1.32.0: - resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [musl] - - lightningcss-win32-arm64-msvc@1.32.0: - resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [win32] - - lightningcss-win32-x64-msvc@1.32.0: - resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [win32] - - lightningcss@1.32.0: - resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} - engines: {node: '>= 12.0.0'} - - lines-and-columns@1.2.4: - resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} - - locate-path@3.0.0: - resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==} - engines: {node: '>=6'} - - locate-path@6.0.0: - resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} - engines: {node: '>=10'} - - lodash-es@4.17.23: - resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==} - - log-symbols@6.0.0: - resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==} - engines: {node: '>=18'} - - longest-streak@3.1.0: - resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==} - - lowlight@3.3.0: - resolution: {integrity: sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==} - - lru-cache@5.1.1: - resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} - - magic-string@0.30.21: - resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} - - markdown-table@3.0.4: - resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==} - - math-intrinsics@1.1.0: - resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} - engines: {node: '>= 0.4'} - - mdast-util-find-and-replace@3.0.2: - resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==} - - mdast-util-from-markdown@2.0.3: - resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==} - - mdast-util-gfm-autolink-literal@2.0.1: - resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==} - - mdast-util-gfm-footnote@2.1.0: - resolution: {integrity: sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==} - - mdast-util-gfm-strikethrough@2.0.0: - resolution: {integrity: sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==} - - mdast-util-gfm-table@2.0.0: - resolution: {integrity: sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==} - - mdast-util-gfm-task-list-item@2.0.0: - resolution: {integrity: sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==} - - mdast-util-gfm@3.1.0: - resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==} - - mdast-util-mdx-expression@2.0.1: - resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==} - - mdast-util-mdx-jsx@3.2.0: - resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==} - - mdast-util-mdxjs-esm@2.0.1: - resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==} - - mdast-util-phrasing@4.1.0: - resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==} - - mdast-util-to-hast@13.2.1: - resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==} - - mdast-util-to-markdown@2.1.2: - resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==} - - mdast-util-to-string@4.0.0: - resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==} - - media-typer@1.1.0: - resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==} - engines: {node: '>= 0.8'} - - merge-descriptors@2.0.0: - resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} - engines: {node: '>=18'} - - merge-stream@2.0.0: - resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} - - merge2@1.4.1: - resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} - engines: {node: '>= 8'} - - micromark-core-commonmark@2.0.3: - resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==} - - micromark-extension-gfm-autolink-literal@2.1.0: - resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==} - - micromark-extension-gfm-footnote@2.1.0: - resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==} - - micromark-extension-gfm-strikethrough@2.1.0: - resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==} - - micromark-extension-gfm-table@2.1.1: - resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==} - - micromark-extension-gfm-tagfilter@2.0.0: - resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==} - - micromark-extension-gfm-task-list-item@2.1.0: - resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==} - - micromark-extension-gfm@3.0.0: - resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==} - - micromark-factory-destination@2.0.1: - resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==} - - micromark-factory-label@2.0.1: - resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==} - - micromark-factory-space@2.0.1: - resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==} - - micromark-factory-title@2.0.1: - resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==} - - micromark-factory-whitespace@2.0.1: - resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==} - - micromark-util-character@2.1.1: - resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==} - - micromark-util-chunked@2.0.1: - resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==} - - micromark-util-classify-character@2.0.1: - resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==} - - micromark-util-combine-extensions@2.0.1: - resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==} - - micromark-util-decode-numeric-character-reference@2.0.2: - resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==} - - micromark-util-decode-string@2.0.1: - resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==} - - micromark-util-encode@2.0.1: - resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} - - micromark-util-html-tag-name@2.0.1: - resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==} - - micromark-util-normalize-identifier@2.0.1: - resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==} - - micromark-util-resolve-all@2.0.1: - resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==} - - micromark-util-sanitize-uri@2.0.1: - resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==} - - micromark-util-subtokenize@2.1.0: - resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==} - - micromark-util-symbol@2.0.1: - resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} - - micromark-util-types@2.0.2: - resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==} - - micromark@4.0.2: - resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==} - - micromatch@4.0.8: - resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} - engines: {node: '>=8.6'} - - mime-db@1.54.0: - resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} - engines: {node: '>= 0.6'} - - mime-types@3.0.2: - resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} - engines: {node: '>=18'} - - mimic-fn@2.1.0: - resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} - engines: {node: '>=6'} - - mimic-fn@3.1.0: - resolution: {integrity: sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ==} - engines: {node: '>=8'} - - mimic-function@5.0.1: - resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==} - engines: {node: '>=18'} - - minimatch@10.2.5: - resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} - engines: {node: 18 || 20 || >=22} - - minimatch@9.0.9: - resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} - engines: {node: '>=16 || 14 >=14.17'} - - minimist@1.2.8: - resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - - ms@2.1.3: - resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - - nanoid@3.3.15: - resolution: {integrity: sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - natural-compare@1.4.0: - resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - - negotiator@1.0.0: - resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} - engines: {node: '>= 0.6'} - - node-releases@2.0.50: - resolution: {integrity: sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==} - engines: {node: '>=18'} - - normalize-path@3.0.0: - resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} - engines: {node: '>=0.10.0'} - - npm-run-path@4.0.1: - resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} - engines: {node: '>=8'} - - npm-run-path@6.0.0: - resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} - engines: {node: '>=18'} - - object-assign@4.1.1: - resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} - engines: {node: '>=0.10.0'} - - object-inspect@1.13.4: - resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} - engines: {node: '>= 0.4'} - - object-treeify@1.1.33: - resolution: {integrity: sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A==} - engines: {node: '>= 10'} - - on-finished@2.4.1: - resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} - engines: {node: '>= 0.8'} - - once@1.4.0: - resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - - onetime@5.1.2: - resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} - engines: {node: '>=6'} - - onetime@7.0.0: - resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==} - engines: {node: '>=18'} - - open@11.0.0: - resolution: {integrity: sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==} - engines: {node: '>=20'} - - open@8.4.2: - resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==} - engines: {node: '>=12'} - - optionator@0.9.4: - resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} - engines: {node: '>= 0.8.0'} - - ora@8.2.0: - resolution: {integrity: sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==} - engines: {node: '>=18'} - - p-limit@2.3.0: - resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} - engines: {node: '>=6'} - - p-limit@3.1.0: - resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} - engines: {node: '>=10'} - - p-locate@3.0.0: - resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==} - engines: {node: '>=6'} - - p-locate@5.0.0: - resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} - engines: {node: '>=10'} - - p-try@2.2.0: - resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} - engines: {node: '>=6'} - - parent-module@1.0.1: - resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} - engines: {node: '>=6'} - - parse-entities@4.0.2: - resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==} - - parse-imports-exports@0.2.4: - resolution: {integrity: sha512-4s6vd6dx1AotCx/RCI2m7t7GCh5bDRUtGNvRfHSP2wbBQdMi67pPe7mtzmgwcaQ8VKK/6IB7Glfyu3qdZJPybQ==} - - parse-json@5.2.0: - resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} - engines: {node: '>=8'} - - parse-ms@4.0.0: - resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==} - engines: {node: '>=18'} - - parse-statements@1.0.11: - resolution: {integrity: sha512-HlsyYdMBnbPQ9Jr/VgJ1YF4scnldvJpJxCVx6KgqPL4dxppsWrJHCIIxQXMJrqGnsRkNPATbeMJ8Yxu7JMsYcA==} - - parse5@7.3.0: - resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} - - parseurl@1.3.3: - resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} - engines: {node: '>= 0.8'} - - path-browserify@1.0.1: - resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} - - path-exists@3.0.0: - resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} - engines: {node: '>=4'} - - path-exists@4.0.0: - resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} - engines: {node: '>=8'} - - path-key@3.1.1: - resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} - engines: {node: '>=8'} - - path-key@4.0.0: - resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} - engines: {node: '>=12'} - - path-to-regexp@8.4.2: - resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} - - pathe@2.0.3: - resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - - picomatch@2.3.2: - resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} - engines: {node: '>=8.6'} - - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - - picomatch@4.0.5: - resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} - engines: {node: '>=12'} - - pkce-challenge@5.0.1: - resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} - engines: {node: '>=16.20.0'} - - pkg-up@3.1.0: - resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==} - engines: {node: '>=8'} - - postcss-selector-parser@6.0.10: - resolution: {integrity: sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==} - engines: {node: '>=4'} - - postcss-selector-parser@7.1.4: - resolution: {integrity: sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg==} - engines: {node: '>=4'} - - postcss@8.5.15: - resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} - engines: {node: ^10 || ^12 || >=14} - - postcss@8.5.16: - resolution: {integrity: sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==} - engines: {node: ^10 || ^12 || >=14} - - powershell-utils@0.1.0: - resolution: {integrity: sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==} - engines: {node: '>=20'} - - prelude-ls@1.2.1: - resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} - engines: {node: '>= 0.8.0'} - - prettier-plugin-tailwindcss@0.8.0: - resolution: {integrity: sha512-V8ITGH87yuBDF6JpEZTOVlUz/saAwqb8f3HRgUj8Lh+tGCcrmorhsLpYqzygwFwK0PE2Ib6Mv3M7T/uE2tZV1g==} - engines: {node: '>=20.19'} - peerDependencies: - '@ianvs/prettier-plugin-sort-imports': '*' - '@prettier/plugin-hermes': '*' - '@prettier/plugin-oxc': '*' - '@prettier/plugin-pug': '*' - '@shopify/prettier-plugin-liquid': '*' - '@trivago/prettier-plugin-sort-imports': '*' - '@zackad/prettier-plugin-twig': '*' - prettier: ^3.0 - prettier-plugin-astro: '*' - prettier-plugin-css-order: '*' - prettier-plugin-jsdoc: '*' - prettier-plugin-marko: '*' - prettier-plugin-multiline-arrays: '*' - prettier-plugin-organize-attributes: '*' - prettier-plugin-organize-imports: '*' - prettier-plugin-sort-imports: '*' - prettier-plugin-svelte: '*' - peerDependenciesMeta: - '@ianvs/prettier-plugin-sort-imports': - optional: true - '@prettier/plugin-hermes': - optional: true - '@prettier/plugin-oxc': - optional: true - '@prettier/plugin-pug': - optional: true - '@shopify/prettier-plugin-liquid': - optional: true - '@trivago/prettier-plugin-sort-imports': - optional: true - '@zackad/prettier-plugin-twig': - optional: true - prettier-plugin-astro: - optional: true - prettier-plugin-css-order: - optional: true - prettier-plugin-jsdoc: - optional: true - prettier-plugin-marko: - optional: true - prettier-plugin-multiline-arrays: - optional: true - prettier-plugin-organize-attributes: - optional: true - prettier-plugin-organize-imports: - optional: true - prettier-plugin-sort-imports: - optional: true - prettier-plugin-svelte: - optional: true - - prettier@3.8.3: - resolution: {integrity: sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==} - engines: {node: '>=14'} - hasBin: true - - pretty-ms@9.3.0: - resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==} - engines: {node: '>=18'} - - prompts@2.4.2: - resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} - engines: {node: '>= 6'} - - property-information@7.1.0: - resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} - - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} - engines: {node: '>= 0.10'} - - punycode@2.3.1: - resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} - engines: {node: '>=6'} - - qs@6.15.3: - resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==} - engines: {node: '>=0.6'} - - queue-microtask@1.2.3: - resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} - - radix-ui@1.4.3: - resolution: {integrity: sha512-aWizCQiyeAenIdUbqEpXgRA1ya65P13NKn/W8rWkcN0OPkRDxdBVLWnIEDsS2RpwCK2nobI7oMUSmexzTDyAmA==} - peerDependencies: - '@types/react': '*' - '@types/react-dom': '*' - react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - range-parser@1.3.0: - resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} - engines: {node: '>= 0.6'} - - raw-body@3.0.2: - resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} - engines: {node: '>= 0.10'} - - react-dom@19.2.5: - resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} - peerDependencies: - react: ^19.2.5 - - react-i18next@17.0.7: - resolution: {integrity: sha512-rwtPXsb/zwzDafN+gytcjF5YnqGQQIRmCQ6DctBC1VSipRB8GD/MWEVrFP42vjMyuYydxWxM8CZRt+yiNuuoHg==} - peerDependencies: - i18next: '>= 26.0.10' - react: '>= 16.8.0' - react-dom: '*' - react-native: '*' - typescript: ^5 || ^6 - peerDependenciesMeta: - react-dom: - optional: true - react-native: - optional: true - typescript: - optional: true - - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - - react-remove-scroll-bar@2.3.8: - resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} - engines: {node: '>=10'} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - - react-remove-scroll@2.7.2: - resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==} - engines: {node: '>=10'} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - react-style-singleton@2.2.3: - resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} - engines: {node: '>=10'} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - react-textarea-autosize@8.5.9: - resolution: {integrity: sha512-U1DGlIQN5AwgjTyOEnI1oCcMuEr1pv1qOtklB2l4nyMGbHzWrI0eFsYK0zos2YWqAolJyG0IWJaqWmWj5ETh0A==} - engines: {node: '>=10'} - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - - react@19.2.5: - resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==} - engines: {node: '>=0.10.0'} - - readdirp@3.6.0: - resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} - engines: {node: '>=8.10.0'} - - recast@0.23.12: - resolution: {integrity: sha512-dEWRjcINDu/F4l2dYx57ugBtD7HV9KXESyxhzw/MqWLeglJrsjJKqACPyUPg+6AF8mIgm+Zi0dZ3ACoIg+QtpA==} - engines: {node: '>= 4'} - - rehype-highlight@7.0.2: - resolution: {integrity: sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA==} - - rehype-raw@7.0.0: - resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==} - - rehype-sanitize@6.0.0: - resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==} - - remark-gfm@4.0.1: - resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==} - - remark-parse@11.0.0: - resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==} - - remark-rehype@11.1.2: - resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==} - - remark-stringify@11.0.0: - resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==} - - require-from-string@2.0.2: - resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} - engines: {node: '>=0.10.0'} - - resolve-from@4.0.0: - resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} - engines: {node: '>=4'} - - resolve-pkg-maps@1.0.0: - resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} - - restore-cursor@5.1.0: - resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==} - engines: {node: '>=18'} - - reusify@1.1.0: - resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} - engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - - rolldown@1.0.3: - resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - - router@2.2.0: - resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} - engines: {node: '>= 18'} - - run-applescript@7.1.0: - resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==} - engines: {node: '>=18'} - - run-parallel@1.2.0: - resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} - - safer-buffer@2.1.2: - resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} - - scheduler@0.27.0: - resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} - - semver@6.3.1: - resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} - hasBin: true - - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} - engines: {node: '>=10'} - hasBin: true - - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} - engines: {node: '>=10'} - hasBin: true - - send@1.2.1: - resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} - engines: {node: '>= 18'} - - seroval-plugins@1.5.1: - resolution: {integrity: sha512-4FbuZ/TMl02sqv0RTFexu0SP6V+ywaIe5bAWCCEik0fk17BhALgwvUDVF7e3Uvf9pxmwCEJsRPmlkUE6HdzLAw==} - engines: {node: '>=10'} - peerDependencies: - seroval: ^1.0 - - seroval-plugins@1.5.4: - resolution: {integrity: sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==} - engines: {node: '>=10'} - peerDependencies: - seroval: ^1.0 - - seroval@1.5.1: - resolution: {integrity: sha512-OwrZRZAfhHww0WEnKHDY8OM0U/Qs8OTfIDWhUD4BLpNJUfXK4cGmjiagGze086m+mhI+V2nD0gfbHEnJjb9STA==} - engines: {node: '>=10'} - - seroval@1.5.4: - resolution: {integrity: sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==} - engines: {node: '>=10'} - - serve-static@2.2.1: - resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} - engines: {node: '>= 18'} - - setprototypeof@1.2.0: - resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} - - shadcn@4.12.0: - resolution: {integrity: sha512-o781ieQziCnXH2FKsEqxp1fnbHdbgAPO9inTSPeZ59hQfsZXuMGp3ul8oFSV5KQS4nbUK9b+DrDE6C7OvfKKQQ==} - engines: {node: '>=20.18.1'} - hasBin: true - - shebang-command@2.0.0: - resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} - engines: {node: '>=8'} - - shebang-regex@3.0.0: - resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} - engines: {node: '>=8'} - - side-channel-list@1.0.1: - resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} - engines: {node: '>= 0.4'} - - side-channel-map@1.0.1: - resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} - engines: {node: '>= 0.4'} - - side-channel-weakmap@1.0.2: - resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} - engines: {node: '>= 0.4'} - - side-channel@1.1.1: - resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} - engines: {node: '>= 0.4'} - - signal-exit@3.0.7: - resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} - - signal-exit@4.1.0: - resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} - engines: {node: '>=14'} - - sisteransi@1.0.5: - resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} - - sonner@2.0.7: - resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==} - peerDependencies: - react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc - react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc - - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} - engines: {node: '>=0.10.0'} - - source-map@0.6.1: - resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} - engines: {node: '>=0.10.0'} - - source-map@0.7.6: - resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} - engines: {node: '>= 12'} - - space-separated-tokens@2.0.2: - resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} - - statuses@2.0.2: - resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} - engines: {node: '>= 0.8'} - - stdin-discarder@0.2.2: - resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==} - engines: {node: '>=18'} - - string-width@7.2.0: - resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} - engines: {node: '>=18'} - - string-width@8.2.0: - resolution: {integrity: sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw==} - engines: {node: '>=20'} - - stringify-entities@4.0.4: - resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} - - stringify-object@5.0.0: - resolution: {integrity: sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg==} - engines: {node: '>=14.16'} - - strip-ansi@6.0.1: - resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} - engines: {node: '>=8'} - - strip-ansi@7.2.0: - resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} - engines: {node: '>=12'} - - strip-bom@3.0.0: - resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} - engines: {node: '>=4'} - - strip-final-newline@2.0.0: - resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} - engines: {node: '>=6'} - - strip-final-newline@4.0.0: - resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==} - engines: {node: '>=18'} - - style-to-js@1.1.21: - resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==} - - style-to-object@1.0.14: - resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==} - - systeminformation@5.31.11: - resolution: {integrity: sha512-I6O7iaUj23AXRgCPDDnvi3xHvdOLp4+1YMbF+X194lJwY1NeWojgHJPhslVKcmTtrLTguRk3QJK+xEdTiI3P0w==} - engines: {node: '>=8.0.0'} - os: [darwin, linux, win32, freebsd, openbsd, netbsd, sunos, android] - hasBin: true - - tailwind-merge@3.5.0: - resolution: {integrity: sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==} - - tailwindcss@4.3.0: - resolution: {integrity: sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==} - - tapable@2.3.3: - resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} - engines: {node: '>=6'} - - tiny-invariant@1.3.3: - resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} - - tinyglobby@0.2.17: - resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} - engines: {node: '>=12.0.0'} - - to-regex-range@5.0.1: - resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} - engines: {node: '>=8.0'} - - toidentifier@1.0.1: - resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} - engines: {node: '>=0.6'} - - trim-lines@3.0.1: - resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} - - trough@2.2.0: - resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==} - - ts-api-utils@2.5.0: - resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} - engines: {node: '>=18.12'} - peerDependencies: - typescript: '>=4.8.4' - - ts-morph@26.0.0: - resolution: {integrity: sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug==} - - tsconfig-paths@4.2.0: - resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} - engines: {node: '>=6'} - - tslib@2.8.1: - resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - - tsx@4.21.0: - resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} - engines: {node: '>=18.0.0'} - hasBin: true - - tw-animate-css@1.4.0: - resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} - - type-check@0.4.0: - resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} - engines: {node: '>= 0.8.0'} - - type-is@2.1.0: - resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} - engines: {node: '>= 18'} - - typescript-eslint@8.62.1: - resolution: {integrity: sha512-vymnnM5g0AKQDSAyfP12nMIBvgwgA42syg74kkuZ4x1VuTzwQKwc5h9rGxeShCjny5o+zWAb6OEoz7XLgrIkIw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' - - typescript@5.9.3: - resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} - engines: {node: '>=14.17'} - hasBin: true - - undici-types@7.19.2: - resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==} - - undici@7.28.0: - resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} - engines: {node: '>=20.18.1'} - - unicorn-magic@0.3.0: - resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==} - engines: {node: '>=18'} - - unified@11.0.5: - resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==} - - unist-util-find-after@5.0.0: - resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==} - - unist-util-is@6.0.1: - resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==} - - unist-util-position@5.0.0: - resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==} - - unist-util-stringify-position@4.0.0: - resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==} - - unist-util-visit-parents@6.0.2: - resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==} - - unist-util-visit@5.1.0: - resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==} - - universalify@2.0.1: - resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} - engines: {node: '>= 10.0.0'} - - unpipe@1.0.0: - resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} - engines: {node: '>= 0.8'} - - unplugin@2.3.11: - resolution: {integrity: sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==} - engines: {node: '>=18.12.0'} - - update-browserslist-db@1.2.3: - resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} - hasBin: true - peerDependencies: - browserslist: '>= 4.21.0' - - uri-js@4.4.1: - resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} - - use-callback-ref@1.3.3: - resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==} - engines: {node: '>=10'} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - use-composed-ref@1.4.0: - resolution: {integrity: sha512-djviaxuOOh7wkj0paeO1Q/4wMZ8Zrnag5H6yBvzN7AKKe8beOaED9SF5/ByLqsku8NP4zQqsvM2u3ew/tJK8/w==} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - - use-isomorphic-layout-effect@1.2.1: - resolution: {integrity: sha512-tpZZ+EX0gaghDAiFR37hj5MgY6ZN55kLiPkJsKxBMZ6GZdOSPJXiOzPM984oPYZ5AnehYx5WQp1+ME8I/P/pRA==} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - - use-latest@1.3.0: - resolution: {integrity: sha512-mhg3xdm9NaM8q+gLT8KryJPnRFOz1/5XPBhmDEVZK1webPzDjrPk7f/mbpeLqTgB9msytYWANxgALOCJKnLvcQ==} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - - use-sidecar@1.1.3: - resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==} - engines: {node: '>=10'} - peerDependencies: - '@types/react': '*' - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc - peerDependenciesMeta: - '@types/react': - optional: true - - use-sync-external-store@1.6.0: - resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==} - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - - util-deprecate@1.0.2: - resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - - validate-npm-package-name@7.0.2: - resolution: {integrity: sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A==} - engines: {node: ^20.17.0 || >=22.9.0} - - vary@1.1.2: - resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} - engines: {node: '>= 0.8'} - - vfile-location@5.0.3: - resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==} - - vfile-message@4.0.3: - resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==} - - vfile@6.0.3: - resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==} - - vite@8.0.16: - resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.1.18 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - - void-elements@3.1.0: - resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==} - engines: {node: '>=0.10.0'} - - web-namespaces@2.0.1: - resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==} - - webpack-virtual-modules@0.6.2: - resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==} - - which@2.0.2: - resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} - engines: {node: '>= 8'} - hasBin: true - - which@4.0.0: - resolution: {integrity: sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==} - engines: {node: ^16.13.0 || >=18.0.0} - hasBin: true - - word-wrap@1.2.5: - resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} - engines: {node: '>=0.10.0'} - - wrap-ansi@10.0.0: - resolution: {integrity: sha512-SGcvg80f0wUy2/fXES19feHMz8E0JoXv2uNgHOu4Dgi2OrCy1lqwFYEJz1BLbDI0exjPMe/ZdzZ/YpGECBG/aQ==} - engines: {node: '>=20'} - - wrappy@1.0.2: - resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - - wsl-utils@0.3.1: - resolution: {integrity: sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==} - engines: {node: '>=20'} - - yallist@3.1.1: - resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - - yocto-queue@0.1.0: - resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} - engines: {node: '>=10'} - - yocto-spinner@1.2.0: - resolution: {integrity: sha512-Yw0hUB6UA3o4YUgKy3oSe9a4cxoaZ9sBfYDw+JSxo6Id0KoJGoxzPA24qqUXYKBWABs/zDSGTz9kww7t3F0XGw==} - engines: {node: '>=18.19'} - - yoctocolors@2.1.2: - resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==} - engines: {node: '>=18'} - - zod-to-json-schema@3.25.2: - resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} - peerDependencies: - zod: ^3.25.28 || ^4 - - zod-validation-error@4.0.2: - resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} - engines: {node: '>=18.0.0'} - peerDependencies: - zod: ^3.25.0 || ^4.0.0 - - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - - zod@4.3.6: - resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} - - zwitch@2.0.4: - resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} - -snapshots: - - '@babel/code-frame@7.29.0': - dependencies: - '@babel/helper-validator-identifier': 7.28.5 - js-tokens: 4.0.0 - picocolors: 1.1.1 - - '@babel/code-frame@7.29.7': - dependencies: - '@babel/helper-validator-identifier': 7.29.7 - js-tokens: 4.0.0 - picocolors: 1.1.1 - - '@babel/compat-data@7.29.3': {} - - '@babel/compat-data@7.29.7': {} - - '@babel/core@7.29.0': - dependencies: - '@babel/code-frame': 7.29.0 - '@babel/generator': 7.29.1 - '@babel/helper-compilation-targets': 7.28.6 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.0) - '@babel/helpers': 7.29.2 - '@babel/parser': 7.29.7 - '@babel/template': 7.28.6 - '@babel/traverse': 7.29.0 - '@babel/types': 7.29.0 - '@jridgewell/remapping': 2.3.5 - convert-source-map: 2.0.0 - debug: 4.4.3 - gensync: 1.0.0-beta.2 - json5: 2.2.3 - semver: 6.3.1 - transitivePeerDependencies: - - supports-color - - '@babel/core@7.29.7': - dependencies: - '@babel/code-frame': 7.29.7 - '@babel/generator': 7.29.7 - '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) - '@babel/helpers': 7.29.7 - '@babel/parser': 7.29.7 - '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - '@jridgewell/remapping': 2.3.5 - convert-source-map: 2.0.0 - debug: 4.4.3 - gensync: 1.0.0-beta.2 - json5: 2.2.3 - semver: 6.3.1 - transitivePeerDependencies: - - supports-color - - '@babel/generator@7.29.1': - dependencies: - '@babel/parser': 7.29.7 - '@babel/types': 7.29.0 - '@jridgewell/gen-mapping': 0.3.13 - '@jridgewell/trace-mapping': 0.3.31 - jsesc: 3.1.0 - - '@babel/generator@7.29.7': - dependencies: - '@babel/parser': 7.29.7 - '@babel/types': 7.29.7 - '@jridgewell/gen-mapping': 0.3.13 - '@jridgewell/trace-mapping': 0.3.31 - jsesc: 3.1.0 - - '@babel/helper-annotate-as-pure@7.29.7': - dependencies: - '@babel/types': 7.29.7 - - '@babel/helper-compilation-targets@7.28.6': - dependencies: - '@babel/compat-data': 7.29.3 - '@babel/helper-validator-option': 7.29.7 - browserslist: 4.28.4 - lru-cache: 5.1.1 - semver: 6.3.1 - - '@babel/helper-compilation-targets@7.29.7': - dependencies: - '@babel/compat-data': 7.29.7 - '@babel/helper-validator-option': 7.29.7 - browserslist: 4.28.4 - lru-cache: 5.1.1 - semver: 6.3.1 - - '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 - '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/traverse': 7.29.7 - semver: 6.3.1 - transitivePeerDependencies: - - supports-color - - '@babel/helper-globals@7.28.0': {} - - '@babel/helper-globals@7.29.7': {} - - '@babel/helper-member-expression-to-functions@7.29.7': - dependencies: - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-module-imports@7.28.6': - dependencies: - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-module-imports@7.29.7': - dependencies: - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.0)': - dependencies: - '@babel/core': 7.29.0 - '@babel/helper-module-imports': 7.28.6 - '@babel/helper-validator-identifier': 7.28.5 - '@babel/traverse': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 - '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-optimise-call-expression@7.29.7': - dependencies: - '@babel/types': 7.29.7 - - '@babel/helper-plugin-utils@7.28.6': {} - - '@babel/helper-plugin-utils@7.29.7': {} - - '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 - '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/traverse': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-skip-transparent-expression-wrappers@7.29.7': - dependencies: - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/helper-string-parser@7.27.1': {} - - '@babel/helper-string-parser@7.29.7': {} - - '@babel/helper-validator-identifier@7.28.5': {} - - '@babel/helper-validator-identifier@7.29.7': {} - - '@babel/helper-validator-option@7.29.7': {} - - '@babel/helpers@7.29.2': - dependencies: - '@babel/template': 7.29.7 - '@babel/types': 7.29.7 - - '@babel/helpers@7.29.7': - dependencies: - '@babel/template': 7.29.7 - '@babel/types': 7.29.7 - - '@babel/parser@7.29.2': - dependencies: - '@babel/types': 7.29.0 - - '@babel/parser@7.29.7': - dependencies: - '@babel/types': 7.29.7 - - '@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0)': - dependencies: - '@babel/core': 7.29.0 - '@babel/helper-plugin-utils': 7.28.6 - - '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-plugin-utils': 7.29.7 - - '@babel/plugin-syntax-typescript@7.28.6(@babel/core@7.29.0)': - dependencies: - '@babel/core': 7.29.0 - '@babel/helper-plugin-utils': 7.28.6 - - '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-plugin-utils': 7.29.7 - - '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) - '@babel/helper-plugin-utils': 7.29.7 - transitivePeerDependencies: - - supports-color - - '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) - '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) - transitivePeerDependencies: - - supports-color - - '@babel/preset-typescript@7.29.7(@babel/core@7.29.7)': - dependencies: - '@babel/core': 7.29.7 - '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-validator-option': 7.29.7 - '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) - transitivePeerDependencies: - - supports-color - - '@babel/runtime@7.29.2': {} - - '@babel/runtime@7.29.7': {} - - '@babel/template@7.28.6': - dependencies: - '@babel/code-frame': 7.29.0 - '@babel/parser': 7.29.7 - '@babel/types': 7.29.0 - - '@babel/template@7.29.7': - dependencies: - '@babel/code-frame': 7.29.7 - '@babel/parser': 7.29.7 - '@babel/types': 7.29.7 - - '@babel/traverse@7.29.0': - dependencies: - '@babel/code-frame': 7.29.0 - '@babel/generator': 7.29.1 - '@babel/helper-globals': 7.28.0 - '@babel/parser': 7.29.7 - '@babel/template': 7.28.6 - '@babel/types': 7.29.0 - debug: 4.4.3 - transitivePeerDependencies: - - supports-color - - '@babel/traverse@7.29.7': - dependencies: - '@babel/code-frame': 7.29.7 - '@babel/generator': 7.29.7 - '@babel/helper-globals': 7.29.7 - '@babel/parser': 7.29.7 - '@babel/template': 7.29.7 - '@babel/types': 7.29.7 - debug: 4.4.3 - transitivePeerDependencies: - - supports-color - - '@babel/types@7.29.0': - dependencies: - '@babel/helper-string-parser': 7.27.1 - '@babel/helper-validator-identifier': 7.28.5 - - '@babel/types@7.29.7': - dependencies: - '@babel/helper-string-parser': 7.29.7 - '@babel/helper-validator-identifier': 7.29.7 - - '@dotenvx/dotenvx@1.75.1': - dependencies: - '@dotenvx/primitives': 0.8.0 - commander: 11.1.0 - conf: 10.2.0 - dotenv: 17.4.2 - enquirer: 2.4.1 - env-paths: 2.2.1 - execa: 5.1.1 - fdir: 6.5.0(picomatch@4.0.5) - ignore: 5.3.2 - object-treeify: 1.1.33 - open: 8.4.2 - picomatch: 4.0.5 - systeminformation: 5.31.11 - undici: 7.28.0 - which: 4.0.0 - yocto-spinner: 1.2.0 - - '@dotenvx/primitives@0.8.0': {} - - '@emnapi/core@1.10.0': - dependencies: - '@emnapi/wasi-threads': 1.2.1 - tslib: 2.8.1 - optional: true - - '@emnapi/runtime@1.10.0': - dependencies: - tslib: 2.8.1 - optional: true - - '@emnapi/wasi-threads@1.2.1': - dependencies: - tslib: 2.8.1 - optional: true - - '@esbuild/aix-ppc64@0.27.4': - optional: true - - '@esbuild/android-arm64@0.27.4': - optional: true - - '@esbuild/android-arm@0.27.4': - optional: true - - '@esbuild/android-x64@0.27.4': - optional: true - - '@esbuild/darwin-arm64@0.27.4': - optional: true - - '@esbuild/darwin-x64@0.27.4': - optional: true - - '@esbuild/freebsd-arm64@0.27.4': - optional: true - - '@esbuild/freebsd-x64@0.27.4': - optional: true - - '@esbuild/linux-arm64@0.27.4': - optional: true - - '@esbuild/linux-arm@0.27.4': - optional: true - - '@esbuild/linux-ia32@0.27.4': - optional: true - - '@esbuild/linux-loong64@0.27.4': - optional: true - - '@esbuild/linux-mips64el@0.27.4': - optional: true - - '@esbuild/linux-ppc64@0.27.4': - optional: true - - '@esbuild/linux-riscv64@0.27.4': - optional: true - - '@esbuild/linux-s390x@0.27.4': - optional: true - - '@esbuild/linux-x64@0.27.4': - optional: true - - '@esbuild/netbsd-arm64@0.27.4': - optional: true - - '@esbuild/netbsd-x64@0.27.4': - optional: true - - '@esbuild/openbsd-arm64@0.27.4': - optional: true - - '@esbuild/openbsd-x64@0.27.4': - optional: true - - '@esbuild/openharmony-arm64@0.27.4': - optional: true - - '@esbuild/sunos-x64@0.27.4': - optional: true - - '@esbuild/win32-arm64@0.27.4': - optional: true - - '@esbuild/win32-ia32@0.27.4': - optional: true - - '@esbuild/win32-x64@0.27.4': - optional: true - - '@eslint-community/eslint-utils@4.9.1(eslint@10.4.1(jiti@2.7.0))': - dependencies: - eslint: 10.4.1(jiti@2.7.0) - eslint-visitor-keys: 3.4.3 - - '@eslint-community/regexpp@4.12.2': {} - - '@eslint/config-array@0.23.5': - dependencies: - '@eslint/object-schema': 3.0.5 - debug: 4.4.3 - minimatch: 10.2.5 - transitivePeerDependencies: - - supports-color - - '@eslint/config-helpers@0.6.0': - dependencies: - '@eslint/core': 1.2.1 - - '@eslint/core@1.2.1': - dependencies: - '@types/json-schema': 7.0.15 - - '@eslint/js@10.0.1(eslint@10.4.1(jiti@2.7.0))': - optionalDependencies: - eslint: 10.4.1(jiti@2.7.0) - - '@eslint/object-schema@3.0.5': {} - - '@eslint/plugin-kit@0.7.2': - dependencies: - '@eslint/core': 1.2.1 - levn: 0.4.1 - - '@floating-ui/core@1.7.5': - dependencies: - '@floating-ui/utils': 0.2.11 - - '@floating-ui/dom@1.7.6': - dependencies: - '@floating-ui/core': 1.7.5 - '@floating-ui/utils': 0.2.11 - - '@floating-ui/react-dom@2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@floating-ui/dom': 1.7.6 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - - '@floating-ui/utils@0.2.11': {} - - '@fontsource-variable/inter@5.2.8': {} - - '@hono/node-server@1.19.14(hono@4.12.27)': - dependencies: - hono: 4.12.27 - - '@humanfs/core@0.19.2': - dependencies: - '@humanfs/types': 0.15.0 - - '@humanfs/node@0.16.8': - dependencies: - '@humanfs/core': 0.19.2 - '@humanfs/types': 0.15.0 - '@humanwhocodes/retry': 0.4.3 - - '@humanfs/types@0.15.0': {} - - '@humanwhocodes/module-importer@1.0.1': {} - - '@humanwhocodes/retry@0.4.3': {} - - '@jridgewell/gen-mapping@0.3.13': - dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 - '@jridgewell/trace-mapping': 0.3.31 - - '@jridgewell/remapping@2.3.5': - dependencies: - '@jridgewell/gen-mapping': 0.3.13 - '@jridgewell/trace-mapping': 0.3.31 - - '@jridgewell/resolve-uri@3.1.2': {} - - '@jridgewell/sourcemap-codec@1.5.5': {} - - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 - - '@modelcontextprotocol/sdk@1.29.0(zod@3.25.76)': - dependencies: - '@hono/node-server': 1.19.14(hono@4.12.27) - ajv: 8.20.0 - ajv-formats: 3.0.1(ajv@8.20.0) - content-type: 1.0.5 - cors: 2.8.6 - cross-spawn: 7.0.6 - eventsource: 3.0.7 - eventsource-parser: 3.1.0 - express: 5.2.1 - express-rate-limit: 8.5.2(express@5.2.1) - hono: 4.12.27 - jose: 6.2.3 - json-schema-typed: 8.0.2 - pkce-challenge: 5.0.1 - raw-body: 3.0.2 - zod: 3.25.76 - zod-to-json-schema: 3.25.2(zod@3.25.76) - transitivePeerDependencies: - - supports-color - - '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': - dependencies: - '@emnapi/core': 1.10.0 - '@emnapi/runtime': 1.10.0 - '@tybys/wasm-util': 0.10.2 - optional: true - - '@nodelib/fs.scandir@2.1.5': - dependencies: - '@nodelib/fs.stat': 2.0.5 - run-parallel: 1.2.0 - - '@nodelib/fs.stat@2.0.5': {} - - '@nodelib/fs.walk@1.2.8': - dependencies: - '@nodelib/fs.scandir': 2.1.5 - fastq: 1.20.1 - - '@oxc-project/types@0.133.0': {} - - '@radix-ui/number@1.1.1': {} - - '@radix-ui/primitive@1.1.3': {} - - '@radix-ui/react-accessible-icon@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-accordion@1.2.12(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collapsible': 1.1.12(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-alert-dialog@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-arrow@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-aspect-ratio@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-avatar@1.1.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-is-hydrated': 0.1.0(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-checkbox@1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-collapsible@1.1.12(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-collection@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-compose-refs@1.1.2(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-context-menu@2.2.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-menu': 2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-context@1.1.2(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-dialog@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - aria-hidden: 1.2.6 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-direction@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-dismissable-layer@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-escape-keydown': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-dropdown-menu@2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-menu': 2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-focus-guards@1.1.3(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-focus-scope@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-form@0.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-label': 2.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-hover-card@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-id@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-label@2.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-menu@2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - aria-hidden: 1.2.6 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-menubar@1.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-menu': 2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-navigation-menu@1.2.14(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-one-time-password-field@0.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/number': 1.1.1 - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-effect-event': 0.0.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-is-hydrated': 0.1.0(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-password-toggle-field@0.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-effect-event': 0.0.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-is-hydrated': 0.1.0(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-popover@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - aria-hidden: 1.2.6 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-popper@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@floating-ui/react-dom': 2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-arrow': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-rect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/rect': 1.1.1 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-portal@1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-presence@1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-primitive@2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-progress@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-radio-group@1.3.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-scroll-area@1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/number': 1.1.1 - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-select@2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/number': 1.1.1 - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - aria-hidden: 1.2.6 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-separator@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-slider@1.3.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/number': 1.1.1 - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-slot@1.2.3(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-switch@1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-tabs@1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-toast@1.2.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-toggle-group@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toggle': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-toggle@1.1.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-toolbar@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-separator': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toggle-group': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-tooltip@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/react-use-callback-ref@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-controllable-state@1.2.2(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-use-effect-event': 0.0.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-effect-event@0.0.2(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-escape-keydown@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-is-hydrated@0.1.0(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - use-sync-external-store: 1.6.0(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-layout-effect@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-previous@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-rect@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/rect': 1.1.1 - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-use-size@1.1.1(@types/react@19.2.14)(react@19.2.5)': - dependencies: - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - '@radix-ui/react-visually-hidden@1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - '@radix-ui/rect@1.1.1': {} - - '@rolldown/binding-android-arm64@1.0.3': - optional: true - - '@rolldown/binding-darwin-arm64@1.0.3': - optional: true - - '@rolldown/binding-darwin-x64@1.0.3': - optional: true - - '@rolldown/binding-freebsd-x64@1.0.3': - optional: true - - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': - optional: true - - '@rolldown/binding-linux-arm64-gnu@1.0.3': - optional: true - - '@rolldown/binding-linux-arm64-musl@1.0.3': - optional: true - - '@rolldown/binding-linux-ppc64-gnu@1.0.3': - optional: true - - '@rolldown/binding-linux-s390x-gnu@1.0.3': - optional: true - - '@rolldown/binding-linux-x64-gnu@1.0.3': - optional: true - - '@rolldown/binding-linux-x64-musl@1.0.3': - optional: true - - '@rolldown/binding-openharmony-arm64@1.0.3': - optional: true - - '@rolldown/binding-wasm32-wasi@1.0.3': - dependencies: - '@emnapi/core': 1.10.0 - '@emnapi/runtime': 1.10.0 - '@napi-rs/wasm-runtime': 1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) - optional: true - - '@rolldown/binding-win32-arm64-msvc@1.0.3': - optional: true - - '@rolldown/binding-win32-x64-msvc@1.0.3': - optional: true - - '@rolldown/pluginutils@1.0.1': {} - - '@sec-ant/readable-stream@0.4.1': {} - - '@sindresorhus/merge-streams@4.0.0': {} - - '@tabler/icons-react@3.43.0(react@19.2.5)': - dependencies: - '@tabler/icons': 3.43.0 - react: 19.2.5 - - '@tabler/icons@3.43.0': {} - - '@tailwindcss/node@4.3.0': - dependencies: - '@jridgewell/remapping': 2.3.5 - enhanced-resolve: 5.21.0 - jiti: 2.7.0 - lightningcss: 1.32.0 - magic-string: 0.30.21 - source-map-js: 1.2.1 - tailwindcss: 4.3.0 - - '@tailwindcss/oxide-android-arm64@4.3.0': - optional: true - - '@tailwindcss/oxide-darwin-arm64@4.3.0': - optional: true - - '@tailwindcss/oxide-darwin-x64@4.3.0': - optional: true - - '@tailwindcss/oxide-freebsd-x64@4.3.0': - optional: true - - '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.0': - optional: true - - '@tailwindcss/oxide-linux-arm64-gnu@4.3.0': - optional: true - - '@tailwindcss/oxide-linux-arm64-musl@4.3.0': - optional: true - - '@tailwindcss/oxide-linux-x64-gnu@4.3.0': - optional: true - - '@tailwindcss/oxide-linux-x64-musl@4.3.0': - optional: true - - '@tailwindcss/oxide-wasm32-wasi@4.3.0': - optional: true - - '@tailwindcss/oxide-win32-arm64-msvc@4.3.0': - optional: true - - '@tailwindcss/oxide-win32-x64-msvc@4.3.0': - optional: true - - '@tailwindcss/oxide@4.3.0': - optionalDependencies: - '@tailwindcss/oxide-android-arm64': 4.3.0 - '@tailwindcss/oxide-darwin-arm64': 4.3.0 - '@tailwindcss/oxide-darwin-x64': 4.3.0 - '@tailwindcss/oxide-freebsd-x64': 4.3.0 - '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.0 - '@tailwindcss/oxide-linux-arm64-gnu': 4.3.0 - '@tailwindcss/oxide-linux-arm64-musl': 4.3.0 - '@tailwindcss/oxide-linux-x64-gnu': 4.3.0 - '@tailwindcss/oxide-linux-x64-musl': 4.3.0 - '@tailwindcss/oxide-wasm32-wasi': 4.3.0 - '@tailwindcss/oxide-win32-arm64-msvc': 4.3.0 - '@tailwindcss/oxide-win32-x64-msvc': 4.3.0 - - '@tailwindcss/typography@0.5.19(tailwindcss@4.3.0)': - dependencies: - postcss-selector-parser: 6.0.10 - tailwindcss: 4.3.0 - - '@tailwindcss/vite@4.3.0(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0))': - dependencies: - '@tailwindcss/node': 4.3.0 - '@tailwindcss/oxide': 4.3.0 - tailwindcss: 4.3.0 - vite: 8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0) - - '@tanstack/history@1.161.6': {} - - '@tanstack/query-core@5.99.0': {} - - '@tanstack/react-query@5.99.0(react@19.2.5)': - dependencies: - '@tanstack/query-core': 5.99.0 - react: 19.2.5 - - '@tanstack/react-router-devtools@1.166.13(@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(@tanstack/router-core@1.169.2)(csstype@3.2.3)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@tanstack/react-router': 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@tanstack/router-devtools-core': 1.167.3(@tanstack/router-core@1.169.2)(csstype@3.2.3) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@tanstack/router-core': 1.169.2 - transitivePeerDependencies: - - csstype - - '@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@tanstack/history': 1.161.6 - '@tanstack/react-store': 0.9.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@tanstack/router-core': 1.169.2 - isbot: 5.1.40 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - - '@tanstack/react-store@0.9.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': - dependencies: - '@tanstack/store': 0.9.3 - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - use-sync-external-store: 1.6.0(react@19.2.5) - - '@tanstack/router-core@1.168.7': - dependencies: - '@tanstack/history': 1.161.6 - cookie-es: 2.0.0 - seroval: 1.5.1 - seroval-plugins: 1.5.1(seroval@1.5.1) - - '@tanstack/router-core@1.169.2': - dependencies: - '@tanstack/history': 1.161.6 - cookie-es: 3.1.1 - seroval: 1.5.4 - seroval-plugins: 1.5.4(seroval@1.5.4) - - '@tanstack/router-devtools-core@1.167.3(@tanstack/router-core@1.169.2)(csstype@3.2.3)': - dependencies: - '@tanstack/router-core': 1.169.2 - clsx: 2.1.1 - goober: 2.1.18(csstype@3.2.3) - optionalDependencies: - csstype: 3.2.3 - - '@tanstack/router-generator@1.166.22': - dependencies: - '@tanstack/router-core': 1.168.7 - '@tanstack/router-utils': 1.161.6 - '@tanstack/virtual-file-routes': 1.161.7 - prettier: 3.8.3 - recast: 0.23.12 - source-map: 0.7.6 - tsx: 4.21.0 - zod: 3.25.76 - transitivePeerDependencies: - - supports-color - - '@tanstack/router-plugin@1.167.9(@tanstack/react-router@1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0))': - dependencies: - '@babel/core': 7.29.0 - '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.0) - '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.0) - '@babel/template': 7.28.6 - '@babel/traverse': 7.29.0 - '@babel/types': 7.29.0 - '@tanstack/router-core': 1.168.7 - '@tanstack/router-generator': 1.166.22 - '@tanstack/router-utils': 1.161.6 - '@tanstack/virtual-file-routes': 1.161.7 - chokidar: 3.6.0 - unplugin: 2.3.11 - zod: 3.25.76 - optionalDependencies: - '@tanstack/react-router': 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - vite: 8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0) - transitivePeerDependencies: - - supports-color - - '@tanstack/router-utils@1.161.6': - dependencies: - '@babel/core': 7.29.7 - '@babel/generator': 7.29.1 - '@babel/parser': 7.29.7 - '@babel/types': 7.29.0 - ansis: 4.2.0 - babel-dead-code-elimination: 1.0.12 - diff: 8.0.4 - pathe: 2.0.3 - tinyglobby: 0.2.17 - transitivePeerDependencies: - - supports-color - - '@tanstack/store@0.9.3': {} - - '@tanstack/virtual-file-routes@1.161.7': {} - - '@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3)': - dependencies: - '@babel/generator': 7.29.1 - '@babel/parser': 7.29.2 - '@babel/traverse': 7.29.0 - '@babel/types': 7.29.0 - javascript-natural-sort: 0.7.1 - lodash-es: 4.17.23 - minimatch: 9.0.9 - parse-imports-exports: 0.2.4 - prettier: 3.8.3 - transitivePeerDependencies: - - supports-color - - '@ts-morph/common@0.27.0': - dependencies: - fast-glob: 3.3.3 - minimatch: 10.2.5 - path-browserify: 1.0.1 - - '@tybys/wasm-util@0.10.2': - dependencies: - tslib: 2.8.1 - optional: true - - '@types/debug@4.1.13': - dependencies: - '@types/ms': 2.1.0 - - '@types/esrecurse@4.3.1': {} - - '@types/estree-jsx@1.0.5': - dependencies: - '@types/estree': 1.0.9 - - '@types/estree@1.0.9': {} - - '@types/hast@3.0.4': - dependencies: - '@types/unist': 3.0.3 - - '@types/json-schema@7.0.15': {} - - '@types/mdast@4.0.4': - dependencies: - '@types/unist': 3.0.3 - - '@types/ms@2.1.0': {} - - '@types/node@25.6.0': - dependencies: - undici-types: 7.19.2 - - '@types/react-dom@19.2.3(@types/react@19.2.14)': - dependencies: - '@types/react': 19.2.14 - - '@types/react@19.2.14': - dependencies: - csstype: 3.2.3 - - '@types/unist@2.0.11': {} - - '@types/unist@3.0.3': {} - - '@types/validate-npm-package-name@4.0.2': {} - - '@typescript-eslint/eslint-plugin@8.58.2(@typescript-eslint/parser@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3))(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/scope-manager': 8.58.2 - '@typescript-eslint/type-utils': 8.58.2(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.58.2(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/visitor-keys': 8.58.2 - eslint: 10.4.1(jiti@2.7.0) - ignore: 7.0.5 - natural-compare: 1.4.0 - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/eslint-plugin@8.62.1(@typescript-eslint/parser@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3))(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/scope-manager': 8.62.1 - '@typescript-eslint/type-utils': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/visitor-keys': 8.62.1 - eslint: 10.4.1(jiti@2.7.0) - ignore: 7.0.5 - natural-compare: 1.4.0 - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/parser@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@typescript-eslint/scope-manager': 8.62.1 - '@typescript-eslint/types': 8.62.1 - '@typescript-eslint/typescript-estree': 8.62.1(typescript@5.9.3) - '@typescript-eslint/visitor-keys': 8.62.1 - debug: 4.4.3 - eslint: 10.4.1(jiti@2.7.0) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/project-service@8.58.2(typescript@5.9.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.62.1(typescript@5.9.3) - '@typescript-eslint/types': 8.62.1 - debug: 4.4.3 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/project-service@8.62.1(typescript@5.9.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.62.1(typescript@5.9.3) - '@typescript-eslint/types': 8.62.1 - debug: 4.4.3 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/scope-manager@8.58.2': - dependencies: - '@typescript-eslint/types': 8.58.2 - '@typescript-eslint/visitor-keys': 8.58.2 - - '@typescript-eslint/scope-manager@8.62.1': - dependencies: - '@typescript-eslint/types': 8.62.1 - '@typescript-eslint/visitor-keys': 8.62.1 - - '@typescript-eslint/tsconfig-utils@8.58.2(typescript@5.9.3)': - dependencies: - typescript: 5.9.3 - - '@typescript-eslint/tsconfig-utils@8.62.1(typescript@5.9.3)': - dependencies: - typescript: 5.9.3 - - '@typescript-eslint/type-utils@8.58.2(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@typescript-eslint/types': 8.58.2 - '@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3) - '@typescript-eslint/utils': 8.58.2(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 10.4.1(jiti@2.7.0) - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/type-utils@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@typescript-eslint/types': 8.62.1 - '@typescript-eslint/typescript-estree': 8.62.1(typescript@5.9.3) - '@typescript-eslint/utils': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 10.4.1(jiti@2.7.0) - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/types@8.58.2': {} - - '@typescript-eslint/types@8.62.1': {} - - '@typescript-eslint/typescript-estree@8.58.2(typescript@5.9.3)': - dependencies: - '@typescript-eslint/project-service': 8.58.2(typescript@5.9.3) - '@typescript-eslint/tsconfig-utils': 8.58.2(typescript@5.9.3) - '@typescript-eslint/types': 8.58.2 - '@typescript-eslint/visitor-keys': 8.58.2 - debug: 4.4.3 - minimatch: 10.2.5 - semver: 7.8.5 - tinyglobby: 0.2.17 - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/typescript-estree@8.62.1(typescript@5.9.3)': - dependencies: - '@typescript-eslint/project-service': 8.62.1(typescript@5.9.3) - '@typescript-eslint/tsconfig-utils': 8.62.1(typescript@5.9.3) - '@typescript-eslint/types': 8.62.1 - '@typescript-eslint/visitor-keys': 8.62.1 - debug: 4.4.3 - minimatch: 10.2.5 - semver: 7.8.5 - tinyglobby: 0.2.17 - ts-api-utils: 2.5.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/utils@8.58.2(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@10.4.1(jiti@2.7.0)) - '@typescript-eslint/scope-manager': 8.58.2 - '@typescript-eslint/types': 8.58.2 - '@typescript-eslint/typescript-estree': 8.58.2(typescript@5.9.3) - eslint: 10.4.1(jiti@2.7.0) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/utils@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3)': - dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@10.4.1(jiti@2.7.0)) - '@typescript-eslint/scope-manager': 8.62.1 - '@typescript-eslint/types': 8.62.1 - '@typescript-eslint/typescript-estree': 8.62.1(typescript@5.9.3) - eslint: 10.4.1(jiti@2.7.0) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/visitor-keys@8.58.2': - dependencies: - '@typescript-eslint/types': 8.58.2 - eslint-visitor-keys: 5.0.1 - - '@typescript-eslint/visitor-keys@8.62.1': - dependencies: - '@typescript-eslint/types': 8.62.1 - eslint-visitor-keys: 5.0.1 - - '@ungap/structured-clone@1.3.0': {} - - '@vitejs/plugin-react@6.0.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0))': - dependencies: - '@rolldown/pluginutils': 1.0.1 - vite: 8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0) - - accepts@2.0.0: - dependencies: - mime-types: 3.0.2 - negotiator: 1.0.0 - - acorn-jsx@5.3.2(acorn@8.17.0): - dependencies: - acorn: 8.17.0 - - acorn@8.16.0: {} - - acorn@8.17.0: {} - - ajv-formats@2.1.1(ajv@8.20.0): - optionalDependencies: - ajv: 8.20.0 - - ajv-formats@3.0.1(ajv@8.20.0): - optionalDependencies: - ajv: 8.20.0 - - ajv@6.15.0: - dependencies: - fast-deep-equal: 3.1.3 - fast-json-stable-stringify: 2.1.0 - json-schema-traverse: 0.4.1 - uri-js: 4.4.1 - - ajv@8.20.0: - dependencies: - fast-deep-equal: 3.1.3 - fast-uri: 3.1.3 - json-schema-traverse: 1.0.0 - require-from-string: 2.0.2 - - ansi-colors@4.1.3: {} - - ansi-regex@5.0.1: {} - - ansi-regex@6.2.2: {} - - ansi-styles@6.2.3: {} - - ansis@4.2.0: {} - - anymatch@3.1.3: - dependencies: - normalize-path: 3.0.0 - picomatch: 2.3.2 - - argparse@2.0.1: {} - - aria-hidden@1.2.6: - dependencies: - tslib: 2.8.1 - - ast-types@0.16.1: - dependencies: - tslib: 2.8.1 - - atomically@1.7.0: {} - - babel-dead-code-elimination@1.0.12: - dependencies: - '@babel/core': 7.29.7 - '@babel/parser': 7.29.7 - '@babel/traverse': 7.29.7 - '@babel/types': 7.29.7 - transitivePeerDependencies: - - supports-color - - bail@2.0.2: {} - - balanced-match@1.0.2: {} - - balanced-match@4.0.4: {} - - baseline-browser-mapping@2.10.41: {} - - binary-extensions@2.3.0: {} - - body-parser@2.3.0: - dependencies: - bytes: 3.1.2 - content-type: 2.0.0 - debug: 4.4.3 - http-errors: 2.0.1 - iconv-lite: 0.7.2 - on-finished: 2.4.1 - qs: 6.15.3 - raw-body: 3.0.2 - type-is: 2.1.0 - transitivePeerDependencies: - - supports-color - - brace-expansion@2.0.3: - dependencies: - balanced-match: 1.0.2 - - brace-expansion@5.0.6: - dependencies: - balanced-match: 4.0.4 - - braces@3.0.3: - dependencies: - fill-range: 7.1.1 - - browserslist@4.28.4: - dependencies: - baseline-browser-mapping: 2.10.41 - caniuse-lite: 1.0.30001800 - electron-to-chromium: 1.5.384 - node-releases: 2.0.50 - update-browserslist-db: 1.2.3(browserslist@4.28.4) - - bundle-name@4.1.0: - dependencies: - run-applescript: 7.1.0 - - bytes@3.1.2: {} - - call-bind-apply-helpers@1.0.2: - dependencies: - es-errors: 1.3.0 - function-bind: 1.1.2 - - call-bound@1.0.4: - dependencies: - call-bind-apply-helpers: 1.0.2 - get-intrinsic: 1.3.0 - - callsites@3.1.0: {} - - caniuse-lite@1.0.30001800: {} - - ccount@2.0.1: {} - - chalk@5.6.2: {} - - character-entities-html4@2.1.0: {} - - character-entities-legacy@3.0.0: {} - - character-entities@2.0.2: {} - - character-reference-invalid@2.0.1: {} - - chokidar@3.6.0: - dependencies: - anymatch: 3.1.3 - braces: 3.0.3 - glob-parent: 5.1.2 - is-binary-path: 2.1.0 - is-glob: 4.0.3 - normalize-path: 3.0.0 - readdirp: 3.6.0 - optionalDependencies: - fsevents: 2.3.3 - - class-variance-authority@0.7.1: - dependencies: - clsx: 2.1.1 - - cli-cursor@5.0.0: - dependencies: - restore-cursor: 5.1.0 - - cli-spinners@2.9.2: {} - - clsx@2.1.1: {} - - cmdk@1.1.1(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5): - dependencies: - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - transitivePeerDependencies: - - '@types/react' - - '@types/react-dom' - - code-block-writer@13.0.3: {} - - comma-separated-tokens@2.0.3: {} - - commander@11.1.0: {} - - commander@14.0.3: {} - - conf@10.2.0: - dependencies: - ajv: 8.20.0 - ajv-formats: 2.1.1(ajv@8.20.0) - atomically: 1.7.0 - debounce-fn: 4.0.0 - dot-prop: 6.0.1 - env-paths: 2.2.1 - json-schema-typed: 7.0.3 - onetime: 5.1.2 - pkg-up: 3.1.0 - semver: 7.8.5 - - content-disposition@1.1.0: {} - - content-type@1.0.5: {} - - content-type@2.0.0: {} - - convert-source-map@2.0.0: {} - - cookie-es@2.0.0: {} - - cookie-es@3.1.1: {} - - cookie-signature@1.2.2: {} - - cookie@0.7.2: {} - - cors@2.8.6: - dependencies: - object-assign: 4.1.1 - vary: 1.1.2 - - cosmiconfig@9.0.2(typescript@5.9.3): - dependencies: - env-paths: 2.2.1 - import-fresh: 3.3.1 - js-yaml: 4.3.0 - parse-json: 5.2.0 - optionalDependencies: - typescript: 5.9.3 - - cross-spawn@7.0.6: - dependencies: - path-key: 3.1.1 - shebang-command: 2.0.0 - which: 2.0.2 - - cssesc@3.0.0: {} - - csstype@3.2.3: {} - - dayjs@1.11.20: {} - - debounce-fn@4.0.0: - dependencies: - mimic-fn: 3.1.0 - - debug@4.4.3: - dependencies: - ms: 2.1.3 - - decode-named-character-reference@1.3.0: - dependencies: - character-entities: 2.0.2 - - dedent@1.7.2: {} - - deep-is@0.1.4: {} - - deepmerge@4.3.1: {} - - default-browser-id@5.0.1: {} - - default-browser@5.5.0: - dependencies: - bundle-name: 4.1.0 - default-browser-id: 5.0.1 - - define-lazy-prop@2.0.0: {} - - define-lazy-prop@3.0.0: {} - - depd@2.0.0: {} - - dequal@2.0.3: {} - - detect-libc@2.1.2: {} - - detect-node-es@1.1.0: {} - - devlop@1.1.0: - dependencies: - dequal: 2.0.3 - - diff@8.0.4: {} - - dot-prop@6.0.1: - dependencies: - is-obj: 2.0.0 - - dotenv@17.4.2: {} - - dunder-proto@1.0.1: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-errors: 1.3.0 - gopd: 1.2.0 - - ee-first@1.1.1: {} - - electron-to-chromium@1.5.384: {} - - emoji-regex@10.6.0: {} - - encodeurl@2.0.0: {} - - enhanced-resolve@5.21.0: - dependencies: - graceful-fs: 4.2.11 - tapable: 2.3.3 - - enquirer@2.4.1: - dependencies: - ansi-colors: 4.1.3 - strip-ansi: 6.0.1 - - entities@6.0.1: {} - - env-paths@2.2.1: {} - - error-ex@1.3.4: - dependencies: - is-arrayish: 0.2.1 - - es-define-property@1.0.1: {} - - es-errors@1.3.0: {} - - es-object-atoms@1.1.2: - dependencies: - es-errors: 1.3.0 - - esbuild@0.27.4: - optionalDependencies: - '@esbuild/aix-ppc64': 0.27.4 - '@esbuild/android-arm': 0.27.4 - '@esbuild/android-arm64': 0.27.4 - '@esbuild/android-x64': 0.27.4 - '@esbuild/darwin-arm64': 0.27.4 - '@esbuild/darwin-x64': 0.27.4 - '@esbuild/freebsd-arm64': 0.27.4 - '@esbuild/freebsd-x64': 0.27.4 - '@esbuild/linux-arm': 0.27.4 - '@esbuild/linux-arm64': 0.27.4 - '@esbuild/linux-ia32': 0.27.4 - '@esbuild/linux-loong64': 0.27.4 - '@esbuild/linux-mips64el': 0.27.4 - '@esbuild/linux-ppc64': 0.27.4 - '@esbuild/linux-riscv64': 0.27.4 - '@esbuild/linux-s390x': 0.27.4 - '@esbuild/linux-x64': 0.27.4 - '@esbuild/netbsd-arm64': 0.27.4 - '@esbuild/netbsd-x64': 0.27.4 - '@esbuild/openbsd-arm64': 0.27.4 - '@esbuild/openbsd-x64': 0.27.4 - '@esbuild/openharmony-arm64': 0.27.4 - '@esbuild/sunos-x64': 0.27.4 - '@esbuild/win32-arm64': 0.27.4 - '@esbuild/win32-ia32': 0.27.4 - '@esbuild/win32-x64': 0.27.4 - - escalade@3.2.0: {} - - escape-html@1.0.3: {} - - escape-string-regexp@4.0.0: {} - - escape-string-regexp@5.0.0: {} - - eslint-config-prettier@10.1.8(eslint@10.4.1(jiti@2.7.0)): - dependencies: - eslint: 10.4.1(jiti@2.7.0) - - eslint-plugin-react-hooks@7.1.1(eslint@10.4.1(jiti@2.7.0)): - dependencies: - '@babel/core': 7.29.0 - '@babel/parser': 7.29.2 - eslint: 10.4.1(jiti@2.7.0) - hermes-parser: 0.25.1 - zod: 4.3.6 - zod-validation-error: 4.0.2(zod@4.3.6) - transitivePeerDependencies: - - supports-color - - eslint-plugin-react-refresh@0.5.2(eslint@10.4.1(jiti@2.7.0)): - dependencies: - eslint: 10.4.1(jiti@2.7.0) - - eslint-scope@9.1.2: - dependencies: - '@types/esrecurse': 4.3.1 - '@types/estree': 1.0.9 - esrecurse: 4.3.0 - estraverse: 5.3.0 - - eslint-visitor-keys@3.4.3: {} - - eslint-visitor-keys@5.0.1: {} - - eslint@10.4.1(jiti@2.7.0): - dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@10.4.1(jiti@2.7.0)) - '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.23.5 - '@eslint/config-helpers': 0.6.0 - '@eslint/core': 1.2.1 - '@eslint/plugin-kit': 0.7.2 - '@humanfs/node': 0.16.8 - '@humanwhocodes/module-importer': 1.0.1 - '@humanwhocodes/retry': 0.4.3 - '@types/estree': 1.0.9 - ajv: 6.15.0 - cross-spawn: 7.0.6 - debug: 4.4.3 - escape-string-regexp: 4.0.0 - eslint-scope: 9.1.2 - eslint-visitor-keys: 5.0.1 - espree: 11.2.0 - esquery: 1.7.0 - esutils: 2.0.3 - fast-deep-equal: 3.1.3 - file-entry-cache: 8.0.0 - find-up: 5.0.0 - glob-parent: 6.0.2 - ignore: 5.3.2 - imurmurhash: 0.1.4 - is-glob: 4.0.3 - json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 10.2.5 - natural-compare: 1.4.0 - optionator: 0.9.4 - optionalDependencies: - jiti: 2.7.0 - transitivePeerDependencies: - - supports-color - - espree@11.2.0: - dependencies: - acorn: 8.17.0 - acorn-jsx: 5.3.2(acorn@8.17.0) - eslint-visitor-keys: 5.0.1 - - esprima@4.0.1: {} - - esquery@1.7.0: - dependencies: - estraverse: 5.3.0 - - esrecurse@4.3.0: - dependencies: - estraverse: 5.3.0 - - estraverse@5.3.0: {} - - estree-util-is-identifier-name@3.0.0: {} - - esutils@2.0.3: {} - - etag@1.8.1: {} - - eventsource-parser@3.1.0: {} - - eventsource@3.0.7: - dependencies: - eventsource-parser: 3.1.0 - - execa@5.1.1: - dependencies: - cross-spawn: 7.0.6 - get-stream: 6.0.1 - human-signals: 2.1.0 - is-stream: 2.0.1 - merge-stream: 2.0.0 - npm-run-path: 4.0.1 - onetime: 5.1.2 - signal-exit: 3.0.7 - strip-final-newline: 2.0.0 - - execa@9.6.1: - dependencies: - '@sindresorhus/merge-streams': 4.0.0 - cross-spawn: 7.0.6 - figures: 6.1.0 - get-stream: 9.0.1 - human-signals: 8.0.1 - is-plain-obj: 4.1.0 - is-stream: 4.0.1 - npm-run-path: 6.0.0 - pretty-ms: 9.3.0 - signal-exit: 4.1.0 - strip-final-newline: 4.0.0 - yoctocolors: 2.1.2 - - express-rate-limit@8.5.2(express@5.2.1): - dependencies: - express: 5.2.1 - ip-address: 10.2.0 - - express@5.2.1: - dependencies: - accepts: 2.0.0 - body-parser: 2.3.0 - content-disposition: 1.1.0 - content-type: 1.0.5 - cookie: 0.7.2 - cookie-signature: 1.2.2 - debug: 4.4.3 - depd: 2.0.0 - encodeurl: 2.0.0 - escape-html: 1.0.3 - etag: 1.8.1 - finalhandler: 2.1.1 - fresh: 2.0.0 - http-errors: 2.0.1 - merge-descriptors: 2.0.0 - mime-types: 3.0.2 - on-finished: 2.4.1 - once: 1.4.0 - parseurl: 1.3.3 - proxy-addr: 2.0.7 - qs: 6.15.3 - range-parser: 1.3.0 - router: 2.2.0 - send: 1.2.1 - serve-static: 2.2.1 - statuses: 2.0.2 - type-is: 2.1.0 - vary: 1.1.2 - transitivePeerDependencies: - - supports-color - - extend@3.0.2: {} - - fast-deep-equal@3.1.3: {} - - fast-glob@3.3.3: - dependencies: - '@nodelib/fs.stat': 2.0.5 - '@nodelib/fs.walk': 1.2.8 - glob-parent: 5.1.2 - merge2: 1.4.1 - micromatch: 4.0.8 - - fast-json-stable-stringify@2.1.0: {} - - fast-levenshtein@2.0.6: {} - - fast-uri@3.1.3: {} - - fastq@1.20.1: - dependencies: - reusify: 1.1.0 - - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - - fdir@6.5.0(picomatch@4.0.5): - optionalDependencies: - picomatch: 4.0.5 - - figures@6.1.0: - dependencies: - is-unicode-supported: 2.1.0 - - file-entry-cache@8.0.0: - dependencies: - flat-cache: 4.0.1 - - fill-range@7.1.1: - dependencies: - to-regex-range: 5.0.1 - - finalhandler@2.1.1: - dependencies: - debug: 4.4.3 - encodeurl: 2.0.0 - escape-html: 1.0.3 - on-finished: 2.4.1 - parseurl: 1.3.3 - statuses: 2.0.2 - transitivePeerDependencies: - - supports-color - - find-up@3.0.0: - dependencies: - locate-path: 3.0.0 - - find-up@5.0.0: - dependencies: - locate-path: 6.0.0 - path-exists: 4.0.0 - - flat-cache@4.0.1: - dependencies: - flatted: 3.4.2 - keyv: 4.5.4 - - flatted@3.4.2: {} - - forwarded@0.2.0: {} - - fresh@2.0.0: {} - - fs-extra@11.3.6: - dependencies: - graceful-fs: 4.2.11 - jsonfile: 6.2.1 - universalify: 2.0.1 - - fsevents@2.3.3: - optional: true - - function-bind@1.1.2: {} - - fuzzysort@3.1.0: {} - - gensync@1.0.0-beta.2: {} - - get-east-asian-width@1.5.0: {} - - get-east-asian-width@1.6.0: {} - - get-intrinsic@1.3.0: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.2 - function-bind: 1.1.2 - get-proto: 1.0.1 - gopd: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.4 - math-intrinsics: 1.1.0 - - get-nonce@1.0.1: {} - - get-own-enumerable-keys@1.0.0: {} - - get-proto@1.0.1: - dependencies: - dunder-proto: 1.0.1 - es-object-atoms: 1.1.2 - - get-stream@6.0.1: {} - - get-stream@9.0.1: - dependencies: - '@sec-ant/readable-stream': 0.4.1 - is-stream: 4.0.1 - - get-tsconfig@4.13.7: - dependencies: - resolve-pkg-maps: 1.0.0 - - glob-parent@5.1.2: - dependencies: - is-glob: 4.0.3 - - glob-parent@6.0.2: - dependencies: - is-glob: 4.0.3 - - globals@17.6.0: {} - - goober@2.1.18(csstype@3.2.3): - dependencies: - csstype: 3.2.3 - - gopd@1.2.0: {} - - graceful-fs@4.2.11: {} - - has-symbols@1.1.0: {} - - hasown@2.0.4: - dependencies: - function-bind: 1.1.2 - - hast-util-from-parse5@8.0.3: - dependencies: - '@types/hast': 3.0.4 - '@types/unist': 3.0.3 - devlop: 1.1.0 - hastscript: 9.0.1 - property-information: 7.1.0 - vfile: 6.0.3 - vfile-location: 5.0.3 - web-namespaces: 2.0.1 - - hast-util-is-element@3.0.0: - dependencies: - '@types/hast': 3.0.4 - - hast-util-parse-selector@4.0.0: - dependencies: - '@types/hast': 3.0.4 - - hast-util-raw@9.1.0: - dependencies: - '@types/hast': 3.0.4 - '@types/unist': 3.0.3 - '@ungap/structured-clone': 1.3.0 - hast-util-from-parse5: 8.0.3 - hast-util-to-parse5: 8.0.1 - html-void-elements: 3.0.0 - mdast-util-to-hast: 13.2.1 - parse5: 7.3.0 - unist-util-position: 5.0.0 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - web-namespaces: 2.0.1 - zwitch: 2.0.4 - - hast-util-sanitize@5.0.2: - dependencies: - '@types/hast': 3.0.4 - '@ungap/structured-clone': 1.3.0 - unist-util-position: 5.0.0 - - hast-util-to-jsx-runtime@2.3.6: - dependencies: - '@types/estree': 1.0.9 - '@types/hast': 3.0.4 - '@types/unist': 3.0.3 - comma-separated-tokens: 2.0.3 - devlop: 1.1.0 - estree-util-is-identifier-name: 3.0.0 - hast-util-whitespace: 3.0.0 - mdast-util-mdx-expression: 2.0.1 - mdast-util-mdx-jsx: 3.2.0 - mdast-util-mdxjs-esm: 2.0.1 - property-information: 7.1.0 - space-separated-tokens: 2.0.2 - style-to-js: 1.1.21 - unist-util-position: 5.0.0 - vfile-message: 4.0.3 - transitivePeerDependencies: - - supports-color - - hast-util-to-parse5@8.0.1: - dependencies: - '@types/hast': 3.0.4 - comma-separated-tokens: 2.0.3 - devlop: 1.1.0 - property-information: 7.1.0 - space-separated-tokens: 2.0.2 - web-namespaces: 2.0.1 - zwitch: 2.0.4 - - hast-util-to-text@4.0.2: - dependencies: - '@types/hast': 3.0.4 - '@types/unist': 3.0.3 - hast-util-is-element: 3.0.0 - unist-util-find-after: 5.0.0 - - hast-util-whitespace@3.0.0: - dependencies: - '@types/hast': 3.0.4 - - hastscript@9.0.1: - dependencies: - '@types/hast': 3.0.4 - comma-separated-tokens: 2.0.3 - hast-util-parse-selector: 4.0.0 - property-information: 7.1.0 - space-separated-tokens: 2.0.2 - - hermes-estree@0.25.1: {} - - hermes-parser@0.25.1: - dependencies: - hermes-estree: 0.25.1 - - highlight.js@11.11.1: {} - - hono@4.12.27: {} - - html-parse-stringify@3.0.1: - dependencies: - void-elements: 3.1.0 - - html-url-attributes@3.0.1: {} - - html-void-elements@3.0.0: {} - - http-errors@2.0.1: - dependencies: - depd: 2.0.0 - inherits: 2.0.4 - setprototypeof: 1.2.0 - statuses: 2.0.2 - toidentifier: 1.0.1 - - human-signals@2.1.0: {} - - human-signals@8.0.1: {} - - i18next-browser-languagedetector@8.2.1: - dependencies: - '@babel/runtime': 7.29.2 - - i18next@26.0.10(typescript@5.9.3): - optionalDependencies: - typescript: 5.9.3 - - iconv-lite@0.7.2: - dependencies: - safer-buffer: 2.1.2 - - ignore@5.3.2: {} - - ignore@7.0.5: {} - - import-fresh@3.3.1: - dependencies: - parent-module: 1.0.1 - resolve-from: 4.0.0 - - imurmurhash@0.1.4: {} - - inherits@2.0.4: {} - - inline-style-parser@0.2.7: {} - - ip-address@10.2.0: {} - - ipaddr.js@1.9.1: {} - - is-alphabetical@2.0.1: {} - - is-alphanumerical@2.0.1: - dependencies: - is-alphabetical: 2.0.1 - is-decimal: 2.0.1 - - is-arrayish@0.2.1: {} - - is-binary-path@2.1.0: - dependencies: - binary-extensions: 2.3.0 - - is-decimal@2.0.1: {} - - is-docker@2.2.1: {} - - is-docker@3.0.0: {} - - is-extglob@2.1.1: {} - - is-glob@4.0.3: - dependencies: - is-extglob: 2.1.1 - - is-hexadecimal@2.0.1: {} - - is-in-ssh@1.0.0: {} - - is-inside-container@1.0.0: - dependencies: - is-docker: 3.0.0 - - is-interactive@2.0.0: {} - - is-number@7.0.0: {} - - is-obj@2.0.0: {} - - is-obj@3.0.0: {} - - is-plain-obj@4.1.0: {} - - is-promise@4.0.0: {} - - is-regexp@3.1.0: {} - - is-stream@2.0.1: {} - - is-stream@4.0.1: {} - - is-unicode-supported@1.3.0: {} - - is-unicode-supported@2.1.0: {} - - is-wsl@2.2.0: - dependencies: - is-docker: 2.2.1 - - is-wsl@3.1.1: - dependencies: - is-inside-container: 1.0.0 - - isbot@5.1.40: {} - - isexe@2.0.0: {} - - isexe@3.1.5: {} - - javascript-natural-sort@0.7.1: {} - - jiti@2.7.0: {} - - jose@6.2.3: {} - - jotai@2.20.0(@babel/core@7.29.7)(@babel/template@7.29.7)(@types/react@19.2.14)(react@19.2.5): - optionalDependencies: - '@babel/core': 7.29.7 - '@babel/template': 7.29.7 - '@types/react': 19.2.14 - react: 19.2.5 - - js-tokens@4.0.0: {} - - js-yaml@4.3.0: - dependencies: - argparse: 2.0.1 - - jsesc@3.1.0: {} - - json-buffer@3.0.1: {} - - json-parse-even-better-errors@2.3.1: {} - - json-schema-traverse@0.4.1: {} - - json-schema-traverse@1.0.0: {} - - json-schema-typed@7.0.3: {} - - json-schema-typed@8.0.2: {} - - json-stable-stringify-without-jsonify@1.0.1: {} - - json5@2.2.3: {} - - jsonfile@6.2.1: - dependencies: - universalify: 2.0.1 - optionalDependencies: - graceful-fs: 4.2.11 - - keyv@4.5.4: - dependencies: - json-buffer: 3.0.1 - - kleur@3.0.3: {} - - kleur@4.1.5: {} - - levn@0.4.1: - dependencies: - prelude-ls: 1.2.1 - type-check: 0.4.0 - - lightningcss-android-arm64@1.32.0: - optional: true - - lightningcss-darwin-arm64@1.32.0: - optional: true - - lightningcss-darwin-x64@1.32.0: - optional: true - - lightningcss-freebsd-x64@1.32.0: - optional: true - - lightningcss-linux-arm-gnueabihf@1.32.0: - optional: true - - lightningcss-linux-arm64-gnu@1.32.0: - optional: true - - lightningcss-linux-arm64-musl@1.32.0: - optional: true - - lightningcss-linux-x64-gnu@1.32.0: - optional: true - - lightningcss-linux-x64-musl@1.32.0: - optional: true - - lightningcss-win32-arm64-msvc@1.32.0: - optional: true - - lightningcss-win32-x64-msvc@1.32.0: - optional: true - - lightningcss@1.32.0: - dependencies: - detect-libc: 2.1.2 - optionalDependencies: - lightningcss-android-arm64: 1.32.0 - lightningcss-darwin-arm64: 1.32.0 - lightningcss-darwin-x64: 1.32.0 - lightningcss-freebsd-x64: 1.32.0 - lightningcss-linux-arm-gnueabihf: 1.32.0 - lightningcss-linux-arm64-gnu: 1.32.0 - lightningcss-linux-arm64-musl: 1.32.0 - lightningcss-linux-x64-gnu: 1.32.0 - lightningcss-linux-x64-musl: 1.32.0 - lightningcss-win32-arm64-msvc: 1.32.0 - lightningcss-win32-x64-msvc: 1.32.0 - - lines-and-columns@1.2.4: {} - - locate-path@3.0.0: - dependencies: - p-locate: 3.0.0 - path-exists: 3.0.0 - - locate-path@6.0.0: - dependencies: - p-locate: 5.0.0 - - lodash-es@4.17.23: {} - - log-symbols@6.0.0: - dependencies: - chalk: 5.6.2 - is-unicode-supported: 1.3.0 - - longest-streak@3.1.0: {} - - lowlight@3.3.0: - dependencies: - '@types/hast': 3.0.4 - devlop: 1.1.0 - highlight.js: 11.11.1 - - lru-cache@5.1.1: - dependencies: - yallist: 3.1.1 - - magic-string@0.30.21: - dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 - - markdown-table@3.0.4: {} - - math-intrinsics@1.1.0: {} - - mdast-util-find-and-replace@3.0.2: - dependencies: - '@types/mdast': 4.0.4 - escape-string-regexp: 5.0.0 - unist-util-is: 6.0.1 - unist-util-visit-parents: 6.0.2 - - mdast-util-from-markdown@2.0.3: - dependencies: - '@types/mdast': 4.0.4 - '@types/unist': 3.0.3 - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - mdast-util-to-string: 4.0.0 - micromark: 4.0.2 - micromark-util-decode-numeric-character-reference: 2.0.2 - micromark-util-decode-string: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - unist-util-stringify-position: 4.0.0 - transitivePeerDependencies: - - supports-color - - mdast-util-gfm-autolink-literal@2.0.1: - dependencies: - '@types/mdast': 4.0.4 - ccount: 2.0.1 - devlop: 1.1.0 - mdast-util-find-and-replace: 3.0.2 - micromark-util-character: 2.1.1 - - mdast-util-gfm-footnote@2.1.0: - dependencies: - '@types/mdast': 4.0.4 - devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - micromark-util-normalize-identifier: 2.0.1 - transitivePeerDependencies: - - supports-color - - mdast-util-gfm-strikethrough@2.0.0: - dependencies: - '@types/mdast': 4.0.4 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-gfm-table@2.0.0: - dependencies: - '@types/mdast': 4.0.4 - devlop: 1.1.0 - markdown-table: 3.0.4 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-gfm-task-list-item@2.0.0: - dependencies: - '@types/mdast': 4.0.4 - devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-gfm@3.1.0: - dependencies: - mdast-util-from-markdown: 2.0.3 - mdast-util-gfm-autolink-literal: 2.0.1 - mdast-util-gfm-footnote: 2.1.0 - mdast-util-gfm-strikethrough: 2.0.0 - mdast-util-gfm-table: 2.0.0 - mdast-util-gfm-task-list-item: 2.0.0 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-mdx-expression@2.0.1: - dependencies: - '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-mdx-jsx@3.2.0: - dependencies: - '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - '@types/unist': 3.0.3 - ccount: 2.0.1 - devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - parse-entities: 4.0.2 - stringify-entities: 4.0.4 - unist-util-stringify-position: 4.0.0 - vfile-message: 4.0.3 - transitivePeerDependencies: - - supports-color - - mdast-util-mdxjs-esm@2.0.1: - dependencies: - '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - devlop: 1.1.0 - mdast-util-from-markdown: 2.0.3 - mdast-util-to-markdown: 2.1.2 - transitivePeerDependencies: - - supports-color - - mdast-util-phrasing@4.1.0: - dependencies: - '@types/mdast': 4.0.4 - unist-util-is: 6.0.1 - - mdast-util-to-hast@13.2.1: - dependencies: - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - '@ungap/structured-clone': 1.3.0 - devlop: 1.1.0 - micromark-util-sanitize-uri: 2.0.1 - trim-lines: 3.0.1 - unist-util-position: 5.0.0 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - - mdast-util-to-markdown@2.1.2: - dependencies: - '@types/mdast': 4.0.4 - '@types/unist': 3.0.3 - longest-streak: 3.1.0 - mdast-util-phrasing: 4.1.0 - mdast-util-to-string: 4.0.0 - micromark-util-classify-character: 2.0.1 - micromark-util-decode-string: 2.0.1 - unist-util-visit: 5.1.0 - zwitch: 2.0.4 - - mdast-util-to-string@4.0.0: - dependencies: - '@types/mdast': 4.0.4 - - media-typer@1.1.0: {} - - merge-descriptors@2.0.0: {} - - merge-stream@2.0.0: {} - - merge2@1.4.1: {} - - micromark-core-commonmark@2.0.3: - dependencies: - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - micromark-factory-destination: 2.0.1 - micromark-factory-label: 2.0.1 - micromark-factory-space: 2.0.1 - micromark-factory-title: 2.0.1 - micromark-factory-whitespace: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-chunked: 2.0.1 - micromark-util-classify-character: 2.0.1 - micromark-util-html-tag-name: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-subtokenize: 2.1.0 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm-autolink-literal@2.1.0: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-sanitize-uri: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm-footnote@2.1.0: - dependencies: - devlop: 1.1.0 - micromark-core-commonmark: 2.0.3 - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-sanitize-uri: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm-strikethrough@2.1.0: - dependencies: - devlop: 1.1.0 - micromark-util-chunked: 2.0.1 - micromark-util-classify-character: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm-table@2.1.1: - dependencies: - devlop: 1.1.0 - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm-tagfilter@2.0.0: - dependencies: - micromark-util-types: 2.0.2 - - micromark-extension-gfm-task-list-item@2.1.0: - dependencies: - devlop: 1.1.0 - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-extension-gfm@3.0.0: - dependencies: - micromark-extension-gfm-autolink-literal: 2.1.0 - micromark-extension-gfm-footnote: 2.1.0 - micromark-extension-gfm-strikethrough: 2.1.0 - micromark-extension-gfm-table: 2.1.1 - micromark-extension-gfm-tagfilter: 2.0.0 - micromark-extension-gfm-task-list-item: 2.1.0 - micromark-util-combine-extensions: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-factory-destination@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-factory-label@2.0.1: - dependencies: - devlop: 1.1.0 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-factory-space@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-types: 2.0.2 - - micromark-factory-title@2.0.1: - dependencies: - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-factory-whitespace@2.0.1: - dependencies: - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-character@2.1.1: - dependencies: - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-chunked@2.0.1: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-classify-character@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-combine-extensions@2.0.1: - dependencies: - micromark-util-chunked: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-decode-numeric-character-reference@2.0.2: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-decode-string@2.0.1: - dependencies: - decode-named-character-reference: 1.3.0 - micromark-util-character: 2.1.1 - micromark-util-decode-numeric-character-reference: 2.0.2 - micromark-util-symbol: 2.0.1 - - micromark-util-encode@2.0.1: {} - - micromark-util-html-tag-name@2.0.1: {} - - micromark-util-normalize-identifier@2.0.1: - dependencies: - micromark-util-symbol: 2.0.1 - - micromark-util-resolve-all@2.0.1: - dependencies: - micromark-util-types: 2.0.2 - - micromark-util-sanitize-uri@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-encode: 2.0.1 - micromark-util-symbol: 2.0.1 - - micromark-util-subtokenize@2.1.0: - dependencies: - devlop: 1.1.0 - micromark-util-chunked: 2.0.1 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-symbol@2.0.1: {} - - micromark-util-types@2.0.2: {} - - micromark@4.0.2: - dependencies: - '@types/debug': 4.1.13 - debug: 4.4.3 - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - micromark-core-commonmark: 2.0.3 - micromark-factory-space: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-chunked: 2.0.1 - micromark-util-combine-extensions: 2.0.1 - micromark-util-decode-numeric-character-reference: 2.0.2 - micromark-util-encode: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-sanitize-uri: 2.0.1 - micromark-util-subtokenize: 2.1.0 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - transitivePeerDependencies: - - supports-color - - micromatch@4.0.8: - dependencies: - braces: 3.0.3 - picomatch: 2.3.2 - - mime-db@1.54.0: {} - - mime-types@3.0.2: - dependencies: - mime-db: 1.54.0 - - mimic-fn@2.1.0: {} - - mimic-fn@3.1.0: {} - - mimic-function@5.0.1: {} - - minimatch@10.2.5: - dependencies: - brace-expansion: 5.0.6 - - minimatch@9.0.9: - dependencies: - brace-expansion: 2.0.3 - - minimist@1.2.8: {} - - ms@2.1.3: {} - - nanoid@3.3.15: {} - - natural-compare@1.4.0: {} - - negotiator@1.0.0: {} - - node-releases@2.0.50: {} - - normalize-path@3.0.0: {} - - npm-run-path@4.0.1: - dependencies: - path-key: 3.1.1 - - npm-run-path@6.0.0: - dependencies: - path-key: 4.0.0 - unicorn-magic: 0.3.0 - - object-assign@4.1.1: {} - - object-inspect@1.13.4: {} - - object-treeify@1.1.33: {} - - on-finished@2.4.1: - dependencies: - ee-first: 1.1.1 - - once@1.4.0: - dependencies: - wrappy: 1.0.2 - - onetime@5.1.2: - dependencies: - mimic-fn: 2.1.0 - - onetime@7.0.0: - dependencies: - mimic-function: 5.0.1 - - open@11.0.0: - dependencies: - default-browser: 5.5.0 - define-lazy-prop: 3.0.0 - is-in-ssh: 1.0.0 - is-inside-container: 1.0.0 - powershell-utils: 0.1.0 - wsl-utils: 0.3.1 - - open@8.4.2: - dependencies: - define-lazy-prop: 2.0.0 - is-docker: 2.2.1 - is-wsl: 2.2.0 - - optionator@0.9.4: - dependencies: - deep-is: 0.1.4 - fast-levenshtein: 2.0.6 - levn: 0.4.1 - prelude-ls: 1.2.1 - type-check: 0.4.0 - word-wrap: 1.2.5 - - ora@8.2.0: - dependencies: - chalk: 5.6.2 - cli-cursor: 5.0.0 - cli-spinners: 2.9.2 - is-interactive: 2.0.0 - is-unicode-supported: 2.1.0 - log-symbols: 6.0.0 - stdin-discarder: 0.2.2 - string-width: 7.2.0 - strip-ansi: 7.2.0 - - p-limit@2.3.0: - dependencies: - p-try: 2.2.0 - - p-limit@3.1.0: - dependencies: - yocto-queue: 0.1.0 - - p-locate@3.0.0: - dependencies: - p-limit: 2.3.0 - - p-locate@5.0.0: - dependencies: - p-limit: 3.1.0 - - p-try@2.2.0: {} - - parent-module@1.0.1: - dependencies: - callsites: 3.1.0 - - parse-entities@4.0.2: - dependencies: - '@types/unist': 2.0.11 - character-entities-legacy: 3.0.0 - character-reference-invalid: 2.0.1 - decode-named-character-reference: 1.3.0 - is-alphanumerical: 2.0.1 - is-decimal: 2.0.1 - is-hexadecimal: 2.0.1 - - parse-imports-exports@0.2.4: - dependencies: - parse-statements: 1.0.11 - - parse-json@5.2.0: - dependencies: - '@babel/code-frame': 7.29.7 - error-ex: 1.3.4 - json-parse-even-better-errors: 2.3.1 - lines-and-columns: 1.2.4 - - parse-ms@4.0.0: {} - - parse-statements@1.0.11: {} - - parse5@7.3.0: - dependencies: - entities: 6.0.1 - - parseurl@1.3.3: {} - - path-browserify@1.0.1: {} - - path-exists@3.0.0: {} - - path-exists@4.0.0: {} - - path-key@3.1.1: {} - - path-key@4.0.0: {} - - path-to-regexp@8.4.2: {} - - pathe@2.0.3: {} - - picocolors@1.1.1: {} - - picomatch@2.3.2: {} - - picomatch@4.0.4: {} - - picomatch@4.0.5: {} - - pkce-challenge@5.0.1: {} - - pkg-up@3.1.0: - dependencies: - find-up: 3.0.0 - - postcss-selector-parser@6.0.10: - dependencies: - cssesc: 3.0.0 - util-deprecate: 1.0.2 - - postcss-selector-parser@7.1.4: - dependencies: - cssesc: 3.0.0 - util-deprecate: 1.0.2 - - postcss@8.5.15: - dependencies: - nanoid: 3.3.15 - picocolors: 1.1.1 - source-map-js: 1.2.1 - - postcss@8.5.16: - dependencies: - nanoid: 3.3.15 - picocolors: 1.1.1 - source-map-js: 1.2.1 - - powershell-utils@0.1.0: {} - - prelude-ls@1.2.1: {} - - prettier-plugin-tailwindcss@0.8.0(@trivago/prettier-plugin-sort-imports@6.0.2(prettier@3.8.3))(prettier@3.8.3): - dependencies: - prettier: 3.8.3 - optionalDependencies: - '@trivago/prettier-plugin-sort-imports': 6.0.2(prettier@3.8.3) - - prettier@3.8.3: {} - - pretty-ms@9.3.0: - dependencies: - parse-ms: 4.0.0 - - prompts@2.4.2: - dependencies: - kleur: 3.0.3 - sisteransi: 1.0.5 - - property-information@7.1.0: {} - - proxy-addr@2.0.7: - dependencies: - forwarded: 0.2.0 - ipaddr.js: 1.9.1 - - punycode@2.3.1: {} - - qs@6.15.3: - dependencies: - es-define-property: 1.0.1 - side-channel: 1.1.1 - - queue-microtask@1.2.3: {} - - radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5): - dependencies: - '@radix-ui/primitive': 1.1.3 - '@radix-ui/react-accessible-icon': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-accordion': 1.2.12(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-alert-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-arrow': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-aspect-ratio': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-avatar': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-checkbox': 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-collapsible': 1.1.12(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-context-menu': 2.2.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-dialog': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-dropdown-menu': 2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-form': 0.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-hover-card': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-label': 2.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-menu': 2.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-menubar': 1.1.16(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-navigation-menu': 1.2.14(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-one-time-password-field': 0.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-password-toggle-field': 0.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-popover': 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-progress': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-radio-group': 1.3.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-scroll-area': 1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-select': 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-separator': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slider': 1.3.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-switch': 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-tabs': 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toast': 1.2.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toggle': 1.1.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toggle-group': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-toolbar': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-tooltip': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-effect-event': 0.0.2(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-escape-keydown': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-is-hydrated': 0.1.0(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) - '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - '@types/react-dom': 19.2.3(@types/react@19.2.14) - - range-parser@1.3.0: {} - - raw-body@3.0.2: - dependencies: - bytes: 3.1.2 - http-errors: 2.0.1 - iconv-lite: 0.7.2 - unpipe: 1.0.0 - - react-dom@19.2.5(react@19.2.5): - dependencies: - react: 19.2.5 - scheduler: 0.27.0 - - react-i18next@17.0.7(i18next@26.0.10(typescript@5.9.3))(react-dom@19.2.5(react@19.2.5))(react@19.2.5)(typescript@5.9.3): - dependencies: - '@babel/runtime': 7.29.7 - html-parse-stringify: 3.0.1 - i18next: 26.0.10(typescript@5.9.3) - react: 19.2.5 - use-sync-external-store: 1.6.0(react@19.2.5) - optionalDependencies: - react-dom: 19.2.5(react@19.2.5) - typescript: 5.9.3 - - react-markdown@10.1.0(@types/react@19.2.14)(react@19.2.5): - dependencies: - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - '@types/react': 19.2.14 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6 - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1 - react: 19.2.5 - remark-parse: 11.0.0 - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - - react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.5) - tslib: 2.8.1 - optionalDependencies: - '@types/react': 19.2.14 - - react-remove-scroll@2.7.2(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - react-remove-scroll-bar: 2.3.8(@types/react@19.2.14)(react@19.2.5) - react-style-singleton: 2.2.3(@types/react@19.2.14)(react@19.2.5) - tslib: 2.8.1 - use-callback-ref: 1.3.3(@types/react@19.2.14)(react@19.2.5) - use-sidecar: 1.1.3(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - - react-style-singleton@2.2.3(@types/react@19.2.14)(react@19.2.5): - dependencies: - get-nonce: 1.0.1 - react: 19.2.5 - tslib: 2.8.1 - optionalDependencies: - '@types/react': 19.2.14 - - react-textarea-autosize@8.5.9(@types/react@19.2.14)(react@19.2.5): - dependencies: - '@babel/runtime': 7.29.2 - react: 19.2.5 - use-composed-ref: 1.4.0(@types/react@19.2.14)(react@19.2.5) - use-latest: 1.3.0(@types/react@19.2.14)(react@19.2.5) - transitivePeerDependencies: - - '@types/react' - - react@19.2.5: {} - - readdirp@3.6.0: - dependencies: - picomatch: 2.3.2 - - recast@0.23.12: - dependencies: - ast-types: 0.16.1 - esprima: 4.0.1 - source-map: 0.6.1 - tiny-invariant: 1.3.3 - tslib: 2.8.1 - - rehype-highlight@7.0.2: - dependencies: - '@types/hast': 3.0.4 - hast-util-to-text: 4.0.2 - lowlight: 3.3.0 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - - rehype-raw@7.0.0: - dependencies: - '@types/hast': 3.0.4 - hast-util-raw: 9.1.0 - vfile: 6.0.3 - - rehype-sanitize@6.0.0: - dependencies: - '@types/hast': 3.0.4 - hast-util-sanitize: 5.0.2 - - remark-gfm@4.0.1: - dependencies: - '@types/mdast': 4.0.4 - mdast-util-gfm: 3.1.0 - micromark-extension-gfm: 3.0.0 - remark-parse: 11.0.0 - remark-stringify: 11.0.0 - unified: 11.0.5 - transitivePeerDependencies: - - supports-color - - remark-parse@11.0.0: - dependencies: - '@types/mdast': 4.0.4 - mdast-util-from-markdown: 2.0.3 - micromark-util-types: 2.0.2 - unified: 11.0.5 - transitivePeerDependencies: - - supports-color - - remark-rehype@11.1.2: - dependencies: - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - mdast-util-to-hast: 13.2.1 - unified: 11.0.5 - vfile: 6.0.3 - - remark-stringify@11.0.0: - dependencies: - '@types/mdast': 4.0.4 - mdast-util-to-markdown: 2.1.2 - unified: 11.0.5 - - require-from-string@2.0.2: {} - - resolve-from@4.0.0: {} - - resolve-pkg-maps@1.0.0: {} - - restore-cursor@5.1.0: - dependencies: - onetime: 7.0.0 - signal-exit: 4.1.0 - - reusify@1.1.0: {} - - rolldown@1.0.3: - dependencies: - '@oxc-project/types': 0.133.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm64': 1.0.3 - '@rolldown/binding-darwin-arm64': 1.0.3 - '@rolldown/binding-darwin-x64': 1.0.3 - '@rolldown/binding-freebsd-x64': 1.0.3 - '@rolldown/binding-linux-arm-gnueabihf': 1.0.3 - '@rolldown/binding-linux-arm64-gnu': 1.0.3 - '@rolldown/binding-linux-arm64-musl': 1.0.3 - '@rolldown/binding-linux-ppc64-gnu': 1.0.3 - '@rolldown/binding-linux-s390x-gnu': 1.0.3 - '@rolldown/binding-linux-x64-gnu': 1.0.3 - '@rolldown/binding-linux-x64-musl': 1.0.3 - '@rolldown/binding-openharmony-arm64': 1.0.3 - '@rolldown/binding-wasm32-wasi': 1.0.3 - '@rolldown/binding-win32-arm64-msvc': 1.0.3 - '@rolldown/binding-win32-x64-msvc': 1.0.3 - - router@2.2.0: - dependencies: - debug: 4.4.3 - depd: 2.0.0 - is-promise: 4.0.0 - parseurl: 1.3.3 - path-to-regexp: 8.4.2 - transitivePeerDependencies: - - supports-color - - run-applescript@7.1.0: {} - - run-parallel@1.2.0: - dependencies: - queue-microtask: 1.2.3 - - safer-buffer@2.1.2: {} - - scheduler@0.27.0: {} - - semver@6.3.1: {} - - semver@7.8.5: {} - - semver@7.8.5: {} - - send@1.2.1: - dependencies: - debug: 4.4.3 - encodeurl: 2.0.0 - escape-html: 1.0.3 - etag: 1.8.1 - fresh: 2.0.0 - http-errors: 2.0.1 - mime-types: 3.0.2 - ms: 2.1.3 - on-finished: 2.4.1 - range-parser: 1.3.0 - statuses: 2.0.2 - transitivePeerDependencies: - - supports-color - - seroval-plugins@1.5.1(seroval@1.5.1): - dependencies: - seroval: 1.5.1 - - seroval-plugins@1.5.4(seroval@1.5.4): - dependencies: - seroval: 1.5.4 - - seroval@1.5.1: {} - - seroval@1.5.4: {} - - serve-static@2.2.1: - dependencies: - encodeurl: 2.0.0 - escape-html: 1.0.3 - parseurl: 1.3.3 - send: 1.2.1 - transitivePeerDependencies: - - supports-color - - setprototypeof@1.2.0: {} - - shadcn@4.12.0(typescript@5.9.3): - dependencies: - '@babel/core': 7.29.7 - '@babel/parser': 7.29.7 - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) - '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7) - '@dotenvx/dotenvx': 1.75.1 - '@modelcontextprotocol/sdk': 1.29.0(zod@3.25.76) - '@types/validate-npm-package-name': 4.0.2 - browserslist: 4.28.4 - commander: 14.0.3 - cosmiconfig: 9.0.2(typescript@5.9.3) - dedent: 1.7.2 - deepmerge: 4.3.1 - diff: 8.0.4 - execa: 9.6.1 - fast-glob: 3.3.3 - fs-extra: 11.3.6 - fuzzysort: 3.1.0 - kleur: 4.1.5 - open: 11.0.0 - ora: 8.2.0 - postcss: 8.5.16 - postcss-selector-parser: 7.1.4 - prompts: 2.4.2 - recast: 0.23.12 - stringify-object: 5.0.0 - tailwind-merge: 3.5.0 - ts-morph: 26.0.0 - tsconfig-paths: 4.2.0 - undici: 7.28.0 - validate-npm-package-name: 7.0.2 - zod: 3.25.76 - zod-to-json-schema: 3.25.2(zod@3.25.76) - transitivePeerDependencies: - - '@cfworker/json-schema' - - babel-plugin-macros - - supports-color - - typescript - - shebang-command@2.0.0: - dependencies: - shebang-regex: 3.0.0 - - shebang-regex@3.0.0: {} - - side-channel-list@1.0.1: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - - side-channel-map@1.0.1: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - object-inspect: 1.13.4 - - side-channel-weakmap@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - object-inspect: 1.13.4 - side-channel-map: 1.0.1 - - side-channel@1.1.1: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - side-channel-list: 1.0.1 - side-channel-map: 1.0.1 - side-channel-weakmap: 1.0.2 - - signal-exit@3.0.7: {} - - signal-exit@4.1.0: {} - - sisteransi@1.0.5: {} - - sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): - dependencies: - react: 19.2.5 - react-dom: 19.2.5(react@19.2.5) - - source-map-js@1.2.1: {} - - source-map@0.6.1: {} - - source-map@0.7.6: {} - - space-separated-tokens@2.0.2: {} - - statuses@2.0.2: {} - - stdin-discarder@0.2.2: {} - - string-width@7.2.0: - dependencies: - emoji-regex: 10.6.0 - get-east-asian-width: 1.6.0 - strip-ansi: 7.2.0 - - string-width@8.2.0: - dependencies: - get-east-asian-width: 1.5.0 - strip-ansi: 7.2.0 - - stringify-entities@4.0.4: - dependencies: - character-entities-html4: 2.1.0 - character-entities-legacy: 3.0.0 - - stringify-object@5.0.0: - dependencies: - get-own-enumerable-keys: 1.0.0 - is-obj: 3.0.0 - is-regexp: 3.1.0 - - strip-ansi@6.0.1: - dependencies: - ansi-regex: 5.0.1 - - strip-ansi@7.2.0: - dependencies: - ansi-regex: 6.2.2 - - strip-bom@3.0.0: {} - - strip-final-newline@2.0.0: {} - - strip-final-newline@4.0.0: {} - - style-to-js@1.1.21: - dependencies: - style-to-object: 1.0.14 - - style-to-object@1.0.14: - dependencies: - inline-style-parser: 0.2.7 - - systeminformation@5.31.11: {} - - tailwind-merge@3.5.0: {} - - tailwindcss@4.3.0: {} - - tapable@2.3.3: {} - - tiny-invariant@1.3.3: {} - - tinyglobby@0.2.17: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - - to-regex-range@5.0.1: - dependencies: - is-number: 7.0.0 - - toidentifier@1.0.1: {} - - trim-lines@3.0.1: {} - - trough@2.2.0: {} - - ts-api-utils@2.5.0(typescript@5.9.3): - dependencies: - typescript: 5.9.3 - - ts-morph@26.0.0: - dependencies: - '@ts-morph/common': 0.27.0 - code-block-writer: 13.0.3 - - tsconfig-paths@4.2.0: - dependencies: - json5: 2.2.3 - minimist: 1.2.8 - strip-bom: 3.0.0 - - tslib@2.8.1: {} - - tsx@4.21.0: - dependencies: - esbuild: 0.27.4 - get-tsconfig: 4.13.7 - optionalDependencies: - fsevents: 2.3.3 - - tw-animate-css@1.4.0: {} - - type-check@0.4.0: - dependencies: - prelude-ls: 1.2.1 - - type-is@2.1.0: - dependencies: - content-type: 2.0.0 - media-typer: 1.1.0 - mime-types: 3.0.2 - - typescript-eslint@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3): - dependencies: - '@typescript-eslint/eslint-plugin': 8.62.1(@typescript-eslint/parser@8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3))(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/parser': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.62.1(typescript@5.9.3) - '@typescript-eslint/utils': 8.62.1(eslint@10.4.1(jiti@2.7.0))(typescript@5.9.3) - eslint: 10.4.1(jiti@2.7.0) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - typescript@5.9.3: {} - - undici-types@7.19.2: {} - - undici@7.28.0: {} - - unicorn-magic@0.3.0: {} - - unified@11.0.5: - dependencies: - '@types/unist': 3.0.3 - bail: 2.0.2 - devlop: 1.1.0 - extend: 3.0.2 - is-plain-obj: 4.1.0 - trough: 2.2.0 - vfile: 6.0.3 - - unist-util-find-after@5.0.0: - dependencies: - '@types/unist': 3.0.3 - unist-util-is: 6.0.1 - - unist-util-is@6.0.1: - dependencies: - '@types/unist': 3.0.3 - - unist-util-position@5.0.0: - dependencies: - '@types/unist': 3.0.3 - - unist-util-stringify-position@4.0.0: - dependencies: - '@types/unist': 3.0.3 - - unist-util-visit-parents@6.0.2: - dependencies: - '@types/unist': 3.0.3 - unist-util-is: 6.0.1 - - unist-util-visit@5.1.0: - dependencies: - '@types/unist': 3.0.3 - unist-util-is: 6.0.1 - unist-util-visit-parents: 6.0.2 - - universalify@2.0.1: {} - - unpipe@1.0.0: {} - - unplugin@2.3.11: - dependencies: - '@jridgewell/remapping': 2.3.5 - acorn: 8.16.0 - picomatch: 4.0.4 - webpack-virtual-modules: 0.6.2 - - update-browserslist-db@1.2.3(browserslist@4.28.4): - dependencies: - browserslist: 4.28.4 - escalade: 3.2.0 - picocolors: 1.1.1 - - uri-js@4.4.1: - dependencies: - punycode: 2.3.1 - - use-callback-ref@1.3.3(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - tslib: 2.8.1 - optionalDependencies: - '@types/react': 19.2.14 - - use-composed-ref@1.4.0(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - use-isomorphic-layout-effect@1.2.1(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - optionalDependencies: - '@types/react': 19.2.14 - - use-latest@1.3.0(@types/react@19.2.14)(react@19.2.5): - dependencies: - react: 19.2.5 - use-isomorphic-layout-effect: 1.2.1(@types/react@19.2.14)(react@19.2.5) - optionalDependencies: - '@types/react': 19.2.14 - - use-sidecar@1.1.3(@types/react@19.2.14)(react@19.2.5): - dependencies: - detect-node-es: 1.1.0 - react: 19.2.5 - tslib: 2.8.1 - optionalDependencies: - '@types/react': 19.2.14 - - use-sync-external-store@1.6.0(react@19.2.5): - dependencies: - react: 19.2.5 - - util-deprecate@1.0.2: {} - - validate-npm-package-name@7.0.2: {} - - vary@1.1.2: {} - - vfile-location@5.0.3: - dependencies: - '@types/unist': 3.0.3 - vfile: 6.0.3 - - vfile-message@4.0.3: - dependencies: - '@types/unist': 3.0.3 - unist-util-stringify-position: 4.0.0 - - vfile@6.0.3: - dependencies: - '@types/unist': 3.0.3 - vfile-message: 4.0.3 - - vite@8.0.16(@types/node@25.6.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0): - dependencies: - lightningcss: 1.32.0 - picomatch: 4.0.4 - postcss: 8.5.15 - rolldown: 1.0.3 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 25.6.0 - esbuild: 0.27.4 - fsevents: 2.3.3 - jiti: 2.7.0 - tsx: 4.21.0 - - void-elements@3.1.0: {} - - web-namespaces@2.0.1: {} - - webpack-virtual-modules@0.6.2: {} - - which@2.0.2: - dependencies: - isexe: 2.0.0 - - which@4.0.0: - dependencies: - isexe: 3.1.5 - - word-wrap@1.2.5: {} - - wrap-ansi@10.0.0: - dependencies: - ansi-styles: 6.2.3 - string-width: 8.2.0 - strip-ansi: 7.2.0 - - wrappy@1.0.2: {} - - wsl-utils@0.3.1: - dependencies: - is-wsl: 3.1.1 - powershell-utils: 0.1.0 - - yallist@3.1.1: {} - - yocto-queue@0.1.0: {} - - yocto-spinner@1.2.0: - dependencies: - yoctocolors: 2.1.2 - - yoctocolors@2.1.2: {} - - zod-to-json-schema@3.25.2(zod@3.25.76): - dependencies: - zod: 3.25.76 - - zod-validation-error@4.0.2(zod@4.3.6): - dependencies: - zod: 4.3.6 - - zod@3.25.76: {} - - zod@4.3.6: {} - - zwitch@2.0.4: {} diff --git a/web/frontend/prettier.config.js b/web/frontend/prettier.config.js deleted file mode 100644 index 492ef1dd..00000000 --- a/web/frontend/prettier.config.js +++ /dev/null @@ -1,17 +0,0 @@ -// @ts-check - -/** @type {import('prettier').Config} */ -const config = { - semi: false, - printWidth: 80, - tabWidth: 2, - importOrder: ["", "", "^@/", "^[./]"], - importOrderSeparation: true, - importOrderSortSpecifiers: true, - plugins: [ - "@trivago/prettier-plugin-sort-imports", - "prettier-plugin-tailwindcss", - ], -} - -export default config diff --git a/web/frontend/public/apple-touch-icon.png b/web/frontend/public/apple-touch-icon.png deleted file mode 100644 index d881c64a..00000000 Binary files a/web/frontend/public/apple-touch-icon.png and /dev/null differ diff --git a/web/frontend/public/favicon-96x96.png b/web/frontend/public/favicon-96x96.png deleted file mode 100644 index 5bdeccea..00000000 Binary files a/web/frontend/public/favicon-96x96.png and /dev/null differ diff --git a/web/frontend/public/favicon.ico b/web/frontend/public/favicon.ico deleted file mode 100644 index 8b46b4b2..00000000 Binary files a/web/frontend/public/favicon.ico and /dev/null differ diff --git a/web/frontend/public/favicon.svg b/web/frontend/public/favicon.svg deleted file mode 100644 index e2f412b7..00000000 --- a/web/frontend/public/favicon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/web/frontend/public/lark.svg b/web/frontend/public/lark.svg deleted file mode 100644 index 0761f278..00000000 --- a/web/frontend/public/lark.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/web/frontend/public/logo_with_text.png b/web/frontend/public/logo_with_text.png deleted file mode 100644 index 70f26788..00000000 Binary files a/web/frontend/public/logo_with_text.png and /dev/null differ diff --git a/web/frontend/public/site.webmanifest b/web/frontend/public/site.webmanifest deleted file mode 100644 index 981d97f1..00000000 --- a/web/frontend/public/site.webmanifest +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "MyWebSite", - "short_name": "MySite", - "icons": [ - { - "src": "/web-app-manifest-192x192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "maskable" - }, - { - "src": "/web-app-manifest-512x512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "maskable" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/web/frontend/public/web-app-manifest-192x192.png b/web/frontend/public/web-app-manifest-192x192.png deleted file mode 100644 index 01933339..00000000 Binary files a/web/frontend/public/web-app-manifest-192x192.png and /dev/null differ diff --git a/web/frontend/public/web-app-manifest-512x512.png b/web/frontend/public/web-app-manifest-512x512.png deleted file mode 100644 index e0b4aab9..00000000 Binary files a/web/frontend/public/web-app-manifest-512x512.png and /dev/null differ diff --git a/web/frontend/scripts/ensure-backend-gitkeep.cjs b/web/frontend/scripts/ensure-backend-gitkeep.cjs deleted file mode 100644 index db9782ab..00000000 --- a/web/frontend/scripts/ensure-backend-gitkeep.cjs +++ /dev/null @@ -1,9 +0,0 @@ -const fs = require("node:fs") -const path = require("node:path") - -const gitkeepPath = path.resolve(__dirname, "../../backend/dist/.gitkeep") -const gitkeepContents = - "# Keep the embedded web backend dist directory in version control.\n" - -fs.mkdirSync(path.dirname(gitkeepPath), { recursive: true }) -fs.writeFileSync(gitkeepPath, gitkeepContents) diff --git a/web/frontend/src/api/channels.ts b/web/frontend/src/api/channels.ts deleted file mode 100644 index 36389ca8..00000000 --- a/web/frontend/src/api/channels.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export type ChannelConfig = Record -export type AppConfig = Record - -export interface SupportedChannel { - name: string - display_name?: string - config_key: string - variant?: string -} - -export interface ChannelConfigResponse { - config: ChannelConfig - configured_secrets: string[] - config_key: string - variant?: string -} - -interface ChannelsCatalogResponse { - channels: SupportedChannel[] -} - -interface ConfigActionResponse { - status: string - errors?: string[] -} - -const BASE_URL = "" - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(`${BASE_URL}${path}`, options) - if (!res.ok) { - let message = `API error: ${res.status} ${res.statusText}` - try { - const body = (await res.json()) as { - error?: string - errors?: string[] - status?: string - } - if (Array.isArray(body.errors) && body.errors.length > 0) { - message = body.errors.join("; ") - } else if (typeof body.error === "string" && body.error.trim() !== "") { - message = body.error - } - } catch { - // Keep default fallback message if response body is not JSON. - } - throw new Error(message) - } - return res.json() as Promise -} - -export async function getChannelsCatalog(): Promise { - return request("/api/channels/catalog") -} - -export async function getAppConfig(): Promise { - return request("/api/config") -} - -export async function getChannelConfig( - channelName: string, -): Promise { - return request( - `/api/channels/${encodeURIComponent(channelName)}/config`, - ) -} - -export async function patchAppConfig( - patch: Record, -): Promise { - return request("/api/config", { - method: "PATCH", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(patch), - }) -} - -export async function resetAppConfig(): Promise { - return request("/api/config/reset", { - method: "POST", - }) -} - -// WeChat QR login flow API - -export interface WeixinFlowResponse { - flow_id: string - status: "wait" | "scaned" | "confirmed" | "expired" | "error" - qr_data_uri?: string - account_id?: string - error?: string -} - -export interface WecomFlowResponse { - flow_id: string - status: "wait" | "scaned" | "confirmed" | "expired" | "error" - qr_data_uri?: string - bot_id?: string - error?: string -} - -export async function startWeixinFlow(): Promise { - return request("/api/weixin/flows", { method: "POST" }) -} - -export async function pollWeixinFlow( - flowID: string, -): Promise { - return request( - `/api/weixin/flows/${encodeURIComponent(flowID)}`, - ) -} - -export async function startWecomFlow(): Promise { - return request("/api/wecom/flows", { method: "POST" }) -} - -export async function pollWecomFlow( - flowID: string, -): Promise { - return request( - `/api/wecom/flows/${encodeURIComponent(flowID)}`, - ) -} - -export type { ChannelsCatalogResponse, ConfigActionResponse } diff --git a/web/frontend/src/api/gateway.ts b/web/frontend/src/api/gateway.ts deleted file mode 100644 index 2742a0a3..00000000 --- a/web/frontend/src/api/gateway.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { launcherFetch } from "@/api/http" - -// API client for gateway process management. - -interface GatewayStatusResponse { - gateway_status: "running" | "starting" | "restarting" | "stopped" | "error" - gateway_start_allowed?: boolean - gateway_start_reason?: string - gateway_restart_required?: boolean - pid?: number - boot_default_model?: string - config_default_model?: string - [key: string]: unknown -} - -interface GatewayLogsResponse { - logs?: string[] - log_total?: number - log_run_id?: number -} - -interface GatewayActionResponse { - status: string - pid?: number - log_total?: number - log_run_id?: number -} - -const BASE_URL = "" - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(`${BASE_URL}${path}`, options) - if (!res.ok) { - throw new Error(`API error: ${res.status} ${res.statusText}`) - } - return res.json() as Promise -} - -export async function getGatewayStatus(): Promise { - return request("/api/gateway/status") -} - -export async function getGatewayLogs(options?: { - log_offset?: number - log_run_id?: number -}): Promise { - const params = new URLSearchParams() - if (options?.log_offset !== undefined) { - params.set("log_offset", options.log_offset.toString()) - } - if (options?.log_run_id !== undefined) { - params.set("log_run_id", options.log_run_id.toString()) - } - const queryString = params.toString() ? `?${params.toString()}` : "" - return request(`/api/gateway/logs${queryString}`) -} - -export async function startGateway(): Promise { - return request("/api/gateway/start", { - method: "POST", - }) -} - -export async function stopGateway(): Promise { - return request("/api/gateway/stop", { - method: "POST", - }) -} - -export async function restartGateway(): Promise { - return request("/api/gateway/restart", { - method: "POST", - }) -} - -export async function clearGatewayLogs(): Promise { - return request("/api/gateway/logs/clear", { - method: "POST", - }) -} - -export type { - GatewayStatusResponse, - GatewayLogsResponse, - GatewayActionResponse, -} diff --git a/web/frontend/src/api/http.ts b/web/frontend/src/api/http.ts deleted file mode 100644 index 347dd937..00000000 --- a/web/frontend/src/api/http.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { isLauncherAuthPathname } from "@/lib/launcher-login-path" - -function isLauncherAuthPath(): boolean { - if (typeof globalThis.location === "undefined") { - return false - } - if (isLauncherAuthPathname(globalThis.location.pathname || "/")) { - return true - } - try { - return isLauncherAuthPathname( - new URL(globalThis.location.href).pathname || "/", - ) - } catch { - return false - } -} - -/** - * Same-origin fetch that sends cookies; redirects to launcher login on 401 JSON responses. - * Skips redirect while already on an auth page (login or setup) to avoid reload loops. - */ -export async function launcherFetch( - input: RequestInfo | URL, - init?: RequestInit, -): Promise { - const res = await fetch(input, { - credentials: "same-origin", - ...init, - }) - if (res.status === 401) { - const ct = res.headers.get("content-type") || "" - if ( - ct.includes("application/json") && - typeof globalThis.location !== "undefined" && - !isLauncherAuthPath() - ) { - globalThis.location.assign("/launcher-login") - } - } - return res -} diff --git a/web/frontend/src/api/launcher-auth.ts b/web/frontend/src/api/launcher-auth.ts deleted file mode 100644 index c7318d96..00000000 --- a/web/frontend/src/api/launcher-auth.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Dashboard launcher auth API. - * Uses plain fetch (not launcherFetch) to avoid redirect loops on auth pages. - */ -export type LoginResult = - | { ok: true } - | { ok: false; status: number; error: string } - -export async function postLauncherDashboardLogin( - password: string, -): Promise { - const res = await fetch("/api/auth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - credentials: "same-origin", - body: JSON.stringify({ password: password.trim() }), - }) - if (res.ok) return { ok: true } - - return { - ok: false, - status: res.status, - error: await readLauncherAuthError(res), - } -} - -export type LauncherAuthStatus = { - authenticated: boolean - /** true when a bcrypt password has been stored in the DB */ - initialized: boolean -} - -export async function getLauncherAuthStatus(): Promise { - const res = await fetch("/api/auth/status", { - method: "GET", - credentials: "same-origin", - }) - if (!res.ok) { - throw new Error(`status ${res.status}`) - } - return (await res.json()) as LauncherAuthStatus -} - -export async function postLauncherDashboardLogout(): Promise { - const res = await fetch("/api/auth/logout", { - method: "POST", - headers: { "Content-Type": "application/json" }, - credentials: "same-origin", - body: "{}", - }) - return res.ok -} - -export type SetupResult = { ok: true } | { ok: false; error: string } - -export async function postLauncherDashboardSetup( - password: string, - confirm: string, -): Promise { - const res = await fetch("/api/auth/setup", { - method: "POST", - headers: { "Content-Type": "application/json" }, - credentials: "same-origin", - body: JSON.stringify({ - password: password.trim(), - confirm: confirm.trim(), - }), - }) - if (res.ok) return { ok: true } - return { ok: false, error: await readLauncherAuthError(res) } -} - -async function readLauncherAuthError(res: Response): Promise { - let msg = `Request failed with status ${res.status}` - try { - const j = (await res.json()) as { error?: string } - if (j.error) msg = j.error - } catch { - /* ignore */ - } - return msg -} diff --git a/web/frontend/src/api/models.ts b/web/frontend/src/api/models.ts deleted file mode 100644 index fef9fda7..00000000 --- a/web/frontend/src/api/models.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { launcherFetch } from "@/api/http" -import { refreshGatewayState } from "@/store/gateway" - -// API client for model list management. - -export interface ModelInfo { - index: number - model_name: string - provider?: string - model: string - api_base?: string - api_key: string - proxy?: string - auth_method?: string - // Advanced fields - connect_mode?: string - workspace?: string - rpm?: number - max_tokens_field?: string - request_timeout?: number - thinking_level?: string - tool_schema_transform?: string - streaming?: { - enabled?: boolean - } - extra_body?: Record - custom_headers?: Record - // Meta - enabled: boolean - available: boolean - status: "available" | "unconfigured" | "unreachable" - is_default: boolean - is_virtual: boolean - default_model_allowed?: boolean -} - -export interface ModelProviderOption { - id: string - display_name?: string - icon_slug?: string - domain?: string - default_api_base: string - empty_api_key_allowed: boolean - create_allowed: boolean - default_model_allowed: boolean - supports_fetch?: boolean - default_auth_method?: string - auth_method_locked?: boolean - local?: boolean - priority?: number - common_models?: string[] - aliases?: string[] -} - -interface ModelsListResponse { - models: ModelInfo[] - total: number - default_model: string - default_provider: string - fallback_chain: string[] - provider_options: ModelProviderOption[] -} - -export interface ModelReferenceRename { - from: string - to: string - default: boolean - fallback: boolean -} - -export interface ModelActionResponse { - status: string - index?: number - default_model?: string - reference_rename?: ModelReferenceRename -} - -export interface DefaultChain { - default_model: string - fallback_chain: string[] -} - -const BASE_URL = "" - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(`${BASE_URL}${path}`, options) - if (!res.ok) { - let detail = "" - try { - detail = await res.text() - } catch { - // ignore - } - throw new Error(detail || `API error: ${res.status} ${res.statusText}`) - } - return res.json() as Promise -} - -export async function getModels(): Promise { - return request("/api/models") -} - -export async function addModel( - model: Partial, -): Promise { - return request("/api/models", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(model), - }) -} - -export async function updateModel( - index: number, - model: Partial, -): Promise { - return request(`/api/models/${index}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(model), - }) -} - -export async function deleteModel(index: number): Promise { - return request(`/api/models/${index}`, { - method: "DELETE", - }) -} - -export async function setDefaultModel( - modelName: string, -): Promise { - const response = await request("/api/models/default", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model_name: modelName }), - }) - - await refreshGatewayState() - return response -} - -export async function getDefaultChain(): Promise { - return request("/api/models/default-chain") -} - -export async function updateDefaultChain( - payload: DefaultChain, -): Promise { - return request("/api/models/default-chain", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - }) -} - -export interface TestModelResponse { - success: boolean - latency_ms: number - status: string - error?: string -} - -export async function testModel(index: number): Promise { - return request(`/api/models/${index}/test`, { - method: "POST", - }) -} - -export interface TestModelInlineRequest { - provider: string - model: string - api_base?: string - api_key?: string - auth_method?: string - model_index?: number -} - -export async function testModelInline( - params: TestModelInlineRequest, -): Promise { - return request("/api/models/test-inline", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(params), - }) -} - -export interface UpstreamModel { - id: string - owned_by?: string - extra?: Record -} - -export interface FetchModelsRequest { - provider: string - api_key?: string - api_base?: string - model_index?: number -} - -export interface FetchModelsResponse { - models: UpstreamModel[] - total: number -} - -export async function fetchUpstreamModels( - req: FetchModelsRequest, -): Promise { - return request("/api/models/fetch", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(req), - }) -} - -// --- Model Catalog API --- - -export interface CatalogModel { - id: string - owned_by?: string - extra?: Record -} - -export interface CatalogEntry { - id: string - provider: string - api_base: string - api_key_mask: string - models: CatalogModel[] - fetched_at: string -} - -interface CatalogListResponse { - entries: CatalogEntry[] - total: number -} - -export async function getCatalogs(): Promise { - return request("/api/models/catalog") -} - -export async function deleteCatalog(id: string): Promise { - await request>( - `/api/models/catalog/${encodeURIComponent(id)}`, - { - method: "DELETE", - }, - ) -} - -export type { ModelsListResponse } diff --git a/web/frontend/src/api/oauth.ts b/web/frontend/src/api/oauth.ts deleted file mode 100644 index 689a2bcd..00000000 --- a/web/frontend/src/api/oauth.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export type OAuthProvider = "openai" | "anthropic" | "google-antigravity" -export type OAuthMethod = "browser" | "device_code" | "token" - -export interface OAuthProviderStatus { - provider: OAuthProvider - display_name: string - methods: OAuthMethod[] - logged_in: boolean - status: "connected" | "expired" | "needs_refresh" | "not_logged_in" - auth_method?: string - expires_at?: string - account_id?: string - email?: string - project_id?: string -} - -export interface OAuthFlowState { - flow_id: string - provider: OAuthProvider - method: OAuthMethod - status: "pending" | "success" | "error" | "expired" - expires_at?: string - error?: string - user_code?: string - verify_url?: string - interval?: number -} - -export interface OAuthLoginRequest { - provider: OAuthProvider - method: OAuthMethod - token?: string -} - -export interface OAuthLoginResponse { - status: string - provider: OAuthProvider - method: OAuthMethod - flow_id?: string - auth_url?: string - user_code?: string - verify_url?: string - interval?: number - expires_at?: string -} - -interface OAuthProvidersResponse { - providers: OAuthProviderStatus[] -} - -const BASE_URL = "" - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(`${BASE_URL}${path}`, options) - if (!res.ok) { - const message = await res.text() - throw new Error(message || `API error: ${res.status} ${res.statusText}`) - } - return res.json() as Promise -} - -export async function getOAuthProviders(): Promise { - return request("/api/oauth/providers") -} - -export async function loginOAuth( - payload: OAuthLoginRequest, -): Promise { - return request("/api/oauth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - }) -} - -export async function getOAuthFlow(flowID: string): Promise { - return request( - `/api/oauth/flows/${encodeURIComponent(flowID)}`, - ) -} - -export async function pollOAuthFlow(flowID: string): Promise { - return request( - `/api/oauth/flows/${encodeURIComponent(flowID)}/poll`, - { - method: "POST", - }, - ) -} - -export async function logoutOAuth( - provider: OAuthProvider, -): Promise<{ status: string; provider: OAuthProvider }> { - return request<{ status: string; provider: OAuthProvider }>( - "/api/oauth/logout", - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ provider }), - }, - ) -} diff --git a/web/frontend/src/api/pico.ts b/web/frontend/src/api/pico.ts deleted file mode 100644 index ca98a06d..00000000 --- a/web/frontend/src/api/pico.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { launcherFetch } from "@/api/http" - -// API client for Pico Channel configuration. - -interface PicoInfoResponse { - ws_url: string - enabled: boolean - configured?: boolean -} - -interface PicoSetupResponse { - ws_url: string - enabled: boolean - configured?: boolean - changed: boolean -} - -const BASE_URL = "" - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(`${BASE_URL}${path}`, options) - if (!res.ok) { - throw new Error(`API error: ${res.status} ${res.statusText}`) - } - return res.json() as Promise -} - -export async function getPicoInfo(): Promise { - return request("/api/pico/info") -} - -export async function regenPicoToken(): Promise { - return request("/api/pico/token", { method: "POST" }) -} - -export async function setupPico(): Promise { - return request("/api/pico/setup", { method: "POST" }) -} - -export type { PicoInfoResponse, PicoSetupResponse } diff --git a/web/frontend/src/api/sessions.ts b/web/frontend/src/api/sessions.ts deleted file mode 100644 index 8c0c5e90..00000000 --- a/web/frontend/src/api/sessions.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export interface SessionSummary { - id: string - title: string - preview: string - message_count: number - created: string - updated: string -} - -export interface SessionDetail { - id: string - messages: { - role: "user" | "assistant" - content: string - created_at?: string - kind?: "normal" | "thought" | "tool_calls" - model_name?: string - media?: string[] - attachments?: { - type?: "image" | "audio" | "video" | "file" - url: string - filename?: string - content_type?: string - }[] - tool_calls?: { - id?: string - type?: string - function?: { - name?: string - arguments?: string - } - extra_content?: { - tool_feedback_explanation?: string - } - }[] - }[] - summary: string - created: string - updated: string -} - -export async function getSessions( - offset: number = 0, - limit: number = 20, -): Promise { - const params = new URLSearchParams({ - offset: offset.toString(), - limit: limit.toString(), - }) - - const res = await launcherFetch(`/api/sessions?${params.toString()}`) - if (!res.ok) { - throw new Error(`Failed to fetch sessions: ${res.status}`) - } - return res.json() -} - -export async function getSessionHistory(id: string): Promise { - const res = await launcherFetch(`/api/sessions/${encodeURIComponent(id)}`) - if (!res.ok) { - throw new Error(`Failed to fetch session ${id}: ${res.status}`) - } - return res.json() -} - -export async function deleteSession(id: string): Promise { - const res = await launcherFetch(`/api/sessions/${encodeURIComponent(id)}`, { - method: "DELETE", - }) - if (!res.ok) { - throw new Error(`Failed to delete session ${id}: ${res.status}`) - } -} diff --git a/web/frontend/src/api/skills.ts b/web/frontend/src/api/skills.ts deleted file mode 100644 index 958808af..00000000 --- a/web/frontend/src/api/skills.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export interface SkillSupportItem { - name: string - path: string - source: "workspace" | "global" | "builtin" | string - description: string - origin_kind: "builtin" | "third_party" | "manual" | string - registry_name?: string - registry_url?: string - installed_version?: string - installed_at?: number -} - -export interface SkillDetailResponse extends SkillSupportItem { - content: string -} - -export interface SkillRegistrySearchResult { - score: number - slug: string - display_name: string - summary: string - version: string - registry_name: string - url?: string - installed: boolean - installed_name?: string -} - -interface SkillsResponse { - skills: SkillSupportItem[] -} - -export interface SkillSearchResponse { - results: SkillRegistrySearchResult[] - limit: number - offset: number - next_offset?: number - has_more: boolean -} - -type SkillActionResponse = Partial & { - status?: string -} - -export interface InstallSkillRequest { - slug: string - registry: string - version?: string - force?: boolean -} - -export interface InstallSkillResponse { - status: string - slug: string - registry: string - version: string - summary?: string - is_suspicious?: boolean - skill?: SkillSupportItem -} - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(path, options) - if (!res.ok) { - throw new Error(await extractErrorMessage(res)) - } - return res.json() as Promise -} - -export async function getSkills(): Promise { - return request("/api/skills") -} - -export async function getSkill(name: string): Promise { - return request(`/api/skills/${encodeURIComponent(name)}`) -} - -export async function searchSkills( - query: string, - limit = 20, - offset = 0, -): Promise { - const params = new URLSearchParams({ - q: query, - limit: String(limit), - offset: String(offset), - }) - return request(`/api/skills/search?${params.toString()}`) -} - -export async function installSkill( - input: InstallSkillRequest, -): Promise { - return request("/api/skills/install", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(input), - }) -} - -export async function importSkill(file: File): Promise { - const formData = new FormData() - formData.set("file", file) - - const res = await launcherFetch("/api/skills/import", { - method: "POST", - body: formData, - }) - if (!res.ok) { - throw new Error(await extractErrorMessage(res)) - } - return res.json() as Promise -} - -export async function deleteSkill(name: string): Promise { - return request( - `/api/skills/${encodeURIComponent(name)}`, - { - method: "DELETE", - }, - ) -} - -async function extractErrorMessage(res: Response): Promise { - try { - const raw = await res.text() - if (raw.trim() === "") { - return `API error: ${res.status} ${res.statusText}` - } - try { - const body = JSON.parse(raw) as { - error?: string - errors?: string[] - } - if (Array.isArray(body.errors) && body.errors.length > 0) { - return body.errors.join("; ") - } - if (typeof body.error === "string" && body.error.trim() !== "") { - return body.error - } - } catch { - return raw.trim() - } - } catch { - // ignore invalid body - } - return `API error: ${res.status} ${res.statusText}` -} diff --git a/web/frontend/src/api/system.ts b/web/frontend/src/api/system.ts deleted file mode 100644 index 55376cc2..00000000 --- a/web/frontend/src/api/system.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export interface AutoStartStatus { - enabled: boolean - supported: boolean - platform: string - message?: string -} - -export interface LauncherConfig { - port: number - public: boolean - allowed_cidrs: string[] - allow_localhost_bypass: boolean - trusted_proxy_cidrs: string[] -} - -export interface SystemVersionInfo { - version: string - git_commit?: string - build_time?: string - go_version: string -} - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(path, options) - if (!res.ok) { - let message = `API error: ${res.status} ${res.statusText}` - try { - const body = (await res.json()) as { - error?: string - errors?: string[] - } - if (Array.isArray(body.errors) && body.errors.length > 0) { - message = body.errors.join("; ") - } else if (typeof body.error === "string" && body.error.trim() !== "") { - message = body.error - } - } catch { - // Keep fallback error message when response body is not JSON. - } - throw new Error(message) - } - return res.json() as Promise -} - -export async function getAutoStartStatus(): Promise { - return request("/api/system/autostart") -} - -export async function setAutoStartEnabled( - enabled: boolean, -): Promise { - return request("/api/system/autostart", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ enabled }), - }) -} - -export async function getLauncherConfig(): Promise { - return request("/api/system/launcher-config") -} - -export async function setLauncherConfig( - payload: LauncherConfig, -): Promise { - return request("/api/system/launcher-config", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - }) -} - -export async function getSystemVersionInfo(): Promise { - return request("/api/system/version") -} diff --git a/web/frontend/src/api/tools.ts b/web/frontend/src/api/tools.ts deleted file mode 100644 index 298b42d3..00000000 --- a/web/frontend/src/api/tools.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { launcherFetch } from "@/api/http" - -export interface ToolSupportItem { - name: string - description: string - category: string - config_key: string - status: "enabled" | "disabled" | "blocked" - reason_code?: string -} - -interface ToolsResponse { - tools: ToolSupportItem[] -} - -interface ToolActionResponse { - status: string -} - -export interface WebSearchProviderOption { - id: string - label: string - configured: boolean - current: boolean - requires_auth: boolean -} - -export interface WebSearchProviderConfig { - enabled: boolean - max_results: number - base_url?: string - api_key?: string - api_keys?: string[] - model?: string - api_key_set?: boolean -} - -export interface WebSearchConfigResponse { - provider: string - current_service: string - prefer_native: boolean - proxy?: string - providers: WebSearchProviderOption[] - settings: Record -} - -async function request(path: string, options?: RequestInit): Promise { - const res = await launcherFetch(path, options) - if (!res.ok) { - let message = `API error: ${res.status} ${res.statusText}` - try { - const body = (await res.json()) as { - error?: string - errors?: string[] - } - if (Array.isArray(body.errors) && body.errors.length > 0) { - message = body.errors.join("; ") - } else if (typeof body.error === "string" && body.error.trim() !== "") { - message = body.error - } - } catch { - // ignore invalid body - } - throw new Error(message) - } - return res.json() as Promise -} - -export async function getTools(): Promise { - return request("/api/tools") -} - -export async function setToolEnabled( - name: string, - enabled: boolean, -): Promise { - return request( - `/api/tools/${encodeURIComponent(name)}/state`, - { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ enabled }), - }, - ) -} - -export async function getWebSearchConfig(): Promise { - return request("/api/tools/web-search-config") -} - -export async function updateWebSearchConfig( - payload: WebSearchConfigResponse, -): Promise { - return request("/api/tools/web-search-config", { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - }) -} diff --git a/web/frontend/src/app-providers.tsx b/web/frontend/src/app-providers.tsx deleted file mode 100644 index bfb5dfb3..00000000 --- a/web/frontend/src/app-providers.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import type { ReactNode } from "react" - -import { useHighlightTheme } from "./hooks/use-highlight-theme" - -interface AppProvidersProps { - children: ReactNode -} - -export function AppProviders({ children }: AppProvidersProps) { - useHighlightTheme() - - return <>{children} -} diff --git a/web/frontend/src/components/agent/hub/hub-page.tsx b/web/frontend/src/components/agent/hub/hub-page.tsx deleted file mode 100644 index 69f0be63..00000000 --- a/web/frontend/src/components/agent/hub/hub-page.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { useTranslation } from "react-i18next" - -import { PageHeader } from "@/components/page-header" - -import { ResultsPanel } from "./results-panel" -import { SearchPanel } from "./search-panel" -import { useHubMarketplace } from "./use-hub-marketplace" - -export function HubPage() { - const { t } = useTranslation() - const hub = useHubMarketplace() - - return ( -
- - -
-
-
- - - -
-
-
-
- ) -} diff --git a/web/frontend/src/components/agent/hub/market-skill-card.tsx b/web/frontend/src/components/agent/hub/market-skill-card.tsx deleted file mode 100644 index 99b00db9..00000000 --- a/web/frontend/src/components/agent/hub/market-skill-card.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import { - IconCheck, - IconFileInfo, - IconLoader2, - IconPlus, -} from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { - type SkillRegistrySearchResult, - type SkillSupportItem, -} from "@/api/skills" -import { Button } from "@/components/ui/button" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" - -export function MarketSkillCard({ - result, - canInstall, - installPending, - installedSkill, - onInstall, - onViewInstalled, -}: { - result: SkillRegistrySearchResult - canInstall: boolean - installPending: boolean - installedSkill: SkillSupportItem | null - onInstall: () => void - onViewInstalled: () => void -}) { - const { t } = useTranslation() - - const installDisabledReason = (() => { - if (installPending) - return t("pages.agent.skills.marketplace_installDisabled.installing") - if (result.installed) - return t("pages.agent.skills.marketplace_installDisabled.installed") - if (!canInstall) - return t("pages.agent.skills.marketplace_installDisabled.cannotInstall") - return t("pages.agent.skills.marketplace_install_action") - })() - const installDisabled = !canInstall || result.installed || installPending - - return ( - - {result.installed && ( -
- )} - -
-
-
- - {result.display_name || result.slug} - - - {result.registry_name} - - {result.installed ? ( - - {t("pages.agent.skills.marketplace_installed")} - - ) : null} -
-
- {result.slug} - {result.version ? ( - - {" "} - · v{result.version} - - ) : null} -
- - {result.summary} - - {result.url ? ( - - ) : null} -
-
- - - - - - - {installDisabledReason} - - {result.installed && installedSkill ? ( - - ) : null} -
-
-
- {result.installed_name ? ( - -
- {t("pages.agent.skills.marketplace_installed_hint", { - name: result.installed_name, - })} -
-
- ) : null} - - ) -} diff --git a/web/frontend/src/components/agent/hub/results-panel.tsx b/web/frontend/src/components/agent/hub/results-panel.tsx deleted file mode 100644 index e2a35195..00000000 --- a/web/frontend/src/components/agent/hub/results-panel.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { IconLoader2, IconSearch, IconX } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { - type SkillRegistrySearchResult, - type SkillSupportItem, -} from "@/api/skills" - -import { MarketSkillCard } from "./market-skill-card" - -export function ResultsPanel({ - canSearchMarketplace, - hasSubmittedQuery, - submittedQuery, - marketResults, - marketSearchError, - isMarketSearchInitialLoading, - isMarketSearchLoadingMore, - canInstallFromMarketplace, - getInstalledSkill, - isInstallPending, - onInstall, - onViewInstalled, -}: { - canSearchMarketplace: boolean - hasSubmittedQuery: boolean - submittedQuery: string - marketResults: SkillRegistrySearchResult[] - marketSearchError: unknown - isMarketSearchInitialLoading: boolean - isMarketSearchLoadingMore: boolean - canInstallFromMarketplace: boolean - getInstalledSkill: (installedName?: string) => SkillSupportItem | null - isInstallPending: (result: SkillRegistrySearchResult) => boolean - onInstall: (result: SkillRegistrySearchResult) => void - onViewInstalled: () => void -}) { - const { t } = useTranslation() - - return ( -
-
- {canSearchMarketplace && hasSubmittedQuery ? ( -
-
-
- {t("pages.agent.skills.marketplace_notice_title")} -
-
- {t("pages.agent.skills.marketplace_notice_body")} -
-
- - {isMarketSearchInitialLoading ? ( -
- - - {t("pages.agent.skills.marketplace_loading_results")} - -
- ) : marketSearchError ? ( -
-
- - - {marketSearchError instanceof Error - ? marketSearchError.message - : t("pages.agent.skills.marketplace_search_error")} - -
-
- ) : marketResults.length ? ( -
-
-

- {t("pages.agent.skills.marketplace_results_title", { - query: submittedQuery, - count: marketResults.length, - })} -

- - {t("pages.agent.skills.marketplace_results_hint")} - -
-
- {marketResults.map((result) => ( - onInstall(result)} - onViewInstalled={onViewInstalled} - /> - ))} -
- {isMarketSearchLoadingMore ? ( -
- - - {t("pages.agent.skills.marketplace_loading_more")} - -
- ) : null} -
- ) : ( -
- - - {t("pages.agent.skills.marketplace_empty_results", { - query: submittedQuery, - })} - -
- )} -
- ) : !canSearchMarketplace ? ( -
- - {t("pages.agent.skills.marketplace_unavailable")} - -
- ) : ( -
- - - {t("pages.agent.skills.marketplace_idle")} - -
- )} -
-
- ) -} diff --git a/web/frontend/src/components/agent/hub/search-panel.tsx b/web/frontend/src/components/agent/hub/search-panel.tsx deleted file mode 100644 index 875aaad6..00000000 --- a/web/frontend/src/components/agent/hub/search-panel.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { IconLoader2 } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" - -import type { UnavailableToolMessage } from "./tool-support" - -export function SearchPanel({ - marketQuery, - canSearchMarketplace, - isMarketSearchInitialLoading, - unavailableToolMessages, - onMarketQueryChange, - onSearchSubmit, -}: { - marketQuery: string - canSearchMarketplace: boolean - isMarketSearchInitialLoading: boolean - unavailableToolMessages: UnavailableToolMessage[] - onMarketQueryChange: (value: string) => void - onSearchSubmit: () => void -}) { - const { t } = useTranslation() - - return ( -
-
-

- {t("pages.agent.skills.marketplace_title", { - defaultValue: "Discover Skills", - })} -

-

- {t("pages.agent.skills.marketplace_description")} -

-
- -
{ - event.preventDefault() - onSearchSubmit() - }} - > -
- onMarketQueryChange(event.target.value)} - placeholder={t("pages.agent.skills.marketplace_search_placeholder")} - className="border-border/60 bg-background/50 hover:bg-background focus-visible:ring-primary/20 h-12 w-full rounded-full pr-20 pl-5 text-sm shadow-sm backdrop-blur-sm transition-all focus-visible:ring-2 md:min-w-[520px]" - disabled={!canSearchMarketplace} - /> - -
-
- - {unavailableToolMessages.length ? ( -
- {unavailableToolMessages.map((item) => ( -
-
{item.label}
-
{item.message}
-
- ))} -
- ) : null} -
- ) -} diff --git a/web/frontend/src/components/agent/hub/tool-support.ts b/web/frontend/src/components/agent/hub/tool-support.ts deleted file mode 100644 index 1553b156..00000000 --- a/web/frontend/src/components/agent/hub/tool-support.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { TFunction } from "i18next" - -import type { ToolSupportItem } from "@/api/tools" - -type MarketplaceTool = - | Pick - | undefined - -export interface UnavailableToolMessage { - key: "search" | "install" - label: string - message: string -} - -export function buildUnavailableToolMessages({ - searchTool, - installTool, - t, -}: { - searchTool: MarketplaceTool - installTool: MarketplaceTool - t: TFunction -}): UnavailableToolMessage[] { - const searchMessage = getToolSupportMessage(searchTool, t) - const installMessage = getToolSupportMessage(installTool, t) - - return [ - searchMessage - ? { - key: "search", - label: t("pages.agent.skills.marketplace_search_status"), - message: searchMessage, - } - : null, - installMessage - ? { - key: "install", - label: t("pages.agent.skills.marketplace_install_status"), - message: installMessage, - } - : null, - ].filter((item): item is UnavailableToolMessage => Boolean(item)) -} - -function getToolSupportMessage( - tool: MarketplaceTool, - t: TFunction, -): string | null { - if (!tool || tool.status === "enabled") { - return null - } - if (tool.reason_code) { - return `${t(`pages.agent.tools.reasons.${tool.reason_code}`)} ${t("pages.agent.skills.marketplace_status_enable_hint")}` - } - return t("pages.agent.skills.marketplace_status_disabled") -} diff --git a/web/frontend/src/components/agent/hub/use-hub-marketplace.ts b/web/frontend/src/components/agent/hub/use-hub-marketplace.ts deleted file mode 100644 index 2777aa37..00000000 --- a/web/frontend/src/components/agent/hub/use-hub-marketplace.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { - useInfiniteQuery, - useMutation, - useQuery, - useQueryClient, -} from "@tanstack/react-query" -import { useNavigate } from "@tanstack/react-router" -import { type UIEvent, useEffect, useRef, useState } from "react" -import { useTranslation } from "react-i18next" -import { toast } from "sonner" - -import { - type SkillRegistrySearchResult, - type SkillSearchResponse, - type SkillSupportItem, - getSkills, - installSkill, - searchSkills, -} from "@/api/skills" -import { getTools } from "@/api/tools" - -import { buildUnavailableToolMessages } from "./tool-support" - -const MARKET_SEARCH_LIMIT = 20 - -export function useHubMarketplace() { - const { t } = useTranslation() - const navigate = useNavigate() - const queryClient = useQueryClient() - const isLoadMoreLockedRef = useRef(false) - - const [marketQuery, setMarketQuery] = useState("") - const [submittedMarketQuery, setSubmittedMarketQuery] = useState("") - - const { data: skillsData } = useQuery({ - queryKey: ["skills"], - queryFn: getSkills, - }) - const { data: toolsData } = useQuery({ - queryKey: ["tools"], - queryFn: getTools, - }) - - const findSkillsTool = toolsData?.tools.find( - (tool) => tool.name === "find_skills", - ) - const installSkillTool = toolsData?.tools.find( - (tool) => tool.name === "install_skill", - ) - const canSearchMarketplace = findSkillsTool?.status === "enabled" - const canInstallFromMarketplace = installSkillTool?.status === "enabled" - const hasSubmittedQuery = submittedMarketQuery.trim() !== "" - const isMarketSearchActive = canSearchMarketplace && hasSubmittedQuery - - const { - data: marketSearchData, - isPending: isMarketSearchPending, - isFetching: isMarketSearchFetching, - isFetchingNextPage, - error: marketSearchError, - hasNextPage, - fetchNextPage, - refetch: refetchMarketSearch, - } = useInfiniteQuery({ - queryKey: ["skills-marketplace", submittedMarketQuery], - initialPageParam: 0, - queryFn: ({ pageParam }) => - searchSkills( - submittedMarketQuery, - MARKET_SEARCH_LIMIT, - Number(pageParam) || 0, - ), - getNextPageParam: (lastPage: SkillSearchResponse) => - lastPage.has_more ? (lastPage.next_offset ?? undefined) : undefined, - enabled: isMarketSearchActive, - staleTime: 5 * 60 * 1000, - refetchOnMount: false, - refetchOnWindowFocus: false, - }) - - const installMutation = useMutation({ - mutationFn: installSkill, - onSuccess: (response) => { - toast.success( - t("pages.agent.skills.install_success", { - name: response.skill?.name ?? response.slug, - }), - ) - void queryClient.invalidateQueries({ queryKey: ["skills"] }) - void queryClient.invalidateQueries({ queryKey: ["skills-marketplace"] }) - }, - onError: (err) => { - toast.error( - err instanceof Error - ? err.message - : t("pages.agent.skills.install_error"), - ) - }, - }) - - const allSkills = skillsData?.skills ?? [] - const workspaceSkillsByName = new Map( - allSkills - .filter((skill) => skill.source === "workspace") - .map((skill) => [skill.name, skill] as const), - ) - const marketResults = - marketSearchData?.pages.flatMap((page) => page.results) ?? [] - const hasMoreMarketResults = hasNextPage ?? false - const isMarketSearchInitialLoading = - isMarketSearchActive && - !marketSearchData && - (isMarketSearchPending || isMarketSearchFetching) - const isMarketSearchLoadingMore = - isMarketSearchActive && Boolean(marketSearchData) && isFetchingNextPage - const installPendingKey = - installMutation.isPending && installMutation.variables - ? `${installMutation.variables.registry}:${installMutation.variables.slug}` - : null - - const unavailableToolMessages = buildUnavailableToolMessages({ - searchTool: findSkillsTool, - installTool: installSkillTool, - t, - }) - - useEffect(() => { - if (!isFetchingNextPage) { - isLoadMoreLockedRef.current = false - } - }, [isFetchingNextPage]) - - const handleSearchSubmit = () => { - const nextQuery = marketQuery.trim() - if (!canSearchMarketplace || nextQuery === "") { - return - } - - isLoadMoreLockedRef.current = false - if (nextQuery === submittedMarketQuery) { - void refetchMarketSearch() - return - } - - setSubmittedMarketQuery(nextQuery) - } - - const handleInstall = (result: SkillRegistrySearchResult) => { - installMutation.mutate({ - slug: result.slug, - registry: result.registry_name, - version: result.version || undefined, - }) - } - - const handleViewInstalled = () => { - void navigate({ to: "/agent/skills" }) - } - - const handleScroll = (event: UIEvent) => { - if ( - !isMarketSearchActive || - !hasMoreMarketResults || - isFetchingNextPage || - isLoadMoreLockedRef.current - ) { - return - } - - const node = event.currentTarget - const remaining = node.scrollHeight - node.scrollTop - node.clientHeight - if (remaining > 240) { - return - } - - isLoadMoreLockedRef.current = true - void fetchNextPage() - } - - const getInstalledSkill = ( - installedName?: string, - ): SkillSupportItem | null => { - if (!installedName) { - return null - } - return workspaceSkillsByName.get(installedName) ?? null - } - - const isInstallPending = (result: SkillRegistrySearchResult) => - installPendingKey === `${result.registry_name}:${result.slug}` - - return { - marketQuery, - submittedMarketQuery, - canSearchMarketplace, - canInstallFromMarketplace, - marketResults, - marketSearchError, - unavailableToolMessages, - hasSubmittedQuery, - isMarketSearchInitialLoading, - isMarketSearchLoadingMore, - setMarketQuery, - handleSearchSubmit, - handleInstall, - handleViewInstalled, - handleScroll, - getInstalledSkill, - isInstallPending, - } -} diff --git a/web/frontend/src/components/agent/skills/delete-dialog.tsx b/web/frontend/src/components/agent/skills/delete-dialog.tsx deleted file mode 100644 index 1f4eba4c..00000000 --- a/web/frontend/src/components/agent/skills/delete-dialog.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { IconLoader2, IconTrash } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import type { SkillSupportItem } from "@/api/skills" -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog" - -interface DeleteDialogProps { - open: boolean - skillPendingDelete: SkillSupportItem | null - isDeletePending: boolean - onOpenChange: (open: boolean) => void - onConfirm: () => void -} - -export function DeleteDialog({ - open, - skillPendingDelete, - isDeletePending, - onOpenChange, - onConfirm, -}: DeleteDialogProps) { - const { t } = useTranslation() - - return ( - - - - - {t("pages.agent.skills.delete_title")} - - - {t("pages.agent.skills.delete_description", { - name: skillPendingDelete?.name, - })} - - - - - {t("common.cancel")} - - - {isDeletePending ? ( - - ) : ( - - )} - {t("pages.agent.skills.delete_confirm")} - - - - - ) -} diff --git a/web/frontend/src/components/agent/skills/detail-sheet.tsx b/web/frontend/src/components/agent/skills/detail-sheet.tsx deleted file mode 100644 index 9ec0c5a0..00000000 --- a/web/frontend/src/components/agent/skills/detail-sheet.tsx +++ /dev/null @@ -1,256 +0,0 @@ -import { - IconFileCode, - IconSparkles, - IconWorld, - IconX, -} from "@tabler/icons-react" -import type { ReactNode } from "react" -import { useTranslation } from "react-i18next" -import ReactMarkdown from "react-markdown" -import rehypeHighlight from "rehype-highlight" -import rehypeRaw from "rehype-raw" -import rehypeSanitize from "rehype-sanitize" -import remarkGfm from "remark-gfm" - -import type { SkillDetailResponse, SkillSupportItem } from "@/api/skills" -import { - MarkdownCodeBlock, - MessageCodeBlock, -} from "@/components/chat/message-code-block" -import { - Sheet, - SheetContent, - SheetDescription, - SheetHeader, - SheetTitle, -} from "@/components/ui/sheet" -import { Skeleton } from "@/components/ui/skeleton" -import { cn } from "@/lib/utils" - -import { OriginBadge } from "./origin-badge" -import { getOriginLabel, getSkillOriginKind } from "./origin-utils" -import type { SkillDetailView } from "./types" - -const DETAIL_VIEWS = [ - "preview", - "raw", - "meta", -] as const satisfies SkillDetailView[] - -interface DetailSheetProps { - open: boolean - selectedSkill: SkillSupportItem | null - selectedSkillDetail?: SkillDetailResponse - isLoading: boolean - error: unknown - detailView: SkillDetailView - onDetailViewChange: (view: SkillDetailView) => void - onOpenChange: (open: boolean) => void -} - -export function DetailSheet({ - open, - selectedSkill, - selectedSkillDetail, - isLoading, - error, - detailView, - onDetailViewChange, - onOpenChange, -}: DetailSheetProps) { - const { t } = useTranslation() - - const activeSkillDetail = selectedSkillDetail ?? selectedSkill - const activeSkillOrigin = activeSkillDetail - ? getSkillOriginKind(activeSkillDetail) - : null - const detailLineCount = selectedSkillDetail - ? selectedSkillDetail.content.split("\n").length - : 0 - const detailCharacterCount = selectedSkillDetail?.content.length ?? 0 - - return ( - - - -
-
- {activeSkillDetail?.origin_kind === "builtin" ? ( - - ) : activeSkillDetail?.registry_name ? ( - - ) : ( - - )} -
-
- - {activeSkillDetail?.name || - t("pages.agent.skills.viewer_title")} - - - {activeSkillDetail?.description || - t("pages.agent.skills.viewer_description")} - -
-
-
- -
- {isLoading ? ( -
- - - -
- ) : error ? ( -
- - - {t("pages.agent.skills.load_detail_error")} - -
- ) : selectedSkillDetail ? ( -
- {activeSkillOrigin === "third_party" ? ( -
-
- -
- -
- {selectedSkillDetail.registry_name ? ( - - ) : null} - {selectedSkillDetail.installed_version ? ( - - ) : null} - {selectedSkillDetail.registry_url ? ( - - {selectedSkillDetail.registry_url} - - } - mono - /> - ) : null} -
-
- ) : null} - -
- {DETAIL_VIEWS.map((view) => ( - - ))} -
- - {detailView === "preview" ? ( -
- - {selectedSkillDetail.content} - -
- ) : null} - - {detailView === "raw" ? ( - - ) : null} - - {detailView === "meta" ? ( -
- - - - -
- ) : null} -
- ) : null} -
-
-
- ) -} - -function MetadataItem({ - label, - value, - mono = false, -}: { - label: string - value: ReactNode - mono?: boolean -}) { - return ( -
-
- {label} -
-
- {value} -
-
- ) -} diff --git a/web/frontend/src/components/agent/skills/filter-bar.tsx b/web/frontend/src/components/agent/skills/filter-bar.tsx deleted file mode 100644 index 033609ea..00000000 --- a/web/frontend/src/components/agent/skills/filter-bar.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import { IconLayoutGrid, IconLayoutList, IconSearch } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { cn } from "@/lib/utils" - -import { getOriginLabel } from "./origin-utils" -import type { SkillLayoutMode, SkillSortOption } from "./types" - -interface FilterBarProps { - searchQuery: string - sourceFilter: string - availableOrigins: string[] - sortOrder: SkillSortOption - layoutMode: SkillLayoutMode - onSearchQueryChange: (value: string) => void - onSourceFilterChange: (value: string) => void - onSortOrderChange: (value: SkillSortOption) => void - onLayoutModeChange: (value: SkillLayoutMode) => void -} - -export function FilterBar({ - searchQuery, - sourceFilter, - availableOrigins, - sortOrder, - layoutMode, - onSearchQueryChange, - onSourceFilterChange, - onSortOrderChange, - onLayoutModeChange, -}: FilterBarProps) { - const { t } = useTranslation() - - return ( -
-
- - onSearchQueryChange(event.target.value)} - placeholder={t("pages.agent.skills.search_placeholder")} - className="hover:bg-background/50 focus-visible:bg-background h-9 border-transparent bg-transparent pl-9 shadow-none focus-visible:ring-1" - /> -
- -
- - - -
- - - -
- -
- - -
-
- ) -} diff --git a/web/frontend/src/components/agent/skills/import-dialog.tsx b/web/frontend/src/components/agent/skills/import-dialog.tsx deleted file mode 100644 index 21f4827e..00000000 --- a/web/frontend/src/components/agent/skills/import-dialog.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { IconLoader2, IconUpload, IconX } from "@tabler/icons-react" -import type { DragEvent } from "react" -import { useTranslation } from "react-i18next" - -import { Button } from "@/components/ui/button" -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog" -import { cn } from "@/lib/utils" - -interface ImportDialogProps { - open: boolean - isImportPending: boolean - isDragActive: boolean - onOpenChange: (open: boolean) => void - onImportClick: () => void - onDragEnter: (event: DragEvent) => void - onDragLeave: (event: DragEvent) => void - onDrop: (event: DragEvent) => void -} - -export function ImportDialog({ - open, - isImportPending, - isDragActive, - onOpenChange, - onImportClick, - onDragEnter, - onDragLeave, - onDrop, -}: ImportDialogProps) { - const { t } = useTranslation() - - return ( - { - if (!isImportPending) { - onOpenChange(nextOpen) - } - }} - > - -
- - - - - {t("pages.agent.skills.dropzone_title")} - - - {t("pages.agent.skills.dropzone_description")} - - -
- - -
-
- ) -} - -function SkillImportPanel({ - isDragActive, - isImportPending, - onDragEnter, - onDragLeave, - onDrop, - onImportClick, -}: { - isDragActive: boolean - isImportPending: boolean - onDragEnter: (event: DragEvent) => void - onDragLeave: (event: DragEvent) => void - onDrop: (event: DragEvent) => void - onImportClick: () => void -}) { - const { t } = useTranslation() - - return ( -
-
{ - if (!isImportPending) { - onImportClick() - } - }} - onDragEnter={onDragEnter} - onDragLeave={onDragLeave} - onDragOver={(event) => event.preventDefault()} - onDrop={onDrop} - > -
- -
-
-
- {isDragActive - ? t("pages.agent.skills.dropzone_active") - : t("pages.agent.skills.dropzone_label")} -
-

- {isDragActive - ? t("pages.agent.skills.dropzone_release") - : t("pages.agent.skills.import_constraints")} -

-
- -
-
- ) -} diff --git a/web/frontend/src/components/agent/skills/origin-badge.tsx b/web/frontend/src/components/agent/skills/origin-badge.tsx deleted file mode 100644 index 0b7bf439..00000000 --- a/web/frontend/src/components/agent/skills/origin-badge.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import { - IconFileCode, - IconFolder, - IconSparkles, - IconWorld, -} from "@tabler/icons-react" - -import { cn } from "@/lib/utils" - -import { getOriginBadgeClasses } from "./origin-utils" - -export function OriginBadge({ - origin, - label, -}: { - origin: string - label: string -}) { - return ( - - - {label} - - ) -} - -export function OriginIcon({ origin }: { origin: string }) { - if (origin === "builtin") { - return - } - if (origin === "third_party") { - return - } - if (origin === "manual") { - return - } - if (origin === "all") { - return - } - return -} diff --git a/web/frontend/src/components/agent/skills/origin-utils.ts b/web/frontend/src/components/agent/skills/origin-utils.ts deleted file mode 100644 index 6163f7bf..00000000 --- a/web/frontend/src/components/agent/skills/origin-utils.ts +++ /dev/null @@ -1,86 +0,0 @@ -import type { TFunction } from "i18next" - -import type { SkillSupportItem } from "@/api/skills" - -import type { SkillSortOption } from "./types" - -const KNOWN_ORIGIN_ORDER = ["builtin", "third_party", "manual"] - -export function compareSkills( - left: SkillSupportItem, - right: SkillSupportItem, - sortOrder: SkillSortOption, -) { - if (sortOrder === "source") { - const sourceDelta = compareOriginOrder( - getSkillOriginKind(left), - getSkillOriginKind(right), - ) - if (sourceDelta !== 0) return sourceDelta - return left.name.localeCompare(right.name) - } - - if (sortOrder === "name-desc") { - return right.name.localeCompare(left.name) - } - - return left.name.localeCompare(right.name) -} - -export function sortOrigins(origins: string[]) { - return [...origins].sort(compareOriginOrder) -} - -export function getSkillOriginKind(skill: SkillSupportItem) { - const origin = skill.origin_kind || skill.source - return origin === "global" ? "builtin" : origin -} - -export function getOriginLabel(origin: string, t: TFunction) { - if (origin === "builtin" || origin === "third_party" || origin === "manual") { - return t(`pages.agent.skills.origin.${origin}`) - } - if (origin === "all") { - return t("pages.agent.skills.origin.all") - } - return origin -} - -export function getOriginAccentClasses(origin: string) { - if (origin === "manual") { - return "bg-emerald-100 text-emerald-700" - } - if (origin === "third_party") { - return "bg-sky-100 text-sky-700" - } - if (origin === "builtin") { - return "bg-amber-100 text-amber-700" - } - return "bg-muted text-muted-foreground" -} - -export function getOriginBadgeClasses(origin: string) { - if (origin === "manual") { - return "bg-emerald-100 text-emerald-700" - } - if (origin === "third_party") { - return "bg-sky-100 text-sky-700" - } - if (origin === "builtin") { - return "bg-amber-100 text-amber-700" - } - return "bg-muted text-muted-foreground" -} - -function compareOriginOrder(left: string, right: string) { - const leftIndex = KNOWN_ORIGIN_ORDER.indexOf(left) - const rightIndex = KNOWN_ORIGIN_ORDER.indexOf(right) - - if (leftIndex !== -1 || rightIndex !== -1) { - if (leftIndex === -1) return 1 - if (rightIndex === -1) return -1 - return leftIndex - rightIndex - } - - return left.localeCompare(right) -} diff --git a/web/frontend/src/components/agent/skills/page-skeleton.tsx b/web/frontend/src/components/agent/skills/page-skeleton.tsx deleted file mode 100644 index 73df6fcd..00000000 --- a/web/frontend/src/components/agent/skills/page-skeleton.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { Skeleton } from "@/components/ui/skeleton" - -export function PageSkeleton() { - return ( -
-
- {[1, 2, 3, 4].map((index) => ( - - ))} -
-
-
- -
- -
- {[1, 2, 3, 4].map((index) => ( - - ))} -
-
-
- ) -} diff --git a/web/frontend/src/components/agent/skills/skill-card.tsx b/web/frontend/src/components/agent/skills/skill-card.tsx deleted file mode 100644 index 15bdc2c6..00000000 --- a/web/frontend/src/components/agent/skills/skill-card.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import { IconFileInfo, IconTrash } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import type { SkillSupportItem } from "@/api/skills" -import { Button } from "@/components/ui/button" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" - -interface SkillCardProps { - skill: SkillSupportItem - onView: () => void - onDelete: () => void -} - -export function SkillCard({ skill, onView, onDelete }: SkillCardProps) { - const { t } = useTranslation() - - return ( - -
- -
-
-
- - {skill.name} - - {skill.registry_name ? ( - - {skill.registry_name} - - ) : null} -
- - {skill.description || t("pages.agent.skills.no_description")} - -
-
- - {skill.source === "workspace" ? ( - - ) : null} -
-
-
- - {skill.registry_url ? ( - - {skill.registry_url} - - ) : null} - - - ) -} diff --git a/web/frontend/src/components/agent/skills/skills-list.tsx b/web/frontend/src/components/agent/skills/skills-list.tsx deleted file mode 100644 index 6a2bb92e..00000000 --- a/web/frontend/src/components/agent/skills/skills-list.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import { IconSearch } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import type { SkillSupportItem } from "@/api/skills" - -import { OriginBadge } from "./origin-badge" -import { getOriginLabel } from "./origin-utils" -import { SkillCard } from "./skill-card" -import type { SkillGroupSection, SkillLayoutMode } from "./types" - -interface SkillsListProps { - sortedSkills: SkillSupportItem[] - groupedSkills: SkillGroupSection[] - layoutMode: SkillLayoutMode - sourceFilter: string - hasActiveFilters: boolean - onViewSkill: (skill: SkillSupportItem) => void - onDeleteSkill: (skill: SkillSupportItem) => void -} - -export function SkillsList({ - sortedSkills, - groupedSkills, - layoutMode, - sourceFilter, - hasActiveFilters, - onViewSkill, - onDeleteSkill, -}: SkillsListProps) { - const { t } = useTranslation() - - if (!sortedSkills.length) { - return ( -
-
- -
-

- {hasActiveFilters - ? t("pages.agent.skills.no_results") - : t("pages.agent.skills.empty")} -

-
- ) - } - - if (layoutMode === "grouped" && sourceFilter === "all") { - return ( -
- {groupedSkills.map((section) => ( -
-
- -
-
- {section.skills.map((skill) => ( - onViewSkill(skill)} - onDelete={() => onDeleteSkill(skill)} - /> - ))} -
-
- ))} -
- ) - } - - return ( -
- {sortedSkills.map((skill) => ( - onViewSkill(skill)} - onDelete={() => onDeleteSkill(skill)} - /> - ))} -
- ) -} diff --git a/web/frontend/src/components/agent/skills/skills-page.tsx b/web/frontend/src/components/agent/skills/skills-page.tsx deleted file mode 100644 index d9b5a7cd..00000000 --- a/web/frontend/src/components/agent/skills/skills-page.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { IconLoader2, IconPlus } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { PageHeader } from "@/components/page-header" -import { Button } from "@/components/ui/button" - -import { DeleteDialog } from "./delete-dialog" -import { DetailSheet } from "./detail-sheet" -import { FilterBar } from "./filter-bar" -import { ImportDialog } from "./import-dialog" -import { PageSkeleton } from "./page-skeleton" -import { SkillsList } from "./skills-list" -import { Stats } from "./stats" -import { useSkillsPage } from "./use-skills-page" - -export function SkillsPage() { - const { t } = useTranslation() - const { - searchQuery, - sourceFilter, - sortOrder, - layoutMode, - detailView, - isDragActive, - isImportDialogOpen, - selectedSkill, - skillPendingDelete, - availableOrigins, - groupedSkills, - stats, - sortedSkills, - hasActiveFilters, - importInputRef, - selectedSkillDetail, - skillsError, - skillDetailError, - isLoading, - isSkillDetailLoading, - isImportPending, - isDeletePending, - setSearchQuery, - setSourceFilter, - setSortOrder, - setLayoutMode, - setDetailView, - openImportDialog, - handleViewSkill, - handleRequestDelete, - handleConfirmDelete, - handleImportClick, - handleImportFileChange, - handleDropZoneDragEnter, - handleDropZoneDragLeave, - handleDropZoneDrop, - handleDetailSheetOpenChange, - handleImportDialogOpenChange, - handleDeleteDialogOpenChange, - } = useSkillsPage() - - return ( -
- - - - - } - /> - -
-
- {isLoading ? ( - - ) : skillsError ? ( -
- {t("pages.agent.load_error")} -
- ) : ( -
- - -
- -
- - -
- )} -
-
- - - - - - -
- ) -} diff --git a/web/frontend/src/components/agent/skills/stats.tsx b/web/frontend/src/components/agent/skills/stats.tsx deleted file mode 100644 index c718fc3b..00000000 --- a/web/frontend/src/components/agent/skills/stats.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Card, CardContent } from "@/components/ui/card" -import { cn } from "@/lib/utils" - -import { OriginIcon } from "./origin-badge" -import { getOriginAccentClasses } from "./origin-utils" -import type { SkillStatItem } from "./types" - -export function Stats({ stats }: { stats: SkillStatItem[] }) { - return ( -
- {stats.map((stat) => ( - - -
-
- {stat.label} -
-
- {stat.count} -
-
-
- -
-
-
- ))} -
- ) -} diff --git a/web/frontend/src/components/agent/skills/types.ts b/web/frontend/src/components/agent/skills/types.ts deleted file mode 100644 index 44509854..00000000 --- a/web/frontend/src/components/agent/skills/types.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { SkillSupportItem } from "@/api/skills" - -export type SkillSortOption = "name-asc" | "name-desc" | "source" -export type SkillLayoutMode = "grouped" | "grid" -export type SkillDetailView = "preview" | "raw" | "meta" - -export interface SkillGroupSection { - origin: string - skills: SkillSupportItem[] -} - -export interface SkillStatItem { - key: string - origin: string - label: string - count: number -} diff --git a/web/frontend/src/components/agent/skills/use-skills-page.ts b/web/frontend/src/components/agent/skills/use-skills-page.ts deleted file mode 100644 index 7cf4a01a..00000000 --- a/web/frontend/src/components/agent/skills/use-skills-page.ts +++ /dev/null @@ -1,339 +0,0 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" -import { - type ChangeEvent, - type DragEvent, - startTransition, - useDeferredValue, - useMemo, - useRef, - useState, -} from "react" -import { useTranslation } from "react-i18next" -import { toast } from "sonner" - -import { - type SkillSupportItem, - deleteSkill, - getSkill, - getSkills, - importSkill, -} from "@/api/skills" - -import { - compareSkills, - getOriginLabel, - getSkillOriginKind, - sortOrigins, -} from "./origin-utils" -import type { - SkillDetailView, - SkillGroupSection, - SkillLayoutMode, - SkillSortOption, - SkillStatItem, -} from "./types" - -const MAX_IMPORT_FILE_SIZE = 1 << 20 - -export function useSkillsPage() { - const { t } = useTranslation() - const queryClient = useQueryClient() - const importInputRef = useRef(null) - const dragDepthRef = useRef(0) - - const [searchQuery, setSearchQuery] = useState("") - const deferredSearchQuery = useDeferredValue(searchQuery) - const [sourceFilter, setSourceFilter] = useState("all") - const [sortOrder, setSortOrder] = useState("name-asc") - const [layoutMode, setLayoutMode] = useState("grouped") - const [detailView, setDetailView] = useState("preview") - const [isDragActive, setIsDragActive] = useState(false) - const [isImportDialogOpen, setIsImportDialogOpen] = useState(false) - const [selectedSkill, setSelectedSkill] = useState( - null, - ) - const [skillPendingDelete, setSkillPendingDelete] = - useState(null) - - const skillsQuery = useQuery({ - queryKey: ["skills"], - queryFn: getSkills, - }) - - const skillDetailQuery = useQuery({ - queryKey: ["skills", selectedSkill?.name], - queryFn: () => getSkill(selectedSkill!.name), - enabled: selectedSkill !== null, - }) - - const importMutation = useMutation({ - mutationFn: async (file: File) => importSkill(file), - onSuccess: (importedSkill) => { - toast.success(t("pages.agent.skills.import_success")) - startTransition(() => { - setIsImportDialogOpen(false) - setDetailView("preview") - if (importedSkill.name) { - setSelectedSkill({ - name: importedSkill.name, - path: importedSkill.path ?? "", - source: importedSkill.source ?? "workspace", - description: importedSkill.description ?? "", - origin_kind: importedSkill.origin_kind ?? "manual", - registry_name: importedSkill.registry_name, - registry_url: importedSkill.registry_url, - installed_version: importedSkill.installed_version, - installed_at: importedSkill.installed_at, - }) - } - }) - void queryClient.invalidateQueries({ queryKey: ["skills"] }) - }, - onError: (err) => { - toast.error( - err instanceof Error - ? err.message - : t("pages.agent.skills.import_error"), - ) - }, - }) - - const deleteMutation = useMutation({ - mutationFn: async (name: string) => deleteSkill(name), - onSuccess: (_, deletedName) => { - toast.success(t("pages.agent.skills.delete_success")) - setSkillPendingDelete(null) - if ( - selectedSkill?.name === deletedName && - selectedSkill.source === "workspace" - ) { - setSelectedSkill(null) - } - void queryClient.invalidateQueries({ queryKey: ["skills"] }) - }, - onError: (err) => { - toast.error( - err instanceof Error - ? err.message - : t("pages.agent.skills.delete_error"), - ) - }, - }) - - const allSkills = useMemo( - () => skillsQuery.data?.skills ?? [], - [skillsQuery.data?.skills], - ) - const normalizedSearchQuery = deferredSearchQuery.trim().toLowerCase() - - const availableOrigins = useMemo( - () => - sortOrigins([ - ...new Set(allSkills.map((skill) => getSkillOriginKind(skill))), - ]), - [allSkills], - ) - - const filteredSkills = useMemo(() => { - return allSkills.filter((skill) => { - const matchesSource = - sourceFilter === "all" - ? true - : getSkillOriginKind(skill) === sourceFilter - if (!matchesSource) return false - if (normalizedSearchQuery === "") return true - - const searchTarget = - `${skill.name} ${skill.description} ${skill.registry_name ?? ""}`.toLowerCase() - return searchTarget.includes(normalizedSearchQuery) - }) - }, [allSkills, normalizedSearchQuery, sourceFilter]) - - const sortedSkills = useMemo( - () => - [...filteredSkills].sort((left, right) => - compareSkills(left, right, sortOrder), - ), - [filteredSkills, sortOrder], - ) - - const groupedSkills = useMemo( - () => - availableOrigins - .map((origin) => ({ - origin, - skills: sortedSkills.filter( - (skill) => getSkillOriginKind(skill) === origin, - ), - })) - .filter((section) => section.skills.length > 0), - [availableOrigins, sortedSkills], - ) - - const stats = useMemo( - () => [ - { - key: "all", - origin: "all", - label: t("pages.agent.skills.summary.total"), - count: allSkills.length, - }, - ...availableOrigins.map((origin) => ({ - key: origin, - origin, - label: getOriginLabel(origin, t), - count: allSkills.filter((skill) => getSkillOriginKind(skill) === origin) - .length, - })), - ], - [allSkills, availableOrigins, t], - ) - - const hasActiveFilters = - normalizedSearchQuery !== "" || sourceFilter !== "all" - - const handleImportClick = () => { - importInputRef.current?.click() - } - - const handleViewSkill = (skill: SkillSupportItem) => { - setDetailView("preview") - setSelectedSkill(skill) - } - - const handleRequestDelete = (skill: SkillSupportItem) => { - setSkillPendingDelete(skill) - } - - const handleConfirmDelete = () => { - if (skillPendingDelete) { - deleteMutation.mutate(skillPendingDelete.name) - } - } - - const handleDetailSheetOpenChange = (open: boolean) => { - if (!open) { - setSelectedSkill(null) - } - } - - const handleImportDialogOpenChange = (open: boolean) => { - if (!importMutation.isPending) { - setIsImportDialogOpen(open) - } - } - - const handleDeleteDialogOpenChange = (open: boolean) => { - if (!open) { - setSkillPendingDelete(null) - } - } - - const validateImportFile = (file: File) => { - const fileName = file.name.toLowerCase() - const isMarkdownFile = - fileName.endsWith(".md") || - file.type === "text/markdown" || - file.type === "text/plain" || - file.type === "" - const isZipFile = - fileName.endsWith(".zip") || - file.type === "application/zip" || - file.type === "application/x-zip-compressed" - - if (!isMarkdownFile && !isZipFile) { - return t("pages.agent.skills.import_invalid_type") - } - - if (file.size > MAX_IMPORT_FILE_SIZE) { - return t("pages.agent.skills.import_invalid_size") - } - - return null - } - - const handleImportFile = (file: File) => { - const validationMessage = validateImportFile(file) - if (validationMessage) { - toast.error(validationMessage) - return - } - importMutation.mutate(file) - } - - const handleImportFileChange = (event: ChangeEvent) => { - const file = event.target.files?.[0] - if (!file) return - handleImportFile(file) - event.target.value = "" - } - - const resetDragState = () => { - dragDepthRef.current = 0 - setIsDragActive(false) - } - - const handleDropZoneDragEnter = (event: DragEvent) => { - event.preventDefault() - dragDepthRef.current += 1 - setIsDragActive(true) - } - - const handleDropZoneDragLeave = (event: DragEvent) => { - event.preventDefault() - dragDepthRef.current = Math.max(0, dragDepthRef.current - 1) - if (dragDepthRef.current === 0) { - setIsDragActive(false) - } - } - - const handleDropZoneDrop = (event: DragEvent) => { - event.preventDefault() - const file = event.dataTransfer.files?.[0] - resetDragState() - if (!file) return - handleImportFile(file) - } - - return { - searchQuery, - sourceFilter, - sortOrder, - layoutMode, - detailView, - isDragActive, - isImportDialogOpen, - selectedSkill, - skillPendingDelete, - availableOrigins, - groupedSkills, - stats, - sortedSkills, - hasActiveFilters, - importInputRef, - selectedSkillDetail: skillDetailQuery.data, - skillsError: skillsQuery.error, - skillDetailError: skillDetailQuery.error, - isLoading: skillsQuery.isLoading, - isSkillDetailLoading: skillDetailQuery.isLoading, - isImportPending: importMutation.isPending, - isDeletePending: deleteMutation.isPending, - setSearchQuery, - setSourceFilter, - setSortOrder, - setLayoutMode, - setDetailView, - openImportDialog: () => setIsImportDialogOpen(true), - handleViewSkill, - handleRequestDelete, - handleConfirmDelete, - handleImportClick, - handleImportFileChange, - handleDropZoneDragEnter, - handleDropZoneDragLeave, - handleDropZoneDrop, - handleDetailSheetOpenChange, - handleImportDialogOpenChange, - handleDeleteDialogOpenChange, - } -} diff --git a/web/frontend/src/components/agent/tools/tool-library-tab.tsx b/web/frontend/src/components/agent/tools/tool-library-tab.tsx deleted file mode 100644 index 6bbfeb09..00000000 --- a/web/frontend/src/components/agent/tools/tool-library-tab.tsx +++ /dev/null @@ -1,270 +0,0 @@ -import { IconSearch, IconSettings } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import type { ToolSupportItem } from "@/api/tools" -import { Button } from "@/components/ui/button" -import { Card, CardContent } from "@/components/ui/card" -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { Skeleton } from "@/components/ui/skeleton" -import { Switch } from "@/components/ui/switch" -import { cn } from "@/lib/utils" - -import { ToolStatusBadge } from "./tool-status-badge" -import type { GroupedTools, ToolStatusFilter } from "./types" - -interface ToolLibraryTabProps { - allTools: ToolSupportItem[] - groupedTools: GroupedTools - totalFilteredCount: number - searchQuery: string - statusFilter: ToolStatusFilter - isLoading: boolean - hasError: boolean - pendingToolName: string | null - onSearchQueryChange: (value: string) => void - onStatusFilterChange: (value: ToolStatusFilter) => void - onOpenWebSearchSettings: () => void - onToggleTool: (name: string, enabled: boolean) => void -} - -export function ToolLibraryTab({ - allTools, - groupedTools, - totalFilteredCount, - searchQuery, - statusFilter, - isLoading, - hasError, - pendingToolName, - onSearchQueryChange, - onStatusFilterChange, - onOpenWebSearchSettings, - onToggleTool, -}: ToolLibraryTabProps) { - const { t } = useTranslation() - - return ( -
-
-
-

- {t("pages.agent.tools.library_title", "Tool Library")} -

-

- {t( - "pages.agent.tools.library_description", - "Browse and manage the toolset available to your AI agents.", - )} -

-
- -
-
- - onSearchQueryChange(event.target.value)} - /> -
- - -
-
- - {hasError ? ( -
-

- {t("pages.agent.load_error", "Failed to load tools")} -

-
- ) : isLoading ? ( - - ) : totalFilteredCount === 0 ? ( - - ) : ( -
- {groupedTools.map(([category, items]) => ( -
-
-

- {t(`pages.agent.tools.categories.${category}`, category)} -

-
-
- {items.map((tool) => ( - - ))} -
-
- ))} -
- )} -
- ) -} - -function ToolCard({ - tool, - isPending, - onOpenWebSearchSettings, - onToggleTool, -}: { - tool: ToolSupportItem - isPending: boolean - onOpenWebSearchSettings: () => void - onToggleTool: (name: string, enabled: boolean) => void -}) { - const { t } = useTranslation() - const reasonText = tool.reason_code - ? t(`pages.agent.tools.reasons.${tool.reason_code}`) - : "" - const isEnabled = tool.status === "enabled" - const isToggledOn = tool.status !== "disabled" - const isDisabled = tool.status === "disabled" - const isBlocked = tool.status === "blocked" - const isWebSearchTool = tool.name === "web_search" - - return ( - - -
-
-

- {tool.name} -

- -
-
- {isWebSearchTool && ( - - )} - onToggleTool(tool.name, checked)} - className={cn( - "shrink-0", - isEnabled && "shadow-xs ring-1 ring-emerald-500/20", - )} - /> -
-
- -

- {tool.description} -

- - {reasonText && ( -
-
- {reasonText} -
-
- )} -
-
- ) -} - -function LibraryLoadingState() { - return ( -
- {[1, 2].map((groupIndex) => ( -
- -
- {[1, 2].map((itemIndex) => ( - - ))} -
-
- ))} -
- ) -} - -function LibraryEmptyState({ allToolsCount }: { allToolsCount: number }) { - const { t } = useTranslation() - - return ( -
-
- -
-

- {allToolsCount === 0 - ? t("pages.agent.tools.empty", "No tools found") - : t("pages.agent.tools.no_results", "No matching tools")} -

- {allToolsCount !== 0 && ( -

- Try adjusting your search criteria or status filters. -

- )} -
- ) -} diff --git a/web/frontend/src/components/agent/tools/tool-status-badge.tsx b/web/frontend/src/components/agent/tools/tool-status-badge.tsx deleted file mode 100644 index 017d167b..00000000 --- a/web/frontend/src/components/agent/tools/tool-status-badge.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ToolSupportItem } from "@/api/tools" -import { cn } from "@/lib/utils" - -interface ToolStatusBadgeProps { - status: ToolSupportItem["status"] -} - -export function ToolStatusBadge({ status }: ToolStatusBadgeProps) { - const { t } = useTranslation() - - return ( - - {t(`pages.agent.tools.status.${status}`, status)} - - ) -} diff --git a/web/frontend/src/components/agent/tools/tools-page.tsx b/web/frontend/src/components/agent/tools/tools-page.tsx deleted file mode 100644 index c221f911..00000000 --- a/web/frontend/src/components/agent/tools/tools-page.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { useLayoutEffect, useRef } from "react" -import { useTranslation } from "react-i18next" - -import { PageHeader } from "@/components/page-header" - -import { ToolLibraryTab } from "./tool-library-tab" -import { ToolsTabs } from "./tools-tabs" -import { useToolsPage } from "./use-tools-page" -import { WebSearchTab } from "./web-search-tab" - -export function ToolsPage() { - const { t } = useTranslation() - const scrollContainerRef = useRef(null) - const { - activeTab, - expandedProvider, - groupedTools, - pendingToolName, - providerLabelMap, - searchQuery, - statusFilter, - tools, - totalFilteredCount, - webSearchDraft, - hasToolsError, - hasWebSearchError, - isToolsLoading, - isWebSearchLoading, - isWebSearchSaving, - isWebSearchDirty, - setActiveTab, - setSearchQuery, - setStatusFilter, - saveWebSearchConfig, - toggleExpandedProvider, - toggleTool, - updateWebSearchDraft, - } = useToolsPage() - - useLayoutEffect(() => { - scrollContainerRef.current?.scrollTo({ top: 0 }) - }, [activeTab]) - - return ( -
- - - -
-
- {activeTab === "library" ? ( - setActiveTab("web-search")} - onToggleTool={toggleTool} - /> - ) : ( - - )} -
-
-
- ) -} diff --git a/web/frontend/src/components/agent/tools/tools-tabs.tsx b/web/frontend/src/components/agent/tools/tools-tabs.tsx deleted file mode 100644 index a5898ccd..00000000 --- a/web/frontend/src/components/agent/tools/tools-tabs.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { useTranslation } from "react-i18next" - -import { cn } from "@/lib/utils" - -import type { ToolsPageTab } from "./types" - -interface ToolsTabsProps { - activeTab: ToolsPageTab - onChange: (tab: ToolsPageTab) => void -} - -const tabs: Array<{ - defaultLabel: string - key: ToolsPageTab - translationKey: string -}> = [ - { - key: "library", - translationKey: "pages.agent.tools.library_title", - defaultLabel: "Tool Library", - }, - { - key: "web-search", - translationKey: "pages.agent.tools.web_search.title", - defaultLabel: "Web Search", - }, -] - -export function ToolsTabs({ activeTab, onChange }: ToolsTabsProps) { - const { t } = useTranslation() - - return ( -
-
- {tabs.map((tab) => ( - - ))} -
-
- ) -} diff --git a/web/frontend/src/components/agent/tools/types.ts b/web/frontend/src/components/agent/tools/types.ts deleted file mode 100644 index 1aec9093..00000000 --- a/web/frontend/src/components/agent/tools/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { ToolSupportItem, WebSearchConfigResponse } from "@/api/tools" - -export type ToolsPageTab = "library" | "web-search" -export type ToolStatusFilter = "all" | ToolSupportItem["status"] -export type GroupedTools = Array<[string, ToolSupportItem[]]> - -export type WebSearchDraftUpdater = ( - updater: (current: WebSearchConfigResponse) => WebSearchConfigResponse, -) => void diff --git a/web/frontend/src/components/agent/tools/use-tools-page.ts b/web/frontend/src/components/agent/tools/use-tools-page.ts deleted file mode 100644 index ecc433b0..00000000 --- a/web/frontend/src/components/agent/tools/use-tools-page.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" -import { useDeferredValue, useMemo, useState } from "react" -import { useTranslation } from "react-i18next" -import { toast } from "sonner" - -import { - type WebSearchConfigResponse, - getTools, - getWebSearchConfig, - setToolEnabled, - updateWebSearchConfig, -} from "@/api/tools" -import { showSaveSuccessOrRestartToast } from "@/lib/restart-required" -import { refreshGatewayState } from "@/store/gateway" - -import type { GroupedTools, ToolStatusFilter, ToolsPageTab } from "./types" - -export function useToolsPage() { - const { t } = useTranslation() - const queryClient = useQueryClient() - - const [activeTab, setActiveTab] = useState("library") - const [searchQuery, setSearchQuery] = useState("") - const deferredSearchQuery = useDeferredValue(searchQuery) - const [statusFilter, setStatusFilter] = useState("all") - const [expandedProvider, setExpandedProvider] = useState(null) - const [webSearchDraftOverride, setWebSearchDraftOverride] = - useState(null) - - const toolsQuery = useQuery({ - queryKey: ["tools"], - queryFn: getTools, - }) - const webSearchQuery = useQuery({ - queryKey: ["tools", "web-search-config"], - queryFn: getWebSearchConfig, - }) - - const tools = useMemo( - () => toolsQuery.data?.tools ?? [], - [toolsQuery.data?.tools], - ) - const normalizedSearchQuery = deferredSearchQuery.trim().toLowerCase() - const webSearchDraft = webSearchDraftOverride ?? webSearchQuery.data ?? null - const isWebSearchDirty = useMemo(() => { - if (!webSearchDraft || !webSearchQuery.data) { - return false - } - return ( - JSON.stringify(webSearchDraft) !== JSON.stringify(webSearchQuery.data) - ) - }, [webSearchDraft, webSearchQuery.data]) - - const toggleToolMutation = useMutation({ - mutationFn: async ({ name, enabled }: { name: string; enabled: boolean }) => - setToolEnabled(name, enabled), - onSuccess: async (_, variables) => { - const gateway = await refreshGatewayState({ force: true }) - showSaveSuccessOrRestartToast( - t, - variables.enabled - ? t("pages.agent.tools.enable_success", "Tool enabled successfully") - : t( - "pages.agent.tools.disable_success", - "Tool disabled successfully", - ), - t("navigation.tools", "Tools"), - gateway?.restartRequired === true, - ) - void queryClient.invalidateQueries({ queryKey: ["tools"] }) - }, - onError: (error) => { - toast.error( - error instanceof Error - ? error.message - : t("pages.agent.tools.toggle_error", "Failed to toggle tool"), - ) - }, - }) - - const saveWebSearchMutation = useMutation({ - mutationFn: updateWebSearchConfig, - onSuccess: async (updatedConfig) => { - queryClient.setQueryData(["tools", "web-search-config"], updatedConfig) - setWebSearchDraftOverride(null) - const gateway = await refreshGatewayState({ force: true }) - showSaveSuccessOrRestartToast( - t, - t( - "pages.agent.tools.web_search.save_success", - "Settings saved successfully", - ), - t("pages.agent.tools.web_search.title", "Web Search Configuration"), - gateway?.restartRequired === true, - ) - void queryClient.invalidateQueries({ - queryKey: ["tools", "web-search-config"], - }) - void queryClient.invalidateQueries({ queryKey: ["tools"] }) - }, - onError: (error) => { - toast.error( - error instanceof Error - ? error.message - : t( - "pages.agent.tools.web_search.save_error", - "Failed to save settings", - ), - ) - }, - }) - - const groupedTools = useMemo<{ - groupedTools: GroupedTools - totalFilteredCount: number - }>(() => { - let totalFilteredCount = 0 - const grouped = new Map() - - for (const tool of tools) { - if (statusFilter !== "all" && tool.status !== statusFilter) { - continue - } - - if (normalizedSearchQuery) { - const matchesName = tool.name - .toLowerCase() - .includes(normalizedSearchQuery) - const matchesDescription = (tool.description || "") - .toLowerCase() - .includes(normalizedSearchQuery) - - if (!matchesName && !matchesDescription) { - continue - } - } - - totalFilteredCount += 1 - const items = grouped.get(tool.category) ?? [] - items.push(tool) - grouped.set(tool.category, items) - } - - return { - groupedTools: Array.from(grouped.entries()), - totalFilteredCount, - } - }, [normalizedSearchQuery, statusFilter, tools]) - - const providerLabelMap = useMemo(() => { - const providers = webSearchDraft?.providers ?? [] - return new Map(providers.map((provider) => [provider.id, provider.label])) - }, [webSearchDraft]) - - const pendingToolName = toggleToolMutation.isPending - ? (toggleToolMutation.variables?.name ?? null) - : null - - const updateWebSearchDraft = ( - updater: (current: WebSearchConfigResponse) => WebSearchConfigResponse, - ) => { - setWebSearchDraftOverride((current) => { - const draft = current ?? webSearchQuery.data - return draft ? updater(draft) : current - }) - } - - const toggleTool = (name: string, enabled: boolean) => { - toggleToolMutation.mutate({ name, enabled }) - } - - const saveWebSearchConfig = () => { - if (webSearchDraft) { - saveWebSearchMutation.mutate(webSearchDraft) - } - } - - const toggleExpandedProvider = (providerId: string) => { - setExpandedProvider((current) => - current === providerId ? null : providerId, - ) - } - - return { - activeTab, - expandedProvider, - groupedTools: groupedTools.groupedTools, - pendingToolName, - providerLabelMap, - searchQuery, - statusFilter, - tools, - totalFilteredCount: groupedTools.totalFilteredCount, - webSearchDraft, - hasToolsError: toolsQuery.error != null, - hasWebSearchError: webSearchQuery.error != null, - isToolsLoading: toolsQuery.isLoading, - isWebSearchLoading: webSearchQuery.isLoading, - isWebSearchSaving: saveWebSearchMutation.isPending, - isWebSearchDirty, - setActiveTab, - setSearchQuery, - setStatusFilter, - saveWebSearchConfig, - toggleExpandedProvider, - toggleTool, - updateWebSearchDraft, - } -} diff --git a/web/frontend/src/components/agent/tools/web-search-general-settings.tsx b/web/frontend/src/components/agent/tools/web-search-general-settings.tsx deleted file mode 100644 index e8c81408..00000000 --- a/web/frontend/src/components/agent/tools/web-search-general-settings.tsx +++ /dev/null @@ -1,136 +0,0 @@ -import type { ReactNode } from "react" -import { useTranslation } from "react-i18next" - -import type { WebSearchConfigResponse } from "@/api/tools" -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { Switch } from "@/components/ui/switch" - -import type { WebSearchDraftUpdater } from "./types" - -interface WebSearchGeneralSettingsProps { - draft: WebSearchConfigResponse - onUpdateDraft: WebSearchDraftUpdater -} - -export function WebSearchGeneralSettings({ - draft, - onUpdateDraft, -}: WebSearchGeneralSettingsProps) { - const { t } = useTranslation() - - return ( -
-

- {t("pages.agent.tools.web_search.global_settings", "General")} -

- -
- - - - - - - onUpdateDraft((current) => ({ - ...current, - proxy: event.target.value, - })) - } - placeholder="http://127.0.0.1:7890" - /> - - - - - onUpdateDraft((current) => ({ - ...current, - prefer_native: checked, - })) - } - className="data-[state=checked]:shadow-xs" - /> - -
-
- ) -} - -function SettingRow({ - label, - description, - children, -}: { - label: string - description: string - children: ReactNode -}) { - return ( -
-
- -

- {description} -

-
- {children} -
- ) -} diff --git a/web/frontend/src/components/agent/tools/web-search-provider-settings.tsx b/web/frontend/src/components/agent/tools/web-search-provider-settings.tsx deleted file mode 100644 index 23bad4ad..00000000 --- a/web/frontend/src/components/agent/tools/web-search-provider-settings.tsx +++ /dev/null @@ -1,279 +0,0 @@ -import { IconChevronDown } from "@tabler/icons-react" -import type { ReactNode } from "react" -import { useTranslation } from "react-i18next" - -import type { WebSearchProviderConfig } from "@/api/tools" -import { maskedSecretPlaceholder } from "@/components/secret-placeholder" -import { KeyInput } from "@/components/shared-form" -import { Input } from "@/components/ui/input" -import { Switch } from "@/components/ui/switch" -import { cn } from "@/lib/utils" - -import type { WebSearchDraftUpdater } from "./types" - -interface WebSearchProviderSettingsProps { - providerLabelMap: Map - settings: Record - expandedProvider: string | null - onToggleProviderExpand: (providerId: string) => void - onUpdateDraft: WebSearchDraftUpdater -} - -const baseUrlProviders = new Set([ - "tavily", - "kagi", - "searxng", - "glm_search", - "baidu_search", -]) - -const apiKeyProviders = new Set([ - "brave", - "tavily", - "kagi", - "perplexity", - "gemini", - "glm_search", - "baidu_search", -]) - -const modelProviders = new Set(["gemini"]) - -export function WebSearchProviderSettings({ - providerLabelMap, - settings, - expandedProvider, - onToggleProviderExpand, - onUpdateDraft, -}: WebSearchProviderSettingsProps) { - const { t } = useTranslation() - - return ( -
-

- {t("pages.agent.tools.web_search.providers_config", "Integrations")} -

- -
- {Object.entries(settings).map(([providerId, providerSettings]) => ( - - ))} -
-
- ) -} - -function ProviderCard({ - providerId, - providerLabel, - settings, - isExpanded, - onToggleExpand, - onUpdateDraft, -}: { - providerId: string - providerLabel: string - settings: WebSearchProviderConfig - isExpanded: boolean - onToggleExpand: (providerId: string) => void - onUpdateDraft: WebSearchDraftUpdater -}) { - const { t } = useTranslation() - const apiKeyPlaceholder = maskedSecretPlaceholder( - settings.api_key_set ? `${providerId}-configured` : "", - t("pages.agent.tools.web_search.api_key_placeholder", "Enter API key..."), - ) - - const updateSettings = ( - updater: (current: WebSearchProviderConfig) => WebSearchProviderConfig, - ) => { - onUpdateDraft((current) => { - const nextSettings = current.settings[providerId] ?? settings - return { - ...current, - settings: { - ...current.settings, - [providerId]: updater(nextSettings), - }, - } - }) - } - - return ( -
-
- - -
event.stopPropagation()} - > - - updateSettings((current) => ({ - ...current, - enabled: checked, - })) - } - /> -
-
- - {isExpanded && ( -
-
- - - updateSettings((current) => ({ - ...current, - max_results: Number(event.target.value) || 0, - })) - } - className="bg-muted/40 hover:bg-muted/60 focus:bg-background focus:ring-primary/20 h-10 rounded-xl border-transparent shadow-none transition-colors" - /> - - - {baseUrlProviders.has(providerId) && ( - - - updateSettings((current) => ({ - ...current, - base_url: event.target.value, - })) - } - placeholder={t( - "pages.agent.tools.web_search.base_url_placeholder", - "Optional endpoint override", - )} - className="bg-muted/40 hover:bg-muted/60 focus:bg-background focus:ring-primary/20 h-10 rounded-xl border-transparent shadow-none transition-colors" - /> - - )} - - {apiKeyProviders.has(providerId) && ( - - - updateSettings((current) => ({ - ...current, - api_key: value, - })) - } - placeholder={apiKeyPlaceholder} - className="bg-muted/40 hover:bg-muted/60 focus:bg-background focus:ring-primary/20 h-10 rounded-xl border-transparent transition-colors" - /> - - )} - - {modelProviders.has(providerId) && ( - - - updateSettings((current) => ({ - ...current, - model: event.target.value, - })) - } - placeholder={t( - "pages.agent.tools.web_search.model_placeholder", - "Optional model override", - )} - className="bg-muted/40 hover:bg-muted/60 focus:bg-background focus:ring-primary/20 h-10 rounded-xl border-transparent shadow-none transition-colors" - /> - - )} -
-
- )} -
- ) -} - -function ProviderField({ - label, - className, - children, -}: { - label: string - className?: string - children: ReactNode -}) { - return ( -
- - {children} -
- ) -} diff --git a/web/frontend/src/components/agent/tools/web-search-tab.tsx b/web/frontend/src/components/agent/tools/web-search-tab.tsx deleted file mode 100644 index 866e0f27..00000000 --- a/web/frontend/src/components/agent/tools/web-search-tab.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { WebSearchConfigResponse } from "@/api/tools" -import { ConfigChangeNotice } from "@/components/config-change-notice" -import { Button } from "@/components/ui/button" -import { Skeleton } from "@/components/ui/skeleton" - -import type { WebSearchDraftUpdater } from "./types" -import { WebSearchGeneralSettings } from "./web-search-general-settings" -import { WebSearchProviderSettings } from "./web-search-provider-settings" - -interface WebSearchTabProps { - draft: WebSearchConfigResponse | null - providerLabelMap: Map - expandedProvider: string | null - isLoading: boolean - hasError: boolean - isSaving: boolean - isDirty: boolean - onSave: () => void - onToggleProviderExpand: (providerId: string) => void - onUpdateDraft: WebSearchDraftUpdater -} - -export function WebSearchTab({ - draft, - providerLabelMap, - expandedProvider, - isLoading, - hasError, - isSaving, - isDirty, - onSave, - onToggleProviderExpand, - onUpdateDraft, -}: WebSearchTabProps) { - const { t } = useTranslation() - - return ( -
- {hasError ? ( -
-

- {t( - "pages.agent.tools.web_search.load_error", - "Failed to load web search configuration", - )} -

-
- ) : isLoading || !draft ? ( - - ) : ( - <> -
-
-

- {t( - "pages.agent.tools.web_search.title", - "Web Search Configuration", - )} -

-

- {t( - "pages.agent.tools.web_search.description", - "Configure how the web search tool behaves by default, including whether the model may use its built-in search capability.", - )} -

-
- - -
- - {isDirty && ( - - )} - -
- - -
- - )} -
- ) -} - -function LoadingState() { - return ( -
- - -
- ) -} diff --git a/web/frontend/src/components/app-header.tsx b/web/frontend/src/components/app-header.tsx deleted file mode 100644 index eb90881f..00000000 --- a/web/frontend/src/components/app-header.tsx +++ /dev/null @@ -1,340 +0,0 @@ -import { - IconBook, - IconLanguage, - IconLoader2, - IconLogout, - IconMenu2, - IconMoon, - IconPlayerPlay, - IconPower, - IconRefresh, - IconSun, -} from "@tabler/icons-react" -import { Link } from "@tanstack/react-router" -import * as React from "react" -import { useTranslation } from "react-i18next" - -import { postLauncherDashboardLogout } from "@/api/launcher-auth" -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog.tsx" -import { Button } from "@/components/ui/button.tsx" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu.tsx" -import { Separator } from "@/components/ui/separator.tsx" -import { SidebarTrigger } from "@/components/ui/sidebar" -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip" -import { useGateway } from "@/hooks/use-gateway.ts" -import { useTheme } from "@/hooks/use-theme.ts" - -export function AppHeader() { - const { i18n, t } = useTranslation() - const { theme, toggleTheme } = useTheme() - const { - state: gwState, - loading: gwLoading, - canStart, - startReason, - restartRequired, - start, - restart, - stop, - error: gwError, - } = useGateway() - - const isRunning = gwState === "running" - const isStarting = gwState === "starting" - const isRestarting = gwState === "restarting" - const isStopping = gwState === "stopping" - const isStopped = gwState === "stopped" || gwState === "unknown" - const showNotConnectedHint = - !isRestarting && - !isStopping && - canStart && - (gwState === "stopped" || gwState === "error") - - const [showStopDialog, setShowStopDialog] = React.useState(false) - const [showLogoutDialog, setShowLogoutDialog] = React.useState(false) - - const handleLogout = async () => { - await postLauncherDashboardLogout() - globalThis.location.assign("/launcher-login") - } - - const handleGatewayToggle = () => { - if (gwLoading || isRestarting || isStopping || (!isRunning && !canStart)) { - return - } - if (isRunning) { - setShowStopDialog(true) - } else { - void start() - } - } - - const handleGatewayRestart = () => { - if (gwLoading || isRestarting || !restartRequired || !canStart) return - void restart() - } - - const confirmStop = () => { - setShowStopDialog(false) - stop() - } - - return ( -
-
- - - -
- - Logo - -
-
- - {/* Center prominent connection status */} -
- {showNotConnectedHint && ( -
- - - - {t("chat.notConnected")} -
- )} -
- - - - - - {t("header.gateway.stopDialog.title")} - - - {t("header.gateway.stopDialog.description")} - - - - {t("common.cancel")} - - {t("header.gateway.stopDialog.confirm")} - - - - - - - - - {t("header.logout.tooltip")} - - {t("header.logout.description")} - - - - {t("common.cancel")} - void handleLogout()}> - {t("header.logout.confirm")} - - - - - -
- {restartRequired && ( - - - - - - {t("header.gateway.restartRequired")} - - - )} - - {/* Gateway Start/Stop */} - {isRunning ? ( - - - - - - {gwError ?? t("header.gateway.action.stop")} - - - ) : ( - - - {/* Wrap in span so the tooltip still fires when the button is disabled */} - - - - - {gwError || (!canStart && startReason) ? ( - {gwError ?? startReason} - ) : null} - - )} - - - - {/* Docs Link */} - - - {/* Language Switcher */} - - - - - - i18n.changeLanguage("en")}> - English - - i18n.changeLanguage("pt-BR")}> - Português (Brasil) - - i18n.changeLanguage("bn-IN")}> - বাংলা - - i18n.changeLanguage("zh")}> - 简体中文 - - i18n.changeLanguage("cs")}> - Čeština - - - - - {/* Theme Toggle */} - - - - - {/* Logout */} - - - - - {t("header.logout.tooltip")} - -
-
- ) -} diff --git a/web/frontend/src/components/app-layout.tsx b/web/frontend/src/components/app-layout.tsx deleted file mode 100644 index a1f8f89a..00000000 --- a/web/frontend/src/components/app-layout.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import type { ReactNode } from "react" -import { Toaster } from "sonner" - -import { AppHeader } from "@/components/app-header" -import { AppSidebar } from "@/components/app-sidebar" -import { TourGuide } from "@/components/tour/tour-guide" -import { SidebarProvider } from "@/components/ui/sidebar" -import { TooltipProvider } from "@/components/ui/tooltip" - -export function AppLayout({ children }: { children: ReactNode }) { - return ( - - - - -
- -
-
- {children} -
-
-
- - -
-
- ) -} diff --git a/web/frontend/src/components/app-sidebar.tsx b/web/frontend/src/components/app-sidebar.tsx deleted file mode 100644 index 1980e458..00000000 --- a/web/frontend/src/components/app-sidebar.tsx +++ /dev/null @@ -1,260 +0,0 @@ -import { IconChevronRight } from "@tabler/icons-react" -import { - IconAtom, - IconChevronsDown, - IconChevronsUp, - IconKey, - IconListDetails, - IconMessageCircle, - IconSearch, - IconSettings, - IconSparkles, - IconTools, -} from "@tabler/icons-react" -import { Link, useRouterState } from "@tanstack/react-router" -import * as React from "react" -import { useTranslation } from "react-i18next" - -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@/components/ui/collapsible" -import { - Sidebar, - SidebarContent, - SidebarGroup, - SidebarGroupContent, - SidebarGroupLabel, - SidebarMenu, - SidebarMenuButton, - SidebarMenuItem, - SidebarRail, - useSidebar, -} from "@/components/ui/sidebar" -import { useSidebarChannels } from "@/hooks/use-sidebar-channels" - -interface NavItem { - title: string - url: string - icon: React.ComponentType<{ className?: string }> - translateTitle?: boolean -} - -interface NavGroup { - label: string - defaultOpen: boolean - items: NavItem[] - isChannelsGroup?: boolean -} - -const baseNavGroups: Omit[] = [ - { - label: "navigation.chat", - defaultOpen: true, - }, - { - label: "navigation.model_group", - defaultOpen: true, - }, - { - label: "navigation.agent_group", - defaultOpen: true, - }, - { - label: "navigation.services", - defaultOpen: true, - }, -] - -export function AppSidebar({ ...props }: React.ComponentProps) { - const routerState = useRouterState() - const { i18n, t } = useTranslation() - const { isMobile, setOpenMobile } = useSidebar() - const currentPath = routerState.location.pathname - const { - channelItems, - hasMoreChannels, - showAllChannels, - toggleShowAllChannels, - } = useSidebarChannels({ - language: (i18n.resolvedLanguage ?? i18n.language ?? "").toLowerCase(), - t, - }) - - const handleNavItemClick = React.useCallback(() => { - if (isMobile) { - setOpenMobile(false) - } - }, [isMobile, setOpenMobile]) - - const navGroups: NavGroup[] = React.useMemo(() => { - return [ - { - ...baseNavGroups[0], - items: [ - { - title: "navigation.chat", - url: "/", - icon: IconMessageCircle, - translateTitle: true, - }, - ], - }, - { - ...baseNavGroups[1], - items: [ - { - title: "navigation.models", - url: "/models", - icon: IconAtom, - translateTitle: true, - }, - { - title: "navigation.credentials", - url: "/credentials", - icon: IconKey, - translateTitle: true, - }, - ], - }, - { - label: "navigation.channels_group", - defaultOpen: true, - items: channelItems.map((item) => ({ - title: item.title, - url: item.url, - icon: item.icon, - translateTitle: false, - })), - isChannelsGroup: true, - }, - { - ...baseNavGroups[2], - items: [ - { - title: "navigation.hub", - url: "/agent/hub", - icon: IconSearch, - translateTitle: true, - }, - { - title: "navigation.skills", - url: "/agent/skills", - icon: IconSparkles, - translateTitle: true, - }, - { - title: "navigation.tools", - url: "/agent/tools", - icon: IconTools, - translateTitle: true, - }, - ], - }, - { - ...baseNavGroups[3], - items: [ - { - title: "navigation.config", - url: "/config", - icon: IconSettings, - translateTitle: true, - }, - { - title: "navigation.logs", - url: "/logs", - icon: IconListDetails, - translateTitle: true, - }, - ], - }, - ] - }, [channelItems]) - - return ( - - - {navGroups.map((group) => ( - - - - - {t(group.label)} - - - - - - - {group.items.map((item) => { - const isActive = - currentPath === item.url || - (item.url !== "/" && - currentPath.startsWith(`${item.url}/`)) - return ( - - - - - - {item.translateTitle === false - ? item.title - : t(item.title)} - - - - - ) - })} - {group.isChannelsGroup && hasMoreChannels && ( - - - {showAllChannels ? ( - - ) : ( - - )} - - {showAllChannels - ? t("navigation.show_less_channels") - : t("navigation.show_more_channels")} - - - - )} - - - - - - ))} - - - - ) -} diff --git a/web/frontend/src/components/channels/channel-array-list-field.tsx b/web/frontend/src/components/channels/channel-array-list-field.tsx deleted file mode 100644 index ff601c07..00000000 --- a/web/frontend/src/components/channels/channel-array-list-field.tsx +++ /dev/null @@ -1,180 +0,0 @@ -import { IconX } from "@tabler/icons-react" -import { - type KeyboardEvent, - useCallback, - useEffect, - useRef, - useState, -} from "react" -import { useTranslation } from "react-i18next" - -import { - mergeUniqueStringItems, - parseConservativeStringListInput, -} from "@/components/channels/channel-array-utils" -import { Field } from "@/components/shared-form" -import { Button } from "@/components/ui/button" -import { Input } from "@/components/ui/input" - -type StringListParser = (raw: string) => string[] -export type ArrayFieldFlusher = () => string[] | null - -type RegisterArrayFieldFlusher = ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, -) => void - -function areStringArraysEqual(left: string[], right: string[]): boolean { - if (left.length !== right.length) { - return false - } - return left.every((item, index) => item === right[index]) -} - -interface ChannelArrayListFieldProps { - label: string - hint?: string - error?: string - required?: boolean - value: string[] - onChange: (value: string[]) => void - placeholder?: string - parser?: StringListParser - fieldPath?: string - registerFlusher?: RegisterArrayFieldFlusher - resetVersion?: number -} - -export function ChannelArrayListField({ - label, - hint, - error, - required, - value, - onChange, - placeholder, - parser = parseConservativeStringListInput, - fieldPath, - registerFlusher, - resetVersion, -}: ChannelArrayListFieldProps) { - const { t } = useTranslation() - const [draft, setDraft] = useState("") - const draftRef = useRef("") - const valueRef = useRef(value) - const localValueRef = useRef(value) - const parserRef = useRef(parser) - const onChangeRef = useRef(onChange) - - useEffect(() => { - valueRef.current = value - localValueRef.current = value - }, [value]) - - useEffect(() => { - draftRef.current = "" - setDraft("") - }, [resetVersion]) - - useEffect(() => { - parserRef.current = parser - }, [parser]) - - useEffect(() => { - onChangeRef.current = onChange - }, [onChange]) - - const commitDraft = useCallback(() => { - const rawDraft = draftRef.current - if (rawDraft.trim() === "") { - if (!areStringArraysEqual(localValueRef.current, valueRef.current)) { - return localValueRef.current - } - draftRef.current = "" - setDraft("") - return null - } - draftRef.current = "" - setDraft("") - const nextItems = parserRef.current(rawDraft) - if (nextItems.length === 0) { - return null - } - const mergedItems = mergeUniqueStringItems(localValueRef.current, nextItems) - localValueRef.current = mergedItems - onChangeRef.current(mergedItems) - return mergedItems - }, []) - - useEffect(() => { - if (!fieldPath || !registerFlusher) { - return - } - registerFlusher(fieldPath, commitDraft) - return () => registerFlusher(fieldPath, null) - }, [commitDraft, fieldPath, registerFlusher]) - - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key !== "Enter") { - return - } - event.preventDefault() - commitDraft() - } - - const handleRemove = (index: number) => { - const nextValue = value.filter((_, itemIndex) => itemIndex !== index) - localValueRef.current = nextValue - onChangeRef.current(nextValue) - } - - return ( - -
- {value.length > 0 && ( -
- {value.map((item, index) => ( - - {item} - - - ))} -
- )} - -
- { - const nextDraft = event.target.value - draftRef.current = nextDraft - setDraft(nextDraft) - }} - onKeyDown={handleKeyDown} - placeholder={placeholder} - /> - -
-
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-array-utils.ts b/web/frontend/src/components/channels/channel-array-utils.ts deleted file mode 100644 index 0f6268be..00000000 --- a/web/frontend/src/components/channels/channel-array-utils.ts +++ /dev/null @@ -1,72 +0,0 @@ -const ALLOW_FROM_HIDDEN_CHARS_RE = - /\u200b|\u200c|\u200d|\u200e|\u200f|\u202a|\u202b|\u202c|\u202d|\u202e|\u2060|\u2061|\u2062|\u2063|\u2064|\u2066|\u2067|\u2068|\u2069|\ufeff/g - -function normalizeStringListItems( - items: string[], - options: { stripHiddenChars?: boolean } = {}, -): string[] { - const result: string[] = [] - const seen = new Set() - - for (const item of items) { - const normalized = options.stripHiddenChars - ? item.replace(ALLOW_FROM_HIDDEN_CHARS_RE, "") - : item - const trimmed = normalized.trim() - if (trimmed.length === 0 || seen.has(trimmed)) { - continue - } - seen.add(trimmed) - result.push(trimmed) - } - - return result -} - -function splitStringList( - raw: string, - separators: RegExp, - options: { stripHiddenChars?: boolean } = {}, -): string[] { - if (raw.trim() === "") { - return [] - } - return normalizeStringListItems(raw.split(separators), options) -} - -export function asStringArray(value: unknown): string[] { - if (!Array.isArray(value)) { - return [] - } - return value.filter((item): item is string => typeof item === "string") -} - -export function parseAllowFromInput(raw: string): string[] { - return splitStringList(raw, /[,\uFF0C、;;\n\r\t]+/, { - stripHiddenChars: true, - }) -} - -export function parseConservativeStringListInput(raw: string): string[] { - return splitStringList(raw, /[,\uFF0C\n\r\t]+/) -} - -export function normalizeAllowFromValues(value: unknown): string[] { - return normalizeStringListItems(asStringArray(value), { - stripHiddenChars: true, - }) -} - -export function mergeUniqueStringItems( - currentItems: string[], - nextItems: string[], -): string[] { - return normalizeStringListItems([...currentItems, ...nextItems]) -} - -export function serializeStringArrayForSubmit(value: unknown): unknown { - if (!Array.isArray(value)) { - return value - } - return normalizeStringListItems(asStringArray(value)).join("\n") -} diff --git a/web/frontend/src/components/channels/channel-config-fields.ts b/web/frontend/src/components/channels/channel-config-fields.ts deleted file mode 100644 index cf8f50ad..00000000 --- a/web/frontend/src/components/channels/channel-config-fields.ts +++ /dev/null @@ -1,103 +0,0 @@ -import type { ChannelConfig } from "@/api/channels" - -export const SECRET_FIELD_MAP = { - token: "_token", - app_secret: "_app_secret", - client_secret: "_client_secret", - corp_secret: "_corp_secret", - channel_secret: "_channel_secret", - channel_access_token: "_channel_access_token", - access_token: "_access_token", - bot_token: "_bot_token", - app_token: "_app_token", - encoding_aes_key: "_encoding_aes_key", - encrypt_key: "_encrypt_key", - verification_token: "_verification_token", - secret: "_secret", - username: "_username", - password: "_password", - nickserv_password: "_nickserv_password", - sasl_password: "_sasl_password", -} as const - -const CHANNEL_SECRET_FIELDS: Record = { - 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"], - mqtt: ["username", "password"], -} - -const SECRET_FIELD_SET = new Set(Object.keys(SECRET_FIELD_MAP)) - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -export function isSecretField(key: string): boolean { - return SECRET_FIELD_SET.has(key) -} - -export function buildEditConfig( - channelName: string, - config: ChannelConfig, -): ChannelConfig { - const edit: ChannelConfig = { ...config } - - for (const key of CHANNEL_SECRET_FIELDS[channelName] ?? []) { - if (!(key in edit)) { - edit[key] = "" - } - const editKey = SECRET_FIELD_MAP[key as keyof typeof SECRET_FIELD_MAP] - if (editKey) { - edit[editKey] = "" - } - } - - return edit -} - -export function hasConfiguredSecret( - configuredSecrets: readonly string[], - key: string, -): boolean { - return configuredSecrets.includes(key) -} - -export function getFieldValueForValidation( - config: ChannelConfig, - configuredSecrets: readonly string[], - key: string, -): unknown { - const editKey = SECRET_FIELD_MAP[key as keyof typeof SECRET_FIELD_MAP] - if (editKey) { - const incoming = asString(config[editKey]).trim() - if (incoming !== "") { - return incoming - } - if (hasConfiguredSecret(configuredSecrets, key)) { - return true - } - } - return config[key] -} - -export function getSecretInputPlaceholder( - configuredSecrets: readonly string[], - key: string, - configuredPlaceholder: string, - fallback = "", -): string { - return hasConfiguredSecret(configuredSecrets, key) - ? configuredPlaceholder - : fallback -} diff --git a/web/frontend/src/components/channels/channel-config-page.tsx b/web/frontend/src/components/channels/channel-config-page.tsx deleted file mode 100644 index 10e2a225..00000000 --- a/web/frontend/src/components/channels/channel-config-page.tsx +++ /dev/null @@ -1,758 +0,0 @@ -import { IconLoader2 } from "@tabler/icons-react" -import { useCallback, useEffect, useMemo, useRef, useState } from "react" -import { useTranslation } from "react-i18next" - -import { - type ChannelConfig, - type SupportedChannel, - getChannelConfig, - getChannelsCatalog, - patchAppConfig, -} from "@/api/channels" -import { type ArrayFieldFlusher } from "@/components/channels/channel-array-list-field" -import { - normalizeAllowFromValues, - serializeStringArrayForSubmit, -} from "@/components/channels/channel-array-utils" -import { - SECRET_FIELD_MAP, - buildEditConfig, - getFieldValueForValidation, - isSecretField, -} from "@/components/channels/channel-config-fields" -import { getChannelDisplayName } from "@/components/channels/channel-display-name" -import { DiscordForm } from "@/components/channels/channel-forms/discord-form" -import { FeishuForm } from "@/components/channels/channel-forms/feishu-form" -import { GenericForm } from "@/components/channels/channel-forms/generic-form" -import { MqttForm } from "@/components/channels/channel-forms/mqtt-form" -import { SlackForm } from "@/components/channels/channel-forms/slack-form" -import { TelegramForm } from "@/components/channels/channel-forms/telegram-form" -import { WecomForm } from "@/components/channels/channel-forms/wecom-form" -import { WeixinForm } from "@/components/channels/channel-forms/weixin-form" -import { ConfigChangeNotice } from "@/components/config-change-notice" -import { PageHeader } from "@/components/page-header" -import { Button } from "@/components/ui/button" -import { Switch } from "@/components/ui/switch" -import { useGateway } from "@/hooks/use-gateway" -import { showSaveSuccessOrRestartToast } from "@/lib/restart-required" -import { refreshGatewayState } from "@/store/gateway" - -interface ChannelConfigPageProps { - channelName: string -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asBool(value: unknown): boolean { - return value === true -} - -function setRecordValueByPath( - source: Record, - pathSegments: string[], - value: unknown, -): Record { - const [segment, ...rest] = pathSegments - if (!segment) { - return source - } - if (rest.length === 0) { - return { ...source, [segment]: value } - } - return { - ...source, - [segment]: setRecordValueByPath(asRecord(source[segment]), rest, value), - } -} - -function setConfigValueByPath( - source: ChannelConfig, - fieldPath: string, - value: unknown, -): ChannelConfig { - return setRecordValueByPath(source, fieldPath.split("."), value) -} - -function serializeGroupTriggerForSubmit(value: unknown): unknown { - const groupTrigger = asRecord(value) - if (Object.keys(groupTrigger).length === 0) { - return value - } - return { - ...groupTrigger, - prefixes: serializeStringArrayForSubmit(groupTrigger.prefixes), - } -} - -const CHANNEL_COMMON_CONFIG_KEYS = new Set([ - "allow_from", - "group_trigger", - "placeholder", - "reasoning_channel_id", - "typing", -]) - -function normalizeConfig( - channel: SupportedChannel, - rawConfig: ChannelConfig, -): ChannelConfig { - const config = { ...rawConfig } - if (channel.name === "whatsapp_native") { - config.use_native = true - } - if (channel.name === "whatsapp") { - config.use_native = false - } - return config -} - -function buildSavePayload( - channel: SupportedChannel, - editConfig: ChannelConfig, - enabled: boolean, -): ChannelConfig { - const payload: ChannelConfig = { enabled, type: channel.config_key } - const settings: ChannelConfig = {} - - for (const [key, value] of Object.entries(editConfig)) { - if (key.startsWith("_")) continue - if (key === "enabled") continue - if (CHANNEL_COMMON_CONFIG_KEYS.has(key)) { - if (key === "allow_from") { - payload[key] = serializeStringArrayForSubmit( - normalizeAllowFromValues(value), - ) - } else if (key === "group_trigger") { - payload[key] = serializeGroupTriggerForSubmit(value) - } else { - payload[key] = value - } - continue - } - if (isSecretField(key)) continue - - settings[key] = serializeStringArrayForSubmit(value) - } - - for (const [secretKey, editKey] of Object.entries(SECRET_FIELD_MAP)) { - const incoming = asString(editConfig[editKey]) - if (incoming !== "") { - settings[secretKey] = incoming - continue - } - const existing = asString(editConfig[secretKey]).trim() - if (existing !== "") { - settings[secretKey] = existing - } - } - - if (channel.name === "whatsapp_native") { - settings.use_native = true - } - if (channel.name === "whatsapp") { - settings.use_native = false - } - - if (Object.keys(settings).length > 0) { - payload.settings = settings - } - - return payload -} - -function isConfigured( - channel: SupportedChannel, - config: ChannelConfig, - configuredSecrets: readonly string[], -): boolean { - const hasValue = (key: string) => - !isMissingRequiredValue( - getFieldValueForValidation(config, configuredSecrets, key), - ) - - switch (channel.name) { - case "telegram": - return hasValue("token") - case "discord": - return hasValue("token") - case "slack": - return hasValue("bot_token") - case "feishu": - return hasValue("app_id") && hasValue("app_secret") - case "dingtalk": - return hasValue("client_id") && hasValue("client_secret") - case "line": - return hasValue("channel_secret") && hasValue("channel_access_token") - case "qq": - return hasValue("app_id") && hasValue("app_secret") - case "onebot": - return hasValue("ws_url") - case "weixin": - return hasValue("account_id") - case "wecom": - return hasValue("bot_id") - case "whatsapp": - return hasValue("bridge_url") - case "whatsapp_native": - return asBool(config.use_native) - case "pico": - return hasValue("token") - case "maixcam": - return hasValue("host") - case "matrix": - return ( - hasValue("homeserver") && - hasValue("user_id") && - hasValue("access_token") - ) - case "irc": - return hasValue("server") - case "mqtt": - return hasValue("broker") && hasValue("agent_id") - default: - return false - } -} - -function getRequiredFieldKeys(channelName: string): string[] { - switch (channelName) { - case "telegram": - return ["token"] - case "discord": - return ["token"] - case "slack": - return ["bot_token"] - case "feishu": - return ["app_id", "app_secret"] - case "dingtalk": - return ["client_id", "client_secret"] - case "line": - return ["channel_secret", "channel_access_token"] - case "qq": - return ["app_id", "app_secret"] - case "onebot": - return ["ws_url"] - case "wecom": - return [] - case "whatsapp": - return ["bridge_url"] - case "pico": - return ["token"] - case "maixcam": - return ["host"] - case "matrix": - return ["homeserver", "user_id", "access_token"] - case "irc": - return ["server"] - case "mqtt": - return ["broker", "agent_id"] - default: - return [] - } -} - -function isMissingRequiredValue(value: unknown): boolean { - if (value === null || value === undefined) { - return true - } - if (typeof value === "string") { - return value.trim() === "" - } - if (Array.isArray(value)) { - return value.length === 0 - } - return false -} - -function getChannelDocSlug(channelName: string): string { - return channelName.replaceAll("_", "-") -} - -const CHANNELS_WITHOUT_DOCS = new Set([ - "pico", - "wecom", - "matrix", - "irc", - "whatsapp", - "whatsapp_native", - "mqtt", -]) - -export function ChannelConfigPage({ channelName }: ChannelConfigPageProps) { - const { t, i18n } = useTranslation() - const { state: gatewayState } = useGateway() - - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [fetchError, setFetchError] = useState("") - const [serverError, setServerError] = useState("") - const [fieldErrors, setFieldErrors] = useState>({}) - - const [channel, setChannel] = useState(null) - const [baseConfig, setBaseConfig] = useState({}) - const [editConfig, setEditConfig] = useState({}) - const [configuredSecrets, setConfiguredSecrets] = useState([]) - const [enabled, setEnabled] = useState(false) - const [arrayFieldResetVersion, setArrayFieldResetVersion] = useState(0) - const arrayFieldFlushersRef = useRef(new Map()) - const loadRequestIdRef = useRef(0) - - const resetPageState = useCallback(() => { - arrayFieldFlushersRef.current.clear() - setChannel(null) - setBaseConfig({}) - setEditConfig({}) - setConfiguredSecrets([]) - setEnabled(false) - setFetchError("") - setServerError("") - setFieldErrors({}) - setArrayFieldResetVersion((version) => version + 1) - }, []) - - const loadData = useCallback( - async (silent = false) => { - const requestId = loadRequestIdRef.current + 1 - loadRequestIdRef.current = requestId - if (!silent) setLoading(true) - try { - const catalog = await getChannelsCatalog() - if (loadRequestIdRef.current !== requestId) return - const matched = - catalog.channels.find((item) => item.name === channelName) ?? null - - if (!matched) { - resetPageState() - setFetchError( - t("channels.page.notFound", { - name: channelName, - }), - ) - return - } - - const channelConfig = await getChannelConfig(channelName) - if (loadRequestIdRef.current !== requestId) return - const raw = asRecord(channelConfig.config) - const normalized = normalizeConfig(matched, raw) - - setChannel(matched) - setBaseConfig(normalized) - setEditConfig(buildEditConfig(matched.name, normalized)) - setConfiguredSecrets(channelConfig.configured_secrets ?? []) - setEnabled(asBool(normalized.enabled)) - setFetchError("") - setServerError("") - setFieldErrors({}) - } catch (e) { - if (loadRequestIdRef.current !== requestId) return - setConfiguredSecrets([]) - setFetchError(e instanceof Error ? e.message : t("channels.loadError")) - } finally { - if (!silent && loadRequestIdRef.current === requestId) { - setLoading(false) - } - } - }, - [channelName, resetPageState, t], - ) - - useEffect(() => { - resetPageState() - setLoading(true) - loadData() - }, [loadData, resetPageState]) - - const previousGatewayStatusRef = useRef(gatewayState) - useEffect(() => { - const previousStatus = previousGatewayStatusRef.current - if (previousStatus !== "running" && gatewayState === "running") { - void loadData() - } - previousGatewayStatusRef.current = gatewayState - }, [gatewayState, loadData]) - - const configured = useMemo(() => { - if (!channel) return false - return isConfigured(channel, editConfig, configuredSecrets) - }, [channel, configuredSecrets, editConfig]) - - const isDirty = useMemo(() => { - if (loading || !channel || channel.name !== channelName) return false - const basePayload = buildSavePayload( - channel, - buildEditConfig(channel.name, baseConfig), - asBool(baseConfig.enabled), - ) - const currentPayload = buildSavePayload(channel, editConfig, enabled) - return JSON.stringify(basePayload) !== JSON.stringify(currentPayload) - }, [baseConfig, channel, channelName, editConfig, enabled, loading]) - - const docsUrl = useMemo(() => { - if (!channel) return "" - if (CHANNELS_WITHOUT_DOCS.has(channel.name)) return "" - const language = ( - i18n.resolvedLanguage ?? - i18n.language ?? - "" - ).toLowerCase() - const base = language.startsWith("zh") - ? "https://docs.picoclaw.io/zh-Hans/docs/channels" - : "https://docs.picoclaw.io/docs/channels" - return `${base}/${getChannelDocSlug(channel.name)}` - }, [channel, i18n.language, i18n.resolvedLanguage]) - - const channelDisplayName = useMemo(() => { - if (!channel) return channelName - return getChannelDisplayName(channel, t) - }, [channel, channelName, t]) - - const hidesPageLevelEnableToggle = channel?.name === "wecom" - - const hiddenKeys = useMemo(() => { - if (!channel) return [] - if (channel.name === "whatsapp") { - return ["use_native"] - } - if (channel.name === "whatsapp_native") { - return ["use_native", "bridge_url"] - } - return [] - }, [channel]) - const requiredKeys = useMemo( - () => getRequiredFieldKeys(channelName), - [channelName], - ) - - const handleChange = useCallback((key: string, value: unknown) => { - const normalizedKey = key.startsWith("_") ? key.slice(1) : key - setEditConfig((prev) => ({ ...prev, [key]: value })) - setFieldErrors((prev) => { - if (!(key in prev) && !(normalizedKey in prev)) { - return prev - } - const next = { ...prev } - delete next[key] - delete next[normalizedKey] - return next - }) - }, []) - - const registerArrayFieldFlusher = useCallback( - (fieldPath: string, flusher: ArrayFieldFlusher | null) => { - if (flusher) { - arrayFieldFlushersRef.current.set(fieldPath, flusher) - return - } - arrayFieldFlushersRef.current.delete(fieldPath) - }, - [], - ) - - const flushPendingArrayFieldDrafts = useCallback( - (sourceConfig: ChannelConfig): ChannelConfig => { - let nextConfig = sourceConfig - for (const [fieldPath, flusher] of arrayFieldFlushersRef.current) { - const flushedValue = flusher() - if (flushedValue === null) { - continue - } - nextConfig = setConfigValueByPath(nextConfig, fieldPath, flushedValue) - } - return nextConfig - }, - [], - ) - - const handleReset = () => { - if (!channel) return - setEditConfig(buildEditConfig(channel.name, baseConfig)) - setEnabled(asBool(baseConfig.enabled)) - setServerError("") - setFieldErrors({}) - setArrayFieldResetVersion((version) => version + 1) - } - - const handleSave = async () => { - if (!channel) return - - const preparedEditConfig = flushPendingArrayFieldDrafts(editConfig) - if (preparedEditConfig !== editConfig) { - setEditConfig(preparedEditConfig) - } - - const missingRequiredFields = requiredKeys.filter((key) => - isMissingRequiredValue( - getFieldValueForValidation(preparedEditConfig, configuredSecrets, key), - ), - ) - if (missingRequiredFields.length > 0) { - const requiredFieldError = t("channels.validation.requiredField") - const nextFieldErrors: Record = {} - for (const key of missingRequiredFields) { - nextFieldErrors[key] = requiredFieldError - } - setFieldErrors(nextFieldErrors) - setServerError("") - return - } - - setSaving(true) - setServerError("") - setFieldErrors({}) - try { - const savePayload = buildSavePayload(channel, preparedEditConfig, enabled) - await patchAppConfig({ - channel_list: { - [channel.config_key]: savePayload, - }, - }) - await loadData() - const gateway = await refreshGatewayState({ force: true }) - showSaveSuccessOrRestartToast( - t, - t("channels.page.saveSuccess"), - channelDisplayName, - gateway?.restartRequired === true, - ) - } catch (e) { - const message = - e instanceof Error ? e.message : t("channels.page.saveError") - setServerError(message) - } finally { - setSaving(false) - } - } - - const handleWeixinBindSuccess = useCallback(async () => { - try { - setEnabled(true) - await Promise.all([loadData(true), refreshGatewayState({ force: true })]) - } catch (e) { - const message = - e instanceof Error ? e.message : t("channels.page.saveError") - setServerError(message) - await loadData(true) - } - }, [loadData, t]) - - const handleWecomBindSuccess = useCallback(async () => { - try { - setEnabled(true) - await Promise.all([loadData(true), refreshGatewayState({ force: true })]) - } catch (e) { - const message = - e instanceof Error ? e.message : t("channels.page.saveError") - setServerError(message) - await loadData(true) - } - }, [loadData, t]) - - const handleWecomEnabledChange = useCallback( - async (nextEnabled: boolean) => { - try { - setEnabled(nextEnabled) - await Promise.all([ - loadData(true), - refreshGatewayState({ force: true }), - ]) - } catch (e) { - const message = - e instanceof Error ? e.message : t("channels.page.saveError") - setServerError(message) - await loadData(true) - } - }, - [loadData, t], - ) - - const renderForm = () => { - if (!channel) return null - const isEdit = configured - - switch (channel.name) { - case "telegram": - return ( - - ) - case "discord": - return ( - - ) - case "slack": - return ( - - ) - case "feishu": - return ( - - ) - case "mqtt": - return ( - - ) - case "weixin": - return ( - void handleWeixinBindSuccess()} - registerArrayFieldFlusher={registerArrayFieldFlusher} - arrayFieldResetVersion={arrayFieldResetVersion} - /> - ) - case "wecom": - return ( - <> - void handleWecomBindSuccess()} - onEnabledChange={(nextEnabled) => - void handleWecomEnabledChange(nextEnabled) - } - /> - - - ) - default: - return ( - - ) - } - } - - return ( -
- - {t("channels.page.docLink")} - - ) - } - /> - -
- {loading ? ( -
- -
- ) : fetchError ? ( -
- {fetchError} -
- ) : ( -
- {!hidesPageLevelEnableToggle && ( -
-

- {t("channels.page.enableLabel")} -

- -
- )} - - {renderForm()} - - {serverError && ( -

{serverError}

- )} - - {isDirty && ( - - )} - -
- - -
-
- )} -
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-display-name.ts b/web/frontend/src/components/channels/channel-display-name.ts deleted file mode 100644 index fe70f5f5..00000000 --- a/web/frontend/src/components/channels/channel-display-name.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { TFunction } from "i18next" - -import type { SupportedChannel } from "@/api/channels" - -export function getChannelDisplayName( - channel: Pick, - t: TFunction, -): string { - const key = `channels.name.${channel.name}` - const translated = t(key) - if (translated !== key) { - return translated - } - - if (channel.display_name && channel.display_name.trim() !== "") { - return channel.display_name - } - - return channel.name - .split("_") - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(" ") -} diff --git a/web/frontend/src/components/channels/channel-forms/discord-form.tsx b/web/frontend/src/components/channels/channel-forms/discord-form.tsx deleted file mode 100644 index d2a98d32..00000000 --- a/web/frontend/src/components/channels/channel-forms/discord-form.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, -} from "@/components/channels/channel-array-utils" -import { getSecretInputPlaceholder } from "@/components/channels/channel-config-fields" -import { Field, KeyInput, SwitchCardField } from "@/components/shared-form" -import { Card, CardContent } from "@/components/ui/card" -import { Input } from "@/components/ui/input" - -interface DiscordFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets: string[] - fieldErrors?: Record - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asBool(value: unknown): boolean { - return value === true -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -export function DiscordForm({ - config, - onChange, - configuredSecrets, - fieldErrors = {}, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: DiscordFormProps) { - const { t } = useTranslation() - const groupTriggerConfig = asRecord(config.group_trigger) - - return ( -
- - - - onChange("_token", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "token", - t("channels.field.secretHintSet"), - t("channels.field.tokenPlaceholder"), - )} - /> - - - - - - - - onChange("proxy", e.target.value)} - placeholder="http://127.0.0.1:7890" - /> - - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - -
- { - onChange("group_trigger", { - ...groupTriggerConfig, - mention_only: checked, - }) - }} - ariaLabel={t("channels.field.mentionOnly")} - /> -
-
-
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/feishu-form.tsx b/web/frontend/src/components/channels/channel-forms/feishu-form.tsx deleted file mode 100644 index ed49e29c..00000000 --- a/web/frontend/src/components/channels/channel-forms/feishu-form.tsx +++ /dev/null @@ -1,182 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, - parseConservativeStringListInput, -} from "@/components/channels/channel-array-utils" -import { getSecretInputPlaceholder } from "@/components/channels/channel-config-fields" -import { Field, KeyInput, SwitchCardField } from "@/components/shared-form" -import { Card, CardContent } from "@/components/ui/card" -import { Input } from "@/components/ui/input" - -interface FeishuFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets: string[] - fieldErrors?: Record - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asBool(value: unknown): boolean { - return typeof value === "boolean" ? value : false -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -export function FeishuForm({ - config, - onChange, - configuredSecrets, - fieldErrors = {}, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: FeishuFormProps) { - const { t } = useTranslation() - const groupTriggerConfig = asRecord(config.group_trigger) - - return ( -
- - - - onChange("app_id", e.target.value)} - placeholder="cli_xxxx" - /> - - - - onChange("_app_secret", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "app_secret", - t("channels.field.secretHintSet"), - t("channels.field.secretPlaceholder"), - )} - /> - - - - - - - - onChange("_verification_token", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "verification_token", - t("channels.field.secretHintSet"), - t("channels.field.secretPlaceholder"), - )} - /> - - - onChange("_encrypt_key", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "encrypt_key", - t("channels.field.secretHintSet"), - t("channels.field.secretPlaceholder"), - )} - /> - - - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - -
- onChange("is_lark", checked)} - ariaLabel={t("channels.field.isLark")} - /> -
-
-
- - - -
- { - onChange("group_trigger", { - ...groupTriggerConfig, - mention_only: checked, - }) - }} - ariaLabel={t("channels.field.groupTriggerMentionOnly")} - /> -
- - onChange("random_reaction_emoji", value)} - placeholder={t("channels.field.randomReactionEmojiPlaceholder")} - parser={parseConservativeStringListInput} - fieldPath="random_reaction_emoji" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> -
-
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/generic-form.tsx b/web/frontend/src/components/channels/channel-forms/generic-form.tsx deleted file mode 100644 index ee429321..00000000 --- a/web/frontend/src/components/channels/channel-forms/generic-form.tsx +++ /dev/null @@ -1,434 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, -} from "@/components/channels/channel-array-utils" -import { - getSecretInputPlaceholder, - isSecretField, -} from "@/components/channels/channel-config-fields" -import { Field, KeyInput, SwitchCardField } from "@/components/shared-form" -import { Card, CardContent } from "@/components/ui/card" -import { Input } from "@/components/ui/input" - -import { StreamingConfigField } from "./streaming-config-field" - -interface GenericFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets?: string[] - hiddenKeys?: string[] - requiredKeys?: string[] - supportsStreaming?: boolean - fieldErrors?: Record - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -// Fields to skip in the generic form (handled by enabled toggle or internal). -const SKIP_FIELDS = new Set(["enabled", "reasoning_channel_id"]) - -// Fields that are objects/nested — show as JSON or skip. -const OBJECT_FIELDS = new Set([ - "group_trigger", - "typing", - "placeholder", - "allow_token_query", - "allow_from", - "allow_origins", - "groups", - "streaming", -]) - -function formatLabel(key: string): string { - return key - .split("_") - .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) - .join(" ") -} - -function formatSentenceFieldName(key: string): string { - const label = formatLabel(key) - return label.charAt(0).toLowerCase() + label.slice(1) -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -function asBool(value: unknown): boolean { - return value === true -} - -export function GenericForm({ - config, - onChange, - configuredSecrets = [], - hiddenKeys = [], - requiredKeys = [], - supportsStreaming = false, - fieldErrors = {}, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: GenericFormProps) { - const { t } = useTranslation() - const hiddenFieldSet = new Set(hiddenKeys) - const requiredFieldSet = new Set(requiredKeys) - const groupTriggerConfig = asRecord(config.group_trigger) - const typingConfig = asRecord(config.typing) - const placeholderConfig = asRecord(config.placeholder) - const placeholderEnabled = asBool(placeholderConfig.enabled) - const showStreamingConfig = - (config.streaming !== undefined || supportsStreaming) && - !hiddenFieldSet.has("streaming") - - const rawFields = Object.keys(config).filter( - (k) => - !k.startsWith("_") && - !SKIP_FIELDS.has(k) && - !OBJECT_FIELDS.has(k) && - !hiddenFieldSet.has(k), - ) - - const buildHint = (key: string): string => { - const descriptions: Record = { - ws_url: t("channels.form.desc.wsUrl"), - reconnect_interval: t("channels.form.desc.reconnectInterval"), - bridge_url: t("channels.form.desc.bridgeUrl"), - session_store_path: t("channels.form.desc.sessionStorePath"), - use_native: t("channels.form.desc.useNative"), - host: t("channels.form.desc.host"), - port: t("channels.form.desc.port"), - homeserver: t("channels.form.desc.homeserver"), - user_id: t("channels.form.desc.userId"), - device_id: t("channels.form.desc.deviceId"), - join_on_invite: t("channels.form.desc.joinOnInvite"), - app_id: t("channels.form.desc.appId"), - client_id: t("channels.form.desc.clientId"), - corp_id: t("channels.form.desc.corpId"), - bot_id: t("channels.form.desc.appId"), - websocket_url: t("channels.form.desc.wsUrl"), - dm_policy: t("channels.form.desc.genericField", { field: "DM policy" }), - group_policy: t("channels.form.desc.genericField", { - field: "group policy", - }), - group_allow_from: t("channels.form.desc.allowFrom"), - send_thinking_message: t("channels.form.desc.genericField", { - field: "thinking message behavior", - }), - agent_id: t("channels.form.desc.agentId"), - webhook_url: t("channels.form.desc.webhookUrl"), - webhook_host: t("channels.form.desc.webhookHost"), - webhook_port: t("channels.form.desc.webhookPort"), - webhook_path: t("channels.form.desc.webhookPath"), - reply_timeout: t("channels.form.desc.replyTimeout"), - max_steps: t("channels.form.desc.maxSteps"), - welcome_message: t("channels.form.desc.welcomeMessage"), - allow_token_query: t("channels.form.desc.allowTokenQuery"), - ping_interval: t("channels.form.desc.pingInterval"), - read_timeout: t("channels.form.desc.readTimeout"), - write_timeout: t("channels.form.desc.writeTimeout"), - max_connections: t("channels.form.desc.maxConnections"), - server: t("channels.form.desc.server"), - tls: t("channels.form.desc.tls"), - nick: t("channels.form.desc.nick"), - user: t("channels.form.desc.user"), - real_name: t("channels.form.desc.realName"), - channels: t("channels.form.desc.channels"), - request_caps: t("channels.form.desc.requestCaps"), - max_base64_file_size_mib: t("channels.form.desc.maxBase64FileSizeMiB"), - } - return ( - descriptions[key] ?? - t("channels.form.desc.genericField", { - field: formatSentenceFieldName(key), - }) - ) - } - - const renderField = (key: string) => { - const isRequired = requiredFieldSet.has(key) - if (isSecretField(key)) { - const editKey = `_${key}` - return ( - - onChange(editKey, v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - key, - t("channels.field.secretHintSet"), - t("channels.field.secretPlaceholder"), - )} - /> - - ) - } - - const value = config[key] - if (typeof value === "boolean") { - return ( - onChange(key, checked)} - ariaLabel={formatLabel(key)} - /> - ) - } - - if (Array.isArray(value)) { - return ( - onChange(key, nextValue)} - fieldPath={key} - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - ) - } - - return ( - - { - const v = e.target.value - if (typeof config[key] === "number") { - onChange(key, v === "" ? 0 : Number(v)) - } else { - onChange(key, v) - } - }} - /> - - ) - } - - const isBasicField = (key: string) => { - if (requiredFieldSet.has(key)) return true - if ( - key.endsWith("id") || - key.endsWith("token") || - key.endsWith("secret") || - key.endsWith("url") || - key === "server" || - key === "host" || - key === "port" - ) { - return true - } - return false - } - - const basicFields = rawFields.filter(isBasicField) - const advancedFields = rawFields.filter((key) => !isBasicField(key)) - - const hasAdvancedContent = - advancedFields.length > 0 || - (config.allow_from !== undefined && !hiddenFieldSet.has("allow_from")) || - (config.allow_origins !== undefined && - !hiddenFieldSet.has("allow_origins")) || - (config.allow_token_query !== undefined && - !hiddenFieldSet.has("allow_token_query")) || - (config.group_trigger !== undefined && - !hiddenFieldSet.has("group_trigger")) || - (config.typing !== undefined && !hiddenFieldSet.has("typing")) || - (config.placeholder !== undefined && !hiddenFieldSet.has("placeholder")) || - (config.streaming !== undefined && !hiddenFieldSet.has("streaming")) - - return ( -
- {basicFields.length > 0 && ( - - - {basicFields.map(renderField)} - - - )} - - {hasAdvancedContent && ( - - - {advancedFields.map(renderField)} - - {config.allow_from !== undefined && - !hiddenFieldSet.has("allow_from") && ( - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - )} - - {config.allow_origins !== undefined && - !hiddenFieldSet.has("allow_origins") && ( - onChange("allow_origins", value)} - placeholder={t("channels.field.allowOriginsPlaceholder")} - fieldPath="allow_origins" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - )} - - {config.allow_token_query !== undefined && - !hiddenFieldSet.has("allow_token_query") && ( -
- - onChange("allow_token_query", checked) - } - ariaLabel={formatLabel("allow_token_query")} - /> -
- )} - - {config.group_trigger !== undefined && - !hiddenFieldSet.has("group_trigger") && ( - <> -
- - onChange("group_trigger", { - ...groupTriggerConfig, - mention_only: checked, - }) - } - ariaLabel={t("channels.field.groupTriggerMentionOnly")} - /> -
- - - onChange("group_trigger", { - ...groupTriggerConfig, - prefixes: value, - }) - } - placeholder={t("channels.field.groupTriggerPrefixes")} - fieldPath="group_trigger.prefixes" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - - )} - - {config.typing !== undefined && !hiddenFieldSet.has("typing") && ( -
- - onChange("typing", { ...typingConfig, enabled: checked }) - } - ariaLabel={t("channels.field.typingEnabled")} - /> -
- )} - - {showStreamingConfig && ( -
- onChange("streaming", value)} - /> -
- )} - - {config.placeholder !== undefined && - !hiddenFieldSet.has("placeholder") && ( -
- - onChange("placeholder", { - ...placeholderConfig, - enabled: checked, - }) - } - ariaLabel={t("channels.field.placeholderEnabled")} - > - {placeholderEnabled && ( -
- - onChange("placeholder", { - ...placeholderConfig, - text: e.target.value, - }) - } - placeholder={t("channels.field.placeholderText")} - aria-label={t("channels.field.placeholderText")} - /> -
- )} -
-
- )} -
-
- )} -
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/mqtt-form.tsx b/web/frontend/src/components/channels/channel-forms/mqtt-form.tsx deleted file mode 100644 index 0be02649..00000000 --- a/web/frontend/src/components/channels/channel-forms/mqtt-form.tsx +++ /dev/null @@ -1,255 +0,0 @@ -import type { ChannelConfig } from "@/api/channels" -import { MessageCodeBlock } from "@/components/chat/message-code-block" -import { getSecretInputPlaceholder } from "@/components/channels/channel-config-fields" -import { Field, KeyInput } from "@/components/shared-form" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" -import { Input } from "@/components/ui/input" -import { useTranslation } from "react-i18next" - -interface MqttFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets: string[] - fieldErrors?: Record -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asNumber(value: unknown): string { - if (typeof value === "number") return String(value) - if (typeof value === "string" && value !== "") return value - return "" -} - -function CodeLine({ children }: { children: string }) { - return ( - - {children} - - ) -} - -export function MqttForm({ - config, - onChange, - configuredSecrets, - fieldErrors = {}, -}: MqttFormProps) { - const { t } = useTranslation() - const prefix = asString(config.topic_prefix) || "/picoclaw" - const agentID = asString(config.agent_id) || "{agent_id}" - const topicBase = `${prefix}/${agentID}/{client_id}` - - return ( -
- - - - onChange("broker", e.target.value)} - placeholder="mqtt://broker.example.com:1883" - /> - - - - onChange("agent_id", e.target.value)} - placeholder="my-agent" - /> - - - - onChange("topic_prefix", e.target.value)} - placeholder="/picoclaw" - /> - - - - - - - - onChange("_username", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "username", - t("channels.mqtt.secretSet"), - t("channels.mqtt.secretEmpty"), - )} - /> - - - - onChange("_password", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "password", - t("channels.mqtt.secretSet"), - t("channels.mqtt.secretEmpty"), - )} - /> - - - - - - - - onChange("client_id", e.target.value)} - placeholder={t("channels.mqtt.clientIdPlaceholder")} - /> - - - - onChange("keep_alive", Number(e.target.value))} - placeholder="60" - /> - - - - onChange("qos", Number(e.target.value))} - placeholder="0" - /> - - - - - - - - {t("channels.mqtt.protocolTitle")} - - - {t("channels.mqtt.protocolDesc")} - - - -
-

- {t("channels.mqtt.uplink")} -

- {`${topicBase}/request`} - -
-

- - {t("channels.mqtt.fieldText")} - - {" — "} - {t("channels.mqtt.uplinkTextDesc")} -

-
-
- -
-

- {t("channels.mqtt.downlink")} -

- {`${topicBase}/response`} - -
-

- - {t("channels.mqtt.fieldText")} - - {" — "} - {t("channels.mqtt.downlinkTextDesc")} -

-
-
- -
-

- {t("channels.mqtt.topicParams")} -

-
-

- - {prefix} - - {" — "} - {t("channels.mqtt.topicPrefixDesc")} -

-

- - {agentID} - - {" — "} - {t("channels.mqtt.agentIdDesc")} -

-

- - {"{client_id}"} - - {" — "} - {t("channels.mqtt.clientIdDesc")} -

-
-
-
-
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/slack-form.tsx b/web/frontend/src/components/channels/channel-forms/slack-form.tsx deleted file mode 100644 index b8184e8b..00000000 --- a/web/frontend/src/components/channels/channel-forms/slack-form.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, -} from "@/components/channels/channel-array-utils" -import { getSecretInputPlaceholder } from "@/components/channels/channel-config-fields" -import { Field, KeyInput } from "@/components/shared-form" -import { Card, CardContent } from "@/components/ui/card" - -interface SlackFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets: string[] - fieldErrors?: Record - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -export function SlackForm({ - config, - onChange, - configuredSecrets, - fieldErrors = {}, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: SlackFormProps) { - const { t } = useTranslation() - - return ( -
- - - - onChange("_bot_token", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "bot_token", - t("channels.field.secretHintSet"), - "xoxb-xxxx", - )} - /> - - - - onChange("_app_token", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "app_token", - t("channels.field.secretHintSet"), - "xapp-xxxx", - )} - /> - - - - - - - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - - -
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/streaming-config-field.tsx b/web/frontend/src/components/channels/channel-forms/streaming-config-field.tsx deleted file mode 100644 index f14b55ac..00000000 --- a/web/frontend/src/components/channels/channel-forms/streaming-config-field.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import { useTranslation } from "react-i18next" - -import { Field, SwitchCardField } from "@/components/shared-form" -import { Input } from "@/components/ui/input" - -interface StreamingConfigFieldProps { - value: unknown - onChange: (value: Record) => void -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -function asBool(value: unknown): boolean { - return value === true -} - -function numberInputValue(value: unknown): string { - return typeof value === "number" && value > 0 ? String(value) : "" -} - -export function StreamingConfigField({ - value, - onChange, -}: StreamingConfigFieldProps) { - const { t } = useTranslation() - const streamingConfig = asRecord(value) - const streamingEnabled = asBool(streamingConfig.enabled) - - const update = (patch: Record) => { - onChange({ ...streamingConfig, ...patch }) - } - - const handleEnabledChange = (checked: boolean) => { - if (!checked) { - onChange({ - enabled: false, - throttle_seconds: null, - min_growth_chars: null, - }) - return - } - update({ enabled: true }) - } - - return ( - - {streamingEnabled && ( -
- - - update({ - throttle_seconds: - e.target.value === "" ? 0 : Number(e.target.value), - }) - } - placeholder="0" - /> - - - - update({ - min_growth_chars: - e.target.value === "" ? 0 : Number(e.target.value), - }) - } - placeholder="0" - /> - -
- )} -
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/telegram-form.tsx b/web/frontend/src/components/channels/channel-forms/telegram-form.tsx deleted file mode 100644 index 31405be6..00000000 --- a/web/frontend/src/components/channels/channel-forms/telegram-form.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, -} from "@/components/channels/channel-array-utils" -import { getSecretInputPlaceholder } from "@/components/channels/channel-config-fields" -import { Field, KeyInput, SwitchCardField } from "@/components/shared-form" -import { Card, CardContent } from "@/components/ui/card" -import { Input } from "@/components/ui/input" - -import { StreamingConfigField } from "./streaming-config-field" - -interface TelegramFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - configuredSecrets: string[] - fieldErrors?: Record - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -function asRecord(value: unknown): Record { - if (value && typeof value === "object" && !Array.isArray(value)) { - return value as Record - } - return {} -} - -function asBool(value: unknown): boolean { - return value === true -} - -export function TelegramForm({ - config, - onChange, - configuredSecrets, - fieldErrors = {}, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: TelegramFormProps) { - const { t } = useTranslation() - const typingConfig = asRecord(config.typing) - const placeholderConfig = asRecord(config.placeholder) - const placeholderEnabled = asBool(placeholderConfig.enabled) - - return ( -
- - - - onChange("_token", v)} - placeholder={getSecretInputPlaceholder( - configuredSecrets, - "token", - t("channels.field.secretHintSet"), - t("channels.field.tokenPlaceholder"), - )} - /> - - - - onChange("base_url", e.target.value)} - placeholder="https://api.telegram.org" - /> - - - - - - - - onChange("proxy", e.target.value)} - placeholder="http://127.0.0.1:7890" - /> - - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - -
- - onChange("typing", { ...typingConfig, enabled: checked }) - } - ariaLabel={t("channels.field.typingEnabled")} - /> -
- -
- onChange("streaming", value)} - /> -
- -
- - onChange("placeholder", { - ...placeholderConfig, - enabled: checked, - }) - } - ariaLabel={t("channels.field.placeholderEnabled")} - > - {placeholderEnabled && ( -
- - onChange("placeholder", { - ...placeholderConfig, - text: e.target.value, - }) - } - placeholder={t("channels.field.placeholderText")} - aria-label={t("channels.field.placeholderText")} - /> -
- )} -
-
-
-
-
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/wecom-form.tsx b/web/frontend/src/components/channels/channel-forms/wecom-form.tsx deleted file mode 100644 index c21ac318..00000000 --- a/web/frontend/src/components/channels/channel-forms/wecom-form.tsx +++ /dev/null @@ -1,368 +0,0 @@ -import { - IconCheck, - IconLoader2, - IconQrcode, - IconRefresh, - IconX, -} from "@tabler/icons-react" -import { useCallback, useEffect, useRef, useState } from "react" -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { patchAppConfig, pollWecomFlow, startWecomFlow } from "@/api/channels" -import { Button } from "@/components/ui/button" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" -import { Switch } from "@/components/ui/switch" - -type BindingState = - | "idle" - | "loading" - | "waiting" - | "scaned" - | "confirmed" - | "expired" - | "error" - -interface WecomFormProps { - config: ChannelConfig - isEdit: boolean - onBindSuccess?: () => void - onEnabledChange?: (enabled: boolean) => void -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -export function WecomForm({ - config, - isEdit, - onBindSuccess, - onEnabledChange, -}: WecomFormProps) { - const { t } = useTranslation() - - const [bindState, setBindState] = useState("idle") - const [qrDataURI, setQrDataURI] = useState(null) - const [botID, setBotID] = useState(null) - const [errorMsg, setErrorMsg] = useState("") - const [enabled, setEnabled] = useState(config.enabled === true) - const [toggleSaving, setToggleSaving] = useState(false) - const [toggleError, setToggleError] = useState("") - - const pollTimerRef = useRef | null>(null) - const pollGenerationRef = useRef(0) - const existingBotID = asString(config.bot_id) - const isBound = isEdit && existingBotID !== "" - - const stopPolling = useCallback(() => { - pollGenerationRef.current += 1 - if (pollTimerRef.current !== null) { - clearInterval(pollTimerRef.current) - pollTimerRef.current = null - } - }, []) - - useEffect(() => () => stopPolling(), [stopPolling]) - - useEffect(() => { - setEnabled(config.enabled === true) - }, [config.enabled]) - - useEffect(() => { - if (!existingBotID) return - stopPolling() - setBotID(existingBotID) - setBindState("confirmed") - setErrorMsg("") - }, [existingBotID, stopPolling]) - - const startPolling = useCallback( - (id: string) => { - stopPolling() - const generation = pollGenerationRef.current - let inFlight = false - pollTimerRef.current = setInterval(async () => { - if (inFlight) return - inFlight = true - try { - const resp = await pollWecomFlow(id) - if (generation !== pollGenerationRef.current) { - return - } - if (resp.status === "scaned") { - setBindState("scaned") - } else if (resp.status === "confirmed") { - stopPolling() - setBotID(resp.bot_id ?? existingBotID ?? null) - setBindState("confirmed") - onBindSuccess?.() - } else if (resp.status === "expired") { - stopPolling() - setBindState("expired") - } else if (resp.status === "error") { - stopPolling() - setBindState("error") - setErrorMsg(resp.error ?? t("channels.wecom.errorGeneric")) - } - } catch { - // transient network error — keep polling - } finally { - inFlight = false - } - }, 2000) - }, - [existingBotID, onBindSuccess, stopPolling, t], - ) - - const handleEnabledChange = useCallback( - async (checked: boolean) => { - if (!existingBotID || toggleSaving) { - return - } - setToggleSaving(true) - setToggleError("") - try { - await patchAppConfig({ - channel_list: { - wecom: { - enabled: checked, - type: "wecom", - }, - }, - }) - setEnabled(checked) - onEnabledChange?.(checked) - } catch (e) { - setToggleError( - e instanceof Error ? e.message : t("channels.wecom.errorGeneric"), - ) - } finally { - setToggleSaving(false) - } - }, - [existingBotID, onEnabledChange, t, toggleSaving], - ) - - const handleBind = async () => { - setBindState("loading") - setErrorMsg("") - setToggleError("") - setQrDataURI(null) - stopPolling() - try { - const resp = await startWecomFlow() - setQrDataURI(resp.qr_data_uri ?? null) - setBindState("waiting") - startPolling(resp.flow_id) - } catch (e) { - setBindState("error") - setErrorMsg( - e instanceof Error ? e.message : t("channels.wecom.errorGeneric"), - ) - } - } - - const handleRebind = () => { - stopPolling() - setBindState("idle") - setQrDataURI(null) - setBotID(null) - setErrorMsg("") - void handleBind() - } - - const renderBindSection = () => { - if (bindState === "idle") { - if (isBound) { - return ( -
-
- - {t("channels.wecom.bound")} -
- {existingBotID && ( -

- {existingBotID} -

- )} - -
- ) - } - return ( -
-

- {t("channels.wecom.notBound")} -

- -
- ) - } - - if (bindState === "loading") { - return ( -
- -

- {t("channels.wecom.generating")} -

-
- ) - } - - if (bindState === "waiting" || bindState === "scaned") { - return ( -
- {qrDataURI ? ( - WeCom QR Code - ) : ( -
- -
- )} - {bindState === "scaned" ? ( -
- - {t("channels.wecom.scanned")} -
- ) : ( -

- {t("channels.wecom.scanHint")} -

- )} - -
- ) - } - - if (bindState === "confirmed") { - return ( -
-
- -
-

- {t("channels.wecom.bound")} -

- {botID && ( -

{botID}

- )} - -
- ) - } - - if (bindState === "expired") { - return ( -
-
- -
-

- {t("channels.wecom.expired")} -

- -
- ) - } - - if (bindState === "error") { - return ( -
-
- -
-

- {errorMsg || t("channels.wecom.errorGeneric")} -

- -
- ) - } - - return null - } - - return ( -
-
-

{t("channels.page.enableLabel")}

-
- void handleEnabledChange(checked)} - /> - {toggleError && ( -

- {toggleError} -

- )} -
-
- - - - - {t("channels.wecom.bindTitle")} - - {t("channels.wecom.bindDesc")} - - {renderBindSection()} - -
- ) -} diff --git a/web/frontend/src/components/channels/channel-forms/weixin-form.tsx b/web/frontend/src/components/channels/channel-forms/weixin-form.tsx deleted file mode 100644 index 29700f09..00000000 --- a/web/frontend/src/components/channels/channel-forms/weixin-form.tsx +++ /dev/null @@ -1,360 +0,0 @@ -import { - IconCheck, - IconLoader2, - IconQrcode, - IconRefresh, - IconX, -} from "@tabler/icons-react" -import { useCallback, useEffect, useRef, useState } from "react" -import { useTranslation } from "react-i18next" - -import type { ChannelConfig } from "@/api/channels" -import { pollWeixinFlow, startWeixinFlow } from "@/api/channels" -import { - type ArrayFieldFlusher, - ChannelArrayListField, -} from "@/components/channels/channel-array-list-field" -import { - asStringArray, - parseAllowFromInput, -} from "@/components/channels/channel-array-utils" -import { Field } from "@/components/shared-form" -import { Button } from "@/components/ui/button" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" -import { Input } from "@/components/ui/input" - -type BindingState = - | "idle" - | "loading" - | "waiting" - | "scaned" - | "confirmed" - | "expired" - | "error" - -interface WeixinFormProps { - config: ChannelConfig - onChange: (key: string, value: unknown) => void - isEdit: boolean - onBindSuccess?: () => void - registerArrayFieldFlusher?: ( - fieldPath: string, - flusher: ArrayFieldFlusher | null, - ) => void - arrayFieldResetVersion?: number -} - -function asString(value: unknown): string { - return typeof value === "string" ? value : "" -} - -export function WeixinForm({ - config, - onChange, - isEdit, - onBindSuccess, - registerArrayFieldFlusher, - arrayFieldResetVersion, -}: WeixinFormProps) { - const { t } = useTranslation() - - const [bindState, setBindState] = useState("idle") - const [qrDataURI, setQrDataURI] = useState(null) - const [accountID, setAccountID] = useState(null) - const [errorMsg, setErrorMsg] = useState("") - - const pollTimerRef = useRef | null>(null) - const pollGenerationRef = useRef(0) - const isBound = isEdit && asString(config.account_id) !== "" - const existingAccountID = asString(config.account_id) - - const stopPolling = useCallback(() => { - pollGenerationRef.current += 1 - if (pollTimerRef.current !== null) { - clearInterval(pollTimerRef.current) - pollTimerRef.current = null - } - }, []) - - useEffect(() => () => stopPolling(), [stopPolling]) - - useEffect(() => { - if (!existingAccountID) return - stopPolling() - setAccountID(existingAccountID) - setBindState("confirmed") - setErrorMsg("") - }, [existingAccountID, stopPolling]) - - const startPolling = useCallback( - (id: string) => { - stopPolling() - const generation = pollGenerationRef.current - let inFlight = false - pollTimerRef.current = setInterval(async () => { - if (inFlight) return - inFlight = true - try { - const resp = await pollWeixinFlow(id) - if (generation !== pollGenerationRef.current) { - return - } - if (resp.status === "scaned") { - setBindState("scaned") - } else if (resp.status === "confirmed") { - stopPolling() - setAccountID(resp.account_id ?? existingAccountID ?? null) - setBindState("confirmed") - onBindSuccess?.() - } else if (resp.status === "expired") { - stopPolling() - setBindState("expired") - } else if (resp.status === "error") { - stopPolling() - setBindState("error") - setErrorMsg(resp.error ?? t("channels.weixin.errorGeneric")) - } - } catch { - // transient network error — keep polling - } finally { - inFlight = false - } - }, 2000) - }, - [existingAccountID, stopPolling, onBindSuccess, t], - ) - - const handleBind = async () => { - setBindState("loading") - setErrorMsg("") - setQrDataURI(null) - stopPolling() - try { - const resp = await startWeixinFlow() - setQrDataURI(resp.qr_data_uri ?? null) - setBindState("waiting") - startPolling(resp.flow_id) - } catch (e) { - setBindState("error") - setErrorMsg( - e instanceof Error ? e.message : t("channels.weixin.errorGeneric"), - ) - } - } - - const handleRebind = () => { - stopPolling() - setBindState("idle") - setQrDataURI(null) - setAccountID(null) - setErrorMsg("") - void handleBind() - } - - const renderBindSection = () => { - if (bindState === "idle") { - if (isBound) { - return ( -
-
- - {t("channels.weixin.bound")} -
- {existingAccountID && ( -

- {existingAccountID} -

- )} - -
- ) - } - return ( -
-

- {t("channels.weixin.notBound")} -

- -
- ) - } - - if (bindState === "loading") { - return ( -
- -

- {t("channels.weixin.generating")} -

-
- ) - } - - if (bindState === "waiting" || bindState === "scaned") { - return ( -
- {qrDataURI ? ( - WeChat QR Code - ) : ( -
- -
- )} - {bindState === "scaned" ? ( -
- - {t("channels.weixin.scanned")} -
- ) : ( -

- {t("channels.weixin.scanHint")} -

- )} - -
- ) - } - - if (bindState === "confirmed") { - return ( -
-
- -
-

- {t("channels.weixin.bound")} -

- {accountID && ( -

- {accountID} -

- )} - -
- ) - } - - if (bindState === "expired") { - return ( -
-
- -
-

- {t("channels.weixin.expired")} -

- -
- ) - } - - if (bindState === "error") { - return ( -
-
- -
-

- {errorMsg || t("channels.weixin.errorGeneric")} -

- -
- ) - } - - return null - } - - return ( -
- - - - {t("channels.weixin.bindTitle")} - - {t("channels.weixin.bindDesc")} - - {renderBindSection()} - - - - - onChange("allow_from", value)} - placeholder={t("channels.field.allowFromPlaceholder")} - parser={parseAllowFromInput} - fieldPath="allow_from" - registerFlusher={registerArrayFieldFlusher} - resetVersion={arrayFieldResetVersion} - /> - - - onChange("proxy", e.target.value)} - placeholder="http://localhost:7890" - /> - - - -
- ) -} diff --git a/web/frontend/src/components/chat/assistant-message.tsx b/web/frontend/src/components/chat/assistant-message.tsx deleted file mode 100644 index 0a197b25..00000000 --- a/web/frontend/src/components/chat/assistant-message.tsx +++ /dev/null @@ -1,303 +0,0 @@ -import { - IconBrain, - IconCheck, - IconChevronDown, - IconCopy, - IconDownload, - IconFileText, - IconTool, -} from "@tabler/icons-react" -import { useState } from "react" -import { useTranslation } from "react-i18next" -import ReactMarkdown from "react-markdown" -import rehypeHighlight from "rehype-highlight" -import rehypeRaw from "rehype-raw" -import rehypeSanitize from "rehype-sanitize" -import remarkGfm from "remark-gfm" - -import { - MessageCodeBlock, - MarkdownCodeBlock, -} from "@/components/chat/message-code-block" -import { Button } from "@/components/ui/button" -import { formatMessageTime } from "@/hooks/use-pico-chat" -import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard" -import { cn } from "@/lib/utils" -import { - type AssistantMessageKind, - type ChatAttachment, - type ChatToolCall, -} from "@/store/chat" - -interface AssistantMessageProps { - content: string - attachments?: ChatAttachment[] - kind?: AssistantMessageKind - modelName?: string - toolCalls?: ChatToolCall[] - timestamp?: string | number -} - -export function AssistantMessage({ - content, - attachments = [], - kind = "normal", - modelName, - toolCalls = [], - timestamp = "", -}: AssistantMessageProps) { - const { t } = useTranslation() - const { copy, isCopied } = useCopyToClipboard() - const isThought = kind === "thought" - const isToolCalls = kind === "tool_calls" - const isCollapsedBlock = isThought || isToolCalls - const hasText = content.trim().length > 0 - const hasToolCalls = toolCalls.length > 0 - const imageAttachments = attachments.filter( - (attachment) => attachment.type === "image", - ) - const fileAttachments = attachments.filter( - (attachment) => attachment.type !== "image", - ) - const [isExpanded, setIsExpanded] = useState(true) - const formattedTimestamp = - timestamp !== "" ? formatMessageTime(timestamp) : "" - const collapsedLabel = isThought - ? t("chat.reasoningLabel") - : t("chat.toolCallsLabel") - const copyMessageLabel = isCopied - ? t("chat.copiedLabel") - : t("chat.copyMessage") - const trimmedModelName = modelName?.trim() ?? "" - - return ( -
- {!isCollapsedBlock && ( -
-
- PicoClaw - {trimmedModelName && ( - <> - • - {trimmedModelName} - - )} - {formattedTimestamp && ( - <> - • - {formattedTimestamp} - - )} -
-
- )} - - {(hasText || isCollapsedBlock || hasToolCalls) && ( -
- {isCollapsedBlock && ( -
setIsExpanded(!isExpanded)} - > -
- {isThought ? ( - - ) : ( - - )} - {collapsedLabel} - {trimmedModelName && ( - {trimmedModelName} - )} -
-
- {formattedTimestamp && ( - {formattedTimestamp} - )} - -
-
- )} - {(!isCollapsedBlock || isExpanded) && isToolCalls && hasToolCalls && ( -
- {toolCalls.map((toolCall, index) => { - const explanation = - toolCall.extraContent?.toolFeedbackExplanation?.trim() ?? "" - const toolName = toolCall.function?.name?.trim() ?? "" - const toolArguments = toolCall.function?.arguments?.trim() ?? "" - const hasFunctionSummary = toolName || toolArguments - - if (!explanation && !hasFunctionSummary) { - return null - } - - return ( -
0 && "border-border/20 border-t pt-3", - )} - > - {explanation && ( -
-
- {t("chat.toolCallExplanationLabel")} -
-
- - {explanation} - -
-
- )} - - {hasFunctionSummary && ( -
-
- {t("chat.toolCallFunctionLabel")} -
-
- {toolName && !toolArguments && ( -
- {toolName} -
- )} - {toolArguments && ( - - )} -
-
- )} -
- ) - })} -
- )} - {(!isCollapsedBlock || isExpanded) && !isToolCalls && hasText && ( -
- - {content} - -
- )} - - {!isCollapsedBlock && hasText && ( - - )} -
- )} - - {imageAttachments.length > 0 && ( -
- {imageAttachments.map((attachment, index) => ( - - {attachment.filename -
- - ))} -
- )} - - {fileAttachments.length > 0 && ( - - )} -
- ) -} diff --git a/web/frontend/src/components/chat/chat-composer.tsx b/web/frontend/src/components/chat/chat-composer.tsx deleted file mode 100644 index 315c2f9f..00000000 --- a/web/frontend/src/components/chat/chat-composer.tsx +++ /dev/null @@ -1,217 +0,0 @@ -import { IconArrowUp, IconPhotoPlus, IconX } from "@tabler/icons-react" -import { - type ClipboardEvent as ReactClipboardEvent, - type DragEvent as ReactDragEvent, - type KeyboardEvent as ReactKeyboardEvent, - useRef, -} from "react" -import { useTranslation } from "react-i18next" -import TextareaAutosize from "react-textarea-autosize" - -import { ContextUsageRing } from "@/components/chat/context-usage-ring" -import { Button } from "@/components/ui/button" -import { cn } from "@/lib/utils" -import type { ChatAttachment, ContextUsage } from "@/store/chat" - -export type ChatInputDisabledReason = - | "gatewayUnknown" - | "gatewayStarting" - | "gatewayRestarting" - | "gatewayStopping" - | "gatewayStopped" - | "gatewayError" - | "websocketConnecting" - | "websocketDisconnected" - | "websocketError" - | "noDefaultModel" - -interface ChatComposerProps { - input: string - attachments: ChatAttachment[] - onInputChange: (value: string) => void - onAddImages: () => void - onPaste: (event: ReactClipboardEvent) => void - onDragEnter: (event: ReactDragEvent) => void - onDragLeave: (event: ReactDragEvent) => void - onDragOver: (event: ReactDragEvent) => void - onDrop: (event: ReactDragEvent) => void - onRemoveAttachment: (index: number) => void - onSend: () => void - onContextDetail?: () => void - inputDisabledReason: ChatInputDisabledReason | null - canSend: boolean - isDragActive: boolean - contextUsage?: ContextUsage -} - -export function ChatComposer({ - input, - attachments, - onInputChange, - onAddImages, - onPaste, - onDragEnter, - onDragLeave, - onDragOver, - onDrop, - onRemoveAttachment, - onSend, - onContextDetail, - inputDisabledReason, - canSend, - isDragActive, - contextUsage, -}: ChatComposerProps) { - const { t } = useTranslation() - const canInput = inputDisabledReason === null - const composingRef = useRef(false) - const hasInput = input.trim().length > 0 - const disabledMessage = - inputDisabledReason === null - ? null - : t(`chat.disabledPlaceholder.${inputDisabledReason}`) - const placeholder = disabledMessage ?? t("chat.placeholder") - - const handleKeyDown = (e: ReactKeyboardEvent) => { - const nativeEvent = e.nativeEvent as Event & { - isComposing?: boolean - keyCode?: number - } - if ( - composingRef.current || - nativeEvent.isComposing || - nativeEvent.keyCode === 229 - ) { - return - } - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault() - onSend() - } - } - - return ( -
-
-
- {isDragActive && ( -
-
- {t("chat.dropImagesActive")} -
-
- )} - - {attachments.length > 0 && ( -
- {attachments.map((attachment, index) => ( -
- {attachment.filename - -
- ))} -
- )} - - onInputChange(e.target.value)} - onCompositionStart={() => { - composingRef.current = true - }} - onCompositionEnd={() => { - composingRef.current = false - }} - onPaste={onPaste} - onKeyDown={handleKeyDown} - placeholder={placeholder} - disabled={!canInput} - title={disabledMessage || undefined} - className={cn( - "placeholder:text-muted-foreground/50 max-h-[200px] min-h-[64px] resize-none border-0 bg-transparent px-2 py-1 text-[15px] shadow-none transition-colors focus-visible:ring-0 focus-visible:outline-none dark:bg-transparent", - !canInput && "cursor-not-allowed", - )} - minRows={1} - maxRows={8} - /> - -
-
- -
- -
- {contextUsage && ( - - )} - {canInput ? ( - - - - ) : null} -
-
-
- -
- {t("chat.composeHint")} -
-
-
- ) -} diff --git a/web/frontend/src/components/chat/chat-empty-state.tsx b/web/frontend/src/components/chat/chat-empty-state.tsx deleted file mode 100644 index 7e1abca1..00000000 --- a/web/frontend/src/components/chat/chat-empty-state.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { - IconPlugConnectedX, - IconRobot, - IconRobotOff, - IconStar, -} from "@tabler/icons-react" -import { Link } from "@tanstack/react-router" -import { useTranslation } from "react-i18next" - -import { Button } from "@/components/ui/button" - -interface ChatEmptyStateProps { - hasAvailableModels: boolean - defaultModelName: string - isConnected: boolean -} - -export function ChatEmptyState({ - hasAvailableModels, - defaultModelName, - isConnected, -}: ChatEmptyStateProps) { - const { t } = useTranslation() - - if (!hasAvailableModels) { - return ( -
-
- -
-

- {t("chat.empty.noConfiguredModel")} -

-

- {t("chat.empty.noConfiguredModelDescription")} -

- -
- ) - } - - if (!defaultModelName) { - return ( -
-
- -
-

- {t("chat.empty.noSelectedModel")} -

-

- {t("chat.empty.noSelectedModelDescription")} -

-
- ) - } - - if (!isConnected) { - return ( -
-
- -
-

- {t("chat.empty.notRunning")} -

-

- {t("chat.empty.notRunningDescription")} -

-
- ) - } - - return ( -
-
- -
-

{t("chat.welcome")}

-

- {t("chat.welcomeDesc")} -

-
- ) -} diff --git a/web/frontend/src/components/chat/chat-page.tsx b/web/frontend/src/components/chat/chat-page.tsx deleted file mode 100644 index 43f5ede5..00000000 --- a/web/frontend/src/components/chat/chat-page.tsx +++ /dev/null @@ -1,466 +0,0 @@ -import { IconPlus } from "@tabler/icons-react" -import { useAtom } from "jotai" -import { - type ChangeEvent, - type ClipboardEvent, - type DragEvent, - useEffect, - useRef, - useState, -} from "react" -import { useTranslation } from "react-i18next" - -import { AssistantMessage } from "@/components/chat/assistant-message" -import { - ChatComposer, - type ChatInputDisabledReason, -} from "@/components/chat/chat-composer" -import { ChatEmptyState } from "@/components/chat/chat-empty-state" -import { ModelSelector } from "@/components/chat/model-selector" -import { SessionHistoryMenu } from "@/components/chat/session-history-menu" -import { TypingIndicator } from "@/components/chat/typing-indicator" -import { UserMessage } from "@/components/chat/user-message" -import { PageHeader } from "@/components/page-header" -import { Button } from "@/components/ui/button" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { - CHAT_IMAGE_ACCEPT, - buildChatImageAttachments, - getTransferredFiles, - hasFileTransfer, -} from "@/features/chat/image-input" -import { useChatModels } from "@/hooks/use-chat-models" -import { useGateway } from "@/hooks/use-gateway" -import { usePicoChat } from "@/hooks/use-pico-chat" -import { useSessionHistory } from "@/hooks/use-session-history" -import type { AssistantDetailVisibility } from "@/store/chat" -import type { ConnectionState } from "@/store/chat" -import type { ChatAttachment } from "@/store/chat" -import { - assistantDetailVisibilityAtom, - shouldShowAssistantMessage, -} from "@/store/chat" -import type { GatewayState } from "@/store/gateway" - -function resolveChatInputDisabledReason({ - hasDefaultModel, - connectionState, - gatewayState, -}: { - hasDefaultModel: boolean - connectionState: ConnectionState - gatewayState: GatewayState -}): ChatInputDisabledReason | null { - if (gatewayState === "unknown") { - return "gatewayUnknown" - } - - if (gatewayState === "starting") { - return "gatewayStarting" - } - - if (gatewayState === "restarting") { - return "gatewayRestarting" - } - - if (gatewayState === "stopping") { - return "gatewayStopping" - } - - if (gatewayState === "stopped") { - return "gatewayStopped" - } - - if (gatewayState === "error") { - return "gatewayError" - } - - if (connectionState === "connecting") { - return "websocketConnecting" - } - - if (connectionState === "error") { - return "websocketError" - } - - if (connectionState === "disconnected") { - return "websocketDisconnected" - } - - if (!hasDefaultModel) { - return "noDefaultModel" - } - - return null -} - -export function ChatPage() { - const { t } = useTranslation() - const scrollRef = useRef(null) - const fileInputRef = useRef(null) - const dragDepthRef = useRef(0) - const [isAtBottom, setIsAtBottom] = useState(true) - const [hasScrolled, setHasScrolled] = useState(false) - const [input, setInput] = useState("") - const [attachments, setAttachments] = useState([]) - const [isDragActive, setIsDragActive] = useState(false) - const [assistantDetailVisibility, setAssistantDetailVisibility] = useAtom( - assistantDetailVisibilityAtom, - ) - - const assistantDetailVisibilityOptions: Array<{ - value: AssistantDetailVisibility - label: string - }> = [ - { value: "none", label: t("chat.assistantDetailVisibility.none") }, - { value: "thought", label: t("chat.assistantDetailVisibility.thought") }, - { - value: "tool_calls", - label: t("chat.assistantDetailVisibility.toolCalls"), - }, - { value: "all", label: t("chat.assistantDetailVisibility.all") }, - ] - - const { - messages, - connectionState, - isTyping, - activeSessionId, - contextUsage, - sendMessage, - switchSession, - newChat, - } = usePicoChat() - - const { state: gwState } = useGateway() - const isGatewayRunning = gwState === "running" - - const { - defaultModelName, - hasAvailableModels, - apiKeyModels, - oauthModels, - localModels, - settingDefault, - handleSetDefault, - } = useChatModels({ isConnected: isGatewayRunning }) - const hasDefaultModel = Boolean(defaultModelName) - const inputDisabledReason = resolveChatInputDisabledReason({ - hasDefaultModel, - connectionState, - gatewayState: gwState, - }) - const canInput = inputDisabledReason === null - - const { - sessions, - hasMore, - loadError, - loadErrorMessage, - observerRef, - loadSessions, - handleDeleteSession, - } = useSessionHistory({ - activeSessionId, - onDeletedActiveSession: newChat, - }) - - const syncScrollState = (element: HTMLDivElement) => { - const { clientHeight, scrollHeight, scrollTop } = element - setHasScrolled(scrollTop > 0) - setIsAtBottom(scrollHeight - scrollTop <= clientHeight + 10) - } - - const handleScroll = (e: React.UIEvent) => { - syncScrollState(e.currentTarget) - } - - useEffect(() => { - if (scrollRef.current) { - if (isAtBottom) { - scrollRef.current.scrollTop = scrollRef.current.scrollHeight - } - syncScrollState(scrollRef.current) - } - }, [messages, isTyping, isAtBottom]) - - const handleSend = () => { - if ((!input.trim() && attachments.length === 0) || !canInput) return - if ( - sendMessage({ - content: input, - attachments, - }) - ) { - setInput("") - setAttachments([]) - } - } - - const handleAddImages = () => { - if (!canInput) return - fileInputRef.current?.click() - } - - const handleRemoveAttachment = (index: number) => { - setAttachments((prev) => prev.filter((_, itemIndex) => itemIndex !== index)) - } - - const appendImageFiles = async (files: readonly File[]) => { - if (!canInput || files.length === 0) { - return - } - - const nextAttachments = await buildChatImageAttachments(files, t) - if (nextAttachments.length === 0) { - return - } - - setAttachments((prev) => [...prev, ...nextAttachments]) - } - - const handleImageSelection = async (event: ChangeEvent) => { - const files = Array.from(event.target.files ?? []) - event.target.value = "" - - if (files.length === 0) { - return - } - - await appendImageFiles(files) - } - - const resetDragState = () => { - dragDepthRef.current = 0 - setIsDragActive(false) - } - - const handleComposerPaste = async ( - event: ClipboardEvent, - ) => { - const files = getTransferredFiles(event.clipboardData) - if (files.length === 0) { - return - } - - await appendImageFiles(files) - } - - const handleComposerDragEnter = (event: DragEvent) => { - if (!hasFileTransfer(event.dataTransfer)) { - return - } - - event.preventDefault() - if (!canInput) { - return - } - dragDepthRef.current += 1 - setIsDragActive(true) - } - - const handleComposerDragLeave = (event: DragEvent) => { - if (!hasFileTransfer(event.dataTransfer)) { - return - } - - event.preventDefault() - if (!canInput) { - resetDragState() - return - } - dragDepthRef.current = Math.max(0, dragDepthRef.current - 1) - if (dragDepthRef.current === 0) { - setIsDragActive(false) - } - } - - const handleComposerDragOver = (event: DragEvent) => { - if (!hasFileTransfer(event.dataTransfer)) { - return - } - - event.preventDefault() - event.dataTransfer.dropEffect = canInput ? "copy" : "none" - } - - const handleComposerDrop = async (event: DragEvent) => { - if (!hasFileTransfer(event.dataTransfer)) { - return - } - - event.preventDefault() - const files = getTransferredFiles(event.dataTransfer) - resetDragState() - - if (!canInput || files.length === 0) { - return - } - - await appendImageFiles(files) - } - - const canSubmit = - canInput && (Boolean(input.trim()) || attachments.length > 0) - - return ( -
- - ) - } - > -
- - {t("chat.showAssistantDetails")} - - -
- - - - { - if (open) { - void loadSessions(true) - } - }} - onSwitchSession={switchSession} - onDeleteSession={handleDeleteSession} - /> -
- -
-
- {messages.length === 0 && !isTyping && ( - - )} - - {messages.map((msg) => { - if ( - !shouldShowAssistantMessage(assistantDetailVisibility, msg.kind) - ) { - return null - } - - return ( -
- {msg.role === "assistant" ? ( - - ) : ( - - )} -
- ) - })} - - {isTyping && } -
-
- - - - { - if (sendMessage({ content: "/context", attachments: [] })) { - setInput("") - } - }} - inputDisabledReason={inputDisabledReason} - canSend={canSubmit} - isDragActive={isDragActive} - contextUsage={contextUsage} - /> -
- ) -} diff --git a/web/frontend/src/components/chat/context-usage-ring.tsx b/web/frontend/src/components/chat/context-usage-ring.tsx deleted file mode 100644 index 000bcb4d..00000000 --- a/web/frontend/src/components/chat/context-usage-ring.tsx +++ /dev/null @@ -1,186 +0,0 @@ -import { IconArrowRight } from "@tabler/icons-react" -import { useEffect, useRef, useState } from "react" -import { useTranslation } from "react-i18next" - -import type { ContextUsage } from "@/store/chat" - -interface ContextUsageRingProps { - usage: ContextUsage - onDetailClick?: () => void -} - -function formatTokens(n: number): string { - if (n >= 1000) return `${(n / 1000).toFixed(1)}k` - return String(n) -} - -export function ContextUsageRing({ - usage, - onDetailClick, -}: ContextUsageRingProps) { - const { t } = useTranslation() - const [intent, setIntent] = useState(false) // user wants open - const [visible, setVisible] = useState(false) // DOM mounted - const [animated, setAnimated] = useState(false) // CSS target state - const [cooldown, setCooldown] = useState(false) - const containerRef = useRef(null) - const timerRef = useRef>(null) - const hoverIntent = useRef>(null) - const closeTimer = useRef>(null) - - useEffect(() => { - if (intent) { - // Mount first, animate in on next frame - if (closeTimer.current) clearTimeout(closeTimer.current) - setVisible(true) - requestAnimationFrame(() => { - requestAnimationFrame(() => setAnimated(true)) - }) - } else if (visible) { - // Animate out, then unmount - setAnimated(false) - closeTimer.current = setTimeout(() => setVisible(false), 150) - } - }, [intent, visible]) - - useEffect(() => { - return () => { - if (timerRef.current) clearTimeout(timerRef.current) - if (hoverIntent.current) clearTimeout(hoverIntent.current) - if (closeTimer.current) clearTimeout(closeTimer.current) - } - }, []) - - const percent = Math.min(usage.used_percent, 100) - const radius = 8 - const circumference = 2 * Math.PI * radius - const offset = circumference - (percent / 100) * circumference - const barPercent = Math.min(percent, 100) - - const handleDetail = () => { - if (cooldown || !onDetailClick) return - setCooldown(true) - onDetailClick() - setIntent(false) - timerRef.current = setTimeout(() => setCooldown(false), 1000) - } - - // Desktop: hover to open, mouse leave to close (with small delay) - const handleMouseEnter = () => { - if (hoverIntent.current) clearTimeout(hoverIntent.current) - setIntent(true) - } - - const handleMouseLeave = () => { - hoverIntent.current = setTimeout(() => setIntent(false), 150) - } - - // Mobile: tap to toggle (preventDefault suppresses synthetic mouseenter) - const handleTouchStart = (e: React.TouchEvent) => { - e.preventDefault() - setIntent((v) => !v) - } - - return ( -
- - - {visible && ( -
-
- -
- - {t("chat.contextTitle")} - - - {formatTokens(usage.used_tokens)} /{" "} - {formatTokens(usage.compress_at_tokens)} - -
-
-
-
- -
- {usage.history_tokens != null && usage.history_tokens > 0 && ( -
- History - - {formatTokens(usage.history_tokens)} - -
- )} -
- {t("chat.contextCompressAt")} - - {formatTokens(usage.compress_at_tokens)} - -
- {usage.summarize_at_tokens != null && usage.summarize_at_tokens > 0 && ( -
- {t("chat.contextSummarizeAt")} - - {formatTokens(usage.summarize_at_tokens)} - -
- )} -
- - -
- )} -
- ) -} diff --git a/web/frontend/src/components/chat/message-code-block.tsx b/web/frontend/src/components/chat/message-code-block.tsx deleted file mode 100644 index 79a3706a..00000000 --- a/web/frontend/src/components/chat/message-code-block.tsx +++ /dev/null @@ -1,249 +0,0 @@ -import { - IconCheck, - IconChevronDown, - IconCopy, -} from "@tabler/icons-react" -import { useAtom } from "jotai" -import hljs from "highlight.js/lib/core" -import json from "highlight.js/lib/languages/json" -import { - type ComponentProps, - type CSSProperties, - type ReactNode, - useState, -} from "react" -import { useTranslation } from "react-i18next" - -import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard" -import { cn } from "@/lib/utils" -import { codeBlockWrapAtom } from "@/store/code-block" - -import { - extractCodeBlockFromPreNode, - extractCodeBlockRenderState, - type MarkdownNode, - splitCodeIntoLines, - splitHighlightedHtmlIntoLines, - splitRenderedCodeContentIntoLines, - trimTrailingEmptyRenderedCodeLine, - trimTrailingEmptyStringLine, -} from "./message-code-block.utils" - -import { Button } from "@/components/ui/button" - -const CODE_LABEL_FONT_FAMILY = - 'ui-monospace, "SFMono-Regular", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", monospace' - -hljs.registerLanguage("json", json) - -interface MessageCodeBlockProps { - code: string - language?: string | null - label?: string - className?: string - bodyClassName?: string - children?: ReactNode - trimTrailingEmptyLine?: boolean -} - -interface MarkdownCodeBlockProps extends ComponentProps<"pre"> { - node?: MarkdownNode -} - -function getHighlightedHtml(code: string, language?: string | null) { - if (!language) { - return null - } - - try { - return hljs.highlight(code, { language }).value - } catch { - return null - } -} - -export function MessageCodeBlock({ - code, - language = null, - label, - className, - bodyClassName, - children, - trimTrailingEmptyLine = false, -}: MessageCodeBlockProps) { - const { t } = useTranslation() - const { copy, isCopied } = useCopyToClipboard() - const [wrapLongLines, setWrapLongLines] = useAtom(codeBlockWrapAtom) - const [isExpanded, setIsExpanded] = useState(true) - const blockLabel = - label ?? - (language - ? language.toLocaleLowerCase() - : t("chat.codeLabel").toLocaleLowerCase()) - const copyLabel = isCopied ? t("chat.copiedLabel") : t("chat.copyCode") - const expandLabel = isExpanded ? t("chat.collapseCode") : t("chat.expandCode") - const wrapLabel = wrapLongLines - ? t("chat.disableCodeWrap") - : t("chat.enableCodeWrap") - const renderedCodeState = children - ? extractCodeBlockRenderState(children) - : { - renderedContent: null, - className: undefined, - } - const highlightedHtml = !children ? getHighlightedHtml(code, language) : null - const highlightedLines = highlightedHtml - ? splitHighlightedHtmlIntoLines(highlightedHtml) - : null - const codeLines = children - ? (trimTrailingEmptyLine - ? trimTrailingEmptyRenderedCodeLine( - splitRenderedCodeContentIntoLines(renderedCodeState.renderedContent), - ) - : splitRenderedCodeContentIntoLines(renderedCodeState.renderedContent)) - : (trimTrailingEmptyLine - ? trimTrailingEmptyStringLine( - highlightedLines ?? splitCodeIntoLines(code), - ) - : (highlightedLines ?? splitCodeIntoLines(code))) - const lineNumberWidth = `${String(codeLines.length).length + 1}ch` - - return ( -
-
- - {blockLabel} - -
- - - -
-
- - {isExpanded && ( -
-          
-            {codeLines.map((line, index) => (
-              
-                
-                  {index + 1}
-                
-                {!children && highlightedLines ? (
-                  
-                ) : (
-                  
-                    {line}
-                  
-                )}
-              
-            ))}
-          
-        
- )} -
- ) -} - -export function MarkdownCodeBlock({ - children, - className, - node, -}: MarkdownCodeBlockProps) { - const { code, language } = extractCodeBlockFromPreNode(node) - - return ( - - {children} - - ) -} diff --git a/web/frontend/src/components/chat/message-code-block.utils.ts b/web/frontend/src/components/chat/message-code-block.utils.ts deleted file mode 100644 index 40e76a2a..00000000 --- a/web/frontend/src/components/chat/message-code-block.utils.ts +++ /dev/null @@ -1,338 +0,0 @@ -import { - Children, - cloneElement, - Fragment, - isValidElement, - type ReactNode, -} from "react" - -export interface MarkdownNode { - type?: string - value?: string - tagName?: string - properties?: Record - children?: MarkdownNode[] -} - -export function toClassNameTokens(className: unknown): string[] { - if (typeof className === "string") { - return className.split(/\s+/).filter(Boolean) - } - - if (Array.isArray(className)) { - return className.filter( - (token): token is string => typeof token === "string" && token.length > 0, - ) - } - - return [] -} - -function findFirstDescendantByTagName( - node: MarkdownNode | undefined, - tagName: string, -): MarkdownNode | undefined { - if (!node) { - return undefined - } - - if (node.tagName === tagName) { - return node - } - - if (!Array.isArray(node.children)) { - return undefined - } - - for (const child of node.children) { - const match = findFirstDescendantByTagName(child, tagName) - if (match) { - return match - } - } - - return undefined -} - -export function extractTextFromMarkdownNode( - node: MarkdownNode | undefined, -): string { - if (!node) { - return "" - } - - if (node.type === "text") { - return typeof node.value === "string" ? node.value : "" - } - - if (!Array.isArray(node.children)) { - return "" - } - - return node.children.map(extractTextFromMarkdownNode).join("") -} - -export function extractCodeBlockLanguage(className: unknown): string | null { - const languageToken = toClassNameTokens(className).find( - (token) => token.startsWith("language-") && token.length > "language-".length, - ) - - return languageToken ? languageToken.slice("language-".length) : null -} - -export function stripSingleTrailingLineBreak(value: string): string { - return value.replace(/\r?\n$/, "") -} - -export function extractCodeBlockFromPreNode(node: MarkdownNode | undefined): { - code: string - language: string | null -} { - const codeNode = findFirstDescendantByTagName(node, "code") - - return { - code: stripSingleTrailingLineBreak(extractTextFromMarkdownNode(codeNode ?? node)), - language: extractCodeBlockLanguage(codeNode?.properties?.className), - } -} - -export function extractCodeBlockRenderState(children: ReactNode): { - renderedContent: ReactNode - className: string | undefined -} { - const childNodes = Children.toArray(children) - const codeChild = childNodes.find( - (child) => - isValidElement<{ children?: ReactNode; className?: unknown }>(child) && - typeof child.type === "string" && - child.type === "code", - ) - - if ( - isValidElement<{ children?: ReactNode; className?: unknown }>(codeChild) - ) { - const classNameTokens = toClassNameTokens(codeChild.props.className) - return { - renderedContent: codeChild.props.children, - className: - classNameTokens.length > 0 ? classNameTokens.join(" ") : undefined, - } - } - - return { - renderedContent: children, - className: undefined, - } -} - -function mergeNodeLineGroups( - currentLines: Node[][], - nextLines: Node[][], -): Node[][] { - if (nextLines.length === 0) { - return currentLines - } - - const mergedLines = currentLines.map((line) => [...line]) - mergedLines[mergedLines.length - 1].push(...nextLines[0]) - - for (const line of nextLines.slice(1)) { - mergedLines.push([...line]) - } - - return mergedLines -} - -function splitDomNodeIntoLines(node: Node, ownerDocument: Document): Node[][] { - if (node.nodeType === Node.TEXT_NODE) { - return (node.textContent ?? "").split("\n").map((line) => - line.length > 0 ? [ownerDocument.createTextNode(line)] : [], - ) - } - - if (node.nodeType !== Node.ELEMENT_NODE) { - return [[]] - } - - const element = node as Element - if (element.tagName.toLowerCase() === "br") { - return [ - [], - [], - ] - } - - const childLines = splitHighlightedHtmlIntoNodeLines( - Array.from(element.childNodes), - ownerDocument, - ) - - return childLines.map((lineChildren) => { - const clonedElement = element.cloneNode(false) - for (const child of lineChildren) { - clonedElement.appendChild(child) - } - - return [clonedElement] - }) -} - -function splitHighlightedHtmlIntoNodeLines( - nodes: Node[], - ownerDocument: Document, -): Node[][] { - let lines: Node[][] = [[]] - - for (const node of nodes) { - lines = mergeNodeLineGroups( - lines, - splitDomNodeIntoLines(node, ownerDocument), - ) - } - - return lines -} - -export function splitCodeIntoLines(code: string): string[] { - return code.split("\n") -} - -export function splitHighlightedHtmlIntoLines(highlightedHtml: string): string[] { - if (typeof document === "undefined") { - return splitCodeIntoLines(highlightedHtml) - } - - const container = document.createElement("div") - container.innerHTML = highlightedHtml - - return splitHighlightedHtmlIntoNodeLines( - Array.from(container.childNodes), - document, - ).map((lineNodes) => { - const lineContainer = document.createElement("div") - for (const node of lineNodes) { - lineContainer.appendChild(node) - } - - return lineContainer.innerHTML - }) -} - -export function trimTrailingEmptyStringLine(lines: string[]): string[] { - if (lines.length > 1 && lines[lines.length - 1] === "") { - return lines.slice(0, -1) - } - - return lines -} - -function isEmptyRenderedCodeNode(node: ReactNode): boolean { - if (node === null || node === undefined || typeof node === "boolean") { - return true - } - - if (typeof node === "string" || typeof node === "number") { - return String(node).length === 0 - } - - if (Array.isArray(node)) { - return node.every(isEmptyRenderedCodeNode) - } - - if (!isValidElement<{ children?: ReactNode }>(node)) { - return false - } - - return Children.toArray(node.props.children).every(isEmptyRenderedCodeNode) -} - -export function trimTrailingEmptyRenderedCodeLine( - lines: ReactNode[][], -): ReactNode[][] { - if ( - lines.length > 1 && - lines[lines.length - 1].every(isEmptyRenderedCodeNode) - ) { - return lines.slice(0, -1) - } - - return lines -} - -function mergeReactLineGroups( - currentLines: ReactNode[][], - nextLines: ReactNode[][], -): ReactNode[][] { - if (nextLines.length === 0) { - return currentLines - } - - const mergedLines = currentLines.map((line) => [...line]) - mergedLines[mergedLines.length - 1].push(...nextLines[0]) - - for (const line of nextLines.slice(1)) { - mergedLines.push([...line]) - } - - return mergedLines -} - -function splitTextNodeIntoLines(value: string | number): ReactNode[][] { - return String(value).split("\n").map((line) => (line.length > 0 ? [line] : [])) -} - -function splitReactNodeIntoLines(node: ReactNode): ReactNode[][] { - if (node === null || node === undefined || typeof node === "boolean") { - return [[]] - } - - if (typeof node === "string" || typeof node === "number") { - return splitTextNodeIntoLines(node) - } - - if (Array.isArray(node)) { - return splitRenderedCodeContentIntoLines(node) - } - - if (!isValidElement<{ children?: ReactNode }>(node)) { - return [[node]] - } - - if (node.type === Fragment) { - return splitRenderedCodeContentIntoLines(Children.toArray(node.props.children)) - } - - if (typeof node.type === "string" && node.type === "br") { - return [ - [], - [], - ] - } - - const childLines = splitRenderedCodeContentIntoLines( - Children.toArray(node.props.children), - ) - - return childLines.map((lineChildren, lineIndex) => [ - cloneElement( - node, - { - key: `${node.key ?? "code-line"}-${lineIndex}`, - }, - ...lineChildren, - ), - ]) -} - -export function splitRenderedCodeContentIntoLines( - content: ReactNode, -): ReactNode[][] { - const contentNodes = Array.isArray(content) ? content : [content] - let lines: ReactNode[][] = [[]] - - for (const node of contentNodes) { - lines = mergeReactLineGroups(lines, splitReactNodeIntoLines(node)) - } - - return lines -} diff --git a/web/frontend/src/components/chat/model-selector.tsx b/web/frontend/src/components/chat/model-selector.tsx deleted file mode 100644 index 7be01c86..00000000 --- a/web/frontend/src/components/chat/model-selector.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { useTranslation } from "react-i18next" - -import type { ModelInfo } from "@/api/models" -import { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectLabel, - SelectSeparator, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" - -interface ModelSelectorProps { - defaultModelName: string - apiKeyModels: ModelInfo[] - oauthModels: ModelInfo[] - localModels: ModelInfo[] - disabled?: boolean - onValueChange: (modelName: string) => void -} - -export function ModelSelector({ - defaultModelName, - apiKeyModels, - oauthModels, - localModels, - disabled = false, - onValueChange, -}: ModelSelectorProps) { - const { t } = useTranslation() - const rawDefaultModel = - defaultModelName && - ![...apiKeyModels, ...oauthModels, ...localModels].some( - (model) => model.model_name === defaultModelName, - ) - ? defaultModelName - : "" - - return ( - - ) -} diff --git a/web/frontend/src/components/chat/session-history-menu.tsx b/web/frontend/src/components/chat/session-history-menu.tsx deleted file mode 100644 index 3ec1a5ed..00000000 --- a/web/frontend/src/components/chat/session-history-menu.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { IconHistory, IconTrash } from "@tabler/icons-react" -import dayjs from "dayjs" -import type { RefObject } from "react" -import { useTranslation } from "react-i18next" - -import type { SessionSummary } from "@/api/sessions" -import { Button } from "@/components/ui/button" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" -import { ScrollArea } from "@/components/ui/scroll-area" - -interface SessionHistoryMenuProps { - sessions: SessionSummary[] - activeSessionId: string - hasMore: boolean - loadError: boolean - loadErrorMessage: string - observerRef: RefObject - onOpenChange: (open: boolean) => void - onSwitchSession: (sessionId: string) => void - onDeleteSession: (sessionId: string) => void -} - -export function SessionHistoryMenu({ - sessions, - activeSessionId, - hasMore, - loadError, - loadErrorMessage, - observerRef, - onOpenChange, - onSwitchSession, - onDeleteSession, -}: SessionHistoryMenuProps) { - const { t } = useTranslation() - - return ( - - - - - - - {loadError && ( - - - {loadErrorMessage} - - - )} - {sessions.length === 0 && !loadError ? ( - - - {t("chat.noHistory")} - - - ) : ( - sessions.map((session) => ( - onSwitchSession(session.id)} - > - - {session.title} - - - {t("chat.messagesCount", { - count: session.message_count, - })}{" "} - · {dayjs(session.updated).fromNow()} - - - - )) - )} - {hasMore && sessions.length > 0 && ( -
- - {t("chat.loadingMore")} - -
- )} -
-
-
- ) -} diff --git a/web/frontend/src/components/chat/typing-indicator.tsx b/web/frontend/src/components/chat/typing-indicator.tsx deleted file mode 100644 index df138553..00000000 --- a/web/frontend/src/components/chat/typing-indicator.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { useEffect, useState } from "react" -import { useTranslation } from "react-i18next" - -export function TypingIndicator() { - const { t } = useTranslation() - const thinkingSteps = [ - t("chat.thinking.step1"), - t("chat.thinking.step2"), - t("chat.thinking.step3"), - t("chat.thinking.step4"), - ] - const [stepIndex, setStepIndex] = useState(0) - - useEffect(() => { - const stepsCount = thinkingSteps.length - const interval = setInterval(() => { - setStepIndex((prev) => (prev + 1) % stepsCount) - }, 3000) - return () => clearInterval(interval) - }, [thinkingSteps.length]) - - return ( -
-
-
- - - -
- -
-
-
- -

- {thinkingSteps[stepIndex]} -

-
-
- ) -} diff --git a/web/frontend/src/components/chat/user-message.tsx b/web/frontend/src/components/chat/user-message.tsx deleted file mode 100644 index 9a05c961..00000000 --- a/web/frontend/src/components/chat/user-message.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { IconCheck, IconCopy } from "@tabler/icons-react" -import { useTranslation } from "react-i18next" - -import { Button } from "@/components/ui/button" -import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard" -import { formatMessageTime } from "@/hooks/use-pico-chat" -import { cn } from "@/lib/utils" -import type { ChatAttachment } from "@/store/chat" - -interface UserMessageProps { - content: string - attachments?: ChatAttachment[] - timestamp?: string | number -} - -export function UserMessage({ - content, - attachments = [], - timestamp = "", -}: UserMessageProps) { - const { t } = useTranslation() - const { copy, isCopied } = useCopyToClipboard() - const hasText = content.trim().length > 0 - const isCommand = content.trim().startsWith("/") - const imageAttachments = attachments.filter( - (attachment) => attachment.type === "image", - ) - const copyMessageLabel = isCopied - ? t("chat.copiedLabel") - : t("chat.copyMessage") - const formattedTimestamp = - timestamp !== "" ? formatMessageTime(timestamp) : "" - - return ( -
- {imageAttachments.length > 0 && ( -
- {imageAttachments.map((attachment, index) => ( - {attachment.filename - ))} -
- )} - - {hasText && ( -
-
- {isCommand ? ( -
- - ❯ - - {content} -
- ) : ( - content - )} -
- -
- )} - - {formattedTimestamp && ( - - {formattedTimestamp} - - )} -
- ) -} diff --git a/web/frontend/src/components/config-change-notice.tsx b/web/frontend/src/components/config-change-notice.tsx deleted file mode 100644 index 27e5eed7..00000000 --- a/web/frontend/src/components/config-change-notice.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { - IconAlertCircle, - IconDeviceFloppy, - IconRefresh, -} from "@tabler/icons-react" - -import { cn } from "@/lib/utils" - -interface ConfigChangeNoticeProps { - kind: "save" | "restart" - title: string - description?: string - className?: string -} - -export function ConfigChangeNotice({ - kind, - title, - description, - className, -}: ConfigChangeNoticeProps) { - const Icon = - kind === "restart" - ? IconRefresh - : kind === "save" - ? IconDeviceFloppy - : IconAlertCircle - - return ( -
- -
-

{title}

- {description && ( -

{description}

- )} -
-
- ) -} diff --git a/web/frontend/src/components/config/config-page.tsx b/web/frontend/src/components/config/config-page.tsx deleted file mode 100644 index e0174e2c..00000000 --- a/web/frontend/src/components/config/config-page.tsx +++ /dev/null @@ -1,872 +0,0 @@ -import { IconCode, IconDeviceFloppy, IconTag } from "@tabler/icons-react" -import { useQuery, useQueryClient } from "@tanstack/react-query" -import { Link } from "@tanstack/react-router" -import { useEffect, useState } from "react" -import { useTranslation } from "react-i18next" -import { toast } from "sonner" - -import { patchAppConfig, resetAppConfig } from "@/api/channels" -import { launcherFetch } from "@/api/http" -import { postLauncherDashboardSetup } from "@/api/launcher-auth" -import { - getAutoStartStatus, - getLauncherConfig, - getSystemVersionInfo, - setAutoStartEnabled as updateAutoStartEnabled, - setLauncherConfig as updateLauncherConfig, -} from "@/api/system" -import { ConfigChangeNotice } from "@/components/config-change-notice" -import { - AgentDefaultsSection, - CronSection, - DevicesSection, - EvolutionSection, - ExecSection, - LauncherSection, - MCPSection, - RuntimeSection, -} from "@/components/config/config-sections" -import { - type CoreConfigForm, - EMPTY_FORM, - EMPTY_LAUNCHER_FORM, - type LauncherForm, - type MCPServerForm, - type TurnProfileForm, - buildFormFromConfig, - parseCIDRText, - parseFloatField, - parseIntField, - parseJSONObjectField, - parseMultilineList, -} from "@/components/config/form-model" -import { PageHeader } from "@/components/page-header" -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from "@/components/ui/alert-dialog" -import { Badge } from "@/components/ui/badge" -import { Button } from "@/components/ui/button" -import { showSaveSuccessOrRestartToast } from "@/lib/restart-required" -import { refreshGatewayState } from "@/store/gateway" - -function buildStringMapMergePatch( - next: Record, - previous: Record, -): Record { - const patch: Record = { ...next } - - for (const key of Object.keys(previous)) { - if (!(key in next)) { - patch[key] = null - } - } - - return patch -} - -function buildTurnProfilePatch( - profile: TurnProfileForm, -): Record { - const result: Record = { - enabled: profile.enabled, - history: { mode: profile.historyMode }, - system_prompt: { mode: profile.systemPromptMode }, - skills: { mode: profile.skillsMode }, - tools: { mode: profile.toolsMode }, - } - - if (profile.skillsMode === "custom") { - result.skills = { - mode: "custom", - allow: parseMultilineList(profile.skillsAllowText), - } - } - if (profile.toolsMode === "custom") { - result.tools = { - mode: "custom", - allow: parseMultilineList(profile.toolsAllowText), - } - } - - return result -} - -export function ConfigPage() { - const { t } = useTranslation() - const queryClient = useQueryClient() - const [form, setForm] = useState(EMPTY_FORM) - const [baseline, setBaseline] = useState(EMPTY_FORM) - const [launcherForm, setLauncherForm] = - useState(EMPTY_LAUNCHER_FORM) - const [launcherBaseline, setLauncherBaseline] = - useState(EMPTY_LAUNCHER_FORM) - const [autoStartEnabled, setAutoStartEnabled] = useState(false) - const [autoStartBaseline, setAutoStartBaseline] = useState(false) - const [saving, setSaving] = useState(false) - const [showFactoryResetDialog, setShowFactoryResetDialog] = useState(false) - - const { data, isLoading, error } = useQuery({ - queryKey: ["config"], - queryFn: async () => { - const controller = new AbortController() - const timer = setTimeout(() => controller.abort(), 5000) - try { - const res = await launcherFetch("/api/config", { - signal: controller.signal, - }) - if (!res.ok) { - throw new Error("Failed to load config") - } - return res.json() - } finally { - clearTimeout(timer) - } - }, - }) - - const { data: launcherConfig, isLoading: isLauncherLoading } = useQuery({ - queryKey: ["system", "launcher-config"], - queryFn: getLauncherConfig, - }) - - const { data: versionInfo } = useQuery({ - queryKey: ["system", "version"], - queryFn: getSystemVersionInfo, - staleTime: 5 * 60 * 1000, - }) - - const { - data: autoStartStatus, - isLoading: isAutoStartLoading, - error: autoStartError, - } = useQuery({ - queryKey: ["system", "autostart"], - queryFn: getAutoStartStatus, - }) - - useEffect(() => { - if (!data) return - const parsed = buildFormFromConfig(data) - setForm(parsed) - setBaseline(parsed) - }, [data]) - - useEffect(() => { - if (!launcherConfig) return - const parsed: LauncherForm = { - port: String(launcherConfig.port), - publicAccess: launcherConfig.public, - allowedCIDRsText: (launcherConfig.allowed_cidrs ?? []).join("\n"), - allowLocalhostBypass: launcherConfig.allow_localhost_bypass ?? true, - trustedProxyCIDRsText: (launcherConfig.trusted_proxy_cidrs ?? []).join( - "\n", - ), - dashboardPassword: "", - dashboardPasswordConfirm: "", - } - setLauncherForm(parsed) - setLauncherBaseline(parsed) - }, [launcherConfig]) - - useEffect(() => { - if (!autoStartStatus) return - setAutoStartEnabled(autoStartStatus.enabled) - setAutoStartBaseline(autoStartStatus.enabled) - }, [autoStartStatus]) - - const configDirty = JSON.stringify(form) !== JSON.stringify(baseline) - const launcherSettingsDirty = - launcherForm.port !== launcherBaseline.port || - launcherForm.publicAccess !== launcherBaseline.publicAccess || - launcherForm.allowedCIDRsText !== launcherBaseline.allowedCIDRsText || - launcherForm.allowLocalhostBypass !== - launcherBaseline.allowLocalhostBypass || - launcherForm.trustedProxyCIDRsText !== - launcherBaseline.trustedProxyCIDRsText - const launcherPasswordDirty = - launcherForm.dashboardPassword.trim() !== "" || - launcherForm.dashboardPasswordConfirm.trim() !== "" - const launcherDirty = launcherSettingsDirty || launcherPasswordDirty - const autoStartDirty = autoStartEnabled !== autoStartBaseline - const isDirty = configDirty || launcherDirty || autoStartDirty - - const autoStartSupported = autoStartStatus?.supported !== false - const autoStartHint = autoStartError - ? t("pages.config.autostart_load_error") - : !autoStartSupported - ? t("pages.config.autostart_unsupported") - : t("pages.config.autostart_hint") - - const updateField = ( - key: K, - value: CoreConfigForm[K], - ) => { - setForm((prev) => ({ ...prev, [key]: value })) - } - - const updateLauncherField = ( - key: K, - value: LauncherForm[K], - ) => { - setLauncherForm((prev) => ({ ...prev, [key]: value })) - } - - const handleMCPServerAdd = () => { - const nextIndex = form.mcpServers.length + 1 - const server: MCPServerForm = { - id: `mcp-${Date.now()}-${nextIndex}`, - name: "", - enabled: true, - deferredOverride: null, - type: "stdio", - url: "", - command: "", - argsText: "", - envText: "{}", - envFile: "", - headersText: "{}", - } - updateField("mcpServers", [...form.mcpServers, server]) - } - - const handleMCPServerRemove = (id: string) => { - updateField( - "mcpServers", - form.mcpServers.filter((server) => server.id !== id), - ) - } - - const handleMCPServerFieldChange = ( - id: string, - key: K, - value: MCPServerForm[K], - ) => { - updateField( - "mcpServers", - form.mcpServers.map((server) => - server.id === id ? { ...server, [key]: value } : server, - ), - ) - } - - const handleTurnProfileFieldChange = ( - key: K, - value: TurnProfileForm[K], - ) => { - updateField("turnProfile", { ...form.turnProfile, [key]: value }) - } - - const handleReset = () => { - setForm(baseline) - setLauncherForm(launcherBaseline) - setAutoStartEnabled(autoStartBaseline) - toast.info(t("pages.config.reset_success")) - } - - const handleFactoryReset = async () => { - try { - await resetAppConfig() - const fresh = await launcherFetch("/api/config").then((r) => r.json()) - const parsed = buildFormFromConfig(fresh) - setForm(parsed) - setBaseline(parsed) - await queryClient.invalidateQueries({ queryKey: ["config"] }) - await refreshGatewayState() - toast.success(t("pages.config.factory_reset_success")) - } catch (err) { - toast.error( - err instanceof Error - ? err.message - : t("pages.config.factory_reset_error"), - ) - } finally { - setShowFactoryResetDialog(false) - } - } - - const handleSave = async () => { - try { - setSaving(true) - const password = launcherForm.dashboardPassword.trim() - const confirm = launcherForm.dashboardPasswordConfirm.trim() - if (launcherPasswordDirty) { - if (!password) { - throw new Error(t("pages.config.dashboard_password_required")) - } - if (password !== confirm) { - throw new Error(t("pages.config.dashboard_password_mismatch")) - } - if (Array.from(password).length < 8) { - throw new Error(t("pages.config.dashboard_password_min_length")) - } - } - - if (configDirty) { - const workspace = form.workspace.trim() - const dmScope = form.dmScope.trim() - - if (!workspace) { - throw new Error("Workspace path is required.") - } - if (!dmScope) { - throw new Error("Session scope is required.") - } - - if ( - form.mcpEnabled && - form.mcpDiscoveryEnabled && - !form.mcpDiscoveryUseBM25 && - !form.mcpDiscoveryUseRegex - ) { - throw new Error( - "MCP discovery requires at least one search method (BM25 or regex).", - ) - } - - const maxTokens = parseIntField(form.maxTokens, "Max tokens", { - min: 1, - }) - const contextWindow = form.contextWindow.trim() - ? parseIntField(form.contextWindow, "Context window", { min: 1 }) - : undefined - const maxToolIterations = parseIntField( - form.maxToolIterations, - "Max tool iterations", - { min: 1 }, - ) - const toolFeedbackMaxArgsLength = parseIntField( - form.toolFeedbackMaxArgsLength, - "Tool feedback max args length", - { min: 0 }, - ) - const summarizeMessageThreshold = parseIntField( - form.summarizeMessageThreshold, - "Summarize message threshold", - { min: 1 }, - ) - const summarizeTokenPercent = parseIntField( - form.summarizeTokenPercent, - "Summarize token percent", - { min: 1, max: 100 }, - ) - const turnProfile = buildTurnProfilePatch(form.turnProfile) - const heartbeatInterval = parseIntField( - form.heartbeatInterval, - "Heartbeat interval", - { min: 1 }, - ) - const cronExecTimeoutMinutes = parseIntField( - form.cronExecTimeoutMinutes, - "Cron exec timeout", - { min: 0 }, - ) - const evolutionMinTaskCount = parseIntField( - form.evolutionMinTaskCount, - "Evolution minimum task count", - { min: 1 }, - ) - const evolutionMinSuccessRatio = parseFloatField( - form.evolutionMinSuccessRatio, - "Evolution minimum success ratio", - { min: 0.01, max: 1 }, - ) - const mcpDiscoveryValidationEnabled = - form.mcpEnabled && form.mcpDiscoveryEnabled - const mcpDiscoveryPatch: Record = { - enabled: form.mcpDiscoveryEnabled, - use_bm25: form.mcpDiscoveryUseBM25, - use_regex: form.mcpDiscoveryUseRegex, - } - - if (mcpDiscoveryValidationEnabled) { - mcpDiscoveryPatch.ttl = parseIntField( - form.mcpDiscoveryTTL, - "MCP discovery ttl", - { - min: 1, - }, - ) - mcpDiscoveryPatch.max_search_results = parseIntField( - form.mcpDiscoveryMaxSearchResults, - "MCP discovery max search results", - { min: 1 }, - ) - } - const execConfigPatch: Record = { - enabled: form.execEnabled, - } - - let mcpServersPatch: Record | null> = {} - if (form.mcpEnabled) { - const baselineServerNames = new Set( - baseline.mcpServers - .map((server) => server.name.trim()) - .filter((name) => name !== ""), - ) - - const normalizedServers = form.mcpServers - .map((server) => ({ - ...server, - name: server.name.trim(), - url: server.url.trim(), - command: server.command.trim(), - envFile: server.envFile.trim(), - })) - .filter((server) => server.name !== "") - - const serverNameCounts = new Map() - for (const server of normalizedServers) { - serverNameCounts.set( - server.name, - (serverNameCounts.get(server.name) ?? 0) + 1, - ) - } - - const duplicateNames = Array.from(serverNameCounts.entries()) - .filter(([, count]) => count > 1) - .map(([name]) => name) - .sort((a, b) => a.localeCompare(b)) - - if (duplicateNames.length > 0) { - throw new Error( - `MCP server names must be unique. Duplicates: ${duplicateNames.join(", ")}.`, - ) - } - - const currentServerNames = new Set( - normalizedServers.map((server) => server.name), - ) - - const removedServerEntries = Array.from(baselineServerNames) - .filter((name) => !currentServerNames.has(name)) - .map((name) => [name, null] as const) - - const baselineServersByName = new Map( - baseline.mcpServers - .map((server) => ({ - ...server, - name: server.name.trim(), - })) - .filter((server) => server.name !== "") - .map((server) => [server.name, server] as const), - ) - - const upsertServerEntries = normalizedServers.map((server) => { - const deferredPatch = { deferred: server.deferredOverride } - const baselineServer = baselineServersByName.get(server.name) - const shouldValidateServer = server.enabled - - if (server.type !== "stdio") { - if (shouldValidateServer && server.url === "") { - throw new Error(`MCP server ${server.name} requires a URL.`) - } - - if (shouldValidateServer) { - try { - const parsedURL = new URL(server.url) - if ( - parsedURL.protocol !== "http:" && - parsedURL.protocol !== "https:" - ) { - throw new Error("invalid protocol") - } - } catch { - throw new Error( - `MCP server ${server.name} requires a valid HTTP(S) URL.`, - ) - } - } - - const baselineHeaders = baselineServer - ? parseJSONObjectField( - baselineServer.headersText, - `Saved MCP server ${server.name} headers`, - ) - : {} - - return [ - server.name, - { - ...deferredPatch, - enabled: server.enabled, - type: server.type, - url: server.url, - headers: buildStringMapMergePatch( - shouldValidateServer - ? parseJSONObjectField( - server.headersText, - `MCP server ${server.name} headers`, - ) - : baselineHeaders, - baselineHeaders, - ), - command: null, - args: null, - env: null, - env_file: null, - }, - ] as const - } - - if (shouldValidateServer && server.command === "") { - throw new Error(`MCP server ${server.name} requires a command.`) - } - - const baselineEnv = baselineServer - ? parseJSONObjectField( - baselineServer.envText, - `Saved MCP server ${server.name} env`, - ) - : {} - - return [ - server.name, - { - ...deferredPatch, - enabled: server.enabled, - type: "stdio", - command: server.command, - args: parseMultilineList(server.argsText), - env: buildStringMapMergePatch( - shouldValidateServer - ? parseJSONObjectField( - server.envText, - `MCP server ${server.name} env`, - ) - : baselineEnv, - baselineEnv, - ), - env_file: server.envFile === "" ? null : server.envFile, - url: null, - headers: null, - }, - ] as const - }) - - mcpServersPatch = Object.fromEntries([ - ...upsertServerEntries, - ...removedServerEntries, - ]) - } - - if (form.execEnabled) { - execConfigPatch.allow_remote = form.allowRemote - execConfigPatch.enable_deny_patterns = form.enableDenyPatterns - execConfigPatch.custom_allow_patterns = parseMultilineList( - form.customAllowPatternsText, - ) - execConfigPatch.timeout_seconds = parseIntField( - form.execTimeoutSeconds, - "Exec timeout", - { min: 0 }, - ) - - if (form.enableDenyPatterns) { - execConfigPatch.custom_deny_patterns = parseMultilineList( - form.customDenyPatternsText, - ) - } - } - - await patchAppConfig({ - agents: { - defaults: { - workspace, - restrict_to_workspace: form.restrictToWorkspace, - split_on_marker: form.splitOnMarker, - tool_feedback: { - enabled: form.toolFeedbackEnabled, - max_args_length: toolFeedbackMaxArgsLength, - separate_messages: form.toolFeedbackSeparateMessages, - }, - max_tokens: maxTokens, - context_window: contextWindow, - max_tool_iterations: maxToolIterations, - summarize_message_threshold: summarizeMessageThreshold, - summarize_token_percent: summarizeTokenPercent, - turn_profile: turnProfile, - }, - }, - session: { - dm_scope: dmScope, - }, - evolution: { - enabled: form.evolutionEnabled, - mode: form.evolutionMode, - state_dir: - form.evolutionStateDir.trim() === "" - ? null - : form.evolutionStateDir.trim(), - min_task_count: evolutionMinTaskCount, - min_success_ratio: evolutionMinSuccessRatio, - cold_path_trigger: form.evolutionColdPathTrigger, - cold_path_times: parseMultilineList( - form.evolutionColdPathTimesText, - ), - }, - tools: { - cron: { - allow_command: form.allowCommand, - exec_timeout_minutes: cronExecTimeoutMinutes, - }, - exec: execConfigPatch, - mcp: { - enabled: form.mcpEnabled, - discovery: mcpDiscoveryPatch, - servers: mcpServersPatch, - }, - }, - heartbeat: { - enabled: form.heartbeatEnabled, - interval: heartbeatInterval, - }, - devices: { - enabled: form.devicesEnabled, - monitor_usb: form.monitorUSB, - }, - }) - - setBaseline(form) - queryClient.invalidateQueries({ queryKey: ["config"] }) - } - - let savedLauncherForm: LauncherForm | null = null - if (launcherSettingsDirty) { - const port = parseIntField(launcherForm.port, "Service port", { - min: 1, - max: 65535, - }) - const allowedCIDRs = parseCIDRText(launcherForm.allowedCIDRsText) - const trustedProxyCIDRs = parseCIDRText( - launcherForm.trustedProxyCIDRsText, - ) - const savedLauncherConfig = await updateLauncherConfig({ - port, - public: launcherForm.publicAccess, - allowed_cidrs: allowedCIDRs, - allow_localhost_bypass: launcherForm.allowLocalhostBypass, - trusted_proxy_cidrs: trustedProxyCIDRs, - }) - const parsedLauncher: LauncherForm = { - port: String(savedLauncherConfig.port), - publicAccess: savedLauncherConfig.public, - allowedCIDRsText: (savedLauncherConfig.allowed_cidrs ?? []).join( - "\n", - ), - allowLocalhostBypass: - savedLauncherConfig.allow_localhost_bypass ?? true, - trustedProxyCIDRsText: ( - savedLauncherConfig.trusted_proxy_cidrs ?? [] - ).join("\n"), - dashboardPassword: "", - dashboardPasswordConfirm: "", - } - savedLauncherForm = parsedLauncher - setLauncherForm(parsedLauncher) - setLauncherBaseline(parsedLauncher) - queryClient.setQueryData( - ["system", "launcher-config"], - savedLauncherConfig, - ) - } - - if (launcherPasswordDirty) { - const result = await postLauncherDashboardSetup(password, confirm) - if (!result.ok) { - throw new Error(result.error) - } - - const clearedLauncherForm = savedLauncherForm ?? { - ...launcherForm, - dashboardPassword: "", - dashboardPasswordConfirm: "", - } - setLauncherForm(clearedLauncherForm) - if (savedLauncherForm) { - setLauncherBaseline(savedLauncherForm) - } - } - - if (autoStartDirty) { - if (!autoStartSupported) { - throw new Error(t("pages.config.autostart_unsupported")) - } - const status = await updateAutoStartEnabled(autoStartEnabled) - setAutoStartEnabled(status.enabled) - setAutoStartBaseline(status.enabled) - queryClient.setQueryData(["system", "autostart"], status) - } - - const gateway = await refreshGatewayState({ force: true }) - showSaveSuccessOrRestartToast( - t, - t("pages.config.save_success"), - t("navigation.config"), - gateway?.restartRequired === true, - ) - } catch (err) { - toast.error( - err instanceof Error ? err.message : t("pages.config.save_error"), - ) - } finally { - setSaving(false) - } - } - - const factoryResetButton = ( - - - - - - - - {t("pages.config.factory_reset_confirm_title")} - - - {t("pages.config.factory_reset_confirm_desc")} - - - - {t("common.cancel")} - - {t("pages.config.factory_reset_confirm")} - - - - - ) - - const actionButtons = ( -
- {factoryResetButton} - - -
- ) - - return ( -
- - - {versionInfo.version} - - ) - } - children={ - - } - /> -
-
- {isLoading ? ( -
- {t("labels.loading")} -
- ) : error ? ( -
-
- {t("pages.config.load_error")} -
-
{factoryResetButton}
-
- ) : ( -
- - - - - - - - - - - - - - - - - {!isDirty && actionButtons} -
- )} -
-
- {isDirty && ( -
-
-
- -
- {actionButtons} -
-
- )} -
- ) -} diff --git a/web/frontend/src/components/config/config-sections.tsx b/web/frontend/src/components/config/config-sections.tsx deleted file mode 100644 index a921b998..00000000 --- a/web/frontend/src/components/config/config-sections.tsx +++ /dev/null @@ -1,1325 +0,0 @@ -import { IconPlus, IconTrash } from "@tabler/icons-react" -import { useState } from "react" -import type { ReactNode } from "react" -import { useTranslation } from "react-i18next" - -import { - type CoreConfigForm, - DM_SCOPE_OPTIONS, - type LauncherForm, - type MCPServerForm, - type MCPServerType, - type TurnProfileForm, - type TurnProfileMode, -} from "@/components/config/form-model" -import { Field, SwitchCardField } from "@/components/shared-form" -import { Button } from "@/components/ui/button" -import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card" -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { Textarea } from "@/components/ui/textarea" - -type UpdateCoreField = ( - key: K, - value: CoreConfigForm[K], -) => void - -type UpdateLauncherField = ( - key: K, - value: LauncherForm[K], -) => void - -interface ConfigSectionCardProps { - title: string - description?: string - children: ReactNode -} - -function ConfigSectionCard({ - title, - description, - children, -}: ConfigSectionCardProps) { - return ( - - - {title} - {description && {description}} - - -
{children}
-
-
- ) -} - -interface AgentDefaultsSectionProps { - form: CoreConfigForm - onFieldChange: UpdateCoreField - onTurnProfileFieldChange: ( - key: K, - value: TurnProfileForm[K], - ) => void -} - -export function AgentDefaultsSection({ - form, - onFieldChange, - onTurnProfileFieldChange, -}: AgentDefaultsSectionProps) { - const { t } = useTranslation() - const renderModeSelect = ({ - value, - onValueChange, - allowCustom, - }: { - value: TurnProfileMode - onValueChange: (mode: TurnProfileMode) => void - allowCustom: boolean - }) => ( - - ) - - return ( - - - onFieldChange("workspace", e.target.value)} - placeholder="~/.picoclaw/workspace" - /> - - - - onFieldChange("restrictToWorkspace", checked) - } - /> - - onFieldChange("splitOnMarker", checked)} - /> - - - onFieldChange("toolFeedbackEnabled", checked) - } - /> - - {form.toolFeedbackEnabled && ( - - onFieldChange("toolFeedbackSeparateMessages", checked) - } - /> - )} - - {form.toolFeedbackEnabled && ( - - - onFieldChange("toolFeedbackMaxArgsLength", e.target.value) - } - /> - - )} - - - onFieldChange("maxTokens", e.target.value)} - /> - - - - onFieldChange("contextWindow", e.target.value)} - placeholder="131072" - /> - - - - onFieldChange("maxToolIterations", e.target.value)} - /> - - - - - onFieldChange("summarizeMessageThreshold", e.target.value) - } - /> - - - - - onFieldChange("summarizeTokenPercent", e.target.value) - } - /> - - - -
- - onTurnProfileFieldChange("enabled", checked) - } - /> - -
-
- - {renderModeSelect({ - value: form.turnProfile.historyMode, - onValueChange: (mode) => - onTurnProfileFieldChange( - "historyMode", - mode === "off" ? "off" : "default", - ), - allowCustom: false, - })} -

- {t("pages.config.turn_profile_history_hint")} -

-
- -
- - {renderModeSelect({ - value: form.turnProfile.systemPromptMode, - onValueChange: (mode) => - onTurnProfileFieldChange( - "systemPromptMode", - mode === "off" ? "off" : "default", - ), - allowCustom: false, - })} -

- {t("pages.config.turn_profile_system_prompt_hint")} -

-
- -
- - {renderModeSelect({ - value: form.turnProfile.skillsMode, - onValueChange: (mode) => - onTurnProfileFieldChange("skillsMode", mode), - allowCustom: true, - })} -

- {t("pages.config.turn_profile_skills_hint")} -

- {form.turnProfile.skillsMode === "custom" && ( -