ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
chore: remove agent code now living in serverkit-agent repo
Juan Denisf9d061045225
diff --git a/.github/workflows/agent-ci.yml b/.github/workflows/agent-ci.ymldeleted file mode 100644index 102ad0e3..00000000--- a/.github/workflows/agent-ci.yml+++ /dev/null@@ -1,103 +0,0 @@-name: Agent CI--# Validates the Go agent on every change: it must vet clean, pass its unit-# tests, and — critically — still COMPILE for every platform it ships on. The-# cross-compile matrix is what catches "this builds on my machine but breaks-# the Windows/macOS build" before it reaches a release, which the-# build-only release workflow did not guard on PRs.--on:- push:- branches: [dev, main]- paths:- - 'agent/**'- - '.github/workflows/agent-ci.yml'- pull_request:- branches: [dev, main]- paths:- - 'agent/**'- - '.github/workflows/agent-ci.yml'--jobs:- build-ui:- name: Build Agent UI- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- # The agent embeds the desktop UI via //go:embed all:dist, so the- # React app must be built into agent/internal/agentui/dist before any- # `go` command — otherwise the embed fails with "no matching files".- - uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'- cache-dependency-path: agent/ui/package-lock.json- - name: Build agent UI- working-directory: agent/ui- run: npm ci && npm run build- - name: Upload UI artifact- uses: actions/upload-artifact@v4- with:- name: agent-ui-dist- path: agent/internal/agentui/dist/- retention-days: 1-- test:- name: vet & test (linux)- runs-on: ubuntu-latest- needs: build-ui- defaults:- run:- working-directory: agent- steps:- - uses: actions/checkout@v4- - uses: actions/setup-go@v5- with:- go-version-file: agent/go.mod- cache-dependency-path: agent/go.sum- - uses: actions/download-artifact@v4- with:- name: agent-ui-dist- path: agent/internal/agentui/dist/- - name: go vet- run: go vet ./...- - name: go test- run: go test ./... -count=1-- build:- name: build (${{ matrix.goos }}/${{ matrix.goarch }})- runs-on: ubuntu-latest- needs: build-ui- defaults:- run:- working-directory: agent- # darwin is intentionally NOT in this matrix: the tray dependency- # (fyne.io/systray) needs the macOS Cocoa toolchain and cannot be- # cross-compiled from Linux. It is built on a macOS host at release time- # (and is treated as best-effort there). These three targets cover the- # real deployment surface — Linux servers and Windows.- strategy:- fail-fast: false- matrix:- include:- - goos: linux- goarch: amd64- - goos: linux- goarch: arm64- - goos: windows- goarch: amd64- steps:- - uses: actions/checkout@v4- - uses: actions/setup-go@v5- with:- go-version-file: agent/go.mod- cache-dependency-path: agent/go.sum- - uses: actions/download-artifact@v4- with:- name: agent-ui-dist- path: agent/internal/agentui/dist/- - name: go build- env:- GOOS: ${{ matrix.goos }}- GOARCH: ${{ matrix.goarch }}- run: go build ./...diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.ymldeleted file mode 100644index 33cd0be0..00000000--- a/.github/workflows/agent-release.yml+++ /dev/null@@ -1,470 +0,0 @@-name: Agent Release--on:- push:- tags:- - 'agent-v*'- workflow_dispatch:- inputs:- version:- description: 'Version to release (e.g., 1.0.0)'- required: true- type: string--env:- GO_VERSION: '1.23'--jobs:- version:- name: Resolve Version- runs-on: ubuntu-latest- outputs:- version: ${{ steps.version.outputs.version }}- steps:- - name: Get version- id: version- run: |- if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then- VERSION="${{ github.event.inputs.version }}"- else- VERSION="${GITHUB_REF#refs/tags/agent-v}"- fi- echo "version=$VERSION" >> $GITHUB_OUTPUT- echo "Releasing agent version: $VERSION"-- build-ui:- name: Build Agent UI- runs-on: ubuntu-latest- needs: version- steps:- - name: Checkout code- uses: actions/checkout@v4-- # The agent embeds its desktop UI via //go:embed all:dist, so the React- # app must be built into agent/internal/agentui/dist before `go build`.- - name: Set up Node- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'- cache-dependency-path: agent/ui/package-lock.json-- - name: Build agent UI- working-directory: agent/ui- run: npm ci && npm run build-- - name: Upload UI artifact- uses: actions/upload-artifact@v4- with:- name: agent-ui-dist- path: agent/internal/agentui/dist/- retention-days: 5-- build-binaries:- name: Build Binary (${{ matrix.goos }}/${{ matrix.goarch }})- runs-on: ubuntu-latest- needs: [version, build-ui]-- strategy:- fail-fast: false- matrix:- include:- - goos: linux- goarch: amd64- suffix: ''- - goos: linux- goarch: arm64- suffix: ''- - goos: windows- goarch: amd64- suffix: '.exe'- - goos: windows- goarch: arm64- suffix: '.exe'-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Set up Go- uses: actions/setup-go@v5- with:- go-version: ${{ env.GO_VERSION }}- cache-dependency-path: agent/go.sum-- - name: Download UI artifact- uses: actions/download-artifact@v4- with:- name: agent-ui-dist- path: agent/internal/agentui/dist/-- - name: Build binary- env:- GOOS: ${{ matrix.goos }}- GOARCH: ${{ matrix.goarch }}- CGO_ENABLED: 0- run: |- cd agent- # Windows builds use -H windowsgui so Start-menu launches don't- # flash a console. attachParentConsole() in cmd/agent restores- # stdio when invoked from PowerShell/cmd for CLI subcommands.- if [ "${{ matrix.goos }}" = "windows" ]; then- EXTRA_LDFLAGS="-H=windowsgui"- else- EXTRA_LDFLAGS=""- fi- go build -ldflags="-s -w $EXTRA_LDFLAGS -X main.Version=${{ needs.version.outputs.version }} -X github.com/serverkit/agent/internal/agent.Version=${{ needs.version.outputs.version }}" \- -o ../dist/serverkit-agent-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} \- ./cmd/agent-- - name: Compress binary (Linux)- if: matrix.goos == 'linux'- run: |- cd dist- tar -czvf serverkit-agent-${{ needs.version.outputs.version }}-${{ matrix.goos }}-${{ matrix.goarch }}.tar.gz \- serverkit-agent-${{ matrix.goos }}-${{ matrix.goarch }}-- - name: Compress binary (Windows)- if: matrix.goos == 'windows'- run: |- cd dist- zip serverkit-agent-${{ needs.version.outputs.version }}-${{ matrix.goos }}-${{ matrix.goarch }}.zip \- serverkit-agent-${{ matrix.goos }}-${{ matrix.goarch }}.exe-- - name: Upload artifact- uses: actions/upload-artifact@v4- with:- name: serverkit-agent-${{ matrix.goos }}-${{ matrix.goarch }}- path: dist/serverkit-agent-${{ needs.version.outputs.version }}-*- retention-days: 5-- # Build .deb packages- build-deb:- name: Build DEB Package (${{ matrix.arch }})- runs-on: ubuntu-latest- needs: [version, build-binaries]-- strategy:- fail-fast: false- matrix:- arch: [amd64, arm64]-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Download binary- uses: actions/download-artifact@v4- with:- name: serverkit-agent-linux-${{ matrix.arch }}- path: dist/-- - name: Extract binary- run: |- cd dist- tar -xzf serverkit-agent-${{ needs.version.outputs.version }}-linux-${{ matrix.arch }}.tar.gz-- - name: Build DEB package- run: |- chmod +x agent/packaging/deb/build.sh- cd agent/packaging/deb- ./build.sh "${{ needs.version.outputs.version }}" "${{ matrix.arch }}" "../../../dist/serverkit-agent-linux-${{ matrix.arch }}" "../../../packages"-- - name: Upload DEB package- uses: actions/upload-artifact@v4- with:- name: serverkit-agent-deb-${{ matrix.arch }}- path: packages/*.deb- retention-days: 5-- # Build .rpm packages- build-rpm:- name: Build RPM Package (${{ matrix.rpmarch }})- runs-on: ubuntu-latest- needs: [version, build-binaries]-- strategy:- fail-fast: false- matrix:- include:- - goarch: amd64- rpmarch: x86_64- - goarch: arm64- rpmarch: aarch64-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Install RPM build tools- run: |- sudo apt-get update- sudo apt-get install -y rpm-- - name: Download binary- uses: actions/download-artifact@v4- with:- name: serverkit-agent-linux-${{ matrix.goarch }}- path: dist/-- - name: Extract binary- run: |- cd dist- tar -xzf serverkit-agent-${{ needs.version.outputs.version }}-linux-${{ matrix.goarch }}.tar.gz-- - name: Build RPM package- run: |- chmod +x agent/packaging/rpm/build.sh- cd agent/packaging/rpm- ./build.sh "${{ needs.version.outputs.version }}" "${{ matrix.rpmarch }}" "../../../dist/serverkit-agent-linux-${{ matrix.goarch }}" "../../../packages"-- - name: Upload RPM package- uses: actions/upload-artifact@v4- with:- name: serverkit-agent-rpm-${{ matrix.rpmarch }}- path: packages/*.rpm- retention-days: 5-- # Build Windows MSI installers (one per architecture)- build-msi:- name: Build MSI Installer (${{ matrix.arch }})- runs-on: windows-latest- needs: [version, build-binaries]-- strategy:- fail-fast: false- matrix:- include:- - goarch: amd64- arch: x64- - goarch: arm64- arch: arm64-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Install WiX Toolset- run: |- dotnet tool install --global wix --version 5.0.2-- - name: Install WiX Util extension- run: |- wix extension add --global WixToolset.Util.wixext/5.0.2-- - name: Download binary- uses: actions/download-artifact@v4- with:- name: serverkit-agent-windows-${{ matrix.goarch }}- path: dist/-- - name: Extract binary- shell: bash- run: |- cd dist- unzip serverkit-agent-${{ needs.version.outputs.version }}-windows-${{ matrix.goarch }}.zip-- - name: Build MSI- shell: pwsh- run: |- cd agent/packaging/msi- .\build.ps1 -Version "${{ needs.version.outputs.version }}" -Arch "${{ matrix.arch }}" -BinaryPath "..\..\..\dist\serverkit-agent-windows-${{ matrix.goarch }}.exe" -OutputDir "..\..\..\packages"-- - name: Upload MSI- uses: actions/upload-artifact@v4- with:- name: serverkit-agent-msi-${{ matrix.arch }}- path: packages/*.msi- retention-days: 5-- # Build Docker image- build-docker:- name: Build Docker Image- runs-on: ubuntu-latest- needs: version-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Set up QEMU- uses: docker/setup-qemu-action@v3-- - name: Set up Docker Buildx- uses: docker/setup-buildx-action@v3-- - name: Login to Docker Hub- uses: docker/login-action@v3- with:- username: ${{ secrets.DOCKERHUB_USERNAME }}- password: ${{ secrets.DOCKERHUB_TOKEN }}- continue-on-error: true-- - name: Build and push Docker image- uses: docker/build-push-action@v5- with:- context: ./agent- platforms: linux/amd64,linux/arm64- push: ${{ secrets.DOCKERHUB_USERNAME != '' }}- tags: |- jhd3197/serverkit-agent:latest- jhd3197/serverkit-agent:${{ needs.version.outputs.version }}- build-args: |- VERSION=${{ needs.version.outputs.version }}- BUILD_TIME=${{ github.event.repository.updated_at }}- GIT_COMMIT=${{ github.sha }}-- release:- name: Create Release- runs-on: ubuntu-latest- needs: [build-binaries, build-deb, build-rpm, build-msi, build-docker]- permissions:- contents: write-- steps:- - name: Download all artifacts- uses: actions/download-artifact@v4- with:- path: artifacts-- - name: Prepare release files- run: |- mkdir -p release- # Binary archives- find artifacts -type f \( -name "*.tar.gz" -o -name "*.zip" \) -exec mv {} release/ \;- # DEB packages- find artifacts -type f -name "*.deb" -exec mv {} release/ \;- # RPM packages- find artifacts -type f -name "*.rpm" -exec mv {} release/ \;- # MSI installers- find artifacts -type f -name "*.msi" -exec mv {} release/ \;- ls -la release/-- - name: Generate checksums- run: |- cd release- sha256sum * > checksums.txt- cat checksums.txt-- - name: Create Release- uses: softprops/action-gh-release@v1- with:- tag_name: agent-v${{ needs.version.outputs.version }}- name: ServerKit Agent v${{ needs.version.outputs.version }}- draft: false- prerelease: false- files: |- release/*- body: |- ## ServerKit Agent v${{ needs.version.outputs.version }}-- ### Downloads-- #### Binary Archives- | Platform | Architecture | Download |- |----------|--------------|----------|- | Linux | x64 (amd64) | `serverkit-agent-${{ needs.version.outputs.version }}-linux-amd64.tar.gz` |- | Linux | ARM64 | `serverkit-agent-${{ needs.version.outputs.version }}-linux-arm64.tar.gz` |- | Windows | x64 (amd64) | `serverkit-agent-${{ needs.version.outputs.version }}-windows-amd64.zip` |- | Windows | ARM64 | `serverkit-agent-${{ needs.version.outputs.version }}-windows-arm64.zip` |-- #### Linux Packages- | Format | Architecture | Download |- |--------|--------------|----------|- | DEB (Debian/Ubuntu) | amd64 | `serverkit-agent_${{ needs.version.outputs.version }}_amd64.deb` |- | DEB (Debian/Ubuntu) | arm64 | `serverkit-agent_${{ needs.version.outputs.version }}_arm64.deb` |- | RPM (RHEL/Fedora) | x86_64 | `serverkit-agent-${{ needs.version.outputs.version }}-1.x86_64.rpm` |- | RPM (RHEL/Fedora) | aarch64 | `serverkit-agent-${{ needs.version.outputs.version }}-1.aarch64.rpm` |-- #### Windows Installer- | Format | Architecture | Download |- |--------|--------------|--------|- | MSI | x64 | `serverkit-agent-${{ needs.version.outputs.version }}-x64.msi` |- | MSI | ARM64 | `serverkit-agent-${{ needs.version.outputs.version }}-arm64.msi` |-- #### Docker- ```bash- docker pull jhd3197/serverkit-agent:${{ needs.version.outputs.version }}- docker pull jhd3197/serverkit-agent:latest- ```-- ### Quick Install-- **Debian/Ubuntu:**- ```bash- curl -LO https://github.com/${{ github.repository }}/releases/download/agent-v${{ needs.version.outputs.version }}/serverkit-agent_${{ needs.version.outputs.version }}_amd64.deb- sudo dpkg -i serverkit-agent_${{ needs.version.outputs.version }}_amd64.deb- sudo serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"- sudo systemctl start serverkit-agent- ```-- **RHEL/Fedora:**- ```bash- sudo rpm -i https://github.com/${{ github.repository }}/releases/download/agent-v${{ needs.version.outputs.version }}/serverkit-agent-${{ needs.version.outputs.version }}-1.x86_64.rpm- sudo serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"- sudo systemctl start serverkit-agent- ```-- **Windows (MSI):**- Download and run the MSI installer, then:- ```powershell- serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"- Start-Service ServerKitAgent- ```-- **Docker:**- ```bash- docker run -d --name serverkit-agent \- -v /var/run/docker.sock:/var/run/docker.sock:ro \- -v serverkit-config:/etc/serverkit-agent \- jhd3197/serverkit-agent:${{ needs.version.outputs.version }}- ```-- ### Verification-- Verify downloads using the checksums in `checksums.txt`:- ```bash- sha256sum -c checksums.txt- ```-- ### What's New-- See [CHANGELOG](https://github.com/${{ github.repository }}/blob/main/agent/CHANGELOG.md) for details.- env:- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}-- summary:- name: Build Summary- runs-on: ubuntu-latest- needs: [version, release]-- steps:- - name: Create summary- run: |- echo "## Agent Release Summary" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "**Version:** v${{ needs.version.outputs.version }}" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "### Built Binaries" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "| Platform | Architecture | Status |" >> $GITHUB_STEP_SUMMARY- echo "|----------|--------------|--------|" >> $GITHUB_STEP_SUMMARY- echo "| Linux | amd64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| Linux | arm64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| Windows | amd64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "### Packages" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "| Format | Architecture | Status |" >> $GITHUB_STEP_SUMMARY- echo "|--------|--------------|--------|" >> $GITHUB_STEP_SUMMARY- echo "| DEB | amd64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| DEB | arm64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| RPM | x86_64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| RPM | aarch64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| MSI | x64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| MSI | ARM64 | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "| Docker | multi-arch | ✅ Built |" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "### Release" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "Release created at: https://github.com/${{ github.repository }}/releases/tag/agent-v${{ needs.version.outputs.version }}" >> $GITHUB_STEP_SUMMARYdiff --git a/agent/.dockerignore b/agent/.dockerignoredeleted file mode 100644index 6289b991..00000000--- a/agent/.dockerignore+++ /dev/null@@ -1,37 +0,0 @@-# Build artifacts-*.exe-serverkit-agent-agent-dist/-ui/dist/-ui/node_modules/--# Git-.git-.gitignore--# IDE-.idea-.vscode-*.swp-*.swo--# Documentation (not needed in image)-*.md-LICENSE--# Scripts (not needed in image)-scripts/--# Local config files-config.yaml-*.key-*.pem--# OS files-.DS_Store-Thumbs.db--# Test files-*_test.go-testdata/diff --git a/agent/.gitignore b/agent/.gitignoredeleted file mode 100644index 0cfd3ca6..00000000--- a/agent/.gitignore+++ /dev/null@@ -1,27 +0,0 @@-# Binaries-serverkit-agent-serverkit-agent.exe-*.exe-*.dll-*.so-*.dylib--# Build output-/dist/-/output/-/packages/--# Test binaries-*.test-*.test.exe--# IDE-.idea/-.vscode/-*.swp-*.swo--# OS files-.DS_Store-Thumbs.db-internal/agentui/dist/diff --git a/agent/CHANGELOG.md b/agent/CHANGELOG.mddeleted file mode 100644index a8f44e01..00000000--- a/agent/CHANGELOG.md+++ /dev/null@@ -1,55 +0,0 @@-# ServerKit Agent Changelog--All notable changes to the **ServerKit agent** are documented here.--The agent is versioned and released independently from the control panel. Release-builds are produced by the `Agent Release` workflow and tagged `agent-vX.Y.Z`;-each tag publishes Linux (amd64/arm64) binaries + `.deb`/`.rpm`, Windows-(x64/arm64) `.msi` installers, and a multi-arch Docker image.--The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).--## [Unreleased]--Substantial work has landed since the last tagged release (`agent-v1.0.4`) and-is awaiting the next release cut. Highlights:--### Added--- **Native Windows experience** — Windows service host, native first-run setup- wizard, system tray, dark-mode aware UI, and an MSI installer that opens the- pairing wizard right after install (no browser or external WebView2 runtime- required). ARM64 Windows builds included.-- **Desktop console UI** — embedded React UI (`agent/ui`) served over local IPC- for status, logs, activity, and actions.-- **Pairing flows** — short-code and passphrase pairing with keypair enrollment- and the `sk1` connection-string format.-- **Dual transport** — Socket.IO/WebSocket primary transport with automatic,- permanent fallback to HTTP polling when the WebSocket connection flaps.-- **Remote operations** — handlers for files, packages, services, cron, sudo,- Docker (incl. extra ops), Cloudflare tunnels, runtime management, and streamed- job progress.-- **Capability probing** — host capability detection reported to the panel and- re-sent on a periodic cadence; system info pushed and persisted.-- **Self-update** — built-in updater with periodic version checks.--### Fixed--- Stopped dropping capability/system-info payloads on transient `/poll` failures.-- Resolved silent failures around empty logs, dead WebSocket connections, and- locked-out agents.-- Windows builds use the `-H=windowsgui` subsystem so Start-menu launches no- longer flash a stray console window; CLI subcommands still re-hook stdio when- run from a real terminal.-- Pinned the Go toolchain to 1.23 for CI compatibility; fixed Docker and MSI- (WiX v5) builds in the release workflow.--## [1.0.4] - 2026-03-28-## [1.0.3] - 2026-03-24-## [1.0.2] - 2026-03-03-## [1.0.1] - 2026-01-24-## [1.0.0] - 2026-01-24--Initial tagged agent releases: cross-platform Go agent with HMAC-SHA256-authentication, Docker integration, system metrics, and auto-reconnect, plus the-multi-platform release pipeline (binaries, `.deb`/`.rpm`, MSI, Docker).diff --git a/agent/Dockerfile b/agent/Dockerfiledeleted file mode 100644index 6783793b..00000000--- a/agent/Dockerfile+++ /dev/null@@ -1,106 +0,0 @@-# ServerKit Agent - Docker Image-# Multi-stage build for minimal image size--# ============================================-# Stage 1: Build agent desktop UI (embedded by //go:embed)-# ============================================-FROM node:20-alpine AS ui-builder--WORKDIR /build--# Install UI dependencies first for better layer caching-COPY ui/package.json ui/package-lock.json ./ui/-RUN cd ui && npm ci--# Copy UI source and build it. Vite outputs to ../internal/agentui/dist,-# which is the exact path the Go embed directive expects.-COPY ui/ ./ui/-RUN cd ui && npm run build--# ============================================-# Stage 2: Build Go binary-# ============================================-FROM golang:1.23-alpine AS builder--# Install build dependencies-RUN apk add --no-cache git ca-certificates tzdata--WORKDIR /build--# Copy go mod files first for better layer caching-COPY go.mod go.sum ./-RUN go mod download--# Copy source code-COPY . .--# Copy the built UI bundle into the Go package that embeds it.-# This must happen before `go build` because //go:embed is validated-# at compile time.-COPY --from=ui-builder /build/internal/agentui/dist ./internal/agentui/dist--# Build arguments for version info-ARG VERSION=dev-ARG BUILD_TIME=unknown-ARG GIT_COMMIT=unknown--# Target architecture for multi-platform builds (buildx sets these).-ARG TARGETOS=linux-ARG TARGETARCH=amd64--# Build the agent binary-RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \- -ldflags="-w -s \- -X main.Version=${VERSION} \- -X main.BuildTime=${BUILD_TIME} \- -X main.GitCommit=${GIT_COMMIT}" \- -o serverkit-agent \- ./cmd/agent--# ============================================-# Stage 3: Runtime-# ============================================-FROM alpine:3.19--# Install runtime dependencies-RUN apk add --no-cache \- ca-certificates \- tzdata \- docker-cli \- docker-cli-compose--# Create non-root user-RUN addgroup -g 1000 serverkit && \- adduser -u 1000 -G serverkit -s /bin/sh -D serverkit--# Create directories-RUN mkdir -p /etc/serverkit-agent /var/log/serverkit-agent && \- chown -R serverkit:serverkit /etc/serverkit-agent /var/log/serverkit-agent--# Copy binary from builder-COPY --from=builder /build/serverkit-agent /usr/local/bin/serverkit-agent--# Set permissions-RUN chmod +x /usr/local/bin/serverkit-agent--# Volume for configuration persistence-VOLUME ["/etc/serverkit-agent"]--# Volume for logs-VOLUME ["/var/log/serverkit-agent"]--# Health check-HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \- CMD serverkit-agent status || exit 1--# Labels-LABEL org.opencontainers.image.title="ServerKit Agent" \- org.opencontainers.image.description="Remote server management agent for ServerKit" \- org.opencontainers.image.vendor="ServerKit" \- org.opencontainers.image.source="https://github.com/jhd3197/ServerKit"--# Default user (can be overridden for Docker socket access)-USER serverkit--ENTRYPOINT ["serverkit-agent"]-CMD ["start"]diff --git a/agent/Makefile b/agent/Makefiledeleted file mode 100644index 4d68f196..00000000--- a/agent/Makefile+++ /dev/null@@ -1,175 +0,0 @@-# ServerKit Agent Makefile--VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")-BUILD_TIME ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")-GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")--LDFLAGS := -s -w \- -X main.Version=$(VERSION) \- -X main.BuildTime=$(BUILD_TIME) \- -X main.GitCommit=$(GIT_COMMIT)--# Agent-specific LDFLAGS (includes agent package version var). On Windows-# we MUST select the GUI subsystem; otherwise Windows attaches a console to-# every launch (the desktop console then renders behind a stray black-# cmd.exe-looking window). attachParentConsole() in console_windows.go-# still re-hooks stdio for CLI subcommands like `status` when invoked from-# a real terminal.-AGENT_LDFLAGS := $(LDFLAGS) \- -X github.com/serverkit/agent/internal/agent.Version=$(VERSION)--WINDOWS_LDFLAGS := $(AGENT_LDFLAGS) -H=windowsgui--BINARY_NAME := serverkit-agent-DIST_DIR := dist-UI_DIR := ui-UI_DIST := internal/agentui/dist--.PHONY: all build clean test lint deps dev run docker-build docker-push docker-buildx build-ui--all: build--# Download dependencies-deps:- go mod download- go mod tidy--# Build the embedded React UI (required by //go:embed in internal/agentui/embed.go)-build-ui:- @cd $(UI_DIR) && npm ci && npm run build--$(UI_DIST): build-ui--# Build for current platform-build: $(UI_DIST)- CGO_ENABLED=0 go build -ldflags "$(AGENT_LDFLAGS)" -o $(BINARY_NAME) ./cmd/agent--# Build for current platform with debug symbols-dev:- go build -o $(BINARY_NAME) ./cmd/agent--# Run the agent-run: build- ./$(BINARY_NAME) start--# Build for all platforms-build-all: $(UI_DIST)- @mkdir -p $(DIST_DIR)- @echo "Building for Linux amd64..."- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-amd64 ./cmd/agent- @echo "Building for Linux arm64..."- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-arm64 ./cmd/agent- @echo "Building for Windows amd64..."- CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent- @echo "Building for Windows arm64..."- CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent- @echo "Building for macOS amd64... (non-fatal: systray needs CGO on darwin, so this only works on a Mac)"- -CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent- @echo "Building for macOS arm64... (non-fatal)"- -CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent- @echo "Done! Binaries in $(DIST_DIR)/"--# Build Linux only-build-linux: $(UI_DIST)- @mkdir -p $(DIST_DIR)- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/agent- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-arm64 ./cmd/agent--# Build Windows only-build-windows: $(UI_DIST)- @mkdir -p $(DIST_DIR)- CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent--# Run tests-test:- go test -v ./...--# Run tests with coverage-test-coverage:- go test -v -coverprofile=coverage.out ./...- go tool cover -html=coverage.out -o coverage.html--# Run linter-lint:- golangci-lint run ./...--# Format code-fmt:- go fmt ./...--# Clean build artifacts-clean:- rm -f $(BINARY_NAME)- rm -rf $(DIST_DIR)- rm -rf $(UI_DIST)- rm -f coverage.out coverage.html--# Install locally-install: build- cp $(BINARY_NAME) /usr/local/bin/--# Create checksums-checksums:- @cd $(DIST_DIR) && sha256sum * > checksums.txt--# Docker image name-DOCKER_IMAGE := serverkit/agent-DOCKER_TAG ?= latest--# Build Docker image-docker-build:- docker build \- --build-arg VERSION=$(VERSION) \- --build-arg BUILD_TIME=$(BUILD_TIME) \- --build-arg GIT_COMMIT=$(GIT_COMMIT) \- -t $(DOCKER_IMAGE):$(DOCKER_TAG) .--# Build and tag Docker image with version-docker-build-version: docker-build- docker tag $(DOCKER_IMAGE):$(DOCKER_TAG) $(DOCKER_IMAGE):$(VERSION)--# Push Docker image-docker-push:- docker push $(DOCKER_IMAGE):$(DOCKER_TAG)- docker push $(DOCKER_IMAGE):$(VERSION)--# Build multi-arch Docker image-docker-buildx:- docker buildx build \- --platform linux/amd64,linux/arm64 \- --build-arg VERSION=$(VERSION) \- --build-arg BUILD_TIME=$(BUILD_TIME) \- --build-arg GIT_COMMIT=$(GIT_COMMIT) \- -t $(DOCKER_IMAGE):$(DOCKER_TAG) \- -t $(DOCKER_IMAGE):$(VERSION) \- --push .--# Help-help:- @echo "ServerKit Agent Build System"- @echo ""- @echo "Usage: make [target]"- @echo ""- @echo "Targets:"- @echo " build Build for current platform"- @echo " build-all Build for all platforms"- @echo " build-linux Build for Linux only"- @echo " build-windows Build for Windows only"- @echo " dev Build with debug symbols"- @echo " run Build and run the agent"- @echo " test Run tests"- @echo " lint Run linter"- @echo " fmt Format code"- @echo " clean Remove build artifacts"- @echo " deps Download dependencies"- @echo " install Install to /usr/local/bin"- @echo ""- @echo "Docker:"- @echo " docker-build Build Docker image"- @echo " docker-push Push Docker image to registry"- @echo " docker-buildx Build multi-arch image (amd64, arm64)"- @echo ""- @echo " help Show this help"- @echo ""- @echo "Note: The agent includes a built-in tray command."- @echo " Run 'serverkit-agent tray' for system tray mode."diff --git a/agent/README.md b/agent/README.mddeleted file mode 100644index f90265da..00000000--- a/agent/README.md+++ /dev/null@@ -1,499 +0,0 @@-# ServerKit Agent--A lightweight, cross-platform agent for remote server management. Connects to a ServerKit control plane to enable Docker management, system monitoring, and remote command execution.--## Features--- **Cross-Platform**: Supports Linux (amd64, arm64, arm), Windows (amd64, arm64), and macOS (amd64, arm64)-- **Lightweight**: Single binary, ~15MB RAM typical usage-- **Docker Integration**: Full Docker API access for container management-- **System Metrics**: Real-time CPU, memory, disk, and network monitoring-- **Secure Communication**: TLS encryption with HMAC-SHA256 authentication-- **Auto-Reconnect**: Automatic reconnection with exponential backoff-- **Self-Update**: Built-in auto-update with periodic version checks--## Quick Start--### Linux (One-liner)--```bash-curl -fsSL https://your-serverkit.com/install.sh | sudo bash -s -- \- --token "sk_reg_your_token" \- --server "https://your-serverkit.com"-```--### Windows (PowerShell as Administrator)--```powershell-irm https://your-serverkit.com/install.ps1 | iex-Install-ServerKitAgent -Token "sk_reg_your_token" -Server "https://your-serverkit.com"-```--> **Most Windows users should install the MSI instead** (see *Package-> Installation* below). The MSI registers the `ServerKitAgent` Windows service-> and opens a native pairing wizard right after install — no token handling and-> no browser required.--### Pairing (recommended)--Instead of baking a long registration token into an install command, you can-adopt an agent with a short, human-friendly code:--```bash-serverkit-agent pair --server "https://your-serverkit.com"-```--The agent generates an Ed25519 keypair, prints a short pairing code (and-passphrase), and waits. In the panel's **Add Server** screen, enter the code +-passphrase and verify the displayed key fingerprint to approve the device. On-Windows the MSI launches this wizard automatically. See-[../docs/pairing.md](../docs/pairing.md) for the full flow and security-properties.--### Docker (Recommended for containerized environments)--```bash-# Pull the image-docker pull serverkit/agent:latest--# Register the agent (one-time setup)-docker run --rm -v serverkit-agent-config:/etc/serverkit-agent \- serverkit/agent:latest register \- --token "sk_reg_your_token" \- --server "https://your-serverkit.com"--# Start the agent-docker run -d --name serverkit-agent \- --restart unless-stopped \- -v /var/run/docker.sock:/var/run/docker.sock:ro \- -v serverkit-agent-config:/etc/serverkit-agent \- serverkit/agent:latest-```--Or use Docker Compose:--```bash-# Clone and navigate to agent directory-cd agent--# Register (one-time setup)-docker compose run --rm agent register -s https://your-serverkit.com -t YOUR_TOKEN--# Start the agent-docker compose up -d--# View logs-docker compose logs -f-```--### Package Installation--**Debian/Ubuntu (.deb):**-```bash-curl -LO https://github.com/jhd3197/ServerKit/releases/latest/download/serverkit-agent_VERSION_amd64.deb-sudo dpkg -i serverkit-agent_VERSION_amd64.deb-sudo serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"-sudo systemctl start serverkit-agent-```--**RHEL/CentOS/Fedora (.rpm):**-```bash-sudo rpm -i https://github.com/jhd3197/ServerKit/releases/latest/download/serverkit-agent-VERSION-1.x86_64.rpm-sudo serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"-sudo systemctl start serverkit-agent-```--**Windows (.msi):**-Download and run the MSI installer from the releases page, then:-```powershell-serverkit-agent register --token "YOUR_TOKEN" --server "https://your-serverkit.com"-Start-Service ServerKitAgent-```--### Manual Installation--1. Download the appropriate binary for your platform from the releases page-2. Register the agent:- ```bash- ./serverkit-agent register --token "sk_reg_xxx" --server "https://your-serverkit.com"- ```-3. Start the agent:- ```bash- ./serverkit-agent start- ```--## Building from Source--### Prerequisites--- Go 1.23 or later (matches CI)-- Make (optional, for using Makefile)--### Build--```bash-# Clone the repository (the agent lives in the ServerKit monorepo)-git clone https://github.com/jhd3197/ServerKit.git-cd ServerKit/agent--# Download dependencies-go mod download--# Build for current platform-make build--# Or build for all platforms-make build-all-```--### Build Outputs--Binaries are placed in the `dist/` directory:-- `serverkit-agent-{version}-linux-amd64`-- `serverkit-agent-{version}-linux-arm64`-- `serverkit-agent-{version}-windows-amd64.exe`-- `serverkit-agent-{version}-darwin-amd64`-- `serverkit-agent-{version}-darwin-arm64`--## Usage--### Commands--```-serverkit-agent [command]--Available Commands:- start Start the agent service- register Register with a ServerKit instance (pre-shared token)- pair Pair with a panel using a short code (recommended)- setup Run the guided setup wizard- status Show agent status- config Configuration management- update Check for and apply self-updates- tray Run the system-tray app (desktop)- console Open the desktop console (WebView2)- version Show version information- help Help about any command--Run with no command to launch the desktop app: the pairing wizard if the agent-is not yet configured, otherwise the system tray.--Flags:- -c, --config string config file path- -d, --debug enable debug logging- -h, --help help for serverkit-agent-```--### Register--```bash-serverkit-agent register \- --token "sk_reg_xxx" \- --server "https://your-serverkit.com" \- --name "my-server"-```--### Start--```bash-# Foreground-serverkit-agent start--# With debug logging-serverkit-agent start --debug-```--## Configuration--Configuration file location:-- **Linux**: `/etc/serverkit-agent/config.yaml`-- **Windows**: `C:\ProgramData\ServerKit\Agent\config.yaml`--### Example Configuration--```yaml-server:- url: wss://your-serverkit.com/agent/ws- reconnect_interval: 5s- max_reconnect_interval: 5m- ping_interval: 30s--agent:- id: "auto-generated"- name: "my-server"--features:- docker: true- metrics: true- logs: true- file_access: false- exec: false--metrics:- enabled: true- interval: 10s- include_per_cpu: true- include_docker_stats: true--docker:- socket: /var/run/docker.sock- timeout: 30s--logging:- level: info- file: /var/log/serverkit-agent/agent.log- max_size_mb: 100- max_backups: 5- max_age_days: 30- compress: true-```--## Security--### Authentication--The agent uses HMAC-SHA256 signatures for authentication:-1. During registration, the agent receives an API key and secret-2. Each WebSocket connection is authenticated using HMAC-signed messages-3. Session tokens are issued after successful authentication--### Credentials Storage--Credentials are encrypted at rest using AES-256-GCM with a **host-stable** key-derived from:-- Hostname-- Machine ID (Linux) / Computer name (Windows)--The key is deliberately **independent of the logged-in user**. On Windows this-lets the `LocalSystem` service decrypt credentials that were written during-user-context pairing. (Mixing in the Windows username broke exactly this and was-removed in 1.6.14.) Because the key is host-bound, a copied credential file-cannot be reused on another machine.--> **Treat `agent.key` as a host-equivalent secret.** Anyone who can read this-> file on the host (or recreate the host-derived key) can recover the agent's-> API credentials. Combined with remote command execution (see below), a leaked-> key file is equivalent to full control of that host.--### Network Security--- All communication uses TLS (WSS)-- Certificate validation is enforced in production-- Replay attack protection via timestamps and nonces--## Systemd Service (Linux)--The installation script automatically creates a systemd service:--```bash-# Check status-systemctl status serverkit-agent--# View logs-journalctl -u serverkit-agent -f--# Restart-systemctl restart serverkit-agent-```--## Windows Service & Desktop App--On Windows the agent has two cooperating parts:--**1. The background service** — a true Windows Service (`ServerKitAgent`)-registered through the Service Control Manager, running as `LocalSystem` and set-to start automatically. This is what stays connected to the panel.--```powershell-# Check status-Get-Service ServerKitAgent--# View logs-Get-Content "C:\ProgramData\ServerKit\Agent\logs\agent.log" -Tail 50--# Restart-Restart-Service ServerKitAgent-```--**2. The desktop app** — an optional per-user UI auto-started via the `HKCU\...\Run`-key:--- **Pairing/setup wizard** — runs after install (or on first launch) to adopt the- agent into a panel.-- **System tray** — shows connection status and quick actions.-- **Desktop console** — a WebView2-hosted view of status, logs, activity, and- actions (no external browser required).--> **Windows limitations to be aware of:** system metrics report a single volume-> (`C:\`), and the remote file browser currently lists the agent's working drive-> rather than enumerating all drives. Multi-drive support is tracked for a future-> release.--### Windows environment variables--| Variable | Purpose |-|----------|---------|-| `SERVERKIT_INSECURE_TLS` | Disable TLS certificate verification (**dev/testing only**) |-| `SERVERKIT_WS_COMPRESSION` | Enable WebSocket permessage-deflate (off by default; some tunnels corrupt compressed frames) |-| `SERVERKIT_AGENT_LEGACY_WIZARD` | Use the legacy native setup wizard instead of the WebView2 one |--## Docker Deployment--### Building the Image--```bash-cd agent--# Build with version info-docker build \- --build-arg VERSION=1.0.0 \- --build-arg BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \- --build-arg GIT_COMMIT=$(git rev-parse --short HEAD) \- -t serverkit/agent:latest .-```--### Running with Docker--```bash-# Register the agent first-docker run --rm \- -v serverkit-agent-config:/etc/serverkit-agent \- serverkit/agent:latest register \- --token "sk_reg_xxx" \- --server "https://your-serverkit.com" \- --name "my-server"--# Run the agent-docker run -d \- --name serverkit-agent \- --restart unless-stopped \- -v /var/run/docker.sock:/var/run/docker.sock:ro \- -v serverkit-agent-config:/etc/serverkit-agent \- -v serverkit-agent-logs:/var/log/serverkit-agent \- serverkit/agent:latest-```--### Running with Docker Compose--```yaml-# docker-compose.yml-services:- agent:- image: serverkit/agent:latest- container_name: serverkit-agent- restart: unless-stopped- user: root- volumes:- - /var/run/docker.sock:/var/run/docker.sock:ro- - serverkit-config:/etc/serverkit-agent- - serverkit-logs:/var/log/serverkit-agent- environment:- - TZ=UTC--volumes:- serverkit-config:- serverkit-logs:-```--```bash-# Register-docker compose run --rm agent register -s https://your-serverkit.com -t YOUR_TOKEN--# Start-docker compose up -d--# Logs-docker compose logs -f--# Stop-docker compose down-```--### Environment Variables--| Variable | Description | Default |-|----------|-------------|---------|-| `TZ` | Timezone | `UTC` |--### Volumes--| Path | Description |-|------|-------------|-| `/etc/serverkit-agent` | Configuration and credentials |-| `/var/log/serverkit-agent` | Log files |-| `/var/run/docker.sock` | Docker socket (mount read-only) |--## Development--### Project Structure--```-agent/-├── cmd/agent/ # Main entry point (+ Windows service/console glue)-├── internal/-│ ├── agent/ # Core agent logic & command handlers-│ ├── agentui/ # Desktop console UI (WebView2)-│ ├── auth/ # HMAC authentication-│ ├── capabilities/ # Host capability probing-│ ├── cloudflared/ # Cloudflare tunnel management-│ ├── config/ # Configuration management-│ ├── cron/ # Remote cron management-│ ├── docker/ # Docker client wrapper-│ ├── ipc/ # Local IPC (desktop UI <-> agent)-│ ├── jobs/ # Background job runner-│ ├── logger/ # Structured logging-│ ├── metrics/ # System metrics collection-│ ├── pairing/ # Pairing client & keypair enrollment-│ ├── setupui/ # First-run setup wizard (Windows)-│ ├── terminal/ # Remote terminal sessions-│ ├── transport/ # WebSocket + HTTP-poll transports-│ ├── tray/ # System tray integration-│ ├── updater/ # Self-update mechanism-│ └── ws/ # WebSocket client-├── pkg/protocol/ # Message protocol (shared contract with the panel)-├── packaging/ # MSI / deb / rpm packaging-├── scripts/ # Build and install scripts-├── ui/ # Agent desktop UI (React)-├── Makefile-└── go.mod-```--### Running Tests--```bash-make test-```--### Code Formatting--```bash-make fmt-```--## Troubleshooting--### Agent won't connect--1. Check the server URL is correct-2. Verify the registration token is valid-3. Check firewall allows outbound WebSocket connections-4. Review logs: `journalctl -u serverkit-agent -n 50`--### Docker commands fail--1. Ensure Docker is installed and running-2. Verify the agent user has Docker permissions:- ```bash- sudo usermod -aG docker serverkit-agent- ```-3. Check Docker socket permissions--### High CPU/Memory usage--1. Increase the metrics interval in config-2. Disable per-CPU metrics if not needed-3. Check for log rotation issues--## License--MIT License - see LICENSE file for details.diff --git a/agent/cmd/agent/app.manifest b/agent/cmd/agent/app.manifestdeleted file mode 100644index 428de2cb..00000000--- a/agent/cmd/agent/app.manifest+++ /dev/null@@ -1,46 +0,0 @@-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>-<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">- <assemblyIdentity- type="win32"- name="ServerKit.Agent"- version="1.0.0.0"- processorArchitecture="*"/>- <description>ServerKit Agent</description>-- <dependency>- <dependentAssembly>- <assemblyIdentity- type="win32"- name="Microsoft.Windows.Common-Controls"- version="6.0.0.0"- processorArchitecture="*"- publicKeyToken="6595b64144ccf1df"- language="*"/>- </dependentAssembly>- </dependency>-- <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">- <security>- <requestedPrivileges>- <requestedExecutionLevel level="asInvoker" uiAccess="false"/>- </requestedPrivileges>- </security>- </trustInfo>-- <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">- <application>- <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>- <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>- <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>- <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>- <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>- </application>- </compatibility>-- <application xmlns="urn:schemas-microsoft-com:asm.v3">- <windowsSettings>- <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>- <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2,PerMonitor</dpiAwareness>- </windowsSettings>- </application>-</assembly>diff --git a/agent/cmd/agent/console_other.go b/agent/cmd/agent/console_other.godeleted file mode 100644index 96a507e2..00000000--- a/agent/cmd/agent/console_other.go+++ /dev/null@@ -1,8 +0,0 @@-//go:build !windows--package main--// attachParentConsole is a no-op outside Windows. The Windows build needs it-// to keep CLI output working when the binary is built with the windowsgui-// subsystem; on POSIX that subsystem distinction does not exist.-func attachParentConsole() {}diff --git a/agent/cmd/agent/console_windows.go b/agent/cmd/agent/console_windows.godeleted file mode 100644index 4e09c3c7..00000000--- a/agent/cmd/agent/console_windows.go+++ /dev/null@@ -1,34 +0,0 @@-//go:build windows--package main--import (- "os"- "syscall"-)--// attachParentConsole reattaches stdin/stdout/stderr to the parent console-// (e.g. PowerShell or cmd.exe) when the binary was built with the-// "windowsgui" subsystem. With that subsystem set, double-clicking a-// shortcut no longer flashes a console — but CLI invocations like-// `serverkit-agent register` would also lose their output. This call-// restores the terminal experience when one is available, and is a-// silent no-op when launched from Explorer/Start menu.-func attachParentConsole() {- const attachParentProcess = ^uint32(0) // -1, ATTACH_PARENT_PROCESS- kernel32 := syscall.NewLazyDLL("kernel32.dll")- proc := kernel32.NewProc("AttachConsole")- r, _, _ := proc.Call(uintptr(attachParentProcess))- if r == 0 {- return // no parent console; we're a GUI process- }- if h, err := syscall.Open("CONOUT$", os.O_WRONLY, 0); err == nil {- os.Stdout = os.NewFile(uintptr(h), "stdout")- }- if h, err := syscall.Open("CONOUT$", os.O_WRONLY, 0); err == nil {- os.Stderr = os.NewFile(uintptr(h), "stderr")- }- if h, err := syscall.Open("CONIN$", os.O_RDONLY, 0); err == nil {- os.Stdin = os.NewFile(uintptr(h), "stdin")- }-}diff --git a/agent/cmd/agent/desktop_debug.go b/agent/cmd/agent/desktop_debug.godeleted file mode 100644index 060587bd..00000000--- a/agent/cmd/agent/desktop_debug.go+++ /dev/null@@ -1,73 +0,0 @@-package main--import (- "fmt"- "os"- "path/filepath"- "sync"- "time"-)--// desktopLog is a small file-backed log used by runDesktop / runSetup so a-// failed launch is never invisible. We deliberately live alongside the agent's-// other state in %LOCALAPPDATA%\ServerKit\Agent rather than next to the exe-// (Program Files needs admin to write into).-type desktopLog struct {- mu sync.Mutex- f *os.File- p string-}--func (d *desktopLog) Path() string { return d.p }--// File exposes the underlying append-only handle so callers can redirect-// other writers (stdlib log, slog handlers) into the same file. Returns-// nil if the desktop log couldn't be opened — callers must guard.-func (d *desktopLog) File() *os.File {- if d == nil {- return nil- }- return d.f-}--func (d *desktopLog) Logf(format string, args ...interface{}) {- if d == nil || d.f == nil {- return- }- d.mu.Lock()- defer d.mu.Unlock()- line := fmt.Sprintf("[%s] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), fmt.Sprintf(format, args...))- _, _ = d.f.WriteString(line)- _ = d.f.Sync()-}--func (d *desktopLog) Close() {- if d == nil || d.f == nil {- return- }- _ = d.f.Close()-}--func openDesktopLog() *desktopLog {- candidates := []string{}- if v := os.Getenv("LOCALAPPDATA"); v != "" {- candidates = append(candidates, filepath.Join(v, "ServerKit", "Agent"))- }- if home, err := os.UserHomeDir(); err == nil {- candidates = append(candidates, filepath.Join(home, "AppData", "Local", "ServerKit", "Agent"))- }- candidates = append(candidates, os.TempDir())-- for _, dir := range candidates {- if err := os.MkdirAll(dir, 0o755); err != nil {- continue- }- p := filepath.Join(dir, "desktop.log")- f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)- if err != nil {- continue- }- return &desktopLog{f: f, p: p}- }- return &desktopLog{}-}diff --git a/agent/cmd/agent/instance_other.go b/agent/cmd/agent/instance_other.godeleted file mode 100644index 2aeb20d0..00000000--- a/agent/cmd/agent/instance_other.go+++ /dev/null@@ -1,15 +0,0 @@-//go:build !windows--package main--// acquireSingleInstance is a Windows-specific concern; on POSIX the user-// runs at most one tray per session anyway and we don't enforce it.-func acquireSingleInstance() (alreadyRunning bool, release func()) {- return false, func() {}-}--// acquireServiceInstance is a no-op on non-Windows; SCM doesn't exist-// and POSIX deployments rely on systemd to enforce single-instance.-func acquireServiceInstance() (alreadyRunning bool, release func()) {- return false, func() {}-}diff --git a/agent/cmd/agent/instance_windows.go b/agent/cmd/agent/instance_windows.godeleted file mode 100644index a61b107f..00000000--- a/agent/cmd/agent/instance_windows.go+++ /dev/null@@ -1,60 +0,0 @@-//go:build windows--package main--import (- "syscall"- "unsafe"-)--const errAlreadyExists = 183--// acquireSingleInstance opens (or creates) a per-user named mutex. If the-// mutex already existed, another instance of the desktop app is already-// running for this user and we should bow out. Otherwise we hold the mutex-// for the lifetime of the process.-//-// Per-user (Local\) namespace: each Windows user gets their own ServerKit-// tray, which matches the per-user Run-key autostart.-func acquireSingleInstance() (alreadyRunning bool, release func()) {- return acquireMutex(`Local\ServerKitAgentDesktop`)-}--// acquireServiceInstance is the agent-service equivalent of the desktop-// mutex above. Lives in the Global\ namespace because the service runs as-// SYSTEM and a per-user mutex wouldn't collide with a user-launched-// `serverkit-agent start`. With this in place, a second invocation of-// the start subcommand exits immediately with a clear message instead-// of racing the SCM-launched service for port 19780 and tripping a-// 30s "service did not respond" timeout.-func acquireServiceInstance() (alreadyRunning bool, release func()) {- return acquireMutex(`Global\ServerKitAgentService`)-}--func acquireMutex(name string) (alreadyRunning bool, release func()) {- kernel32 := syscall.NewLazyDLL("kernel32.dll")- createMutexW := kernel32.NewProc("CreateMutexW")- closeHandle := kernel32.NewProc("CloseHandle")-- wname, err := syscall.UTF16PtrFromString(name)- if err != nil {- return false, func() {}- }-- handle, _, lastErr := createMutexW.Call(- 0, // lpMutexAttributes = NULL- 0, // bInitialOwner = FALSE- uintptr(unsafe.Pointer(wname)),- )-- if handle == 0 {- return false, func() {}- }-- if errno, ok := lastErr.(syscall.Errno); ok && uintptr(errno) == errAlreadyExists {- closeHandle.Call(handle)- return true, func() {}- }-- return false, func() { closeHandle.Call(handle) }-}diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.godeleted file mode 100644index 062465be..00000000--- a/agent/cmd/agent/main.go+++ /dev/null@@ -1,809 +0,0 @@-package main--import (- "context"- "fmt"- stdlog "log"- "net"- "os"- "os/exec"- "os/signal"- "path/filepath"- "syscall"-- "github.com/serverkit/agent/internal/agent"- "github.com/serverkit/agent/internal/agentui"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/connstring"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/setupui"- pollclient "github.com/serverkit/agent/internal/transport/poll"- "github.com/serverkit/agent/internal/tray"- "github.com/serverkit/agent/internal/updater"- wsclient "github.com/serverkit/agent/internal/ws"- "github.com/spf13/cobra"-)--var (- Version = "dev"- BuildTime = "unknown"- GitCommit = "unknown"-)--// Mirror Version into every package that surfaces it in user-visible-// strings. ldflags set main.Version, but the agent / ws / poll packages-// each have their own Version var — they were silently drifting, which-// is why the panel UI displayed "ServerKit-Agent-Poll/dev" even when-// `serverkit-agent version` correctly printed the build tag.-func init() {- if Version != "dev" {- agent.Version = Version- wsclient.Version = Version- pollclient.Version = Version- }-}--var (- cfgFile string- debugMode bool- repair bool-)--func main() {- attachParentConsole()-- rootCmd := &cobra.Command{- Use: "serverkit-agent",- Short: "ServerKit Agent - Remote server management agent",- Long: `ServerKit Agent connects your server to a ServerKit control plane,-enabling remote Docker management, monitoring, and more.--When run without a subcommand on Windows, opens the desktop application-(pairing wizard if not configured, otherwise system tray).`,- RunE: func(cmd *cobra.Command, args []string) error {- return runDesktop()- },- SilenceUsage: true,- SilenceErrors: true,- }-- // Global flags- rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file path")- rootCmd.PersistentFlags().BoolVarP(&debugMode, "debug", "d", false, "enable debug logging")- rootCmd.PersistentFlags().BoolVar(&repair, "repair", false, "force the pairing wizard even if a config already exists")-- // Add commands- rootCmd.AddCommand(startCmd())- rootCmd.AddCommand(registerCmd())- rootCmd.AddCommand(pairCmd())- rootCmd.AddCommand(setupCmd())- rootCmd.AddCommand(statusCmd())- rootCmd.AddCommand(versionCmd())- rootCmd.AddCommand(configCmd())- rootCmd.AddCommand(updateCmd())- rootCmd.AddCommand(trayCmd())- rootCmd.AddCommand(consoleCmd())-- if err := rootCmd.Execute(); err != nil {- fmt.Fprintln(os.Stderr, err)- os.Exit(1)- }-}--func startCmd() *cobra.Command {- return &cobra.Command{- Use: "start",- Short: "Start the agent service",- RunE: func(cmd *cobra.Command, args []string) error {- return runAgent()- },- }-}--func registerCmd() *cobra.Command {- var token string- var serverURL string- var name string- var connStr string-- cmd := &cobra.Command{- Use: "register",- Short: "Register this agent with a ServerKit instance",- RunE: func(cmd *cobra.Command, args []string) error {- // Let the secret-bearing inputs come from the environment so the- // installer never has to put the registration token in argv —- // process arguments are world-readable (`ps`, /proc/<pid>/cmdline),- // whereas a process's environment is readable only by its owner and- // root. Explicit flags still win when provided.- if connStr == "" {- connStr = os.Getenv("SERVERKIT_CONNECTION_STRING")- }- if token == "" {- token = os.Getenv("SERVERKIT_REGISTRATION_TOKEN")- }- if serverURL == "" {- serverURL = os.Getenv("SERVERKIT_SERVER_URL")- }-- // --connection-string is the modern entry path: a single- // pasteable blob from the panel that already contains the- // URL and token. When present, it overrides the legacy- // flags so users don't have to copy three things.- if connStr != "" {- decoded, err := connstring.Decode(connStr)- if err != nil {- return fmt.Errorf("invalid connection string: %w", err)- }- return runRegister(decoded.Token, decoded.URL, name)- }- if token == "" || serverURL == "" {- return fmt.Errorf("provide either --connection-string or both --token and --server")- }- return runRegister(token, serverURL, name)- },- }-- // no shorthand: "c" belongs to the global --config persistent flag, and- // pflag panics on shorthand redefinition the moment any command runs- cmd.Flags().StringVar(&connStr, "connection-string", "", "panel connection string (single value, replaces --token + --server)")- cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (use with --server; or set SERVERKIT_REGISTRATION_TOKEN to keep it out of the process arg list)")- cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit server URL (use with --token)")- cmd.Flags().StringVarP(&name, "name", "n", "", "display name for this server")-- return cmd-}--func statusCmd() *cobra.Command {- return &cobra.Command{- Use: "status",- Short: "Show agent status",- RunE: func(cmd *cobra.Command, args []string) error {- return showStatus()- },- }-}--func versionCmd() *cobra.Command {- return &cobra.Command{- Use: "version",- Short: "Show version information",- Run: func(cmd *cobra.Command, args []string) {- fmt.Printf("ServerKit Agent\n")- fmt.Printf(" Version: %s\n", Version)- fmt.Printf(" Build Time: %s\n", BuildTime)- fmt.Printf(" Git Commit: %s\n", GitCommit)- },- }-}--func configCmd() *cobra.Command {- cmd := &cobra.Command{- Use: "config",- Short: "Configuration management",- }-- cmd.AddCommand(&cobra.Command{- Use: "show",- Short: "Show current configuration",- RunE: func(cmd *cobra.Command, args []string) error {- cfg, err := config.Load(cfgFile)- if err != nil {- return fmt.Errorf("failed to load config: %w", err)- }- cfg.Print()- return nil- },- })-- cmd.AddCommand(&cobra.Command{- Use: "path",- Short: "Show configuration file path",- Run: func(cmd *cobra.Command, args []string) {- fmt.Println(config.DefaultConfigPath())- },- })-- return cmd-}--func updateCmd() *cobra.Command {- var forceUpdate bool- var checkOnly bool-- cmd := &cobra.Command{- Use: "update",- Short: "Check for and install updates",- Long: `Check for available updates and optionally install them.--By default, this command checks for updates and prompts before installing.-Use --force to install without prompting.-Use --check to only check for updates without installing.`,- RunE: func(cmd *cobra.Command, args []string) error {- return runUpdate(forceUpdate, checkOnly)- },- }-- cmd.Flags().BoolVarP(&forceUpdate, "force", "f", false, "install update without prompting")- cmd.Flags().BoolVarP(&checkOnly, "check", "c", false, "only check for updates, don't install")-- return cmd-}--func runUpdate(force, checkOnly bool) error {- // Load configuration- cfg, err := config.Load(cfgFile)- if err != nil {- return fmt.Errorf("failed to load config: %w", err)- }-- log := logger.New(config.LoggingConfig{Level: "info"})- u := updater.New(cfg, log, Version)-- ctx := context.Background()-- fmt.Printf("Current version: %s\n", Version)- fmt.Println("Checking for updates...")-- info, err := u.CheckForUpdate(ctx)- if err != nil {- return fmt.Errorf("failed to check for updates: %w", err)- }-- if !info.UpdateAvailable {- fmt.Println("You are running the latest version.")- return nil- }-- fmt.Printf("\nUpdate available: v%s -> v%s\n", info.CurrentVersion, info.LatestVersion)- fmt.Printf("Published: %s\n", info.PublishedAt)- if info.ReleaseNotesURL != "" {- fmt.Printf("Release notes: %s\n", info.ReleaseNotesURL)- }-- if checkOnly {- return nil- }-- // Prompt for confirmation unless forced- if !force {- fmt.Print("\nDo you want to install this update? [y/N]: ")- var response string- fmt.Scanln(&response)- if response != "y" && response != "Y" {- fmt.Println("Update cancelled.")- return nil- }- }-- fmt.Println("\nDownloading update...")- binaryPath, err := u.DownloadUpdate(ctx, info)- if err != nil {- return fmt.Errorf("failed to download update: %w", err)- }-- fmt.Println("Installing update...")- if err := u.InstallUpdate(binaryPath); err != nil {- u.Cleanup(binaryPath)- return fmt.Errorf("failed to install update: %w", err)- }-- fmt.Println("\nUpdate installed successfully!")- fmt.Println("The agent will restart with the new version.")-- return nil-}--func runAgent() error {- // SCM detection: when launched as a Windows Service, the binary must- // implement the Service Control dispatcher protocol or SCM kills it- // with error 1053 within 30s. Older versions of the agent skipped- // this entirely — every "Start-Service ServerKitAgent" was silently- // failing while manual `serverkit-agent start` worked, which had- // users running the agent in foreground console windows as a- // workaround. Now: if SCM started us, route through svc.Run; if- // the user ran it from CLI, run directly with signal handling.- if isWindowsService() {- return runAsService(agentMainLoop)- }- return agentMainLoop(nil)-}--// agentMainLoop is the actual run logic, factored out so both the-// SCM-driven path (svc.Run dispatching to serviceHandler.Execute) and-// the CLI path can share it. Pass nil for ctx to use a fresh-// signal-handled context (CLI mode); pass the SCM-supplied ctx for-// service mode.-func agentMainLoop(parentCtx context.Context) error {- // Load configuration- cfg, err := config.Load(cfgFile)- if err != nil {- return fmt.Errorf("failed to load config: %w", err)- }-- // Override debug mode if flag is set- if debugMode {- cfg.Logging.Level = "debug"- }-- // Initialize logger- log := logger.New(cfg.Logging)- log.Info("Starting ServerKit Agent",- "version", Version,- "config", config.DefaultConfigPath(),- "mode", map[bool]string{true: "service", false: "cli"}[isWindowsService()],- )-- // Loud warning if credentials failed to decrypt. Without surfacing- // this, the agent would proceed with empty APIKey/APISecret and- // every panel /connect would 400 "Missing required fields" — which- // is exactly the silent failure mode that hid this bug for years.- if cfg.Auth.LoadError != "" && cfg.Agent.ID != "" {- log.Error("Failed to load credentials — agent cannot authenticate. "+- "Re-pair the agent (Actions → Open wizard) to regenerate the key file.",- "error", cfg.Auth.LoadError,- "key_file", cfg.Auth.KeyFile,- )- }-- // Single-instance enforcement for the service. Multiple "start"- // invocations would fight for IPC port 19780 and the SCM-launched- // service would lose to a manually-started one (or vice versa) with- // a 30s timeout in either direction. Mutex is in the Global\- // namespace because the service runs as SYSTEM and a per-user lock- // wouldn't catch a user-context "serverkit-agent start" race.- if alreadyRunning, release := acquireServiceInstance(); alreadyRunning {- log.Error("Another ServerKit agent service is already running. " +- "If this is unexpected, end leftover serverkit-agent.exe processes via " +- "Task Manager (or run `taskkill /F /IM serverkit-agent.exe /T`) and try again.")- return fmt.Errorf("another agent service is already running (mutex held)")- } else {- defer release()- }-- // Probe the IPC port up-front. If it's held by something else (a- // stale agent, another tool, anything), fail fast with a clear- // message instead of letting the IPC server later time out and- // trip SCM's 1053 "service did not respond" error.- if cfg.IPC.Enabled {- probe, perr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.IPC.Port))- if perr != nil {- log.Error("IPC port is already in use — likely a leftover serverkit-agent.exe process",- "port", cfg.IPC.Port, "error", perr)- return fmt.Errorf("IPC port %d is in use; "+- "end leftover agent processes (Task Manager → 'serverkit-agent.exe') and try again",- cfg.IPC.Port)- }- // Release the probe — the real IPC server will rebind in a moment.- // There's a tiny race window where another process could grab the- // port between probe-close and real-bind, but that's acceptable- // for what's effectively a "is anyone else here?" check.- probe.Close()- }-- // Check if registered- if cfg.Agent.ID == "" {- return fmt.Errorf("agent not registered. Run 'serverkit-agent register' first")- }-- // Build the run context. Service mode supplies its own (cancelled- // when SCM sends Stop). CLI mode wires SIGINT/SIGTERM as the- // cancellation signal.- var ctx context.Context- var cancel context.CancelFunc- if parentCtx != nil {- ctx, cancel = context.WithCancel(parentCtx)- } else {- ctx, cancel = context.WithCancel(context.Background())- sigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)- go func() {- sig := <-sigCh- log.Info("Received shutdown signal", "signal", sig.String())- cancel()- }()- }- defer cancel()-- ag, err := agent.New(cfg, log)- if err != nil {- return fmt.Errorf("failed to create agent: %w", err)- }-- // Start update checker in background- updateChecker := updater.NewChecker(cfg, log, Version)- go updateChecker.Start(ctx)-- // Start agent- if err := ag.Run(ctx); err != nil && err != context.Canceled {- return fmt.Errorf("agent error: %w", err)- }-- log.Info("Agent stopped gracefully")- return nil-}--func runRegister(token, serverURL, name string) error {- log := logger.New(config.LoggingConfig{Level: "info"})-- log.Info("Registering agent with ServerKit",- "server", serverURL,- )-- // Load or create config- cfg, err := config.Load(cfgFile)- if err != nil {- // Create new config if doesn't exist- cfg = config.Default()- }-- // Register with server- reg := agent.NewRegistration(log)- result, err := reg.Register(serverURL, token, name)- if err != nil {- return fmt.Errorf("registration failed: %w", err)- }-- // Update config- cfg.Server.URL = result.WebSocketURL- cfg.Agent.ID = result.AgentID- cfg.Agent.Name = result.Name- cfg.Auth.APIKey = result.APIKey- cfg.Auth.APISecret = result.APISecret-- // Determine config path (use --config flag if set, otherwise default)- configPath := cfgFile- if configPath == "" {- configPath = config.DefaultConfigPath()- }-- // Update key file path to be relative to config directory if using custom path- if cfgFile != "" {- cfg.Auth.KeyFile = filepath.Join(filepath.Dir(configPath), "agent.key")- }-- // Save config (key_file path must be set before saving)- if err := cfg.Save(configPath); err != nil {- return fmt.Errorf("failed to save config: %w", err)- }-- // Save credentials securely- if err := cfg.SaveCredentials(); err != nil {- return fmt.Errorf("failed to save credentials: %w", err)- }-- log.Info("Registration successful!",- "agent_id", result.AgentID,- "name", result.Name,- )-- fmt.Println("\nAgent registered successfully!")- fmt.Printf(" Agent ID: %s\n", result.AgentID)- fmt.Printf(" Name: %s\n", result.Name)- fmt.Println("\nStart the agent with: serverkit-agent start")-- return nil-}--func showStatus() error {- cfg, err := config.Load(cfgFile)- if err != nil {- fmt.Println("Status: Not configured")- fmt.Printf(" Config file not found at %s\n", config.DefaultConfigPath())- fmt.Println("\nRun 'serverkit-agent register' to configure.")- return nil- }-- if cfg.Agent.ID == "" {- fmt.Println("Status: Not registered")- fmt.Println("\nRun 'serverkit-agent register' to register with a ServerKit instance.")- return nil- }-- fmt.Println("Status: Configured")- fmt.Printf(" Agent ID: %s\n", cfg.Agent.ID)- fmt.Printf(" Agent Name: %s\n", cfg.Agent.Name)- fmt.Printf(" Server: %s\n", cfg.Server.URL)-- // TODO: Check if actually connected- // This would require checking a PID file or socket-- return nil-}--func setupCmd() *cobra.Command {- return &cobra.Command{- Use: "setup",- Short: "Open the pairing wizard",- Long: `Opens the desktop console at the pairing wizard. Enter the panel-URL and a server name; the agent generates a code and passphrase to type-into the panel UI to claim this server.--For headless servers, use 'serverkit-agent pair' instead.`,- RunE: func(cmd *cobra.Command, args []string) error {- // The wizard now lives inside the React console; setup is a- // thin alias that opens it. The PairGate component routes the- // user straight to /pair when no config is present.- if legacyWizard {- return runSetup()- }- return runConsole()- },- }-}--// consoleCmd opens the WebView2-based agent console window. Sibling to the-// `setup` (pairing wizard) command — they coexist while the wizard is being-// migrated to the same React app. Once the wizard lives inside the console,-// `setup` becomes a thin alias that opens the console at the /pair route.-func consoleCmd() *cobra.Command {- return &cobra.Command{- Use: "console",- Short: "Open the agent console window (status, logs, actions)",- Long: `Opens the desktop console for this agent. Shows pairing status,-connection state, recent activity, raw logs, and service controls.`,- RunE: func(cmd *cobra.Command, args []string) error {- return runConsole()- },- }-}--func runConsole() error {- dbg := openDesktopLog()- defer dbg.Close()- dbg.Logf("--- runConsole start, version=%s pid=%d ---", Version, os.Getpid())-- // go-webview2 uses the stdlib log package internally for fatal errors- // during chromium init. Without this redirect, "Error calling- // Webview2Loader: ..." goes to a hidden stdout and we'd never see it- // on a blank-window report. Path is the same desktop.log so all the- // diagnostic breadcrumbs end up in one file.- if f := dbg.File(); f != nil {- stdlog.SetOutput(f)- stdlog.SetFlags(stdlog.LstdFlags | stdlog.Lmicroseconds)- stdlog.SetPrefix("[stdlib] ")- }-- defer func() {- if r := recover(); r != nil {- msg := fmt.Sprintf("ServerKit Agent console crashed:\n\n%v\n\nLog: %s", r, dbg.Path())- dbg.Logf("PANIC: %v", r)- showMessageBox("ServerKit Agent", msg, mbIconError)- }- }()-- // Point the slog logger at the same desktop.log so internal log.Info- // calls in agentui land alongside the dbg.Logf trail. Without this, any- // diagnostic logging from the package goes to a hidden stdout (the- // console binary uses the windowsgui subsystem) and we end up debugging- // blank windows blind.- log := logger.New(config.LoggingConfig{- Level: "info",- File: dbg.Path(),- MaxSize: 10,- MaxBackups: 2,- MaxAge: 7,- })-- configPath := cfgFile- if configPath == "" {- configPath = config.DefaultConfigPath()- }- dbg.Logf("configPath=%s", configPath)-- ctx, cancel := context.WithCancel(context.Background())- defer cancel()-- sigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)- go func() {- <-sigCh- cancel()- }()-- dbg.Logf("calling agentui.Run …")- err := agentui.Run(ctx, log, configPath)- dbg.Logf("agentui.Run returned: %v", err)- if err != nil {- showMessageBox("ServerKit Agent",- fmt.Sprintf("Couldn't open the agent console.\n\n%v\n\nLog: %s", err, dbg.Path()),- mbIconError)- }- return err-}--// runSetup is retained as a fallback into the legacy walk wizard. The-// current setup command points at runConsole, but if WebView2 is somehow-// unavailable on a target machine the user can still pair via this path-// by setting SERVERKIT_AGENT_LEGACY_WIZARD=1.-func runSetup() error {- dbg := openDesktopLog()- defer dbg.Close()- dbg.Logf("--- runSetup (legacy) start, version=%s pid=%d ---", Version, os.Getpid())-- log := logger.New(config.LoggingConfig{Level: "info"})-- configPath := cfgFile- if configPath == "" {- configPath = config.DefaultConfigPath()- }-- ctx, cancel := context.WithCancel(context.Background())- defer cancel()-- sigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)- go func() {- <-sigCh- cancel()- }()-- return setupui.Run(ctx, log, configPath)-}--// init wires the legacy fallback when explicitly requested, replacing the-// console-based setup runner with the walk wizard. This is purely an escape-// hatch — primary path is the React console.-func init() {- if os.Getenv("SERVERKIT_AGENT_LEGACY_WIZARD") == "1" {- legacyWizard = true- }-}--var legacyWizard bool--// runDesktop is what `serverkit-agent` (no args) does on a desktop install.-// First-run: shows the pairing wizard. Subsequent runs (config exists): goes-// straight to tray. Either way the tray runs after pairing completes.-// runDesktop is what `serverkit-agent` (no args) does on a desktop install.-// Architecture: the tray always runs in this process and is the primary-// entry point — the user-visible app. If the agent is unconfigured (or the-// caller passed --repair) we spawn the pairing wizard as a *separate*-// detached process so the tray is visible immediately and remains the-// recovery surface even if the wizard fails to render.-func runDesktop() error {- dbg := openDesktopLog()- defer dbg.Close()- dbg.Logf("--- runDesktop start, version=%s pid=%d ---", Version, os.Getpid())-- // Single-instance: if a tray is already running for this user, just- // kick the wizard if needed and exit. Avoids the two-trays-in-one-bar- // problem when the autostart and a Start-menu click race.- if alreadyRunning, release := acquireSingleInstance(); alreadyRunning {- dbg.Logf("another instance is already running; not starting a second tray")- if repair {- spawnSetupWizard(dbg)- }- return nil- } else {- defer release()- }-- cfg, cfgErr := config.Load(cfgFile)- dbg.Logf("config.Load err=%v", cfgErr)- if cfg != nil {- dbg.Logf("agent.id=%q server.url=%q", cfg.Agent.ID, cfg.Server.URL)- }-- needsSetup := cfg == nil || cfg.Agent.ID == "" || repair- dbg.Logf("needsSetup=%v (repair=%v)", needsSetup, repair)-- if needsSetup {- spawnSetupWizard(dbg)- }-- dbg.Logf("→ launching tray (needsSetup=%v)", needsSetup)- return runTrayWithOpts(cfg, needsSetup)-}--func cfgName(cfg *config.Config) string {- if cfg == nil {- return ""- }- return cfg.Agent.Name-}--// spawnSetupWizard launches `serverkit-agent setup` as a detached child so-// the wizard runs in its own process and the parent (the tray) is unaffected-// by what happens to the wizard's window. Used both at desktop boot when-// pairing is needed and from the tray's "Open setup wizard…" menu.-func spawnSetupWizard(dbg *desktopLog) {- exe, err := os.Executable()- if err != nil {- if dbg != nil {- dbg.Logf("spawn: os.Executable err=%v", err)- }- return- }- cmd := exec.Command(exe, "setup")- cmd.SysProcAttr = detachedProcessAttrs()- if err := cmd.Start(); err != nil {- if dbg != nil {- dbg.Logf("spawn: cmd.Start err=%v", err)- }- return- }- if dbg != nil {- dbg.Logf("spawn: wizard pid=%d started", cmd.Process.Pid)- }-}--// reopenSetupWizard is the OnOpenSetup callback the tray hands to its menu.-// Same as spawnSetupWizard but without a debug log (the tray runs in the-// long-lived parent process where re-opening logs would be noisy).-func reopenSetupWizard() {- spawnSetupWizard(nil)-}--func trayCmd() *cobra.Command {- return &cobra.Command{- Use: "tray",- Short: "Run the system tray application",- Long: `Start the ServerKit Agent system tray application.--The tray app shows the agent status in the system tray and provides-quick access to start/stop the service, view logs, and open the dashboard.--This is typically auto-started on Windows login when installed via MSI.`,- RunE: func(cmd *cobra.Command, args []string) error {- return runTray()- },- }-}--func runTray() error {- cfg, err := config.Load(cfgFile)- if err != nil {- cfg = config.Default()- }- return runTrayWithOpts(cfg, cfg.Agent.ID == "")-}--func runTrayWithOpts(cfg *config.Config, needsSetup bool) error {- if cfg == nil {- cfg = config.Default()- }-- app := tray.NewApp(tray.AppConfig{- Version: Version,- IPCAddress: cfg.IPC.Address,- IPCPort: cfg.IPC.Port,- ServerURL: cfg.Server.URL,- DashboardURL: getDashboardURL(cfg.Server.URL),- LogFile: cfg.Logging.File,- NeedsSetup: needsSetup,- OnOpenSetup: reopenSetupWizard,- })-- sigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)-- go func() {- <-sigCh- app.Quit()- }()-- app.Run()- return nil-}--func getDashboardURL(serverURL string) string {- // Convert WebSocket URL to HTTP dashboard URL- // wss://server.example.com/ws/agent -> https://server.example.com- if serverURL == "" {- return ""- }- // Simple conversion - strip /ws/agent suffix and convert wss to https- url := serverURL- if len(url) > 4 && url[:4] == "wss:" {- url = "https:" + url[4:]- } else if len(url) > 3 && url[:3] == "ws:" {- url = "http:" + url[3:]- }- // Strip path suffix- for i := len(url) - 1; i >= 0; i-- {- if url[i] == '/' && i > 8 { // After https://- return url[:i]- }- }- return url-}diff --git a/agent/cmd/agent/msgbox_other.go b/agent/cmd/agent/msgbox_other.godeleted file mode 100644index a72c6aa1..00000000--- a/agent/cmd/agent/msgbox_other.go+++ /dev/null@@ -1,10 +0,0 @@-//go:build !windows--package main--const (- mbIconError = 0- mbIconInfo = 0-)--func showMessageBox(_ string, _ string, _ uint32) {}diff --git a/agent/cmd/agent/msgbox_windows.go b/agent/cmd/agent/msgbox_windows.godeleted file mode 100644index 9167b5b8..00000000--- a/agent/cmd/agent/msgbox_windows.go+++ /dev/null@@ -1,24 +0,0 @@-//go:build windows--package main--import (- "syscall"- "unsafe"-)--const (- mbIconError = 0x00000010- mbIconInfo = 0x00000040-)--// showMessageBox is a tiny user32!MessageBoxW wrapper for early-stage failures-// where we either don't have walk loaded yet or we want to display before the-// main window exists. Modal; blocks until the user clicks OK.-func showMessageBox(title, body string, icon uint32) {- user32 := syscall.NewLazyDLL("user32.dll")- mb := user32.NewProc("MessageBoxW")- t, _ := syscall.UTF16PtrFromString(title)- b, _ := syscall.UTF16PtrFromString(body)- _, _, _ = mb.Call(0, uintptr(unsafe.Pointer(b)), uintptr(unsafe.Pointer(t)), uintptr(icon))-}diff --git a/agent/cmd/agent/pair.go b/agent/cmd/agent/pair.godeleted file mode 100644index 608fb98a..00000000--- a/agent/cmd/agent/pair.go+++ /dev/null@@ -1,258 +0,0 @@-package main--import (- "bufio"- "context"- "crypto/rand"- "encoding/base64"- "fmt"- "os"- "path/filepath"- "runtime"- "strings"- "syscall"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/metrics"- "github.com/serverkit/agent/internal/pairing"- "github.com/spf13/cobra"- "golang.org/x/term"-)--// pairCmd implements `serverkit-agent pair` — RustDesk-style short-code pairing.-//-// Flags:-//-// --server, -s Panel base URL (e.g. https://panel.example.com)-// --passphrase Passphrase to set on this agent (will prompt if absent)-// --headless No interactive prompts; read passphrase from $SERVERKIT_AGENT_PASSPHRASE-// --set-passphrase Write/overwrite passphrase only; don't begin pairing-func pairCmd() *cobra.Command {- var (- serverURL string- passphrase string- headless bool- setPassphrase bool- )-- cmd := &cobra.Command{- Use: "pair",- Short: "Pair this agent with a ServerKit panel using a short code",- Long: `Pair this agent with a ServerKit panel.--Generates an Ed25519 keypair (cached at-rest), enrolls with the panel, and-displays a rotating 6-character pair code. An operator enters that code +-the passphrase set here in the panel UI to claim this server. Once claimed,-credentials are saved and the agent is ready to start.--This is the recommended way to add a server. Run 'serverkit-agent register'-only if you have a long pre-shared registration token.`,- RunE: func(cmd *cobra.Command, args []string) error {- return runPair(serverURL, passphrase, headless, setPassphrase)- },- }-- cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit panel URL (required, unless previously paired)")- cmd.Flags().StringVar(&passphrase, "passphrase", "", "passphrase (will prompt if empty)")- cmd.Flags().BoolVar(&headless, "headless", false, "no interactive prompts; read $SERVERKIT_AGENT_PASSPHRASE")- cmd.Flags().BoolVar(&setPassphrase, "set-passphrase", false, "store passphrase only; don't pair yet")-- return cmd-}--func runPair(serverURL, passphrase string, headless, setPassphraseOnly bool) error {- log := logger.New(config.LoggingConfig{Level: "info"})-- // Resolve passphrase- if passphrase == "" && headless {- passphrase = os.Getenv("SERVERKIT_AGENT_PASSPHRASE")- if passphrase == "" {- return fmt.Errorf("--headless requires SERVERKIT_AGENT_PASSPHRASE env var")- }- }- if passphrase == "" {- var err error- passphrase, err = promptPassphrase()- if err != nil {- return err- }- }- if len(passphrase) < 4 {- return fmt.Errorf("passphrase must be at least 4 characters")- }-- // Persist passphrase reference (for later re-pair flows). We never write- // the plaintext to disk; we only store a marker so the tray can show- // "passphrase set". The bcrypt'd canonical form lives on the panel.- if err := writePassphraseMarker(); err != nil {- log.Warn("could not write passphrase marker", "error", err)- }-- if setPassphraseOnly {- fmt.Println("Passphrase stored. Run 'serverkit-agent pair --server <url>' when ready to pair.")- return nil- }-- if serverURL == "" {- return fmt.Errorf("--server is required (e.g. --server https://panel.example.com)")- }-- // Load or create Ed25519 pairing keypair- kp, err := pairing.LoadOrCreate(pairing.DefaultKeyPath())- if err != nil {- return fmt.Errorf("load keypair: %w", err)- }-- // Collect system info- collector := metrics.NewCollector(config.MetricsConfig{}, log)- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- sysInfo, _ := collector.GetSystemInfo(ctx)- sysMap := map[string]interface{}{}- if sysInfo != nil {- sysMap = map[string]interface{}{- "hostname": sysInfo.Hostname,- "os": sysInfo.OS,- "platform": sysInfo.Platform,- "platform_version": sysInfo.PlatformVersion,- "architecture": sysInfo.Architecture,- "cpu_cores": sysInfo.CPUCores,- "total_memory": sysInfo.TotalMemory,- "total_disk": sysInfo.TotalDisk,- "agent_version": Version,- }- } else {- hostname, _ := os.Hostname()- sysMap["hostname"] = hostname- sysMap["os"] = runtime.GOOS- sysMap["architecture"] = runtime.GOARCH- sysMap["agent_version"] = Version- }-- // Enroll- client := pairing.NewClient(serverURL, log)- enrollCtx, enrollCancel := context.WithTimeout(context.Background(), 30*time.Second)- defer enrollCancel()-- enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{- Pubkey: kp.PublicKeyHex(),- Passphrase: passphrase,- MachineID: config.MachineID(),- SystemInfo: sysMap,- })- if err != nil {- return fmt.Errorf("enroll failed: %w", err)- }-- printPairBanner(enrollResp.PairCodeFormatted, enrollResp.PubkeyFingerprint)-- // Wait for claim (with periodic code rotation)- claimCtx, claimCancel := context.WithCancel(context.Background())- defer claimCancel()-- creds, err := client.WaitForClaim(claimCtx, func(code, formatted, expiresAt string) {- printPairBanner(formatted, enrollResp.PubkeyFingerprint)- })- if err != nil {- return fmt.Errorf("waiting for claim: %w", err)- }-- // Save credentials and config- cfg, err := config.Load(cfgFile)- if err != nil {- cfg = config.Default()- }-- wsURL := strings.TrimSuffix(serverURL, "/")- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)- cfg.Server.URL = wsURL + "/agent"- cfg.Agent.ID = creds.AgentID- cfg.Agent.Name = creds.Name- cfg.Auth.APIKey = creds.APIKey- cfg.Auth.APISecret = creds.APISecret-- configPath := cfgFile- if configPath == "" {- configPath = config.DefaultConfigPath()- }- if cfgFile != "" {- cfg.Auth.KeyFile = filepath.Join(filepath.Dir(configPath), "agent.key")- }- if err := cfg.Save(configPath); err != nil {- return fmt.Errorf("save config: %w", err)- }- if err := cfg.SaveCredentials(); err != nil {- return fmt.Errorf("save credentials: %w", err)- }-- fmt.Println()- fmt.Println("✓ Pairing successful!")- fmt.Printf(" Server name: %s\n", creds.Name)- fmt.Printf(" Agent ID: %s\n", creds.AgentID)- fmt.Printf(" Fingerprint: %s\n", enrollResp.PubkeyFingerprint)- fmt.Println()- fmt.Println("Start the agent with: serverkit-agent start")- return nil-}--func printPairBanner(code, fingerprint string) {- fmt.Println()- fmt.Println("┌──────────────────────────────────────────────┐")- fmt.Println("│ ServerKit Agent — Pairing │")- fmt.Println("├──────────────────────────────────────────────┤")- fmt.Printf("│ Pair code: %-30s│\n", code)- fmt.Printf("│ Fingerprint: %-30s│\n", fingerprint)- fmt.Println("├──────────────────────────────────────────────┤")- fmt.Println("│ 1. Open ServerKit panel → Add Server │")- fmt.Println("│ 2. Enter the pair code + your passphrase │")- fmt.Println("│ 3. Verify the fingerprint matches │")- fmt.Println("└──────────────────────────────────────────────┘")- fmt.Println("Waiting for claim...")-}--func promptPassphrase() (string, error) {- if !term.IsTerminal(int(syscall.Stdin)) {- // Fallback: read line from stdin (e.g., piped postinst input)- reader := bufio.NewReader(os.Stdin)- fmt.Print("Passphrase: ")- line, err := reader.ReadString('\n')- if err != nil {- return "", err- }- return strings.TrimRight(line, "\r\n"), nil- }- fmt.Print("Set a passphrase for this agent (4+ chars, you'll need it to pair): ")- pass, err := term.ReadPassword(int(syscall.Stdin))- fmt.Println()- if err != nil {- return "", err- }- fmt.Print("Confirm passphrase: ")- pass2, err := term.ReadPassword(int(syscall.Stdin))- fmt.Println()- if err != nil {- return "", err- }- if string(pass) != string(pass2) {- return "", fmt.Errorf("passphrases do not match")- }- return string(pass), nil-}--// writePassphraseMarker writes a non-secret marker file used by the tray to-// indicate that a passphrase has been configured. It does NOT contain the-// passphrase itself.-func writePassphraseMarker() error {- dir := filepath.Dir(pairing.DefaultKeyPath())- if err := os.MkdirAll(dir, 0700); err != nil {- return err- }- marker := filepath.Join(dir, "passphrase.set")- // Random non-secret token so the file timestamps differ across resets.- buf := make([]byte, 16)- _, _ = rand.Read(buf)- return os.WriteFile(marker, []byte(base64.RawURLEncoding.EncodeToString(buf)), 0600)-}diff --git a/agent/cmd/agent/rsrc_windows_amd64.syso b/agent/cmd/agent/rsrc_windows_amd64.sysodeleted file mode 100644index 4fa39879..00000000Binary files a/agent/cmd/agent/rsrc_windows_amd64.syso and /dev/null differdiff --git a/agent/cmd/agent/rsrc_windows_arm64.syso b/agent/cmd/agent/rsrc_windows_arm64.sysodeleted file mode 100644index e6663a50..00000000Binary files a/agent/cmd/agent/rsrc_windows_arm64.syso and /dev/null differdiff --git a/agent/cmd/agent/service_other.go b/agent/cmd/agent/service_other.godeleted file mode 100644index 7fad4d1c..00000000--- a/agent/cmd/agent/service_other.go+++ /dev/null@@ -1,13 +0,0 @@-//go:build !windows--package main--import "context"--// runAsService is a no-op stub on POSIX — systemd handles process-// supervision, so there's nothing to dispatch.-func runAsService(runFn func(ctx context.Context) error) error {- return runFn(context.Background())-}--func isWindowsService() bool { return false }diff --git a/agent/cmd/agent/service_windows.go b/agent/cmd/agent/service_windows.godeleted file mode 100644index 1ad8f853..00000000--- a/agent/cmd/agent/service_windows.go+++ /dev/null@@ -1,100 +0,0 @@-//go:build windows--package main--import (- "context"- "fmt"-- "golang.org/x/sys/windows/svc"-)--// serviceHandler implements the Windows Service Control dispatcher-// contract. SCM launches the binary, calls Execute on a serviceHandler,-// expects status callbacks via the supplied channel within 30s. Without-// this dispatcher the binary runs normally but never signals-// SERVICE_RUNNING and SCM kills it with error 1053. Agents on Windows-// have been silently failing as services since the 1.0 line because of-// this — the whole "Start-Service ServerKitAgent" path was broken.-type serviceHandler struct {- // runFn is the actual agent loop. Returns when ctx is cancelled or- // the agent terminates on its own. We pass it a cancellable ctx and- // flip cancel when SCM tells us to stop.- runFn func(ctx context.Context) error-}--// Execute is invoked by svc.Run after the SCM connection is established.-// We immediately tell SCM we're starting, then SCM we're running, then-// run the agent loop in a goroutine while we listen for stop/shutdown-// requests on the supplied channel. The svc package owns the timing of-// the SCM handshake so all we need to do is push the right StateRunning-// / StateStopped statuses at the right moments.-func (h *serviceHandler) Execute(args []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (svcSpecificEC bool, exitCode uint32) {- const accepted = svc.AcceptStop | svc.AcceptShutdown- status <- svc.Status{State: svc.StartPending}-- ctx, cancel := context.WithCancel(context.Background())- defer cancel()-- runDone := make(chan error, 1)- go func() {- runDone <- h.runFn(ctx)- }()-- status <- svc.Status{State: svc.Running, Accepts: accepted}-- for {- select {- case c := <-r:- switch c.Cmd {- case svc.Interrogate:- // SCM polling for liveness — re-echo our status so it- // knows we're still alive. Required by the contract.- status <- c.CurrentStatus- case svc.Stop, svc.Shutdown:- status <- svc.Status{State: svc.StopPending}- cancel()- // Wait for the agent loop to exit cleanly. svc.Run- // internally allows up to 30s after StopPending- // before SCM force-kills, which matches the existing- // shutdown timing in agent.Run.- <-runDone- status <- svc.Status{State: svc.Stopped}- return false, 0- default:- // Unknown control code — ignore. SCM doesn't send- // pause/continue without us advertising support.- }- case err := <-runDone:- // Agent loop exited on its own (config error, fatal panic- // caught upstream, etc.). Tell SCM we're done so the- // service shows as stopped instead of "running but dead".- if err != nil && err != context.Canceled {- status <- svc.Status{State: svc.Stopped, Win32ExitCode: 1}- return false, 1- }- status <- svc.Status{State: svc.Stopped}- return false, 0- }- }-}--// runAsService is the SCM entry point. Called from runAgent when we-// detect we're in a service context. Blocks until SCM tells us to stop.-func runAsService(runFn func(ctx context.Context) error) error {- if err := svc.Run("ServerKitAgent", &serviceHandler{runFn: runFn}); err != nil {- return fmt.Errorf("service dispatcher failed: %w", err)- }- return nil-}--// isWindowsService reports whether the current process was launched by-// the SCM. The svc package detects this by inspecting the process tree-// and the Windows session — there's no other reliable signal.-func isWindowsService() bool {- in, err := svc.IsWindowsService()- if err != nil {- return false- }- return in-}diff --git a/agent/cmd/agent/spawn_other.go b/agent/cmd/agent/spawn_other.godeleted file mode 100644index 3302450b..00000000--- a/agent/cmd/agent/spawn_other.go+++ /dev/null@@ -1,9 +0,0 @@-//go:build !windows--package main--import "syscall"--func detachedProcessAttrs() *syscall.SysProcAttr {- return &syscall.SysProcAttr{Setpgid: true}-}diff --git a/agent/cmd/agent/spawn_windows.go b/agent/cmd/agent/spawn_windows.godeleted file mode 100644index ddc4c6e8..00000000--- a/agent/cmd/agent/spawn_windows.go+++ /dev/null@@ -1,30 +0,0 @@-//go:build windows--package main--import "syscall"--const (- // CreateNoWindow: hide the new console window if any.- createNoWindow = 0x08000000- // DetachedProcess: child process is not bound to the parent's console.- detachedProcess = 0x00000008-)--// detachedProcessAttrs returns SysProcAttr that detaches the spawned process-// from the parent without smothering its UI. Used when the tray spawns a-// fresh `serverkit-agent setup` to relaunch the wizard.-//-// HideWindow MUST be false here. STARTUPINFO.wShowWindow propagates to the-// child's first top-level window via SW_SHOWDEFAULT, so HideWindow:true-// (which sets SW_HIDE) was leaving the wizard window invisible until the-// user manually called ShowWindow from outside — exactly the "Start Menu-// blank, CLI works" inconsistency users reported in 1.6.2. The agent .exe-// is built as a GUI subsystem so there's no console window to hide; the-// flag was redundant from the start.-func detachedProcessAttrs() *syscall.SysProcAttr {- return &syscall.SysProcAttr{- HideWindow: false,- CreationFlags: createNoWindow | detachedProcess,- }-}diff --git a/agent/docker-compose.yml b/agent/docker-compose.ymldeleted file mode 100644index 02422b2f..00000000--- a/agent/docker-compose.yml+++ /dev/null@@ -1,69 +0,0 @@-# ServerKit Agent - Docker Compose Configuration-#-# Usage:-# 1. Register first (one-time setup):-# docker compose run --rm agent register -s https://your-serverkit.com -t YOUR_TOKEN-#-# 2. Start the agent:-# docker compose up -d-#-# 3. View logs:-# docker compose logs -f-#-# 4. Stop the agent:-# docker compose down--services:- agent:- image: jhd3197/serverkit-agent:${AGENT_VERSION:-1.0.0}- container_name: serverkit-agent- restart: unless-stopped-- # Use docker group for socket access instead of running as root- group_add:- - docker-- volumes:- # Docker socket for container management- - /var/run/docker.sock:/var/run/docker.sock:ro-- # Persist configuration between restarts- - serverkit-config:/etc/serverkit-agent-- # Persist logs- - serverkit-logs:/var/log/serverkit-agent-- environment:- # Optional: Set timezone- - TZ=UTC-- # Optional: Resource limits- deploy:- resources:- limits:- cpus: '0.5'- memory: 256M- reservations:- cpus: '0.1'- memory: 64M-- # Health check- healthcheck:- test: ["CMD", "serverkit-agent", "status"]- interval: 30s- timeout: 10s- retries: 3- start_period: 10s-- # Logging configuration- logging:- driver: "json-file"- options:- max-size: "10m"- max-file: "3"--volumes:- serverkit-config:- name: serverkit-agent-config- serverkit-logs:- name: serverkit-agent-logsdiff --git a/agent/go.mod b/agent/go.moddeleted file mode 100644index 740d59a2..00000000--- a/agent/go.mod+++ /dev/null@@ -1,56 +0,0 @@-module github.com/serverkit/agent--go 1.23.1--require (- fyne.io/systray v1.11.0- github.com/creack/pty v1.1.21- github.com/docker/docker v24.0.7+incompatible- github.com/docker/go-connections v0.4.0- github.com/gorilla/websocket v1.5.1- github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808- github.com/lxn/walk v0.0.0-20210112085537-c389da54e794- github.com/shirou/gopsutil/v3 v3.24.1- github.com/spf13/cobra v1.8.0- golang.org/x/sys v0.32.0- golang.org/x/term v0.31.0- golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446- gopkg.in/natefinch/lumberjack.v2 v2.2.1- gopkg.in/yaml.v3 v3.0.1-)--require (- github.com/Microsoft/go-winio v0.6.1 // indirect- github.com/distribution/reference v0.5.0 // indirect- github.com/docker/distribution v2.8.3+incompatible // indirect- github.com/docker/go-units v0.5.0 // indirect- github.com/go-ole/go-ole v1.3.0 // indirect- github.com/godbus/dbus/v5 v5.1.0 // indirect- github.com/gogo/protobuf v1.3.2 // indirect- github.com/google/btree v1.1.2 // indirect- github.com/inconshreveable/mousetrap v1.1.0 // indirect- github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect- github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirect- github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect- github.com/moby/term v0.5.0 // indirect- github.com/morikuni/aec v1.0.0 // indirect- github.com/opencontainers/go-digest v1.0.0 // indirect- github.com/opencontainers/image-spec v1.1.0 // indirect- github.com/pkg/errors v0.9.1 // indirect- github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect- github.com/shoenig/go-m1cpu v0.1.6 // indirect- github.com/spf13/pflag v1.0.5 // indirect- github.com/tklauser/go-sysconf v0.3.13 // indirect- github.com/tklauser/numcpus v0.7.0 // indirect- github.com/yusufpapurcu/wmi v1.2.3 // indirect- golang.org/x/crypto v0.37.0 // indirect- golang.org/x/mod v0.21.0 // indirect- golang.org/x/net v0.39.0 // indirect- golang.org/x/sync v0.8.0 // indirect- golang.org/x/time v0.7.0 // indirect- golang.org/x/tools v0.26.0 // indirect- golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect- gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect- gotest.tools/v3 v3.5.1 // indirect- gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect-)diff --git a/agent/go.sum b/agent/go.sumdeleted file mode 100644index 982b5fb8..00000000--- a/agent/go.sum+++ /dev/null@@ -1,162 +0,0 @@-fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg=-fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=-github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=-github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=-github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=-github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=-github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=-github.com/creack/pty v1.1.21 h1:1/QdRyBaHHJP61QkWMXlOIBfsgdDeeKfK8SYVUWJKf0=-github.com/creack/pty v1.1.21/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=-github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=-github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=-github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=-github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig1seQen0cKYlM=-github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=-github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=-github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=-github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=-github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=-github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=-github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=-github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=-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/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=-github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=-github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=-github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=-github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=-github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=-github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=-github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=-github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=-github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=-github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo=-github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=-github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=-github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=-github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=-github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=-github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=-github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed h1:036IscGBfJsFIgJQzlui7nK1Ncm0tp2ktmPj8xO4N/0=-github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=-github.com/lxn/walk v0.0.0-20210112085537-c389da54e794 h1:NVRJ0Uy0SOFcXSKLsS65OmI1sgCCfiDUPj+cwnH7GZw=-github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ=-github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=-github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=-github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=-github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=-github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=-github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=-github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=-github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=-github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=-github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=-github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=-github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=-github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig=-github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=-github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=-github.com/shirou/gopsutil/v3 v3.24.1 h1:R3t6ondCEvmARp3wxODhXMTLC/klMa87h2PHUw5m7QI=-github.com/shirou/gopsutil/v3 v3.24.1/go.mod h1:UU7a2MSBQa+kW1uuDq8DeEBS8kmrnQwsv2b5O513rwU=-github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=-github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=-github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=-github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=-github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=-github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=-github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=-github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=-github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=-github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=-github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=-github.com/tklauser/go-sysconf v0.3.13 h1:GBUpcahXSpR2xN01jhkNAbTLRk2Yzgggk8IM08lq3r4=-github.com/tklauser/go-sysconf v0.3.13/go.mod h1:zwleP4Q4OehZHGn4CYZDipCgg9usW5IJePewFCGVEa0=-github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=-github.com/tklauser/numcpus v0.7.0 h1:yjuerZP127QG9m5Zh/mSO4wqurYil27tHrqwRoRjpr4=-github.com/tklauser/numcpus v0.7.0/go.mod h1:bb6dMVcj8A42tSE7i32fsIUCbQNllK5iDguyOZRUzAY=-github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=-github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=-github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=-github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=-golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=-golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=-golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=-golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=-golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=-golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=-golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=-golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=-golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=-golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=-golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=-golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=-golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=-golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=-golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=-golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=-golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=-golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=-golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=-golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=-golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=-golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=-golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=-golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=-golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=-golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=-golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=-golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=-golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=-golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=-golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=-golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=-golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=-golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=-golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=-gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc=-gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=-gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=-gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=-gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=-gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=-gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g=diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.godeleted file mode 100644index 857e3478..00000000--- a/agent/internal/agent/agent.go+++ /dev/null@@ -1,1830 +0,0 @@-package agent--import (- "bufio"- "context"- "crypto/hmac"- "crypto/sha256"- "encoding/base64"- "encoding/hex"- "encoding/json"- "fmt"- "io"- "net"- "os"- "path/filepath"- "sync"- "time"-- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/internal/capabilities"- "github.com/serverkit/agent/internal/cloudflared"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/cron"- "github.com/serverkit/agent/internal/docker"- "github.com/serverkit/agent/internal/events"- "github.com/serverkit/agent/internal/gui"- "github.com/serverkit/agent/internal/ipc"- "github.com/serverkit/agent/internal/jobs"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/metrics"- "github.com/serverkit/agent/internal/terminal"- "github.com/serverkit/agent/internal/transport"- "github.com/serverkit/agent/internal/transport/poll"- "github.com/serverkit/agent/internal/updater"- "github.com/serverkit/agent/internal/wireguard"- "github.com/serverkit/agent/internal/ws"- "github.com/serverkit/agent/pkg/protocol"-)--// Agent is the main agent that coordinates all components-type Agent struct {- cfg *config.Config- log *logger.Logger- auth *auth.Authenticator- // ws is the active transport — either the WS client directly or the- // fallback Manager that wraps WS+poll. Named "ws" for compatibility- // with the dozens of existing call sites in this file.- ws transport.Transport- docker *docker.Client- metrics *metrics.Collector- terminal *terminal.Manager- cron cron.Manager- cloudflared cloudflared.Manager- wireguard wireguard.Manager- ipc *ipc.Server- sampler *metricSampler- events *events.Store- gui *gui.SDK- jobs *jobs.Registry-- // pkgLock serializes package-manager mutations (install / remove /- // upgrade / update_cache) inside a single agent so two concurrent- // requests don't race on dpkg/rpm locks. Reads (list_installed,- // search, info) don't take the lock.- pkgLock sync.Mutex-- // Active subscriptions- subscriptions map[string]context.CancelFunc- subMu sync.Mutex-- // Command handlers- handlers map[string]CommandHandler-- // Capabilities probed at startup, refreshable via- // agent:recapabilities. Sent to the panel each time the transport- // reconnects (so a panel restart picks them up without waiting for- // the agent to also restart). capMu guards reads/writes during a- // re-probe so we don't ship a half-mutated payload.- capabilities protocol.CapabilitiesMessage- capMu sync.Mutex- reprobing bool-- // sudoMode is the agent's privilege-escalation mode (root /- // passwordless / unavailable). Probed once at startup; if the user- // adds sudoers config later, agent:recapabilities re-probes.- sudoMode SudoMode-- // systemdJSON tracks whether `systemctl --output=json` is supported- // on this host (systemd >= 244). Probed lazily on first use.- systemdJSON bool- systemdJSONOnce sync.Once-- // Lifecycle tracking- startTime time.Time- restartCh chan struct{}- lastConnected time.Time- reconnectCount int-}--// CommandHandler is a function that handles a command-type CommandHandler func(ctx context.Context, params json.RawMessage) (interface{}, error)--// New creates a new Agent-func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {- // Create authenticator- authenticator := auth.New(cfg.Agent.ID, cfg.Auth.APIKey, cfg.Auth.APISecret)-- // Build the transport: a Manager wrapping the WS client (primary) and- // a polling client (fallback for tunnels that mangle WS frames). The- // Manager presents the same Transport surface as the bare WS client- // did, so the rest of the agent doesn't care which is active.- wsClient := ws.NewClient(cfg.Server, authenticator, log)- pollClient := poll.NewClient(cfg.Server, authenticator, log)- transportClient := transport.NewManager(wsClient, pollClient, log)-- // Create Docker client if enabled- var dockerClient *docker.Client- if cfg.Features.Docker {- var err error- dockerClient, err = docker.NewClient(cfg.Docker, log)- if err != nil {- log.Warn("Failed to create Docker client", "error", err)- // Don't fail - Docker may not be available- }- }-- // Create metrics collector if enabled- var metricsCollector *metrics.Collector- if cfg.Features.Metrics {- metricsCollector = metrics.NewCollector(cfg.Metrics, log)- }-- // Create terminal manager if exec is enabled- var termManager *terminal.Manager- if cfg.Features.Exec {- termManager = terminal.NewManager()- log.Info("Terminal/PTY support enabled")- }-- // Persist the event store next to the existing config so it survives- // service restarts. Falls back to in-memory only if we can't infer a- // data directory (shouldn't happen on a normal install).- dataDir := ""- if cfg.Logging.File != "" {- dataDir = filepath.Dir(cfg.Logging.File)- }- eventStore := events.NewStore(200, events.DefaultPath(dataDir))-- // WireGuard private keys live in a root-only subdir of the agent's- // data dir; empty dataDir falls back to a system default inside the- // wireguard package.- wgKeyDir := ""- if dataDir != "" {- wgKeyDir = filepath.Join(dataDir, "wireguard")- }-- agent := &Agent{- cfg: cfg,- log: log,- auth: authenticator,- ws: transportClient,- docker: dockerClient,- metrics: metricsCollector,- terminal: termManager,- cron: cron.New(),- cloudflared: cloudflared.New(),- wireguard: wireguard.New(wgKeyDir),- sampler: newMetricSampler(300), // 5 min @ 1 Hz- events: eventStore,- gui: gui.New(log),- jobs: jobs.NewRegistry(64),- subscriptions: make(map[string]context.CancelFunc),- handlers: make(map[string]CommandHandler),- startTime: time.Now(),- // Buffered so an IPC restart fired before the agent's main- // select{} reaches the receive doesn't hang the IPC handler.- // At most one restart can be in-flight at a time anyway —- // Restart() uses a non-blocking send and returns "already in- // progress" if the slot is full.- restartCh: make(chan struct{}, 1),- }-- // Probe capabilities up-front so connectionWatcher can ship them on- // every reconnect without re-probing. Docker availability is taken- // from whether NewClient succeeded above; the capability layer- // doesn't redo that work.- probeCtx, probeCancel := context.WithTimeout(context.Background(), 10*time.Second)- agent.capabilities = capabilities.Probe(- probeCtx,- log,- dockerClient != nil,- cfg.Features.FileAccess,- cfg.Security.AllowedPaths,- )- agent.sudoMode = probeSudoMode(probeCtx)- agent.capabilities.Sudo = string(agent.sudoMode)- agent.capabilities.RuntimeManagers = map[string]string{- "python": pyenvManagerKind(),- }- agent.capabilities.ProbedAt = time.Now().UnixMilli()- probeCancel()- log.Info("Sudo probe complete", "mode", agent.sudoMode)-- // Register command handlers- agent.registerHandlers()-- // Install the message handler on the transport (manager fans this- // out to both backends so a fallback switch doesn't drop the- // binding).- transportClient.SetHandler(agent.handleMessage)-- // Create IPC server if enabled- if cfg.IPC.Enabled {- agent.ipc = ipc.NewServer(cfg.IPC, log, agent)- }-- return agent, nil-}--// registerHandlers registers all command handlers-func (a *Agent) registerHandlers() {- // Docker container commands- if a.docker != nil {- a.handlers[protocol.ActionDockerContainerList] = a.handleDockerContainerList- a.handlers[protocol.ActionDockerContainerInspect] = a.handleDockerContainerInspect- a.handlers[protocol.ActionDockerContainerCreate] = a.handleDockerContainerCreate- a.handlers[protocol.ActionDockerContainerStart] = a.handleDockerContainerStart- a.handlers[protocol.ActionDockerContainerStop] = a.handleDockerContainerStop- a.handlers[protocol.ActionDockerContainerRestart] = a.handleDockerContainerRestart- a.handlers[protocol.ActionDockerContainerRemove] = a.handleDockerContainerRemove- a.handlers[protocol.ActionDockerContainerStats] = a.handleDockerContainerStats- a.handlers[protocol.ActionDockerContainerLogs] = a.handleDockerContainerLogs- a.handlers[protocol.ActionDockerContainerExec] = a.handleDockerContainerExec-- // Docker image commands- a.handlers[protocol.ActionDockerImageList] = a.handleDockerImageList- a.handlers[protocol.ActionDockerImagePull] = a.handleDockerImagePull- a.handlers[protocol.ActionDockerImageRemove] = a.handleDockerImageRemove- a.handlers[protocol.ActionDockerImageBuild] = a.handleDockerImageBuild-- // Docker volume commands- a.handlers[protocol.ActionDockerVolumeList] = a.handleDockerVolumeList- a.handlers[protocol.ActionDockerVolumeCreate] = a.handleDockerVolumeCreate- a.handlers[protocol.ActionDockerVolumeRemove] = a.handleDockerVolumeRemove-- // Docker network commands- a.handlers[protocol.ActionDockerNetworkList] = a.handleDockerNetworkList- a.handlers[protocol.ActionDockerNetworkCreate] = a.handleDockerNetworkCreate- a.handlers[protocol.ActionDockerNetworkRemove] = a.handleDockerNetworkRemove-- // Docker compose commands- a.handlers[protocol.ActionDockerComposeList] = a.handleDockerComposeList- a.handlers[protocol.ActionDockerComposePs] = a.handleDockerComposePs- a.handlers[protocol.ActionDockerComposeUp] = a.handleDockerComposeUp- a.handlers[protocol.ActionDockerComposeDown] = a.handleDockerComposeDown- a.handlers[protocol.ActionDockerComposeLogs] = a.handleDockerComposeLogs- a.handlers[protocol.ActionDockerComposeRestart] = a.handleDockerComposeRestart- a.handlers[protocol.ActionDockerComposePull] = a.handleDockerComposePull- }-- // System commands- if a.metrics != nil {- a.handlers[protocol.ActionSystemMetrics] = a.handleSystemMetrics- a.handlers[protocol.ActionSystemInfo] = a.handleSystemInfo- a.handlers[protocol.ActionSystemProcesses] = a.handleSystemProcesses- }-- // File commands- if a.cfg.Features.FileAccess {- a.handlers[protocol.ActionFileRead] = a.handleFileRead- a.handlers[protocol.ActionFileWrite] = a.handleFileWrite- a.handlers[protocol.ActionFileList] = a.handleFileList- }-- // Terminal commands- if a.terminal != nil {- a.handlers[protocol.ActionTerminalCreate] = a.handleTerminalCreate- a.handlers[protocol.ActionTerminalInput] = a.handleTerminalInput- a.handlers[protocol.ActionTerminalResize] = a.handleTerminalResize- a.handlers[protocol.ActionTerminalClose] = a.handleTerminalClose- }-- // Cron commands — Linux-only, but registered unconditionally so a- // stub returns a clear error on Windows/macOS instead of "unknown- // action".- a.handlers[protocol.ActionCronStatus] = a.handleCronStatus- a.handlers[protocol.ActionCronList] = a.handleCronList- a.handlers[protocol.ActionCronAdd] = a.handleCronAdd- a.handlers[protocol.ActionCronRemove] = a.handleCronRemove- a.handlers[protocol.ActionCronToggle] = a.handleCronToggle-- // Cloudflared commands — same Linux-only/stub pattern. Auth state- // (cert.pem present) is exposed via :status, not via the- // capabilities probe, so the panel can distinguish "binary- // installed but not logged in" from "not installed at all."- a.handlers[protocol.ActionCloudflaredStatus] = a.handleCloudflaredStatus- a.handlers[protocol.ActionCloudflaredLogin] = a.handleCloudflaredLogin- a.handlers[protocol.ActionCloudflaredTunnelList] = a.handleCloudflaredTunnelList- a.handlers[protocol.ActionCloudflaredTunnelCreate] = a.handleCloudflaredTunnelCreate- a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoute- a.handlers[protocol.ActionCloudflaredTunnelDelete] = a.handleCloudflaredTunnelDelete-- // WireGuard tunnel primitives. Registered unconditionally so- // non-Linux agents return a clear "unsupported" error rather than- // "unknown action"; the `wireguard` capability gates the panel's- // Remote Access flow. See docs/REMOTE_ACCESS_ROADMAP.md.- a.handlers[protocol.ActionWireguardKeygen] = a.handleWireguardKeygen- a.handlers[protocol.ActionWireguardInterfaceUp] = a.handleWireguardInterfaceUp- a.handlers[protocol.ActionWireguardInterfaceDown] = a.handleWireguardInterfaceDown- a.handlers[protocol.ActionWireguardPeerSet] = a.handleWireguardPeerSet- a.handlers[protocol.ActionWireguardPeerRemove] = a.handleWireguardPeerRemove- a.handlers[protocol.ActionWireguardStatus] = a.handleWireguardStatus- a.handlers[protocol.ActionWireguardForward] = a.handleWireguardForward- a.handlers[protocol.ActionWireguardUnforward] = a.handleWireguardUnforward-- // Firewall — used by the tunnel broker to open the edge's WireGuard- // UDP port (#10). Linux-only; returns a clear error elsewhere.- a.handlers[protocol.ActionFirewallAllowPort] = a.handleFirewallAllowPort- a.handlers[protocol.ActionFirewallDenyPort] = a.handleFirewallDenyPort-- // Phase 4 primitives — packages, systemd, exec. Registered- // unconditionally so non-Linux agents return a clear error rather- // than "unknown action"; the capability probe gates the panel's- // target picker so users don't normally hit this on Windows.- a.handlers[protocol.ActionPackagesInstall] = a.handlePackagesInstall- a.handlers[protocol.ActionPackagesRemove] = a.handlePackagesRemove- a.handlers[protocol.ActionPackagesListInstalled] = a.handlePackagesListInstalled- a.handlers[protocol.ActionPackagesUpdateCache] = a.handlePackagesUpdateCache- a.handlers[protocol.ActionPackagesInstallAsync] = a.handlePackagesInstallAsync- a.handlers[protocol.ActionPackagesUpgrade] = a.handlePackagesUpgrade- a.handlers[protocol.ActionPackagesSearch] = a.handlePackagesSearch- a.handlers[protocol.ActionPackagesInfo] = a.handlePackagesInfo- a.handlers[protocol.ActionSystemdStatus] = a.handleSystemdStatus- a.handlers[protocol.ActionSystemdStart] = a.handleSystemdStart- a.handlers[protocol.ActionSystemdStop] = a.handleSystemdStop- a.handlers[protocol.ActionSystemdRestart] = a.handleSystemdRestart- a.handlers[protocol.ActionSystemdEnable] = a.handleSystemdEnable- a.handlers[protocol.ActionSystemdDisable] = a.handleSystemdDisable- a.handlers[protocol.ActionSystemdDaemonReload] = a.handleSystemdDaemonReload- a.handlers[protocol.ActionSystemdListUnits] = a.handleSystemdListUnits- a.handlers[protocol.ActionSystemdLogs] = a.handleSystemdLogs- a.handlers[protocol.ActionSystemdLogsFollow] = a.handleSystemdLogsFollow-- // system:exec is gated on Features.Exec rather than registered- // unconditionally — the previous version installed the handler- // regardless of the feature flag, which made the flag misleading- // (Exec=false still let the panel run any command). The handler- // itself enforces this too, but failing fast at registration means- // the panel sees a clean "unknown action" instead of a runtime- // error and can disable the feature in its UI.- if a.cfg.Features.Exec {- a.handlers[protocol.ActionSystemExec] = a.handleSystemExec- }-- // Agent commands- a.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdate- a.handlers[protocol.ActionAgentRecapabilities] = a.handleAgentRecapabilities-- // Runtime version managers (Phase 5). pyenv on Linux,- // pyenv-win on Windows. Always registered so pages that probe- // runtimes:list can tell "manager not installed" from "unknown- // action" — bootstrap then becomes a one-click action.- a.handlers[protocol.ActionRuntimesList] = a.handleRuntimesList- a.handlers[protocol.ActionRuntimesPyenvBootstrap] = a.handleRuntimesPyenvBootstrap- a.handlers[protocol.ActionRuntimesPythonInstalled] = a.handleRuntimesPythonInstalled- a.handlers[protocol.ActionRuntimesPythonAvailable] = a.handleRuntimesPythonAvailable- a.handlers[protocol.ActionRuntimesPythonInstall] = a.handleRuntimesPythonInstall- a.handlers[protocol.ActionRuntimesPythonUninstall] = a.handleRuntimesPythonUninstall- a.handlers[protocol.ActionRuntimesPythonSetGlobal] = a.handleRuntimesPythonSetGlobal- a.handlers[protocol.ActionRuntimesPythonSetLocal] = a.handleRuntimesPythonSetLocal- a.handlers[protocol.ActionRuntimesPythonCurrent] = a.handleRuntimesPythonCurrent-- // GUI SDK — primitives that panel extensions (serverkit-gui, etc.)- // compose into desktop-streaming or synthetic-UI features. Always- // registered; the SDK reports "none" capability on hosts that can't- // capture, so plugins can probe instead of failing.- a.handlers[protocol.ActionGUICapabilities] = a.gui.HandleCapabilities- a.handlers[protocol.ActionGUIScreenshot] = a.gui.HandleScreenshot-}--// Run starts the agent-func (a *Agent) Run(ctx context.Context) error {- a.log.Info("Starting agent",- "agent_id", a.cfg.Agent.ID,- "version", Version,- "features", fmt.Sprintf("docker=%v metrics=%v ipc=%v exec=%v file_access=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics, a.cfg.IPC.Enabled, a.cfg.Features.Exec, a.cfg.Features.FileAccess),- )- // Surface insecure-TLS at WARN every startup so a misconfigured- // deployment script can't silently disable certificate verification- // across every TLS dial in the agent (we have four independent- // tls.Configs respecting this env var). The user explicitly opted- // in via env var, so don't refuse to start — just make it loud.- if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {- a.log.Warn("SERVERKIT_INSECURE_TLS=true: TLS certificate verification is DISABLED for all panel connections; only use this for local development")- a.events.Append(events.KindInfo, events.SeverityWarn,- "Insecure TLS mode enabled (SERVERKIT_INSECURE_TLS)", nil)- }- a.events.Append(events.KindServiceStart, events.SeverityInfo,- "Agent service started",- map[string]interface{}{"version": Version})-- // Verify Docker connection if enabled- if a.docker != nil {- if err := a.docker.Ping(ctx); err != nil {- a.log.Warn("Docker is not available", "error", err)- } else {- version, _ := a.docker.Version(ctx)- a.log.Info("Docker connected", "version", version)- }- }-- // Start IPC server if enabled- if a.ipc != nil {- if err := a.ipc.Start(ctx); err != nil {- a.log.Warn("Failed to start IPC server", "error", err)- }- }-- // Start WebSocket connection in background- go func() {- if err := a.ws.Run(ctx); err != nil && err != context.Canceled {- a.log.Error("WebSocket error", "error", err)- }- }()-- // Start heartbeat loop- go a.heartbeatLoop(ctx)-- // Start discovery responder- go a.discoveryLoop(ctx)-- // Start the desktop-console metrics sampler (1 Hz ring buffer, 5 min)- if a.sampler != nil {- go a.samplerLoop(ctx)- }-- // Watch WS connection state and emit Activity events on transitions.- // Polling at 1 Hz is fine — the activity tab is a human-readable- // timeline, not a real-time monitor.- go a.connectionWatcher(ctx)-- // Wait for context cancellation or restart request- select {- case <-ctx.Done():- a.events.Append(events.KindServiceStop, events.SeverityInfo,- "Agent stopping (signal)", nil)- case <-a.restartCh:- a.log.Info("Restart requested")- a.events.Append(events.KindRestartRequested, events.SeverityInfo,- "Restart requested via IPC", nil)- }-- // Cleanup- a.cleanup()-- return ctx.Err()-}--// discoveryLoop listens for UDP discovery requests and responds with agent info-func (a *Agent) discoveryLoop(ctx context.Context) {- // Simple UDP broadcast listener- // Port 9000 matches DiscoveryService in backend- port := 9000- addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", port))- if err != nil {- a.log.Error("Failed to resolve UDP address for discovery", "error", err)- return- }-- conn, err := net.ListenUDP("udp", addr)- if err != nil {- a.log.Error("Failed to listen for discovery broadcasts", "error", err)- return- }- defer conn.Close()-- a.log.Info("Agent discovery responder started", "port", port)-- buf := make([]byte, 1024)- for {- select {- case <-ctx.Done():- return- default:- conn.SetReadDeadline(time.Now().Add(1 * time.Second))- n, remoteAddr, err := conn.ReadFromUDP(buf)- if err != nil {- // A read deadline timeout is the normal case (no- // inbound discovery this second) — fall through and- // wait again. A real socket error (closed FD, ICMP- // unreachable storms) used to busy-loop here at- // 100% CPU; sleep briefly so the loop doesn't spin- // while still being responsive to ctx cancellation.- if ne, ok := err.(net.Error); ok && ne.Timeout() {- continue- }- a.log.Debug("UDP discovery read error", "error", err)- select {- case <-ctx.Done():- return- case <-time.After(250 * time.Millisecond):- }- continue- }-- var req struct {- Type string `json:"type"`- Timestamp int64 `json:"timestamp"`- Signature string `json:"signature"`- }- if err := json.Unmarshal(buf[:n], &req); err != nil || (req.Type != "discovery_request" && req.Type != string(protocol.TypeDiscoveryRequest)) {- continue- }-- // If agent has no credentials (not registered), don't respond to discovery- if a.cfg.Auth.APIKey == "" {- continue- }-- // Validate timestamp is within 60 seconds- now := time.Now().UnixMilli()- if req.Timestamp <= 0 || abs(now-req.Timestamp) > 60000 {- a.log.Debug("Ignoring discovery request with stale timestamp")- continue- }-- // Verify HMAC signature- if req.Signature == "" {- a.log.Debug("Ignoring discovery request without signature")- continue- }- expectedMessage := fmt.Sprintf("discovery:%d", req.Timestamp)- mac := hmac.New(sha256.New, []byte(a.cfg.Auth.APIKey))- mac.Write([]byte(expectedMessage))- expectedSignature := hex.EncodeToString(mac.Sum(nil))- if !hmac.Equal([]byte(req.Signature), []byte(expectedSignature)) {- a.log.Debug("Ignoring discovery request with invalid signature")- continue- }-- // Respond with minimal agent info (no detailed hardware specs)- hostname, _ := os.Hostname()- resp := struct {- Type string `json:"type"`- AgentID string `json:"agent_id"`- Hostname string `json:"hostname"`- Status string `json:"status"`- AgentVersion string `json:"agent_version"`- Timestamp int64 `json:"timestamp"`- }{- Type: "discovery",- AgentID: a.cfg.Agent.ID,- Hostname: hostname,- Status: "online",- AgentVersion: Version,- Timestamp: time.Now().UnixMilli(),- }-- data, _ := json.Marshal(resp)-- // Send response to remoteAddr on port+1- respAddr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", remoteAddr.IP.String(), port+1))- conn.WriteToUDP(data, respAddr)- }- }-}--// abs returns the absolute value of an int64-func abs(x int64) int64 {- if x < 0 {- return -x- }- return x-}--// connectionWatcher polls the WS connection flag and emits Activity events-// on each transition. Avoids dragging events.Store into the ws package or-// adding a new callback API for one consumer.-//-// Also doubles as the "send capabilities on connect" hook: each time the-// transport flips from down→up, we re-ship the capability map so the-// panel's record stays current after a panel restart.-//-// On top of the transition trigger, we also re-send capabilities on a-// 60-second cadence whenever the transport is up. The transition path-// is fragile when the WS-then-poll fallback dance briefly raises-// IsConnected() against a backend that's about to be replaced — the-// message can land on a transport whose Send() silently drops it-// (or buffers it forever). Periodic re-sends mean a single missed-// transition doesn't leave the panel with an empty capability map for-// the lifetime of the agent process; the worst case is a 60-second-// gap before the next refresh.-func (a *Agent) connectionWatcher(ctx context.Context) {- transitionTicker := time.NewTicker(1 * time.Second)- defer transitionTicker.Stop()- // Aggressive cadence for the first minute so a cold-boot agent- // populates the panel within ~5s of the first successful transport- // connect. Aaron's law: the WS-then-poll fallback dance can land- // the transition's send on a backend that's about to be replaced,- // and the panel ends up with an empty capability map until the- // next steady-state tick fires.- resendTicker := time.NewTicker(5 * time.Second)- defer resendTicker.Stop()- resendTicks := 0-- prev := false- first := true- for {- select {- case <-ctx.Done():- return- case <-resendTicker.C:- // Idempotent re-send. The panel's update_capabilities is a- // pure overwrite, so re-shipping the same payload costs us- // nothing; the panel just rewrites the same row.- if a.ws.IsConnected() {- a.sendCapabilities()- a.sendSystemInfo(ctx)- }- resendTicks++- // After ~60 seconds (12 ticks at 5s), back the cadence off- // to once a minute. The first minute is the only window- // where transport churn is likely; long-lived connections- // don't need the heavier pulse.- if resendTicks == 12 {- resendTicker.Reset(60 * time.Second)- }- case <-transitionTicker.C:- now := a.ws.IsConnected()- if now == prev && !first {- continue- }- first = false- if now {- a.events.Append(events.KindWSConnected, events.SeverityInfo,- "Connected to panel",- map[string]interface{}{"url": a.cfg.Server.URL})- a.sendCapabilities()- a.sendSystemInfo(ctx)- } else if prev {- // Only log disconnect after we'd previously been up — avoids- // a spurious "lost connection" on cold-start before the- // first connect ever succeeds.- a.events.Append(events.KindWSDisconnected, events.SeverityWarn,- "Connection lost", nil)- }- prev = now- }- }-}--// sendSystemInfo collects the host's system info (CPU, memory, disk,-// hostname, OS, kernel) and pushes it to the panel as a typed-// SystemInfoMessage so it lands in update_system_info → DB. The agent-// previously only answered system:info synchronously, which meant the-// panel never persisted the values — Overview would show "N/A" for-// CPU/memory/disk whenever the page was loaded against a server whose-// info hadn't been queried yet (or if the query timed out).-//-// Also surfaces the agent's local IPv4 (first non-loopback) so the-// panel can show *which* host is reporting in, separate from the-// public IP it sees on the inbound connection.-func (a *Agent) sendSystemInfo(ctx context.Context) {- if a.metrics == nil {- return- }- infoCtx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()- info, err := a.metrics.GetSystemInfo(infoCtx)- if err != nil || info == nil {- a.log.Debug("system info collect failed", "error", err)- return- }- // Build the protocol shape — different field names than the metrics- // package's SystemInfo (CPUCores vs CPUThreads, etc.). Send the- // most useful subset and let the panel's update_system_info pick- // the keys it cares about.- payload := protocol.SystemInfoMessage{- Message: protocol.NewMessage(protocol.TypeSystemInfo, auth.GenerateNonce()),- Info: protocol.SystemInfo{- Hostname: info.Hostname,- OS: info.OS,- OSVersion: info.PlatformVersion,- Platform: info.Platform,- Architecture: info.Architecture,- CPUModel: info.CPUModel,- CPUCores: info.CPUThreads, // surface threads as "cores" — matches the panel's existing column- TotalMemory: info.TotalMemory,- TotalDisk: info.TotalDisk,- DockerVersion: a.dockerVersion(),- AgentVersion: Version,- },- }- if err := a.ws.Send(payload); err != nil {- a.log.Debug("system info send failed", "error", err)- }-}--// dockerVersion returns the running Docker daemon version, or "" if-// docker isn't reachable (which the capability probe already-// surfaces). Best-effort — we don't want a dockerd hiccup to block-// system_info delivery.-func (a *Agent) dockerVersion() string {- if a.docker == nil {- return ""- }- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- v, err := a.docker.Version(ctx)- if err != nil {- return ""- }- return v-}--// sendCapabilities ships the cached capability probe to the panel.-// Failures are logged and ignored — capabilities are best-effort-// metadata; missing ones just mean an agent doesn't show up in feature-// pickers until the next reconnect.-func (a *Agent) sendCapabilities() {- a.capMu.Lock()- caps := a.capabilities- a.capMu.Unlock()- msg := protocol.CapabilitiesMessage{- Message: protocol.NewMessage(protocol.TypeCapabilities, auth.GenerateNonce()),- Capabilities: caps.Capabilities,- Platform: caps.Platform,- Distro: caps.Distro,- DistroVersion: caps.DistroVersion,- Runtimes: caps.Runtimes,- AllowedPaths: caps.AllowedPaths,- Sudo: caps.Sudo,- RuntimeManagers: caps.RuntimeManagers,- SystemdJSON: caps.SystemdJSON,- ProbedAt: caps.ProbedAt,- }- a.log.Info("Sending capabilities to panel",- "sudo", caps.Sudo,- "cap_count", len(caps.Capabilities),- "runtime_count", len(caps.Runtimes),- )- if err := a.ws.Send(msg); err != nil {- a.log.Warn("Failed to send capabilities", "error", err)- return- }- a.log.Debug("Sent capabilities to panel",- "platform", caps.Platform,- "distro", caps.Distro,- "sudo", caps.Sudo,- )-}--// heartbeatLoop sends periodic heartbeats-func (a *Agent) heartbeatLoop(ctx context.Context) {- ticker := time.NewTicker(a.cfg.Server.PingInterval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- if !a.ws.IsConnected() {- continue- }-- heartbeatMetrics := protocol.HeartbeatMetrics{}-- // Collect basic metrics for heartbeat- if a.metrics != nil {- sysMetrics, err := a.metrics.Collect(ctx)- if err == nil {- heartbeatMetrics.CPUPercent = sysMetrics.CPUPercent- heartbeatMetrics.MemoryPercent = sysMetrics.MemoryPercent- heartbeatMetrics.DiskPercent = sysMetrics.DiskPercent- }- }-- // Get container counts if Docker is available- if a.docker != nil {- total, running, err := a.docker.GetContainerCount(ctx)- if err == nil {- heartbeatMetrics.ContainerCount = total- heartbeatMetrics.ContainerRunning = running- }- }-- if err := a.ws.SendHeartbeat(heartbeatMetrics); err != nil {- a.log.Warn("Failed to send heartbeat", "error", err)- } else {- a.log.Debug("Heartbeat sent",- "cpu", fmt.Sprintf("%.1f%%", heartbeatMetrics.CPUPercent),- "mem", fmt.Sprintf("%.1f%%", heartbeatMetrics.MemoryPercent),- )- }- }- }-}--// handleMessage handles incoming WebSocket messages-func (a *Agent) handleMessage(msgType protocol.MessageType, data []byte) {- a.log.Debug("Received message", "type", msgType)-- switch msgType {- case protocol.TypeCommand:- a.handleCommand(data)- case protocol.TypeSubscribe:- a.handleSubscribe(data)- case protocol.TypeUnsubscribe:- a.handleUnsubscribe(data)- case protocol.TypeCredentialUpdate:- a.handleCredentialUpdate(data)- default:- a.log.Warn("Unknown message type", "type", msgType)- }-}--// handleCommand handles command messages-func (a *Agent) handleCommand(data []byte) {- var cmd protocol.CommandMessage- if err := json.Unmarshal(data, &cmd); err != nil {- a.log.Error("Failed to parse command", "error", err)- return- }-- a.log.Info("Executing command",- "id", cmd.ID,- "action", cmd.Action,- )-- // Find handler- handler, ok := a.handlers[cmd.Action]- if !ok {- a.log.Warn("Unknown command action", "action", cmd.Action)- a.ws.SendCommandResult(cmd.ID, false, nil, "unknown action: "+cmd.Action, 0)- return- }-- // Execute command with enforced maximum timeout. The ceiling is- // configurable via Security.MaxExecTimeout; resolveMaxExecTimeout- // returns the operator's value or the default safety net.- start := time.Now()- maxTimeout := a.resolveMaxExecTimeout()- cmdTimeout := time.Duration(cmd.Timeout) * time.Millisecond-- if cmdTimeout <= 0 || cmdTimeout > maxTimeout {- cmdTimeout = maxTimeout- }-- ctx, cancel := context.WithTimeout(context.Background(), cmdTimeout)- defer cancel()-- result, err := handler(ctx, cmd.Params)- duration := time.Since(start)-- if err != nil {- a.log.Error("Command failed",- "id", cmd.ID,- "action", cmd.Action,- "error", err,- "duration", duration,- )- a.ws.SendCommandResult(cmd.ID, false, nil, err.Error(), duration)- return- }-- a.log.Info("Command completed",- "id", cmd.ID,- "action", cmd.Action,- "duration", duration,- )- a.ws.SendCommandResult(cmd.ID, true, result, "", duration)-}--// handleSubscribe handles subscription requests-func (a *Agent) handleSubscribe(data []byte) {- var sub protocol.SubscribeMessage- if err := json.Unmarshal(data, &sub); err != nil {- a.log.Error("Failed to parse subscribe message", "error", err)- return- }-- a.log.Info("Subscribing to channel", "channel", sub.Channel)-- // Replay any buffered events for job channels so a panel that- // subscribed mid-flight (or just after the job finished) still sees- // the full progress history. Replay before installing the- // subscription record so a brand-new "live" event can't get- // interleaved before the replay.- if job := a.jobs.LookupByChannel(sub.Channel); job != nil {- for _, ev := range job.Replay() {- if err := a.ws.SendStream(sub.Channel, ev); err != nil {- a.log.Warn("Failed to replay job event", "channel", sub.Channel, "error", err)- break- }- }- }-- // Create cancellable context for this subscription- ctx, cancel := context.WithCancel(context.Background())-- a.subMu.Lock()- // Cancel existing subscription if any- if existingCancel, ok := a.subscriptions[sub.Channel]; ok {- existingCancel()- }- a.subscriptions[sub.Channel] = cancel- a.subMu.Unlock()-- // Start streaming based on channel type- go a.streamData(ctx, sub.Channel)-}--// handleUnsubscribe handles unsubscription requests-func (a *Agent) handleUnsubscribe(data []byte) {- var unsub protocol.UnsubscribeMessage- if err := json.Unmarshal(data, &unsub); err != nil {- a.log.Error("Failed to parse unsubscribe message", "error", err)- return- }-- a.log.Info("Unsubscribing from channel", "channel", unsub.Channel)-- a.subMu.Lock()- if cancel, ok := a.subscriptions[unsub.Channel]; ok {- cancel()- delete(a.subscriptions, unsub.Channel)- }- a.subMu.Unlock()-}--// streamData streams data for a subscription-func (a *Agent) streamData(ctx context.Context, channel string) {- // Determine what to stream based on channel- switch channel {- case protocol.ChannelMetrics:- a.streamMetrics(ctx, channel)- default:- a.log.Warn("Unknown stream channel", "channel", channel)- }-}--// streamMetrics streams system metrics-func (a *Agent) streamMetrics(ctx context.Context, channel string) {- ticker := time.NewTicker(a.cfg.Metrics.Interval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- if a.metrics == nil {- continue- }-- sysMetrics, err := a.metrics.Collect(ctx)- if err != nil {- a.log.Warn("Failed to collect metrics", "error", err)- continue- }-- if err := a.ws.SendStream(channel, sysMetrics); err != nil {- a.log.Warn("Failed to send metrics stream", "error", err)- }- }- }-}--// handleCredentialUpdate handles credential rotation from server.-//-// Before applying the rotation we verify an HMAC over the new-// credentials computed with the agent's current secret. The session--// level WS auth alone is not sufficient: the panel is a large surface-// and a session token leak (or a panel-side bug that lets an-// authenticated user cross server boundaries) would otherwise let an-// attacker rotate any agent's credentials to ones they control. The-// extra check means an attacker has to also know the agent's current-// secret — which is exactly what we're trying to protect.-func (a *Agent) handleCredentialUpdate(data []byte) {- var msg protocol.CredentialUpdateMessage- if err := json.Unmarshal(data, &msg); err != nil {- a.log.Error("Failed to parse credential update", "error", err)- return- }-- a.log.Info("Received credential update request", "rotation_id", msg.RotationID)-- if err := a.verifyCredentialRotation(msg); err != nil {- a.log.Warn("Rejecting credential rotation", "rotation_id", msg.RotationID, "error", err)- a.events.Append(events.KindAuthFailed, events.SeverityWarn,- "Credential rotation rejected: "+err.Error(),- map[string]interface{}{"rotation_id": msg.RotationID})- ack := protocol.CredentialUpdateAck{- Message: protocol.NewMessage(protocol.TypeCredentialUpdateAck, auth.GenerateNonce()),- RotationID: msg.RotationID,- Success: false,- Error: err.Error(),- }- a.ws.Send(ack)- return- }-- // Update authenticator with new credentials- a.auth.UpdateCredentials(msg.APIKey, msg.APISecret)-- // Save new credentials to config file- err := a.saveCredentials(msg.APIKey, msg.APISecret)-- // Send acknowledgment- ack := protocol.CredentialUpdateAck{- Message: protocol.NewMessage(protocol.TypeCredentialUpdateAck, auth.GenerateNonce()),- RotationID: msg.RotationID,- Success: err == nil,- }- if err != nil {- ack.Error = err.Error()- a.log.Error("Failed to save new credentials", "error", err)- } else {- a.log.Info("Credentials updated successfully", "rotation_id", msg.RotationID)- }-- a.ws.Send(ack)-}--// verifyCredentialRotation checks the HMAC the panel attaches to a-// rotation message against the agent's current secret. Returns nil-// only when the signature is present, well-formed, and matches.-//-// The panel must compute hex(HMAC-SHA256(-//-// "rotation_id:agent_id:new_api_key:new_api_secret",-// current_api_secret)).-func (a *Agent) verifyCredentialRotation(msg protocol.CredentialUpdateMessage) error {- if msg.RotationID == "" || msg.APIKey == "" || msg.APISecret == "" {- return fmt.Errorf("rotation message missing required fields")- }- if msg.HMACSig == "" {- return fmt.Errorf("rotation message missing hmac signature")- }- currentSecret := a.auth.GetAPISecret()- if currentSecret == "" {- return fmt.Errorf("agent has no current secret; refusing to rotate")- }- payload := fmt.Sprintf("%s:%s:%s:%s",- msg.RotationID, a.cfg.Agent.ID, msg.APIKey, msg.APISecret)- mac := hmac.New(sha256.New, []byte(currentSecret))- mac.Write([]byte(payload))- expected := hex.EncodeToString(mac.Sum(nil))- if !hmac.Equal([]byte(msg.HMACSig), []byte(expected)) {- return fmt.Errorf("hmac signature mismatch")- }- return nil-}--// saveCredentials saves new credentials to the key file-func (a *Agent) saveCredentials(apiKey, apiSecret string) error {- // Update config with new credentials- a.cfg.Auth.APIKey = apiKey- a.cfg.Auth.APISecret = apiSecret-- // Save using existing secure method- return a.cfg.SaveCredentials()-}--func (a *Agent) cleanup() {- a.log.Info("Cleaning up...")-- // Cancel all subscriptions- a.subMu.Lock()- for _, cancel := range a.subscriptions {- cancel()- }- a.subscriptions = make(map[string]context.CancelFunc)- a.subMu.Unlock()-- // Close all terminal sessions- if a.terminal != nil {- a.terminal.CloseAll()- }-- // Stop IPC server- if a.ipc != nil {- a.ipc.Stop()- }-- // Close WebSocket- a.ws.Close()-- // Close Docker client- if a.docker != nil {- a.docker.Close()- }-}--// Docker command handlers--func (a *Agent) handleDockerContainerList(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- All bool `json:"all"`- }- if len(params) > 0 {- json.Unmarshal(params, &p)- }- return a.docker.ListContainers(ctx, p.All)-}--func (a *Agent) handleDockerContainerInspect(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return a.docker.InspectContainer(ctx, p.ID)-}--func (a *Agent) handleDockerContainerStart(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.StartContainer(ctx, p.ID)-}--func (a *Agent) handleDockerContainerStop(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Timeout *int `json:"timeout"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.StopContainer(ctx, p.ID, p.Timeout)-}--func (a *Agent) handleDockerContainerRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Timeout *int `json:"timeout"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.RestartContainer(ctx, p.ID, p.Timeout)-}--func (a *Agent) handleDockerContainerRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Force bool `json:"force"`- RemoveVolumes bool `json:"remove_volumes"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.RemoveContainer(ctx, p.ID, p.Force, p.RemoveVolumes)-}--func (a *Agent) handleDockerContainerStats(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return a.docker.ContainerStats(ctx, p.ID)-}--func (a *Agent) handleDockerContainerLogs(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Tail string `json:"tail"`- Since string `json:"since"`- Timestamps bool `json:"timestamps"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- // Set defaults- if p.Tail == "" {- p.Tail = "100"- }-- reader, err := a.docker.ContainerLogs(ctx, p.ID, p.Tail, p.Since, false)- if err != nil {- return nil, err- }- defer reader.Close()-- // Drain the stream up to a 1 MB cap. The previous implementation- // did a single Read() and dropped the error — Docker's stream- // framing means one Read returns whatever happens to be in the- // first chunk (often a few KB), so the panel's "logs" command- // got a tiny prefix of the requested tail. io.ReadAll over a- // LimitReader gives the panel the full payload it asked for.- const maxLogBytes = 1024 * 1024- data, err := io.ReadAll(io.LimitReader(reader, maxLogBytes))- if err != nil {- return nil, fmt.Errorf("read docker logs: %w", err)- }-- return map[string]interface{}{- "logs": string(data),- }, nil-}--func (a *Agent) handleDockerImageList(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.docker.ListImages(ctx)-}--func (a *Agent) handleDockerImagePull(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Image string `json:"image"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- reader, err := a.docker.PullImage(ctx, p.Image)- if err != nil {- return nil, err- }- defer reader.Close()-- // Read the output to completion- var output []map[string]interface{}- decoder := json.NewDecoder(reader)- for decoder.More() {- var msg map[string]interface{}- if err := decoder.Decode(&msg); err != nil {- break- }- output = append(output, msg)- }-- return map[string]interface{}{- "success": true,- "output": output,- }, nil-}--func (a *Agent) handleDockerImageRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Force bool `json:"force"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.RemoveImage(ctx, p.ID, p.Force)-}--func (a *Agent) handleDockerVolumeList(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.docker.ListVolumes(ctx)-}--func (a *Agent) handleDockerVolumeRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Name string `json:"name"`- Force bool `json:"force"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.RemoveVolume(ctx, p.Name, p.Force)-}--func (a *Agent) handleDockerNetworkList(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.docker.ListNetworks(ctx)-}--func (a *Agent) handleDockerNetworkRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return map[string]bool{"success": true}, a.docker.RemoveNetwork(ctx, p.ID)-}--// System command handlers--func (a *Agent) handleSystemMetrics(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.metrics.Collect(ctx)-}--func (a *Agent) handleSystemInfo(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.metrics.GetSystemInfo(ctx)-}--func (a *Agent) handleSystemProcesses(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.metrics.ListProcesses(ctx)-}--// File command handlers live in file_handlers.go.--// Docker Compose command handlers--func (a *Agent) handleDockerComposeList(ctx context.Context, params json.RawMessage) (interface{}, error) {- return a.docker.ComposeList(ctx)-}--func (a *Agent) handleDockerComposePs(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }- return a.docker.ComposePsProject(ctx, p.ProjectPath)-}--func (a *Agent) handleDockerComposeUp(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- Detach bool `json:"detach"`- Build bool `json:"build"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }-- // Default to detached mode- if !p.Detach {- p.Detach = true- }-- output, err := a.docker.ComposeUp(ctx, p.ProjectPath, p.Detach, p.Build)- if err != nil {- return map[string]interface{}{- "success": false,- "output": output,- "error": err.Error(),- }, nil- }-- return map[string]interface{}{- "success": true,- "output": output,- }, nil-}--func (a *Agent) handleDockerComposeDown(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- Volumes bool `json:"volumes"`- RemoveOrphans bool `json:"remove_orphans"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }-- output, err := a.docker.ComposeDown(ctx, p.ProjectPath, p.Volumes, p.RemoveOrphans)- if err != nil {- return map[string]interface{}{- "success": false,- "output": output,- "error": err.Error(),- }, nil- }-- return map[string]interface{}{- "success": true,- "output": output,- }, nil-}--func (a *Agent) handleDockerComposeLogs(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- Service string `json:"service"`- Tail int `json:"tail"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }-- // Default tail to 100- if p.Tail == 0 {- p.Tail = 100- }-- logs, err := a.docker.ComposeLogs(ctx, p.ProjectPath, p.Service, p.Tail)- if err != nil {- return nil, err- }-- return map[string]interface{}{- "logs": logs,- }, nil-}--func (a *Agent) handleDockerComposeRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- Service string `json:"service"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }-- output, err := a.docker.ComposeRestart(ctx, p.ProjectPath, p.Service)- if err != nil {- return map[string]interface{}{- "success": false,- "output": output,- "error": err.Error(),- }, nil- }-- return map[string]interface{}{- "success": true,- "output": output,- }, nil-}--func (a *Agent) handleDockerComposePull(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ProjectPath string `json:"project_path"`- Service string `json:"service"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.validateFileAccess(p.ProjectPath); err != nil {- return nil, err- }-- output, err := a.docker.ComposePull(ctx, p.ProjectPath, p.Service)- if err != nil {- return map[string]interface{}{- "success": false,- "output": output,- "error": err.Error(),- }, nil- }-- return map[string]interface{}{- "success": true,- "output": output,- }, nil-}--// Terminal command handlers--func (a *Agent) handleTerminalCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- SessionID string `json:"session_id"`- Cols uint16 `json:"cols"`- Rows uint16 `json:"rows"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- if p.SessionID == "" {- return nil, fmt.Errorf("session_id is required")- }-- // Default terminal size- if p.Cols == 0 {- p.Cols = 80- }- if p.Rows == 0 {- p.Rows = 24- }-- // Create terminal session- session, err := a.terminal.CreateSession(p.SessionID, p.Cols, p.Rows)- if err != nil {- return nil, fmt.Errorf("failed to create terminal session: %w", err)- }-- // Set up output handler to stream data back- channel := fmt.Sprintf(protocol.ChannelTerminal, p.SessionID)- session.SetOutputHandler(func(data []byte) {- // Encode as base64 for safe transport- encoded := base64.StdEncoding.EncodeToString(data)- if err := a.ws.SendStream(channel, map[string]interface{}{- "type": "output",- "data": encoded,- }); err != nil {- a.log.Warn("Failed to send terminal output", "error", err)- }- })-- // Set up close handler- session.SetCloseHandler(func() {- if err := a.ws.SendStream(channel, map[string]interface{}{- "type": "closed",- }); err != nil {- a.log.Warn("Failed to send terminal close event", "error", err)- }- // Clean up session- a.terminal.CloseSession(p.SessionID)- })-- a.log.Info("Terminal session created",- "session_id", p.SessionID,- "cols", p.Cols,- "rows", p.Rows,- "shell", session.Shell,- )-- return map[string]interface{}{- "success": true,- "session_id": p.SessionID,- "shell": session.Shell,- "cols": session.Cols,- "rows": session.Rows,- }, nil-}--func (a *Agent) handleTerminalInput(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- SessionID string `json:"session_id"`- Data string `json:"data"` // base64 encoded- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- session, ok := a.terminal.GetSession(p.SessionID)- if !ok {- return nil, fmt.Errorf("terminal session not found: %s", p.SessionID)- }-- // Decode base64 data- data, err := base64.StdEncoding.DecodeString(p.Data)- if err != nil {- return nil, fmt.Errorf("invalid base64 data: %w", err)- }-- // Write to terminal- _, err = session.Write(data)- if err != nil {- return nil, fmt.Errorf("failed to write to terminal: %w", err)- }-- return map[string]interface{}{- "success": true,- }, nil-}--func (a *Agent) handleTerminalResize(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- SessionID string `json:"session_id"`- Cols uint16 `json:"cols"`- Rows uint16 `json:"rows"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- session, ok := a.terminal.GetSession(p.SessionID)- if !ok {- return nil, fmt.Errorf("terminal session not found: %s", p.SessionID)- }-- if err := session.Resize(p.Cols, p.Rows); err != nil {- return nil, fmt.Errorf("failed to resize terminal: %w", err)- }-- a.log.Debug("Terminal resized",- "session_id", p.SessionID,- "cols", p.Cols,- "rows", p.Rows,- )-- return map[string]interface{}{- "success": true,- "cols": p.Cols,- "rows": p.Rows,- }, nil-}--func (a *Agent) handleTerminalClose(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- SessionID string `json:"session_id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- if err := a.terminal.CloseSession(p.SessionID); err != nil {- return nil, fmt.Errorf("failed to close terminal: %w", err)- }-- a.log.Info("Terminal session closed", "session_id", p.SessionID)-- return map[string]interface{}{- "success": true,- }, nil-}--// IPC StatusProvider implementation--// GetStatus returns the current agent status for the IPC API-func (a *Agent) GetStatus() ipc.AgentStatus {- status := ipc.AgentStatus{- Running: true,- Connected: a.ws.IsConnected(),- Registered: a.cfg.Agent.ID != "",- AgentID: a.cfg.Agent.ID,- AgentName: a.cfg.Agent.Name,- ServerURL: a.cfg.Server.URL,- Uptime: int64(time.Since(a.startTime).Seconds()),- Version: Version,- Transport: string(a.ws.Mode()),- }-- // Collect current metrics if available- if a.metrics != nil {- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- if sysMetrics, err := a.metrics.Collect(ctx); err == nil {- status.CPUPercent = sysMetrics.CPUPercent- status.MemPercent = sysMetrics.MemoryPercent- status.DiskPercent = sysMetrics.DiskPercent- }- }-- return status-}--// GetDetailedMetrics returns detailed system metrics for the IPC API-func (a *Agent) GetDetailedMetrics() *ipc.DetailedMetrics {- if a.metrics == nil {- return nil- }-- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()-- sysMetrics, err := a.metrics.Collect(ctx)- if err != nil {- return nil- }-- cores := 0- if sysMetrics.CPUPerCore != nil {- cores = len(sysMetrics.CPUPerCore)- }-- return &ipc.DetailedMetrics{- CPU: ipc.CPUMetrics{- UsagePercent: sysMetrics.CPUPercent,- PerCPU: sysMetrics.CPUPerCore,- Cores: cores,- },- Memory: ipc.MemoryMetrics{- Total: sysMetrics.MemoryTotal,- Used: sysMetrics.MemoryUsed,- Free: sysMetrics.MemoryTotal - sysMetrics.MemoryUsed,- UsagePercent: sysMetrics.MemoryPercent,- },- Disk: ipc.DiskMetrics{- Total: sysMetrics.DiskTotal,- Used: sysMetrics.DiskUsed,- Free: sysMetrics.DiskTotal - sysMetrics.DiskUsed,- UsagePercent: sysMetrics.DiskPercent,- },- Network: ipc.NetworkMetrics{- BytesSent: sysMetrics.NetworkTx,- BytesRecv: sysMetrics.NetworkRx,- PacketsSent: 0, // Not tracked in current implementation- PacketsRecv: 0, // Not tracked in current implementation- },- Timestamp: time.Now().UnixMilli(),- }-}--// GetMetricsHistory returns the recent CPU/memory ring buffer for the-// desktop console's sparkline charts. Returns an empty slice (not nil) when-// metrics are disabled or the sampler hasn't run yet, so the JSON shape-// stays stable.-func (a *Agent) GetMetricsHistory() []ipc.MetricSample {- if a.sampler == nil {- return []ipc.MetricSample{}- }- return a.sampler.snapshot()-}--// GetEvents returns recent activity events newer than `since` (unix ms).-// Pass 0 to get all events currently held in the ring buffer.-func (a *Agent) GetEvents(since int64) []events.Event {- if a.events == nil {- return []events.Event{}- }- return a.events.Snapshot(since)-}--// ClearLogs rotates agent.log so the desktop console can start with a-// clean tail. Existing content moves to an automatic backup file. Records-// the action in the activity log so the user has an audit trail.-func (a *Agent) ClearLogs() error {- if err := a.log.Rotate(); err != nil {- return err- }- if a.events != nil {- a.events.Append(events.KindInfo, events.SeverityInfo,- "Logs cleared from console", nil)- }- return nil-}--// GetConnectionInfo returns WebSocket connection information for the IPC API-func (a *Agent) GetConnectionInfo() ipc.ConnectionInfo {- info := ipc.ConnectionInfo{- Connected: a.ws.IsConnected(),- ServerURL: a.cfg.Server.URL,- ReconnectCount: a.reconnectCount,- }-- if !a.lastConnected.IsZero() {- info.LastConnected = a.lastConnected.UnixMilli()- }-- if session := a.ws.Session(); session != nil {- info.SessionExpires = session.ExpiresAt.UnixMilli()- }-- return info-}--// GetRecentLogs returns recent log lines from the log file-func (a *Agent) GetRecentLogs(lines int) []string {- logFile := a.cfg.Logging.File- if logFile == "" {- return []string{}- }-- file, err := os.Open(logFile)- if err != nil {- return []string{}- }- defer file.Close()-- // Read all lines and keep the last N- var allLines []string- scanner := bufio.NewScanner(file)- for scanner.Scan() {- allLines = append(allLines, scanner.Text())- }-- // Return the last N lines- if len(allLines) <= lines {- return allLines- }- return allLines[len(allLines)-lines:]-}--// Restart initiates a graceful restart of the agent-func (a *Agent) Restart() error {- a.log.Info("Restart requested via IPC")- select {- case a.restartCh <- struct{}{}:- return nil- default:- return fmt.Errorf("restart already in progress")- }-}--// handleAgentUpdate handles agent upgrade commands-func (a *Agent) handleAgentUpdate(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Version string `json:"version"`- DownloadURL string `json:"download_url"`- ChecksumsURL string `json:"checksums_url"`- Force bool `json:"force"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- if p.Version == "" {- return nil, fmt.Errorf("version is required")- }-- a.log.Info("Agent update triggered via panel", "version", p.Version)-- // Create updater- u := updater.New(a.cfg, a.log, Version)-- // Trigger update in background so we can respond to the command- go func() {- // Small delay to allow command result to be sent- time.Sleep(2 * time.Second)-- // Download and install- // In a real implementation, we would use the provided URLs- // For now, we'll let the updater handle it using its default logic- // or extend it to use the provided URLs.-- err := u.UpdateTo(context.Background(), p.Version, p.DownloadURL, p.ChecksumsURL)- if err != nil {- a.log.Error("Update failed", "error", err)- return- }-- a.log.Info("Update successful, restarting...")- a.Restart()- }()-- return map[string]interface{}{- "success": true,- "message": "Update triggered",- "version": p.Version,- }, nil-}diff --git a/agent/internal/agent/cloudflared_handlers.go b/agent/internal/agent/cloudflared_handlers.godeleted file mode 100644index 624781a0..00000000--- a/agent/internal/agent/cloudflared_handlers.go+++ /dev/null@@ -1,140 +0,0 @@-package agent--import (- "context"- "encoding/json"- "fmt"-- "github.com/serverkit/agent/internal/cloudflared"- "github.com/serverkit/agent/internal/jobs"-)--// Handlers for cloudflared:* actions. Same shape as cron handlers:-// thin parse + dispatch. Validation lives in the cloudflared package.--func (a *Agent) handleCloudflaredStatus(ctx context.Context, _ json.RawMessage) (interface{}, error) {- return a.cloudflared.Status(ctx)-}--func (a *Agent) handleCloudflaredTunnelList(ctx context.Context, _ json.RawMessage) (interface{}, error) {- tunnels, err := a.cloudflared.List(ctx)- if err != nil {- return nil, err- }- if tunnels == nil {- tunnels = []cloudflared.Tunnel{}- }- return map[string]interface{}{"tunnels": tunnels}, nil-}--func (a *Agent) handleCloudflaredTunnelCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {- var req cloudflared.CreateRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- tunnel, err := a.cloudflared.Create(ctx, req)- if err != nil {- return nil, err- }- return tunnel, nil-}--func (a *Agent) handleCloudflaredTunnelRoute(ctx context.Context, params json.RawMessage) (interface{}, error) {- var req cloudflared.RouteRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.cloudflared.Route(ctx, req); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--// handleCloudflaredLogin starts `cloudflared tunnel login` and streams-// progress on a job channel. Returns {job_id, channel} immediately so-// the panel can subscribe and surface the auth URL the moment-// cloudflared prints it. The flow:-//-// 1. Agent spawns `cloudflared tunnel login` with stdout/stderr piped-// 2. First line containing https://dash.cloudflare.com/argotunnel?...-// is reported as a 'status' event with auth_url-// 3. Panel renders a clickable button; user opens URL → authorises-// 4. cloudflared writes cert.pem and exits-// 5. Agent emits 'done' with the cert path; panel can refresh-// capabilities to flip the Authenticated badge.-//-// 15-minute hard ceiling (cloudflared blocks waiting for the OAuth-// callback) — long enough for a coffee break, short enough that a-// forgotten browser tab gets reaped.-func (a *Agent) handleCloudflaredLogin(ctx context.Context, _ json.RawMessage) (interface{}, error) {- // Use a background context for the subscription so the agent's- // 5-minute command timeout doesn't kill the login flow.- loginCtx := context.Background()- ch, err := a.cloudflared.Login(loginCtx)- if err != nil {- return nil, fmt.Errorf("start login: %w", err)- }- job := a.jobs.New(64)- go a.runCloudflaredLoginJob(job, ch)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- }, nil-}--func (a *Agent) runCloudflaredLoginJob(job *jobs.Job, events <-chan cloudflared.LoginEvent) {- exit := 0- emit := func(ev jobs.Event) { _ = job.Push(a.ws, ev) }- emit(jobs.Event{Phase: jobs.PhaseStart, Message: "starting cloudflared tunnel login"})-- for ev := range events {- switch {- case ev.AuthURL != "":- emit(jobs.Event{- Phase: jobs.PhaseStatus,- Message: "Open this URL in your browser to authorise the agent",- Extra: map[string]interface{}{"auth_url": ev.AuthURL},- })- if ev.Line != "" {- emit(jobs.Event{Phase: jobs.PhaseLog, Lines: []string{ev.Line}})- }- case ev.Done:- if ev.Error != "" {- exit = 1- emit(jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: ev.Error,- })- } else {- emit(jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Message: "authenticated",- Extra: map[string]interface{}{"cert_path": ev.CertPath},- })- }- case ev.Line != "":- emit(jobs.Event{Phase: jobs.PhaseLog, Lines: []string{ev.Line}})- }- }- // Channel closed without explicit Done — emit a defensive- // terminator so the panel modal doesn't hang indefinitely.- if !job.HasTerminated() {- exit = 1- emit(jobs.Event{Phase: jobs.PhaseDone, ExitCode: &exit, Error: "login stream ended unexpectedly"})- }-}--func (a *Agent) handleCloudflaredTunnelDelete(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Ref string `json:"ref"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.cloudflared.Delete(ctx, p.Ref); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}diff --git a/agent/internal/agent/cron_handlers.go b/agent/internal/agent/cron_handlers.godeleted file mode 100644index 6cafbe77..00000000--- a/agent/internal/agent/cron_handlers.go+++ /dev/null@@ -1,79 +0,0 @@-package agent--import (- "context"- "encoding/json"- "fmt"-- "github.com/serverkit/agent/internal/cron"-)--// Cron handlers wrap the cron.Manager interface for the panel's-// command-routing path. Validation happens inside the cron package,-// so handlers here are thin: parse params, dispatch, return.-//-// Linux-only operations on non-Linux agents return the manager's-// "unsupported" error, which the panel surfaces as a normal failure-// rather than a transport bug.--func (a *Agent) handleCronStatus(ctx context.Context, _ json.RawMessage) (interface{}, error) {- return a.cron.Status(ctx)-}--func (a *Agent) handleCronList(ctx context.Context, _ json.RawMessage) (interface{}, error) {- entries, err := a.cron.List(ctx)- if err != nil {- return nil, err- }- // Stable shape even on empty: {"jobs": []} so the UI can- // unconditionally read .jobs.- if entries == nil {- entries = []cron.Entry{}- }- return map[string]interface{}{"jobs": entries}, nil-}--func (a *Agent) handleCronAdd(ctx context.Context, params json.RawMessage) (interface{}, error) {- var req cron.AddRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- entry, err := a.cron.Add(ctx, req)- if err != nil {- return nil, err- }- return entry, nil-}--func (a *Agent) handleCronRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.ID == "" {- return nil, fmt.Errorf("id is required")- }- if err := a.cron.Remove(ctx, p.ID); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleCronToggle(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- ID string `json:"id"`- Enabled bool `json:"enabled"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.ID == "" {- return nil, fmt.Errorf("id is required")- }- if err := a.cron.Toggle(ctx, p.ID, p.Enabled); err != nil {- return nil, err- }- return map[string]bool{"success": true, "enabled": p.Enabled}, nil-}diff --git a/agent/internal/agent/docker_extra_handlers.go b/agent/internal/agent/docker_extra_handlers.godeleted file mode 100644index 002193d3..00000000--- a/agent/internal/agent/docker_extra_handlers.go+++ /dev/null@@ -1,270 +0,0 @@-package agent--// Phase 1e — fill in the docker actions that were declared in the-// protocol but never wired to handlers: container:create,-// container:exec, image:build, volume:create, network:create. The-// existing handlers (start/stop/list/inspect/logs/stats, image-// list/pull/remove, compose) live in agent.go alongside their-// containers; we put the new ones in their own file to keep the diff-// reviewable.--import (- "context"- "encoding/json"- "errors"- "fmt"- "os/exec"- "path/filepath"- "strings"- "time"-- "github.com/serverkit/agent/internal/docker"- "github.com/serverkit/agent/internal/jobs"-)--// validateImageName rejects shell metacharacters in user-supplied image-// references. Docker is generally tolerant about what it accepts as a-// tag, but we don't want a "registry.example.com/img;rm -rf /" landing-// in argv even if exec.Command is safe — it's a clearer error to-// reject up front.-func validateImageName(s string) error {- s = strings.TrimSpace(s)- if s == "" {- return errors.New("image is required")- }- if strings.ContainsAny(s, ";&|`$<>\n\r\"'\\") {- return fmt.Errorf("invalid image: %q", s)- }- return nil-}--func validateContainerID(s string) error {- s = strings.TrimSpace(s)- if s == "" {- return errors.New("container is required")- }- if strings.ContainsAny(s, ";&|`$<>\n\r\"'\\ /") {- return fmt.Errorf("invalid container id/name: %q", s)- }- return nil-}--// ───── docker:container:create ────────────────────────────────────--func (a *Agent) handleDockerContainerCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.docker == nil {- return nil, errors.New("docker not available")- }- var spec docker.ContainerCreateSpec- if err := json.Unmarshal(params, &spec); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validateImageName(spec.Image); err != nil {- return nil, err- }- // v1 reject privileged-ish fields. They round-trip in the JSON but- // are not part of ContainerCreateSpec — defensively check raw params- // to fail loudly when a caller tries to set them. The struct-shaped- // check is at the field level above.- var raw map[string]interface{}- _ = json.Unmarshal(params, &raw)- for _, banned := range []string{"privileged", "cap_add", "devices"} {- if _, ok := raw[banned]; ok {- return nil, fmt.Errorf("%s is not supported in v1 container:create", banned)- }- }- id, err := a.docker.CreateContainer(ctx, spec)- if err != nil {- return nil, fmt.Errorf("create container: %w", err)- }- return map[string]interface{}{- "id": id,- "name": spec.Name,- "image": spec.Image,- "status": "created",- }, nil-}--// ───── docker:container:exec ──────────────────────────────────────--func (a *Agent) handleDockerContainerExec(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.docker == nil {- return nil, errors.New("docker not available")- }- var p struct {- Container string `json:"container"`- Cmd []string `json:"cmd"`- User string `json:"user"`- WorkingDir string `json:"working_dir"`- TimeoutSeconds int `json:"timeout_seconds"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validateContainerID(p.Container); err != nil {- return nil, err- }- if len(p.Cmd) == 0 {- return nil, errors.New("cmd is required")- }- timeout := time.Duration(p.TimeoutSeconds) * time.Second- if timeout <= 0 || timeout > 5*time.Minute {- timeout = 60 * time.Second- }- cctx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()- res, err := a.docker.ExecContainer(cctx, p.Container, p.Cmd, p.User, p.WorkingDir, 1024*1024)- if err != nil {- return nil, fmt.Errorf("exec: %w", err)- }- return res, nil-}--// ───── docker:image:build ─────────────────────────────────────────--func (a *Agent) handleDockerImageBuild(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.docker == nil {- return nil, errors.New("docker not available")- }- var spec docker.ImageBuildSpec- if err := json.Unmarshal(params, &spec); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validateImageName(spec.Tag); err != nil {- return nil, fmt.Errorf("tag: %w", err)- }- abs, err := filepath.Abs(spec.ContextPath)- if err != nil {- return nil, fmt.Errorf("context_path: %w", err)- }- if !a.contextPathAllowed(abs) {- return nil, fmt.Errorf("context_path %q is not under any allowed root", abs)- }- spec.ContextPath = abs-- job := a.jobs.New(500)- go a.runDockerBuildJob(job, spec)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- "tag": spec.Tag,- }, nil-}--func (a *Agent) contextPathAllowed(path string) bool {- for _, root := range a.cfg.Security.AllowedPaths {- ar, err := filepath.Abs(root)- if err != nil {- continue- }- // path must be under ar (or equal). Use Rel to detect ".." escapes.- rel, err := filepath.Rel(ar, path)- if err != nil {- continue- }- if rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {- return true- }- }- return false-}--func (a *Agent) runDockerBuildJob(job *jobs.Job, spec docker.ImageBuildSpec) {- exit := 0- emitDone := func(errStr string) {- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{"tag": spec.Tag},- })- }- cctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)- defer cancel()- cmd, err := a.docker.BuildImageCmd(cctx, spec)- if err != nil {- exit = -1- emitDone(err.Error())- return- }- _ = job.Push(a.ws, jobs.Event{Phase: jobs.PhaseStart, Message: fmt.Sprintf("docker build -t %s", spec.Tag)})- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOfCmd(cerr)- if exit == 0 {- exit = -1- }- emitDone(cerr.Error())- return- }- emitDone("")-}--// exitCodeOfCmd duplicates exitCodeOf from package_handlers.go to-// avoid an import cycle in this file. They're trivial enough that the-// duplication is cheaper than refactoring callers.-func exitCodeOfCmd(err error) int {- var ee *exec.ExitError- if errors.As(err, &ee) {- return ee.ExitCode()- }- return -1-}--// ───── docker:volume:create ───────────────────────────────────────--func (a *Agent) handleDockerVolumeCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.docker == nil {- return nil, errors.New("docker not available")- }- var p struct {- Name string `json:"name"`- Driver string `json:"driver"`- Labels map[string]string `json:"labels"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if strings.TrimSpace(p.Name) == "" {- return nil, errors.New("name is required")- }- if strings.ContainsAny(p.Name, ";&|`$<>\n\r\"'\\ /") {- return nil, fmt.Errorf("invalid volume name: %q", p.Name)- }- vol, err := a.docker.CreateVolume(ctx, p.Name, p.Driver, p.Labels)- if err != nil {- return nil, fmt.Errorf("create volume: %w", err)- }- return vol, nil-}--// ───── docker:network:create ──────────────────────────────────────--func (a *Agent) handleDockerNetworkCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.docker == nil {- return nil, errors.New("docker not available")- }- var spec docker.NetworkCreateSpec- if err := json.Unmarshal(params, &spec); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if strings.TrimSpace(spec.Name) == "" {- return nil, errors.New("name is required")- }- if strings.ContainsAny(spec.Name, ";&|`$<>\n\r\"'\\ /") {- return nil, fmt.Errorf("invalid network name: %q", spec.Name)- }- id, err := a.docker.CreateNetwork(ctx, spec)- if err != nil {- return nil, fmt.Errorf("create network: %w", err)- }- return map[string]interface{}{- "id": id,- "name": spec.Name,- "driver": spec.Driver,- }, nil-}diff --git a/agent/internal/agent/file_handlers.go b/agent/internal/agent/file_handlers.godeleted file mode 100644index 0e24213b..00000000--- a/agent/internal/agent/file_handlers.go+++ /dev/null@@ -1,255 +0,0 @@-package agent--// File-access handlers (file:read, file:write, file:list) and the-// allowlist-aware path validator they share. Lives separately from-// agent.go so the security-sensitive path-resolution logic is easy to-// find and review without scrolling through 2000 lines of unrelated-// command handlers.-//-// Every handler in this file goes through validateFileAccess, which-// resolves symlinks before comparing against AllowedPaths — without-// that, an operator-allowed root containing a symlink to /etc would-// let the panel read or write arbitrary files. handleFileWrite also-// re-validates the parent directory before MkdirAll so CreateDirs-// can't escape via a not-yet-existing path that crosses a symlink-// boundary.--import (- "context"- "encoding/base64"- "encoding/json"- "fmt"- "os"- "path/filepath"- "runtime"- "strings"-)--func (a *Agent) handleFileRead(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Path == "" {- return nil, fmt.Errorf("path is required")- }- if err := a.validateFileAccess(p.Path); err != nil {- return nil, err- }-- data, err := os.ReadFile(p.Path)- if err != nil {- return nil, fmt.Errorf("failed to read file: %w", err)- }-- return map[string]interface{}{- "path": p.Path,- "content": base64.StdEncoding.EncodeToString(data),- "size": len(data),- }, nil-}--func (a *Agent) handleFileWrite(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- Content string `json:"content"` // base64 encoded- Mode uint32 `json:"mode"`- CreateDirs bool `json:"create_dirs"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Path == "" {- return nil, fmt.Errorf("path is required")- }- if err := a.validateFileAccess(p.Path); err != nil {- return nil, err- }-- data, err := base64.StdEncoding.DecodeString(p.Content)- if err != nil {- return nil, fmt.Errorf("invalid base64 content: %w", err)- }-- mode := os.FileMode(0644)- if p.Mode != 0 {- // Mask off SUID/SGID/sticky bits — the panel has no business- // requesting them and a compromised panel could otherwise drop- // a setuid binary into an allowed path. If an operator- // genuinely needs to write a setuid file they can chmod it via- // system:exec (which is independently gated).- mode = os.FileMode(p.Mode) & os.ModePerm- }-- if p.CreateDirs {- // Re-validate the parent directory under the symlink-resolved- // rules — MkdirAll otherwise lets the panel create directories- // outside AllowedPaths if the requested path is something like- // /var/lib/serverkit/<symlink>/foo and <symlink> escapes.- parent := filepath.Dir(p.Path)- if err := a.validateFileAccess(parent); err != nil {- return nil, fmt.Errorf("parent dir not allowed: %w", err)- }- if err := os.MkdirAll(parent, 0755); err != nil {- return nil, fmt.Errorf("failed to create parent directories: %w", err)- }- }-- if err := os.WriteFile(p.Path, data, mode); err != nil {- return nil, fmt.Errorf("failed to write file: %w", err)- }-- return map[string]interface{}{- "success": true,- "path": p.Path,- "size": len(data),- }, nil-}--func (a *Agent) handleFileList(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Path string `json:"path"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }-- // The panel speaks forward-slash paths on the wire regardless of the- // agent's OS. Convert to the native separator before any filesystem- // call so os.ReadDir and the allowlist validation behave on Windows.- reqPath := filepath.FromSlash(p.Path)-- // An empty (or bare-root) request has no single filesystem root on- // Windows. Enumerate the logical drives as virtual directory entries- // so the panel's file browser can pick a drive instead of silently- // listing only the agent process's working drive. On non-Windows- // enumerateDriveRoots() returns nil and we fall through to "/".- if reqPath == "" || reqPath == "/" || reqPath == `\` {- if drives := enumerateDriveRoots(); drives != nil {- return map[string]interface{}{- "path": "/",- "files": drives,- }, nil- }- reqPath = "/"- }-- if err := a.validateFileAccess(reqPath); err != nil {- return nil, err- }-- entries, err := os.ReadDir(reqPath)- if err != nil {- return nil, fmt.Errorf("failed to list directory: %w", err)- }-- // Each entry carries an absolute, forward-slash path. The frontend- // keys/selects/navigates on entry.path, and the agent is the only- // party that knows the host separator, so it emits the canonical- // path. (It was previously omitted, which broke remote browse- // navigation on every OS — Windows additionally needs the separator- // normalized.)- files := make([]map[string]interface{}, 0, len(entries))- for _, entry := range entries {- info, err := entry.Info()- if err != nil {- continue- }- files = append(files, map[string]interface{}{- "name": entry.Name(),- "path": filepath.ToSlash(filepath.Join(reqPath, entry.Name())),- "is_dir": entry.IsDir(),- "size": info.Size(),- "modified": info.ModTime().UnixMilli(),- })- }-- return map[string]interface{}{- "path": filepath.ToSlash(reqPath),- "files": files,- }, nil-}--func (a *Agent) validateFileAccess(path string) error {- allowedPaths := a.cfg.Security.AllowedPaths- if len(allowedPaths) == 0 {- return fmt.Errorf("file access denied: no allowed_paths configured")- }-- target, err := resolveSymlinkPath(path)- if err != nil {- return fmt.Errorf("invalid path: %w", err)- }-- for _, allowedPath := range allowedPaths {- if strings.TrimSpace(allowedPath) == "" {- continue- }- allowed, err := resolveSymlinkPath(allowedPath)- if err != nil {- continue- }-- if pathWithinAllowedRoot(target, allowed) {- return nil- }- }-- return fmt.Errorf("file access denied for path: %s", path)-}--// resolveSymlinkPath returns an absolute, symlink-free path for use in-// allowlist comparison. Without this, an operator-allowed root that-// contains a symlink (eg. /var/lib/serverkit/data → /etc) lets the-// panel read or write any file the symlink points at — strings.HasPrefix-// matches the unresolved target string, which never sees the escape.-//-// For paths that don't yet exist (handleFileWrite creating a new file-// in an allowed directory), EvalSymlinks fails. Fall back to resolving-// the deepest existing ancestor and reattaching the unresolved suffix-// so a fresh file path is still validated against the real allowed-// root rather than its symlink alias.-func resolveSymlinkPath(p string) (string, error) {- abs, err := filepath.Abs(filepath.Clean(p))- if err != nil {- return "", err- }- if resolved, err := filepath.EvalSymlinks(abs); err == nil {- return resolved, nil- }- // Path (or some ancestor) doesn't exist yet. Walk up to the- // nearest existing ancestor, resolve that, then reattach the- // missing suffix. This is the standard pattern for allowlist- // checks against not-yet-created files; the suffix can't- // introduce a new symlink because nothing on disk corresponds- // to it yet.- dir := abs- suffix := ""- for {- parent := filepath.Dir(dir)- if parent == dir {- return abs, nil- }- if resolved, err := filepath.EvalSymlinks(parent); err == nil {- return filepath.Join(resolved, filepath.Base(dir), suffix), nil- }- suffix = filepath.Join(filepath.Base(dir), suffix)- dir = parent- }-}--func pathWithinAllowedRoot(target, allowed string) bool {- if runtime.GOOS == "windows" {- target = strings.ToLower(target)- allowed = strings.ToLower(allowed)- }-- if target == allowed {- return true- }-- allowedWithSeparator := strings.TrimRight(allowed, string(os.PathSeparator)) + string(os.PathSeparator)- return strings.HasPrefix(target, allowedWithSeparator)-}diff --git a/agent/internal/agent/file_handlers_other.go b/agent/internal/agent/file_handlers_other.godeleted file mode 100644index 475ecee1..00000000--- a/agent/internal/agent/file_handlers_other.go+++ /dev/null@@ -1,10 +0,0 @@-//go:build !windows--package agent--// enumerateDriveRoots is a no-op on non-Windows platforms, which have a-// single "/" filesystem root and therefore no drive list to enumerate.-// Returning nil makes handleFileList fall through to reading "/".-func enumerateDriveRoots() []map[string]interface{} {- return nil-}diff --git a/agent/internal/agent/file_handlers_test.go b/agent/internal/agent/file_handlers_test.godeleted file mode 100644index 9ac72be9..00000000--- a/agent/internal/agent/file_handlers_test.go+++ /dev/null@@ -1,67 +0,0 @@-package agent--import (- "context"- "encoding/json"- "os"- "path/filepath"- "strings"- "testing"-- "github.com/serverkit/agent/internal/config"-)--// handleFileList must emit an absolute, forward-slash `path` for every-// entry (and for the directory itself). The frontend keys, selects, and-// navigates on entry.path; before this was added remote browse was broken-// on every OS. Cross-platform: on Windows the join also normalizes the-// backslash separator to forward-slash on the wire.-func TestHandleFileListEmitsForwardSlashPaths(t *testing.T) {- tmp := t.TempDir()- if err := os.MkdirAll(filepath.Join(tmp, "sub"), 0o755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filepath.Join(tmp, "a.txt"), []byte("hi"), 0o644); err != nil {- t.Fatal(err)- }-- a := &Agent{cfg: &config.Config{- Security: config.SecurityConfig{AllowedPaths: []string{tmp}},- }}- params, _ := json.Marshal(map[string]string{"path": filepath.ToSlash(tmp)})-- res, err := a.handleFileList(context.Background(), params)- if err != nil {- t.Fatalf("handleFileList error: %v", err)- }-- m, ok := res.(map[string]interface{})- if !ok {- t.Fatalf("unexpected result type %T", res)- }- if dp, _ := m["path"].(string); strings.ContainsRune(dp, '\\') {- t.Errorf("directory path must be forward-slash on the wire, got %q", dp)- }-- files, ok := m["files"].([]map[string]interface{})- if !ok {- t.Fatalf("unexpected files type %T", m["files"])- }- if len(files) != 2 {- t.Fatalf("expected 2 entries, got %d", len(files))- }-- for _, f := range files {- p, ok := f["path"].(string)- if !ok || p == "" {- t.Fatalf("entry missing path field: %#v", f)- }- if strings.ContainsRune(p, '\\') {- t.Errorf("entry path must be forward-slash on the wire, got %q", p)- }- want := filepath.ToSlash(filepath.Join(tmp, f["name"].(string)))- if p != want {- t.Errorf("entry path = %q, want %q", p, want)- }- }-}diff --git a/agent/internal/agent/file_handlers_windows.go b/agent/internal/agent/file_handlers_windows.godeleted file mode 100644index b1d5baa1..00000000--- a/agent/internal/agent/file_handlers_windows.go+++ /dev/null@@ -1,36 +0,0 @@-//go:build windows--package agent--import "golang.org/x/sys/windows"--// enumerateDriveRoots lists the available logical drives (C:/, D:/, …) as-// virtual directory entries. Windows has no single filesystem root, so a-// browse request for "" or "/" returns the drive list rather than silently-// listing only the agent process's working drive. Paths are forward-slash-// to match the on-the-wire convention the rest of file:list uses; the-// allowlist still gates whether the panel can actually enter each drive.-func enumerateDriveRoots() []map[string]interface{} {- mask, err := windows.GetLogicalDrives()- if err != nil || mask == 0 {- return nil- }- drives := make([]map[string]interface{}, 0)- for i := 0; i < 26; i++ {- if mask&(1<<uint(i)) == 0 {- continue- }- letter := string(rune('A' + i))- drives = append(drives, map[string]interface{}{- "name": letter + ":",- "path": letter + ":/",- "is_dir": true,- "size": int64(0),- "modified": int64(0),- })- }- if len(drives) == 0 {- return nil- }- return drives-}diff --git a/agent/internal/agent/firewall_handlers.go b/agent/internal/agent/firewall_handlers.godeleted file mode 100644index 10a9fda3..00000000--- a/agent/internal/agent/firewall_handlers.go+++ /dev/null@@ -1,86 +0,0 @@-package agent--import (- "context"- "encoding/json"- "fmt"- "os/exec"- "runtime"- "strconv"- "strings"-)--// Handlers for firewall:* actions. Minimal host-firewall control so the-// tunnel broker can open the edge's inbound WireGuard UDP port (roadmap-// #10). Linux-only; tries ufw → firewalld → iptables, first present.-// Requires root (the agent already runs privileged for systemd/packages);-// failures return a clear error and the broker falls back to surfacing-// the manual command.--func (a *Agent) handleFirewallAllowPort(_ context.Context, params json.RawMessage) (interface{}, error) {- return firewallPort(params, true)-}--func (a *Agent) handleFirewallDenyPort(_ context.Context, params json.RawMessage) (interface{}, error) {- return firewallPort(params, false)-}--func firewallPort(params json.RawMessage, allow bool) (interface{}, error) {- var p struct {- Port int `json:"port"`- Protocol string `json:"protocol"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if p.Port < 1 || p.Port > 65535 {- return nil, fmt.Errorf("invalid port %d", p.Port)- }- proto := strings.ToLower(strings.TrimSpace(p.Protocol))- if proto != "tcp" && proto != "udp" {- proto = "udp"- }- if runtime.GOOS != "linux" {- return nil, fmt.Errorf("firewall management is only supported on Linux agents")- }- spec := fmt.Sprintf("%d/%s", p.Port, proto)-- if _, err := exec.LookPath("ufw"); err == nil {- action := "allow"- if !allow {- action = "deny"- }- if out, err := exec.Command("ufw", action, spec).CombinedOutput(); err != nil {- return nil, fmt.Errorf("ufw %s %s: %w (%s)", action, spec, err, strings.TrimSpace(string(out)))- }- return map[string]interface{}{"success": true, "method": "ufw", "spec": spec}, nil- }-- if _, err := exec.LookPath("firewall-cmd"); err == nil {- flag := "--add-port"- if !allow {- flag = "--remove-port"- }- if out, err := exec.Command("firewall-cmd", flag+"="+spec).CombinedOutput(); err != nil {- return nil, fmt.Errorf("firewall-cmd %s=%s: %w (%s)", flag, spec, err, strings.TrimSpace(string(out)))- }- // Persist across reboots (best-effort) + reload.- _, _ = exec.Command("firewall-cmd", flag+"="+spec, "--permanent").CombinedOutput()- _, _ = exec.Command("firewall-cmd", "--reload").CombinedOutput()- return map[string]interface{}{"success": true, "method": "firewalld", "spec": spec}, nil- }-- if _, err := exec.LookPath("iptables"); err == nil {- op := "-I" // insert (allow)- if !allow {- op = "-D" // delete the rule- }- out, err := exec.Command("iptables", op, "INPUT", "-p", proto, "--dport", strconv.Itoa(p.Port), "-j", "ACCEPT").CombinedOutput()- if err != nil {- return nil, fmt.Errorf("iptables %s %s: %w (%s)", op, spec, err, strings.TrimSpace(string(out)))- }- return map[string]interface{}{"success": true, "method": "iptables", "spec": spec}, nil- }-- return nil, fmt.Errorf("no supported firewall found (ufw / firewalld / iptables)")-}diff --git a/agent/internal/agent/package_handlers.go b/agent/internal/agent/package_handlers.godeleted file mode 100644index 407920d1..00000000--- a/agent/internal/agent/package_handlers.go+++ /dev/null@@ -1,564 +0,0 @@-package agent--// Phase 1c additions — package manager actions beyond the original-// install/remove/list trio: search, info, update-cache, plus a-// streaming variant of install/upgrade that emits progress on a job-// channel for the Packages tab and one-click templates.-//-// The existing handlePackagesInstall (single-name, synchronous,-// idempotent short-circuit) is left alone so the workflow engine's-// agent_command callers still get a structured result. New callers-// wanting progress streaming use packages:install_async / packages:upgrade.--import (- "bufio"- "context"- "encoding/json"- "errors"- "fmt"- "io"- "os/exec"- "strings"- "sync"- "time"-- "github.com/serverkit/agent/internal/jobs"-)--// extendedPackageManager carries the new-action arg patterns alongside-// the existing packageManager. We don't fold these into packageManager-// itself to keep the original definition (and its callers) untouched.-type extendedPackageManager struct {- bin string- updateCache []string- upgradeAll []string- upgradePkg []string // appended with package name(s)- searchCmd []string- infoCmd []string // appended with name-}--func extendedFor(pm *packageManager) *extendedPackageManager {- switch pm.bin {- case "apt-get":- return &extendedPackageManager{- bin: "apt-get",- updateCache: []string{"update"},- upgradeAll: []string{"upgrade", "-y", "-o", "Dpkg::Options::=--force-confold"},- upgradePkg: []string{"install", "--only-upgrade", "-y", "-o", "Dpkg::Options::=--force-confold"},- searchCmd: []string{"search"}, // run via apt-cache below- infoCmd: []string{"show"}, // run via apt-cache below- }- case "dnf", "yum":- return &extendedPackageManager{- bin: pm.bin,- updateCache: []string{"check-update"},- upgradeAll: []string{"upgrade", "-y"},- upgradePkg: []string{"upgrade", "-y"},- searchCmd: []string{"search"},- infoCmd: []string{"info"},- }- case "apk":- return &extendedPackageManager{- bin: "apk",- updateCache: []string{"update"},- upgradeAll: []string{"upgrade"},- upgradePkg: []string{"upgrade"},- searchCmd: []string{"search", "-v"},- infoCmd: []string{"info"},- }- case "pacman":- return &extendedPackageManager{- bin: "pacman",- updateCache: []string{"-Sy"},- upgradeAll: []string{"-Syu", "--noconfirm"},- upgradePkg: []string{"-S", "--noconfirm"},- searchCmd: []string{"-Ss"},- infoCmd: []string{"-Si"},- }- case "zypper":- return &extendedPackageManager{- bin: "zypper",- updateCache: []string{"refresh"},- upgradeAll: []string{"update", "-y"},- upgradePkg: []string{"update", "-y"},- searchCmd: []string{"se"},- infoCmd: []string{"info"},- }- }- return nil-}--// ───── packages:update_cache ──────────────────────────────────────--func (a *Agent) handlePackagesUpdateCache(ctx context.Context, params json.RawMessage) (interface{}, error) {- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- ext := extendedFor(pm)- if ext == nil {- return nil, fmt.Errorf("update_cache: manager %q not supported", pm.bin)- }- a.pkgLock.Lock()- defer a.pkgLock.Unlock()-- cctx, cancel := context.WithTimeout(ctx, 2*time.Minute)- defer cancel()- cmd, err := sudoCommandContext(cctx, a.sudoMode, ext.bin, ext.updateCache...)- if err != nil {- return nil, err- }- out, err := cmd.CombinedOutput()- tail := truncate(string(out), 4096)- if err != nil && !isCheckUpdateExit100(ext.bin, err) {- // dnf check-update returns 100 when updates are available; that- // isn't a failure, just an "actionable" exit. Anything else is- // treated as a real error.- if classifySudoError(string(out)) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("%s %s: %w (%s)", ext.bin, strings.Join(ext.updateCache, " "), err, tail)- }- return map[string]interface{}{- "manager": ext.bin,- "output": tail,- }, nil-}--// dnf check-update conventionally exits 100 when there are updates-// pending, 0 when nothing to do. We treat both as success.-func isCheckUpdateExit100(bin string, err error) bool {- if bin != "dnf" && bin != "yum" {- return false- }- var ee *exec.ExitError- if errors.As(err, &ee) {- return ee.ExitCode() == 100- }- return false-}--// ───── packages:search ────────────────────────────────────────────--func (a *Agent) handlePackagesSearch(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Query string `json:"query"`- Limit int `json:"limit"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- q := strings.TrimSpace(p.Query)- if q == "" {- return nil, errors.New("query is required")- }- if err := validatePackageName(q); err != nil {- // Reject metachars; reuse the install validator since search- // goes straight to argv.- return nil, err- }- if p.Limit <= 0 || p.Limit > 500 {- p.Limit = 500- }-- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- ext := extendedFor(pm)- if ext == nil {- return nil, fmt.Errorf("search: manager %q not supported", pm.bin)- }-- cctx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()-- bin := ext.bin- args := append([]string{}, ext.searchCmd...)- if pm.bin == "apt-get" {- bin = "apt-cache"- }- args = append(args, q)- out, err := exec.CommandContext(cctx, bin, args...).CombinedOutput()- if err != nil && len(out) == 0 {- return nil, fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err)- }- lines := splitNonEmptyLines(string(out))- if len(lines) > p.Limit {- lines = lines[:p.Limit]- }- return map[string]interface{}{- "manager": pm.bin,- "query": q,- "limit": p.Limit,- "results": lines,- }, nil-}--// ───── packages:info ──────────────────────────────────────────────--func (a *Agent) handlePackagesInfo(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Name string `json:"name"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validatePackageName(p.Name); err != nil {- return nil, err- }- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- ext := extendedFor(pm)- if ext == nil {- return nil, fmt.Errorf("info: manager %q not supported", pm.bin)- }-- cctx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()- bin := ext.bin- if pm.bin == "apt-get" {- bin = "apt-cache"- }- args := append(append([]string{}, ext.infoCmd...), p.Name)- out, err := exec.CommandContext(cctx, bin, args...).CombinedOutput()- if err != nil && len(out) == 0 {- return nil, fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err)- }- return map[string]interface{}{- "manager": pm.bin,- "name": p.Name,- "output": truncate(string(out), 16*1024),- }, nil-}--// ───── packages:install_async + packages:upgrade ─────────────────--// installRequest is the shared param shape for install_async / upgrade.-// Either Names (list) or Name (single) may be set; an empty Names with-// All=true upgrades everything (only meaningful for upgrade).-type installRequest struct {- Names []string `json:"names"`- Name string `json:"name"`- All bool `json:"all"`-}--func (r *installRequest) normalize() error {- if r.Name != "" {- r.Names = append(r.Names, r.Name)- }- for _, n := range r.Names {- if err := validatePackageName(n); err != nil {- return err- }- }- return nil-}--// handlePackagesInstallAsync is a streaming variant of install: returns-// {job_id, channel} immediately and emits per-line progress on the-// channel. Idempotent like the sync variant — packages already-// installed are skipped (we still emit a status event).-func (a *Agent) handlePackagesInstallAsync(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p installRequest- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := p.normalize(); err != nil {- return nil, err- }- if len(p.Names) == 0 {- return nil, errors.New("at least one package name required")- }- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- if a.sudoMode == SudoUnavailable {- return nil, errSudoRequired- }-- job := a.jobs.New(200)- go a.runPackageInstallJob(job, pm, p.Names)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- }, nil-}--// handlePackagesUpgrade upgrades the named packages, or all packages-// when All=true. Streams progress identically to install_async.-func (a *Agent) handlePackagesUpgrade(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p installRequest- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := p.normalize(); err != nil {- return nil, err- }- if !p.All && len(p.Names) == 0 {- return nil, errors.New("either names[] or all=true required")- }- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- ext := extendedFor(pm)- if ext == nil {- return nil, fmt.Errorf("upgrade: manager %q not supported", pm.bin)- }- if a.sudoMode == SudoUnavailable {- return nil, errSudoRequired- }-- job := a.jobs.New(200)- go a.runPackageUpgradeJob(job, pm, ext, p.Names, p.All)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- }, nil-}--// runPackageInstallJob runs the apt/dnf/etc. install in the background,-// streams output line-by-line on the job channel, and emits a final-// done event with the structured result.-func (a *Agent) runPackageInstallJob(job *jobs.Job, pm *packageManager, names []string) {- a.pkgLock.Lock()- defer a.pkgLock.Unlock()-- exit := 0- emitDone := func(errStr string, installed []string) {- ev := jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{- "manager": pm.bin,- "action": "install",- "installed": installed,- },- }- _ = job.Push(a.ws, ev)- }-- // Skip already-installed packages.- probeCtx, probeCancel := context.WithTimeout(context.Background(), 30*time.Second)- var toInstall, alreadyInstalled []string- for _, n := range names {- if installed, _ := pm.isInstalled(probeCtx, n); installed {- alreadyInstalled = append(alreadyInstalled, n)- continue- }- toInstall = append(toInstall, n)- }- probeCancel()-- if len(alreadyInstalled) > 0 {- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseStatus,- Message: fmt.Sprintf("already installed: %s", strings.Join(alreadyInstalled, ", ")),- })- }- if len(toInstall) == 0 {- emitDone("", alreadyInstalled)- return- }-- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseStart,- Message: fmt.Sprintf("installing %d package(s) via %s", len(toInstall), pm.bin),- })-- // Long-running command — bound at 15 minutes.- cctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)- defer cancel()- args := append(append([]string{}, pm.install...), toInstall...)- cmd, err := sudoCommandContext(cctx, a.sudoMode, pm.bin, args...)- if err != nil {- exit = -1- emitDone(err.Error(), nil)- return- }- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error(), nil)- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOf(cerr)- if exit == 0 {- exit = -1- }- emitDone(cerr.Error(), nil)- return- }- emitDone("", append(alreadyInstalled, toInstall...))-}--func (a *Agent) runPackageUpgradeJob(job *jobs.Job, pm *packageManager, ext *extendedPackageManager, names []string, all bool) {- a.pkgLock.Lock()- defer a.pkgLock.Unlock()-- exit := 0- emitDone := func(errStr string) {- ev := jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{- "manager": pm.bin,- "action": "upgrade",- "all": all,- },- }- _ = job.Push(a.ws, ev)- }-- cctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)- defer cancel()-- // apt: refresh the package index first so upgrade sees newly- // published versions. Other managers do this implicitly.- if pm.bin == "apt-get" {- updCmd, err := sudoCommandContext(cctx, a.sudoMode, ext.bin, ext.updateCache...)- if err != nil {- exit = -1- emitDone(err.Error())- return- }- if err := streamCmdOutput(updCmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- _ = updCmd.Wait()- }-- var args []string- if all {- args = append([]string{}, ext.upgradeAll...)- } else {- args = append(append([]string{}, ext.upgradePkg...), names...)- }- cmd, err := sudoCommandContext(cctx, a.sudoMode, ext.bin, args...)- if err != nil {- exit = -1- emitDone(err.Error())- return- }- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseStart,- Message: fmt.Sprintf("%s %s", ext.bin, strings.Join(args, " ")),- })- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOf(cerr)- if exit == 0 {- exit = -1- }- emitDone(cerr.Error())- return- }- emitDone("")-}--// streamCmdOutput attaches a line-buffered stdout/stderr scanner to cmd-// and pushes batches of lines on the job channel. Lines are flushed on-// a 100ms window or 32-line threshold, whichever comes first, so the-// panel sees steady progress without one event per line at high-// throughput.-//-// Blocks until both pipes close, then returns. Caller is expected to-// invoke cmd.Wait() afterwards to reap the process and get the exit-// code. Returns an error only if cmd.Start fails or pipe setup fails.-func streamCmdOutput(cmd *exec.Cmd, job *jobs.Job, s jobs.Streamer) error {- stdout, err := cmd.StdoutPipe()- if err != nil {- return err- }- stderr, err := cmd.StderrPipe()- if err != nil {- return err- }- if err := cmd.Start(); err != nil {- return err- }-- lines := make(chan string, 256)- var wg sync.WaitGroup- wg.Add(2)- go scanLines(stdout, lines, &wg)- go scanLines(stderr, lines, &wg)-- // Closer goroutine: once both scanners have returned, close the- // channel so the batcher knows there's no more input.- go func() {- wg.Wait()- close(lines)- }()-- // Batcher: flush every 100ms or 32 lines. Runs synchronously so- // the caller can rely on "all output emitted before we return."- batch := make([]string, 0, 32)- flush := func() {- if len(batch) == 0 {- return- }- _ = job.Push(s, jobs.Event{Phase: jobs.PhaseLog, Lines: append([]string{}, batch...)})- batch = batch[:0]- }- ticker := time.NewTicker(100 * time.Millisecond)- defer ticker.Stop()- for {- select {- case ln, ok := <-lines:- if !ok {- flush()- return nil- }- batch = append(batch, ln)- if len(batch) >= 32 {- flush()- }- case <-ticker.C:- flush()- }- }-}--func scanLines(r io.ReadCloser, out chan<- string, wg *sync.WaitGroup) {- defer wg.Done()- defer r.Close()- sc := bufio.NewScanner(r)- sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)- for sc.Scan() {- out <- sc.Text()- }-}--func exitCodeOf(err error) int {- var ee *exec.ExitError- if errors.As(err, &ee) {- return ee.ExitCode()- }- return -1-}--func splitNonEmptyLines(s string) []string {- var out []string- for _, ln := range strings.Split(s, "\n") {- ln = strings.TrimRight(ln, "\r")- if strings.TrimSpace(ln) == "" {- continue- }- out = append(out, ln)- }- return out-}-diff --git a/agent/internal/agent/recapabilities.go b/agent/internal/agent/recapabilities.godeleted file mode 100644index 479139b2..00000000--- a/agent/internal/agent/recapabilities.go+++ /dev/null@@ -1,128 +0,0 @@-package agent--// agent:recapabilities — re-runs the capability probe on demand. The-// panel calls this after the user installs a runtime / sudoers entry /-// new package manager, so new feature surfaces light up without a-// service restart.-//-// Concurrent re-probes are common (the panel may fire one per server-// detail page open) and the underlying probes spawn subprocesses, so-// we guard with a coarse mutex: if a probe is already in flight we-// return the cached set with reprobe="in_progress" instead of-// queueing.--import (- "context"- "encoding/json"- "time"-- "github.com/serverkit/agent/internal/capabilities"- "github.com/serverkit/agent/pkg/protocol"-)--func (a *Agent) handleAgentRecapabilities(ctx context.Context, params json.RawMessage) (interface{}, error) {- a.capMu.Lock()- if a.reprobing {- caps := a.capabilities- a.capMu.Unlock()- return map[string]interface{}{- "reprobe": "in_progress",- "capabilities": caps,- }, nil- }- a.reprobing = true- a.capMu.Unlock()- defer func() {- a.capMu.Lock()- a.reprobing = false- a.capMu.Unlock()- }()-- // Use a fresh, bounded context — the caller's request timeout- // might be shorter than the probe takes, but we still want to- // finish so the next subscriber sees fresh state.- probeCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)- defer cancel()-- // Clear the PATH lookup cache so newly installed binaries (e.g. the- // user just ran apt install nginx) are seen by this re-probe.- capabilities.ClearPathCache()-- fresh := capabilities.Probe(- probeCtx,- a.log,- a.docker != nil,- a.cfg.Features.FileAccess,- a.cfg.Security.AllowedPaths,- )-- // Re-probe sudo as well — the user may have added passwordless- // sudoers config since boot.- mode := probeSudoMode(probeCtx)- fresh.Sudo = string(mode)- // Re-detect runtime version managers; user may have just bootstrapped- // pyenv via runtimes:pyenv:bootstrap and is hitting refresh.- fresh.RuntimeManagers = map[string]string{- "python": pyenvManagerKind(),- }- fresh.ProbedAt = time.Now().UnixMilli()-- // Capabilities are additive across re-probes: if the previous- // snapshot saw a feature the panel cared about, don't drop it just- // because a transient probe failed (e.g. dockerd briefly- // restarting). Only flip false→true here, never true→false.- a.capMu.Lock()- merged := mergeCapabilities(a.capabilities, fresh)- a.capabilities = merged- a.sudoMode = mode- a.capMu.Unlock()-- // Push to the panel so the in-memory ConnectedAgent record updates- // without an explicit refetch.- a.sendCapabilities()-- return map[string]interface{}{- "reprobe": "ok",- "capabilities": merged,- }, nil-}--// mergeCapabilities returns a payload where bool capabilities are the-// OR of prev and fresh, runtime maps are unioned, and the "presence"-// of optional fields prefers fresh values. Numeric/string fields like-// distro version are taken from fresh because the host might have been-// upgraded between probes.-//-// The asymmetry is deliberate: a transient probe failure (dockerd-// briefly down, journalctl hung) shouldn't cause a panel-side feature-// to disappear, but a real upgrade/install should be reflected. So we-// only flip false→true here, never true→false. To force a clean view-// the operator can restart the agent.-func mergeCapabilities(prev, fresh protocol.CapabilitiesMessage) protocol.CapabilitiesMessage {- out := fresh- if out.Capabilities == nil {- out.Capabilities = protocol.Capabilities{}- }- for k, v := range prev.Capabilities {- if v && !out.Capabilities[k] {- out.Capabilities[k] = true- }- }- if out.Runtimes == nil {- out.Runtimes = map[string]string{}- }- for k, v := range prev.Runtimes {- if _, ok := out.Runtimes[k]; !ok && v != "" {- out.Runtimes[k] = v- }- }- if out.RuntimeManagers == nil {- out.RuntimeManagers = map[string]string{}- }- for k, v := range prev.RuntimeManagers {- if _, ok := out.RuntimeManagers[k]; !ok && v != "" {- out.RuntimeManagers[k] = v- }- }- return out-}diff --git a/agent/internal/agent/registration.go b/agent/internal/agent/registration.godeleted file mode 100644index e55513cc..00000000--- a/agent/internal/agent/registration.go+++ /dev/null@@ -1,206 +0,0 @@-package agent--import (- "bytes"- "context"- "crypto/hmac"- "crypto/sha256"- "crypto/tls"- "encoding/hex"- "encoding/json"- "fmt"- "io"- "net/http"- "os"- "runtime"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/metrics"-)--// Registration handles agent registration with ServerKit-type Registration struct {- log *logger.Logger-}--// RegistrationResult contains the result of registration-type RegistrationResult struct {- AgentID string `json:"agent_id"`- Name string `json:"name"`- APIKey string `json:"api_key"`- APISecret string `json:"api_secret"`- WebSocketURL string `json:"websocket_url"`-}--// NewRegistration creates a new Registration handler-func NewRegistration(log *logger.Logger) *Registration {- return &Registration{- log: log.WithComponent("registration"),- }-}--// Register registers the agent with a ServerKit instance-func (r *Registration) Register(serverURL, token, name string) (*RegistrationResult, error) {- // Normalize server URL- serverURL = strings.TrimSuffix(serverURL, "/")-- // If no name provided, use hostname- if name == "" {- hostname, err := os.Hostname()- if err != nil {- name = "unknown-server"- } else {- name = hostname- }- }-- // Collect system info for registration- collector := metrics.NewCollector(config.MetricsConfig{}, r.log)- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- sysInfo, err := collector.GetSystemInfo(ctx)- if err != nil {- r.log.Warn("Failed to collect system info", "error", err)- sysInfo = &metrics.SystemInfo{- Hostname: name,- OS: runtime.GOOS,- Architecture: runtime.GOARCH,- }- }-- // Prepare registration request- reqBody := map[string]interface{}{- "token": token,- "name": name,- "system_info": map[string]interface{}{- "hostname": sysInfo.Hostname,- "os": sysInfo.OS,- "platform": sysInfo.Platform,- "platform_version": sysInfo.PlatformVersion,- "architecture": sysInfo.Architecture,- "cpu_cores": sysInfo.CPUCores,- "total_memory": sysInfo.TotalMemory,- "total_disk": sysInfo.TotalDisk,- },- "agent_version": Version,- }-- bodyBytes, err := json.Marshal(reqBody)- if err != nil {- return nil, fmt.Errorf("failed to marshal request: %w", err)- }-- // Create HTTP client- client := &http.Client{- Timeout: 30 * time.Second,- Transport: &http.Transport{- TLSClientConfig: &tls.Config{- InsecureSkipVerify: os.Getenv("SERVERKIT_INSECURE_TLS") == "true",- },- },- }-- // Make registration request- registrationURL := serverURL + "/api/v1/servers/register"- r.log.Info("Sending registration request", "url", registrationURL)-- req, err := http.NewRequestWithContext(ctx, "POST", registrationURL, bytes.NewReader(bodyBytes))- if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", Version))-- resp, err := client.Do(req)- if err != nil {- return nil, fmt.Errorf("registration request failed: %w", err)- }- defer resp.Body.Close()-- // Read response- respBody, err := io.ReadAll(resp.Body)- if err != nil {- return nil, fmt.Errorf("failed to read response: %w", err)- }-- // Check status code- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {- var errResp struct {- Error string `json:"error"`- }- json.Unmarshal(respBody, &errResp)- if errResp.Error != "" {- return nil, fmt.Errorf("registration failed: %s", errResp.Error)- }- return nil, fmt.Errorf("registration failed with status %d", resp.StatusCode)- }-- // Parse response- var result RegistrationResult- if err := json.Unmarshal(respBody, &result); err != nil {- return nil, fmt.Errorf("failed to parse response: %w", err)- }-- // Construct WebSocket URL if not provided- if result.WebSocketURL == "" {- wsURL := serverURL- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)- result.WebSocketURL = wsURL + "/agent/ws"- }-- r.log.Info("Registration successful",- "agent_id", result.AgentID,- "name", result.Name,- )-- return &result, nil-}--// Unregister unregisters the agent from ServerKit-func (r *Registration) Unregister(serverURL, agentID, apiKey, apiSecret string) error {- serverURL = strings.TrimSuffix(serverURL, "/")-- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- client := &http.Client{- Timeout: 30 * time.Second,- }-- req, err := http.NewRequestWithContext(ctx, "DELETE", serverURL+"/api/v1/agents/"+agentID, nil)- if err != nil {- return fmt.Errorf("failed to create request: %w", err)- }-- // HMAC-based authentication instead of sending raw secret- timestamp := fmt.Sprintf("%d", time.Now().UnixMilli())- message := fmt.Sprintf("%s:%s", agentID, timestamp)- mac := hmac.New(sha256.New, []byte(apiSecret))- mac.Write([]byte(message))- signature := hex.EncodeToString(mac.Sum(nil))-- req.Header.Set("X-Agent-ID", agentID)- req.Header.Set("X-Timestamp", timestamp)- req.Header.Set("X-Signature", signature)-- resp, err := client.Do(req)- if err != nil {- return fmt.Errorf("unregister request failed: %w", err)- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {- return fmt.Errorf("unregister failed with status %d", resp.StatusCode)- }-- return nil-}--// Version is set during build-var Version = "dev"diff --git a/agent/internal/agent/runtime_handlers.go b/agent/internal/agent/runtime_handlers.godeleted file mode 100644index d6710748..00000000--- a/agent/internal/agent/runtime_handlers.go+++ /dev/null@@ -1,400 +0,0 @@-package agent--// Phase 5 — runtime version managers (pyenv on Linux, pyenv-win on-// Windows). The agent already ships a Python version via the-// capability probe; these handlers add install / uninstall / select--// version flows so users can pick a Python without SSHing in.-//-// Bootstrap and install actions stream on a job channel because they-// take minutes — pyenv compiles CPython from source on Linux and-// downloads + extracts MSI installers on Windows.--import (- "context"- "encoding/json"- "errors"- "fmt"- "os"- "os/exec"- "path/filepath"- "runtime"- "strings"- "sync"- "time"-- "github.com/serverkit/agent/internal/jobs"-)--// pyenvLock serializes pyenv mutations on a single agent. pyenv's-// shim management is not safe under concurrent installs.-var pyenvLock sync.Mutex--// pyenvBin returns the path to the pyenv binary the agent should use,-// or "" if pyenv isn't installed. On Linux we look at $HOME/.pyenv/bin-// and PATH; on Windows we look at %USERPROFILE%\.pyenv\pyenv-win\bin.-func pyenvBin() string {- if runtime.GOOS == "windows" {- home, _ := os.UserHomeDir()- if home == "" {- home = os.Getenv("USERPROFILE")- }- if home != "" {- candidate := filepath.Join(home, ".pyenv", "pyenv-win", "bin", "pyenv.bat")- if _, err := os.Stat(candidate); err == nil {- return candidate- }- }- if p, err := exec.LookPath("pyenv"); err == nil {- return p- }- return ""- }- // Linux/macOS- home, _ := os.UserHomeDir()- if home != "" {- candidate := filepath.Join(home, ".pyenv", "bin", "pyenv")- if _, err := os.Stat(candidate); err == nil {- return candidate- }- }- if p, err := exec.LookPath("pyenv"); err == nil {- return p- }- return ""-}--// pyenvManagerKind returns "pyenv", "pyenv-win", or "" for absent.-// Surfaced as RuntimeManagers["python"] in the capabilities payload.-func pyenvManagerKind() string {- if pyenvBin() == "" {- return ""- }- if runtime.GOOS == "windows" {- return "pyenv-win"- }- return "pyenv"-}--// runPyenv runs the pyenv binary with the given args and returns the-// trimmed stdout/stderr. Used by the read-only handlers.-func runPyenv(ctx context.Context, args ...string) (string, error) {- bin := pyenvBin()- if bin == "" {- return "", errors.New("pyenv not installed (run runtimes:pyenv:bootstrap first)")- }- cctx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()- out, err := exec.CommandContext(cctx, bin, args...).CombinedOutput()- return strings.TrimSpace(string(out)), err-}--// ───── runtimes:list ──────────────────────────────────────────────--func (a *Agent) handleRuntimesList(ctx context.Context, params json.RawMessage) (interface{}, error) {- out := map[string]interface{}{- "managers": map[string]string{- "python": pyenvManagerKind(),- },- "runtimes": a.capabilities.Runtimes,- }- if pyenvManagerKind() != "" {- current, _ := runPyenv(ctx, "version")- installed, _ := runPyenv(ctx, "versions", "--bare")- out["python"] = map[string]interface{}{- "current": strings.SplitN(current, " ", 2)[0],- "installed": splitNonEmptyLines(installed),- }- }- return out, nil-}--// ───── runtimes:python:installed ─────────────────────────────────--func (a *Agent) handleRuntimesPythonInstalled(ctx context.Context, params json.RawMessage) (interface{}, error) {- out, err := runPyenv(ctx, "versions", "--bare")- if err != nil {- return nil, err- }- return map[string]interface{}{- "versions": splitNonEmptyLines(out),- "manager": pyenvManagerKind(),- }, nil-}--// ───── runtimes:python:available ─────────────────────────────────--func (a *Agent) handleRuntimesPythonAvailable(ctx context.Context, params json.RawMessage) (interface{}, error) {- // `pyenv install --list` on Linux and `pyenv install -l` on- // pyenv-win both work, but pyenv-win prints them with leading- // whitespace. Normalize.- out, err := runPyenv(ctx, "install", "--list")- if err != nil && pyenvManagerKind() == "pyenv-win" {- out, err = runPyenv(ctx, "install", "-l")- }- if err != nil {- return nil, err- }- versions := []string{}- for _, line := range strings.Split(out, "\n") {- line = strings.TrimSpace(line)- if line == "" || strings.HasPrefix(line, "Available") || strings.HasPrefix(line, ":") {- continue- }- versions = append(versions, line)- }- return map[string]interface{}{- "versions": versions,- "manager": pyenvManagerKind(),- }, nil-}--// ───── runtimes:python:current ───────────────────────────────────--func (a *Agent) handleRuntimesPythonCurrent(ctx context.Context, params json.RawMessage) (interface{}, error) {- out, err := runPyenv(ctx, "version")- if err != nil {- return nil, err- }- parts := strings.SplitN(out, " ", 2)- return map[string]interface{}{- "version": parts[0],- "raw": out,- }, nil-}--// ───── runtimes:python:set_global ────────────────────────────────--func (a *Agent) handleRuntimesPythonSetGlobal(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Version string `json:"version"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, err- }- if err := validateVersion(p.Version); err != nil {- return nil, err- }- out, err := runPyenv(ctx, "global", p.Version)- if err != nil {- return nil, fmt.Errorf("pyenv global %s: %w (%s)", p.Version, err, out)- }- return map[string]interface{}{"global": p.Version}, nil-}--// ───── runtimes:python:set_local ─────────────────────────────────--func (a *Agent) handleRuntimesPythonSetLocal(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Version string `json:"version"`- Dir string `json:"dir"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, err- }- if err := validateVersion(p.Version); err != nil {- return nil, err- }- abs, err := filepath.Abs(p.Dir)- if err != nil {- return nil, fmt.Errorf("dir: %w", err)- }- if !a.contextPathAllowed(abs) {- return nil, fmt.Errorf("dir %q is not under any allowed root", abs)- }- bin := pyenvBin()- if bin == "" {- return nil, errors.New("pyenv not installed")- }- cctx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()- cmd := exec.CommandContext(cctx, bin, "local", p.Version)- cmd.Dir = abs- out, err := cmd.CombinedOutput()- if err != nil {- return nil, fmt.Errorf("pyenv local %s in %s: %w (%s)", p.Version, abs, err, string(out))- }- return map[string]interface{}{"local": p.Version, "dir": abs}, nil-}--// ───── runtimes:python:uninstall ─────────────────────────────────--func (a *Agent) handleRuntimesPythonUninstall(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Version string `json:"version"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, err- }- if err := validateVersion(p.Version); err != nil {- return nil, err- }- pyenvLock.Lock()- defer pyenvLock.Unlock()- out, err := runPyenv(ctx, "uninstall", "-f", p.Version)- if err != nil {- return nil, fmt.Errorf("pyenv uninstall %s: %w (%s)", p.Version, err, out)- }- return map[string]interface{}{"uninstalled": p.Version}, nil-}--// ───── runtimes:python:install (streaming) ───────────────────────--func (a *Agent) handleRuntimesPythonInstall(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Version string `json:"version"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, err- }- if err := validateVersion(p.Version); err != nil {- return nil, err- }- if pyenvBin() == "" {- return nil, errors.New("pyenv not installed (run runtimes:pyenv:bootstrap first)")- }- job := a.jobs.New(500)- go a.runPyenvInstallJob(job, p.Version)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- "version": p.Version,- }, nil-}--func (a *Agent) runPyenvInstallJob(job *jobs.Job, version string) {- pyenvLock.Lock()- defer pyenvLock.Unlock()-- exit := 0- emitDone := func(errStr string) {- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{"version": version, "manager": pyenvManagerKind()},- })- }-- cctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)- defer cancel()- cmd := exec.CommandContext(cctx, pyenvBin(), "install", "-s", version)- _ = job.Push(a.ws, jobs.Event{Phase: jobs.PhaseStart, Message: fmt.Sprintf("pyenv install %s", version)})- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOfCmd(cerr)- if exit == 0 {- exit = -1- }- emitDone(cerr.Error())- return- }- emitDone("")-}--// ───── runtimes:pyenv:bootstrap (streaming) ──────────────────────-//-// Linux: clones pyenv to ~/.pyenv. Does NOT touch ~/.bashrc — most-// agents run as a non-login systemd unit and the user already has-// shell init from their interactive sessions; we don't want to-// duplicate it. Clone path matches the upstream installer.-//-// Windows: clones pyenv-win to %USERPROFILE%\.pyenv\pyenv-win.--func (a *Agent) handleRuntimesPyenvBootstrap(ctx context.Context, params json.RawMessage) (interface{}, error) {- if pyenvBin() != "" {- return map[string]interface{}{- "status": "already_installed",- "manager": pyenvManagerKind(),- }, nil- }- if _, err := exec.LookPath("git"); err != nil {- return nil, errors.New("git is required to install pyenv (please install git first)")- }- job := a.jobs.New(200)- go a.runPyenvBootstrapJob(job)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- }, nil-}--func (a *Agent) runPyenvBootstrapJob(job *jobs.Job) {- exit := 0- emitDone := func(errStr string) {- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{"manager": pyenvManagerKind()},- })- }-- home, _ := os.UserHomeDir()- if home == "" && runtime.GOOS == "windows" {- home = os.Getenv("USERPROFILE")- }- if home == "" {- exit = -1- emitDone("could not determine user home directory")- return- }-- var repo, dest string- if runtime.GOOS == "windows" {- repo = "https://github.com/pyenv-win/pyenv-win.git"- dest = filepath.Join(home, ".pyenv")- } else {- repo = "https://github.com/pyenv/pyenv.git"- dest = filepath.Join(home, ".pyenv")- }-- _ = job.Push(a.ws, jobs.Event{Phase: jobs.PhaseStart, Message: fmt.Sprintf("git clone %s %s", repo, dest)})-- cctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)- defer cancel()- cmd := exec.CommandContext(cctx, "git", "clone", "--depth", "1", repo, dest)- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOfCmd(cerr)- if exit == 0 {- exit = -1- }- emitDone(cerr.Error())- return- }- emitDone("")-}--// validateVersion rejects shell metacharacters in the user-supplied-// pyenv version reference. pyenv tags are dotted-version strings ("3.12.0",-// "3.13.0a4") so the allow-list is conservative.-func validateVersion(v string) error {- v = strings.TrimSpace(v)- if v == "" {- return errors.New("version is required")- }- for _, r := range v {- if r >= 'a' && r <= 'z' {- continue- }- if r >= 'A' && r <= 'Z' {- continue- }- if r >= '0' && r <= '9' {- continue- }- if r == '.' || r == '-' || r == '_' || r == '+' {- continue- }- return fmt.Errorf("invalid version: %q", v)- }- return nil-}diff --git a/agent/internal/agent/sampler.go b/agent/internal/agent/sampler.godeleted file mode 100644index e92e50ef..00000000--- a/agent/internal/agent/sampler.go+++ /dev/null@@ -1,80 +0,0 @@-package agent--import (- "context"- "sync"- "time"-- "github.com/serverkit/agent/internal/ipc"-)--// metricSampler maintains a fixed-size ring buffer of CPU and memory samples-// taken once per second. The agent's main metrics path (Collect → emit over-// the WebSocket) already pulls live values, but the desktop console needs a-// short-lived history to render sparklines without keeping a long-lived-// websocket of its own to the agent. 300 samples × 1 s = 5 minutes of-// scrollback, which matches the Overview tab design.-type metricSampler struct {- mu sync.Mutex- samples []ipc.MetricSample- cap int-}--func newMetricSampler(capacity int) *metricSampler {- return &metricSampler{- samples: make([]ipc.MetricSample, 0, capacity),- cap: capacity,- }-}--// push records one sample, evicting the oldest when the buffer is full.-func (s *metricSampler) push(sample ipc.MetricSample) {- s.mu.Lock()- defer s.mu.Unlock()- if len(s.samples) >= s.cap {- copy(s.samples, s.samples[1:])- s.samples = s.samples[:len(s.samples)-1]- }- s.samples = append(s.samples, sample)-}--// snapshot returns a copy of the current samples in chronological order so-// the caller can serialize them without holding the lock.-func (s *metricSampler) snapshot() []ipc.MetricSample {- s.mu.Lock()- defer s.mu.Unlock()- out := make([]ipc.MetricSample, len(s.samples))- copy(out, s.samples)- return out-}--// samplerLoop runs until ctx is cancelled. Every tick it pulls one CPU/Mem-// sample from the agent's metrics collector and pushes it into the ring.-// Transient collection errors are swallowed: a one-tick gap is preferable-// to a stutter in the graph or a noisy log.-func (a *Agent) samplerLoop(ctx context.Context) {- ticker := time.NewTicker(1 * time.Second)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- if a.metrics == nil || a.sampler == nil {- continue- }- collectCtx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)- sm, err := a.metrics.Collect(collectCtx)- cancel()- if err != nil {- continue- }- a.sampler.push(ipc.MetricSample{- Timestamp: time.Now().UnixMilli(),- CPU: sm.CPUPercent,- Mem: sm.MemoryPercent,- })- }- }-}diff --git a/agent/internal/agent/security_test.go b/agent/internal/agent/security_test.godeleted file mode 100644index eb7a84e6..00000000--- a/agent/internal/agent/security_test.go+++ /dev/null@@ -1,199 +0,0 @@-package agent--import (- "crypto/hmac"- "crypto/sha256"- "encoding/hex"- "fmt"- "os"- "path/filepath"- "runtime"- "testing"-- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/pkg/protocol"-)--func TestCommandBlocked(t *testing.T) {- cases := []struct {- name string- blocked []string- cmd string- want bool- }{- {"empty list allows everything", nil, "/bin/ls", false},- {"absolute path match", []string{"/usr/bin/rm"}, "/usr/bin/rm", true},- {"basename match against absolute path", []string{"rm"}, "/usr/bin/rm", true},- {"absolute-to-basename match", []string{"/sbin/shutdown"}, "/usr/local/sbin/shutdown", true},- {"unrelated command not blocked", []string{"/usr/bin/rm"}, "/usr/bin/ls", false},- {"blank entries ignored", []string{"", " ", "/usr/bin/rm"}, "/usr/bin/rm", true},- {"blank entries don't deny everything", []string{"", " "}, "/bin/ls", false},- {"whitespace trimmed on entries", []string{" /bin/dd "}, "/bin/dd", true},- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- if got := commandBlocked(tc.blocked, tc.cmd); got != tc.want {- t.Fatalf("commandBlocked(%v, %q) = %v, want %v", tc.blocked, tc.cmd, got, tc.want)- }- })- }-}--func TestResolveMaxExecTimeout(t *testing.T) {- a := &Agent{cfg: &config.Config{}}- got := a.resolveMaxExecTimeout()- if got != defaultMaxExecTimeout {- t.Fatalf("default fallback: got %s, want %s", got, defaultMaxExecTimeout)- }-- a.cfg.Security.MaxExecTimeout = defaultMaxExecTimeout / 2- if got := a.resolveMaxExecTimeout(); got != defaultMaxExecTimeout/2 {- t.Fatalf("operator override: got %s, want %s", got, defaultMaxExecTimeout/2)- }-- a.cfg.Security.MaxExecTimeout = -1- if got := a.resolveMaxExecTimeout(); got != defaultMaxExecTimeout {- t.Fatalf("negative ignored: got %s, want %s", got, defaultMaxExecTimeout)- }-}--func TestValidateFileAccessAllowsConfiguredRoot(t *testing.T) {- root := t.TempDir()- a := &Agent{cfg: &config.Config{- Security: config.SecurityConfig{AllowedPaths: []string{root}},- }}- target := filepath.Join(root, "sub", "file.txt")- // Create the parent so EvalSymlinks succeeds for the parent walk.- if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {- t.Fatal(err)- }- if err := a.validateFileAccess(target); err != nil {- t.Fatalf("expected access allowed for %s: %v", target, err)- }-}--func TestValidateFileAccessDeniesOutsideRoot(t *testing.T) {- root := t.TempDir()- other := t.TempDir()- a := &Agent{cfg: &config.Config{- Security: config.SecurityConfig{AllowedPaths: []string{root}},- }}- if err := a.validateFileAccess(filepath.Join(other, "file.txt")); err == nil {- t.Fatalf("expected access denied for path outside allowed root")- }-}--func TestValidateFileAccessDeniesSymlinkEscape(t *testing.T) {- if runtime.GOOS == "windows" {- // Windows symlink creation requires elevated privileges or- // SeCreateSymbolicLinkPrivilege in CI; skip rather than make- // the test environmentally fragile.- t.Skip("symlink test requires non-Windows environment")- }- root := t.TempDir()- secret := t.TempDir()- a := &Agent{cfg: &config.Config{- Security: config.SecurityConfig{AllowedPaths: []string{root}},- }}- // Drop a symlink inside the allowed root that points outside it.- // The pre-fix validateFileAccess would let the escape through- // because filepath.Clean doesn't resolve symlinks.- link := filepath.Join(root, "escape")- if err := os.Symlink(secret, link); err != nil {- t.Fatalf("symlink: %v", err)- }- target := filepath.Join(link, "file.txt")- if err := a.validateFileAccess(target); err == nil {- t.Fatalf("expected symlink escape to be denied; %s resolved past allowed root", target)- }-}--func TestValidateFileAccessNoAllowedPaths(t *testing.T) {- a := &Agent{cfg: &config.Config{}}- if err := a.validateFileAccess("/anything"); err == nil {- t.Fatalf("expected denial when AllowedPaths is empty")- }-}--func TestVerifyCredentialRotation(t *testing.T) {- currentSecret := "current-secret-value"- rotationID := "rot-123"- agentID := "agent-uuid"- newKey := "sk_newkey"- newSecret := "new-secret-value"-- a := &Agent{- cfg: &config.Config{Agent: config.AgentConfig{ID: agentID}},- auth: auth.New(agentID, "sk_oldkey", currentSecret),- }-- sign := func(secret string) string {- mac := hmac.New(sha256.New, []byte(secret))- mac.Write([]byte(fmt.Sprintf("%s:%s:%s:%s", rotationID, agentID, newKey, newSecret)))- return hex.EncodeToString(mac.Sum(nil))- }-- t.Run("valid signature accepted", func(t *testing.T) {- msg := protocol.CredentialUpdateMessage{- RotationID: rotationID,- APIKey: newKey,- APISecret: newSecret,- HMACSig: sign(currentSecret),- }- if err := a.verifyCredentialRotation(msg); err != nil {- t.Fatalf("expected valid rotation accepted, got: %v", err)- }- })-- t.Run("missing signature rejected", func(t *testing.T) {- msg := protocol.CredentialUpdateMessage{- RotationID: rotationID,- APIKey: newKey,- APISecret: newSecret,- }- if err := a.verifyCredentialRotation(msg); err == nil {- t.Fatalf("expected rejection for missing signature")- }- })-- t.Run("wrong-secret signature rejected", func(t *testing.T) {- msg := protocol.CredentialUpdateMessage{- RotationID: rotationID,- APIKey: newKey,- APISecret: newSecret,- HMACSig: sign("attacker-guessed-secret"),- }- if err := a.verifyCredentialRotation(msg); err == nil {- t.Fatalf("expected rejection when HMAC computed with wrong secret")- }- })-- t.Run("missing required field rejected", func(t *testing.T) {- msg := protocol.CredentialUpdateMessage{- RotationID: "",- APIKey: newKey,- APISecret: newSecret,- HMACSig: sign(currentSecret),- }- if err := a.verifyCredentialRotation(msg); err == nil {- t.Fatalf("expected rejection for missing rotation_id")- }- })-- t.Run("agent without secret refuses rotation", func(t *testing.T) {- empty := &Agent{- cfg: &config.Config{Agent: config.AgentConfig{ID: agentID}},- auth: auth.New(agentID, "", ""),- }- msg := protocol.CredentialUpdateMessage{- RotationID: rotationID,- APIKey: newKey,- APISecret: newSecret,- HMACSig: sign(""),- }- if err := empty.verifyCredentialRotation(msg); err == nil {- t.Fatalf("expected rejection when agent has no current secret")- }- })-}diff --git a/agent/internal/agent/sudo.go b/agent/internal/agent/sudo.godeleted file mode 100644index 8fef5666..00000000--- a/agent/internal/agent/sudo.go+++ /dev/null@@ -1,124 +0,0 @@-package agent--// Privilege escalation helpers. The agent's install script lays down a-// dedicated `serverkit-agent` user, so handlers that touch system state-// (systemctl, apt, dnf, journalctl on system journals) need to escalate-// when the agent isn't running as root. We use passwordless sudo (-n)-// so a hung password prompt can't tie up a request.-//-// The decision is made once at startup: probe whether `sudo -n true`-// succeeds, cache the result, and surface it on the capabilities-// payload as one of "root", "passwordless", or "unavailable" so the-// panel can warn users *before* they try to install something.-//-// When the mode is "unavailable", privileged handlers fail fast with a-// "sudo_required" error instead of spawning a subprocess that would-// deadlock waiting for a password.--import (- "context"- "errors"- "os"- "os/exec"- "runtime"- "strings"- "time"-)--// SudoMode describes how the agent escalates privileges.-type SudoMode string--const (- SudoRoot SudoMode = "root" // EUID == 0- SudoPasswordless SudoMode = "passwordless" // sudo -n works- SudoUnavailable SudoMode = "unavailable" // no escalation possible-)--// errSudoRequired is returned by privileged handlers when escalation-// isn't available. Wrapped with extra context by the calling handler.-var errSudoRequired = errors.New("sudo required: agent is running as a non-root user and passwordless sudo is not configured")--// probeSudoMode determines the agent's escalation capability. Called-// once at startup; the result is cached in Agent.sudoMode.-func probeSudoMode(ctx context.Context) SudoMode {- if runtime.GOOS != "linux" {- // Non-linux hosts don't run the privileged handlers anyway —- // systemd/packages capabilities are gated off on those.- if isAdminWindows() {- return SudoRoot- }- return SudoUnavailable- }- if os.Geteuid() == 0 {- return SudoRoot- }- if _, err := exec.LookPath("sudo"); err != nil {- return SudoUnavailable- }- cctx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()- cmd := exec.CommandContext(cctx, "sudo", "-n", "true")- if err := cmd.Run(); err != nil {- return SudoUnavailable- }- return SudoPasswordless-}--// isAdminWindows is a placeholder: the privileged handlers are gated by-// runtime.GOOS == "linux" anyway, so the only effect is the value-// surfaced on the capabilities payload. Returning false everywhere on-// Windows is safe.-func isAdminWindows() bool { return false }--// sudoCommandContext returns an exec.Cmd that runs `name args...` with-// privilege escalation according to the agent's sudo mode. When the-// mode is "unavailable", it returns nil and a sudo_required error —-// callers must check both.-//-// The returned Cmd has DEBIAN_FRONTEND=noninteractive in its env so-// dpkg conffile prompts don't hang installs in production. Callers-// that need additional env should append to cmd.Env after the call.-func sudoCommandContext(ctx context.Context, mode SudoMode, name string, args ...string) (*exec.Cmd, error) {- switch mode {- case SudoRoot:- cmd := exec.CommandContext(ctx, name, args...)- cmd.Env = privilegedEnv()- return cmd, nil- case SudoPasswordless:- full := append([]string{"-n", name}, args...)- cmd := exec.CommandContext(ctx, "sudo", full...)- cmd.Env = privilegedEnv()- return cmd, nil- default:- return nil, errSudoRequired- }-}--// privilegedEnv builds the env block used for privileged commands.-// Inherits the parent process env and adds DEBIAN_FRONTEND so apt-// upgrades don't stop on conffile prompts.-func privilegedEnv() []string {- out := append([]string{}, os.Environ()...)- out = append(out, "DEBIAN_FRONTEND=noninteractive")- return out-}--// classifySudoError matches stderr text from a failed escalation-// attempt and returns true when sudo specifically refused (password-// required, terminal required, no permission). Used to wrap downstream-// errors with a clean "sudo_required" code instead of leaking the raw-// sudo banner to the panel.-func classifySudoError(stderr string) bool {- low := strings.ToLower(stderr)- for _, marker := range []string{- "a password is required",- "a terminal is required",- "sudo: not allowed",- "sudo: must be setuid root",- } {- if strings.Contains(low, marker) {- return true- }- }- return false-}diff --git a/agent/internal/agent/systemd_handlers.go b/agent/internal/agent/systemd_handlers.godeleted file mode 100644index 5cb7c9df..00000000--- a/agent/internal/agent/systemd_handlers.go+++ /dev/null@@ -1,363 +0,0 @@-package agent--// Phase 1c additions — systemd actions beyond status/start/stop/restart/-// enable/disable: daemon-reload, list-units, journal logs (bounded fetch-// and follow-stream variants).-//-// list-units prefers `systemctl --output=json` (systemd 244+) for clean-// parsing and falls back to plain text on older systems. The choice is-// probed once and cached on the agent so we don't pay the fork cost on-// every list call.--import (- "context"- "encoding/json"- "errors"- "fmt"- "os/exec"- "strings"- "time"-- "github.com/serverkit/agent/internal/jobs"- "github.com/serverkit/agent/pkg/protocol"-)--// runSystemctlPrivileged is the sudo-aware variant of runSystemctl. It-// preserves the existing 30-second timeout for read operations; long-// operations (start/stop/restart/daemon-reload) override via timeout-// param.-func (a *Agent) runSystemctlPrivileged(ctx context.Context, timeout time.Duration, args ...string) (string, error) {- cctx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()- cmd, err := sudoCommandContext(cctx, a.sudoMode, "systemctl", args...)- if err != nil {- return "", err- }- out, err := cmd.CombinedOutput()- return strings.TrimSpace(string(out)), err-}--// ───── systemd:daemon_reload ──────────────────────────────────────--func (a *Agent) handleSystemdDaemonReload(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- out, err := a.runSystemctlPrivileged(ctx, 5*time.Minute, "daemon-reload")- if err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl daemon-reload: %w (%s)", err, out)- }- return map[string]interface{}{- "action": "daemon_reloaded",- "output": out,- }, nil-}--// ───── systemd:list_units ─────────────────────────────────────────--// systemctlUnit is the canonical row shape returned by list_units-// regardless of whether we got JSON or plain text from systemctl.-type systemctlUnit struct {- Unit string `json:"unit"`- Load string `json:"load,omitempty"`- Active string `json:"active,omitempty"`- Sub string `json:"sub,omitempty"`- Description string `json:"description,omitempty"`-}--func (a *Agent) handleSystemdListUnits(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- var p struct {- State string `json:"state"` // optional filter: failed, active, inactive…- Type string `json:"type"` // unit type: service (default), socket, timer…- }- _ = json.Unmarshal(params, &p)- if p.Type == "" {- p.Type = "service"- }- if err := validateUnitName(p.Type); err != nil {- return nil, fmt.Errorf("type: %w", err)- }- if p.State != "" {- if err := validateUnitName(p.State); err != nil {- return nil, fmt.Errorf("state: %w", err)- }- }-- args := []string{"list-units", "--all", "--no-legend", "--no-pager", "--type=" + p.Type}- if p.State != "" {- args = append(args, "--state="+p.State)- }-- useJSON := a.detectSystemctlJSON(ctx)- if useJSON {- jsonArgs := append(append([]string{}, args...), "--output=json")- out, err := a.runSystemctlPrivileged(ctx, 30*time.Second, jsonArgs...)- if err == nil {- var rows []map[string]interface{}- if jerr := json.Unmarshal([]byte(out), &rows); jerr == nil {- units := make([]systemctlUnit, 0, len(rows))- for _, r := range rows {- u := systemctlUnit{}- if v, ok := r["unit"].(string); ok {- u.Unit = v- }- if v, ok := r["load"].(string); ok {- u.Load = v- }- if v, ok := r["active"].(string); ok {- u.Active = v- }- if v, ok := r["sub"].(string); ok {- u.Sub = v- }- if v, ok := r["description"].(string); ok {- u.Description = v- }- units = append(units, u)- }- return map[string]interface{}{"units": units, "format": "json"}, nil- }- }- // JSON failed (older systemd, malformed output) — fall through- // to plain text and remember the choice.- a.capMu.Lock()- a.capabilities.SystemdJSON = false- a.systemdJSON = false- a.capMu.Unlock()- }-- // Plain text fallback. Columns: UNIT LOAD ACTIVE SUB DESCRIPTION.- out, err := a.runSystemctlPrivileged(ctx, 30*time.Second, args...)- if err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl list-units: %w (%s)", err, truncate(out, 1024))- }- units := parsePlainListUnits(out)- return map[string]interface{}{"units": units, "format": "plain"}, nil-}--// detectSystemctlJSON probes once whether `systemctl --output=json` is-// supported. Caches the result on the agent + advertises via the-// capabilities payload so the panel can show an "older systemd" hint.-func (a *Agent) detectSystemctlJSON(ctx context.Context) bool {- a.systemdJSONOnce.Do(func() {- cctx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()- err := exec.CommandContext(cctx, "systemctl", "list-units", "--no-legend", "--no-pager", "--output=json", "--type=service").Run()- ok := err == nil- a.capMu.Lock()- a.systemdJSON = ok- a.capabilities.SystemdJSON = ok- a.capMu.Unlock()- })- a.capMu.Lock()- defer a.capMu.Unlock()- return a.systemdJSON-}--func parsePlainListUnits(out string) []systemctlUnit {- units := []systemctlUnit{}- for _, line := range strings.Split(out, "\n") {- line = strings.TrimSpace(line)- if line == "" || strings.HasPrefix(line, "●") {- continue- }- fields := strings.Fields(line)- if len(fields) < 4 {- continue- }- u := systemctlUnit{- Unit: fields[0],- Load: fields[1],- Active: fields[2],- Sub: fields[3],- }- if len(fields) > 4 {- u.Description = strings.Join(fields[4:], " ")- }- units = append(units, u)- }- return units-}--// ───── systemd:logs (bounded fetch) ──────────────────────────────--func (a *Agent) handleSystemdLogs(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- var p struct {- Unit string `json:"unit"`- Lines int `json:"lines"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validateUnitName(p.Unit); err != nil {- return nil, err- }- if p.Lines <= 0 {- p.Lines = 200- }- if p.Lines > 5000 {- p.Lines = 5000- }-- if _, err := exec.LookPath("journalctl"); err != nil {- return nil, errors.New("journalctl not on PATH")- }-- cctx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()- cmd, err := sudoCommandContext(cctx, a.sudoMode, "journalctl",- "-u", p.Unit, "--no-pager", "-n", fmt.Sprintf("%d", p.Lines), "-o", "json")- if err != nil {- return nil, err- }- out, err := cmd.CombinedOutput()- if err != nil {- if classifySudoError(string(out)) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("journalctl -u %s: %w (%s)", p.Unit, err, truncate(string(out), 1024))- }-- // journalctl -o json prints one JSON object per line. Parse each- // into a flat shape the panel can render directly.- type entry struct {- Time string `json:"time"`- Priority string `json:"priority"`- PID string `json:"pid"`- Message string `json:"message"`- }- var entries []entry- for _, line := range strings.Split(string(out), "\n") {- line = strings.TrimSpace(line)- if line == "" {- continue- }- var raw map[string]interface{}- if err := json.Unmarshal([]byte(line), &raw); err != nil {- continue- }- e := entry{- Time: stringField(raw, "__REALTIME_TIMESTAMP"),- Priority: stringField(raw, "PRIORITY"),- PID: stringField(raw, "_PID"),- Message: stringField(raw, "MESSAGE"),- }- entries = append(entries, e)- }- return map[string]interface{}{- "unit": p.Unit,- "lines": p.Lines,- "entries": entries,- }, nil-}--func stringField(m map[string]interface{}, k string) string {- v, ok := m[k]- if !ok {- return ""- }- switch t := v.(type) {- case string:- return t- case float64:- return fmt.Sprintf("%.0f", t)- default:- return fmt.Sprintf("%v", t)- }-}--// ───── systemd:logs_follow (streaming) ───────────────────────────--// handleSystemdLogsFollow returns a job channel and starts streaming-// `journalctl -fu <unit>` lines on it. The job ends when either the-// caller unsubscribes (which we detect by closing job.Done) or a fixed-// 1-hour cap elapses to prevent runaway logs.-//-// The pattern mirrors handlePackagesInstallAsync: hand back-// {job_id, channel} immediately, work happens in a goroutine.-func (a *Agent) handleSystemdLogsFollow(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- var p struct {- Unit string `json:"unit"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validateUnitName(p.Unit); err != nil {- return nil, err- }- if _, err := exec.LookPath("journalctl"); err != nil {- return nil, errors.New("journalctl not on PATH")- }-- job := a.jobs.New(500)- // The protocol channel format is documented but we override to use- // the job: namespace so the panel's existing job-channel- // infrastructure handles it. The systemd:<unit>:logs format is- // reserved for a future multi-subscriber broadcast variant.- _ = protocol.ChannelSystemdLogs- go a.runSystemdLogsFollowJob(job, p.Unit)- return map[string]interface{}{- "job_id": job.ID,- "channel": job.Channel,- "unit": p.Unit,- }, nil-}--func (a *Agent) runSystemdLogsFollowJob(job *jobs.Job, unit string) {- exit := 0- emitDone := func(errStr string) {- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseDone,- ExitCode: &exit,- Error: errStr,- Extra: map[string]interface{}{"unit": unit},- })- }-- // Cap any single follow at 1 hour. Panel can re-subscribe.- cctx, cancel := context.WithTimeout(context.Background(), 1*time.Hour)- defer cancel()- cmd, err := sudoCommandContext(cctx, a.sudoMode, "journalctl",- "-fu", unit, "--no-pager", "-o", "short-iso")- if err != nil {- exit = -1- emitDone(err.Error())- return- }- _ = job.Push(a.ws, jobs.Event{- Phase: jobs.PhaseStart,- Message: fmt.Sprintf("following journal for %s", unit),- })- if err := streamCmdOutput(cmd, job, a.ws); err != nil {- exit = -1- emitDone(err.Error())- return- }- if cerr := cmd.Wait(); cerr != nil {- exit = exitCodeOf(cerr)- // journalctl returns non-zero when killed by the deadline; that's- // a graceful end, not an error.- if cctx.Err() == context.DeadlineExceeded {- emitDone("")- return- }- emitDone(cerr.Error())- return- }- emitDone("")-}diff --git a/agent/internal/agent/wireguard_handlers.go b/agent/internal/agent/wireguard_handlers.godeleted file mode 100644index e98aa5a8..00000000--- a/agent/internal/agent/wireguard_handlers.go+++ /dev/null@@ -1,105 +0,0 @@-package agent--import (- "context"- "encoding/json"- "fmt"-- "github.com/serverkit/agent/internal/wireguard"-)--// Handlers for wireguard:* actions. Thin parse + dispatch; validation-// lives in the wireguard package. The panel's tunnel broker-// (backend/app/services/tunnel_broker_service.py) sequences these to-// pair two agents. See docs/REMOTE_ACCESS_ROADMAP.md.--func (a *Agent) handleWireguardKeygen(_ context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Interface string `json:"interface"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return a.wireguard.Keygen(p.Interface)-}--func (a *Agent) handleWireguardInterfaceUp(_ context.Context, params json.RawMessage) (interface{}, error) {- var req wireguard.InterfaceUpRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.InterfaceUp(req); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleWireguardInterfaceDown(_ context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Interface string `json:"interface"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.InterfaceDown(p.Interface); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleWireguardPeerSet(_ context.Context, params json.RawMessage) (interface{}, error) {- var req wireguard.PeerSetRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.SetPeer(req); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleWireguardPeerRemove(_ context.Context, params json.RawMessage) (interface{}, error) {- var req wireguard.PeerRemoveRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.RemovePeer(req); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleWireguardStatus(_ context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Interface string `json:"interface"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- return a.wireguard.Status(p.Interface)-}--func (a *Agent) handleWireguardForward(_ context.Context, params json.RawMessage) (interface{}, error) {- var req wireguard.ForwardRequest- if err := json.Unmarshal(params, &req); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.Forward(req); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}--func (a *Agent) handleWireguardUnforward(_ context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Interface string `json:"interface"`- ListenPort int `json:"listen_port"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := a.wireguard.Unforward(p.Interface, p.ListenPort); err != nil {- return nil, err- }- return map[string]bool{"success": true}, nil-}diff --git a/agent/internal/agent/workflow_handlers.go b/agent/internal/agent/workflow_handlers.godeleted file mode 100644index 4dee27aa..00000000--- a/agent/internal/agent/workflow_handlers.go+++ /dev/null@@ -1,481 +0,0 @@-package agent--// Phase 4 primitive handlers — package install/remove/list, systemd-// unit control, and bounded shell exec. The workflow engine on the-// panel sequences these to drive playbooks like "install Docker" or-// "install LAMP" against any agent-managed server.-//-// All handlers are Linux-only. The capability probe advertises-// "packages" / "systemd" only on Linux hosts where the relevant tooling-// is present, so the panel won't normally call these on Windows/macOS;-// the runtime guard here is belt-and-suspenders.-//-// Idempotency is the contract: re-running an install on a host where-// the package is already there returns success with installed=true and-// no side effects. Same for systemd start on a unit already active.--import (- "context"- "encoding/json"- "errors"- "fmt"- "os/exec"- "path/filepath"- "runtime"- "strings"- "time"-)--const (- // Package install can be slow on a fresh host (apt update + index- // + downloads). Bound at 5 minutes — longer than any single- // install we've seen, short enough to surface a hung mirror.- packageOpTimeout = 5 * time.Minute- // systemctl operations are quick; if one hangs longer than 30s- // something is wrong (mount-blocked unit, hung shutdown).- systemdOpTimeout = 30 * time.Second- // Hard ceiling on exec timeouts when the operator hasn't set- // Security.MaxExecTimeout. The configured value, if any, wins —- // this is just the safety net so a misconfigured agent can't run- // arbitrary commands forever.- defaultMaxExecTimeout = 10 * time.Minute-)--// ───── packages ────────────────────────────────────────────────────--type packageManager struct {- bin string // "apt-get", "dnf", "apk", "pacman", "zypper"- install []string // args before package name(s)- remove []string- list []string- queryFlag string // arg pattern for "is X installed"-}--// detectPackageManager returns the active manager on PATH or an error-// if none is recognised. Order matters — apt-get is preferred over apt-// for non-interactive use.-func detectPackageManager() (*packageManager, error) {- if runtime.GOOS != "linux" {- return nil, errors.New("packages:* is Linux-only")- }- candidates := []*packageManager{- {bin: "apt-get", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "--installed"}, queryFlag: "dpkg"},- {bin: "dnf", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "installed"}, queryFlag: "rpm"},- {bin: "yum", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "installed"}, queryFlag: "rpm"},- {bin: "apk", install: []string{"add"}, remove: []string{"del"}, list: []string{"info"}, queryFlag: "apk"},- {bin: "pacman", install: []string{"-S", "--noconfirm"}, remove: []string{"-R", "--noconfirm"}, list: []string{"-Q"}, queryFlag: "pacman"},- {bin: "zypper", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"se", "--installed-only"}, queryFlag: "rpm"},- }- for _, c := range candidates {- if _, err := exec.LookPath(c.bin); err == nil {- return c, nil- }- }- return nil, errors.New("no recognised package manager on PATH")-}--// isInstalled checks the package database directly so install/remove-// can short-circuit when there's nothing to do. Avoids re-running the-// full manager (which on apt would otherwise refresh sources first).-func (pm *packageManager) isInstalled(ctx context.Context, name string) (bool, error) {- switch pm.queryFlag {- case "dpkg":- out, err := exec.CommandContext(ctx, "dpkg-query", "-W", "-f=${Status}", name).Output()- if err != nil {- return false, nil // not installed- }- return strings.Contains(string(out), "install ok installed"), nil- case "rpm":- err := exec.CommandContext(ctx, "rpm", "-q", name).Run()- return err == nil, nil- case "apk":- err := exec.CommandContext(ctx, "apk", "info", "-e", name).Run()- return err == nil, nil- case "pacman":- err := exec.CommandContext(ctx, "pacman", "-Q", name).Run()- return err == nil, nil- }- return false, fmt.Errorf("unsupported query flag: %s", pm.queryFlag)-}--func validatePackageName(name string) error {- name = strings.TrimSpace(name)- if name == "" {- return errors.New("name is required")- }- // Reject shell metacharacters — the package name goes straight- // into argv but we still don't want to explain to a user why- // `apt-get install "foo; rm -rf /"` worked.- if strings.ContainsAny(name, ";&|`$<>\n\r\"'\\") {- return fmt.Errorf("invalid package name: %q", name)- }- return nil-}--func (a *Agent) handlePackagesInstall(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Name string `json:"name"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validatePackageName(p.Name); err != nil {- return nil, err- }- pm, err := detectPackageManager()- if err != nil {- return nil, err- }-- // Idempotency: check first so a re-run is cheap and obvious.- if installed, _ := pm.isInstalled(ctx, p.Name); installed {- return map[string]interface{}{- "package": p.Name,- "installed": true,- "action": "noop",- "manager": pm.bin,- }, nil- }-- cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)- defer cancel()- args := append(append([]string{}, pm.install...), p.Name)- out, err := exec.CommandContext(cctx, pm.bin, args...).CombinedOutput()- if err != nil {- return nil, fmt.Errorf("%s %s: %w (%s)", pm.bin, strings.Join(args, " "), err, truncate(string(out), 1024))- }- return map[string]interface{}{- "package": p.Name,- "installed": true,- "action": "installed",- "manager": pm.bin,- "output": truncate(string(out), 4096),- }, nil-}--func (a *Agent) handlePackagesRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {- var p struct {- Name string `json:"name"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- if err := validatePackageName(p.Name); err != nil {- return nil, err- }- pm, err := detectPackageManager()- if err != nil {- return nil, err- }-- if installed, _ := pm.isInstalled(ctx, p.Name); !installed {- return map[string]interface{}{- "package": p.Name,- "installed": false,- "action": "noop",- "manager": pm.bin,- }, nil- }-- cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)- defer cancel()- args := append(append([]string{}, pm.remove...), p.Name)- out, err := exec.CommandContext(cctx, pm.bin, args...).CombinedOutput()- if err != nil {- return nil, fmt.Errorf("%s %s: %w (%s)", pm.bin, strings.Join(args, " "), err, truncate(string(out), 1024))- }- return map[string]interface{}{- "package": p.Name,- "installed": false,- "action": "removed",- "manager": pm.bin,- "output": truncate(string(out), 4096),- }, nil-}--func (a *Agent) handlePackagesListInstalled(ctx context.Context, params json.RawMessage) (interface{}, error) {- pm, err := detectPackageManager()- if err != nil {- return nil, err- }- cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)- defer cancel()- out, err := exec.CommandContext(cctx, pm.bin, pm.list...).Output()- if err != nil {- return nil, fmt.Errorf("%s %s: %w", pm.bin, strings.Join(pm.list, " "), err)- }- // Don't try to parse — formats vary too much. Ship the raw output- // and let downstream tooling pick what it cares about.- return map[string]interface{}{- "manager": pm.bin,- "output": truncate(string(out), 1024*256),- }, nil-}--// ───── systemd ─────────────────────────────────────────────────────--func validateUnitName(name string) error {- name = strings.TrimSpace(name)- if name == "" {- return errors.New("unit is required")- }- if strings.ContainsAny(name, ";&|`$<>\n\r\"'\\ ") {- return fmt.Errorf("invalid unit name: %q", name)- }- return nil-}--func systemctlAvailable() error {- if runtime.GOOS != "linux" {- return errors.New("systemd:* is Linux-only")- }- if _, err := exec.LookPath("systemctl"); err != nil {- return errors.New("systemctl not on PATH")- }- return nil-}--func runSystemctl(ctx context.Context, args ...string) (string, error) {- cctx, cancel := context.WithTimeout(ctx, systemdOpTimeout)- defer cancel()- out, err := exec.CommandContext(cctx, "systemctl", args...).CombinedOutput()- return strings.TrimSpace(string(out)), err-}--func parseUnitParam(params json.RawMessage) (string, error) {- var p struct {- Unit string `json:"unit"`- }- if err := json.Unmarshal(params, &p); err != nil {- return "", fmt.Errorf("invalid params: %w", err)- }- if err := validateUnitName(p.Unit); err != nil {- return "", err- }- return p.Unit, nil-}--func (a *Agent) handleSystemdStatus(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- // is-active exits non-zero for inactive — that's expected, capture it.- active, _ := runSystemctl(ctx, "is-active", unit)- enabled, _ := runSystemctl(ctx, "is-enabled", unit)- return map[string]interface{}{- "unit": unit,- "active": active,- "enabled": enabled,- }, nil-}--// systemdMutateTimeout is the per-action timeout for state-changing-// systemctl calls (start/stop/restart/enable/disable). Cold service-// starts (postgresql, mongodb) routinely take 30-90s, so the original-// 30s ceiling was too tight; bump to 2 minutes.-const systemdMutateTimeout = 2 * time.Minute--func (a *Agent) handleSystemdStart(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- if out, err := a.runSystemctlPrivileged(ctx, systemdMutateTimeout, "start", unit); err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl start %s: %w (%s)", unit, err, out)- }- return map[string]interface{}{"unit": unit, "action": "started"}, nil-}--func (a *Agent) handleSystemdStop(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- if out, err := a.runSystemctlPrivileged(ctx, systemdMutateTimeout, "stop", unit); err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl stop %s: %w (%s)", unit, err, out)- }- return map[string]interface{}{"unit": unit, "action": "stopped"}, nil-}--func (a *Agent) handleSystemdRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- if out, err := a.runSystemctlPrivileged(ctx, systemdMutateTimeout, "restart", unit); err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl restart %s: %w (%s)", unit, err, out)- }- return map[string]interface{}{"unit": unit, "action": "restarted"}, nil-}--func (a *Agent) handleSystemdEnable(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- if out, err := a.runSystemctlPrivileged(ctx, systemdMutateTimeout, "enable", unit); err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl enable %s: %w (%s)", unit, err, out)- }- return map[string]interface{}{"unit": unit, "action": "enabled"}, nil-}--func (a *Agent) handleSystemdDisable(ctx context.Context, params json.RawMessage) (interface{}, error) {- if err := systemctlAvailable(); err != nil {- return nil, err- }- unit, err := parseUnitParam(params)- if err != nil {- return nil, err- }- if out, err := a.runSystemctlPrivileged(ctx, systemdMutateTimeout, "disable", unit); err != nil {- if classifySudoError(out) {- return nil, fmt.Errorf("sudo refused: %w", errSudoRequired)- }- return nil, fmt.Errorf("systemctl disable %s: %w (%s)", unit, err, out)- }- return map[string]interface{}{"unit": unit, "action": "disabled"}, nil-}--// ───── system:exec ─────────────────────────────────────────────────--// commandBlocked reports whether cmd matches one of the operator's-// configured BlockedCommands entries. Comparison is exact-match against-// either the full path or the basename, after both sides are-// normalised — operators tend to write either "/usr/bin/rm" or just-// "rm" and we want to honour both. Empty entries are ignored so a-// stray newline in YAML doesn't deny everything.-func commandBlocked(blocked []string, cmd string) bool {- if len(blocked) == 0 {- return false- }- cmdAbs := strings.TrimSpace(cmd)- cmdBase := filepath.Base(cmdAbs)- for _, raw := range blocked {- entry := strings.TrimSpace(raw)- if entry == "" {- continue- }- if entry == cmdAbs || entry == cmdBase {- return true- }- if filepath.Base(entry) == cmdBase {- return true- }- }- return false-}--// resolveMaxExecTimeout honours the operator's Security.MaxExecTimeout-// when set (any positive duration), otherwise falls back to the-// hardcoded ceiling. Negative or zero values are treated as "unset"-// rather than "no timeout"; the agent never runs an unbounded-// subprocess.-func (a *Agent) resolveMaxExecTimeout() time.Duration {- if a.cfg != nil && a.cfg.Security.MaxExecTimeout > 0 {- return a.cfg.Security.MaxExecTimeout- }- return defaultMaxExecTimeout-}--// handleSystemExec runs an arbitrary command, captures stdout/stderr,-// and returns the exit code. The first token must be an absolute path-// (same rule as cron commands) so a misconfigured caller can't depend-// on $PATH state of the agent process. Output is truncated to keep the-// command envelope reasonable; the runner can poll a file if it needs-// the full output of a chatty install.-//-// This handler is only registered when cfg.Features.Exec is true (see-// agent.go:registerHandlers). When Exec is disabled, the panel sees an-// "unknown action" error rather than the command silently running.-func (a *Agent) handleSystemExec(ctx context.Context, params json.RawMessage) (interface{}, error) {- if a.cfg == nil || !a.cfg.Features.Exec {- return nil, errors.New("system:exec is disabled by agent config (features.exec=false)")- }-- var p struct {- Command string `json:"command"`- Args []string `json:"args"`- WorkingDir string `json:"working_dir"`- TimeoutSeconds int `json:"timeout_seconds"`- }- if err := json.Unmarshal(params, &p); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- cmd := strings.TrimSpace(p.Command)- if cmd == "" {- return nil, errors.New("command is required")- }- if !strings.HasPrefix(cmd, "/") {- return nil, errors.New("command must be an absolute path")- }- if strings.ContainsAny(cmd, ";&|`$<>\n\r") {- return nil, errors.New("command contains shell metacharacters; pass arguments via args[]")- }- if commandBlocked(a.cfg.Security.BlockedCommands, cmd) {- return nil, fmt.Errorf("command %q is blocked by agent security config", cmd)- }-- maxTimeout := a.resolveMaxExecTimeout()- timeout := time.Duration(p.TimeoutSeconds) * time.Second- if timeout <= 0 || timeout > maxTimeout {- timeout = maxTimeout- }- cctx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()-- c := exec.CommandContext(cctx, cmd, p.Args...)- if p.WorkingDir != "" {- c.Dir = p.WorkingDir- }- out, err := c.CombinedOutput()- exitCode := 0- if err != nil {- var ee *exec.ExitError- if errors.As(err, &ee) {- exitCode = ee.ExitCode()- } else {- return nil, fmt.Errorf("exec %s: %w", cmd, err)- }- }- return map[string]interface{}{- "command": cmd,- "args": p.Args,- "exit_code": exitCode,- "output": truncate(string(out), 1024*32),- }, nil-}--func truncate(s string, n int) string {- if len(s) <= n {- return s- }- return s[:n] + "\n…[truncated]"-}diff --git a/agent/internal/agentui/actions.go b/agent/internal/agentui/actions.godeleted file mode 100644index 06c03e34..00000000--- a/agent/internal/agentui/actions.go+++ /dev/null@@ -1,194 +0,0 @@-package agentui--import (- "encoding/json"- "net/http"- "os"- "os/exec"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"-)--// localActions exposes a small set of console-process-level operations to-// the React app: things that need to happen even when the agent service is-// down, or that need to be performed by a Windows interactive session-// rather than by SYSTEM-context service code.-//-// All endpoints live under /local/ so they're trivially distinguishable-// from agent-service IPC calls (which target a different port entirely).-type localActions struct {- exePath string- configPath string-}--func newLocalActions(configPath string) *localActions {- exe, _ := exeForSpawn()- return &localActions{exePath: exe, configPath: configPath}-}--// register hooks the action handlers into the asset server's mux.-func (a *localActions) register(mux *http.ServeMux) {- mux.HandleFunc("/local/service/restart", a.handleServiceAction("restart"))- mux.HandleFunc("/local/service/start", a.handleServiceAction("start"))- mux.HandleFunc("/local/service/stop", a.handleServiceAction("stop"))- mux.HandleFunc("/local/open", a.handleOpen)- mux.HandleFunc("/local/wizard", a.handleWizard)- mux.HandleFunc("/local/diag", a.handleDiag)- mux.HandleFunc("/local/status", a.handleStatus)- mux.HandleFunc("/local/ipc-token", a.handleIPCToken)-}--// handleIPCToken returns the agent's IPC bearer token to the in-process-// React UI so it can authenticate against the agent service's HTTP API.-// Both processes run on the same machine under the same user, so the-// console process can read the token file directly — this endpoint-// just hides the OS-specific path from the JS side.-//-// Returns 503 (not 401) when the token isn't ready yet so the UI can-// distinguish "agent service hasn't started writing the file" from-// "you got the wrong credential" — the former resolves itself when the-// service starts, the latter is a real config bug.-func (a *localActions) handleIPCToken(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- data, err := os.ReadFile(config.IPCTokenPath())- if err != nil {- writeJSON(w, http.StatusServiceUnavailable, map[string]string{- "error": "ipc token not yet available; is the agent service running?",- })- return- }- tok := strings.TrimSpace(string(data))- if tok == "" {- writeJSON(w, http.StatusServiceUnavailable, map[string]string{- "error": "ipc token file empty",- })- return- }- writeJSON(w, http.StatusOK, map[string]string{"token": tok})-}--// handleStatus reports whether the agent has been paired by reading-// config.yaml directly. The React PairGate uses this as a fallback when-// the agent service IPC is unreachable — which is exactly the case on a-// fresh install: no config means no service, so the service can't tell-// the UI it isn't registered. Without this endpoint the wizard is a-// dead end on first run.-func (a *localActions) handleStatus(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- resp := map[string]interface{}{- "registered": false,- "agent_id": "",- "server_url": "",- }- if cfg, err := config.Load(a.configPath); err == nil && cfg != nil {- if cfg.Agent.ID != "" {- resp["registered"] = true- resp["agent_id"] = cfg.Agent.ID- resp["server_url"] = cfg.Server.URL- }- }- writeJSON(w, http.StatusOK, resp)-}--func writeJSON(w http.ResponseWriter, status int, v interface{}) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(status)- _ = json.NewEncoder(w).Encode(v)-}--// handleServiceAction performs sc.exe stop/start/restart against the-// installed ServerKitAgent service. Restart is "stop, brief wait, start"-// because sc.exe has no native restart verb and the agent's IPC restart-// is just a graceful stop with no auto-spin-up.-func (a *localActions) handleServiceAction(action string) http.HandlerFunc {- return func(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- switch action {- case "start":- if err := runServiceCmd("start"); err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- case "stop":- if err := runServiceCmd("stop"); err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- case "restart":- // Best-effort stop — ignore "service not running" errors and- // move on. Then start. This is what the tray's restart button- // should have been doing all along.- _ = runServiceCmd("stop")- time.Sleep(1500 * time.Millisecond)- if err := runServiceCmd("start"); err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- }-- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})- }-}--// handleOpen launches a path in Explorer or a URL in the default browser.-// Body: {"path": "C:\\..."} OR {"url": "https://..."}.-func (a *localActions) handleOpen(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- var body struct {- Path string `json:"path"`- URL string `json:"url"`- }- if err := json.NewDecoder(r.Body).Decode(&body); err != nil {- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})- return- }- target := body.URL- if target == "" {- target = body.Path- }- if target == "" {- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "path or url required"})- return- }- if err := openTarget(target); err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})-}--// handleWizard spawns the pairing wizard as a detached child process.-// Used by the Re-pair button — gives the user a fresh form without-// interrupting the running console window.-func (a *localActions) handleWizard(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- if a.exePath == "" {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "agent executable path unknown"})- return- }- cmd := exec.Command(a.exePath, "setup")- if err := cmd.Start(); err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- // We don't Wait on the child — it lives on its own.- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})-}diff --git a/agent/internal/agentui/diag.go b/agent/internal/agentui/diag.godeleted file mode 100644index eb490e6f..00000000--- a/agent/internal/agentui/diag.go+++ /dev/null@@ -1,214 +0,0 @@-package agentui--import (- "archive/zip"- "bytes"- "encoding/json"- "fmt"- "io"- "net/http"- "os"- "path/filepath"- "runtime"- "strings"- "time"-- "gopkg.in/yaml.v3"-)--// handleDiag builds a diagnostic bundle on the user's Desktop. Includes the-// current agent log, the activity events file, a redacted copy of-// config.yaml, and a small system info JSON. Returns the path so the React-// app can prompt "Open in Explorer" or just inform the user where it is.-//-// We write to Desktop on purpose: the most common reason to grab a bundle-// is to share it with someone, and Desktop is the universally-known spot.-// Falls back to the user's home dir if Desktop can't be located.-func (a *localActions) handleDiag(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- dest, err := buildDiagBundle()- if err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }- writeJSON(w, http.StatusOK, map[string]string{"path": dest})-}--func buildDiagBundle() (string, error) {- dataDir := dataDirGuess()- dest := diagDestPath()-- out, err := os.Create(dest)- if err != nil {- return "", fmt.Errorf("create diag: %w", err)- }- defer out.Close()-- zw := zip.NewWriter(out)- defer zw.Close()-- // Current agent log (might not exist if never started — that's fine)- if dataDir != "" {- _ = addFileToZip(zw, filepath.Join(dataDir, "logs", "agent.log"), "agent.log")- // Most-recent rotated backup, if any (lumberjack names them with a- // timestamp suffix). Search and add up to 3 to keep the bundle slim.- if backups, err := findLogBackups(filepath.Join(dataDir, "logs")); err == nil {- for i, p := range backups {- if i >= 3 {- break- }- _ = addFileToZip(zw, p, "logs-backups/"+filepath.Base(p))- }- }- // Events- _ = addFileToZip(zw, filepath.Join(dataDir, "events.json"), "events.json")- // Config (redacted)- if redacted, err := redactedConfigYAML(filepath.Join(dataDir, "config.yaml")); err == nil {- _ = addBytesToZip(zw, "config.redacted.yaml", redacted)- }- }-- // System info written last so it's the easiest to find when somebody- // opens the zip.- sysJSON, _ := json.MarshalIndent(systemInfo(), "", " ")- _ = addBytesToZip(zw, "sysinfo.json", sysJSON)-- return dest, nil-}--func addFileToZip(zw *zip.Writer, src, archivedName string) error {- info, err := os.Stat(src)- if err != nil || info.IsDir() {- return err- }- f, err := os.Open(src)- if err != nil {- return err- }- defer f.Close()- w, err := zw.Create(archivedName)- if err != nil {- return err- }- _, err = io.Copy(w, f)- return err-}--func addBytesToZip(zw *zip.Writer, name string, data []byte) error {- w, err := zw.Create(name)- if err != nil {- return err- }- _, err = w.Write(data)- return err-}--// redactedConfigYAML reads config.yaml and returns it with any auth secrets-// stripped. We don't need the api_key / api_secret to debug connectivity,-// and shipping them through casual support channels is a bad habit.-func redactedConfigYAML(path string) ([]byte, error) {- data, err := os.ReadFile(path)- if err != nil {- return nil, err- }- var doc map[string]interface{}- if err := yaml.Unmarshal(data, &doc); err != nil {- // Couldn't parse — return the raw bytes with a header noting that- // redaction was skipped. Better than failing the bundle.- var buf bytes.Buffer- buf.WriteString("# diag: failed to parse for redaction; original returned as-is\n")- buf.Write(data)- return buf.Bytes(), nil- }- if auth, ok := doc["auth"].(map[string]interface{}); ok {- for _, k := range []string{"api_key", "api_secret", "apikey", "apisecret"} {- if _, has := auth[k]; has {- auth[k] = "[REDACTED]"- }- }- }- return yaml.Marshal(doc)-}--func findLogBackups(dir string) ([]string, error) {- entries, err := os.ReadDir(dir)- if err != nil {- return nil, err- }- var out []string- for _, e := range entries {- name := e.Name()- if strings.HasPrefix(name, "agent-") && (strings.HasSuffix(name, ".log") || strings.HasSuffix(name, ".log.gz")) {- out = append(out, filepath.Join(dir, name))- }- }- // Newest first- sortDescByModTime(out)- return out, nil-}--func sortDescByModTime(paths []string) {- type entry struct {- path string- mod time.Time- }- infos := make([]entry, 0, len(paths))- for _, p := range paths {- st, err := os.Stat(p)- if err != nil {- continue- }- infos = append(infos, entry{p, st.ModTime()})- }- // Tiny list (<= a handful) — bubble sort is plenty.- for i := 0; i < len(infos); i++ {- for j := i + 1; j < len(infos); j++ {- if infos[j].mod.After(infos[i].mod) {- infos[i], infos[j] = infos[j], infos[i]- }- }- }- for i, e := range infos {- if i < len(paths) {- paths[i] = e.path- }- }-}--func systemInfo() map[string]interface{} {- host, _ := os.Hostname()- return map[string]interface{}{- "os": runtime.GOOS,- "arch": runtime.GOARCH,- "hostname": host,- "go_version": runtime.Version(),- "generated": time.Now().Format(time.RFC3339),- }-}--func dataDirGuess() string {- // Mirrors agent/config.DefaultConfigPath() without importing it (avoids- // a cycle with the rest of the agent package). Best-effort — if the env- // var isn't set we just skip the parts that need it.- if pd := os.Getenv("ProgramData"); pd != "" {- return filepath.Join(pd, "ServerKit", "Agent")- }- return ""-}--func diagDestPath() string {- stamp := time.Now().Format("20060102-150405")- name := fmt.Sprintf("serverkit-diag-%s.zip", stamp)- if home, err := os.UserHomeDir(); err == nil {- desktop := filepath.Join(home, "Desktop")- if st, err := os.Stat(desktop); err == nil && st.IsDir() {- return filepath.Join(desktop, name)- }- return filepath.Join(home, name)- }- return name-}diff --git a/agent/internal/agentui/embed.go b/agent/internal/agentui/embed.godeleted file mode 100644index 07e6324c..00000000--- a/agent/internal/agentui/embed.go+++ /dev/null@@ -1,27 +0,0 @@-// Package agentui hosts the ServerKit agent's desktop console: a WebView2-// window driven by an embedded React SPA. It coexists with the legacy walk-// pairing wizard in setupui — the wizard handles first-run pairing today,-// and this package owns the post-pair "running app" experience that the-// tray previously delegated to a few menu items. Over the next milestones-// the wizard migrates here too so there's one window for everything.-package agentui--import (- "embed"- "io/fs"-)--// uiDist is the built React app from agent/ui/dist. The Makefile / CI must-// run `npm run build` in that folder before `go build`, otherwise the-// embed below fails at compile time. We accept that hard-fail so a release-// can never accidentally ship a stale or empty UI bundle.-//-//go:embed all:dist-var uiDist embed.FS--// distFS returns the embedded UI rooted at the dist/ directory so the HTTP-// server can serve "/" → "dist/index.html" without leaking the dist prefix-// into URLs.-func distFS() (fs.FS, error) {- return fs.Sub(uiDist, "dist")-}diff --git a/agent/internal/agentui/focus_windows.go b/agent/internal/agentui/focus_windows.godeleted file mode 100644index d229894f..00000000--- a/agent/internal/agentui/focus_windows.go+++ /dev/null@@ -1,95 +0,0 @@-//go:build windows--package agentui--import (- "syscall"- "unsafe"-)--// 1.6.1 shipped without explicit show/focus, leaving the host window hidden-// when the wizard was spawned with HideWindow:true (the STARTUPINFO bit-// propagates to child windows on some Windows builds — explicit SW_SHOW in-// the webview library wasn't enough). This file forces visibility from our-// side so 1.6.2 doesn't depend on that race.--const (- swHide = 0- swShow = 5- swRestore = 9- hwndTopmost = ^uintptr(0) // -1- hwndNotopmost = ^uintptr(1) // -2- swpNoMove = 0x0002- swpNoSize = 0x0001- swpShowWindow = 0x0040-)--// hideHostWindow stuffs the WebView2 host out of sight immediately after-// construction so the user never sees the white pre-paint or black-// post-CSS-but-pre-React frames. We re-show via forceForeground once the-// JS bundle reports ready (or a safety timeout fires).-func hideHostWindow(hwnd unsafe.Pointer) {- if hwnd == nil {- return- }- procShowWindow.Call(uintptr(hwnd), swHide)-}--var (- user32 = syscall.NewLazyDLL("user32.dll")- procShowWindow = user32.NewProc("ShowWindow")- procSetForegroundWindow = user32.NewProc("SetForegroundWindow")- procBringWindowToTop = user32.NewProc("BringWindowToTop")- procSetWindowPos = user32.NewProc("SetWindowPos")- procIsIconic = user32.NewProc("IsIconic")- procAttachThreadInput = user32.NewProc("AttachThreadInput")- procGetForegroundWindow = user32.NewProc("GetForegroundWindow")- procGetWindowThreadProc = user32.NewProc("GetWindowThreadProcessId")- kernel32 = syscall.NewLazyDLL("kernel32.dll")- procGetCurrentThreadID = kernel32.NewProc("GetCurrentThreadId")-)--// forceForeground does the dance Windows requires when a non-foreground-// process wants to grab focus: attach to the foreground thread's input-// queue, call SetForegroundWindow + BringWindowToTop, then detach. Without-// the attach step Windows silently demotes the request to a flashing-// taskbar button — exactly the symptom we saw in 1.6.1.-func forceForeground(hwnd unsafe.Pointer) {- if hwnd == nil {- return- }- h := uintptr(hwnd)-- // If minimized, restore first.- if iconic, _, _ := procIsIconic.Call(h); iconic != 0 {- procShowWindow.Call(h, swRestore)- } else {- procShowWindow.Call(h, swShow)- }-- // Topmost-then-not flash forces the window onto Z-top reliably; some- // users reported the window living below the taskbar otherwise.- procSetWindowPos.Call(h, hwndTopmost, 0, 0, 0, 0, swpNoMove|swpNoSize|swpShowWindow)- procSetWindowPos.Call(h, hwndNotopmost, 0, 0, 0, 0, swpNoMove|swpNoSize|swpShowWindow)-- fg, _, _ := procGetForegroundWindow.Call()- if fg == 0 {- procSetForegroundWindow.Call(h)- procBringWindowToTop.Call(h)- return- }-- curThread, _, _ := procGetCurrentThreadID.Call()- var fgPid uint32- fgThread, _, _ := procGetWindowThreadProc.Call(fg, uintptr(unsafe.Pointer(&fgPid)))- if fgThread == 0 || fgThread == curThread {- procSetForegroundWindow.Call(h)- procBringWindowToTop.Call(h)- return- }-- procAttachThreadInput.Call(curThread, fgThread, 1)- procSetForegroundWindow.Call(h)- procBringWindowToTop.Call(h)- procAttachThreadInput.Call(curThread, fgThread, 0)-}diff --git a/agent/internal/agentui/pairer.go b/agent/internal/agentui/pairer.godeleted file mode 100644index 483e140e..00000000--- a/agent/internal/agentui/pairer.go+++ /dev/null@@ -1,384 +0,0 @@-package agentui--import (- "context"- "encoding/json"- "errors"- "net/http"- "os"- "path/filepath"- "strings"- "sync"- "time"-- "github.com/serverkit/agent/internal/agent"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/connstring"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/pairdriver"-)--// pairer adapts the callback-style pairdriver into a polled state machine-// the React wizard can drive over HTTP. The wizard POSTs /local/pair/start-// once with panel URL + server name; from then on it polls-// /local/pair/state every second to render the current stage and react-// to claim / error transitions.-type pairer struct {- log *logger.Logger- configPath string-- mu sync.Mutex- state string // "idle" | "enrolling" | "waiting" | "claimed" | "error"- code string- codeFmt string- pass string- panelURL string- server string- errMsg string- cancel context.CancelFunc-}--func newPairer(log *logger.Logger, configPath string) *pairer {- return &pairer{- log: log.WithComponent("agentui-pair"),- configPath: configPath,- state: "idle",- }-}--// register adds the wizard endpoints to the asset server's mux.-func (p *pairer) register(mux *http.ServeMux) {- mux.HandleFunc("/local/pair/start", p.handleStart)- mux.HandleFunc("/local/pair/state", p.handleState)- mux.HandleFunc("/local/pair/cancel", p.handleCancel)- mux.HandleFunc("/local/pair/connection-string", p.handleConnectionString)-}--type pairStartRequest struct {- PanelURL string `json:"panel_url"`- ServerName string `json:"server_name"`-}--type pairStateResponse struct {- State string `json:"state"`- Code string `json:"code,omitempty"`- CodeFormatted string `json:"code_formatted,omitempty"`- Passphrase string `json:"passphrase,omitempty"`- PanelURL string `json:"panel_url,omitempty"`- ServerName string `json:"server_name,omitempty"`- Error string `json:"error,omitempty"`-}--func (p *pairer) handleStart(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- var req pairStartRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})- return- }- if req.PanelURL == "" {- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "panel_url is required"})- return- }-- pass, err := pairdriver.GeneratePassphrase()- if err != nil {- writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})- return- }-- p.mu.Lock()- if p.cancel != nil {- // Replace any in-flight pairing — typical when the user edits the- // form and re-submits.- p.cancel()- }- ctx, cancel := context.WithCancel(context.Background())- p.cancel = cancel- p.state = "enrolling"- p.errMsg = ""- p.code = ""- p.codeFmt = ""- p.pass = pass- p.panelURL = req.PanelURL- p.server = req.ServerName- p.mu.Unlock()-- cb := pairdriver.Callbacks{- OnEnrolled: func(code, formatted string) {- p.mu.Lock()- p.state = "waiting"- p.code = code- p.codeFmt = formatted- p.mu.Unlock()- },- OnClaimed: func(serverName string) {- p.mu.Lock()- p.state = "claimed"- if serverName != "" {- p.server = serverName- }- p.mu.Unlock()- // After credentials land on disk the running service still has- // the old config in memory — restart it so the new URL/agent_id- // take effect immediately, and verify it actually came up.- // Earlier versions ignored sc start errors silently which is- // why users saw "successfully paired" on a dead service and- // had to start it manually from the CLI.- // Standalone (non-MSI) installs have no ServerKitAgent service- // to restart — the credentials on disk are all the pairing- // produces, and the agent runtime starts separately. Skip the- // restart cleanly in that case instead of surfacing 1060.- if !isServiceInstalled() {- p.log.Info("ServerKitAgent service not installed; skipping post-pair restart (standalone mode)")- } else {- if err := runServiceCmd("stop"); err != nil {- p.log.Info("Service stop reported error (likely already stopped)", "error", err)- }- // sc.exe returns once SCM accepts the stop request, not when the- // service is fully stopped. Issuing sc start while the service is- // still STOP_PENDING fails with 1056 ("instance already running"),- // so wait until SCM reports STOPPED before starting.- if err := waitForServiceStopped(15 * time.Second); err != nil {- p.log.Info("Service did not reach STOPPED before start", "error", err)- }- if err := runServiceCmd("start"); err != nil {- p.log.Error("Failed to start service after pairing", "error", err)- p.mu.Lock()- p.state = "error"- p.errMsg = "Pairing succeeded but the agent service failed to start: " + err.Error() +- "\n\nTry: restart the machine, or open Actions → Restart agent."- p.mu.Unlock()- return- }- }- // sc start returns as soon as the SCM accepts the request, not- // when the service is actually running. Poll for state=RUNNING- // so the wizard's "claimed" stage reflects reality.- if err := waitForServiceRunning(20 * time.Second); err != nil {- p.log.Error("Service did not reach RUNNING after pairing", "error", err)- p.mu.Lock()- p.state = "error"- p.errMsg = "Pairing succeeded but the agent service didn't come up within 20s. " +- "This usually means another agent process is holding port 19780 — " +- "try ending all serverkit-agent.exe processes from Task Manager and reopen the wizard.\n\n" +- "Detail: " + err.Error()- p.mu.Unlock()- return- }- p.log.Info("Agent service running after pair", "server", serverName)- },- OnError: func(err error) {- p.mu.Lock()- // Cancellation isn't a "failure" the UI should surface.- if !errors.Is(err, context.Canceled) {- p.state = "error"- p.errMsg = err.Error()- }- p.mu.Unlock()- },- }-- go pairdriver.Run(ctx, p.log, p.configPath, req.PanelURL, pass, req.ServerName, cb)-- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})-}--func (p *pairer) handleState(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- p.mu.Lock()- resp := pairStateResponse{- State: p.state,- Code: p.code,- CodeFormatted: p.codeFmt,- Passphrase: p.pass,- PanelURL: p.panelURL,- ServerName: p.server,- Error: p.errMsg,- }- p.mu.Unlock()- writeJSON(w, http.StatusOK, resp)-}--func (p *pairer) handleCancel(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- p.mu.Lock()- if p.cancel != nil {- p.cancel()- }- p.state = "idle"- p.code = ""- p.codeFmt = ""- p.pass = ""- p.errMsg = ""- p.mu.Unlock()- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})-}--type connStringRequest struct {- ConnectionString string `json:"connection_string"`-}--// handleConnectionString accepts a single sk1://… connection string,-// decodes it into a panel URL + registration token, and runs the legacy-// /api/v1/servers/register flow against the panel — the same one the-// `serverkit-agent register` CLI uses. We reuse the existing pairer-// state machine ("enrolling" -> "claimed") so the React wizard's polling-// loop doesn't need a separate state for this entry path.-//-// Note: this bypasses the pair-code/passphrase flow entirely. The token-// inside the connection string IS the credential — the panel mints the-// agent's permanent api_key/api_secret server-side once we POST to-// /register, which is exactly what the operator wanted: "one string from-// the panel, one paste in the agent."-func (p *pairer) handleConnectionString(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- var req connStringRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})- return- }- decoded, err := connstring.Decode(req.ConnectionString)- if err != nil {- // Surface decoder errors directly: "unknown version" / "missing- // url or token" are actionable for the user, where as a generic- // "invalid input" wouldn't tell them whether to regenerate or- // upgrade.- writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})- return- }-- panelURL := pairdriver.NormalizePanelURL(decoded.URL)-- // Mark the pairer state machine "in-flight" so the wizard's poll- // loop renders a spinner instead of bouncing back to the form.- p.mu.Lock()- if p.cancel != nil {- p.cancel()- }- ctx, cancel := context.WithCancel(context.Background())- p.cancel = cancel- p.state = "enrolling"- p.errMsg = ""- p.code = ""- p.codeFmt = ""- p.pass = ""- p.panelURL = panelURL- p.server = ""- p.mu.Unlock()-- go p.runConnectionStringFlow(ctx, panelURL, decoded.Token)-- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})-}--// runConnectionStringFlow performs the actual register + persist + service-// restart sequence. Mirrors the OnClaimed path of the pair-code flow so-// the user-visible end state ("agent running, panel reconnected") is-// identical regardless of which entry path they took.-func (p *pairer) runConnectionStringFlow(ctx context.Context, panelURL, token string) {- reg := agent.NewRegistration(p.log)-- result, err := reg.Register(panelURL, token, "")- if err != nil {- p.failConnString("register: " + err.Error())- return- }- if ctx.Err() != nil {- // User clicked Cancel between the network call and the save.- return- }-- if err := saveRegistrationCredentials(p.configPath, panelURL, result); err != nil {- p.failConnString("save credentials: " + err.Error())- return- }-- p.mu.Lock()- p.state = "claimed"- p.server = result.Name- p.mu.Unlock()-- // Same restart-and-verify dance as the pair-code claim path. Earlier- // versions skipped this and left users staring at "successfully- // paired" on a service that never actually picked up the new config.- // Standalone (non-MSI) installs have no service to restart; pairing- // is still complete because the credentials are on disk.- if !isServiceInstalled() {- p.log.Info("ServerKitAgent service not installed; skipping post-pair restart (standalone mode)")- return- }- if err := runServiceCmd("stop"); err != nil {- p.log.Info("Service stop reported error (likely already stopped)", "error", err)- }- // Wait for STOPPED before starting — issuing sc start during- // STOP_PENDING fails with 1056 ("instance already running").- if err := waitForServiceStopped(15 * time.Second); err != nil {- p.log.Info("Service did not reach STOPPED before start", "error", err)- }- if err := runServiceCmd("start"); err != nil {- p.log.Error("Failed to start service after pairing", "error", err)- p.failConnString("Pairing succeeded but the agent service failed to start: " + err.Error() +- "\n\nTry: restart the machine, or open Actions → Restart agent.")- return- }- if err := waitForServiceRunning(20 * time.Second); err != nil {- p.log.Error("Service did not reach RUNNING after pairing", "error", err)- p.failConnString("Pairing succeeded but the agent service didn't come up within 20s. " +- "This usually means another agent process is holding port 19780 — " +- "try ending all serverkit-agent.exe processes from Task Manager and reopen the wizard.\n\n" +- "Detail: " + err.Error())- return- }- p.log.Info("Agent service running after connection-string pair", "server", result.Name)-}--func (p *pairer) failConnString(msg string) {- p.mu.Lock()- p.state = "error"- p.errMsg = msg- p.mu.Unlock()-}--// saveRegistrationCredentials persists the result of a /register call to-// disk in the same shape as pairdriver.saveCredentials does for the-// claim flow. Lives here rather than in registration.go because the CLI-// `register` command does its own (slightly older-shaped) save and we-// don't want to disturb that path.-func saveRegistrationCredentials(configPath, panelURL string, r *agent.RegistrationResult) error {- cfg, err := config.Load(configPath)- if err != nil {- cfg = config.Default()- }- wsURL := strings.TrimSuffix(panelURL, "/")- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)- cfg.Server.URL = wsURL + "/agent"- cfg.Agent.ID = r.AgentID- cfg.Agent.Name = r.Name- cfg.Auth.APIKey = r.APIKey- cfg.Auth.APISecret = r.APISecret-- if configPath == "" {- configPath = config.DefaultConfigPath()- }- if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {- return err- }- if err := cfg.Save(configPath); err != nil {- return err- }- return cfg.SaveCredentials()-}diff --git a/agent/internal/agentui/platform_other.go b/agent/internal/agentui/platform_other.godeleted file mode 100644index efffd4e0..00000000--- a/agent/internal/agentui/platform_other.go+++ /dev/null@@ -1,38 +0,0 @@-//go:build !windows--package agentui--import (- "fmt"- "time"-)--// runServiceCmd is a stub on non-Windows: the console window is Windows-only-// for now, and the platform-specific service controls land alongside the-// cross-platform webview wrapper later.-func runServiceCmd(verb string) error {- return fmt.Errorf("service control not implemented on this platform")-}--func waitForServiceRunning(timeout time.Duration) error {- return fmt.Errorf("service control not implemented on this platform")-}--// isServiceInstalled reports false on non-Windows so the pairing flow skips-// the SCM stop/start dance entirely (there is no service manager to drive;-// systemd integration lands with the cross-platform service controls).-func isServiceInstalled() bool {- return false-}--func waitForServiceStopped(timeout time.Duration) error {- return fmt.Errorf("service control not implemented on this platform")-}--func openTarget(target string) error {- return fmt.Errorf("open not implemented on this platform")-}--func exeForSpawn() (string, error) {- return "", fmt.Errorf("not implemented on this platform")-}diff --git a/agent/internal/agentui/platform_windows.go b/agent/internal/agentui/platform_windows.godeleted file mode 100644index 9d70152d..00000000--- a/agent/internal/agentui/platform_windows.go+++ /dev/null@@ -1,107 +0,0 @@-//go:build windows--package agentui--import (- "fmt"- "os"- "os/exec"- "strings"- "syscall"- "time"-)--// runServiceCmd issues sc.exe verb against ServerKitAgent. The MSI grants-// BUILTIN\Users start/stop/configure rights so this works as the regular-// user with no UAC prompt.-func runServiceCmd(verb string) error {- cmd := exec.Command("sc.exe", verb, "ServerKitAgent")- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- out, err := cmd.CombinedOutput()- if err != nil {- return fmt.Errorf("sc %s: %w (output: %s)", verb, err, string(out))- }- return nil-}--// isServiceInstalled reports whether ServerKitAgent is registered with-// Windows SCM. Used to skip the post-pair stop/start dance when the user-// is running the standalone exe without the MSI install — there's no-// service to control, and `sc start` would fail with error 1060-// ("service does not exist") and surface as a fake pairing failure.-func isServiceInstalled() bool {- cmd := exec.Command("sc.exe", "query", "ServerKitAgent")- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- out, err := cmd.CombinedOutput()- if err == nil {- return true- }- // sc.exe sets exit status 1060 (and prints that code) when the- // service is unknown. Any other error (access denied, SCM down) we- // optimistically treat as "service exists, just couldn't query it"- // — the subsequent stop/start will surface the real problem with- // better context than the query would.- return !strings.Contains(string(out), "1060")-}--// waitForServiceRunning polls `sc query` until the service reports state-// 4 (RUNNING) or the deadline passes. Returns nil when running, or a-// descriptive error including the most recent state output. Used to-// verify the post-pair sc start actually took — otherwise the wizard-// silently shows "claimed" while the service quietly failed to start.-func waitForServiceRunning(timeout time.Duration) error {- deadline := time.Now().Add(timeout)- var lastOut string- for time.Now().Before(deadline) {- cmd := exec.Command("sc.exe", "query", "ServerKitAgent")- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- out, err := cmd.CombinedOutput()- lastOut = string(out)- if err == nil && strings.Contains(lastOut, "RUNNING") {- return nil- }- // STATE = 2 (START_PENDING) and 3 (STOP_PENDING) are transients —- // just wait. STATE = 1 (STOPPED) means the service either died or- // never came up; we'll catch it after the deadline.- time.Sleep(500 * time.Millisecond)- }- return fmt.Errorf("service did not reach RUNNING within %s (last sc query: %s)",- timeout, strings.TrimSpace(lastOut))-}--// waitForServiceStopped polls `sc query` until the service reports state-// 1 (STOPPED) or the deadline passes. `sc stop` returns as soon as SCM-// accepts the stop request — issuing `sc start` while the service is-// still STOP_PENDING returns error 1056 ("instance already running"),-// which is exactly what users hit on the post-pair restart.-func waitForServiceStopped(timeout time.Duration) error {- deadline := time.Now().Add(timeout)- var lastOut string- for time.Now().Before(deadline) {- cmd := exec.Command("sc.exe", "query", "ServerKitAgent")- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- out, err := cmd.CombinedOutput()- lastOut = string(out)- if err == nil && strings.Contains(lastOut, "STOPPED") {- return nil- }- time.Sleep(500 * time.Millisecond)- }- return fmt.Errorf("service did not reach STOPPED within %s (last sc query: %s)",- timeout, strings.TrimSpace(lastOut))-}--// openTarget hands a path or URL to Explorer / the default browser via-// rundll32 + url.dll, which is the canonical "open this thing" entry point-// on Windows. Faster than shelling out to cmd /c start.-func openTarget(target string) error {- cmd := exec.Command("rundll32", "url.dll,FileProtocolHandler", target)- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- return cmd.Start()-}--// exeForSpawn returns the path to the currently running agent binary so the-// wizard re-launch can spawn another instance of the same exe.-func exeForSpawn() (string, error) {- return os.Executable()-}diff --git a/agent/internal/agentui/preflight_other.go b/agent/internal/agentui/preflight_other.godeleted file mode 100644index 3ea019dc..00000000--- a/agent/internal/agentui/preflight_other.go+++ /dev/null@@ -1,6 +0,0 @@-//go:build !windows--package agentui--func detectWebView2() string { return "" }-func preflightWebView2() error { return nil }diff --git a/agent/internal/agentui/preflight_windows.go b/agent/internal/agentui/preflight_windows.godeleted file mode 100644index b0f66dc7..00000000--- a/agent/internal/agentui/preflight_windows.go+++ /dev/null@@ -1,59 +0,0 @@-//go:build windows--package agentui--import (- "fmt"-- "golang.org/x/sys/windows/registry"-)--// WebView2 evergreen runtime registers itself under this UUID. We probe both-// the 32-bit and 64-bit hives plus per-user, mirroring Microsoft's own-// detection guidance. If pv is non-empty we treat the runtime as installed.-//-// https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#detect-if-a-webview2-runtime-is-already-installed-const webview2GUID = `{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}`--// detectWebView2 returns the installed runtime version, or empty string if-// not installed. Errors at the registry layer are folded into "not present"-// — the calling code only needs a yes/no with a version when found.-func detectWebView2() string {- candidates := []struct {- root registry.Key- path string- }{- {registry.LOCAL_MACHINE, `SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\` + webview2GUID},- {registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\EdgeUpdate\Clients\` + webview2GUID},- {registry.CURRENT_USER, `Software\Microsoft\EdgeUpdate\Clients\` + webview2GUID},- }- for _, c := range candidates {- k, err := registry.OpenKey(c.root, c.path, registry.QUERY_VALUE)- if err != nil {- continue- }- v, _, err := k.GetStringValue("pv")- k.Close()- if err == nil && v != "" {- return v- }- }- return ""-}--// preflightWebView2 returns nil when the runtime is present, or an error-// pointing the user at the download URL. We surface this *before* trying-// to construct the webview, because go-webview2's NewWithOptions can-// silently produce a non-nil but non-functional handle in certain-// failure modes — leaving the user with a blank window and no error.-func preflightWebView2() error {- v := detectWebView2()- if v == "" {- return fmt.Errorf(- "WebView2 runtime not installed. " +- "Install the Evergreen Bootstrapper from " +- "https://developer.microsoft.com/microsoft-edge/webview2/ and try again",- )- }- return nil-}diff --git a/agent/internal/agentui/server.go b/agent/internal/agentui/server.godeleted file mode 100644index 560d4d07..00000000--- a/agent/internal/agentui/server.go+++ /dev/null@@ -1,72 +0,0 @@-package agentui--import (- "context"- "fmt"- "net"- "net/http"- "time"-- "github.com/serverkit/agent/internal/logger"-)--// startAssetServer binds an HTTP server to a free 127.0.0.1 port and serves-// the embedded UI bundle from it. WebView2 then navigates to the resulting-// URL — using a real HTTP origin (rather than file:// or a virtual host-// mapping) means relative imports, fetch(), and the dev tools "Network"-// panel all behave the same as when running the dev server, which keeps-// surprises out of the migration. Returns the URL to navigate to and a-// shutdown func that stops the server cleanly.-func startAssetServer(ctx context.Context, log *logger.Logger, configPath string) (url string, shutdown func(), err error) {- dist, err := distFS()- if err != nil {- return "", nil, fmt.Errorf("load embedded ui: %w", err)- }-- // Bind to :0 so the OS hands us an unused port; we don't conflict with- // the agent's IPC server (19780) or any panel running locally.- ln, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- return "", nil, fmt.Errorf("bind asset server: %w", err)- }-- mux := http.NewServeMux()- newLocalActions(configPath).register(mux)- newPairer(log, configPath).register(mux)-- // Wrap the static file server with no-store headers. WebView2 caches- // per-user-data-folder aggressively; on an MSI upgrade the new bundle- // would otherwise be shadowed by the previous index.html for several- // runs. Asset payload is ~600KB total, so loading it fresh each launch- // has no perceptible cost and removes a whole class of stale-asset- // bug reports.- noCache := func(h http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate")- w.Header().Set("Pragma", "no-cache")- w.Header().Set("Expires", "0")- h.ServeHTTP(w, r)- })- }- mux.Handle("/", noCache(http.FileServer(http.FS(dist))))-- srv := &http.Server{- Handler: mux,- ReadHeaderTimeout: 5 * time.Second,- }-- go func() {- _ = srv.Serve(ln)- }()-- addr := ln.Addr().(*net.TCPAddr)- url = fmt.Sprintf("http://127.0.0.1:%d/", addr.Port)-- shutdown = func() {- ctxShut, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- _ = srv.Shutdown(ctxShut)- }-- return url, shutdown, nil-}diff --git a/agent/internal/agentui/window_other.go b/agent/internal/agentui/window_other.godeleted file mode 100644index f8e4a72d..00000000--- a/agent/internal/agentui/window_other.go+++ /dev/null@@ -1,17 +0,0 @@-//go:build !windows--package agentui--import (- "context"- "fmt"-- "github.com/serverkit/agent/internal/logger"-)--// Run is a stub on non-Windows platforms; the WebView2-based console is-// Windows-only for now. macOS / Linux desktop console support arrives once-// the wizard migration is done and we pick a cross-platform webview wrapper.-func Run(_ context.Context, _ *logger.Logger, _ string) error {- return fmt.Errorf("the agent console window is only available on Windows")-}diff --git a/agent/internal/agentui/window_windows.go b/agent/internal/agentui/window_windows.godeleted file mode 100644index 7e657741..00000000--- a/agent/internal/agentui/window_windows.go+++ /dev/null@@ -1,216 +0,0 @@-//go:build windows--package agentui--import (- "context"- "fmt"- "os"- "runtime"- "time"-- webview2 "github.com/jchv/go-webview2"-- "github.com/serverkit/agent/internal/logger"-)--// Run launches the agent's WebView2 console window and blocks until the user-// closes it. configPath is reserved for the upcoming wizard-migration-// milestone — for now the React app loads in console-only mode and the-// existing setupui wizard still owns first-run pairing.-//-// Set SERVERKIT_AGENT_UI_DEV=http://localhost:5174 to point the webview at-// the Vite dev server instead of the embedded bundle. Useful while iterating-// on the UI: changes hot-reload without rebuilding the Go binary.-//-// Set SERVERKIT_AGENT_UI_DEVTOOLS=false to disable DevTools. By default the-// 1.6.2 console ships with DevTools enabled so blank-page reports come with-// a way for the user to press F12 and capture errors.-func Run(ctx context.Context, log *logger.Logger, configPath string) error {- runtime.LockOSThread()-- log.Info("agentui.Run: starting")-- // Preflight: bail with a clear error before constructing the webview.- // Skipping this leads to "blank window" reports when the runtime is- // missing — go-webview2 doesn't always return nil on failure.- if v := detectWebView2(); v == "" {- log.Error("agentui.Run: WebView2 runtime not detected")- return fmt.Errorf(- "WebView2 runtime not installed. " +- "Download the Evergreen Bootstrapper from " +- "https://developer.microsoft.com/microsoft-edge/webview2/ and re-run setup",- )- } else {- log.Info("agentui.Run: WebView2 runtime detected", "version", v)- }-- target := os.Getenv("SERVERKIT_AGENT_UI_DEV")- var stopServer func()- if target == "" {- log.Info("agentui.Run: starting embedded asset server")- url, shutdown, err := startAssetServer(ctx, log, configPath)- if err != nil {- log.Error("agentui.Run: asset server failed", "error", err)- return fmt.Errorf("start asset server: %w", err)- }- log.Info("agentui.Run: asset server up", "url", url)- target = url- stopServer = shutdown- } else {- // Even in dev mode we still need the action/pair endpoints — the- // Vite dev server only serves UI assets. Start the asset server- // alongside it; dev UI fetches the local API by absolute origin.- _, shutdown, err := startAssetServer(ctx, log, configPath)- if err != nil {- return fmt.Errorf("start asset server: %w", err)- }- stopServer = shutdown- log.Info("agentui.Run: using dev server", "url", target)- }- if stopServer != nil {- defer stopServer()- }-- // 1.6.1 reports said: blank white window, no errors. We could not see- // what the React app was doing because the only diagnostic was the Go- // log on the host side. 1.6.2 ships with DevTools enabled by default so- // users can press F12 and screenshot errors. Set the env var to "false"- // to turn it off in installs where security policy prohibits it.- devtools := os.Getenv("SERVERKIT_AGENT_UI_DEVTOOLS") != "false"- log.Info("agentui.Run: constructing WebView2 window", "devtools", devtools)- w := webview2.NewWithOptions(webview2.WebViewOptions{- Debug: devtools,- AutoFocus: true,- WindowOptions: webview2.WindowOptions{- Title: "ServerKit Agent",- // Sidebar is 220px; content area at 1200x800 lands at 980x800- // which gives the Overview metric cards and the Logs/Activity- // timeline room to breathe without horizontal scrollbars.- Width: 1200,- Height: 800,- IconId: 2,- Center: true,- },- })- if w == nil {- log.Error("agentui.Run: webview2.NewWithOptions returned nil")- return fmt.Errorf("webview2 init failed; the runtime may be present but blocked by group policy or AV")- }- defer w.Destroy()-- // Bridge JS console + window errors back to the Go log so 1.6.2 doesn't- // leave us blind on blank-page reports. The page calls these via- // window.agentLog / window.agentNavReady, which Init() wires up below.- if err := w.Bind("agentLog", func(level, msg string) {- switch level {- case "error":- log.Error("ui.js: " + msg)- case "warn":- log.Warn("ui.js: " + msg)- default:- log.Info("ui.js: " + msg)- }- return- }); err != nil {- log.Warn("agentui.Run: Bind agentLog failed", "error", err)- }- navReady := make(chan struct{}, 1)- if err := w.Bind("agentNavReady", func(href string) {- log.Info("ui.js: navigation ready", "href", href)- select {- case navReady <- struct{}{}:- default:- }- return- }); err != nil {- log.Warn("agentui.Run: Bind agentNavReady failed", "error", err)- }-- // Inject a tiny shim *before* the React bundle runs. It forwards every- // console.error / unhandledrejection / window.onerror through agentLog,- // and pings agentNavReady once the document has parsed. This is what- // fills the gap that NavigationCompleted would have filled if the- // upstream library exposed it on the public WebView interface.- w.Init(`- (function() {- var safe = function(fn) { try { fn(); } catch (e) {} };- var send = function(level, msg) {- if (window.agentLog) safe(function(){ window.agentLog(level, String(msg)); });- };- safe(function(){- var origErr = console.error;- console.error = function() {- send('error', Array.prototype.slice.call(arguments).map(String).join(' '));- return origErr.apply(console, arguments);- };- });- window.addEventListener('error', function(ev) {- send('error', (ev.message || 'window.onerror') + ' @ ' + (ev.filename||'?') + ':' + (ev.lineno||0));- });- window.addEventListener('unhandledrejection', function(ev) {- var r = ev && ev.reason;- send('error', 'unhandledrejection: ' + (r && r.message ? r.message : String(r)));- });- var ready = function() {- if (window.agentNavReady) safe(function(){ window.agentNavReady(location.href); });- };- if (document.readyState === 'complete' || document.readyState === 'interactive') {- setTimeout(ready, 0);- } else {- document.addEventListener('DOMContentLoaded', ready);- }- send('info', 'agent shim installed, ua=' + navigator.userAgent);- })();- `)-- w.SetSize(900, 600, webview2.HintMin)-- // Hide the host window immediately so the user never sees WebView2's- // pre-paint white rectangle or the dark-CSS-but-pre-React black gap.- // We re-show in forceForeground once navReady fires (or 3s elapses as- // a safety net for cases where the JS shim never installs).- hideHostWindow(w.Window())-- log.Info("agentui.Run: navigating", "url", target)- w.Navigate(target)-- // Reveal the window the moment the bundle reports ready. The 3s- // fallback is deliberately generous: on cold-start machines, WebView2- // can take ~1.5s to hydrate the first paint, and we'd rather show a- // real (if late) UI than show a flash. The 8s mark logs a louder- // warning so blank-page reports have a clear breadcrumb.- go func() {- select {- case <-navReady:- log.Info("agentui.Run: UI bundle reported ready, showing window")- forceForeground(w.Window())- case <-time.After(3 * time.Second):- log.Warn("agentui.Run: no UI ready signal after 3s; revealing window anyway")- forceForeground(w.Window())- select {- case <-navReady:- log.Info("agentui.Run: UI bundle reported ready (after fallback)")- case <-time.After(5 * time.Second):- log.Warn("agentui.Run: no UI ready signal after 8s; bundle likely failed (right-click → Inspect to debug)")- case <-ctx.Done():- }- case <-ctx.Done():- return- }- }()-- // Hook ctx cancellation to terminate the webview from a background- // goroutine. Run() blocks on the OS message pump, so we need an external- // signal to break it cleanly when the parent process is torn down.- go func() {- <-ctx.Done()- log.Info("agentui.Run: ctx cancelled, terminating webview")- w.Terminate()- }()-- log.Info("agentui.Run: entering message loop (w.Run)")- w.Run()- log.Info("agentui.Run: message loop exited cleanly")- return nil-}diff --git a/agent/internal/auth/auth.go b/agent/internal/auth/auth.godeleted file mode 100644index 8e111b0c..00000000--- a/agent/internal/auth/auth.go+++ /dev/null@@ -1,131 +0,0 @@-package auth--import (- "crypto/hmac"- "crypto/rand"- "crypto/sha256"- "encoding/hex"- "fmt"- "time"-)--// Authenticator handles HMAC-based authentication-type Authenticator struct {- agentID string- apiKey string- apiSecret string-}--// New creates a new Authenticator-func New(agentID, apiKey, apiSecret string) *Authenticator {- return &Authenticator{- agentID: agentID,- apiKey: apiKey,- apiSecret: apiSecret,- }-}--// SignMessage creates an HMAC signature for authentication-// The signature is computed as: HMAC-SHA256(agent_id:timestamp, api_secret)-func (a *Authenticator) SignMessage(timestamp int64) string {- message := fmt.Sprintf("%s:%d", a.agentID, timestamp)- return a.computeHMAC(message)-}--// SignMessageWithNonce creates an HMAC signature including a nonce for replay protection-// The signature is computed as: HMAC-SHA256(agent_id:timestamp:nonce, api_secret)-func (a *Authenticator) SignMessageWithNonce(timestamp int64, nonce string) string {- message := fmt.Sprintf("%s:%d:%s", a.agentID, timestamp, nonce)- return a.computeHMAC(message)-}--// UpdateCredentials updates the API credentials-func (a *Authenticator) UpdateCredentials(apiKey, apiSecret string) {- a.apiKey = apiKey- a.apiSecret = apiSecret-}--// GetAPIKey returns the full API key-func (a *Authenticator) GetAPIKey() string {- return a.apiKey-}--// GetAPISecret returns the API secret-func (a *Authenticator) GetAPISecret() string {- return a.apiSecret-}--// SignCommand creates an HMAC signature for a command-// Used to verify commands weren't tampered with-func (a *Authenticator) SignCommand(commandID string, action string, timestamp int64) string {- message := fmt.Sprintf("%s:%s:%d", commandID, action, timestamp)- return a.computeHMAC(message)-}--// VerifySignature verifies an HMAC signature-func (a *Authenticator) VerifySignature(message, signature string) bool {- expected := a.computeHMAC(message)- return hmac.Equal([]byte(expected), []byte(signature))-}--// VerifyTimestamp checks if a timestamp is within acceptable range-// Prevents replay attacks-func (a *Authenticator) VerifyTimestamp(timestamp int64, maxAgeSeconds int64) bool {- now := time.Now().UnixMilli()- diff := now - timestamp- if diff < 0 {- diff = -diff- }- return diff <= maxAgeSeconds*1000-}--// GetAPIKeyPrefix returns the first 12 characters of the API key for-// server-side identification. Must match the panel's storage width-// (backend/app/models/server.py: api_key_prefix = api_key[:12]) — the-// panel does direct string equality, so any drift between the two-// sides 401s every auth attempt. Was 8 here historically, which is a-// dormant bug only exposed once the polling fallback transport made-// auth failures visible (WS would just retry silently forever).-func (a *Authenticator) GetAPIKeyPrefix() string {- if len(a.apiKey) < 12 {- return a.apiKey- }- return a.apiKey[:12]-}--// AgentID returns the agent ID-func (a *Authenticator) AgentID() string {- return a.agentID-}--func (a *Authenticator) computeHMAC(message string) string {- h := hmac.New(sha256.New, []byte(a.apiSecret))- h.Write([]byte(message))- return hex.EncodeToString(h.Sum(nil))-}--// GenerateNonce generates a cryptographically random nonce for request uniqueness-func GenerateNonce() string {- b := make([]byte, 16)- if _, err := rand.Read(b); err != nil {- // Fallback to time-based if random fails- return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().UnixMilli())- }- return hex.EncodeToString(b)-}--// SessionToken represents an authenticated session-type SessionToken struct {- Token string- ExpiresAt time.Time-}--// IsExpired checks if the session token has expired-func (s *SessionToken) IsExpired() bool {- return time.Now().After(s.ExpiresAt)-}--// IsExpiringSoon checks if the token expires within the given duration-func (s *SessionToken) IsExpiringSoon(within time.Duration) bool {- return time.Now().Add(within).After(s.ExpiresAt)-}diff --git a/agent/internal/capabilities/capabilities.go b/agent/internal/capabilities/capabilities.godeleted file mode 100644index 755f73eb..00000000--- a/agent/internal/capabilities/capabilities.go+++ /dev/null@@ -1,350 +0,0 @@-// Package capabilities probes the host for which feature surfaces the-// agent can manage (cron, docker, systemd, nginx, …). The result is a-// flat map[string]bool the agent ships to the panel on connect; the-// panel uses it to gate per-feature target pickers.-//-// Probes are cheap (PATH lookups + a couple of file/socket checks) and-// run once per agent process at startup. Results are cached for the-// process lifetime — re-probing is a future concern (e.g. SIGHUP, an-// explicit panel-issued "recapability" command).-package capabilities--import (- "context"- "os"- "os/exec"- "path/filepath"- "regexp"- "runtime"- "strings"- "sync"-- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/pkg/protocol"- gopsutilhost "github.com/shirou/gopsutil/v3/host"-)--// Probe runs all known capability probes and returns the result. log is-// optional — used to record what the probe found, mostly for ops-// debugging when an agent unexpectedly fails to expose a feature.-//-// dockerAvailable is passed in by the agent because it has already-// dialled the docker socket during startup; re-probing here would just-// duplicate that work.-//-// fileAccess + allowedPaths come from agent config (Features.FileAccess /-// Security.AllowedPaths). Surfacing them here lets the panel hide-// remote-file features on agents that have file access disabled, and-// show the user which roots they can browse instead of guessing.-func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAccess bool, allowedPaths []string) protocol.CapabilitiesMessage {- caps := protocol.Capabilities{}-- // Docker — the agent's own client is the source of truth. If the- // agent couldn't dial dockerd, nothing this layer probes will fix- // it.- caps["docker"] = dockerAvailable-- // File access — exposed via the Features.FileAccess config bit.- // The agent already gates file:* handler registration on this; we- // advertise it so the panel can hide the file manager target picker- // for agents where it's off (and Phase 3+ verbs that depend on it).- caps["files"] = fileAccess && len(allowedPaths) > 0-- // Linux service surfaces. On non-Linux these stay false; the- // panel's UI is already conditional on them.- caps["cron"] = probeCron()- caps["systemd"] = probeSystemd()- caps["nginx"] = probeNginx()- caps["php_fpm"] = probePHPFPM()- caps["packages"] = probePackageManager()-- // Cloudflared — present if the binary is on PATH. The panel uses- // this to decide whether to show the Cloudflare Tunnels tab; it- // doesn't imply the user has authenticated yet (cert.pem check- // happens in the cloudflared:status action).- caps["cloudflared"] = probeCloudflared()-- // WireGuard — the agent can manage a tunnel interface: kernel WG on- // Linux (`wg` + `ip`), userspace wireguard-go on Windows/macOS. The- // panel gates the Remote Access / tunnel flow on this.- caps["wireguard"] = probeWireguard()-- // Firewall — a supported host firewall is present so the broker can- // open the edge's WireGuard UDP port (#10). Linux-only.- caps["firewall"] = probeFirewall()-- // Language runtimes — best-effort version probes. A missing key- // means "not installed"; an empty string means "installed but- // `--version` parse failed" so the panel can still light up the- // runtime indicator without claiming a wrong version.- runtimes := probeRuntimes(ctx)-- // Platform / distro for any code that needs more than the booleans- // (e.g. "use apt vs dnf" — Phase 4 territory, but we capture it- // now so we don't have to add another roundtrip later).- platform := runtime.GOOS- distro := ""- distroVer := ""- if info, err := gopsutilhost.InfoWithContext(ctx); err == nil {- // gopsutil reports "ubuntu", "debian", "centos", etc. on Linux;- // "windows", "darwin" on those platforms — we don't need it- // there.- distro = info.Platform- distroVer = info.PlatformVersion- }-- if log != nil {- log.Info("Capability probe complete",- "platform", platform,- "distro", distro,- "docker", caps["docker"],- "cron", caps["cron"],- "systemd", caps["systemd"],- "nginx", caps["nginx"],- "php_fpm", caps["php_fpm"],- "packages", caps["packages"],- "cloudflared", caps["cloudflared"],- "wireguard", caps["wireguard"],- "firewall", caps["firewall"],- "runtimes", runtimes,- )- }-- // Only forward allowed_paths when files capability is true — saves- // the panel from having to defensively check both fields.- var advertisedPaths []string- if caps["files"] {- advertisedPaths = append(advertisedPaths, allowedPaths...)- }-- return protocol.CapabilitiesMessage{- Capabilities: caps,- Platform: platform,- Distro: distro,- DistroVersion: distroVer,- Runtimes: runtimes,- AllowedPaths: advertisedPaths,- }-}--// probeCloudflared — true if cloudflared is on PATH. The capability-// flips to true at install time, well before the user has logged in-// (cloudflared tunnel login). The auth state is exposed separately by-// the cloudflared:status action so the UI can show "binary installed,-// not authenticated" without having to teach the panel about-// /etc/cloudflared/cert.pem locations.-func probeCloudflared() bool {- return hasOnPath("cloudflared")-}--// probeWireguard — whether the agent can manage a WireGuard interface.-// On Linux that needs the kernel tools (`wg` + `ip`); on Windows/macOS-// the userspace wireguard-go backend (roadmap #6) is always available.-func probeWireguard() bool {- if runtime.GOOS == "linux" {- return hasOnPath("wg") && hasOnPath("ip")- }- return true-}--// probeFirewall — true on Linux when a supported host firewall-// (ufw / firewalld / iptables) is on PATH, so the tunnel broker can open-// the edge's WireGuard UDP port (#10).-func probeFirewall() bool {- if runtime.GOOS != "linux" {- return false- }- return hasOnPath("ufw") || hasOnPath("firewall-cmd") || hasOnPath("iptables")-}--// probeRuntimes detects common language runtimes by shelling out to-// each "<bin> --version" and parsing the first line. Versions are kept-// as raw strings (e.g. "3.11.4", "20.10.0", "8.2.0") so consumers can-// do their own semver compares without us guessing the schema.-//-// Per-binary timeout is short — every probe is bounded so a hung-// subprocess can't block the agent from connecting.-func probeRuntimes(ctx context.Context) map[string]string {- results := map[string]string{}- probes := []struct {- key string- bins []string // try in order; first match wins- }{- {key: "python", bins: []string{"python3", "python"}},- {key: "node", bins: []string{"node", "nodejs"}},- {key: "php", bins: []string{"php"}},- {key: "go", bins: []string{"go"}},- {key: "ruby", bins: []string{"ruby"}},- {key: "java", bins: []string{"java"}},- }- for _, p := range probes {- for _, bin := range p.bins {- if !hasOnPath(bin) {- continue- }- ver := readVersion(ctx, bin)- results[p.key] = ver- break // don't keep trying once we found one- }- }- return results-}--// versionPattern grabs the first dotted-number sequence in a version-// string. Works across the messy outputs:-// - python: "Python 3.11.4"-// - node: "v20.10.0"-// - php: "PHP 8.2.0 (cli) ..."-// - go: "go version go1.22.0 linux/amd64"-// - ruby: "ruby 3.2.2p53 ..."-// - java: "openjdk version \"17.0.6\" 2023-01-17"-var versionPattern = regexp.MustCompile(`(\d+\.\d+(?:\.\d+)?)`)--func readVersion(ctx context.Context, bin string) string {- // Each runtime has its own way to print version. Try a small- // allow-list of forms in order; the first non-empty wins.- // --version: python, node, php, ruby- // -version: java (legacy)- // version: go (subcommand, NOT a flag)- candidates := [][]string{{"--version"}, {"-version"}, {"version"}}- // Special-case go up front so we don't waste two failed forks on- // hosts where probing this matters.- base := strings.ToLower(filepathBase(bin))- if base == "go" || base == "go.exe" {- candidates = [][]string{{"version"}, {"--version"}}- }- var out []byte- for _, args := range candidates {- cmd := exec.CommandContext(ctx, bin, args...)- o, err := cmd.CombinedOutput()- if err == nil && len(o) > 0 {- out = o- break- }- }- if len(out) == 0 {- return ""- }- first := strings.SplitN(strings.TrimSpace(string(out)), "\n", 2)[0]- if m := versionPattern.FindString(first); m != "" {- return m- }- // Fall through with the raw first line so the panel at least shows- // something rather than a blank.- return first-}--// filepathBase mirrors filepath.Base without pulling the import — this-// file already has plenty.-func filepathBase(p string) string {- p = strings.ReplaceAll(p, "\\", "/")- if i := strings.LastIndex(p, "/"); i >= 0 {- p = p[i+1:]- }- return p-}--// probeCron — present if `crontab` is on PATH OR a cron daemon is-// installed (we don't require it to be running; the panel can start it).-func probeCron() bool {- if runtime.GOOS != "linux" {- return false- }- if hasOnPath("crontab") {- return true- }- // On systemd hosts that only expose the timer subsystem, crontab- // may be missing but cron.d is still useful. Treat presence of- // /etc/cron.d as the fallback signal.- if _, err := os.Stat("/etc/cron.d"); err == nil {- return true- }- return false-}--// probeSystemd — systemctl on PATH and the system bus is reachable.-// On a container without systemd, systemctl is sometimes installed as a-// shim that fails with "Failed to connect to bus", so we additionally-// check for /run/systemd/system which is the canonical "systemd is PID 1-// here" marker.-func probeSystemd() bool {- if runtime.GOOS != "linux" {- return false- }- if !hasOnPath("systemctl") {- return false- }- if _, err := os.Stat("/run/systemd/system"); err == nil {- return true- }- return false-}--func probeNginx() bool {- if runtime.GOOS != "linux" {- return false- }- return hasOnPath("nginx")-}--func probePHPFPM() bool {- if runtime.GOOS != "linux" {- return false- }- // PHP-FPM is shipped per-version on Debian/Ubuntu (php-fpm,- // php8.1-fpm, php8.2-fpm, …). hasOnPath only catches the bare- // name, so glob the common install dirs as a fallback.- if hasOnPath("php-fpm") {- return true- }- for _, pat := range []string{- "/usr/sbin/php*-fpm*",- "/usr/local/sbin/php*-fpm*",- } {- if matches, _ := filepath.Glob(pat); len(matches) > 0 {- return true- }- }- return false-}--// probePackageManager — true if any of the recognized managers (apt,-// dnf, yum, apk, pacman, zypper) is on PATH. Phase 0 only needs-// "package management is possible from here"; identifying which manager-// goes in the system_info / capabilities Distro field above.-func probePackageManager() bool {- if runtime.GOOS != "linux" {- return false- }- for _, mgr := range []string{"apt-get", "apt", "dnf", "yum", "apk", "pacman", "zypper"} {- if hasOnPath(mgr) {- return true- }- }- return false-}--// hasOnPath checks whether a binary is reachable via $PATH. Cached to-// avoid hammering the filesystem on agents that re-probe via SIGHUP.-func hasOnPath(name string) bool {- if v, ok := pathCache.Load(name); ok {- return v.(bool)- }- _, err := exec.LookPath(name)- ok := err == nil- pathCache.Store(name, ok)- return ok-}--var pathCache sync.Map--// ClearPathCache empties the binary-on-PATH cache. Called by agent:-// recapabilities so a binary that was installed since the last probe-// (e.g. the user just ran apt install nginx) is detected fresh-// instead of returning the stale "not found" result.-func ClearPathCache() {- pathCache.Range(func(k, _ interface{}) bool {- pathCache.Delete(k)- return true- })-}diff --git a/agent/internal/cloudflared/cloudflared.go b/agent/internal/cloudflared/cloudflared.godeleted file mode 100644index c56345c3..00000000--- a/agent/internal/cloudflared/cloudflared.go+++ /dev/null@@ -1,106 +0,0 @@-// Package cloudflared manages Cloudflare named tunnels via the-// cloudflared CLI. Linux-only.-//-// Auth model (approach A):-//-// The user runs `cloudflared tunnel login` once per host. That writes-// ~/.cloudflared/cert.pem (or /etc/cloudflared/cert.pem when run as-// root). The cert is the long-lived "I'm allowed to manage tunnels-// for account X" credential. We never see, copy, or store the user's-// Cloudflare API token; the panel only ever shells out to-// `cloudflared` and trusts whatever auth the binary already has.-//-// Status() reports two flags:-// - Available: cloudflared is on PATH-// - Authenticated: cert.pem is present in one of the standard-// locations-//-// The panel uses both: the tab is gated on `capabilities.cloudflared`-// (binary installed, set by capabilities.Probe at agent startup) and-// the tab body shows an "authenticate first" affordance when-// Authenticated=false.-//-// Tunnel lifecycle:-//-// 1. Create: `cloudflared tunnel create <name>`-// (writes <UUID>.json credentials file)-// 2. Route: `cloudflared tunnel route dns <name|UUID> <hostname>`-// (creates a Cloudflare DNS record pointing the-// hostname at the tunnel — *the* useful action)-// 3. Run: out of scope here; the operator wires up-// `cloudflared tunnel run <name>` as a systemd service-// with a config.yml ingress mapping. Future iteration.-// 4. Delete: `cloudflared tunnel delete <name|UUID>`-package cloudflared--import (- "context"- "os/exec"-)--// Status reports usability and auth state.-type Status struct {- Available bool `json:"available"` // binary installed- Authenticated bool `json:"authenticated"` // cert.pem present- CertPath string `json:"cert_path,omitempty"` // detected cert.pem path, if any- Reason string `json:"reason,omitempty"` // explanation when Available=false- LoginHint string `json:"login_hint,omitempty"` // canned "run this command" when Authenticated=false- Version string `json:"version,omitempty"` // cloudflared --version line, best-effort-}--// Tunnel mirrors `cloudflared tunnel list --output json` rows.-type Tunnel struct {- ID string `json:"id"`- Name string `json:"name"`- CreatedAt string `json:"created_at,omitempty"`- Connections []string `json:"connections,omitempty"`-}--// CreateRequest creates a new named tunnel.-type CreateRequest struct {- Name string `json:"name"`-}--// RouteRequest binds a hostname to an existing tunnel via Cloudflare-// DNS. TunnelRef can be the tunnel name or UUID — cloudflared accepts-// either.-type RouteRequest struct {- TunnelRef string `json:"tunnel_ref"`- Hostname string `json:"hostname"`-}--// LoginEvent is emitted while a `cloudflared tunnel login` flow is in-// flight. AuthURL is the OAuth URL the user must open in a browser-// to authorise the agent host with their Cloudflare account; cert.pem-// is written by cloudflared once the OAuth round-trips.-type LoginEvent struct {- AuthURL string `json:"auth_url,omitempty"`- Line string `json:"line,omitempty"`- Done bool `json:"done,omitempty"`- CertPath string `json:"cert_path,omitempty"`- Error string `json:"error,omitempty"`-}--// Manager is the platform-agnostic interface; the Linux build wires-// it up with real exec calls, non-Linux builds return "unsupported."-type Manager interface {- Status(ctx context.Context) (*Status, error)- List(ctx context.Context) ([]Tunnel, error)- Create(ctx context.Context, req CreateRequest) (*Tunnel, error)- Route(ctx context.Context, req RouteRequest) error- Delete(ctx context.Context, ref string) error- // Login starts `cloudflared tunnel login` and streams events on- // the returned channel. The first event carries the auth URL; the- // channel closes when cert.pem is written (Done=true) or the- // underlying process errors out.- Login(ctx context.Context) (<-chan LoginEvent, error)-}--// hasCloudflared is shared between the Linux backend and tests.-func hasCloudflared() (string, bool) {- p, err := exec.LookPath("cloudflared")- if err != nil {- return "", false- }- return p, true-}diff --git a/agent/internal/cloudflared/cloudflared_linux.go b/agent/internal/cloudflared/cloudflared_linux.godeleted file mode 100644index 844f2594..00000000--- a/agent/internal/cloudflared/cloudflared_linux.go+++ /dev/null@@ -1,302 +0,0 @@-//go:build linux--package cloudflared--import (- "bufio"- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "os"- "os/exec"- "path/filepath"- "regexp"- "strings"- "time"-)--// New returns a Linux Manager that drives `cloudflared`.-func New() Manager { return &linuxManager{} }--type linuxManager struct{}--// validNameRegex constrains tunnel names to characters that won't-// trip cloudflared or shell escaping. Matches the cloudflared docs:-// up to 32 chars, alphanumeric + dash + underscore.-var validNameRegex = regexp.MustCompile(`^[A-Za-z0-9_\-]{1,32}$`)--// validHostnameRegex is a permissive FQDN check — no protocol, no-// path, no spaces. Cloudflare itself does the authoritative check.-var validHostnameRegex = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?)+$`)--// certSearchPaths covers the two install patterns: the user ran-// `cloudflared tunnel login` as a regular user (~/.cloudflared) or as-// root / via the official install (/etc/cloudflared).-func certSearchPaths() []string {- paths := []string{"/etc/cloudflared/cert.pem"}- if home, err := os.UserHomeDir(); err == nil {- paths = append(paths, filepath.Join(home, ".cloudflared", "cert.pem"))- }- return paths-}--func findCert() (string, bool) {- for _, p := range certSearchPaths() {- if _, err := os.Stat(p); err == nil {- return p, true- }- }- return "", false-}--func (l *linuxManager) Status(ctx context.Context) (*Status, error) {- binPath, ok := hasCloudflared()- if !ok {- return &Status{- Available: false,- Reason: "cloudflared not installed on host",- LoginHint: "Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/",- }, nil- }-- cert, authed := findCert()-- // Best-effort version probe — failure is non-fatal, we still- // report Available=true based on PATH.- verCmd := exec.CommandContext(ctx, binPath, "--version")- verOut, _ := verCmd.Output()- version := strings.TrimSpace(strings.SplitN(string(verOut), "\n", 2)[0])-- st := &Status{- Available: true,- Authenticated: authed,- CertPath: cert,- Version: version,- }- if !authed {- st.LoginHint = "Run on the server: sudo cloudflared tunnel login"- }- return st, nil-}--// runTunnel runs `cloudflared tunnel <args>` and returns-// (stdout, error). Errors include the full stderr because the user-// will likely see them in the panel UI when something goes wrong.-func (l *linuxManager) runTunnel(ctx context.Context, args ...string) ([]byte, error) {- args = append([]string{"tunnel"}, args...)- cmd := exec.CommandContext(ctx, "cloudflared", args...)- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr- if err := cmd.Run(); err != nil {- return nil, fmt.Errorf("cloudflared %s: %w (%s)",- strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))- }- return stdout.Bytes(), nil-}--func (l *linuxManager) List(ctx context.Context) ([]Tunnel, error) {- out, err := l.runTunnel(ctx, "list", "--output", "json")- if err != nil {- return nil, err- }-- // cloudflared prints `[]` (sometimes with trailing whitespace) when- // no tunnels exist; json.Unmarshal handles both. Tunnel rows have- // more fields than we surface — we cherry-pick id, name,- // created_at, connections.- var raw []struct {- ID string `json:"id"`- Name string `json:"name"`- CreatedAt string `json:"created_at"`- Connections []map[string]interface{} `json:"connections"`- }- if err := json.Unmarshal(bytes.TrimSpace(out), &raw); err != nil {- return nil, fmt.Errorf("parse tunnel list: %w", err)- }-- out2 := make([]Tunnel, 0, len(raw))- for _, r := range raw {- conns := make([]string, 0, len(r.Connections))- for _, c := range r.Connections {- if origin, ok := c["origin_ip"].(string); ok && origin != "" {- conns = append(conns, origin)- }- }- out2 = append(out2, Tunnel{- ID: r.ID, Name: r.Name, CreatedAt: r.CreatedAt, Connections: conns,- })- }- return out2, nil-}--func (l *linuxManager) Create(ctx context.Context, req CreateRequest) (*Tunnel, error) {- if !validNameRegex.MatchString(req.Name) {- return nil, fmt.Errorf("invalid tunnel name (alphanumeric, -, _, max 32 chars)")- }- // `cloudflared tunnel create <name>` prints something like:- // Created tunnel <name> with id <UUID>- // Newer versions also have --output json on create; we parse the- // stdout text to be portable across versions.- out, err := l.runTunnel(ctx, "create", req.Name)- if err != nil {- return nil, err- }- // Look up by name afterwards so we have the full Tunnel record- // (the create stdout is informational, not structured JSON across- // all cloudflared versions).- _ = out- tunnels, err := l.List(ctx)- if err != nil {- return nil, err- }- for _, t := range tunnels {- if t.Name == req.Name {- return &t, nil- }- }- return nil, fmt.Errorf("tunnel created but not found in list")-}--func (l *linuxManager) Route(ctx context.Context, req RouteRequest) error {- if req.TunnelRef == "" {- return fmt.Errorf("tunnel_ref is required")- }- if !validHostnameRegex.MatchString(req.Hostname) {- return fmt.Errorf("invalid hostname")- }- // `cloudflared tunnel route dns <tunnel> <hostname>` creates the- // CNAME in Cloudflare DNS.- _, err := l.runTunnel(ctx, "route", "dns", req.TunnelRef, req.Hostname)- return err-}--// loginURLRegex matches the `https://dash.cloudflare.com/argotunnel?...`-// URL cloudflared prints to stdout during `tunnel login`. The exact-// text varies by version ("Please open the following URL", "Please-// visit", etc.), so we match the URL itself rather than the prompt.-var loginURLRegex = regexp.MustCompile(`https://dash\.cloudflare\.com/argotunnel\?\S+`)--// Login spawns `cloudflared tunnel login` and streams a typed event-// channel. The first event after the URL is found carries AuthURL;-// the channel closes (with a final Done event) when cert.pem appears-// or the process exits / 15-minute hard ceiling fires.-//-// We can't just look at process exit because cloudflared sometimes-// prints the URL and exits cleanly while waiting on the OAuth callback-// in a separate flow. The cert.pem watcher is the source of truth.-func (l *linuxManager) Login(ctx context.Context) (<-chan LoginEvent, error) {- if _, ok := hasCloudflared(); !ok {- return nil, fmt.Errorf("cloudflared not installed")- }- // If cert.pem already exists, short-circuit — login would- // overwrite, which surprises the user.- if cert, ok := findCert(); ok {- out := make(chan LoginEvent, 1)- out <- LoginEvent{Done: true, CertPath: cert, Line: "already authenticated"}- close(out)- return out, nil- }-- out := make(chan LoginEvent, 8)-- // 15-minute ceiling on the login flow — long enough for a coffee- // break, short enough to garbage-collect a forgotten browser tab.- cctx, cancel := context.WithTimeout(ctx, 15*time.Minute)-- cmd := exec.CommandContext(cctx, "cloudflared", "tunnel", "login")- stdout, err := cmd.StdoutPipe()- if err != nil {- cancel()- return nil, fmt.Errorf("stdout pipe: %w", err)- }- stderr, err := cmd.StderrPipe()- if err != nil {- cancel()- return nil, fmt.Errorf("stderr pipe: %w", err)- }- if err := cmd.Start(); err != nil {- cancel()- return nil, fmt.Errorf("start cloudflared: %w", err)- }-- go func() {- defer cancel()- defer close(out)-- // Tee stdout + stderr into a single line stream. cloudflared- // has historically printed the auth URL on stderr (older- // versions) and stdout (newer), so listen to both.- lines := make(chan string, 32)- go scanLines(stdout, lines)- go scanLines(stderr, lines)-- urlSent := false- // Best-effort cert.pem watcher running in parallel. cloudflared- // itself exits as soon as the cert is fetched on success, but- // the watcher is the more reliable signal in case of weird- // stdout buffering.- certCheck := time.NewTicker(2 * time.Second)- defer certCheck.Stop()-- // Drain pipes + watch cert in the same select loop.- for {- select {- case <-cctx.Done():- out <- LoginEvent{Done: true, Error: "login timed out"}- _ = cmd.Process.Kill()- return- case line, ok := <-lines:- if !ok {- // pipes closed — wait for cmd to reap and emit final.- _ = cmd.Wait()- if cert, ok := findCert(); ok {- out <- LoginEvent{Done: true, CertPath: cert}- } else {- out <- LoginEvent{Done: true, Error: "cloudflared exited without writing cert.pem"}- }- return- }- if !urlSent {- if u := loginURLRegex.FindString(line); u != "" {- urlSent = true- out <- LoginEvent{AuthURL: u, Line: line}- continue- }- }- out <- LoginEvent{Line: line}- case <-certCheck.C:- if cert, ok := findCert(); ok {- out <- LoginEvent{Done: true, CertPath: cert}- _ = cmd.Process.Kill()- return- }- }- }- }()- return out, nil-}--// scanLines pumps r line-by-line into out. Closes out when r is-// exhausted; multiple producers are fine because the consumer treats-// a single closed channel as "all done."-func scanLines(r io.ReadCloser, out chan<- string) {- defer r.Close()- sc := bufio.NewScanner(r)- sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)- for sc.Scan() {- out <- sc.Text()- }-}--func (l *linuxManager) Delete(ctx context.Context, ref string) error {- if ref == "" {- return fmt.Errorf("ref is required")- }- // -f forces deletion when the tunnel still has active connections;- // safer default for a panel-driven flow.- _, err := l.runTunnel(ctx, "delete", "-f", ref)- return err-}diff --git a/agent/internal/cloudflared/cloudflared_other.go b/agent/internal/cloudflared/cloudflared_other.godeleted file mode 100644index 2bb1b071..00000000--- a/agent/internal/cloudflared/cloudflared_other.go+++ /dev/null@@ -1,28 +0,0 @@-//go:build !linux--package cloudflared--import (- "context"- "fmt"-)--// New returns a stub Manager on non-Linux platforms.-func New() Manager { return stubManager{} }--type stubManager struct{}--var errUnsupported = fmt.Errorf("cloudflared is only supported on Linux agents")--func (stubManager) Status(ctx context.Context) (*Status, error) {- return &Status{Available: false, Reason: "cloudflared is only supported on Linux agents"}, nil-}-func (stubManager) List(ctx context.Context) ([]Tunnel, error) { return nil, errUnsupported }-func (stubManager) Create(ctx context.Context, _ CreateRequest) (*Tunnel, error) {- return nil, errUnsupported-}-func (stubManager) Route(ctx context.Context, _ RouteRequest) error { return errUnsupported }-func (stubManager) Delete(ctx context.Context, _ string) error { return errUnsupported }-func (stubManager) Login(ctx context.Context) (<-chan LoginEvent, error) {- return nil, errUnsupported-}diff --git a/agent/internal/config/config.go b/agent/internal/config/config.godeleted file mode 100644index 5095bd89..00000000--- a/agent/internal/config/config.go+++ /dev/null@@ -1,520 +0,0 @@-package config--import (- "crypto/aes"- "crypto/cipher"- "crypto/rand"- "crypto/sha256"- "encoding/base64"- "fmt"- "io"- "os"- "path/filepath"- "runtime"- "time"-- "gopkg.in/yaml.v3"-)--// Config holds all agent configuration-type Config struct {- Server ServerConfig `yaml:"server"`- Agent AgentConfig `yaml:"agent"`- Auth AuthConfig `yaml:"auth"`- Features FeaturesConfig `yaml:"features"`- Metrics MetricsConfig `yaml:"metrics"`- Docker DockerConfig `yaml:"docker"`- Security SecurityConfig `yaml:"security"`- Logging LoggingConfig `yaml:"logging"`- Update UpdateConfig `yaml:"update"`- IPC IPCConfig `yaml:"ipc"`-}--// ServerConfig holds connection settings-type ServerConfig struct {- URL string `yaml:"url"`- ReconnectInterval time.Duration `yaml:"reconnect_interval"`- MaxReconnectInterval time.Duration `yaml:"max_reconnect_interval"`- PingInterval time.Duration `yaml:"ping_interval"`- InsecureSkipVerify bool `yaml:"insecure_skip_verify"` // For dev only-}--// AgentConfig holds agent identity-type AgentConfig struct {- ID string `yaml:"id"`- Name string `yaml:"name"`-}--// AuthConfig holds authentication credentials-type AuthConfig struct {- KeyFile string `yaml:"key_file"`- APIKey string `yaml:"api_key,omitempty"` // Not saved to config file- APISecret string `yaml:"api_secret,omitempty"` // Not saved to config file- // LoadError is populated by Load() when LoadCredentials() failed.- // Surfaced in agent startup logs so "service runs but every /connect- // returns 400 missing fields" reports become trivial to diagnose- // (means the key file couldn't be decrypted under any known key).- LoadError string `yaml:"-"`-}--// FeaturesConfig controls enabled features-type FeaturesConfig struct {- Docker bool `yaml:"docker"`- Metrics bool `yaml:"metrics"`- Logs bool `yaml:"logs"`- FileAccess bool `yaml:"file_access"`- Exec bool `yaml:"exec"`-}--// MetricsConfig controls metrics collection-type MetricsConfig struct {- Enabled bool `yaml:"enabled"`- Interval time.Duration `yaml:"interval"`- IncludePerCPU bool `yaml:"include_per_cpu"`- IncludeDockerStats bool `yaml:"include_docker_stats"`-}--// DockerConfig holds Docker connection settings-type DockerConfig struct {- Socket string `yaml:"socket"`- Timeout time.Duration `yaml:"timeout"`-}--// SecurityConfig holds security settings-type SecurityConfig struct {- AllowedPaths []string `yaml:"allowed_paths"`- BlockedCommands []string `yaml:"blocked_commands"`- MaxExecTimeout time.Duration `yaml:"max_exec_timeout"`-}--// LoggingConfig holds logging settings-type LoggingConfig struct {- Level string `yaml:"level"`- File string `yaml:"file"`- MaxSize int `yaml:"max_size_mb"`- MaxBackups int `yaml:"max_backups"`- MaxAge int `yaml:"max_age_days"`- Compress bool `yaml:"compress"`-}--// UpdateConfig holds auto-update settings-type UpdateConfig struct {- Enabled bool `yaml:"enabled"`- CheckInterval time.Duration `yaml:"check_interval"`- AutoInstall bool `yaml:"auto_install"`-}--// IPCConfig holds local IPC server settings for tray app communication-type IPCConfig struct {- Enabled bool `yaml:"enabled"`- Port int `yaml:"port"`- Address string `yaml:"address"`-}--// Default returns default configuration-func Default() *Config {- return &Config{- Server: ServerConfig{- ReconnectInterval: 5 * time.Second,- MaxReconnectInterval: 5 * time.Minute,- PingInterval: 30 * time.Second,- },- Agent: AgentConfig{},- Auth: AuthConfig{- KeyFile: defaultKeyPath(),- },- Features: FeaturesConfig{- Docker: true,- Metrics: true,- Logs: true,- FileAccess: true,- Exec: false,- },- Metrics: MetricsConfig{- Enabled: true,- Interval: 10 * time.Second,- IncludePerCPU: true,- IncludeDockerStats: true,- },- Docker: DockerConfig{- Socket: defaultDockerSocket(),- Timeout: 30 * time.Second,- },- Security: SecurityConfig{- AllowedPaths: defaultAllowedPaths(),- BlockedCommands: []string{},- MaxExecTimeout: 5 * time.Minute,- },- Logging: LoggingConfig{- Level: "info",- File: defaultLogPath(),- MaxSize: 100,- MaxBackups: 5,- MaxAge: 30,- Compress: true,- },- Update: UpdateConfig{- Enabled: true,- CheckInterval: 1 * time.Hour,- AutoInstall: false, // Require manual confirmation by default- },- IPC: IPCConfig{- Enabled: true,- Port: 19780,- Address: "127.0.0.1",- },- }-}--// Load loads configuration from file-func Load(path string) (*Config, error) {- if path == "" {- path = DefaultConfigPath()- }-- data, err := os.ReadFile(path)- if err != nil {- if os.IsNotExist(err) {- return nil, fmt.Errorf("config file not found: %s", path)- }- return nil, fmt.Errorf("failed to read config: %w", err)- }-- cfg := Default()- if err := yaml.Unmarshal(data, cfg); err != nil {- return nil, fmt.Errorf("failed to parse config: %w", err)- }-- // Load credentials from secure storage. We don't fail loading the- // config if creds are missing — that's normal pre-pairing — but we- // stash the error on the config so callers running with cfg.Agent.ID- // set (i.e. should-be-paired) can detect "creds went missing"- // scenarios that would otherwise silently produce empty auth fields- // and 400s on every connect attempt.- if err := cfg.LoadCredentials(); err != nil {- cfg.Auth.LoadError = err.Error()- }-- return cfg, nil-}--// Save saves configuration to file-func (c *Config) Save(path string) error {- if path == "" {- path = DefaultConfigPath()- }-- // Ensure directory exists- dir := filepath.Dir(path)- if err := os.MkdirAll(dir, 0755); err != nil {- return fmt.Errorf("failed to create config directory: %w", err)- }-- // Create a copy without sensitive data- safeCfg := *c- safeCfg.Auth.APIKey = ""- safeCfg.Auth.APISecret = ""-- data, err := yaml.Marshal(&safeCfg)- if err != nil {- return fmt.Errorf("failed to marshal config: %w", err)- }-- // Write with restricted permissions- if err := os.WriteFile(path, data, 0600); err != nil {- return fmt.Errorf("failed to write config: %w", err)- }-- return nil-}--// Print prints configuration (excluding secrets)-func (c *Config) Print() {- safeCfg := *c- safeCfg.Auth.APIKey = "[REDACTED]"- safeCfg.Auth.APISecret = "[REDACTED]"-- data, _ := yaml.Marshal(&safeCfg)- fmt.Println(string(data))-}--// SaveCredentials saves API credentials securely-func (c *Config) SaveCredentials() error {- if c.Auth.APIKey == "" || c.Auth.APISecret == "" {- return nil- }-- keyPath := c.Auth.KeyFile- if keyPath == "" {- keyPath = defaultKeyPath()- }-- // Ensure directory exists- dir := filepath.Dir(keyPath)- if err := os.MkdirAll(dir, 0700); err != nil {- return fmt.Errorf("failed to create key directory: %w", err)- }-- // Create credential data- creds := fmt.Sprintf("%s:%s", c.Auth.APIKey, c.Auth.APISecret)-- // Encrypt credentials using machine-specific key- encrypted, err := encryptCredentials([]byte(creds))- if err != nil {- return fmt.Errorf("failed to encrypt credentials: %w", err)- }-- // Write with restricted permissions- if err := os.WriteFile(keyPath, encrypted, 0600); err != nil {- return fmt.Errorf("failed to write key file: %w", err)- }-- return nil-}--// LoadCredentials loads API credentials from secure storage. Tries the-// current key derivation first, then falls back to the legacy (pre-1.6.14)-// key that included USERNAME. If the legacy key is what worked, we-// transparently re-encrypt under the current scheme so the next load-// uses the host-stable key — required for the SCM-launched service-// (running as SYSTEM) to read credentials paired by a user-context wizard.-func (c *Config) LoadCredentials() error {- keyPath := c.Auth.KeyFile- if keyPath == "" {- keyPath = defaultKeyPath()- }-- data, err := os.ReadFile(keyPath)- if err != nil {- return fmt.Errorf("failed to read key file: %w", err)- }-- decrypted, usedLegacy, err := decryptCredentialsWithMigration(data)- if err != nil {- return fmt.Errorf("failed to decrypt credentials: %w", err)- }-- // Parse credentials- var apiKey, apiSecret string- if _, err := fmt.Sscanf(string(decrypted), "%s:%s", &apiKey, &apiSecret); err != nil {- // Try splitting by colon- parts := splitFirst(string(decrypted), ':')- if len(parts) != 2 {- return fmt.Errorf("invalid credentials format")- }- apiKey = parts[0]- apiSecret = parts[1]- }-- c.Auth.APIKey = apiKey- c.Auth.APISecret = apiSecret-- // Migrate creds onto the host-only key so the next service start- // (which may run as a different user / SYSTEM) can decrypt them.- // Best-effort: failure here doesn't block this run.- if usedLegacy {- _ = c.SaveCredentials()- }-- return nil-}--// DefaultConfigPath returns the default config file path-func DefaultConfigPath() string {- if runtime.GOOS == "windows" {- return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "config.yaml")- }- return "/etc/serverkit-agent/config.yaml"-}--func defaultKeyPath() string {- if runtime.GOOS == "windows" {- return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "agent.key")- }- return "/etc/serverkit-agent/agent.key"-}--func defaultDockerSocket() string {- if runtime.GOOS == "windows" {- return "npipe:////./pipe/docker_engine"- }- return "unix:///var/run/docker.sock"-}--func defaultLogPath() string {- if runtime.GOOS == "windows" {- return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "logs", "agent.log")- }- return "/var/log/serverkit-agent/agent.log"-}--// IPCTokenPath returns the absolute path to the agent's IPC bearer-token-// file. The token gates the local HTTP API the desktop console and tray-// app use; clients must pass it as `Authorization: Bearer <token>`.-// Living next to the existing key file means it inherits the same 0600-// directory ACLs and ships with the same backup/restore policies.-func IPCTokenPath() string {- if runtime.GOOS == "windows" {- return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "ipc.token")- }- return "/etc/serverkit-agent/ipc.token"-}--func defaultAllowedPaths() []string {- if runtime.GOOS == "windows" {- return []string{filepath.Join(os.Getenv("ProgramData"), "ServerKit")}- }- return []string{"/var/lib/serverkit", "/var/serverkit"}-}--// getMachineKey generates a machine-specific encryption key.-//-// Stable across user contexts on the same host. The previous derivation-// included USERNAME, which meant credentials encrypted by a user-context-// pairing wizard (juanh) were undecryptable by the SYSTEM-context service-// — agent service started up with empty credentials, every /connect-// returned 400 "Missing required fields". This was masked for years-// because the agent was never actually running as a real Windows service-// (the SCM dispatcher only landed in 1.6.13). Now that it is, the key-// must be host-stable, not user-stable.-func getMachineKey() []byte {- hostname, _ := os.Hostname()-- var machineID string- if runtime.GOOS == "linux" {- data, err := os.ReadFile("/etc/machine-id")- if err == nil {- machineID = string(data)- }- } else if runtime.GOOS == "windows" {- machineID = os.Getenv("COMPUTERNAME")- }-- combined := fmt.Sprintf("serverkit-agent:%s:%s", hostname, machineID)- hash := sha256.Sum256([]byte(combined))- return hash[:]-}--// getMachineKeyLegacyV1 is the pre-1.6.14 derivation (Windows: included-// USERNAME). Kept solely so already-paired agents can decrypt their old-// key file once, re-encrypt under the stable v2 key, and never need it-// again. Drop after a few releases.-func getMachineKeyLegacyV1() []byte {- hostname, _ := os.Hostname()-- var machineID string- if runtime.GOOS == "linux" {- data, err := os.ReadFile("/etc/machine-id")- if err == nil {- machineID = string(data)- }- } else if runtime.GOOS == "windows" {- machineID = os.Getenv("COMPUTERNAME") + os.Getenv("USERNAME")- }-- combined := fmt.Sprintf("serverkit-agent:%s:%s", hostname, machineID)- hash := sha256.Sum256([]byte(combined))- return hash[:]-}--func encryptCredentials(plaintext []byte) ([]byte, error) {- key := getMachineKey()-- block, err := aes.NewCipher(key)- if err != nil {- return nil, err- }-- gcm, err := cipher.NewGCM(block)- if err != nil {- return nil, err- }-- nonce := make([]byte, gcm.NonceSize())- if _, err := io.ReadFull(rand.Reader, nonce); err != nil {- return nil, err- }-- ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)- return []byte(base64.StdEncoding.EncodeToString(ciphertext)), nil-}--// decryptCredentials tries the current (host-only) machine key first,-// then falls back to the legacy v1 key (host + username) so credentials-// paired before 1.6.14 still load. The bool return indicates whether the-// legacy fallback was used — callers re-encrypt under the stable v2 key-// so the migration only happens once.-func decryptCredentials(data []byte) ([]byte, error) {- plaintext, _, err := decryptCredentialsWithMigration(data)- return plaintext, err-}--func decryptCredentialsWithMigration(data []byte) (plaintext []byte, usedLegacy bool, err error) {- ciphertext, err := base64.StdEncoding.DecodeString(string(data))- if err != nil {- return nil, false, err- }-- if pt, err2 := tryDecrypt(ciphertext, getMachineKey()); err2 == nil {- return pt, false, nil- }- if pt, err2 := tryDecrypt(ciphertext, getMachineKeyLegacyV1()); err2 == nil {- return pt, true, nil- }- return nil, false, fmt.Errorf("decryption failed with both current and legacy machine keys")-}--func tryDecrypt(ciphertext, key []byte) ([]byte, error) {- block, err := aes.NewCipher(key)- if err != nil {- return nil, err- }- gcm, err := cipher.NewGCM(block)- if err != nil {- return nil, err- }- nonceSize := gcm.NonceSize()- if len(ciphertext) < nonceSize {- return nil, fmt.Errorf("ciphertext too short")- }- nonce, body := ciphertext[:nonceSize], ciphertext[nonceSize:]- return gcm.Open(nil, nonce, body, nil)-}--func splitFirst(s string, sep byte) []string {- for i := 0; i < len(s); i++ {- if s[i] == sep {- return []string{s[:i], s[i+1:]}- }- }- return []string{s}-}--// EncryptBytes encrypts bytes using the machine-derived AES-GCM key.-// Exported for use by other internal packages (e.g. pairing keypair storage).-func EncryptBytes(plaintext []byte) ([]byte, error) {- return encryptCredentials(plaintext)-}--// DecryptBytes decrypts bytes previously encrypted with EncryptBytes.-func DecryptBytes(data []byte) ([]byte, error) {- return decryptCredentials(data)-}--// MachineID returns a stable per-host identifier suitable for re-pair detection.-func MachineID() string {- hostname, _ := os.Hostname()- var id string- if runtime.GOOS == "linux" {- if data, err := os.ReadFile("/etc/machine-id"); err == nil {- id = string(data)- }- } else if runtime.GOOS == "windows" {- id = os.Getenv("COMPUTERNAME")- }- if id == "" {- id = hostname- }- hash := sha256.Sum256([]byte("serverkit-machine-id:" + hostname + ":" + id))- return base64.RawURLEncoding.EncodeToString(hash[:16])-}diff --git a/agent/internal/connstring/connstring.go b/agent/internal/connstring/connstring.godeleted file mode 100644index 91af9e95..00000000--- a/agent/internal/connstring/connstring.go+++ /dev/null@@ -1,102 +0,0 @@-// Package connstring decodes the panel's "connection string" — a single-// URL-shaped string the user copies from the ServerKit panel and pastes-// into the agent's pairing wizard. It bundles the panel host plus a-// single-use registration token plus an optional expiry, replacing the-// older flow where the user typed those into separate fields.-//-// Format: ``sk1://<host>[:<port>]/<token>[?exp=<ISO8601>][&insecure=1]``-//-// The ``sk1://`` scheme self-identifies the format (you can recognise a-// ServerKit connection string at a glance) and gives us a version-// lever: any future format change goes out as ``sk2://``. The host is-// visible up front so the user can sanity-check which panel they're-// pointing at before pasting. ``insecure=1`` flips the implied scheme-// from https to http for dev / local-network use; absent it, https is-// implied. Older agents reject newer-versioned payloads cleanly with-// ErrUnknownVersion instead of mis-parsing them.-package connstring--import (- "errors"- "fmt"- "net/url"- "strings"- "time"-)--const (- // SchemePrefix is the scheme + separator that introduces every v1- // connection string. Used to fail fast on legacy or unrelated input- // before we try to parse it as a URL.- SchemePrefix = "sk1://"-)--// Decoded is the data extracted from a connection string.-type Decoded struct {- URL string // reconstructed http/https URL of the panel- Token string // single-use registration token- ExpiresAt time.Time // zero value means "never" or "unparseable"- ExpiresAtRaw string // panel's exact expiry string (or "" if none)-}--// ErrUnknownVersion is returned when the prefix is missing or names a-// version this build doesn't understand. Callers should surface this as-// "your panel is newer than this agent" rather than a generic decode-// error — it's almost always the cause.-var ErrUnknownVersion = errors.New("connstring: unknown version prefix")--// Decode parses a connection string. Whitespace surrounding the input-// is stripped (paste-from-clipboard often picks up a trailing newline).-func Decode(s string) (*Decoded, error) {- s = strings.TrimSpace(s)- if s == "" {- return nil, errors.New("connstring: empty input")- }- if !strings.HasPrefix(s, SchemePrefix) {- return nil, ErrUnknownVersion- }-- u, err := url.Parse(s)- if err != nil {- return nil, fmt.Errorf("connstring: parse: %w", err)- }- if u.Scheme != "sk1" {- return nil, ErrUnknownVersion- }- if u.Host == "" {- return nil, errors.New("connstring: missing host")- }-- token := strings.TrimPrefix(u.Path, "/")- if token == "" {- return nil, errors.New("connstring: missing token")- }- // Tokens are url-safe by construction (panel uses secrets.token_urlsafe);- // a stray slash means the user mangled the string. Better to fail- // loudly than silently truncate.- if strings.Contains(token, "/") {- return nil, errors.New("connstring: token must not contain '/'")- }-- q := u.Query()- scheme := "https"- switch q.Get("insecure") {- case "1", "true", "yes":- scheme = "http"- }-- out := &Decoded{- URL: scheme + "://" + u.Host,- Token: token,- }- if exp := q.Get("exp"); exp != "" {- out.ExpiresAtRaw = exp- // Best-effort parse — if the panel sends a format we don't- // understand we still surface the raw value, and the panel- // remains the source of truth on whether the token is good.- if t, perr := time.Parse(time.RFC3339, exp); perr == nil {- out.ExpiresAt = t- }- }- return out, nil-}diff --git a/agent/internal/connstring/connstring_test.go b/agent/internal/connstring/connstring_test.godeleted file mode 100644index e76f8337..00000000--- a/agent/internal/connstring/connstring_test.go+++ /dev/null@@ -1,124 +0,0 @@-package connstring--import (- "errors"- "strings"- "testing"-)--func TestDecode_Roundtrip(t *testing.T) {- got, err := Decode("sk1://panel.example.com/sk_reg_abc?exp=2026-05-08T17:00:00Z")- if err != nil {- t.Fatalf("decode: %v", err)- }- if got.URL != "https://panel.example.com" {- t.Errorf("url = %q", got.URL)- }- if got.Token != "sk_reg_abc" {- t.Errorf("token = %q", got.Token)- }- if got.ExpiresAtRaw != "2026-05-08T17:00:00Z" {- t.Errorf("expires_at_raw = %q", got.ExpiresAtRaw)- }- if got.ExpiresAt.IsZero() {- t.Errorf("expires_at not parsed: %v", got.ExpiresAt)- }-}--func TestDecode_PreservesPort(t *testing.T) {- got, err := Decode("sk1://panel.example.com:9443/t")- if err != nil {- t.Fatalf("decode: %v", err)- }- if got.URL != "https://panel.example.com:9443" {- t.Errorf("url = %q", got.URL)- }-}--func TestDecode_HonoursInsecureFlag(t *testing.T) {- // http panels (typically dev / local-network) round-trip via the- // insecure=1 flag. Without honouring it, the agent would default- // to https and fail TLS against an http-only backend.- got, err := Decode("sk1://localhost:47927/t?insecure=1")- if err != nil {- t.Fatalf("decode: %v", err)- }- if got.URL != "http://localhost:47927" {- t.Errorf("url = %q (want http scheme)", got.URL)- }-}--func TestDecode_NoExpiry(t *testing.T) {- got, err := Decode("sk1://panel.example.com/t")- if err != nil {- t.Fatalf("decode: %v", err)- }- if got.ExpiresAtRaw != "" {- t.Errorf("expected no raw expiry, got %q", got.ExpiresAtRaw)- }- if !got.ExpiresAt.IsZero() {- t.Errorf("expected zero ExpiresAt, got %v", got.ExpiresAt)- }-}--func TestDecode_TrimsWhitespace(t *testing.T) {- // Clipboard pastes often have a trailing newline; verify Decode- // doesn't reject a string just because of that.- if _, err := Decode("\n sk1://panel.example.com/t \n"); err != nil {- t.Fatalf("decode with whitespace: %v", err)- }-}--func TestDecode_RejectsUnknownVersion(t *testing.T) {- cases := []string{- "sk2://panel.example.com/t",- "sk_conn_v1.eyJ1cmwiOiJodHRwczovL3gifQ", // legacy format- "not-a-connection-string",- }- for _, in := range cases {- _, err := Decode(in)- if !errors.Is(err, ErrUnknownVersion) {- t.Errorf("Decode(%q): want ErrUnknownVersion, got %v", in, err)- }- }-}--func TestDecode_RejectsEmpty(t *testing.T) {- if _, err := Decode(""); err == nil {- t.Errorf("want error for empty input")- }- if _, err := Decode(" "); err == nil {- t.Errorf("want error for whitespace-only input")- }-}--func TestDecode_RejectsMissingToken(t *testing.T) {- cases := []string{- "sk1://panel.example.com",- "sk1://panel.example.com/",- }- for _, in := range cases {- _, err := Decode(in)- if err == nil {- t.Errorf("Decode(%q): want error, got nil", in)- continue- }- if !strings.Contains(err.Error(), "token") {- t.Errorf("Decode(%q): unexpected error %v", in, err)- }- }-}--func TestDecode_RejectsTokenWithSlash(t *testing.T) {- _, err := Decode("sk1://panel.example.com/sk_reg/abc")- if err == nil || !strings.Contains(err.Error(), "/") {- t.Errorf("expected error about '/', got %v", err)- }-}--func TestDecode_RejectsMissingHost(t *testing.T) {- _, err := Decode("sk1:///t")- if err == nil || !strings.Contains(err.Error(), "host") {- t.Errorf("expected host error, got %v", err)- }-}diff --git a/agent/internal/cron/cron.go b/agent/internal/cron/cron.godeleted file mode 100644index abcccefb..00000000--- a/agent/internal/cron/cron.go+++ /dev/null@@ -1,68 +0,0 @@-// Package cron manages user-crontab entries for the agent host.-//-// Linux-only. The Manager is implemented by a build-tagged file-// (cron_linux.go for the real thing, cron_other.go for a stub that-// returns "unsupported" on every call). Higher layers always go through-// New() so non-Linux agents short-circuit before doing any work.-//-// Storage model:-//-// - The user's crontab is the source of truth for schedule + command.-// - Entries get a stable ID derived from sha256(schedule + command),-// truncated to 12 hex chars. IDs survive add/remove of unrelated-// entries — line-index IDs would not.-// - Disabled entries are commented (`# <line>`); the leading `# `-// is stripped on parse and re-added on toggle. We do NOT store-// enable state out-of-band.-// - Optional human metadata (name, description) lives in a sibling-// JSON file owned by the agent. Loss of that file degrades to "no-// names" but doesn't lose any actual schedules.-package cron--import (- "context"- "crypto/sha256"- "encoding/hex"-)--// Entry is one cron line.-type Entry struct {- ID string `json:"id"`- Schedule string `json:"schedule"`- Command string `json:"command"`- Enabled bool `json:"enabled"`- Name string `json:"name,omitempty"`- Description string `json:"description,omitempty"`-}--// Status reports whether cron is usable on this host.-type Status struct {- Available bool `json:"available"`- Running bool `json:"running"`- Daemon string `json:"daemon,omitempty"` // e.g. "cron", "cronie"- Reason string `json:"reason,omitempty"` // explanation when Available=false-}--// AddRequest is what the panel sends to add a job.-type AddRequest struct {- Schedule string `json:"schedule"`- Command string `json:"command"`- Name string `json:"name,omitempty"`- Description string `json:"description,omitempty"`-}--// Manager is the platform-agnostic interface over the crontab.-type Manager interface {- Status(ctx context.Context) (*Status, error)- List(ctx context.Context) ([]Entry, error)- Add(ctx context.Context, req AddRequest) (*Entry, error)- Remove(ctx context.Context, id string) error- Toggle(ctx context.Context, id string, enabled bool) error-}--// entryID is the public hashing rule for content-based IDs.-// Exposed so tests can mirror it; not used outside the package.-func entryID(schedule, command string) string {- sum := sha256.Sum256([]byte(schedule + "\x00" + command))- return "cron_" + hex.EncodeToString(sum[:6])-}diff --git a/agent/internal/cron/cron_linux.go b/agent/internal/cron/cron_linux.godeleted file mode 100644index df9e0703..00000000--- a/agent/internal/cron/cron_linux.go+++ /dev/null@@ -1,313 +0,0 @@-//go:build linux--package cron--import (- "bufio"- "bytes"- "context"- "fmt"- "os/exec"- "regexp"- "strings"-)--// New returns a Manager. On Linux this drives crontab(1).-func New() Manager { return &linuxManager{} }--type linuxManager struct{}--// blockedShellPatterns mirror the panel's CronService validation. We-// re-check on the agent because a malicious or misconfigured panel-// shouldn't be able to push shell-injection payloads through. Reject-// anything that turns "X command" into multiple shell-evaluated-// statements.-var blockedShellPatterns = []string{";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r"}--func validateCommand(cmd string) error {- cmd = strings.TrimSpace(cmd)- if cmd == "" {- return fmt.Errorf("command cannot be empty")- }- for _, p := range blockedShellPatterns {- if strings.Contains(cmd, p) {- return fmt.Errorf("command contains blocked shell operator %q", p)- }- }- // First token must be an absolute path to a binary — same rule as- // the panel-local CronService.- first := strings.Fields(cmd)[0]- if !strings.HasPrefix(first, "/") {- return fmt.Errorf("command must start with an absolute path")- }- return nil-}--var scheduleRegex = regexp.MustCompile(`^[\d\*,\-/]+$`)--func validateSchedule(schedule string) error {- parts := strings.Fields(schedule)- if len(parts) != 5 {- return fmt.Errorf("schedule must have 5 fields, got %d", len(parts))- }- for _, p := range parts {- if !scheduleRegex.MatchString(p) {- return fmt.Errorf("invalid schedule field %q", p)- }- }- return nil-}--func (l *linuxManager) Status(ctx context.Context) (*Status, error) {- if _, err := exec.LookPath("crontab"); err != nil {- return &Status{- Available: false,- Reason: "crontab not installed on host",- }, nil- }- // Best-effort daemon liveness. systemctl will respond on most modern- // distros; if it isn't present we still report Available=true since- // crontab(1) is what we drive — the user's job sits in the table- // either way.- running, daemon := false, ""- for _, name := range []string{"cron", "crond", "cronie"} {- out, _ := exec.CommandContext(ctx, "systemctl", "is-active", name).Output()- if strings.TrimSpace(string(out)) == "active" {- running = true- daemon = name- break- }- }- return &Status{Available: true, Running: running, Daemon: daemon}, nil-}--// readCrontab returns the current user's crontab. An exit code 1 with-// "no crontab for $USER" on stderr is normal and means "empty"; treat-// that as success with empty content.-func (l *linuxManager) readCrontab(ctx context.Context) (string, error) {- cmd := exec.CommandContext(ctx, "crontab", "-l")- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr- err := cmd.Run()- if err != nil {- // "no crontab for X" is not an error — it's the empty state.- if strings.Contains(stderr.String(), "no crontab for") {- return "", nil- }- return "", fmt.Errorf("crontab -l: %w (%s)", err, strings.TrimSpace(stderr.String()))- }- return stdout.String(), nil-}--// writeCrontab installs new content via `crontab -`.-func (l *linuxManager) writeCrontab(ctx context.Context, content string) error {- cmd := exec.CommandContext(ctx, "crontab", "-")- cmd.Stdin = strings.NewReader(content)- var stderr bytes.Buffer- cmd.Stderr = &stderr- if err := cmd.Run(); err != nil {- return fmt.Errorf("crontab install: %w (%s)", err, strings.TrimSpace(stderr.String()))- }- return nil-}--// parsedLine is a typed view of one crontab row.-type parsedLine struct {- Raw string // verbatim text including leading "# " for disabled- Schedule string- Command string- Enabled bool- IsEntry bool // false for blank lines / pure comments-}--// parseLine extracts schedule + command from one crontab row. Pure-// comments (lines that are # without a 5-field schedule body) are-// ignored. Disabled entries (# <schedule> <command>) are recognised.-func parseLine(line string) parsedLine {- out := parsedLine{Raw: line}- body := strings.TrimSpace(line)- if body == "" {- return out- }- enabled := true- if strings.HasPrefix(body, "#") {- // Could be a pure comment or a disabled entry. Strip the leading- // "#" and any whitespace, then try to parse as cron syntax.- body = strings.TrimSpace(strings.TrimPrefix(body, "#"))- enabled = false- }- fields := strings.Fields(body)- if len(fields) < 6 {- return out // not an entry- }- if validateSchedule(strings.Join(fields[:5], " ")) != nil {- return out // first 5 fields don't look like a schedule- }- out.IsEntry = true- out.Schedule = strings.Join(fields[:5], " ")- out.Command = strings.Join(fields[5:], " ")- out.Enabled = enabled- return out-}--func (l *linuxManager) List(ctx context.Context) ([]Entry, error) {- content, err := l.readCrontab(ctx)- if err != nil {- return nil, err- }- var entries []Entry- scanner := bufio.NewScanner(strings.NewReader(content))- for scanner.Scan() {- p := parseLine(scanner.Text())- if !p.IsEntry {- continue- }- entries = append(entries, Entry{- ID: entryID(p.Schedule, p.Command),- Schedule: p.Schedule,- Command: p.Command,- Enabled: p.Enabled,- Description: describeSchedule(p.Schedule),- })- }- return entries, nil-}--func (l *linuxManager) Add(ctx context.Context, req AddRequest) (*Entry, error) {- if err := validateSchedule(req.Schedule); err != nil {- return nil, err- }- if err := validateCommand(req.Command); err != nil {- return nil, err- }- id := entryID(req.Schedule, req.Command)-- content, err := l.readCrontab(ctx)- if err != nil {- return nil, err- }-- // Reject duplicates by content ID. Lets the panel safely retry on a- // flaky network without ending up with two identical rows.- scanner := bufio.NewScanner(strings.NewReader(content))- for scanner.Scan() {- p := parseLine(scanner.Text())- if p.IsEntry && entryID(p.Schedule, p.Command) == id {- return nil, fmt.Errorf("an entry with the same schedule and command already exists")- }- }-- var b strings.Builder- b.WriteString(strings.TrimRight(content, "\n"))- if b.Len() > 0 {- b.WriteString("\n")- }- if req.Name != "" {- fmt.Fprintf(&b, "# ServerKit: %s\n", req.Name)- }- fmt.Fprintf(&b, "%s %s\n", req.Schedule, req.Command)-- if err := l.writeCrontab(ctx, b.String()); err != nil {- return nil, err- }-- return &Entry{- ID: id,- Schedule: req.Schedule,- Command: req.Command,- Enabled: true,- Name: req.Name,- Description: describeSchedule(req.Schedule),- }, nil-}--func (l *linuxManager) Remove(ctx context.Context, id string) error {- content, err := l.readCrontab(ctx)- if err != nil {- return err- }- var out strings.Builder- scanner := bufio.NewScanner(strings.NewReader(content))- removed := false- skipNextComment := false- for scanner.Scan() {- line := scanner.Text()- if skipNextComment {- // Don't drop unrelated comments — only strip the- // immediately-following entry comment if we just removed- // its schedule line. Reset the flag here regardless.- skipNextComment = false- }- p := parseLine(line)- if p.IsEntry && entryID(p.Schedule, p.Command) == id {- removed = true- continue- }- out.WriteString(line)- out.WriteString("\n")- }- if !removed {- return fmt.Errorf("entry %s not found", id)- }- return l.writeCrontab(ctx, strings.TrimRight(out.String(), "\n")+"\n")-}--func (l *linuxManager) Toggle(ctx context.Context, id string, enabled bool) error {- content, err := l.readCrontab(ctx)- if err != nil {- return err- }- var out strings.Builder- scanner := bufio.NewScanner(strings.NewReader(content))- matched := false- for scanner.Scan() {- line := scanner.Text()- p := parseLine(line)- if p.IsEntry && entryID(p.Schedule, p.Command) == id {- matched = true- if enabled {- out.WriteString(p.Schedule + " " + p.Command + "\n")- } else {- out.WriteString("# " + p.Schedule + " " + p.Command + "\n")- }- continue- }- out.WriteString(line)- out.WriteString("\n")- }- if !matched {- return fmt.Errorf("entry %s not found", id)- }- return l.writeCrontab(ctx, strings.TrimRight(out.String(), "\n")+"\n")-}--// describeSchedule returns a short human label for common patterns.-// Falls back to the raw schedule when nothing matches — matches the-// behaviour the panel-local CronService already produces, so per-server-// rows look the same as panel-local rows in the UI.-func describeSchedule(schedule string) string {- switch schedule {- case "* * * * *":- return "Every minute"- case "*/5 * * * *":- return "Every 5 minutes"- case "*/15 * * * *":- return "Every 15 minutes"- case "*/30 * * * *":- return "Every 30 minutes"- case "0 * * * *":- return "Hourly"- case "0 0 * * *":- return "Daily at midnight"- case "0 12 * * *":- return "Daily at noon"- case "0 0 * * 0":- return "Weekly (Sunday)"- case "0 0 1 * *":- return "Monthly (1st)"- case "0 0 1 1 *":- return "Yearly (Jan 1)"- }- return schedule-}diff --git a/agent/internal/cron/cron_other.go b/agent/internal/cron/cron_other.godeleted file mode 100644index 2c1f64d8..00000000--- a/agent/internal/cron/cron_other.go+++ /dev/null@@ -1,27 +0,0 @@-//go:build !linux--package cron--import (- "context"- "fmt"-)--// New returns a stub Manager on non-Linux platforms. Every operation-// reports the feature as unavailable so callers fail loudly rather-// than silently doing nothing.-func New() Manager { return stubManager{} }--type stubManager struct{}--var errUnsupported = fmt.Errorf("cron is only supported on Linux agents")--func (stubManager) Status(ctx context.Context) (*Status, error) {- return &Status{Available: false, Reason: "cron is only supported on Linux agents"}, nil-}-func (stubManager) List(ctx context.Context) ([]Entry, error) { return nil, errUnsupported }-func (stubManager) Add(ctx context.Context, _ AddRequest) (*Entry, error) {- return nil, errUnsupported-}-func (stubManager) Remove(ctx context.Context, _ string) error { return errUnsupported }-func (stubManager) Toggle(ctx context.Context, _ string, _ bool) error { return errUnsupported }diff --git a/agent/internal/docker/client.go b/agent/internal/docker/client.godeleted file mode 100644index ff99c18c..00000000--- a/agent/internal/docker/client.go+++ /dev/null@@ -1,901 +0,0 @@-package docker--import (- "context"- "encoding/json"- "fmt"- "io"- "os/exec"- "strings"-- "github.com/docker/docker/api/types"- containertypes "github.com/docker/docker/api/types/container"- "github.com/docker/docker/api/types/filters"- networktypes "github.com/docker/docker/api/types/network"- volumetypes "github.com/docker/docker/api/types/volume"- "github.com/docker/docker/client"- "github.com/docker/go-connections/nat"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"-)--// Client wraps the Docker client with additional functionality-type Client struct {- cli *client.Client- cfg config.DockerConfig- log *logger.Logger-}--// ContainerInfo represents container information-type ContainerInfo struct {- ID string `json:"id"`- Name string `json:"name"`- Image string `json:"image"`- ImageID string `json:"image_id"`- Command string `json:"command"`- Created int64 `json:"created"`- State string `json:"state"`- Status string `json:"status"`- Ports []PortMapping `json:"ports"`- Labels map[string]string `json:"labels"`-}--// PortMapping represents a port mapping-type PortMapping struct {- IP string `json:"ip,omitempty"`- PrivatePort uint16 `json:"private_port"`- PublicPort uint16 `json:"public_port,omitempty"`- Type string `json:"type"`-}--// ContainerStats represents container statistics-type ContainerStats struct {- ID string `json:"id"`- Name string `json:"name"`- CPUPercent float64 `json:"cpu_percent"`- MemoryUsage uint64 `json:"memory_usage"`- MemoryLimit uint64 `json:"memory_limit"`- MemoryPercent float64 `json:"memory_percent"`- NetworkRx uint64 `json:"network_rx"`- NetworkTx uint64 `json:"network_tx"`- BlockRead uint64 `json:"block_read"`- BlockWrite uint64 `json:"block_write"`- PIDs uint64 `json:"pids"`-}--// ImageInfo represents image information-type ImageInfo struct {- ID string `json:"id"`- RepoTags []string `json:"repo_tags"`- RepoDigests []string `json:"repo_digests"`- Created int64 `json:"created"`- Size int64 `json:"size"`-}--// VolumeInfo represents volume information-type VolumeInfo struct {- Name string `json:"name"`- Driver string `json:"driver"`- Mountpoint string `json:"mountpoint"`- Labels map[string]string `json:"labels"`- Scope string `json:"scope"`- CreatedAt string `json:"created_at"`-}--// NetworkInfo represents network information-type NetworkInfo struct {- ID string `json:"id"`- Name string `json:"name"`- Driver string `json:"driver"`- Scope string `json:"scope"`- Internal bool `json:"internal"`- Labels map[string]string `json:"labels"`- Containers int `json:"containers"`-}--// NewClient creates a new Docker client-func NewClient(cfg config.DockerConfig, log *logger.Logger) (*Client, error) {- var opts []client.Opt-- // Set host if configured- if cfg.Socket != "" {- host := cfg.Socket- // Convert socket path to Docker format- if strings.HasPrefix(host, "/") {- host = "unix://" + host- }- opts = append(opts, client.WithHost(host))- }-- opts = append(opts, client.WithAPIVersionNegotiation())-- if cfg.Timeout > 0 {- opts = append(opts, client.WithTimeout(cfg.Timeout))- }-- cli, err := client.NewClientWithOpts(opts...)- if err != nil {- return nil, fmt.Errorf("failed to create Docker client: %w", err)- }-- return &Client{- cli: cli,- cfg: cfg,- log: log.WithComponent("docker"),- }, nil-}--// Ping checks if Docker is available-func (c *Client) Ping(ctx context.Context) error {- _, err := c.cli.Ping(ctx)- return err-}--// Version returns the Docker version-func (c *Client) Version(ctx context.Context) (string, error) {- info, err := c.cli.ServerVersion(ctx)- if err != nil {- return "", err- }- return info.Version, nil-}--// Info returns Docker system info-func (c *Client) Info(ctx context.Context) (*types.Info, error) {- info, err := c.cli.Info(ctx)- if err != nil {- return nil, err- }- return &info, nil-}--// ListContainers lists all containers-func (c *Client) ListContainers(ctx context.Context, all bool) ([]ContainerInfo, error) {- containers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{- All: all,- })- if err != nil {- return nil, err- }-- result := make([]ContainerInfo, len(containers))- for i, cont := range containers {- ports := make([]PortMapping, len(cont.Ports))- for j, p := range cont.Ports {- ports[j] = PortMapping{- IP: p.IP,- PrivatePort: p.PrivatePort,- PublicPort: p.PublicPort,- Type: p.Type,- }- }-- name := ""- if len(cont.Names) > 0 {- name = strings.TrimPrefix(cont.Names[0], "/")- }-- result[i] = ContainerInfo{- ID: cont.ID[:12],- Name: name,- Image: cont.Image,- ImageID: cont.ImageID,- Command: cont.Command,- Created: cont.Created,- State: cont.State,- Status: cont.Status,- Ports: ports,- Labels: cont.Labels,- }- }-- return result, nil-}--// InspectContainer inspects a container-func (c *Client) InspectContainer(ctx context.Context, id string) (*types.ContainerJSON, error) {- cont, err := c.cli.ContainerInspect(ctx, id)- if err != nil {- return nil, err- }- return &cont, nil-}--// StartContainer starts a container-func (c *Client) StartContainer(ctx context.Context, id string) error {- return c.cli.ContainerStart(ctx, id, types.ContainerStartOptions{})-}--// StopContainer stops a container-func (c *Client) StopContainer(ctx context.Context, id string, timeout *int) error {- var stopOpts containertypes.StopOptions- if timeout != nil {- stopOpts.Timeout = timeout- }- return c.cli.ContainerStop(ctx, id, stopOpts)-}--// RestartContainer restarts a container-func (c *Client) RestartContainer(ctx context.Context, id string, timeout *int) error {- var stopOpts containertypes.StopOptions- if timeout != nil {- stopOpts.Timeout = timeout- }- return c.cli.ContainerRestart(ctx, id, stopOpts)-}--// RemoveContainer removes a container-func (c *Client) RemoveContainer(ctx context.Context, id string, force, removeVolumes bool) error {- return c.cli.ContainerRemove(ctx, id, types.ContainerRemoveOptions{- Force: force,- RemoveVolumes: removeVolumes,- })-}--// ContainerLogs returns container logs-func (c *Client) ContainerLogs(ctx context.Context, id string, tail string, since string, follow bool) (io.ReadCloser, error) {- opts := types.ContainerLogsOptions{- ShowStdout: true,- ShowStderr: true,- Follow: follow,- Timestamps: true,- }-- if tail != "" {- opts.Tail = tail- }-- if since != "" {- opts.Since = since- }-- return c.cli.ContainerLogs(ctx, id, opts)-}--// ContainerStats returns container stats-func (c *Client) ContainerStats(ctx context.Context, id string) (*ContainerStats, error) {- resp, err := c.cli.ContainerStats(ctx, id, false)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- var stats types.StatsJSON- if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {- return nil, err- }-- // Calculate CPU percentage- cpuPercent := calculateCPUPercent(&stats)-- // Calculate memory percentage- memPercent := 0.0- if stats.MemoryStats.Limit > 0 {- memPercent = float64(stats.MemoryStats.Usage) / float64(stats.MemoryStats.Limit) * 100- }-- // Calculate network I/O- var rx, tx uint64- for _, net := range stats.Networks {- rx += net.RxBytes- tx += net.TxBytes- }-- // Calculate block I/O- var read, write uint64- for _, bio := range stats.BlkioStats.IoServiceBytesRecursive {- if bio.Op == "Read" {- read += bio.Value- } else if bio.Op == "Write" {- write += bio.Value- }- }-- // Get container name- inspect, _ := c.cli.ContainerInspect(ctx, id)- name := strings.TrimPrefix(inspect.Name, "/")-- return &ContainerStats{- ID: id[:12],- Name: name,- CPUPercent: cpuPercent,- MemoryUsage: stats.MemoryStats.Usage,- MemoryLimit: stats.MemoryStats.Limit,- MemoryPercent: memPercent,- NetworkRx: rx,- NetworkTx: tx,- BlockRead: read,- BlockWrite: write,- PIDs: stats.PidsStats.Current,- }, nil-}--// ListImages lists all images-func (c *Client) ListImages(ctx context.Context) ([]ImageInfo, error) {- images, err := c.cli.ImageList(ctx, types.ImageListOptions{})- if err != nil {- return nil, err- }-- result := make([]ImageInfo, len(images))- for i, img := range images {- result[i] = ImageInfo{- ID: img.ID,- RepoTags: img.RepoTags,- RepoDigests: img.RepoDigests,- Created: img.Created,- Size: img.Size,- }- }-- return result, nil-}--// PullImage pulls an image-func (c *Client) PullImage(ctx context.Context, imageName string) (io.ReadCloser, error) {- return c.cli.ImagePull(ctx, imageName, types.ImagePullOptions{})-}--// RemoveImage removes an image-func (c *Client) RemoveImage(ctx context.Context, id string, force bool) error {- _, err := c.cli.ImageRemove(ctx, id, types.ImageRemoveOptions{- Force: force,- })- return err-}--// ListVolumes lists all volumes-func (c *Client) ListVolumes(ctx context.Context) ([]VolumeInfo, error) {- resp, err := c.cli.VolumeList(ctx, volumetypes.ListOptions{})- if err != nil {- return nil, err- }-- result := make([]VolumeInfo, len(resp.Volumes))- for i, vol := range resp.Volumes {- result[i] = VolumeInfo{- Name: vol.Name,- Driver: vol.Driver,- Mountpoint: vol.Mountpoint,- Labels: vol.Labels,- Scope: vol.Scope,- CreatedAt: vol.CreatedAt,- }- }-- return result, nil-}--// CreateVolume creates a volume-func (c *Client) CreateVolume(ctx context.Context, name, driver string, labels map[string]string) (*VolumeInfo, error) {- vol, err := c.cli.VolumeCreate(ctx, volumetypes.CreateOptions{- Name: name,- Driver: driver,- Labels: labels,- })- if err != nil {- return nil, err- }-- return &VolumeInfo{- Name: vol.Name,- Driver: vol.Driver,- Mountpoint: vol.Mountpoint,- Labels: vol.Labels,- Scope: vol.Scope,- CreatedAt: vol.CreatedAt,- }, nil-}--// RemoveVolume removes a volume-func (c *Client) RemoveVolume(ctx context.Context, name string, force bool) error {- return c.cli.VolumeRemove(ctx, name, force)-}--// ListNetworks lists all networks-func (c *Client) ListNetworks(ctx context.Context) ([]NetworkInfo, error) {- networks, err := c.cli.NetworkList(ctx, types.NetworkListOptions{})- if err != nil {- return nil, err- }-- result := make([]NetworkInfo, len(networks))- for i, net := range networks {- result[i] = NetworkInfo{- ID: net.ID[:12],- Name: net.Name,- Driver: net.Driver,- Scope: net.Scope,- Internal: net.Internal,- Labels: net.Labels,- Containers: len(net.Containers),- }- }-- return result, nil-}--// RemoveNetwork removes a network-func (c *Client) RemoveNetwork(ctx context.Context, id string) error {- return c.cli.NetworkRemove(ctx, id)-}--// GetContainerCount returns the number of containers-func (c *Client) GetContainerCount(ctx context.Context) (total int, running int, err error) {- allContainers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{All: true})- if err != nil {- return 0, 0, err- }-- runningContainers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{- Filters: filters.NewArgs(filters.Arg("status", "running")),- })- if err != nil {- return 0, 0, err- }-- return len(allContainers), len(runningContainers), nil-}--// Close closes the Docker client-func (c *Client) Close() error {- return c.cli.Close()-}--// ───── container:create / container:exec / image:build / network:create--// ContainerCreateSpec is the curated input shape for CreateContainer.-// We deliberately don't expose raw HostConfig — the panel sends the-// fields a one-click template needs and we map them. Privileged /-// CapAdd / Devices are intentionally absent in v1; if a user needs-// them they should run `docker create` directly.-type ContainerCreateSpec struct {- Image string `json:"image"`- Name string `json:"name,omitempty"`- Command []string `json:"command,omitempty"`- Env []string `json:"env,omitempty"` // KEY=VAL- Labels map[string]string `json:"labels,omitempty"`- RestartPolicy string `json:"restart_policy,omitempty"` // no, on-failure, always, unless-stopped- Network string `json:"network,omitempty"`- Ports []ContainerPort `json:"ports,omitempty"`- Volumes []ContainerMount `json:"volumes,omitempty"`- WorkingDir string `json:"working_dir,omitempty"`-}--type ContainerPort struct {- Host uint16 `json:"host"`- Container uint16 `json:"container"`- Proto string `json:"proto,omitempty"` // "tcp" (default) or "udp"-}--type ContainerMount struct {- Source string `json:"src"`- Target string `json:"dst"`- Mode string `json:"mode,omitempty"` // "ro" or "" for rw-}--// CreateContainer wires a curated spec to the Docker SDK's-// ContainerCreate. Returns the new container ID.-func (c *Client) CreateContainer(ctx context.Context, spec ContainerCreateSpec) (string, error) {- if strings.TrimSpace(spec.Image) == "" {- return "", fmt.Errorf("image is required")- }-- exposed := nat.PortSet{}- bindings := nat.PortMap{}- for _, p := range spec.Ports {- proto := p.Proto- if proto == "" {- proto = "tcp"- }- port, err := nat.NewPort(proto, fmt.Sprintf("%d", p.Container))- if err != nil {- return "", fmt.Errorf("invalid port %d/%s: %w", p.Container, proto, err)- }- exposed[port] = struct{}{}- bindings[port] = []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: fmt.Sprintf("%d", p.Host)}}- }-- binds := make([]string, 0, len(spec.Volumes))- for _, v := range spec.Volumes {- bind := v.Source + ":" + v.Target- if v.Mode != "" {- bind += ":" + v.Mode- }- binds = append(binds, bind)- }-- cfg := &containertypes.Config{- Image: spec.Image,- Cmd: spec.Command,- Env: spec.Env,- Labels: spec.Labels,- WorkingDir: spec.WorkingDir,- ExposedPorts: exposed,- }- hostCfg := &containertypes.HostConfig{- PortBindings: bindings,- Binds: binds,- RestartPolicy: containertypes.RestartPolicy{- Name: spec.RestartPolicy,- },- }- var netCfg *networktypes.NetworkingConfig- if spec.Network != "" {- netCfg = &networktypes.NetworkingConfig{- EndpointsConfig: map[string]*networktypes.EndpointSettings{- spec.Network: {},- },- }- }- resp, err := c.cli.ContainerCreate(ctx, cfg, hostCfg, netCfg, nil, spec.Name)- if err != nil {- return "", err- }- return resp.ID, nil-}--// ContainerExecResult is the bounded result of an exec call.-type ContainerExecResult struct {- Stdout string `json:"stdout"`- Stderr string `json:"stderr"`- ExitCode int `json:"exit_code"`-}--// ExecContainer runs a command inside a running container, captures-// stdout/stderr (capped to outputCap bytes), and returns the exit code.-// User and WorkingDir are optional; pass an empty string to inherit.-func (c *Client) ExecContainer(ctx context.Context, id string, cmd []string, user, workingDir string, outputCap int) (ContainerExecResult, error) {- if outputCap <= 0 {- outputCap = 1024 * 1024 // 1MB default- }- createResp, err := c.cli.ContainerExecCreate(ctx, id, types.ExecConfig{- Cmd: cmd,- AttachStdout: true,- AttachStderr: true,- User: user,- WorkingDir: workingDir,- })- if err != nil {- return ContainerExecResult{}, err- }- hijack, err := c.cli.ContainerExecAttach(ctx, createResp.ID, types.ExecStartCheck{})- if err != nil {- return ContainerExecResult{}, err- }- defer hijack.Close()-- // Read multiplexed stream: docker frames stdout/stderr together- // with an 8-byte header. stdcopy.StdCopy demultiplexes, but to- // avoid an extra import we use a bounded ReadAll and ship the raw- // stream — the panel only needs the combined output anyway.- buf := &boundedBuffer{cap: outputCap}- _, _ = io.Copy(buf, hijack.Reader)-- insp, err := c.cli.ContainerExecInspect(ctx, createResp.ID)- if err != nil {- return ContainerExecResult{}, err- }- return ContainerExecResult{- Stdout: buf.String(),- ExitCode: insp.ExitCode,- }, nil-}--// boundedBuffer is a tiny io.Writer that drops bytes past a cap. Used-// instead of bytes.Buffer to keep exec output from blowing memory on a-// chatty command like `find /`.-type boundedBuffer struct {- cap int- data []byte-}--func (b *boundedBuffer) Write(p []byte) (int, error) {- remaining := b.cap - len(b.data)- if remaining <= 0 {- return len(p), nil- }- if len(p) > remaining {- b.data = append(b.data, p[:remaining]...)- return len(p), nil- }- b.data = append(b.data, p...)- return len(p), nil-}--func (b *boundedBuffer) String() string { return string(b.data) }--// ImageBuildSpec carries the curated input for BuildImage.-type ImageBuildSpec struct {- ContextPath string `json:"context_path"`- Dockerfile string `json:"dockerfile,omitempty"`- Tag string `json:"tag"`- BuildArgs map[string]string `json:"build_args,omitempty"`- NoCache bool `json:"no_cache,omitempty"`- Pull bool `json:"pull,omitempty"`-}--// BuildImageCmd builds the *exec.Cmd for a `docker build` invocation-// based on spec. The caller streams stdout/stderr (we use the same-// jobs streaming helper as packages). Returning a Cmd rather than a-// reader keeps this file from importing the docker SDK's archive-// package, which pulls in containerd/moby deps that aren't in our-// go.mod.-func (c *Client) BuildImageCmd(ctx context.Context, spec ImageBuildSpec) (*exec.Cmd, error) {- if strings.TrimSpace(spec.ContextPath) == "" {- return nil, fmt.Errorf("context_path is required")- }- if strings.TrimSpace(spec.Tag) == "" {- return nil, fmt.Errorf("tag is required")- }- args := []string{"build", "-t", spec.Tag}- if spec.Dockerfile != "" {- args = append(args, "-f", spec.Dockerfile)- }- for k, v := range spec.BuildArgs {- args = append(args, "--build-arg", k+"="+v)- }- if spec.NoCache {- args = append(args, "--no-cache")- }- if spec.Pull {- args = append(args, "--pull")- }- args = append(args, spec.ContextPath)- return exec.CommandContext(ctx, "docker", args...), nil-}--// NetworkCreateSpec carries curated input for CreateNetwork.-type NetworkCreateSpec struct {- Name string `json:"name"`- Driver string `json:"driver,omitempty"` // bridge (default), overlay, host- Internal bool `json:"internal,omitempty"`- Attachable bool `json:"attachable,omitempty"`- Labels map[string]string `json:"labels,omitempty"`-}--// CreateNetwork creates a Docker network and returns its ID.-func (c *Client) CreateNetwork(ctx context.Context, spec NetworkCreateSpec) (string, error) {- if strings.TrimSpace(spec.Name) == "" {- return "", fmt.Errorf("name is required")- }- driver := spec.Driver- if driver == "" {- driver = "bridge"- }- resp, err := c.cli.NetworkCreate(ctx, spec.Name, types.NetworkCreate{- Driver: driver,- Internal: spec.Internal,- Attachable: spec.Attachable,- Labels: spec.Labels,- })- if err != nil {- return "", err- }- return resp.ID, nil-}--// calculateCPUPercent calculates CPU usage percentage-func calculateCPUPercent(stats *types.StatsJSON) float64 {- cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage - stats.PreCPUStats.CPUUsage.TotalUsage)- systemDelta := float64(stats.CPUStats.SystemUsage - stats.PreCPUStats.SystemUsage)-- if systemDelta > 0 && cpuDelta > 0 {- cpuPercent := (cpuDelta / systemDelta) * float64(stats.CPUStats.OnlineCPUs) * 100.0- return cpuPercent- }-- return 0.0-}--// ==================== Docker Compose ====================--// ComposeProject represents a Docker Compose project-type ComposeProject struct {- Name string `json:"name"`- Status string `json:"status"`- ConfigFiles string `json:"config_files"`-}--// ComposeContainer represents a container in a compose project-type ComposeContainer struct {- ID string `json:"id"`- Name string `json:"name"`- Service string `json:"service"`- State string `json:"state"`- Status string `json:"status"`- Ports string `json:"ports"`-}--// ComposeList lists all compose projects-func (c *Client) ComposeList(ctx context.Context) ([]ComposeProject, error) {- cmd := exec.CommandContext(ctx, "docker", "compose", "ls", "--format", "json")- output, err := cmd.Output()- if err != nil {- return nil, fmt.Errorf("failed to list compose projects: %w", err)- }-- var projects []ComposeProject- if err := json.Unmarshal(output, &projects); err != nil {- return nil, fmt.Errorf("failed to parse compose projects: %w", err)- }-- return projects, nil-}--// ComposePsProject lists containers for a specific compose project-func (c *Client) ComposePsProject(ctx context.Context, projectPath string) ([]ComposeContainer, error) {- if err := validateProjectPath(projectPath); err != nil {- return nil, err- }-- cmd := exec.CommandContext(ctx, "docker", "compose", "-f", projectPath, "ps", "--format", "json", "-a")- output, err := cmd.Output()- if err != nil {- return nil, fmt.Errorf("failed to list compose containers: %w", err)- }-- // Handle empty output- if len(output) == 0 {- return []ComposeContainer{}, nil- }-- // Docker compose ps can return either a JSON array or line-delimited JSON objects- var containers []ComposeContainer-- // Try parsing as JSON array first- if err := json.Unmarshal(output, &containers); err != nil {- // Try line-by-line JSON parsing- lines := strings.Split(string(output), "\n")- for _, line := range lines {- line = strings.TrimSpace(line)- if line == "" {- continue- }- var container ComposeContainer- if err := json.Unmarshal([]byte(line), &container); err != nil {- continue- }- containers = append(containers, container)- }- }-- return containers, nil-}--// ComposeUp starts a compose project-func (c *Client) ComposeUp(ctx context.Context, projectPath string, detach, build bool) (string, error) {- if err := validateProjectPath(projectPath); err != nil {- return "", err- }-- args := []string{"compose", "-f", projectPath, "up"}- if detach {- args = append(args, "-d")- }- if build {- args = append(args, "--build")- }-- cmd := exec.CommandContext(ctx, "docker", args...)- output, err := cmd.CombinedOutput()- if err != nil {- return string(output), fmt.Errorf("compose up failed: %w: %s", err, output)- }-- return string(output), nil-}--// ComposeDown stops a compose project-func (c *Client) ComposeDown(ctx context.Context, projectPath string, volumes, removeOrphans bool) (string, error) {- if err := validateProjectPath(projectPath); err != nil {- return "", err- }-- args := []string{"compose", "-f", projectPath, "down"}- if volumes {- args = append(args, "-v")- }- if removeOrphans {- args = append(args, "--remove-orphans")- }-- cmd := exec.CommandContext(ctx, "docker", args...)- output, err := cmd.CombinedOutput()- if err != nil {- return string(output), fmt.Errorf("compose down failed: %w: %s", err, output)- }-- return string(output), nil-}--// ComposeLogs gets logs from a compose project-func (c *Client) ComposeLogs(ctx context.Context, projectPath, service string, tail int) (string, error) {- if err := validateProjectPath(projectPath); err != nil {- return "", err- }-- args := []string{"compose", "-f", projectPath, "logs", "--no-color"}- if tail > 0 {- args = append(args, "--tail", fmt.Sprintf("%d", tail))- }- if service != "" {- args = append(args, service)- }-- cmd := exec.CommandContext(ctx, "docker", args...)- output, err := cmd.CombinedOutput()- if err != nil {- return string(output), fmt.Errorf("compose logs failed: %w: %s", err, output)- }-- return string(output), nil-}--// ComposeRestart restarts a compose project or specific service-func (c *Client) ComposeRestart(ctx context.Context, projectPath, service string) (string, error) {- if err := validateProjectPath(projectPath); err != nil {- return "", err- }-- args := []string{"compose", "-f", projectPath, "restart"}- if service != "" {- args = append(args, service)- }-- cmd := exec.CommandContext(ctx, "docker", args...)- output, err := cmd.CombinedOutput()- if err != nil {- return string(output), fmt.Errorf("compose restart failed: %w: %s", err, output)- }-- return string(output), nil-}--// ComposePull pulls images for a compose project-func (c *Client) ComposePull(ctx context.Context, projectPath, service string) (string, error) {- if err := validateProjectPath(projectPath); err != nil {- return "", err- }-- args := []string{"compose", "-f", projectPath, "pull"}- if service != "" {- args = append(args, service)- }-- cmd := exec.CommandContext(ctx, "docker", args...)- output, err := cmd.CombinedOutput()- if err != nil {- return string(output), fmt.Errorf("compose pull failed: %w: %s", err, output)- }-- return string(output), nil-}--// validateProjectPath is a syntactic sanity check on a compose project path-// (non-empty, absolute, no `..` traversal). It is NOT the authorization-// boundary: the real restriction to the operator-configured roots is the-// symlink-resolved allowlist in the agent layer-// (agent.validateFileAccess → resolveSymlinkPath/pathWithinAllowedRoot),-// which every compose handler in internal/agent/agent.go runs on the-// project_path BEFORE calling these Compose* methods. Any NEW caller of the-// Compose* API must perform that AllowedPaths check first — this function-// alone does not confine paths to AllowedPaths.-func validateProjectPath(projectPath string) error {- if projectPath == "" {- return fmt.Errorf("project path is required")- }-- // Check for path traversal attempts- if strings.Contains(projectPath, "..") {- return fmt.Errorf("invalid project path: path traversal not allowed")- }-- // Check if path is absolute- if !strings.HasPrefix(projectPath, "/") {- return fmt.Errorf("invalid project path: must be absolute path")- }-- return nil-}-diff --git a/agent/internal/events/store.go b/agent/internal/events/store.godeleted file mode 100644index 8f1a4c3e..00000000--- a/agent/internal/events/store.go+++ /dev/null@@ -1,191 +0,0 @@-// Package events provides a small append-only event log that powers the-// agent console's Activity tab. Events are higher-signal than raw log lines:-// "Service started", "Connection lost (timeout)", "Restart requested by-// tray". The agent process owns the store; producers across the codebase-// (websocket, lifecycle, IPC handlers) push to it via Append; the IPC server-// exposes the snapshot to the desktop UI.-//-// Persistence is a single JSON file rewritten on each Append. That sounds-// wasteful but the buffer is tiny (~200 events, one or two KB) and these-// events don't fire often enough for the rewrite cost to matter. Trade-off:-// crash-during-write is a non-issue since each rewrite is the entire state.-package events--import (- "encoding/json"- "os"- "path/filepath"- "sync"- "time"-)--// Kind is a stable identifier for the event type. Frontends use it to pick-// icons and colours; storage uses it for filtering.-type Kind string--const (- KindServiceStart Kind = "service_start"- KindServiceStop Kind = "service_stop"- KindRestartRequested Kind = "restart_requested"- KindWSConnected Kind = "ws_connected"- KindWSDisconnected Kind = "ws_disconnected"- KindWSReconnecting Kind = "ws_reconnecting"- KindAuthFailed Kind = "auth_failed"- KindError Kind = "error"- KindInfo Kind = "info"-)--// Severity controls visual emphasis in the UI. Use sparingly — Info is the-// default; Warn for transient issues; Error for things the user should act on.-type Severity string--const (- SeverityInfo Severity = "info"- SeverityWarn Severity = "warn"- SeverityError Severity = "error"-)--// Event is one entry in the activity log. Keep the JSON keys short and-// stable — they're a public-ish wire format consumed by the desktop UI.-type Event struct {- ID int64 `json:"id"`- Time int64 `json:"t"`- Kind Kind `json:"kind"`- Severity Severity `json:"sev"`- Message string `json:"msg"`- Metadata map[string]interface{} `json:"meta,omitempty"`-}--// Store is a bounded ring buffer of events with optional disk persistence.-// Methods are safe for concurrent callers.-type Store struct {- mu sync.Mutex- events []Event- cap int- nextID int64- persist string // file path; empty = in-memory only-}--// NewStore returns a new event store with the given capacity. If-// persistPath is non-empty, the store loads events from that file on-// startup and rewrites it on every Append. Pass "" to skip persistence-// (e.g. tests).-func NewStore(capacity int, persistPath string) *Store {- s := &Store{- events: make([]Event, 0, capacity),- cap: capacity,- persist: persistPath,- }- s.load()- return s-}--// Append records an event. Caller doesn't need to set ID or Time — the-// store assigns them. Persistence errors are swallowed (best-effort) since-// the in-memory buffer is the source of truth at runtime.-func (s *Store) Append(kind Kind, sev Severity, message string, meta map[string]interface{}) Event {- s.mu.Lock()- defer s.mu.Unlock()-- s.nextID++- ev := Event{- ID: s.nextID,- Time: time.Now().UnixMilli(),- Kind: kind,- Severity: sev,- Message: message,- Metadata: meta,- }-- if len(s.events) >= s.cap {- copy(s.events, s.events[1:])- s.events = s.events[:len(s.events)-1]- }- s.events = append(s.events, ev)-- s.saveLocked()- return ev-}--// Snapshot returns a copy of all events in chronological order. Optional-// since=unix-ms returns only events newer than that; pass 0 to get all.-func (s *Store) Snapshot(since int64) []Event {- s.mu.Lock()- defer s.mu.Unlock()-- out := make([]Event, 0, len(s.events))- for _, ev := range s.events {- if ev.Time > since {- out = append(out, ev)- }- }- return out-}--// Clear drops all events and rewrites the persisted file.-func (s *Store) Clear() {- s.mu.Lock()- defer s.mu.Unlock()- s.events = s.events[:0]- s.saveLocked()-}--// load reads persisted events from disk. Silent on missing file (first run)-// and swallows malformed-file errors so a corrupt persist file can never-// take down the agent — we'd rather lose history than fail to start.-func (s *Store) load() {- if s.persist == "" {- return- }- data, err := os.ReadFile(s.persist)- if err != nil {- return- }- var events []Event- if err := json.Unmarshal(data, &events); err != nil {- return- }- if len(events) > s.cap {- events = events[len(events)-s.cap:]- }- s.events = events- for _, ev := range events {- if ev.ID > s.nextID {- s.nextID = ev.ID- }- }-}--// saveLocked persists the current buffer. Must be called with s.mu held.-// Writes to a tempfile and renames so a partial write can't corrupt the-// canonical file.-func (s *Store) saveLocked() {- if s.persist == "" {- return- }- dir := filepath.Dir(s.persist)- if err := os.MkdirAll(dir, 0700); err != nil {- return- }- tmp, err := os.CreateTemp(dir, "events-*.tmp")- if err != nil {- return- }- enc := json.NewEncoder(tmp)- if err := enc.Encode(s.events); err != nil {- tmp.Close()- os.Remove(tmp.Name())- return- }- tmp.Close()- _ = os.Rename(tmp.Name(), s.persist)-}--// DefaultPath returns the canonical event-log file location next to the-// agent's other data files.-func DefaultPath(dataDir string) string {- if dataDir == "" {- return ""- }- return filepath.Join(dataDir, "events.json")-}diff --git a/agent/internal/gui/gui.go b/agent/internal/gui/gui.godeleted file mode 100644index f8ea4ea0..00000000--- a/agent/internal/gui/gui.go+++ /dev/null@@ -1,123 +0,0 @@-// Package gui implements the agent's GUI/desktop capability bridge.-//-// This is a deliberately small SDK that any panel-side extension can lean on-// without forcing the agent to fork: the agent owns *how* a screenshot is-// captured on each platform, and exposes a stable JSON contract through the-// gui:screenshot and gui:capabilities actions. Plugins (e.g. serverkit-gui)-// only deal with the contract — they never ship binaries to the agent.-//-// Implementation note: the platform paths shell out to OS-built-in tools-// (PowerShell's System.Drawing on Windows, scrot/grim/import on Linux). This-// keeps the agent dep-free and dodges cgo, at the cost of ~200ms per frame on-// Windows. A native fast path (kbinani/screenshot) is a future optimization;-// at the 1–2 fps the streaming UI runs at, shell-out is comfortably fast-// enough.-package gui--import (- "context"- "encoding/json"- "fmt"-- "github.com/serverkit/agent/internal/logger"-)--// Capabilities describes what the host can do for desktop capture.-type Capabilities struct {- // Capability is one of: "windows-gdi", "linux-x11", "linux-wayland",- // "macos-quartz", "none". Plugins gate behavior on this string.- Capability string `json:"capability"`-- // Resolution is "WxH" of the primary display, when known.- Resolution string `json:"resolution,omitempty"`-- // MaxFPS is what the agent recommends as a sane upper bound. The- // panel may run slower; it should not run faster.- MaxFPS int `json:"max_fps"`-- // SyntheticFallback hints to the panel that no real capture is- // possible and it should render its synthetic UI mode.- SyntheticFallback bool `json:"synthetic_fallback"`-- // Reason explains why Capability is "none", when applicable.- Reason string `json:"reason,omitempty"`-}--// ScreenshotParams are the per-frame knobs the panel can dial.-type ScreenshotParams struct {- // Scale 0 < s <= 1 — server-side downscale before encoding.- Scale float64 `json:"scale"`- // Quality 10..95 for JPEG; ignored for PNG.- Quality int `json:"quality"`- // Format "jpeg" or "png". JPEG is smaller; PNG preserves text.- Format string `json:"format"`-}--// Frame is what we hand back. ImageBase64 is the encoded image; the rest is-// metadata so the UI can size and timestamp the frame without decoding.-type Frame struct {- ImageBase64 string `json:"image_base64"`- Format string `json:"format"`- Width int `json:"width"`- Height int `json:"height"`- CapturedAt string `json:"captured_at"`-}--// SDK is the agent-side capability bridge. One instance per agent process.-type SDK struct {- log *logger.Logger-}--// New returns an initialized SDK.-func New(log *logger.Logger) *SDK {- return &SDK{log: log}-}--// HandleCapabilities — wired to protocol.ActionGUICapabilities.-func (s *SDK) HandleCapabilities(_ context.Context, _ json.RawMessage) (interface{}, error) {- c, err := detectCapabilities()- if err != nil {- // Capability detection isn't supposed to fail loudly; downgrade- // to a synthetic-fallback response so the UI degrades gracefully.- return Capabilities{- Capability: "none",- SyntheticFallback: true,- Reason: err.Error(),- }, nil- }- return c, nil-}--// HandleScreenshot — wired to protocol.ActionGUIScreenshot.-func (s *SDK) HandleScreenshot(ctx context.Context, raw json.RawMessage) (interface{}, error) {- params := ScreenshotParams{Scale: 0.75, Quality: 70, Format: "jpeg"}- if len(raw) > 0 {- if err := json.Unmarshal(raw, ¶ms); err != nil {- return nil, fmt.Errorf("invalid params: %w", err)- }- }- if params.Scale <= 0 || params.Scale > 1 {- params.Scale = 0.75- }- if params.Quality < 10 || params.Quality > 95 {- params.Quality = 70- }- if params.Format != "png" && params.Format != "jpeg" {- params.Format = "jpeg"- }-- frame, err := captureFrame(ctx, params)- if err != nil {- return nil, fmt.Errorf("capture: %w", err)- }-- if s.log != nil {- s.log.Info("gui:screenshot",- "format", frame.Format,- "width", frame.Width,- "height", frame.Height,- "bytes_b64", len(frame.ImageBase64),- )- }- return frame, nil-}diff --git a/agent/internal/gui/gui_linux.go b/agent/internal/gui/gui_linux.godeleted file mode 100644index 14427021..00000000--- a/agent/internal/gui/gui_linux.go+++ /dev/null@@ -1,191 +0,0 @@-//go:build linux--package gui--import (- "bytes"- "context"- "encoding/base64"- "errors"- "fmt"- "image"- "image/jpeg"- "image/png"- "os"- "os/exec"- "strconv"- "strings"- "time"-)--func detectCapabilities() (Capabilities, error) {- if os.Getenv("WAYLAND_DISPLAY") != "" {- if hasOnPath("grim") {- return Capabilities{- Capability: "linux-wayland",- MaxFPS: 3,- SyntheticFallback: false,- }, nil- }- }- if os.Getenv("DISPLAY") != "" {- for _, bin := range []string{"scrot", "import", "gnome-screenshot"} {- if hasOnPath(bin) {- return Capabilities{- Capability: "linux-x11",- MaxFPS: 3,- SyntheticFallback: false,- }, nil- }- }- return Capabilities{- Capability: "none",- SyntheticFallback: true,- Reason: "X11 detected but no scrot/import/gnome-screenshot installed",- }, nil- }- return Capabilities{- Capability: "none",- SyntheticFallback: true,- Reason: "no display server (headless)",- }, nil-}--func captureFrame(ctx context.Context, p ScreenshotParams) (*Frame, error) {- raw, capturedFormat, err := captureRawPNG(ctx)- if err != nil {- return nil, err- }-- // Decode → optionally downscale → re-encode to requested format.- // We pay the decode cost so we can guarantee Scale + Quality work- // regardless of which capture tool we used.- src, _, err := image.Decode(bytes.NewReader(raw))- if err != nil {- // Some tools occasionally emit non-PNG; if the panel asked for- // the same format we already have, pass it through verbatim.- if capturedFormat == p.Format {- return &Frame{- ImageBase64: base64.StdEncoding.EncodeToString(raw),- Format: capturedFormat,- CapturedAt: time.Now().UTC().Format(time.RFC3339),- }, nil- }- return nil, fmt.Errorf("decode capture: %w", err)- }-- if p.Scale > 0 && p.Scale < 1.0 {- src = nearestScale(src, p.Scale)- }-- var buf bytes.Buffer- switch p.Format {- case "png":- if err := png.Encode(&buf, src); err != nil {- return nil, fmt.Errorf("png encode: %w", err)- }- default:- if err := jpeg.Encode(&buf, src, &jpeg.Options{Quality: p.Quality}); err != nil {- return nil, fmt.Errorf("jpeg encode: %w", err)- }- }-- b := src.Bounds()- return &Frame{- ImageBase64: base64.StdEncoding.EncodeToString(buf.Bytes()),- Format: p.Format,- Width: b.Dx(),- Height: b.Dy(),- CapturedAt: time.Now().UTC().Format(time.RFC3339),- }, nil-}--// captureRawPNG returns raw bytes from whichever capture tool is available.-// Format is always "png" today, but returned explicitly to leave room for-// JPEG-native captures in the future.-func captureRawPNG(ctx context.Context) ([]byte, string, error) {- switch {- case os.Getenv("WAYLAND_DISPLAY") != "" && hasOnPath("grim"):- out, err := run(ctx, "grim", "-")- return out, "png", err-- case hasOnPath("scrot"):- // scrot can write PNG to a file; it can't write to stdout in- // every version, so we take the file route via /dev/stdout- // where supported.- out, err := run(ctx, "scrot", "-o", "/dev/stdout")- if err != nil {- // Older scrot — fall back to a temp file.- return scrotViaTemp(ctx)- }- return out, "png", nil-- case hasOnPath("import"):- out, err := run(ctx, "import", "-window", "root", "png:-")- return out, "png", err- }- return nil, "", errors.New("no screenshot tool on PATH (install scrot, grim, or imagemagick)")-}--func scrotViaTemp(ctx context.Context) ([]byte, string, error) {- f, err := os.CreateTemp("", "sk-scrot-*.png")- if err != nil {- return nil, "", err- }- path := f.Name()- f.Close()- defer os.Remove(path)-- if _, err := run(ctx, "scrot", "-o", path); err != nil {- return nil, "", err- }- data, err := os.ReadFile(path)- if err != nil {- return nil, "", err- }- return data, "png", nil-}--func run(ctx context.Context, name string, args ...string) ([]byte, error) {- cctx, cancel := context.WithTimeout(ctx, 10*time.Second)- defer cancel()- cmd := exec.CommandContext(cctx, name, args...)- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr- if err := cmd.Run(); err != nil {- return nil, fmt.Errorf("%s: %w (%s)", name, err, strings.TrimSpace(stderr.String()))- }- return stdout.Bytes(), nil-}--func hasOnPath(name string) bool {- _, err := exec.LookPath(name)- return err == nil-}--// nearestScale is a stdlib-only scaler. Quality is fine for streaming-// previews at 50–75%; we don't need bilinear/bicubic here.-func nearestScale(src image.Image, scale float64) image.Image {- b := src.Bounds()- dstW := int(float64(b.Dx()) * scale)- dstH := int(float64(b.Dy()) * scale)- if dstW < 1 {- dstW = 1- }- if dstH < 1 {- dstH = 1- }- dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))- for y := 0; y < dstH; y++ {- sy := b.Min.Y + int(float64(y)/scale)- for x := 0; x < dstW; x++ {- sx := b.Min.X + int(float64(x)/scale)- dst.Set(x, y, src.At(sx, sy))- }- }- return dst-}--// Avoid an unused-import warning when strconv isn't used in a build variant.-var _ = strconv.Itoadiff --git a/agent/internal/gui/gui_other.go b/agent/internal/gui/gui_other.godeleted file mode 100644index 26e3116e..00000000--- a/agent/internal/gui/gui_other.go+++ /dev/null@@ -1,23 +0,0 @@-//go:build !windows && !linux--package gui--import "context"--func detectCapabilities() (Capabilities, error) {- return Capabilities{- Capability: "none",- SyntheticFallback: true,- Reason: "platform not yet supported by gui SDK",- }, nil-}--func captureFrame(_ context.Context, _ ScreenshotParams) (*Frame, error) {- return nil, errNotImplemented-}--var errNotImplemented = &platformErr{"gui capture not implemented on this platform"}--type platformErr struct{ msg string }--func (e *platformErr) Error() string { return e.msg }diff --git a/agent/internal/gui/gui_windows.go b/agent/internal/gui/gui_windows.godeleted file mode 100644index e4509555..00000000--- a/agent/internal/gui/gui_windows.go+++ /dev/null@@ -1,174 +0,0 @@-//go:build windows--package gui--import (- "bytes"- "context"- "encoding/base64"- "errors"- "fmt"- "os/exec"- "strconv"- "strings"- "time"-)--// PowerShell snippet: capture the primary screen with System.Drawing,-// optionally downscale, encode to JPEG/PNG, base64-emit to stdout. We-// pass scale and quality as args; format is selected by name.-//-// Why PowerShell instead of a Go-native call: System.Drawing ships in every-// Windows install since the dawn of time, and shelling out keeps the agent-// free of GDI cgo wrappers. Slow, but at 1–2 fps it's invisible.-const psCaptureScript = `-param(- [double]$Scale = 0.75,- [int]$Quality = 70,- [string]$Format = "jpeg"-)-$ErrorActionPreference = "Stop"-Add-Type -AssemblyName System.Drawing-Add-Type -AssemblyName System.Windows.Forms--$bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds-$srcW = $bounds.Width-$srcH = $bounds.Height--$bmp = New-Object System.Drawing.Bitmap $srcW, $srcH-$g = [System.Drawing.Graphics]::FromImage($bmp)-$g.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.Size)--if ($Scale -lt 1.0 -and $Scale -gt 0) {- $dstW = [int]([Math]::Round($srcW * $Scale))- $dstH = [int]([Math]::Round($srcH * $Scale))- $resized = New-Object System.Drawing.Bitmap $dstW, $dstH- $rg = [System.Drawing.Graphics]::FromImage($resized)- $rg.InterpolationMode = "HighQualityBicubic"- $rg.DrawImage($bmp, 0, 0, $dstW, $dstH)- $rg.Dispose()- $bmp.Dispose()- $bmp = $resized-}--$ms = New-Object System.IO.MemoryStream-if ($Format -eq "png") {- $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)-} else {- $codecs = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()- $jpegCodec = $codecs | Where-Object { $_.MimeType -eq "image/jpeg" } | Select-Object -First 1- $params = New-Object System.Drawing.Imaging.EncoderParameters 1- $params.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality), [long]$Quality- $bmp.Save($ms, $jpegCodec, $params)-}--$bytes = $ms.ToArray()-$ms.Dispose()-$bmp.Dispose()--# Emit a single line: WIDTH HEIGHT BASE64-[Console]::Out.Write("$($bmp.Width) $($bmp.Height) ")-[Console]::Out.WriteLine([Convert]::ToBase64String($bytes))-`--func detectCapabilities() (Capabilities, error) {- res, err := runPowerShell(context.Background(), `-$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds 2>$null-if ($b) { Write-Output ("{0}x{1}" -f $b.Width, $b.Height) }-`, 5*time.Second)- if err != nil || strings.TrimSpace(res) == "" {- // Most common cause: agent running as a Windows service in- // session 0 with no logged-in user. The bitmap will exist but- // we won't capture anything visible.- return Capabilities{- Capability: "none",- SyntheticFallback: true,- Reason: "no active user session",- }, nil- }- return Capabilities{- Capability: "windows-gdi",- Resolution: strings.TrimSpace(res),- MaxFPS: 5,- SyntheticFallback: false,- }, nil-}--func captureFrame(ctx context.Context, p ScreenshotParams) (*Frame, error) {- args := []string{- "-Scale", strconv.FormatFloat(p.Scale, 'f', 3, 64),- "-Quality", strconv.Itoa(p.Quality),- "-Format", p.Format,- }- out, err := runPowerShellWithArgs(ctx, psCaptureScript, args, 15*time.Second)- if err != nil {- return nil, err- }- // stdout is "WIDTH HEIGHT BASE64\n"- line := strings.TrimSpace(out)- parts := strings.SplitN(line, " ", 3)- if len(parts) != 3 {- return nil, fmt.Errorf("malformed capture output: %q", truncate(line, 120))- }- w, err1 := strconv.Atoi(parts[0])- h, err2 := strconv.Atoi(parts[1])- if err1 != nil || err2 != nil {- return nil, errors.New("malformed dimensions")- }- // Sanity-check the base64 payload but don't decode it; the panel does that.- if _, err := base64.StdEncoding.DecodeString(parts[2][:min(64, len(parts[2]))]); err != nil {- return nil, fmt.Errorf("invalid base64 prefix: %w", err)- }- return &Frame{- ImageBase64: parts[2],- Format: p.Format,- Width: w,- Height: h,- CapturedAt: time.Now().UTC().Format(time.RFC3339),- }, nil-}--func runPowerShell(ctx context.Context, script string, timeout time.Duration) (string, error) {- return runPowerShellWithArgs(ctx, script, nil, timeout)-}--func runPowerShellWithArgs(ctx context.Context, script string, args []string, timeout time.Duration) (string, error) {- cctx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()-- bin := "powershell"- if p, err := exec.LookPath("pwsh"); err == nil {- bin = p- }-- all := []string{- "-NoProfile", "-NonInteractive",- "-ExecutionPolicy", "Bypass",- "-Command", script,- }- all = append(all, args...)-- cmd := exec.CommandContext(cctx, bin, all...)- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr-- if err := cmd.Run(); err != nil {- return "", fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String()))- }- return stdout.String(), nil-}--func truncate(s string, n int) string {- if len(s) <= n {- return s- }- return s[:n] + "…"-}--func min(a, b int) int {- if a < b {- return a- }- return b-}diff --git a/agent/internal/ipc/auth_test.go b/agent/internal/ipc/auth_test.godeleted file mode 100644index 5b696c5c..00000000--- a/agent/internal/ipc/auth_test.go+++ /dev/null@@ -1,142 +0,0 @@-package ipc--import (- "net/http"- "net/http/httptest"- "os"- "path/filepath"- "testing"-)--func TestBearerToken(t *testing.T) {- cases := []struct {- name string- header string- query string- want string- }{- {"no auth header, no query", "", "", ""},- {"valid bearer", "Bearer abc123", "", "abc123"},- {"case-insensitive scheme", "bearer abc123", "", "abc123"},- {"trims whitespace", "Bearer abc123 ", "", "abc123"},- {"non-bearer scheme", "Basic abc123", "", ""},- {"query string fallback", "", "tok-from-query", "tok-from-query"},- {"header wins over query", "Bearer header-tok", "query-tok", "header-tok"},- }- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- r := httptest.NewRequest(http.MethodGet, "/x", nil)- if tc.header != "" {- r.Header.Set("Authorization", tc.header)- }- if tc.query != "" {- q := r.URL.Query()- q.Set("token", tc.query)- r.URL.RawQuery = q.Encode()- }- if got := bearerToken(r); got != tc.want {- t.Fatalf("bearerToken: got %q, want %q", got, tc.want)- }- })- }-}--func TestAuthMiddleware(t *testing.T) {- const tok = "secret-token-value"- inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- _, _ = w.Write([]byte("ok"))- })- mw := authMiddleware(tok, inner)-- t.Run("health is exempt", func(t *testing.T) {- r := httptest.NewRequest(http.MethodGet, "/health", nil)- w := httptest.NewRecorder()- mw.ServeHTTP(w, r)- if w.Code != http.StatusOK {- t.Fatalf("/health blocked: got %d", w.Code)- }- })-- t.Run("missing token rejected", func(t *testing.T) {- r := httptest.NewRequest(http.MethodGet, "/status", nil)- w := httptest.NewRecorder()- mw.ServeHTTP(w, r)- if w.Code != http.StatusUnauthorized {- t.Fatalf("expected 401, got %d", w.Code)- }- })-- t.Run("wrong token rejected", func(t *testing.T) {- r := httptest.NewRequest(http.MethodGet, "/status", nil)- r.Header.Set("Authorization", "Bearer wrong-token")- w := httptest.NewRecorder()- mw.ServeHTTP(w, r)- if w.Code != http.StatusUnauthorized {- t.Fatalf("expected 401, got %d", w.Code)- }- })-- t.Run("correct token allowed", func(t *testing.T) {- r := httptest.NewRequest(http.MethodGet, "/status", nil)- r.Header.Set("Authorization", "Bearer "+tok)- w := httptest.NewRecorder()- mw.ServeHTTP(w, r)- if w.Code != http.StatusOK {- t.Fatalf("expected 200, got %d", w.Code)- }- })-- t.Run("OPTIONS bypasses auth (CORS preflight)", func(t *testing.T) {- r := httptest.NewRequest(http.MethodOptions, "/status", nil)- w := httptest.NewRecorder()- mw.ServeHTTP(w, r)- if w.Code != http.StatusOK {- t.Fatalf("CORS preflight blocked: got %d", w.Code)- }- })-}--func TestLoadOrGenerateToken(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "ipc.token")-- // First call creates the file with a fresh token.- tok1, err := loadOrGenerateToken(path)- if err != nil {- t.Fatalf("first generate: %v", err)- }- if len(tok1) < 32 {- t.Fatalf("token too short: %q", tok1)- }-- // Second call reuses the same token (so a tray app already running- // keeps working through agent restarts).- tok2, err := loadOrGenerateToken(path)- if err != nil {- t.Fatalf("second load: %v", err)- }- if tok1 != tok2 {- t.Fatalf("token regenerated unexpectedly: %q vs %q", tok1, tok2)- }-}--func TestLoadOrGenerateTokenRegeneratesOnTooShort(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "ipc.token")-- // Pre-seed with a short value (eg. truncated file). loadOrGenerateToken- // should treat it as corrupted and write a fresh one rather than honour- // the stub credential.- if err := os.WriteFile(path, []byte("short"), 0o600); err != nil {- t.Fatal(err)- }-- tok, err := loadOrGenerateToken(path)- if err != nil {- t.Fatalf("regen: %v", err)- }- if tok == "short" || len(tok) < 32 {- t.Fatalf("expected regenerated token, got %q", tok)- }-}diff --git a/agent/internal/ipc/handlers.go b/agent/internal/ipc/handlers.godeleted file mode 100644index e5aabaab..00000000--- a/agent/internal/ipc/handlers.go+++ /dev/null@@ -1,182 +0,0 @@-package ipc--import (- "encoding/json"- "net/http"- "strconv"-- "github.com/serverkit/agent/internal/logger"-)--// Handlers contains the HTTP handlers for the IPC API-type Handlers struct {- provider StatusProvider- log *logger.Logger-}--// NewHandlers creates a new handlers instance-func NewHandlers(provider StatusProvider, log *logger.Logger) *Handlers {- return &Handlers{- provider: provider,- log: log,- }-}--// HandleStatus returns the current agent status-func (h *Handlers) HandleStatus(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- status := h.provider.GetStatus()- h.writeJSON(w, status)-}--// HandleMetrics returns detailed system metrics-func (h *Handlers) HandleMetrics(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- metrics := h.provider.GetDetailedMetrics()- if metrics == nil {- h.writeJSON(w, map[string]string{"error": "metrics not available"})- return- }-- h.writeJSON(w, metrics)-}--// HandleMetricsHistory returns the recent CPU/memory ring buffer used by-// the agent console to render sparklines. The buffer is bounded (5 minutes-// at 1 Hz) so the response is always tiny.-func (h *Handlers) HandleMetricsHistory(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- samples := h.provider.GetMetricsHistory()- h.writeJSON(w, map[string]interface{}{- "samples": samples,- })-}--// HandleLogsClear rotates the agent log so the live tail in the desktop-// console starts fresh. Existing entries move to a timestamped backup file-// (lumberjack handles the rename) and the agent continues writing to a-// brand-new agent.log without re-opening or interrupting any goroutine.-func (h *Handlers) HandleLogsClear(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- if err := h.provider.ClearLogs(); err != nil {- h.writeJSON(w, map[string]interface{}{- "success": false,- "error": err.Error(),- })- return- }- h.writeJSON(w, map[string]bool{"success": true})-}--// HandleEvents returns the agent's recent activity events. Optional `since`-// query param (unix milliseconds) makes the endpoint cheap to poll: clients-// pass the timestamp of the most recent event they've seen and only get-// new ones back.-func (h *Handlers) HandleEvents(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }- var since int64- if s := r.URL.Query().Get("since"); s != "" {- if parsed, err := strconv.ParseInt(s, 10, 64); err == nil {- since = parsed- }- }- evs := h.provider.GetEvents(since)- h.writeJSON(w, map[string]interface{}{- "events": evs,- })-}--// HandleConnection returns WebSocket connection information-func (h *Handlers) HandleConnection(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- info := h.provider.GetConnectionInfo()- h.writeJSON(w, info)-}--// HandleLogs returns recent log lines-func (h *Handlers) HandleLogs(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- // Parse lines parameter (default 50)- lines := 50- if l := r.URL.Query().Get("lines"); l != "" {- if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 1000 {- lines = parsed- }- }-- logs := h.provider.GetRecentLogs(lines)- h.writeJSON(w, map[string]interface{}{- "lines": logs,- "count": len(logs),- })-}--// HandleRestart triggers a graceful agent restart-func (h *Handlers) HandleRestart(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- h.log.Info("Restart requested via IPC")-- if err := h.provider.Restart(); err != nil {- h.writeJSON(w, map[string]interface{}{- "success": false,- "error": err.Error(),- })- return- }-- h.writeJSON(w, map[string]interface{}{- "success": true,- "message": "Restart initiated",- })-}--// HandleHealth returns a simple health check response-func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return- }-- status := h.provider.GetStatus()- h.writeJSON(w, map[string]interface{}{- "healthy": status.Running,- "connected": status.Connected,- })-}--// writeJSON writes a JSON response-func (h *Handlers) writeJSON(w http.ResponseWriter, data interface{}) {- w.Header().Set("Content-Type", "application/json")- if err := json.NewEncoder(w).Encode(data); err != nil {- h.log.Warn("Failed to encode JSON response", "error", err)- }-}diff --git a/agent/internal/ipc/server.go b/agent/internal/ipc/server.godeleted file mode 100644index 1f0dfef3..00000000--- a/agent/internal/ipc/server.go+++ /dev/null@@ -1,359 +0,0 @@-package ipc--import (- "context"- "crypto/rand"- "crypto/subtle"- "encoding/hex"- "fmt"- "net"- "net/http"- "os"- "path/filepath"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/events"- "github.com/serverkit/agent/internal/logger"-)--// StatusProvider provides agent status information-type StatusProvider interface {- GetStatus() AgentStatus- GetDetailedMetrics() *DetailedMetrics- GetMetricsHistory() []MetricSample- GetConnectionInfo() ConnectionInfo- GetRecentLogs(lines int) []string- ClearLogs() error- GetEvents(since int64) []events.Event- Restart() error-}--// AgentStatus represents the current agent status-type AgentStatus struct {- Running bool `json:"running"`- Connected bool `json:"connected"`- Registered bool `json:"registered"`- AgentID string `json:"agent_id"`- AgentName string `json:"agent_name"`- ServerURL string `json:"server_url"`- Uptime int64 `json:"uptime_seconds"`- Version string `json:"version"`- // Transport reports which link the agent is on right now: "ws" for- // the primary Socket.IO link, "poll" when WS-incompatible tunnels- // forced a fallback to the REST polling transport. UI uses this to- // surface a "limited mode" badge — streams are unavailable in poll.- Transport string `json:"transport,omitempty"`- CPUPercent float64 `json:"cpu_percent"`- MemPercent float64 `json:"mem_percent"`- DiskPercent float64 `json:"disk_percent"`-}--// DetailedMetrics contains detailed system metrics-type DetailedMetrics struct {- CPU CPUMetrics `json:"cpu"`- Memory MemoryMetrics `json:"memory"`- Disk DiskMetrics `json:"disk"`- Network NetworkMetrics `json:"network"`- Timestamp int64 `json:"timestamp"`-}--// CPUMetrics contains CPU information-type CPUMetrics struct {- UsagePercent float64 `json:"usage_percent"`- PerCPU []float64 `json:"per_cpu,omitempty"`- Cores int `json:"cores"`-}--// MemoryMetrics contains memory information-type MemoryMetrics struct {- Total uint64 `json:"total"`- Used uint64 `json:"used"`- Free uint64 `json:"free"`- UsagePercent float64 `json:"usage_percent"`-}--// DiskMetrics contains disk information-type DiskMetrics struct {- Total uint64 `json:"total"`- Used uint64 `json:"used"`- Free uint64 `json:"free"`- UsagePercent float64 `json:"usage_percent"`-}--// NetworkMetrics contains network information-type NetworkMetrics struct {- BytesSent uint64 `json:"bytes_sent"`- BytesRecv uint64 `json:"bytes_recv"`- PacketsSent uint64 `json:"packets_sent"`- PacketsRecv uint64 `json:"packets_recv"`-}--// MetricSample is one entry in the agent's CPU/memory ring buffer used by-// the desktop console to render sparklines. Timestamp is unix milliseconds.-type MetricSample struct {- Timestamp int64 `json:"t"`- CPU float64 `json:"cpu"`- Mem float64 `json:"mem"`-}--// ConnectionInfo contains WebSocket connection details-type ConnectionInfo struct {- Connected bool `json:"connected"`- ServerURL string `json:"server_url"`- ReconnectCount int `json:"reconnect_count"`- LastConnected int64 `json:"last_connected,omitempty"`- SessionExpires int64 `json:"session_expires,omitempty"`-}--// Server is the IPC HTTP server for tray app communication-type Server struct {- cfg config.IPCConfig- log *logger.Logger- server *http.Server- provider StatusProvider- startTime time.Time- // token is the bearer credential that gates every endpoint except- // /health. Loaded from disk if present (so a tray app already- // running survives an agent restart) or generated on first start.- // Localhost binding alone isn't enough — any local process on the- // box (browser tab, malicious npm postinstall, low-priv service- // account) could otherwise read panel URL / agent ID / logs and- // trigger /restart without authorisation.- token string-}--// NewServer creates a new IPC server-func NewServer(cfg config.IPCConfig, log *logger.Logger, provider StatusProvider) *Server {- return &Server{- cfg: cfg,- log: log.WithComponent("ipc"),- provider: provider,- startTime: time.Now(),- }-}--// Start starts the IPC HTTP server-func (s *Server) Start(ctx context.Context) error {- if !s.cfg.Enabled {- s.log.Info("IPC server disabled")- return nil- }-- // Load or generate the bearer token before binding the listener.- // Token failures are fatal — running the IPC API without auth- // would expose /restart and /logs to any local process.- //- // SERVERKIT_IPC_NO_AUTH=true disables the bearer check entirely.- // This exists for dev environments where the desktop console- // bundle, asset server, and agent service can't always be- // rebuilt in lockstep — the auth requires all three to ship- // together. Logged at WARN every startup so it can't be set- // silently in production.- noAuth := os.Getenv("SERVERKIT_IPC_NO_AUTH") == "true"- if noAuth {- s.log.Warn("SERVERKIT_IPC_NO_AUTH=true: IPC bearer-token check is DISABLED; only use this for development")- } else {- tok, err := loadOrGenerateToken(config.IPCTokenPath())- if err != nil {- return fmt.Errorf("ipc token: %w", err)- }- s.token = tok- }-- mux := http.NewServeMux()-- // Register handlers- handlers := NewHandlers(s.provider, s.log)- mux.HandleFunc("/status", handlers.HandleStatus)- mux.HandleFunc("/metrics", handlers.HandleMetrics)- mux.HandleFunc("/metrics/history", handlers.HandleMetricsHistory)- mux.HandleFunc("/events", handlers.HandleEvents)- mux.HandleFunc("/logs/clear", handlers.HandleLogsClear)- mux.HandleFunc("/connection", handlers.HandleConnection)- mux.HandleFunc("/logs", handlers.HandleLogs)- mux.HandleFunc("/restart", handlers.HandleRestart)- mux.HandleFunc("/health", handlers.HandleHealth)-- addr := fmt.Sprintf("%s:%d", s.cfg.Address, s.cfg.Port)-- // Verify we're only binding to localhost for security- host, _, err := net.SplitHostPort(addr)- if err != nil || (host != "127.0.0.1" && host != "localhost" && host != "::1") {- s.log.Warn("IPC server can only bind to localhost, forcing 127.0.0.1")- addr = fmt.Sprintf("127.0.0.1:%d", s.cfg.Port)- }-- var handler http.Handler = mux- if !noAuth {- handler = authMiddleware(s.token, handler)- }- s.server = &http.Server{- Addr: addr,- Handler: corsMiddleware(handler),- ReadTimeout: 5 * time.Second,- WriteTimeout: 10 * time.Second,- IdleTimeout: 60 * time.Second,- }-- s.log.Info("Starting IPC server", "address", addr)-- // Start server in goroutine- errCh := make(chan error, 1)- go func() {- if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {- errCh <- err- }- }()-- // Check for immediate startup errors- select {- case err := <-errCh:- return fmt.Errorf("IPC server failed to start: %w", err)- case <-time.After(100 * time.Millisecond):- // Server started successfully- }-- // Wait for context cancellation- go func() {- <-ctx.Done()- s.Stop()- }()-- return nil-}--// Stop gracefully stops the IPC server-func (s *Server) Stop() error {- if s.server == nil {- return nil- }-- s.log.Info("Stopping IPC server")-- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()-- return s.server.Shutdown(ctx)-}--// corsMiddleware adds CORS headers for local development.-//-// The desktop console's React UI runs on the asset server (127.0.0.1:<random>)-// and calls the IPC server (127.0.0.1:19780) — different ports means CORS-// applies. Authorization must be in Allow-Headers, otherwise the browser-// preflight refuses to forward the bearer token and every IPC request-// arrives unauthenticated → 401 storm. The previous list (just Content-Type)-// was OK before IPC auth existed; with auth required, it silently broke-// the entire desktop console.-func corsMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Only allow requests from localhost- origin := r.Header.Get("Origin")- if origin == "" || isLocalhost(origin) {- w.Header().Set("Access-Control-Allow-Origin", origin)- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")- w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")- }-- if r.Method == "OPTIONS" {- w.WriteHeader(http.StatusOK)- return- }-- next.ServeHTTP(w, r)- })-}--// isLocalhost checks if the origin is from localhost. Strict suffix-// matching against a small allowlist keeps this honest — earlier-// substring slicing was easy to mis-edit and survives only because-// browsers send a fixed-format Origin header.-func isLocalhost(origin string) bool {- switch origin {- case "http://localhost", "https://localhost",- "http://127.0.0.1", "https://127.0.0.1":- return true- }- for _, prefix := range []string{- "http://localhost:", "https://localhost:",- "http://127.0.0.1:", "https://127.0.0.1:",- } {- if strings.HasPrefix(origin, prefix) {- return true- }- }- return false-}--// authMiddleware enforces a constant-time bearer-token check on every-// request. /health is exempt so external probes (systemd watchdog,-// external monitoring) can verify the agent is reachable without-// being trusted with the token. Every other endpoint exposes data-// (panel URL, agent ID, logs, metrics) or actions (restart, log-// rotation) that a malicious local process must not reach.-func authMiddleware(expected string, next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- // Always allow CORS preflight to pass through; the actual- // request that follows still has to authenticate.- if r.Method == http.MethodOptions {- next.ServeHTTP(w, r)- return- }- if r.URL.Path == "/health" {- next.ServeHTTP(w, r)- return- }- got := bearerToken(r)- if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(expected)) != 1 {- w.Header().Set("WWW-Authenticate", `Bearer realm="serverkit-agent"`)- http.Error(w, "unauthorized", http.StatusUnauthorized)- return- }- next.ServeHTTP(w, r)- })-}--func bearerToken(r *http.Request) string {- h := r.Header.Get("Authorization")- if h == "" {- // Fallback to query string for places where setting headers- // is awkward (eg. EventSource URLs in older browsers). The- // token is only valid on 127.0.0.1 anyway, so this isn't a- // new exposure.- return r.URL.Query().Get("token")- }- const prefix = "Bearer "- if len(h) > len(prefix) && strings.EqualFold(h[:len(prefix)], prefix) {- return strings.TrimSpace(h[len(prefix):])- }- return ""-}--// loadOrGenerateToken returns a per-host IPC bearer token. The file is-// reused across runs so a tray app that picked up the token on first-// launch keeps working through agent restarts; only when the file is-// missing or unreadable do we generate a fresh one.-func loadOrGenerateToken(path string) (string, error) {- if data, err := os.ReadFile(path); err == nil {- tok := strings.TrimSpace(string(data))- if len(tok) >= 32 {- return tok, nil- }- // File exists but contents are too short — treat as- // corrupted and regenerate.- }- if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {- return "", fmt.Errorf("create token dir: %w", err)- }- buf := make([]byte, 32)- if _, err := rand.Read(buf); err != nil {- return "", fmt.Errorf("generate token: %w", err)- }- tok := hex.EncodeToString(buf)- if err := os.WriteFile(path, []byte(tok), 0o600); err != nil {- return "", fmt.Errorf("write token: %w", err)- }- return tok, nil-}diff --git a/agent/internal/jobs/jobs.go b/agent/internal/jobs/jobs.godeleted file mode 100644index e87b5ff2..00000000--- a/agent/internal/jobs/jobs.go+++ /dev/null@@ -1,208 +0,0 @@-// Package jobs tracks long-running operations (package installs, image-// builds, pyenv installs) so the panel can subscribe to a streaming-// channel and receive progress events as they happen, plus a replay of-// recent events when subscribing mid-flight.-//-// A Job is created when a handler kicks off async work (e.g.-// packages:install) and returns {job_id, channel} to the caller. The-// handler then emits Event values via Job.Push, which:-// - sends the event to the agent's stream transport (so any active-// subscriber sees it live), AND-// - records the event in a bounded ring buffer (so a late subscriber-// can be caught up via Replay).-//-// The package is small on purpose — no goroutines, no timers, no I/O.-// Callers own concurrency. The only synchronization is a mutex around-// the registry map and per-job buffer mutex.-package jobs--import (- "crypto/rand"- "encoding/hex"- "fmt"- "sync"- "time"-)--// newID returns a 16-byte hex string suitable as a job identifier.-// Falls back to a timestamp if /dev/urandom is unavailable, matching-// the agent's auth.GenerateNonce style without taking a dep on it.-func newID() string {- b := make([]byte, 16)- if _, err := rand.Read(b); err != nil {- return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().UnixMilli())- }- return hex.EncodeToString(b)-}--// Phase enumerates lifecycle phases emitted by streaming jobs. The-// panel uses these to drive its progress UI.-const (- PhaseStart = "start"- PhaseLog = "log"- PhaseStatus = "status"- PhaseDone = "done"-)--// Event is the wire shape pushed onto a job's channel. Fields are kept-// minimal and JSON-tagged so the panel can render terminal-style output-// without per-handler parsers. Free-form Extra is for handlers that-// want to attach structured data (e.g. installed package list) to the-// final event.-type Event struct {- Phase string `json:"phase"`- Lines []string `json:"lines,omitempty"`- Message string `json:"message,omitempty"`- Percent *int `json:"percent,omitempty"`- ExitCode *int `json:"exit_code,omitempty"`- Error string `json:"error,omitempty"`- Extra map[string]interface{} `json:"extra,omitempty"`-}--// Job is one in-flight long-running operation. It owns a ring buffer-// of recent events so late subscribers can replay missed history.-type Job struct {- ID string- Channel string-- mu sync.Mutex- events []Event // ring buffer- cap int- head int // index of the next slot to write- full bool // whether we've wrapped past cap-- doneOnce sync.Once- done chan struct{}-}--// Streamer is the slice of the agent transport that jobs need. Wraps-// SendStream so handlers don't have to import the transport package-// directly.-type Streamer interface {- SendStream(channel string, data interface{}) error-}--// Registry tracks active and recently-completed jobs by ID. The bounded-// retention means a panel that subscribes to a job channel a few-// seconds after it completed still sees the final event. After enough-// new jobs land, the old job ages out and Replay returns nothing — at-// which point the panel knows the job is gone and should show "no-// progress available."-type Registry struct {- mu sync.Mutex- jobs map[string]*Job- // keep the last MaxJobs jobs in memory so a brief subscribe-after-finish- // race still serves the final "done" event.- maxJobs int- order []string // FIFO of job IDs; trimmed when len > maxJobs-}--// NewRegistry returns a Registry retaining up to maxJobs jobs.-func NewRegistry(maxJobs int) *Registry {- if maxJobs <= 0 {- maxJobs = 64- }- return &Registry{- jobs: make(map[string]*Job),- maxJobs: maxJobs,- }-}--// New creates and registers a new Job. bufferCap is the ring-buffer-// size for replay (suggested 200).-func (r *Registry) New(bufferCap int) *Job {- if bufferCap <= 0 {- bufferCap = 200- }- id := newID()- j := &Job{- ID: id,- Channel: "job:" + id,- events: make([]Event, bufferCap),- cap: bufferCap,- done: make(chan struct{}),- }- r.mu.Lock()- r.jobs[id] = j- r.order = append(r.order, id)- // Trim oldest jobs if we're over capacity.- for len(r.order) > r.maxJobs {- oldest := r.order[0]- r.order = r.order[1:]- delete(r.jobs, oldest)- }- r.mu.Unlock()- return j-}--// Get returns the job with the given ID, or nil if unknown.-func (r *Registry) Get(id string) *Job {- r.mu.Lock()- defer r.mu.Unlock()- return r.jobs[id]-}--// LookupByChannel returns the job whose Channel matches the given-// channel name (e.g. "job:<id>"), or nil. Used by Subscribe handlers-// to decide whether to replay buffered events.-func (r *Registry) LookupByChannel(channel string) *Job {- if len(channel) <= 4 || channel[:4] != "job:" {- return nil- }- return r.Get(channel[4:])-}--// Push records an event in the ring buffer and pushes it on the-// transport's stream channel. Panic-safe: a nil streamer just records-// the event, useful for tests.-func (j *Job) Push(s Streamer, ev Event) error {- j.mu.Lock()- j.events[j.head] = ev- j.head = (j.head + 1) % j.cap- if j.head == 0 {- j.full = true- }- j.mu.Unlock()-- if ev.Phase == PhaseDone {- j.doneOnce.Do(func() { close(j.done) })- }-- if s == nil {- return nil- }- return s.SendStream(j.Channel, ev)-}--// Replay returns a copy of the buffered events in chronological order.-// Used when a late subscriber wants to catch up.-func (j *Job) Replay() []Event {- j.mu.Lock()- defer j.mu.Unlock()- if !j.full {- out := make([]Event, j.head)- copy(out, j.events[:j.head])- return out- }- // Ring is full: oldest is at head, newest is just before head.- out := make([]Event, 0, j.cap)- out = append(out, j.events[j.head:]...)- out = append(out, j.events[:j.head]...)- return out-}--// Done returns a channel closed when the job emits a final event with-// Phase == PhaseDone. Useful for tests.-func (j *Job) Done() <-chan struct{} { return j.done }--// HasTerminated reports whether a Done event has already been emitted.-// Useful for handler shutdown paths that want to avoid double-emitting-// a final terminator if their primary loop already pushed one.-func (j *Job) HasTerminated() bool {- select {- case <-j.done:- return true- default:- return false- }-}diff --git a/agent/internal/jobs/jobs_test.go b/agent/internal/jobs/jobs_test.godeleted file mode 100644index aee2b9fb..00000000--- a/agent/internal/jobs/jobs_test.go+++ /dev/null@@ -1,114 +0,0 @@-package jobs--import (- "strconv"- "sync"- "testing"-)--type recorder struct {- mu sync.Mutex- sent []Event-}--func (r *recorder) SendStream(channel string, data interface{}) error {- ev, _ := data.(Event)- r.mu.Lock()- r.sent = append(r.sent, ev)- r.mu.Unlock()- return nil-}--func TestRegistryNewAssignsUniqueChannel(t *testing.T) {- r := NewRegistry(8)- a := r.New(0)- b := r.New(0)- if a.ID == b.ID {- t.Fatal("expected unique IDs")- }- if a.Channel != "job:"+a.ID || b.Channel != "job:"+b.ID {- t.Fatalf("unexpected channels: %q %q", a.Channel, b.Channel)- }- if r.LookupByChannel(a.Channel) != a {- t.Fatal("LookupByChannel did not round-trip")- }- if r.LookupByChannel("metrics") != nil {- t.Fatal("non-job channel should return nil")- }-}--func TestPushAndReplayPreserveOrder(t *testing.T) {- r := NewRegistry(8)- j := r.New(4)- rec := &recorder{}-- for i := 0; i < 3; i++ {- if err := j.Push(rec, Event{Phase: PhaseLog, Message: strconv.Itoa(i)}); err != nil {- t.Fatal(err)- }- }- got := j.Replay()- if len(got) != 3 {- t.Fatalf("want 3 events, got %d", len(got))- }- for i, ev := range got {- if ev.Message != strconv.Itoa(i) {- t.Fatalf("event %d out of order: %q", i, ev.Message)- }- }- if len(rec.sent) != 3 {- t.Fatalf("transport got %d events, want 3", len(rec.sent))- }-}--func TestRingBufferDropsOldest(t *testing.T) {- r := NewRegistry(8)- j := r.New(3)- rec := &recorder{}- for i := 0; i < 5; i++ {- _ = j.Push(rec, Event{Phase: PhaseLog, Message: strconv.Itoa(i)})- }- got := j.Replay()- if len(got) != 3 {- t.Fatalf("ring should hold 3 events, got %d", len(got))- }- // Oldest two events (0,1) should have been dropped; expect 2,3,4.- for i, ev := range got {- want := strconv.Itoa(i + 2)- if ev.Message != want {- t.Fatalf("ring order broken at %d: got %q want %q", i, ev.Message, want)- }- }-}--func TestDoneClosedOnTerminalEvent(t *testing.T) {- r := NewRegistry(8)- j := r.New(4)- select {- case <-j.Done():- t.Fatal("done before terminal event")- default:- }- exit := 0- _ = j.Push(nil, Event{Phase: PhaseDone, ExitCode: &exit})- select {- case <-j.Done():- default:- t.Fatal("done not closed after terminal event")- }- // Idempotent: second done event must not panic.- _ = j.Push(nil, Event{Phase: PhaseDone, ExitCode: &exit})-}--func TestRegistryEvictsOldestJobs(t *testing.T) {- r := NewRegistry(2)- j1 := r.New(0)- j2 := r.New(0)- j3 := r.New(0)- if r.Get(j1.ID) != nil {- t.Fatal("j1 should have been evicted")- }- if r.Get(j2.ID) == nil || r.Get(j3.ID) == nil {- t.Fatal("j2/j3 should still be present")- }-}diff --git a/agent/internal/logger/logger.go b/agent/internal/logger/logger.godeleted file mode 100644index 79d1eb56..00000000--- a/agent/internal/logger/logger.go+++ /dev/null@@ -1,148 +0,0 @@-package logger--import (- "fmt"- "io"- "os"- "path/filepath"- "sync"-- "github.com/serverkit/agent/internal/config"- "gopkg.in/natefinch/lumberjack.v2"- "log/slog"-)--// resilientWriter wraps multiple io.Writers and writes to all of them-// independently, swallowing per-writer errors. The standard library's-// io.MultiWriter aborts the entire write chain on the first error,-// which is a real bug on Windows services: a single transient stdout-// write failure (closed handle, ERROR_NO_DATA, etc.) blocks the-// lumberjack file writer from ever getting subsequent log records.-// That's how agent.log ended up at 0 bytes while events.json worked-// fine — events.json uses a direct os.File handle, not slog's-// handler chain.-type resilientWriter struct {- mu sync.Mutex- writers []io.Writer-}--func (r *resilientWriter) Write(p []byte) (int, error) {- r.mu.Lock()- defer r.mu.Unlock()- for _, w := range r.writers {- // Best-effort: write to each writer, but never let one writer's- // failure cascade to another. Returns len(p), nil unconditionally- // so slog never sees a write error and disables itself.- _, _ = w.Write(p)- }- return len(p), nil-}--// Logger wraps slog.Logger with additional context-type Logger struct {- *slog.Logger- // rotator is the lumberjack writer when file logging is enabled. Nil- // when only stdout is configured. Exposed via Rotate() so the desktop- // console's Logs-tab "Clear" button can roll the file without racing- // the live writer.- rotator *lumberjack.Logger-}--// New creates a new logger with the given configuration-func New(cfg config.LoggingConfig) *Logger {- var level slog.Level- switch cfg.Level {- case "debug":- level = slog.LevelDebug- case "info":- level = slog.LevelInfo- case "warn":- level = slog.LevelWarn- case "error":- level = slog.LevelError- default:- level = slog.LevelInfo- }-- opts := &slog.HandlerOptions{- Level: level,- }-- var writers []io.Writer- // Capture init errors so we can write them somewhere visible after- // the logger is constructed — silently swallowing them was how we- // got 0-byte agent.log files in the first place.- var initErrs []string-- // Always write to stdout (services on Windows: still safe even if- // the write goes nowhere — resilientWriter swallows per-writer- // errors).- writers = append(writers, os.Stdout)-- // Also write to file if configured.- var rotator *lumberjack.Logger- if cfg.File != "" {- dir := filepath.Dir(cfg.File)- if err := os.MkdirAll(dir, 0755); err != nil {- initErrs = append(initErrs, fmt.Sprintf("MkdirAll(%q): %v", dir, err))- } else {- // Probe file writability before handing the path to lumberjack- // so a permission error gets surfaced at boot instead of- // silently disabling file logging.- if f, perr := os.OpenFile(cfg.File, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); perr != nil {- initErrs = append(initErrs, fmt.Sprintf("OpenFile(%q): %v", cfg.File, perr))- } else {- _ = f.Close()- rotator = &lumberjack.Logger{- Filename: cfg.File,- MaxSize: cfg.MaxSize, // megabytes- MaxBackups: cfg.MaxBackups,- MaxAge: cfg.MaxAge, // days- Compress: cfg.Compress,- }- writers = append(writers, rotator)- }- }- }-- multi := &resilientWriter{writers: writers}- handler := slog.NewJSONHandler(multi, opts)- logger := slog.New(handler)-- // If rotator wired up successfully, drop a startup marker so the- // file is never confused with "logger broken" — empty file is the- // failure mode we just fixed, so always emit one explicit line.- if rotator != nil {- logger.Info("logger initialized",- "file", cfg.File, "level", cfg.Level,- "max_size_mb", cfg.MaxSize, "max_backups", cfg.MaxBackups)- }- for _, e := range initErrs {- // Visible on stdout AND via slog (which still has rotator==nil- // in this branch — best-effort visibility either way).- logger.Warn("logger init issue", "error", e)- }-- return &Logger{Logger: logger, rotator: rotator}-}--// Rotate triggers a manual log rotation. No-op when file logging is-// disabled. Used by the desktop console's "Clear logs" button so the live-// writer flushes to a backup before the in-memory tail clears.-func (l *Logger) Rotate() error {- if l.rotator == nil {- return nil- }- return l.rotator.Rotate()-}--// With returns a new logger with additional attributes. Carries the rotator-// reference so component loggers can also trigger rotation if needed.-func (l *Logger) With(args ...any) *Logger {- return &Logger{Logger: l.Logger.With(args...), rotator: l.rotator}-}--// WithComponent returns a logger with a component name-func (l *Logger) WithComponent(name string) *Logger {- return l.With("component", name)-}diff --git a/agent/internal/metrics/collector.go b/agent/internal/metrics/collector.godeleted file mode 100644index 10e52e9b..00000000--- a/agent/internal/metrics/collector.go+++ /dev/null@@ -1,293 +0,0 @@-package metrics--import (- "context"- "os"- "runtime"- "time"-- "github.com/shirou/gopsutil/v3/cpu"- "github.com/shirou/gopsutil/v3/disk"- "github.com/shirou/gopsutil/v3/host"- "github.com/shirou/gopsutil/v3/mem"- "github.com/shirou/gopsutil/v3/net"- "github.com/shirou/gopsutil/v3/process"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"-)--// Collector collects system metrics-type Collector struct {- cfg config.MetricsConfig- log *logger.Logger-- // Previous values for rate calculations- prevNetworkRx uint64- prevNetworkTx uint64- prevTime time.Time-}--// SystemMetrics contains all collected metrics-type SystemMetrics struct {- Timestamp int64 `json:"timestamp"`- CPUPercent float64 `json:"cpu_percent"`- CPUPerCore []float64 `json:"cpu_per_core,omitempty"`- MemoryTotal uint64 `json:"memory_total"`- MemoryUsed uint64 `json:"memory_used"`- MemoryPercent float64 `json:"memory_percent"`- SwapTotal uint64 `json:"swap_total"`- SwapUsed uint64 `json:"swap_used"`- SwapPercent float64 `json:"swap_percent"`- DiskTotal uint64 `json:"disk_total"`- DiskUsed uint64 `json:"disk_used"`- DiskPercent float64 `json:"disk_percent"`- NetworkRx uint64 `json:"network_rx"` // Bytes received (total)- NetworkTx uint64 `json:"network_tx"` // Bytes transmitted (total)- NetworkRxRate float64 `json:"network_rx_rate"` // Bytes/sec- NetworkTxRate float64 `json:"network_tx_rate"` // Bytes/sec- Uptime uint64 `json:"uptime"`- LoadAvg1 float64 `json:"load_avg_1,omitempty"`- LoadAvg5 float64 `json:"load_avg_5,omitempty"`- LoadAvg15 float64 `json:"load_avg_15,omitempty"`-}--// SystemInfo contains static system information-type SystemInfo struct {- Hostname string `json:"hostname"`- OS string `json:"os"`- Platform string `json:"platform"`- PlatformVersion string `json:"platform_version"`- KernelVersion string `json:"kernel_version"`- Architecture string `json:"architecture"`- CPUModel string `json:"cpu_model"`- CPUCores int `json:"cpu_cores"`- CPUThreads int `json:"cpu_threads"`- TotalMemory uint64 `json:"total_memory"`- TotalDisk uint64 `json:"total_disk"`-}--// ProcessInfo contains process information-type ProcessInfo struct {- PID int32 `json:"pid"`- Name string `json:"name"`- Username string `json:"username"`- CPUPercent float64 `json:"cpu_percent"`- MemPercent float32 `json:"mem_percent"`- MemRSS uint64 `json:"mem_rss"`- Status string `json:"status"`- CreateTime int64 `json:"create_time"`- Cmdline string `json:"cmdline"`-}--// NewCollector creates a new metrics collector-func NewCollector(cfg config.MetricsConfig, log *logger.Logger) *Collector {- return &Collector{- cfg: cfg,- log: log.WithComponent("metrics"),- prevTime: time.Now(),- }-}--// Collect collects current system metrics-func (c *Collector) Collect(ctx context.Context) (*SystemMetrics, error) {- now := time.Now()- metrics := &SystemMetrics{- Timestamp: now.UnixMilli(),- }-- // CPU usage- cpuPercent, err := cpu.PercentWithContext(ctx, 0, false)- if err == nil && len(cpuPercent) > 0 {- metrics.CPUPercent = cpuPercent[0]- }-- // Per-core CPU (optional)- if c.cfg.IncludePerCPU {- perCore, err := cpu.PercentWithContext(ctx, 0, true)- if err == nil {- metrics.CPUPerCore = perCore- }- }-- // Memory- memInfo, err := mem.VirtualMemoryWithContext(ctx)- if err == nil {- metrics.MemoryTotal = memInfo.Total- metrics.MemoryUsed = memInfo.Used- metrics.MemoryPercent = memInfo.UsedPercent- }-- // Swap- swapInfo, err := mem.SwapMemoryWithContext(ctx)- if err == nil {- metrics.SwapTotal = swapInfo.Total- metrics.SwapUsed = swapInfo.Used- metrics.SwapPercent = swapInfo.UsedPercent- }-- // Disk (root partition)- diskPath := "/"- if runtime.GOOS == "windows" {- diskPath = "C:\\"- }- diskInfo, err := disk.UsageWithContext(ctx, diskPath)- if err == nil {- metrics.DiskTotal = diskInfo.Total- metrics.DiskUsed = diskInfo.Used- metrics.DiskPercent = diskInfo.UsedPercent- }-- // Network I/O- netIO, err := net.IOCountersWithContext(ctx, false)- if err == nil && len(netIO) > 0 {- metrics.NetworkRx = netIO[0].BytesRecv- metrics.NetworkTx = netIO[0].BytesSent-- // Calculate rate- elapsed := now.Sub(c.prevTime).Seconds()- if elapsed > 0 && c.prevNetworkRx > 0 {- metrics.NetworkRxRate = float64(netIO[0].BytesRecv-c.prevNetworkRx) / elapsed- metrics.NetworkTxRate = float64(netIO[0].BytesSent-c.prevNetworkTx) / elapsed- }-- c.prevNetworkRx = netIO[0].BytesRecv- c.prevNetworkTx = netIO[0].BytesSent- }-- // Uptime- hostInfo, err := host.InfoWithContext(ctx)- if err == nil {- metrics.Uptime = hostInfo.Uptime- }-- // Load average (Unix only)- if runtime.GOOS != "windows" {- loadAvg, err := cpu.Percent(0, false)- if err == nil && len(loadAvg) > 0 {- // Note: gopsutil load average is in misc package- // Using a simple approximation here- }- }-- c.prevTime = now- return metrics, nil-}--// GetSystemInfo returns static system information-func (c *Collector) GetSystemInfo(ctx context.Context) (*SystemInfo, error) {- info := &SystemInfo{- OS: runtime.GOOS,- Architecture: runtime.GOARCH,- }-- // Hostname- hostname, err := os.Hostname()- if err == nil {- info.Hostname = hostname- }-- // Host info- hostInfo, err := host.InfoWithContext(ctx)- if err == nil {- info.Platform = hostInfo.Platform- info.PlatformVersion = hostInfo.PlatformVersion- info.KernelVersion = hostInfo.KernelVersion- }-- // CPU info — gopsutil's WMI/sysctl calls fail intermittently on- // some Windows service contexts, so fall back to runtime.NumCPU()- // for the count (always non-zero) and leave the model empty- // rather than reporting nonsense.- cpuInfo, err := cpu.InfoWithContext(ctx)- if err == nil && len(cpuInfo) > 0 {- info.CPUModel = cpuInfo[0].ModelName- info.CPUCores = int(cpuInfo[0].Cores)- }-- // CPU count- threads, err := cpu.CountsWithContext(ctx, true)- if err == nil {- info.CPUThreads = threads- }- cores, err := cpu.CountsWithContext(ctx, false)- if err == nil {- info.CPUCores = cores- }- // Last-resort fallback: runtime.NumCPU is always >= 1 on a- // running process. Better than reporting 0 cores.- if info.CPUCores == 0 {- info.CPUCores = runtime.NumCPU()- }- if info.CPUThreads == 0 {- info.CPUThreads = runtime.NumCPU()- }-- // Memory- memInfo, err := mem.VirtualMemoryWithContext(ctx)- if err == nil {- info.TotalMemory = memInfo.Total- }-- // Disk- diskPath := "/"- if runtime.GOOS == "windows" {- diskPath = "C:\\"- }- diskInfo, err := disk.UsageWithContext(ctx, diskPath)- if err == nil {- info.TotalDisk = diskInfo.Total- }-- return info, nil-}--// ListProcesses returns a list of running processes-func (c *Collector) ListProcesses(ctx context.Context) ([]ProcessInfo, error) {- procs, err := process.ProcessesWithContext(ctx)- if err != nil {- return nil, err- }-- result := make([]ProcessInfo, 0, len(procs))- for _, p := range procs {- info := ProcessInfo{- PID: p.Pid,- }-- if name, err := p.NameWithContext(ctx); err == nil {- info.Name = name- }-- if username, err := p.UsernameWithContext(ctx); err == nil {- info.Username = username- }-- if cpuPct, err := p.CPUPercentWithContext(ctx); err == nil {- info.CPUPercent = cpuPct- }-- if memPct, err := p.MemoryPercentWithContext(ctx); err == nil {- info.MemPercent = memPct- }-- if memInfo, err := p.MemoryInfoWithContext(ctx); err == nil && memInfo != nil {- info.MemRSS = memInfo.RSS- }-- if status, err := p.StatusWithContext(ctx); err == nil && len(status) > 0 {- info.Status = status[0]- }-- if createTime, err := p.CreateTimeWithContext(ctx); err == nil {- info.CreateTime = createTime- }-- if cmdline, err := p.CmdlineWithContext(ctx); err == nil {- info.Cmdline = cmdline- }-- result = append(result, info)- }-- return result, nil-}diff --git a/agent/internal/pairdriver/driver.go b/agent/internal/pairdriver/driver.godeleted file mode 100644index 8c616fc2..00000000--- a/agent/internal/pairdriver/driver.go+++ /dev/null@@ -1,173 +0,0 @@-// Package pairdriver runs the agent's pairing protocol: enroll with the-// panel, wait for the operator to claim, persist the resulting credentials.-// It's UI-agnostic — both the legacy walk wizard (setupui) and the-// React-based console wizard (agentui) drive it via callbacks.-package pairdriver--import (- "context"- "crypto/rand"- "fmt"- "math/big"- "os"- "path/filepath"- "runtime"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/metrics"- "github.com/serverkit/agent/internal/pairing"-)--// passphraseAlphabet excludes confusable characters (0/o/1/i/l) for-// readability. Lowercase so the operator's natural typing matches the-// displayed value — no shift-dance, no caps-lock surprises.-const passphraseAlphabet = "23456789abcdefghjkmnpqrstuvwxyz"--// GeneratePassphrase returns a fresh 8-char passphrase for an enroll-// request. 8 chars from this 30-char alphabet ≈ 39 bits of entropy, which-// is overkill for a one-shot value that becomes useless once the panel-// claims the agent.-func GeneratePassphrase() (string, error) {- const n = 8- max := big.NewInt(int64(len(passphraseAlphabet)))- buf := make([]byte, n)- for i := 0; i < n; i++ {- idx, err := rand.Int(rand.Reader, max)- if err != nil {- return "", err- }- buf[i] = passphraseAlphabet[idx.Int64()]- }- return string(buf), nil-}--// Callbacks lets the UI observe state transitions in the pairing driver.-// All callbacks fire on a background goroutine; UI code is responsible for-// marshalling them onto its own thread when relevant.-type Callbacks struct {- OnEnrolled func(code, formatted string)- OnClaimed func(serverName string)- OnError func(err error)-}--// Run performs the full enroll → wait-for-claim → save-credentials flow.-// It returns when pairing succeeds, the user cancels (ctx done), or an-// error occurs. All progress is reported via cb.-func Run(- ctx context.Context,- log *logger.Logger,- configPath, panelURL, passphrase, displayName string,- cb Callbacks,-) {- panelURL = NormalizePanelURL(panelURL)-- kp, err := pairing.LoadOrCreate(pairing.DefaultKeyPath())- if err != nil {- cb.OnError(fmt.Errorf("load keypair: %w", err))- return- }-- collector := metrics.NewCollector(config.MetricsConfig{}, log)- infoCtx, infoCancel := context.WithTimeout(ctx, 8*time.Second)- sysInfo, _ := collector.GetSystemInfo(infoCtx)- infoCancel()-- sysMap := buildSystemInfo(sysInfo, displayName)-- client := pairing.NewClient(panelURL, log)- client.SetKeyPair(kp) // enables Ed25519 proof-of-possession on poll- enrollCtx, enrollCancel := context.WithTimeout(ctx, 30*time.Second)- enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{- Pubkey: kp.PublicKeyHex(),- Passphrase: passphrase,- MachineID: config.MachineID(),- SystemInfo: sysMap,- })- enrollCancel()- if err != nil {- cb.OnError(fmt.Errorf("enroll: %w", err))- return- }-- cb.OnEnrolled(enrollResp.PairCode, enrollResp.PairCodeFormatted)-- creds, err := client.WaitForClaim(ctx, func(code, formatted, _ string) {- cb.OnEnrolled(code, formatted)- })- if err != nil {- if ctx.Err() != nil {- return // user cancelled- }- cb.OnError(fmt.Errorf("waiting for claim: %w", err))- return- }-- if err := saveCredentials(configPath, panelURL, creds); err != nil {- cb.OnError(fmt.Errorf("save credentials: %w", err))- return- }-- cb.OnClaimed(creds.Name)-}--// NormalizePanelURL strips trailing slashes and adds an https:// prefix-// when the user types a bare hostname.-func NormalizePanelURL(u string) string {- u = strings.TrimSpace(u)- if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {- u = "https://" + u- }- return strings.TrimSuffix(u, "/")-}--func buildSystemInfo(sysInfo *metrics.SystemInfo, displayName string) map[string]interface{} {- m := map[string]interface{}{}- if sysInfo != nil {- m["hostname"] = sysInfo.Hostname- m["os"] = sysInfo.OS- m["platform"] = sysInfo.Platform- m["platform_version"] = sysInfo.PlatformVersion- m["architecture"] = sysInfo.Architecture- m["cpu_cores"] = sysInfo.CPUCores- m["total_memory"] = sysInfo.TotalMemory- m["total_disk"] = sysInfo.TotalDisk- } else {- hostname, _ := os.Hostname()- m["hostname"] = hostname- m["os"] = runtime.GOOS- m["architecture"] = runtime.GOARCH- }- if displayName = strings.TrimSpace(displayName); displayName != "" {- m["display_name"] = displayName- }- return m-}--func saveCredentials(configPath, panelURL string, creds *pairing.Credentials) error {- cfg, err := config.Load(configPath)- if err != nil {- cfg = config.Default()- }- wsURL := strings.TrimSuffix(panelURL, "/")- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)- cfg.Server.URL = wsURL + "/agent"- cfg.Agent.ID = creds.AgentID- cfg.Agent.Name = creds.Name- cfg.Auth.APIKey = creds.APIKey- cfg.Auth.APISecret = creds.APISecret-- if configPath == "" {- configPath = config.DefaultConfigPath()- }- if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {- return err- }- if err := cfg.Save(configPath); err != nil {- return err- }- return cfg.SaveCredentials()-}diff --git a/agent/internal/pairing/client.go b/agent/internal/pairing/client.godeleted file mode 100644index 034026c2..00000000--- a/agent/internal/pairing/client.go+++ /dev/null@@ -1,259 +0,0 @@-package pairing--import (- "bytes"- "context"- "crypto/tls"- "encoding/base64"- "encoding/json"- "fmt"- "io"- "net/http"- "os"- "strings"- "time"-- "github.com/serverkit/agent/internal/logger"-)--// EnrollRequest is the body of POST /api/v1/pairing/enroll.-type EnrollRequest struct {- Pubkey string `json:"pubkey"`- Passphrase string `json:"passphrase"`- MachineID string `json:"machine_id,omitempty"`- SystemInfo map[string]interface{} `json:"system_info,omitempty"`-}--// EnrollResponse is what the panel returns on successful enroll.-type EnrollResponse struct {- EnrollmentID string `json:"enrollment_id"`- EnrollmentSecret string `json:"enrollment_secret"`- PairCode string `json:"pair_code"`- PairCodeFormatted string `json:"pair_code_formatted"`- PairCodeExpiresAt string `json:"pair_code_expires_at"`- ExpiresAt string `json:"expires_at"`- PubkeyFingerprint string `json:"pubkey_fpr"`-}--// PollResponse is the body of GET /api/v1/pairing/poll.-type PollResponse struct {- Status string `json:"status"` // pending | claimed- PairCode string `json:"pair_code,omitempty"`- PairCodeExpiresAt string `json:"pair_code_expires_at,omitempty"`- Credentials *Credentials `json:"credentials,omitempty"`-}--// Credentials are returned to the agent once an operator claims it.-type Credentials struct {- AgentID string `json:"agent_id"`- ServerID string `json:"server_id"`- Name string `json:"name"`- APIKey string `json:"api_key"`- APISecret string `json:"api_secret"`-}--// RefreshResponse is returned from /code/refresh and /code/freeze.-type RefreshResponse struct {- PairCode string `json:"pair_code"`- PairCodeFormatted string `json:"pair_code_formatted"`- PairCodeExpiresAt string `json:"pair_code_expires_at"`- PairCodeFrozen bool `json:"pair_code_frozen"`-}--// Client talks to the panel pairing API.-type Client struct {- BaseURL string- HTTP *http.Client- UserAgent string- EnrollmentID string- EnrollmentSecret string- keypair *KeyPair- log *logger.Logger-}--// SetKeyPair attaches the agent's Ed25519 keypair so Poll can prove-// possession of the private key matching the enrolled pubkey. Optional: when-// unset, Poll falls back to bearer-secret-only auth (older behavior).-func (c *Client) SetKeyPair(kp *KeyPair) {- c.keypair = kp-}--// NewClient constructs a pairing client. baseURL must be the panel HTTPS root.-func NewClient(baseURL string, log *logger.Logger) *Client {- baseURL = strings.TrimSuffix(baseURL, "/")- return &Client{- BaseURL: baseURL,- HTTP: &http.Client{- Timeout: 60 * time.Second,- Transport: &http.Transport{- TLSClientConfig: &tls.Config{- InsecureSkipVerify: os.Getenv("SERVERKIT_INSECURE_TLS") == "true",- },- },- },- UserAgent: "ServerKit-Agent-Pairing/1.0",- log: log.WithComponent("pairing"),- }-}--// Enroll submits the agent's pubkey + passphrase to obtain an enrollment + pair code.-func (c *Client) Enroll(ctx context.Context, req EnrollRequest) (*EnrollResponse, error) {- var resp EnrollResponse- if err := c.do(ctx, "POST", "/api/v1/pairing/enroll", req, nil, &resp); err != nil {- return nil, err- }- c.EnrollmentID = resp.EnrollmentID- c.EnrollmentSecret = resp.EnrollmentSecret- return &resp, nil-}--// RotateCode requests a new pair code (no-op if frozen unless force=true).-func (c *Client) RotateCode(ctx context.Context, force bool) (*RefreshResponse, error) {- body := map[string]bool{"force": force}- var resp RefreshResponse- if err := c.do(ctx, "POST", "/api/v1/pairing/code/refresh", body, c.enrollHeaders(), &resp); err != nil {- return nil, err- }- return &resp, nil-}--// SetFreeze freezes or unfreezes the rotating pair code.-func (c *Client) SetFreeze(ctx context.Context, frozen bool) (*RefreshResponse, error) {- body := map[string]bool{"frozen": frozen}- var resp RefreshResponse- if err := c.do(ctx, "POST", "/api/v1/pairing/code/freeze", body, c.enrollHeaders(), &resp); err != nil {- return nil, err- }- return &resp, nil-}--// Poll waits up to ~30s for an operator to claim this enrollment.-// Returns (claimed, credentials, err). If err is nil and claimed is false the-// caller should reconnect immediately for another long-poll.-func (c *Client) Poll(ctx context.Context) (bool, *Credentials, error) {- headers := c.enrollHeaders()- // Prove possession of the enrolled private key by signing the- // enrollment_id. The panel verifies this against the pubkey we submitted at- // enroll() time, so a stolen enrollment_secret alone can't claim our creds.- if c.keypair != nil && c.EnrollmentID != "" {- sig := base64.StdEncoding.EncodeToString(c.keypair.Sign([]byte(c.EnrollmentID)))- headers.Set("X-Enrollment-Signature", sig)- }- var resp PollResponse- if err := c.do(ctx, "GET", "/api/v1/pairing/poll", nil, headers, &resp); err != nil {- return false, nil, err- }- if resp.Status == "claimed" && resp.Credentials != nil {- return true, resp.Credentials, nil- }- return false, nil, nil-}--// WaitForClaim blocks until the agent is claimed, retrying long-polls and-// occasionally rotating the pair code (every ~5 minutes) so codes never get stale.-//-// onCode is invoked whenever the visible pair code changes — typically wired-// into the tray UI. It may be nil for headless operation.-func (c *Client) WaitForClaim(ctx context.Context, onCode func(code, formatted string, expiresAt string)) (*Credentials, error) {- codeRotateTicker := time.NewTicker(4 * time.Minute)- defer codeRotateTicker.Stop()-- for {- select {- case <-ctx.Done():- return nil, ctx.Err()- case <-codeRotateTicker.C:- if rr, err := c.RotateCode(ctx, false); err == nil && onCode != nil {- onCode(rr.PairCode, formatPairCode(rr.PairCode), rr.PairCodeExpiresAt)- }- default:- }-- pollCtx, cancel := context.WithTimeout(ctx, 35*time.Second)- claimed, creds, err := c.Poll(pollCtx)- cancel()- if err != nil {- c.log.Warn("pairing poll failed; retrying", "error", err)- select {- case <-ctx.Done():- return nil, ctx.Err()- case <-time.After(5 * time.Second):- }- continue- }- if claimed {- return creds, nil- }- }-}--// ----- internals -------func (c *Client) enrollHeaders() http.Header {- h := http.Header{}- if c.EnrollmentID != "" {- h.Set("X-Enrollment-Id", c.EnrollmentID)- }- if c.EnrollmentSecret != "" {- h.Set("X-Enrollment-Secret", c.EnrollmentSecret)- }- return h-}--func (c *Client) do(ctx context.Context, method, path string, body interface{}, extraHeaders http.Header, out interface{}) error {- url := c.BaseURL + path-- var bodyReader io.Reader- if body != nil {- buf, err := json.Marshal(body)- if err != nil {- return fmt.Errorf("marshal: %w", err)- }- bodyReader = bytes.NewReader(buf)- }-- req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)- if err != nil {- return fmt.Errorf("new request: %w", err)- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Accept", "application/json")- req.Header.Set("User-Agent", c.UserAgent)- for k, v := range extraHeaders {- for _, vv := range v {- req.Header.Add(k, vv)- }- }-- resp, err := c.HTTP.Do(req)- if err != nil {- return fmt.Errorf("%s %s: %w", method, path, err)- }- defer resp.Body.Close()-- respBody, _ := io.ReadAll(resp.Body)- if resp.StatusCode >= 400 {- var er struct {- Error string `json:"error"`- }- _ = json.Unmarshal(respBody, &er)- if er.Error != "" {- return fmt.Errorf("%s %s: %s (status %d)", method, path, er.Error, resp.StatusCode)- }- return fmt.Errorf("%s %s: status %d", method, path, resp.StatusCode)- }- if out != nil && len(respBody) > 0 {- if err := json.Unmarshal(respBody, out); err != nil {- return fmt.Errorf("decode response: %w", err)- }- }- return nil-}--func formatPairCode(code string) string {- if len(code) < 2 {- return code- }- half := len(code) / 2- return code[:half] + "-" + code[half:]-}diff --git a/agent/internal/pairing/keypair.go b/agent/internal/pairing/keypair.godeleted file mode 100644index 51e1483d..00000000--- a/agent/internal/pairing/keypair.go+++ /dev/null@@ -1,115 +0,0 @@-// Package pairing implements the RustDesk-style short-code agent pairing flow.-package pairing--import (- "crypto/ed25519"- "crypto/rand"- "crypto/sha256"- "encoding/hex"- "fmt"- "os"- "path/filepath"- "runtime"- "strings"-- "github.com/serverkit/agent/internal/config"-)--// KeyPair holds an Ed25519 keypair plus a short fingerprint string.-type KeyPair struct {- Public ed25519.PublicKey- Private ed25519.PrivateKey- Fingerprint string // matches panel format: uppercase hex, first 16 chars of SHA-256(pubkey_hex).-}--// PublicKeyHex returns the public key as lowercase hex (64 chars).-func (k *KeyPair) PublicKeyHex() string {- return hex.EncodeToString(k.Public)-}--// Sign produces an Ed25519 signature over message using the private key.-// Used for pairing proof-of-possession: the panel verifies the signature-// against the enrolled public key before releasing credentials.-func (k *KeyPair) Sign(message []byte) []byte {- return ed25519.Sign(k.Private, message)-}--// DefaultKeyPath returns the OS-specific default path for the pairing keyfile.-func DefaultKeyPath() string {- if runtime.GOOS == "windows" {- return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "pairing.key")- }- return "/etc/serverkit-agent/pairing.key"-}--// LoadOrCreate returns the keypair at path, generating + persisting one if-// no file exists. The file is encrypted with the machine-derived key.-func LoadOrCreate(path string) (*KeyPair, error) {- if path == "" {- path = DefaultKeyPath()- }- if _, err := os.Stat(path); err == nil {- return Load(path)- } else if !os.IsNotExist(err) {- return nil, fmt.Errorf("stat key file: %w", err)- }- kp, err := Generate()- if err != nil {- return nil, err- }- if err := Save(kp, path); err != nil {- return nil, err- }- return kp, nil-}--// Generate creates a new random Ed25519 keypair.-func Generate() (*KeyPair, error) {- pub, priv, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- return nil, fmt.Errorf("generate keypair: %w", err)- }- return &KeyPair{Public: pub, Private: priv, Fingerprint: fingerprint(pub)}, nil-}--// Load reads + decrypts a keypair file.-func Load(path string) (*KeyPair, error) {- data, err := os.ReadFile(path)- if err != nil {- return nil, fmt.Errorf("read key file: %w", err)- }- plain, err := config.DecryptBytes(data)- if err != nil {- return nil, fmt.Errorf("decrypt key file: %w", err)- }- if len(plain) != ed25519.PrivateKeySize {- return nil, fmt.Errorf("invalid key file size: %d", len(plain))- }- priv := ed25519.PrivateKey(plain)- pub := priv.Public().(ed25519.PublicKey)- return &KeyPair{Public: pub, Private: priv, Fingerprint: fingerprint(pub)}, nil-}--// Save encrypts and writes the keypair to disk with restricted permissions.-func Save(kp *KeyPair, path string) error {- if path == "" {- path = DefaultKeyPath()- }- if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {- return fmt.Errorf("create key dir: %w", err)- }- encrypted, err := config.EncryptBytes(kp.Private)- if err != nil {- return fmt.Errorf("encrypt key: %w", err)- }- if err := os.WriteFile(path, encrypted, 0600); err != nil {- return fmt.Errorf("write key file: %w", err)- }- return nil-}--func fingerprint(pub ed25519.PublicKey) string {- pubHex := hex.EncodeToString(pub)- digest := sha256.Sum256([]byte(pubHex))- return strings.ToUpper(hex.EncodeToString(digest[:8]))-}diff --git a/agent/internal/setupui/darkmode_windows.go b/agent/internal/setupui/darkmode_windows.godeleted file mode 100644index 08ccf12c..00000000--- a/agent/internal/setupui/darkmode_windows.go+++ /dev/null@@ -1,40 +0,0 @@-//go:build windows--package setupui--import (- "syscall"- "unsafe"-- "github.com/lxn/walk"-)--// enableDarkMode flips the window's title bar to the dark colour scheme on-// Windows 10/11 and registers the process as dark-mode aware so native-// controls (Edit, Button, ScrollBar) follow suit on Win11.-//-// Belt-and-braces: try the documented Win11 attribute (20), fall back to the-// undocumented Win10 1903+ value (19); call SetPreferredAppMode via its-// uxtheme ordinal export. All calls are best-effort and silently ignored on-// older builds where the API isn't present.-func enableDarkMode(form walk.Form) {- if form == nil {- return- }- hwnd := form.Handle()- if hwnd == 0 {- return- }-- dwmapi := syscall.NewLazyDLL("dwmapi.dll")- setAttr := dwmapi.NewProc("DwmSetWindowAttribute")- var enable int32 = 1- setAttr.Call(uintptr(hwnd), 20, uintptr(unsafe.Pointer(&enable)), 4)- setAttr.Call(uintptr(hwnd), 19, uintptr(unsafe.Pointer(&enable)), 4)-- uxtheme := syscall.NewLazyDLL("uxtheme.dll")- // SetPreferredAppMode(AllowDark = 1). Ordinal #135 on Win10 1903+.- if proc := uxtheme.NewProc("SetPreferredAppMode"); proc != nil && proc.Find() == nil {- proc.Call(1)- }-}diff --git a/agent/internal/setupui/foreground_windows.go b/agent/internal/setupui/foreground_windows.godeleted file mode 100644index 5535833f..00000000--- a/agent/internal/setupui/foreground_windows.go+++ /dev/null@@ -1,124 +0,0 @@-//go:build windows--package setupui--import (- "syscall"- "time"- "unsafe"-- "github.com/lxn/walk"-)--// forceForegroundWindow uses the documented AttachThreadInput recipe to bring-// a freshly-created walk window to the front, working around Windows'-// anti-focus-stealing rules.-//-// The plain TopMost-toggle trick is unreliable: it changes the Z-order but-// Windows still treats the activation as a focus-steal attempt and silently-// drops it on Windows 10/11 if our process isn't already in the foreground.-// AttachThreadInput briefly merges our input queue with the current-// foreground thread's, which Windows treats as the same UI session — and so-// SetForegroundWindow goes through.-func forceForegroundWindow(form walk.Form) {- if form == nil {- return- }- hwnd := uintptr(form.Handle())- if hwnd == 0 {- return- }-- user32 := syscall.NewLazyDLL("user32.dll")- kernel32 := syscall.NewLazyDLL("kernel32.dll")-- showWindow := user32.NewProc("ShowWindow")- setForegroundWindow := user32.NewProc("SetForegroundWindow")- setFocus := user32.NewProc("SetFocus")- setActiveWindow := user32.NewProc("SetActiveWindow")- bringWindowToTop := user32.NewProc("BringWindowToTop")- getForegroundWindow := user32.NewProc("GetForegroundWindow")- getWindowThreadProcessId := user32.NewProc("GetWindowThreadProcessId")- getCurrentThreadId := kernel32.NewProc("GetCurrentThreadId")- attachThreadInput := user32.NewProc("AttachThreadInput")- setWindowPos := user32.NewProc("SetWindowPos")- keybdEvent := user32.NewProc("keybd_event")- allowSetForegroundWindow := user32.NewProc("AllowSetForegroundWindow")-- const (- swRestore = 9- hwndTopmost = ^uintptr(0) // -1- hwndNotTopmost = ^uintptr(0) - 1 // -2- swpNoSize = 0x0001- swpNoMove = 0x0002- swpShowWindow = 0x0040- keyEventfKeyUp = 0x0002- ASFW_ANY = ^uint32(0) // -1- )-- // (1) Allow ourselves to be the foreground for the next operation,- // regardless of who's calling. -1 = ASFW_ANY.- allowSetForegroundWindow.Call(uintptr(ASFW_ANY))-- // (2) Make sure the window is at least restored from any minimized state.- showWindow.Call(hwnd, swRestore)-- // (3) Simulate a no-op keypress. Windows treats keyboard input as user- // activity and grants the receiving thread foreground privilege —- // even on Win10/11 where SetForegroundWindow is otherwise denied.- keybdEvent.Call(0, 0, 0, 0)- keybdEvent.Call(0, 0, keyEventfKeyUp, 0)-- // (4) AttachThreadInput trick: temporarily fuse our input queue with the- // current foreground thread's so SetForegroundWindow is treated as- // coming from the same UI session.- fgHwnd, _, _ := getForegroundWindow.Call()- var fgPid uint32- fgThread, _, _ := getWindowThreadProcessId.Call(fgHwnd, uintptr(unsafe.Pointer(&fgPid)))- ourThread, _, _ := getCurrentThreadId.Call()-- attached := false- if fgThread != 0 && fgThread != ourThread {- r, _, _ := attachThreadInput.Call(fgThread, ourThread, 1)- attached = r != 0- }-- // (5) The full activation sequence: Z-order, foreground, active, focus.- bringWindowToTop.Call(hwnd)- setWindowPos.Call(hwnd, hwndTopmost, 0, 0, 0, 0,- uintptr(swpNoMove|swpNoSize|swpShowWindow))- setForegroundWindow.Call(hwnd)- setActiveWindow.Call(hwnd)- setFocus.Call(hwnd)- setWindowPos.Call(hwnd, hwndNotTopmost, 0, 0, 0, 0,- uintptr(swpNoMove|swpNoSize|swpShowWindow))-- if attached {- attachThreadInput.Call(fgThread, ourThread, 0)- }-}--// scheduleForceForeground fires the activation recipe several times across-// the first ~1.5 seconds of window life. The first attempt usually races-// the message loop start; later attempts win once the pump is servicing.-// Cheap and idempotent.-func scheduleForceForeground(form walk.Form) {- if form == nil {- return- }- go func() {- for _, d := range []time.Duration{- 0,- 50 * time.Millisecond,- 150 * time.Millisecond,- 400 * time.Millisecond,- 900 * time.Millisecond,- 1500 * time.Millisecond,- } {- time.Sleep(d)- form.Synchronize(func() {- forceForegroundWindow(form)- })- }- }()-}diff --git a/agent/internal/setupui/serverkit.ico b/agent/internal/setupui/serverkit.icodeleted file mode 100644index e6f126db..00000000Binary files a/agent/internal/setupui/serverkit.ico and /dev/null differdiff --git a/agent/internal/setupui/serverkit_header.png b/agent/internal/setupui/serverkit_header.pngdeleted file mode 100644index d3484310..00000000Binary files a/agent/internal/setupui/serverkit_header.png and /dev/null differdiff --git a/agent/internal/setupui/service_other.go b/agent/internal/setupui/service_other.godeleted file mode 100644index 1ce2fb5e..00000000--- a/agent/internal/setupui/service_other.go+++ /dev/null@@ -1,5 +0,0 @@-//go:build !windows--package setupui--func startServiceIfInstalled() {}diff --git a/agent/internal/setupui/service_windows.go b/agent/internal/setupui/service_windows.godeleted file mode 100644index daf57be7..00000000--- a/agent/internal/setupui/service_windows.go+++ /dev/null@@ -1,21 +0,0 @@-//go:build windows--package setupui--import (- "os/exec"- "syscall"-)--// startServiceIfInstalled flips the ServerKitAgent service to auto-start-// and starts it. Best-effort: silently ignores errors (e.g. service not-// installed, no admin rights).-func startServiceIfInstalled() {- run := func(args ...string) {- cmd := exec.Command("sc.exe", args...)- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}- _ = cmd.Run()- }- run("config", "ServerKitAgent", "start=", "auto")- run("start", "ServerKitAgent")-}diff --git a/agent/internal/setupui/setupui.go b/agent/internal/setupui/setupui.godeleted file mode 100644index 5fdbc545..00000000--- a/agent/internal/setupui/setupui.go+++ /dev/null@@ -1,20 +0,0 @@-// Package setupui shows the legacy native-walk pairing wizard. The pairing-// protocol itself moved to internal/pairdriver so both this wizard and the-// React-based agentui console can drive it.-package setupui--import (- "context"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"-)--// Run shows the pairing wizard and blocks until the user closes it.-// configPath may be empty to use the default location.-func Run(ctx context.Context, log *logger.Logger, configPath string) error {- if configPath == "" {- configPath = config.DefaultConfigPath()- }- return runWindow(ctx, log.WithComponent("setupui"), configPath)-}diff --git a/agent/internal/setupui/theme_windows.go b/agent/internal/setupui/theme_windows.godeleted file mode 100644index 21d25eab..00000000--- a/agent/internal/setupui/theme_windows.go+++ /dev/null@@ -1,99 +0,0 @@-//go:build windows--package setupui--import (- "github.com/lxn/walk"- dec "github.com/lxn/walk/declarative"- "golang.org/x/sys/windows/registry"-)--// palette holds the colour tokens used by the wizard. We carry separate-// light/dark instances and pick at startup based on the user's Windows-// theme, mirroring the panel's own light/dark behaviour.-type palette struct {- dark bool-- bgDeep uint32 // outer window background- bgCard uint32 // card surface- textHeading uint32 // section titles- textBody uint32 // descriptive body- textLabel uint32 // form labels- textMuted uint32 // subtitles- textHelper uint32 // helper text under inputs / footer- indigo uint32 // brand accent (button text + pair code)- errorRed uint32- successGr uint32-- // Brushes derived from the colours above. Cached to avoid recomputing- // the same SolidColorBrush thousands of times during widget construction.- brushBgDeep dec.Brush- brushBgCard dec.Brush-}--func newPalette(dark bool) palette {- if dark {- p := palette{- dark: true,- bgDeep: 0x09090B,- bgCard: 0x121214,- textHeading: 0xFFFFFF,- textBody: 0xEDEDED,- textLabel: 0xE4E4E7,- textMuted: 0xA1A1AA,- textHelper: 0x71717A,- indigo: 0x818CF8, // slightly lifted for contrast on dark bg- errorRed: 0xF87171,- successGr: 0x34D399,- }- p.brushBgDeep = dec.SolidColorBrush{Color: rgbHex(p.bgDeep)}- p.brushBgCard = dec.SolidColorBrush{Color: rgbHex(p.bgCard)}- return p- }- p := palette{- dark: false,- bgDeep: 0xF1F5F9, // slate-100, gentler than pure white- bgCard: 0xFFFFFF,- textHeading: 0x111827,- textBody: 0x1F2937,- textLabel: 0x374151,- textMuted: 0x6B7280,- textHelper: 0x9CA3AF,- indigo: 0x4F46E5,- errorRed: 0xDC2626,- successGr: 0x059669,- }- p.brushBgDeep = dec.SolidColorBrush{Color: rgbHex(p.bgDeep)}- p.brushBgCard = dec.SolidColorBrush{Color: rgbHex(p.bgCard)}- return p-}--// detectThemePalette currently always returns the light palette regardless-// of the user's Windows theme preference. Walk's native LineEdit and-// PushButton controls don't reliably respect dark mode (the white-input-on--// dark-card contrast looks broken), so until the wizard is ported to Wails-// we keep a single, consistent light palette. The registry-reading path is-// preserved below in case we want to flip this back when the controls-// behave.-func detectThemePalette() palette {- return newPalette(false)-}--// systemPrefersDark is the would-be feature toggle we'd hand detectThemePalette-// once we actually have themable inputs (i.e. after the Wails port).-func systemPrefersDark() bool {- k, err := registry.OpenKey(registry.CURRENT_USER,- `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`,- registry.QUERY_VALUE)- if err != nil {- return false- }- defer k.Close()- v, _, err := k.GetIntegerValue("AppsUseLightTheme")- if err != nil {- return false- }- return v == 0-}--func (p palette) Color(c uint32) walk.Color { return rgbHex(c) }diff --git a/agent/internal/setupui/window_other.go b/agent/internal/setupui/window_other.godeleted file mode 100644index 27f13217..00000000--- a/agent/internal/setupui/window_other.go+++ /dev/null@@ -1,16 +0,0 @@-//go:build !windows--package setupui--import (- "context"- "fmt"-- "github.com/serverkit/agent/internal/logger"-)--// runWindow returns an error directing non-Windows users to the CLI command.-// The desktop wizard is Windows-only because it uses native Win32 controls.-func runWindow(_ context.Context, _ *logger.Logger, _ string) error {- return fmt.Errorf("the graphical setup wizard is only available on Windows; on this platform run: serverkit-agent pair")-}diff --git a/agent/internal/setupui/window_windows.go b/agent/internal/setupui/window_windows.godeleted file mode 100644index e079cd3d..00000000--- a/agent/internal/setupui/window_windows.go+++ /dev/null@@ -1,698 +0,0 @@-//go:build windows--package setupui--import (- "bytes"- "context"- _ "embed"- "errors"- "fmt"- "image/png"- "os"- "runtime"- "strings"- "sync"- "time"-- "github.com/lxn/walk"- dec "github.com/lxn/walk/declarative"-- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/pairdriver"-)--//go:embed serverkit.ico-var iconBytes []byte--//go:embed serverkit_header.png-var headerPNG []byte--// stage names (used as panel keys for clarity)-const (- stageForm = "form"- stagePairing = "pairing"- stageDone = "done"-)--// runWindow shows the native pairing wizard. It blocks until the user closes-// the window (success, cancel, or X-button). Returns nil on graceful close.-//-// Walk's MainWindow event loop must run on the OS main thread; the caller-// (cmd/agent.runDesktop) is responsible for runtime.LockOSThread before us.-func runWindow(ctx context.Context, log *logger.Logger, configPath string) (retErr error) {- runtime.LockOSThread()-- // Surface panics as a real error dialog so a misconfigured widget can- // never produce the silent-failure mode that motivated this rewrite.- defer func() {- if r := recover(); r != nil {- retErr = fmt.Errorf("setup wizard panic: %v", r)- walk.MsgBox(nil, "ServerKit Agent", retErr.Error(), walk.MsgBoxIconError)- }- }()-- w := &wizardUI{- log: log,- configPath: configPath,- }-- // Hook ctx cancellation into the wizard: if the parent ctx is cancelled- // (e.g. SIGINT) we close the window from a goroutine.- w.runCtx, w.cancel = context.WithCancel(ctx)- defer w.cancel()-- go func() {- <-w.runCtx.Done()- if w.mw != nil {- w.mw.Synchronize(func() {- if w.mw != nil {- w.mw.Close()- }- })- }- }()-- return w.show()-}--type wizardUI struct {- log *logger.Logger- configPath string-- runCtx context.Context- cancel context.CancelFunc-- mu sync.Mutex- pairCancel context.CancelFunc-- mw *walk.MainWindow-- headerImage *walk.ImageView-- // stage 1 widgets- urlEdit *walk.LineEdit- nameEdit *walk.LineEdit- formErr *walk.Label- startBtn *walk.PushButton-- // stage 2 widgets- codeLabel *walk.Label- passLabel *walk.Label- copyCodeBtn *walk.PushButton- copyPassBtn *walk.PushButton- statusLabel *walk.Label- pairErrLabel *walk.Label- cancelBtn *walk.PushButton-- // raw values backing the copy buttons (codeLabel renders a spaced version)- rawCode string- rawPass string-- // stage 3 widgets- doneTitle *walk.Label- doneSub *walk.Label-- // stage panels- formPanel *walk.Composite- pairPanel *walk.Composite- donePanel *walk.Composite-}--func (w *wizardUI) show() error {- hostname, _ := os.Hostname()-- // Match the user's Windows theme so the wizard sits naturally on top of- // whatever the rest of their desktop looks like. The panel's own UI is- // light/dark adaptive; the wizard mirrors that.- pal := detectThemePalette()-- const (- titleSize = 14- bodySize = 9- smallSize = 8- codeSize = 32- )-- bgDeepBrush := pal.brushBgDeep- bgCardBrush := pal.brushBgCard-- textWhite := pal.textHeading- textPrimary := pal.textBody- textLabel := pal.textLabel- textMuted := pal.textMuted- textHelper := pal.textHelper- indigo := pal.indigo- errorRed := pal.errorRed- successGr := pal.successGr-- err := (dec.MainWindow{- AssignTo: &w.mw,- Title: "ServerKit Agent",- MinSize: dec.Size{Width: 460, Height: 600},- Size: dec.Size{Width: 460, Height: 600},- Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 24, Top: 24, Right: 24, Bottom: 24}, Spacing: 0},- Background: bgDeepBrush,- Children: []dec.Widget{- // ── Card surface (lighter than outer bg, simulates the .agent-window block) ──- dec.Composite{- Layout: dec.VBox{MarginsZero: false, Margins: dec.Margins{Left: 24, Top: 24, Right: 24, Bottom: 24}, Spacing: 0},- Background: bgCardBrush,- Children: []dec.Widget{- // ── Brand header ─────────────────────────────────────────- dec.Composite{- Layout: dec.HBox{MarginsZero: true, Spacing: 16},- Background: bgCardBrush,- Children: []dec.Widget{- dec.ImageView{- AssignTo: &w.headerImage,- MinSize: dec.Size{Width: 48, Height: 48},- MaxSize: dec.Size{Width: 48, Height: 48},- Mode: dec.ImageViewModeZoom,- Background: bgCardBrush,- },- dec.Composite{- Layout: dec.VBox{MarginsZero: true, Spacing: 4},- Background: bgCardBrush,- Children: []dec.Widget{- dec.VSpacer{},- dec.Label{- Text: "Pair this server",- Font: dec.Font{PointSize: titleSize, Bold: true, Family: "Segoe UI"},- TextColor: rgbHex(textWhite),- Background: bgCardBrush,- },- dec.Label{- Text: "Connect this machine to your ServerKit panel.",- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textMuted),- Background: bgCardBrush,- },- dec.VSpacer{},- },- },- },- },-- dec.VSpacer{Size: 28},-- // ── Stage 1: connection form ─────────────────────────────- dec.Composite{- AssignTo: &w.formPanel,- Layout: dec.VBox{MarginsZero: true, Spacing: 0},- Background: bgCardBrush,- Children: []dec.Widget{- // Panel URL- dec.Label{- Text: "Panel URL",- Font: dec.Font{Bold: true, PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textLabel),- Background: bgCardBrush,- },- dec.VSpacer{Size: 6},- dec.LineEdit{- AssignTo: &w.urlEdit,- CueBanner: "https://panel.example.com",- MaxLength: 500,- MinSize: dec.Size{Height: 28},- },- dec.VSpacer{Size: 6},- dec.Label{- Text: "The full URL of your ServerKit control panel.",- Font: dec.Font{PointSize: smallSize, Family: "Segoe UI"},- TextColor: rgbHex(textHelper),- Background: bgCardBrush,- },-- dec.VSpacer{Size: 20},-- // Server name- dec.Label{- Text: "Server name (optional)",- Font: dec.Font{Bold: true, PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textLabel),- Background: bgCardBrush,- },- dec.VSpacer{Size: 6},- dec.LineEdit{- AssignTo: &w.nameEdit,- Text: hostname,- CueBanner: "Defaults to hostname",- MinSize: dec.Size{Height: 28},- },- dec.VSpacer{Size: 6},- dec.Label{- Text: "How this machine appears in your panel.",- Font: dec.Font{PointSize: smallSize, Family: "Segoe UI"},- TextColor: rgbHex(textHelper),- Background: bgCardBrush,- },-- dec.VSpacer{Size: 20},-- dec.Label{- AssignTo: &w.formErr,- TextColor: rgbHex(errorRed),- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- Background: bgCardBrush,- Text: "",- },- dec.PushButton{- AssignTo: &w.startBtn,- Text: "Connect →",- MinSize: dec.Size{Height: 36},- Font: dec.Font{PointSize: bodySize, Bold: true, Family: "Segoe UI"},- OnClicked: w.handleConnect,- },- },- },-- // ── Stage 2: pairing code (hidden initially) ──────────────- // Mirrors the panel's "Add Server → Pair existing agent" drawer:- // the user reads the code here and types it into that field.- dec.Composite{- AssignTo: &w.pairPanel,- Visible: false,- Layout: dec.VBox{MarginsZero: true, Spacing: 0},- Background: bgCardBrush,- Children: []dec.Widget{- dec.Label{- Text: "On your panel, open Add Server → Pair existing agent.",- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textPrimary),- Background: bgCardBrush,- },- dec.VSpacer{Size: 4},- dec.Label{- Text: "Enter both values in the Pair code and Passphrase fields:",- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textMuted),- Background: bgCardBrush,- },- dec.VSpacer{Size: 20},- dec.Label{- Text: "Pair code",- Font: dec.Font{Bold: true, PointSize: smallSize, Family: "Segoe UI"},- TextColor: rgbHex(textLabel),- Background: bgCardBrush,- TextAlignment: dec.AlignCenter,- },- dec.VSpacer{Size: 6},- // Code "field" — visually echoes the panel's letter-spaced- // input. We can't render a real bordered box, but a- // centered Composite with the card colour at least- // gives the code its own dedicated zone.- dec.Composite{- Layout: dec.HBox{MarginsZero: true},- Background: bgCardBrush,- Children: []dec.Widget{- dec.HSpacer{},- dec.Label{- AssignTo: &w.codeLabel,- Text: "",- Font: dec.Font{PointSize: codeSize, Bold: true, Family: "Consolas"},- TextColor: rgbHex(indigo),- Background: bgCardBrush,- TextAlignment: dec.AlignCenter,- },- dec.HSpacer{},- },- },- dec.VSpacer{Size: 8},- dec.Composite{- Layout: dec.HBox{MarginsZero: true},- Background: bgCardBrush,- Children: []dec.Widget{- dec.HSpacer{},- dec.PushButton{- AssignTo: &w.copyCodeBtn,- Text: "Copy",- MinSize: dec.Size{Width: 90, Height: 26},- MaxSize: dec.Size{Width: 90, Height: 26},- Font: dec.Font{PointSize: smallSize, Family: "Segoe UI"},- OnClicked: w.copyCode,- },- dec.HSpacer{},- },- },- dec.VSpacer{Size: 18},- dec.Label{- Text: "Passphrase",- Font: dec.Font{Bold: true, PointSize: smallSize, Family: "Segoe UI"},- TextColor: rgbHex(textLabel),- Background: bgCardBrush,- TextAlignment: dec.AlignCenter,- },- dec.VSpacer{Size: 6},- dec.Composite{- Layout: dec.HBox{MarginsZero: true},- Background: bgCardBrush,- Children: []dec.Widget{- dec.HSpacer{},- dec.Label{- AssignTo: &w.passLabel,- Text: "",- Font: dec.Font{PointSize: 18, Bold: true, Family: "Consolas"},- TextColor: rgbHex(textPrimary),- Background: bgCardBrush,- TextAlignment: dec.AlignCenter,- },- dec.HSpacer{},- },- },- dec.VSpacer{Size: 8},- dec.Composite{- Layout: dec.HBox{MarginsZero: true},- Background: bgCardBrush,- Children: []dec.Widget{- dec.HSpacer{},- dec.PushButton{- AssignTo: &w.copyPassBtn,- Text: "Copy",- MinSize: dec.Size{Width: 90, Height: 26},- MaxSize: dec.Size{Width: 90, Height: 26},- Font: dec.Font{PointSize: smallSize, Family: "Segoe UI"},- OnClicked: w.copyPass,- },- dec.HSpacer{},- },- },- dec.VSpacer{Size: 20},- dec.Label{- AssignTo: &w.statusLabel,- Text: "Waiting for the panel to claim this server…",- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textHelper),- Background: bgCardBrush,- TextAlignment: dec.AlignCenter,- },- dec.Label{- AssignTo: &w.pairErrLabel,- TextColor: rgbHex(errorRed),- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- Background: bgCardBrush,- Text: "",- },- dec.VSpacer{Size: 20},- dec.PushButton{- AssignTo: &w.cancelBtn,- Text: "Cancel",- MinSize: dec.Size{Height: 34},- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- OnClicked: w.handleCancel,- },- },- },-- // ── Stage 3: success ─────────────────────────────────────- dec.Composite{- AssignTo: &w.donePanel,- Visible: false,- Layout: dec.VBox{MarginsZero: true, Spacing: 10},- Background: bgCardBrush,- Children: []dec.Widget{- dec.Label{- AssignTo: &w.doneTitle,- Text: "Successfully paired",- Font: dec.Font{PointSize: titleSize, Bold: true, Family: "Segoe UI"},- TextColor: rgbHex(successGr),- Background: bgCardBrush,- },- dec.Label{- AssignTo: &w.doneSub,- Text: "",- Font: dec.Font{PointSize: bodySize, Family: "Segoe UI"},- TextColor: rgbHex(textPrimary),- Background: bgCardBrush,- },- dec.VSpacer{Size: 8},- dec.PushButton{- Text: "Close",- MinSize: dec.Size{Height: 36},- Font: dec.Font{PointSize: bodySize, Bold: true, Family: "Segoe UI"},- OnClicked: func() { w.mw.Close() },- },- },- },-- dec.VSpacer{},-- // Subtle in-card footer mirrors the panel's brand strip.- dec.Composite{- Layout: dec.HBox{MarginsZero: true},- Background: bgCardBrush,- Children: []dec.Widget{- dec.HSpacer{},- dec.Label{- Text: "ServerKit • Pairing wizard",- Font: dec.Font{PointSize: smallSize, Family: "Segoe UI"},- TextColor: rgbHex(textHelper),- Background: bgCardBrush,- },- dec.HSpacer{},- },- },- },- },- },- }).Create()- if err != nil {- return fmt.Errorf("create window: %w", err)- }-- if icon, err := loadAppIcon(); err == nil && icon != nil {- _ = w.mw.SetIcon(icon)- }- if bmp, err := loadHeaderBitmap(); err == nil && bmp != nil && w.headerImage != nil {- _ = w.headerImage.SetImage(bmp)- }-- // Title-bar chrome stays system-default; we're light-themed everywhere- // for now to avoid the dark-card / white-input contrast clash.- w.mw.Show()- // Windows' anti-focus-stealing rule will leave the window invisible behind- // the desktop when the agent is launched from the Start menu shortcut.- // scheduleForceForeground retries the AttachThreadInput-based activation- // recipe several times across the first ~1.5s of window life so we win- // regardless of when walk's message pump actually starts servicing.- scheduleForceForeground(w.mw)- w.mw.Run()-- w.mu.Lock()- if w.pairCancel != nil {- w.pairCancel()- }- w.mu.Unlock()-- return nil-}--// handleConnect is fired by the "Connect" button. Validates inputs, kicks off-// pairing in a goroutine, and transitions to the pairing stage on success.-func (w *wizardUI) handleConnect() {- url := w.urlEdit.Text()- name := w.nameEdit.Text()-- if url == "" {- w.formErr.SetText("Panel URL is required.")- return- }- pass, err := pairdriver.GeneratePassphrase()- if err != nil {- w.formErr.SetText("Could not generate a passphrase: " + err.Error())- return- }- w.rawPass = pass- w.formErr.SetText("")- w.startBtn.SetEnabled(false)- w.startBtn.SetText("Connecting…")-- pairCtx, cancel := context.WithCancel(w.runCtx)- w.mu.Lock()- w.pairCancel = cancel- w.mu.Unlock()-- cb := pairdriver.Callbacks{- OnEnrolled: func(code, formatted string) {- w.mw.Synchronize(func() {- w.rawCode = code- w.codeLabel.SetText(displayCode(code, formatted))- w.passLabel.SetText(pass)- w.showStage(stagePairing)- })- },- OnClaimed: func(serverName string) {- w.mw.Synchronize(func() {- if serverName == "" {- serverName = "this server"- }- w.doneSub.SetText(fmt.Sprintf("This machine is now connected to ServerKit as %q.\n\nThe agent service has been started in the background. You can close this window.", serverName))- w.showStage(stageDone)- })- startServiceIfInstalled()- },- OnError: func(err error) {- w.mw.Synchronize(func() {- msg := errorPretty(err)- if w.pairPanel.Visible() {- w.pairErrLabel.SetText(msg)- w.cancelBtn.SetText("Try again")- } else {- w.formErr.SetText(msg)- w.startBtn.SetEnabled(true)- w.startBtn.SetText("Connect")- }- })- },- }-- go pairdriver.Run(pairCtx, w.log, w.configPath, url, pass, name, cb)-}--// handleCancel rolls back to the form stage and cancels any in-flight pairing.-func (w *wizardUI) handleCancel() {- w.mu.Lock()- if w.pairCancel != nil {- w.pairCancel()- w.pairCancel = nil- }- w.mu.Unlock()-- w.formErr.SetText("")- w.pairErrLabel.SetText("")- w.codeLabel.SetText("")- w.passLabel.SetText("")- w.copyCodeBtn.SetText("Copy")- w.copyPassBtn.SetText("Copy")- w.rawCode = ""- w.rawPass = ""- w.cancelBtn.SetText("Cancel")- w.startBtn.SetEnabled(true)- w.startBtn.SetText("Connect")- w.showStage(stageForm)-}--// copyCode / copyPass place the raw value on the clipboard and flash the-// button label so the user has visual confirmation that the click landed.-func (w *wizardUI) copyCode() { w.copyToClipboard(w.rawCode, w.copyCodeBtn) }-func (w *wizardUI) copyPass() { w.copyToClipboard(w.rawPass, w.copyPassBtn) }--func (w *wizardUI) copyToClipboard(value string, btn *walk.PushButton) {- if value == "" || btn == nil {- return- }- if cb := walk.Clipboard(); cb != nil {- _ = cb.SetText(value)- }- btn.SetText("Copied!")- time.AfterFunc(1500*time.Millisecond, func() {- if w.mw == nil {- return- }- w.mw.Synchronize(func() {- if btn != nil {- btn.SetText("Copy")- }- })- })-}--func (w *wizardUI) showStage(stage string) {- w.formPanel.SetVisible(stage == stageForm)- w.pairPanel.SetVisible(stage == stagePairing)- w.donePanel.SetVisible(stage == stageDone)-}--// errorPretty turns errors from runPairing into a user-friendly one-liner.-func errorPretty(err error) string {- if err == nil {- return ""- }- if errors.Is(err, context.Canceled) {- return "Cancelled."- }- return err.Error()-}--// displayCode renders the pair code with letter-spacing, mirroring the-// panel's "Add Server" input field which uses CSS letter-spacing: 0.5em on-// the same code. Walk Labels don't support letter-spacing as a property, so-// we fake it by inserting two-space gaps between glyphs of the unformatted-// code. Result for code "AB12CD" looks like "A B 1 2 C D".-func displayCode(code, formatted string) string {- raw := code- if raw == "" {- raw = formatted- }- clean := strings.ReplaceAll(raw, "-", "")- clean = strings.ReplaceAll(clean, " ", "")- if clean == "" {- return ""- }- var b strings.Builder- for i, r := range clean {- if i > 0 {- b.WriteString(" ")- }- b.WriteRune(r)- }- return b.String()-}--func rgbHex(rgb uint32) walk.Color {- return walk.RGB(byte(rgb>>16), byte(rgb>>8), byte(rgb))-}--// loadAppIcon writes the embedded .ico to a temp file (walk doesn't load icons-// from raw bytes) and returns it. The temp file lingers until process exit;-// Windows handles cleanup of %TEMP%.-var (- iconOnce sync.Once- iconRef *walk.Icon-)--func loadAppIcon() (*walk.Icon, error) {- iconOnce.Do(func() {- f, err := os.CreateTemp("", "serverkit-*.ico")- if err != nil {- return- }- _, _ = f.Write(iconBytes)- _ = f.Close()- ic, err := walk.NewIconFromFile(f.Name())- if err != nil {- return- }- iconRef = ic- })- if iconRef == nil {- return nil, fmt.Errorf("icon not loaded")- }- return iconRef, nil-}--// loadHeaderBitmap decodes the embedded brand PNG into a walk Bitmap suitable-// for an ImageView. Must be called after the walk runtime is up (i.e. after-// MainWindow.Create), otherwise the underlying GDI calls return errors.-var (- headerOnce sync.Once- headerBmp *walk.Bitmap-)--func loadHeaderBitmap() (*walk.Bitmap, error) {- headerOnce.Do(func() {- img, err := png.Decode(bytes.NewReader(headerPNG))- if err != nil {- return- }- bmp, err := walk.NewBitmapFromImageForDPI(img, 96)- if err != nil {- return- }- headerBmp = bmp- })- if headerBmp == nil {- return nil, fmt.Errorf("header bitmap not loaded")- }- return headerBmp, nil-}diff --git a/agent/internal/terminal/terminal.go b/agent/internal/terminal/terminal.godeleted file mode 100644index d46835ca..00000000--- a/agent/internal/terminal/terminal.go+++ /dev/null@@ -1,303 +0,0 @@-// Package terminal provides PTY (pseudo-terminal) support for remote shell sessions.-package terminal--import (- "context"- "fmt"- "io"- "os"- "os/exec"- "runtime"- "sync"-- "github.com/creack/pty"-)--// Session represents an active terminal session-type Session struct {- ID string- Shell string- Cols uint16- Rows uint16- cmd *exec.Cmd- pty *os.File- ctx context.Context- cancel context.CancelFunc- mu sync.Mutex- closed bool- onOutput func(data []byte)- onClose func()-}--// Manager manages terminal sessions-type Manager struct {- sessions map[string]*Session- mu sync.RWMutex-}--// NewManager creates a new terminal manager-func NewManager() *Manager {- return &Manager{- sessions: make(map[string]*Session),- }-}--// CreateSession creates a new terminal session-func (m *Manager) CreateSession(id string, cols, rows uint16) (*Session, error) {- m.mu.Lock()- defer m.mu.Unlock()-- // Check if session already exists- if _, exists := m.sessions[id]; exists {- return nil, fmt.Errorf("session %s already exists", id)- }-- // Determine the shell to use- shell := getDefaultShell()-- ctx, cancel := context.WithCancel(context.Background())-- session := &Session{- ID: id,- Shell: shell,- Cols: cols,- Rows: rows,- ctx: ctx,- cancel: cancel,- }-- // Start the shell with PTY- if err := session.start(); err != nil {- cancel()- return nil, fmt.Errorf("failed to start shell: %w", err)- }-- m.sessions[id] = session- return session, nil-}--// GetSession retrieves a session by ID-func (m *Manager) GetSession(id string) (*Session, bool) {- m.mu.RLock()- defer m.mu.RUnlock()- session, exists := m.sessions[id]- return session, exists-}--// CloseSession closes and removes a session-func (m *Manager) CloseSession(id string) error {- m.mu.Lock()- session, exists := m.sessions[id]- if exists {- delete(m.sessions, id)- }- m.mu.Unlock()-- if !exists {- return fmt.Errorf("session %s not found", id)- }-- return session.Close()-}--// CloseAll closes all sessions-func (m *Manager) CloseAll() {- m.mu.Lock()- sessions := make([]*Session, 0, len(m.sessions))- for _, s := range m.sessions {- sessions = append(sessions, s)- }- m.sessions = make(map[string]*Session)- m.mu.Unlock()-- for _, s := range sessions {- s.Close()- }-}--// ListSessions returns all active session IDs-func (m *Manager) ListSessions() []string {- m.mu.RLock()- defer m.mu.RUnlock()-- ids := make([]string, 0, len(m.sessions))- for id := range m.sessions {- ids = append(ids, id)- }- return ids-}--// start initializes the PTY and starts the shell-func (s *Session) start() error {- s.mu.Lock()- defer s.mu.Unlock()-- // Create the command- s.cmd = exec.CommandContext(s.ctx, s.Shell)-- // Set up environment- s.cmd.Env = append(os.Environ(),- "TERM=xterm-256color",- "COLORTERM=truecolor",- )-- // Start with PTY- ptmx, err := pty.StartWithSize(s.cmd, &pty.Winsize{- Cols: s.Cols,- Rows: s.Rows,- })- if err != nil {- return fmt.Errorf("failed to start pty: %w", err)- }-- s.pty = ptmx-- // Start reading output in background- go s.readLoop()-- return nil-}--// readLoop continuously reads from the PTY and calls the output handler-func (s *Session) readLoop() {- buf := make([]byte, 4096)-- for {- select {- case <-s.ctx.Done():- return- default:- }-- n, err := s.pty.Read(buf)- if err != nil {- if err != io.EOF {- // Log error but don't break - might be temporary- }- // Check if we should exit- s.mu.Lock()- closed := s.closed- s.mu.Unlock()- if closed {- return- }- // Shell might have exited- if s.onClose != nil {- s.onClose()- }- return- }-- if n > 0 && s.onOutput != nil {- // Make a copy of the data- data := make([]byte, n)- copy(data, buf[:n])- s.onOutput(data)- }- }-}--// Write sends input to the terminal-func (s *Session) Write(data []byte) (int, error) {- s.mu.Lock()- defer s.mu.Unlock()-- if s.closed || s.pty == nil {- return 0, fmt.Errorf("session is closed")- }-- return s.pty.Write(data)-}--// Resize changes the terminal size-func (s *Session) Resize(cols, rows uint16) error {- s.mu.Lock()- defer s.mu.Unlock()-- if s.closed || s.pty == nil {- return fmt.Errorf("session is closed")- }-- s.Cols = cols- s.Rows = rows-- return pty.Setsize(s.pty, &pty.Winsize{- Cols: cols,- Rows: rows,- })-}--// SetOutputHandler sets the callback for terminal output-func (s *Session) SetOutputHandler(handler func(data []byte)) {- s.onOutput = handler-}--// SetCloseHandler sets the callback for when the session closes-func (s *Session) SetCloseHandler(handler func()) {- s.onClose = handler-}--// Close terminates the terminal session-func (s *Session) Close() error {- s.mu.Lock()- defer s.mu.Unlock()-- if s.closed {- return nil- }-- s.closed = true- s.cancel()-- var errs []error-- if s.pty != nil {- if err := s.pty.Close(); err != nil {- errs = append(errs, fmt.Errorf("failed to close pty: %w", err))- }- }-- if s.cmd != nil && s.cmd.Process != nil {- if err := s.cmd.Process.Kill(); err != nil {- // Process might have already exited- }- }-- if len(errs) > 0 {- return errs[0]- }- return nil-}--// IsClosed returns whether the session is closed-func (s *Session) IsClosed() bool {- s.mu.Lock()- defer s.mu.Unlock()- return s.closed-}--// getDefaultShell returns the default shell for the current platform-func getDefaultShell() string {- if runtime.GOOS == "windows" {- // Try PowerShell first, fall back to cmd- if _, err := exec.LookPath("powershell.exe"); err == nil {- return "powershell.exe"- }- return "cmd.exe"- }-- // Unix: try to get user's shell from environment- if shell := os.Getenv("SHELL"); shell != "" {- return shell- }-- // Fall back to common shells- shells := []string{"/bin/bash", "/bin/sh", "/bin/zsh"}- for _, shell := range shells {- if _, err := os.Stat(shell); err == nil {- return shell- }- }-- return "/bin/sh"-}diff --git a/agent/internal/transport/manager.go b/agent/internal/transport/manager.godeleted file mode 100644index 2dc48198..00000000--- a/agent/internal/transport/manager.go+++ /dev/null@@ -1,282 +0,0 @@-package transport--import (- "context"- "strings"- "sync"- "sync/atomic"- "time"-- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/pkg/protocol"-)--// wsBackend is the slice of ws.Client functionality the manager needs.-// We avoid importing ws here to keep the dependency graph clean — the-// agent package wires concrete clients in via NewManager.-type wsBackend interface {- Transport- LastError() error- EverConnected() bool-}--// Manager wraps two Transports (WS primary, poll fallback) and presents a-// single Transport surface to the agent. It runs WS first; if WS doesn't-// authenticate within the upgrade deadline OR errors out with a tunnel--// incompat signature (RSV1, "engine.io handshake failed"), it shuts WS-// down and starts the polling client. The active transport is what every-// Send/SendHeartbeat/etc. call goes to.-//-// Once we've fallen back to polling, we stay there until the process-// restarts. Toggling back and forth would burn through reconnect/auth-// cycles and the whole point of falling back is "this network can't do-// WS." Restart-to-recover is fine — agents reconnect on service start-// and try WS again.-type Manager struct {- primary wsBackend- fallback Transport- log *logger.Logger- handler MessageHandler-- mu sync.RWMutex- active Transport- mode atomic.Value // Mode-- // Upgrade deadline: WS gets this long to complete a handshake before- // we declare it dead and switch to poll.- upgradeDeadline time.Duration-}--// NewManager constructs a transport manager. Pass the WS client as the-// primary and a poll client as the fallback.-func NewManager(primary wsBackend, fallback Transport, log *logger.Logger) *Manager {- m := &Manager{- primary: primary,- fallback: fallback,- log: log.WithComponent("transport"),- upgradeDeadline: 30 * time.Second,- }- m.active = primary- m.mode.Store(primary.Mode())- return m-}--// SetHandler installs the inbound dispatcher on both backends so a-// transport switch doesn't lose the binding.-func (m *Manager) SetHandler(h MessageHandler) {- m.handler = h- m.primary.SetHandler(h)- m.fallback.SetHandler(h)-}--// Mode reports which transport is currently active.-func (m *Manager) Mode() Mode {- if v, ok := m.mode.Load().(Mode); ok {- return v- }- return ModeWS-}--func (m *Manager) IsConnected() bool {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.IsConnected()-}--func (m *Manager) Send(msg interface{}) error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.Send(msg)-}--func (m *Manager) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.SendHeartbeat(metrics)-}--func (m *Manager) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.SendCommandResult(commandID, success, data, errMsg, duration)-}--func (m *Manager) SendStream(channel string, data interface{}) error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.SendStream(channel, data)-}--func (m *Manager) SendError(code, details string) error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.SendError(code, details)-}--func (m *Manager) Session() *auth.SessionToken {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.Session()-}--func (m *Manager) Close() error {- m.mu.RLock()- defer m.mu.RUnlock()- return m.active.Close()-}--// Stability thresholds for the WS-flap detector. CF tunnels and other-// proxies can let WS connect successfully but kill it every couple of-// minutes — the symptom your events.json shows is "ws_connected →-// ws_disconnected" cycling forever, which generates pointless reconnect-// traffic without ever delivering live streams. Once we see the-// connection prove itself unstable, drop to polling permanently and-// stop wasting bandwidth on retries.-const (- wsFlapWindow = 10 * time.Minute- wsFlapThreshold = 3 // disconnects within wsFlapWindow that trigger fallback-)--// Run executes the WS transport and watches for tunnel-incompat-// failures. When detected, it cancels WS and runs the poll transport.-// Blocks until ctx is cancelled.-func (m *Manager) Run(ctx context.Context) error {- wsCtx, cancelWS := context.WithCancel(ctx)- defer cancelWS()-- wsDone := make(chan error, 1)- go func() {- wsDone <- m.primary.Run(wsCtx)- }()-- // Watch WS for tunnel-incompat failure within the upgrade deadline.- // If detected, kill WS and run poll for the rest of ctx's lifetime.- deadline := time.NewTimer(m.upgradeDeadline)- defer deadline.Stop()-- check := time.NewTicker(2 * time.Second)- defer check.Stop()-- // Stability monitor: ticks at 1Hz to sample IsConnected and record- // transitions. When we see wsFlapThreshold disconnects within- // wsFlapWindow, give up on WS and run the fallback.- stabilityTicker := time.NewTicker(1 * time.Second)- defer stabilityTicker.Stop()- wasConnected := false- disconnectTimes := make([]time.Time, 0, wsFlapThreshold+1)-- for {- select {- case <-ctx.Done():- cancelWS()- <-wsDone- return ctx.Err()-- case err := <-wsDone:- // WS exited on its own (rare — its loop runs until ctx is- // done). If ctx isn't cancelled, treat this as a permanent- // WS failure and fall back.- if ctx.Err() != nil {- return ctx.Err()- }- m.log.Warn("WS transport exited; falling back to polling", "error", err)- return m.runFallback(ctx)-- case <-deadline.C:- // Soft deadline: WS hasn't authenticated yet. If it never has- // AND the last error looks like a tunnel issue, fall back.- // If WS just hasn't connected yet for a benign reason- // (panel slow to start), give it more rope.- if !m.primary.EverConnected() {- lastErr := m.primary.LastError()- if isTunnelIncompat(lastErr) {- m.log.Warn("WS handshake failed with a tunnel-incompat signature; falling back to polling",- "error", lastErr)- cancelWS()- <-wsDone- return m.runFallback(ctx)- }- m.log.Info("WS not yet connected after upgrade deadline; continuing to retry",- "last_error", lastErr)- }- // Stop checking after the soft deadline; if WS is still- // trying it'll either succeed eventually or stay broken- // quietly. The user can restart the service to retry from- // scratch.-- case <-check.C:- // While WS is still inside the upgrade window, check- // proactively for unambiguous failure modes that warrant a- // fast switch instead of waiting out the deadline.- if !m.primary.EverConnected() {- if isTunnelIncompat(m.primary.LastError()) {- m.log.Warn("WS reports tunnel-incompat error; falling back early to polling",- "error", m.primary.LastError())- cancelWS()- <-wsDone- return m.runFallback(ctx)- }- } else {- // WS got through. Stop the deadline timer — we're good.- deadline.Stop()- }-- case now := <-stabilityTicker.C:- // Sample the WS connection state and detect flap patterns:- // repeatedly connecting then dropping within minutes- // indicates an intermediary (CF tunnel, ngrok, NAT timeout)- // that won't keep a long-lived WS open. Counting drops in a- // sliding window catches both rapid churn and the slower- // "drops every couple minutes" pattern reported in- // events.json.- isConn := m.primary.IsConnected()- if !isConn && wasConnected {- disconnectTimes = append(disconnectTimes, now)- // Trim drops outside the window.- cutoff := now.Add(-wsFlapWindow)- kept := disconnectTimes[:0]- for _, t := range disconnectTimes {- if t.After(cutoff) {- kept = append(kept, t)- }- }- disconnectTimes = kept- m.log.Info("WS disconnected", "drops_in_window", len(disconnectTimes))- if len(disconnectTimes) >= wsFlapThreshold {- m.log.Warn("WS connection unstable — falling back to polling permanently",- "drops", len(disconnectTimes),- "window_minutes", int(wsFlapWindow.Minutes()))- cancelWS()- <-wsDone- return m.runFallback(ctx)- }- }- wasConnected = isConn- }- }-}--func (m *Manager) runFallback(ctx context.Context) error {- m.mu.Lock()- m.active = m.fallback- m.mu.Unlock()- m.mode.Store(m.fallback.Mode())- m.log.Info("Active transport switched to polling (streams unavailable in this mode)")- return m.fallback.Run(ctx)-}--// isTunnelIncompat reports whether err carries one of the known-// signatures of a tunnel intermediary mangling WebSocket frames.-// Matches both "RSV1" frame errors and engine.io handshake failures-// after a successful TCP/TLS dial — both indicate the connection is-// reaching the panel but the WS layer is unusable.-func isTunnelIncompat(err error) bool {- if err == nil {- return false- }- msg := err.Error()- return strings.Contains(msg, "RSV1 set") ||- strings.Contains(msg, "engine.io handshake failed") ||- strings.Contains(msg, "websocket: close 1006") // abnormal closure mid-handshake-}diff --git a/agent/internal/transport/poll/client.go b/agent/internal/transport/poll/client.godeleted file mode 100644index 976d16d4..00000000--- a/agent/internal/transport/poll/client.go+++ /dev/null@@ -1,437 +0,0 @@-// Package poll implements the REST long-poll fallback transport.-//-// Used when WS-incompatible tunnels (free-tier ngrok, Cloudflare quick-// tunnels) corrupt WebSocket frames. Endpoints (panel side):-//-// POST /api/v1/agent/connect — HMAC auth, returns session_token-// POST /api/v1/agent/poll — heartbeat + long-poll for commands-// POST /api/v1/agent/result — command result-// POST /api/v1/agent/disconnect — clean shutdown-//-// Streams (logs/metrics fan-out, terminal) are intentionally dropped —-// streaming features degrade to "view recent only" via the panel REST API.-package poll--import (- "bytes"- "context"- "crypto/tls"- "encoding/json"- "fmt"- "io"- "net/http"- "net/url"- "os"- "strings"- "sync"- "sync/atomic"- "time"-- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/transport"- "github.com/serverkit/agent/pkg/protocol"-)--// Version is the agent version string surfaced in the User-Agent-// header. Defaults to "dev"; main.go's init() mirrors the ldflags-set-// main.Version into this on release builds. Was previously a hardcoded-// "dev" literal which made the panel display "ServerKit-Agent-Poll/dev"-// regardless of the actual built version.-var Version = "dev"--// Client is the polling-mode transport. Mirrors the surface of ws.Client-// so agent.Agent doesn't need to know which transport is wired up.-type Client struct {- cfg config.ServerConfig- auth *auth.Authenticator- log *logger.Logger- http *http.Client- handler transport.MessageHandler-- mu sync.Mutex- session *auth.SessionToken- connected atomic.Bool-- // Heartbeat metrics buffered between /poll requests. Updated when- // SendHeartbeat is called; read and cleared by the poll loop.- hbMu sync.Mutex- hbMetrics *protocol.HeartbeatMetrics- // One-shot system info, sent on the first /poll after it's queued.- sysInfo map[string]interface{}- // One-shot capabilities, sent on the first /poll after it's queued.- // Re-queued on every reconnect by agent.connectionWatcher so the- // panel's record stays current after a panel restart.- caps map[string]interface{}-- baseURL string-}--// NewClient constructs a poll-mode client. baseURL is derived from the-// configured server URL — wss://host/agent → https://host. The agent-// already gets an http(s) scheme out of buildBaseURL.-func NewClient(cfg config.ServerConfig, authenticator *auth.Authenticator, log *logger.Logger) *Client {- c := &Client{- cfg: cfg,- auth: authenticator,- log: log.WithComponent("poll"),- http: &http.Client{- Timeout: 35 * time.Second, // > server long-poll window (25s)- },- }- if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {- c.http.Transport = &http.Transport{- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},- }- }- c.baseURL = buildBaseURL(cfg.URL)- return c-}--// buildBaseURL converts the configured ws(s) server URL to its http(s)-// equivalent and strips the namespace path. Examples:-// wss://panel.example.com/agent → https://panel.example.com-// ws://localhost:5000/agent → http://localhost:5000-func buildBaseURL(raw string) string {- if raw == "" {- return ""- }- u, err := url.Parse(raw)- if err != nil {- return ""- }- switch u.Scheme {- case "wss":- u.Scheme = "https"- case "ws":- u.Scheme = "http"- }- u.Path = ""- u.RawQuery = ""- return strings.TrimRight(u.String(), "/")-}--func (c *Client) SetHandler(h transport.MessageHandler) { c.handler = h }-func (c *Client) Mode() transport.Mode { return transport.ModePoll }-func (c *Client) Session() *auth.SessionToken {- c.mu.Lock()- defer c.mu.Unlock()- return c.session-}-func (c *Client) IsConnected() bool { return c.connected.Load() }--// Run authenticates, then runs the long-poll loop until ctx is cancelled-// or auth fails irrecoverably. Reconnects on transient errors.-func (c *Client) Run(ctx context.Context) error {- if err := c.connect(ctx); err != nil {- return fmt.Errorf("poll connect: %w", err)- }- c.log.Info("Connected via polling transport", "base", c.baseURL)- defer c.disconnect()-- backoff := 1 * time.Second- const backoffMax = 30 * time.Second-- for {- if ctx.Err() != nil {- return ctx.Err()- }- err := c.pollOnce(ctx)- if err == nil {- backoff = 1 * time.Second- continue- }- if ctx.Err() != nil {- return ctx.Err()- }- // Transient — back off and retry. Fatal-class errors (401)- // are re-handled by re-authenticating.- c.log.Warn("Poll cycle failed", "error", err, "backoff", backoff)- c.connected.Store(false)- select {- case <-ctx.Done():- return ctx.Err()- case <-time.After(backoff):- }- if backoff < backoffMax {- backoff *= 2- }- if isAuthError(err) {- if cerr := c.connect(ctx); cerr != nil {- c.log.Warn("Re-auth failed", "error", cerr)- } else {- c.log.Info("Re-authenticated polling session")- backoff = 1 * time.Second- }- }- }-}--func (c *Client) connect(ctx context.Context) error {- timestamp := time.Now().UnixMilli()- nonce := auth.GenerateNonce()- signature := c.auth.SignMessageWithNonce(timestamp, nonce)-- body := map[string]interface{}{- "agent_id": c.auth.AgentID(),- "api_key_prefix": c.auth.GetAPIKeyPrefix(),- "signature": signature,- "timestamp": timestamp,- "nonce": nonce,- }- var resp struct {- Success bool `json:"success"`- SessionToken string `json:"session_token"`- ServerID string `json:"server_id"`- PollInterval int `json:"poll_interval_s"`- Error string `json:"error"`- }- if err := c.postJSON(ctx, "/api/v1/agent/connect", "", body, &resp); err != nil {- return err- }- if !resp.Success {- return fmt.Errorf("auth rejected: %s", resp.Error)- }- c.mu.Lock()- c.session = &auth.SessionToken{- Token: resp.SessionToken,- ExpiresAt: time.Now().Add(1 * time.Hour),- }- c.mu.Unlock()- c.connected.Store(true)- return nil-}--func (c *Client) disconnect() {- c.mu.Lock()- tok := ""- if c.session != nil {- tok = c.session.Token- }- c.mu.Unlock()- if tok == "" {- return- }- // Best-effort, don't block — server cleans up on heartbeat timeout- // regardless. Use a short context so shutdown isn't held up.- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- _ = c.postJSON(ctx, "/api/v1/agent/disconnect", tok, nil, nil)- c.connected.Store(false)-}--// pollOnce executes a single /poll request, dispatches any returned-// commands through the handler, and sends a one-shot system_info-// payload if queued. Returns the request error, if any.-func (c *Client) pollOnce(ctx context.Context) error {- c.mu.Lock()- tok := ""- if c.session != nil {- tok = c.session.Token- }- c.mu.Unlock()- if tok == "" {- return fmt.Errorf("no session")- }-- // Don't drain the system_info / capabilities buffers here. They- // get refreshed by the agent every 5–60s anyway, and if /poll- // fails (tunnel reconnect, transient 5xx) the previous behaviour- // was to silently lose the payload — the panel would then show- // "none reported" until the next sendCapabilities tick. Re-sending- // the same payload on every /poll is cheap and the panel's- // update_capabilities is idempotent (pure overwrite).- c.hbMu.Lock()- body := map[string]interface{}{}- if c.hbMetrics != nil {- body["metrics"] = c.hbMetrics- }- if c.sysInfo != nil {- body["system_info"] = c.sysInfo- }- if c.caps != nil {- body["capabilities"] = c.caps- }- c.hbMu.Unlock()-- var resp struct {- Commands []json.RawMessage `json:"commands"`- Ack bool `json:"ack"`- }- if err := c.postJSON(ctx, "/api/v1/agent/poll", tok, body, &resp); err != nil {- return err- }- c.connected.Store(true)-- for _, cmd := range resp.Commands {- c.dispatchCommand(cmd)- }- return nil-}--// dispatchCommand routes a server-issued command to the agent's-// MessageHandler. The wire format mirrors what AgentNamespace emits.-func (c *Client) dispatchCommand(payload json.RawMessage) {- if c.handler == nil {- c.log.Warn("Dropping command — no handler installed")- return- }- c.handler(protocol.TypeCommand, []byte(payload))-}--// SendHeartbeat buffers metrics for the next /poll request.-func (c *Client) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {- c.hbMu.Lock()- defer c.hbMu.Unlock()- m := metrics- c.hbMetrics = &m- return nil-}--// SendCommandResult posts the outcome of a server-issued command.-func (c *Client) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {- c.mu.Lock()- tok := ""- if c.session != nil {- tok = c.session.Token- }- c.mu.Unlock()- body := map[string]interface{}{- "command_id": commandID,- "success": success,- "data": data,- "error": errMsg,- "duration": int64(duration.Milliseconds()),- }- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- return c.postJSON(ctx, "/api/v1/agent/result", tok, body, nil)-}--// SendStream is a no-op in poll mode — streaming features degrade to-// "view recent only" via the panel's REST API. We log at debug because-// the agent emits these often (system metrics fan-out) and warning-level-// would flood desktop.log.-func (c *Client) SendStream(channel string, data interface{}) error {- c.log.Debug("Dropping stream in poll mode", "channel", channel)- return nil-}--// SendError is best-effort — embed in next /poll body. Acceptable to-// drop because errors are also persisted server-side via heartbeat-// metadata in most cases.-func (c *Client) SendError(code, details string) error {- c.log.Warn("Agent error in poll mode", "code", code, "details", details)- return nil-}--// Send is the catch-all for protocol packets that don't fit the-// dedicated methods. The polling protocol only handles the explicit-// methods, so we surface a soft warning rather than fail.-func (c *Client) Send(msg interface{}) error {- // Special-case system_info because the agent emits it on connect.- if m, ok := msg.(map[string]interface{}); ok {- if t, _ := m["type"].(string); t == string(protocol.TypeSystemInfo) {- info, _ := m["info"].(map[string]interface{})- c.hbMu.Lock()- c.sysInfo = info- c.hbMu.Unlock()- return nil- }- }- // Typed SystemInfoMessage path — the agent ships these on connect- // and on a periodic cadence so the panel can persist CPU/memory/- // disk/docker info. Round-trip through JSON to extract the inner- // info field without a struct dependency in this layer.- if sm, ok := msg.(protocol.SystemInfoMessage); ok {- buf, err := json.Marshal(sm.Info)- if err != nil {- return err- }- var raw map[string]interface{}- if err := json.Unmarshal(buf, &raw); err != nil {- return err- }- c.hbMu.Lock()- c.sysInfo = raw- c.hbMu.Unlock()- return nil- }- // Capabilities arrive as a typed struct (CapabilitiesMessage), not- // a map — round-trip through JSON to lift the inner fields out- // without growing this layer a Go-typed dependency on the- // protocol message shape.- if cm, ok := msg.(protocol.CapabilitiesMessage); ok {- buf, err := json.Marshal(cm)- if err != nil {- return err- }- var raw map[string]interface{}- if err := json.Unmarshal(buf, &raw); err != nil {- return err- }- // Strip the envelope (type/id/timestamp/signature) — the panel- // poll endpoint cares about the inner payload.- delete(raw, "type")- delete(raw, "id")- delete(raw, "timestamp")- delete(raw, "signature")- c.hbMu.Lock()- c.caps = raw- c.hbMu.Unlock()- return nil- }- c.log.Debug("Dropping unsupported Send in poll mode")- return nil-}--func (c *Client) Close() error {- c.disconnect()- return nil-}--// postJSON sends a JSON body and decodes a JSON response. Empty body or-// out is allowed for endpoints that don't have one.-func (c *Client) postJSON(ctx context.Context, path, token string, body interface{}, out interface{}) error {- var rdr io.Reader- if body != nil {- buf, err := json.Marshal(body)- if err != nil {- return fmt.Errorf("marshal body: %w", err)- }- rdr = bytes.NewReader(buf)- }- req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, rdr)- if err != nil {- return err- }- req.Header.Set("Content-Type", "application/json")- req.Header.Set("Accept", "application/json")- req.Header.Set("User-Agent", "ServerKit-Agent-Poll/"+Version)- if token != "" {- req.Header.Set("X-Session-Token", token)- }- resp, err := c.http.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode == http.StatusUnauthorized {- return errAuth- }- if resp.StatusCode >= 400 {- b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))- return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))- }- if out == nil {- return nil- }- return json.NewDecoder(resp.Body).Decode(out)-}--var errAuth = fmt.Errorf("session unauthorized")--func isAuthError(err error) bool {- return err != nil && (err == errAuth || strings.Contains(err.Error(), "session unauthorized"))-}diff --git a/agent/internal/transport/transport.go b/agent/internal/transport/transport.godeleted file mode 100644index 1c43f8d2..00000000--- a/agent/internal/transport/transport.go+++ /dev/null@@ -1,84 +0,0 @@-// Package transport abstracts the agent ↔ panel link. Two implementations-// share the same surface:-//-// - ws (internal/ws.Client) — primary, long-lived Socket.IO connection.-// - poll (internal/transport/poll.Client) — REST long-poll fallback used-// when WS-incompatible tunnels (free-tier ngrok, cf quick tunnels)-// mangle WebSocket frames.-//-// agent.Agent talks to a Transport, not a concrete client, and a small-// fallback Manager swaps which one is wired up when WS connectivity-// keeps failing.-package transport--import (- "context"- "time"-- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/pkg/protocol"-)--// MessageHandler is invoked when an inbound packet (typically a command)-// arrives from the panel. data is the raw JSON payload.-type MessageHandler func(msgType protocol.MessageType, data []byte)--// Mode names a transport implementation. Surfaced through IPC so the UI-// can show "Connected via polling" when the agent has fallen back.-type Mode string--const (- ModeWS Mode = "ws"- ModePoll Mode = "poll"-)--// Transport is the shared surface between WS and polling.-//-// Streaming methods (SendStream) are best-effort — the polling-// implementation drops them silently. Callers must not rely on stream-// delivery for correctness.-type Transport interface {- // SetHandler installs the inbound message dispatcher.- SetHandler(MessageHandler)-- // Run blocks until ctx is cancelled or the transport gives up. WS- // runs the read/write/ping/reconnect loops; poll runs the- // long-poll loop. Returns the reason it exited so the manager can- // decide whether to retry, fall back, or surface the error.- Run(ctx context.Context) error-- // IsConnected reports whether the transport is currently live (WS:- // authenticated socket open; poll: at least one /poll round-trip- // succeeded recently).- IsConnected() bool-- // Send pushes a generic JSON-able message; only meaningful for WS.- // Polling silently no-ops on these unless they map to a known- // command result.- Send(msg interface{}) error-- // SendHeartbeat dispatches metrics. WS sends an event; polling- // piggybacks on the next /poll request.- SendHeartbeat(metrics protocol.HeartbeatMetrics) error-- // SendCommandResult delivers the outcome of a command. Both- // transports route this synchronously.- SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error-- // SendStream pushes streaming data (logs, container output, real-time- // metrics fan-out). Polling drops these — streaming features- // degrade naturally to "view recent only" via the panel's REST API.- SendStream(channel string, data interface{}) error-- // SendError surfaces an error to the panel. Best-effort.- SendError(code, details string) error-- // Session returns the current session token, or nil if unauthenticated.- Session() *auth.SessionToken-- // Close terminates the transport.- Close() error-- // Mode reports which implementation this is.- Mode() Mode-}diff --git a/agent/internal/tray/client.go b/agent/internal/tray/client.godeleted file mode 100644index 67e18c1b..00000000--- a/agent/internal/tray/client.go+++ /dev/null@@ -1,201 +0,0 @@-package tray--import (- "encoding/json"- "fmt"- "net/http"- "os"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/ipc"-)--// Client communicates with the agent's IPC server-type Client struct {- baseURL string- httpClient *http.Client- // token is the bearer credential the IPC server requires on every- // endpoint except /health. Loaded lazily from disk on each request- // so the tray picks up token rotations without restart. An empty- // token still lets /health probes work (the only endpoint the- // IPC server leaves unauthenticated), but every other call will- // 401 — IsAgentRunning() therefore stays accurate.- token string-}--// NewClient creates a new IPC client-func NewClient(address string, port int) *Client {- return &Client{- baseURL: fmt.Sprintf("http://%s:%d", address, port),- httpClient: &http.Client{- Timeout: 5 * time.Second,- },- }-}--// loadToken reads the IPC token from the well-known path the agent-// service writes on startup. Best-effort: a missing file just means-// "agent never finished initialising the IPC server" — the caller-// gets a 401 and surfaces it as an unreachable agent.-func (c *Client) loadToken() string {- if data, err := os.ReadFile(config.IPCTokenPath()); err == nil {- return strings.TrimSpace(string(data))- }- return ""-}--// authedRequest builds a GET/POST with the Authorization header set.-// Centralising the header lets us swap to a different scheme later-// without touching every endpoint method.-func (c *Client) authedRequest(method, url string) (*http.Request, error) {- req, err := http.NewRequest(method, url, nil)- if err != nil {- return nil, err- }- if tok := c.loadToken(); tok != "" {- req.Header.Set("Authorization", "Bearer "+tok)- }- return req, nil-}--// GetStatus fetches the agent status-func (c *Client) GetStatus() (*ipc.AgentStatus, error) {- req, err := c.authedRequest(http.MethodGet, c.baseURL+"/status")- if err != nil {- return nil, err- }- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)- }-- var status ipc.AgentStatus- if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {- return nil, err- }-- return &status, nil-}--// GetMetrics fetches detailed system metrics-func (c *Client) GetMetrics() (*ipc.DetailedMetrics, error) {- req, err := c.authedRequest(http.MethodGet, c.baseURL+"/metrics")- if err != nil {- return nil, err- }- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)- }-- var metrics ipc.DetailedMetrics- if err := json.NewDecoder(resp.Body).Decode(&metrics); err != nil {- return nil, err- }-- return &metrics, nil-}--// GetConnection fetches WebSocket connection info-func (c *Client) GetConnection() (*ipc.ConnectionInfo, error) {- req, err := c.authedRequest(http.MethodGet, c.baseURL+"/connection")- if err != nil {- return nil, err- }- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)- }-- var info ipc.ConnectionInfo- if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {- return nil, err- }-- return &info, nil-}--// GetLogs fetches recent log lines-func (c *Client) GetLogs(lines int) ([]string, error) {- req, err := c.authedRequest(http.MethodGet, fmt.Sprintf("%s/logs?lines=%d", c.baseURL, lines))- if err != nil {- return nil, err- }- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)- }-- var result struct {- Lines []string `json:"lines"`- }- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return nil, err- }-- return result.Lines, nil-}--// Restart requests agent restart-func (c *Client) Restart() error {- req, err := c.authedRequest(http.MethodPost, c.baseURL+"/restart")- if err != nil {- return err- }- req.Header.Set("Content-Type", "application/json")- resp, err := c.httpClient.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("unexpected status: %d", resp.StatusCode)- }-- var result struct {- Success bool `json:"success"`- Error string `json:"error,omitempty"`- }- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {- return err- }-- if !result.Success {- return fmt.Errorf("restart failed: %s", result.Error)- }-- return nil-}--// IsAgentRunning checks if the agent is reachable-func (c *Client) IsAgentRunning() bool {- resp, err := c.httpClient.Get(c.baseURL + "/health")- if err != nil {- return false- }- defer resp.Body.Close()- return resp.StatusCode == http.StatusOK-}diff --git a/agent/internal/tray/icons.go b/agent/internal/tray/icons.godeleted file mode 100644index f1ea61d5..00000000--- a/agent/internal/tray/icons.go+++ /dev/null@@ -1,50 +0,0 @@-package tray--import (- _ "embed"-)--// Icon states for the system tray-// Icons should be 16x16 or 32x32 PNG/ICO files-// These are embedded at compile time--// Default icons are simple colored squares-// Replace these with actual icon files for production--//go:embed icons/connected.ico-var iconConnected []byte--//go:embed icons/disconnected.ico-var iconDisconnected []byte--//go:embed icons/error.ico-var iconError []byte--//go:embed icons/stopped.ico-var iconStopped []byte--// IconState represents the current icon state-type IconState int--const (- IconStateConnected IconState = iota // Green - connected and running- IconStateDisconnected // Yellow - running but disconnected- IconStateError // Red - error state- IconStateStopped // Gray - agent not running-)--// GetIcon returns the icon bytes for a given state-func GetIcon(state IconState) []byte {- switch state {- case IconStateConnected:- return iconConnected- case IconStateDisconnected:- return iconDisconnected- case IconStateError:- return iconError- case IconStateStopped:- return iconStopped- default:- return iconStopped- }-}diff --git a/agent/internal/tray/icons/connected.ico b/agent/internal/tray/icons/connected.icodeleted file mode 100644index 8d1b44a4..00000000Binary files a/agent/internal/tray/icons/connected.ico and /dev/null differdiff --git a/agent/internal/tray/icons/disconnected.ico b/agent/internal/tray/icons/disconnected.icodeleted file mode 100644index 6c21cc3d..00000000Binary files a/agent/internal/tray/icons/disconnected.ico and /dev/null differdiff --git a/agent/internal/tray/icons/error.ico b/agent/internal/tray/icons/error.icodeleted file mode 100644index 565eeab5..00000000Binary files a/agent/internal/tray/icons/error.ico and /dev/null differdiff --git a/agent/internal/tray/icons/stopped.ico b/agent/internal/tray/icons/stopped.icodeleted file mode 100644index 435cb151..00000000Binary files a/agent/internal/tray/icons/stopped.ico and /dev/null differdiff --git a/agent/internal/tray/tray.go b/agent/internal/tray/tray.godeleted file mode 100644index a7d9ea1b..00000000--- a/agent/internal/tray/tray.go+++ /dev/null@@ -1,376 +0,0 @@-package tray--import (- "fmt"- "os/exec"- "runtime"- "sync"- "time"-- "fyne.io/systray"-- "github.com/serverkit/agent/internal/config"-)--// AppConfig holds tray app configuration-type AppConfig struct {- Version string- IPCAddress string- IPCPort int- ServerURL string- DashboardURL string- LogFile string- // NeedsSetup is set by runDesktop when the agent has no pairing config- // yet. The tray shows a prominent "Open setup wizard…" item in that case- // so the user can recover from a closed-without-pairing wizard window.- NeedsSetup bool- OnOpenSetup func()- OnOpenLogs func()-}--// App is the system tray application-type App struct {- config AppConfig- client *Client-- // Current state- mu sync.RWMutex- connected bool- agentRunning bool- lastStatus string- cpuPercent float64- memPercent float64-- // Menu items- menuSetup *systray.MenuItem- menuStatus *systray.MenuItem- menuCPU *systray.MenuItem- menuMem *systray.MenuItem- menuStartAgent *systray.MenuItem- menuStopAgent *systray.MenuItem- menuRestartAgent *systray.MenuItem- menuViewLogs *systray.MenuItem- menuDashboard *systray.MenuItem- menuAbout *systray.MenuItem- menuQuit *systray.MenuItem-- // Control channels- quitCh chan struct{}-}--// NewApp creates a new tray application-func NewApp(config AppConfig) *App {- return &App{- config: config,- client: NewClient(config.IPCAddress, config.IPCPort),- quitCh: make(chan struct{}),- }-}--// Run starts the tray application (blocking)-func (a *App) Run() {- systray.Run(a.onReady, a.onExit)-}--// Quit requests the tray app to quit-func (a *App) Quit() {- close(a.quitCh)- systray.Quit()-}--func (a *App) onReady() {- // Set initial icon (gray/stopped)- systray.SetIcon(GetIcon(IconStateStopped))- systray.SetTitle("ServerKit")- systray.SetTooltip("ServerKit Agent")-- // Always create the setup item — its title flips between "Open setup- // wizard…" (unconfigured) and "Re-pair this server…" (configured) based- // on what refresh() observes. Putting it first means the user can always- // reach pairing from the tray, which is the user-visible recovery surface.- a.menuSetup = systray.AddMenuItem("Open setup wizard…", "Pair this server with a ServerKit panel")- systray.AddSeparator()-- // Create menu items- a.menuStatus = systray.AddMenuItem("Status: Checking...", "Agent status")- a.menuStatus.Disable()-- a.menuCPU = systray.AddMenuItem("CPU: --", "CPU usage")- a.menuCPU.Disable()-- a.menuMem = systray.AddMenuItem("Memory: --", "Memory usage")- a.menuMem.Disable()-- systray.AddSeparator()-- a.menuStartAgent = systray.AddMenuItem("Start Agent", "Start the ServerKit agent service")- a.menuStopAgent = systray.AddMenuItem("Stop Agent", "Stop the ServerKit agent service")- a.menuRestartAgent = systray.AddMenuItem("Restart Agent", "Restart the ServerKit agent service")-- systray.AddSeparator()-- a.menuViewLogs = systray.AddMenuItem("View Logs", "Open log file")- a.menuDashboard = systray.AddMenuItem("Open Dashboard", "Open ServerKit dashboard in browser")- if a.config.DashboardURL == "" {- a.menuDashboard.Disable()- }-- systray.AddSeparator()-- a.menuAbout = systray.AddMenuItem(fmt.Sprintf("About ServerKit Tray v%s", a.config.Version), "About this application")- a.menuAbout.Disable()-- a.menuQuit = systray.AddMenuItem("Quit Tray", "Exit the tray application")-- // Start background refresh- go a.refreshLoop()-- // Handle menu clicks- go a.handleMenuClicks()-}--func (a *App) onExit() {- // Cleanup on exit-}--func (a *App) refreshLoop() {- // Initial fetch- a.refresh()-- ticker := time.NewTicker(5 * time.Second)- defer ticker.Stop()-- for {- select {- case <-a.quitCh:- return- case <-ticker.C:- a.refresh()- }- }-}--func (a *App) refresh() {- // Re-load config every refresh so the tray picks up freshly-saved- // credentials from a separate setup-wizard process the moment they- // land. Cheap; the file is tiny.- cfg, _ := config.Load("")- configured := cfg != nil && cfg.Agent.ID != ""-- if a.menuSetup != nil {- if configured {- a.menuSetup.SetTitle("Re-pair this server…")- a.menuSetup.SetTooltip("Replace the current pairing with a fresh one")- } else {- a.menuSetup.SetTitle("Open setup wizard…")- a.menuSetup.SetTooltip("Pair this server with a ServerKit panel")- }- }-- if !configured {- a.mu.Lock()- defer a.mu.Unlock()- a.agentRunning = false- a.connected = false- a.lastStatus = "Not configured"- systray.SetIcon(GetIcon(IconStateStopped))- systray.SetTooltip("ServerKit Agent - Setup required")- a.menuStatus.SetTitle("Status: Not configured")- a.menuCPU.SetTitle("CPU: --")- a.menuMem.SetTitle("Memory: --")- a.menuStartAgent.Disable()- a.menuStopAgent.Disable()- a.menuRestartAgent.Disable()- return- }-- status, err := a.client.GetStatus()-- a.mu.Lock()- defer a.mu.Unlock()-- if err != nil {- // Agent not reachable- a.agentRunning = false- a.connected = false- a.lastStatus = "Agent Not Running"- systray.SetIcon(GetIcon(IconStateStopped))- systray.SetTooltip("ServerKit Agent - Not Running")- a.menuStatus.SetTitle("Status: Agent Not Running")- a.menuCPU.SetTitle("CPU: --")- a.menuMem.SetTitle("Memory: --")- a.menuStartAgent.Enable()- a.menuStopAgent.Disable()- a.menuRestartAgent.Disable()- return- }-- a.agentRunning = status.Running- a.connected = status.Connected- a.cpuPercent = status.CPUPercent- a.memPercent = status.MemPercent-- // Update icon based on connection state- if status.Connected {- a.lastStatus = "Connected"- systray.SetIcon(GetIcon(IconStateConnected))- systray.SetTooltip(fmt.Sprintf("ServerKit Agent - Connected | CPU: %.1f%% | Mem: %.1f%%",- status.CPUPercent, status.MemPercent))- } else if status.Running {- a.lastStatus = "Disconnected"- systray.SetIcon(GetIcon(IconStateDisconnected))- systray.SetTooltip("ServerKit Agent - Disconnected from server")- } else {- a.lastStatus = "Stopped"- systray.SetIcon(GetIcon(IconStateStopped))- systray.SetTooltip("ServerKit Agent - Stopped")- }-- // Update menu items- a.menuStatus.SetTitle(fmt.Sprintf("Status: %s", a.lastStatus))- a.menuCPU.SetTitle(fmt.Sprintf("CPU: %.1f%%", status.CPUPercent))- a.menuMem.SetTitle(fmt.Sprintf("Memory: %.1f%%", status.MemPercent))-- // Enable/disable service controls- if status.Running {- a.menuStartAgent.Disable()- a.menuStopAgent.Enable()- a.menuRestartAgent.Enable()- } else {- a.menuStartAgent.Enable()- a.menuStopAgent.Disable()- a.menuRestartAgent.Disable()- }-}--func (a *App) handleMenuClicks() {- for {- select {- case <-a.quitCh:- return- case <-a.menuSetup.ClickedCh:- if a.config.OnOpenSetup != nil {- a.config.OnOpenSetup()- }- case <-a.menuStartAgent.ClickedCh:- a.startAgent()- case <-a.menuStopAgent.ClickedCh:- a.stopAgent()- case <-a.menuRestartAgent.ClickedCh:- a.restartAgent()- case <-a.menuViewLogs.ClickedCh:- a.viewLogs()- case <-a.menuDashboard.ClickedCh:- a.openDashboard()- case <-a.menuQuit.ClickedCh:- systray.Quit()- return- }- }-}--func (a *App) startAgent() {- if err := startService(); err != nil {- a.showNotification("Failed to Start", err.Error())- return- }- a.showNotification("Agent Started", "ServerKit agent service started")- // Refresh immediately- time.Sleep(1 * time.Second)- a.refresh()-}--func (a *App) stopAgent() {- if err := stopService(); err != nil {- a.showNotification("Failed to Stop", err.Error())- return- }- a.showNotification("Agent Stopped", "ServerKit agent service stopped")- a.refresh()-}--func (a *App) restartAgent() {- // IPC "restart" is actually just a graceful stop — SCM doesn't- // auto-relaunch a service that exits cleanly, so the previous- // IPC-first path silently left the user with a stopped agent and- // required a second click. Always do sc stop + sc start instead.- if err := restartService(); err != nil {- a.showNotification("Failed to Restart", err.Error())- return- }- a.showNotification("Agent Restarted", "ServerKit agent service restarted")- time.Sleep(2 * time.Second)- a.refresh()-}--func (a *App) viewLogs() {- if a.config.LogFile == "" {- return- }- openFile(a.config.LogFile)-}--func (a *App) openDashboard() {- if a.config.DashboardURL == "" {- return- }- openURL(a.config.DashboardURL)-}--func (a *App) showNotification(title, message string) {- // Note: systray doesn't have built-in notification support- // For now, this is a placeholder - could use beeep or toast libraries- fmt.Printf("Notification: %s - %s\n", title, message)-}--// Platform-specific helpers--func startService() error {- if runtime.GOOS == "windows" {- return exec.Command("sc", "start", "ServerKitAgent").Run()- }- return exec.Command("systemctl", "start", "serverkit-agent").Run()-}--func stopService() error {- if runtime.GOOS == "windows" {- return exec.Command("sc", "stop", "ServerKitAgent").Run()- }- return exec.Command("systemctl", "stop", "serverkit-agent").Run()-}--func restartService() error {- if runtime.GOOS == "windows" {- // Windows doesn't have restart, so stop then start- stopService()- time.Sleep(1 * time.Second)- return startService()- }- return exec.Command("systemctl", "restart", "serverkit-agent").Run()-}--func openURL(url string) error {- var cmd *exec.Cmd- switch runtime.GOOS {- case "windows":- cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)- case "darwin":- cmd = exec.Command("open", url)- default:- cmd = exec.Command("xdg-open", url)- }- return cmd.Start()-}--func openFile(path string) error {- var cmd *exec.Cmd- switch runtime.GOOS {- case "windows":- cmd = exec.Command("notepad", path)- case "darwin":- cmd = exec.Command("open", "-t", path)- default:- cmd = exec.Command("xdg-open", path)- }- return cmd.Start()-}diff --git a/agent/internal/updater/checker.go b/agent/internal/updater/checker.godeleted file mode 100644index f16dd985..00000000--- a/agent/internal/updater/checker.go+++ /dev/null@@ -1,152 +0,0 @@-package updater--import (- "context"- "sync"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"-)--// UpdateChecker runs periodic update checks-type UpdateChecker struct {- updater *Updater- cfg *config.Config- log *logger.Logger-- mu sync.Mutex- lastCheck time.Time- latestVersion string- updatePending bool-}--// NewChecker creates a new update checker-func NewChecker(cfg *config.Config, log *logger.Logger, currentVersion string) *UpdateChecker {- return &UpdateChecker{- updater: New(cfg, log, currentVersion),- cfg: cfg,- log: log,- }-}--// Start begins the periodic update check routine-func (c *UpdateChecker) Start(ctx context.Context) {- if !c.cfg.Update.Enabled {- c.log.Info("Auto-update checks disabled")- return- }-- c.log.Info("Starting update checker",- "interval", c.cfg.Update.CheckInterval,- "auto_install", c.cfg.Update.AutoInstall,- )-- // Do initial check after a short delay- go func() {- select {- case <-ctx.Done():- return- case <-time.After(1 * time.Minute):- c.checkAndNotify(ctx)- }- }()-- // Start periodic checks- ticker := time.NewTicker(c.cfg.Update.CheckInterval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- c.log.Debug("Update checker stopped")- return- case <-ticker.C:- c.checkAndNotify(ctx)- }- }-}--func (c *UpdateChecker) checkAndNotify(ctx context.Context) {- c.mu.Lock()- defer c.mu.Unlock()-- c.lastCheck = time.Now()-- info, err := c.updater.CheckForUpdate(ctx)- if err != nil {- c.log.Warn("Update check failed", "error", err)- return- }-- if !info.UpdateAvailable {- c.log.Debug("No update available")- c.updatePending = false- return- }-- c.latestVersion = info.LatestVersion- c.updatePending = true-- c.log.Info("Update available",- "current", info.CurrentVersion,- "latest", info.LatestVersion,- )-- // Auto-install if enabled- if c.cfg.Update.AutoInstall {- c.log.Info("Auto-install enabled, downloading update...")- if err := c.installUpdate(ctx, info); err != nil {- c.log.Error("Auto-update failed", "error", err)- }- }-}--func (c *UpdateChecker) installUpdate(ctx context.Context, info *VersionInfo) error {- binaryPath, err := c.updater.DownloadUpdate(ctx, info)- if err != nil {- return err- }-- if err := c.updater.InstallUpdate(binaryPath); err != nil {- c.updater.Cleanup(binaryPath)- return err- }-- return nil-}--// CheckNow performs an immediate update check-func (c *UpdateChecker) CheckNow(ctx context.Context) (*VersionInfo, error) {- c.mu.Lock()- defer c.mu.Unlock()-- c.lastCheck = time.Now()- return c.updater.CheckForUpdate(ctx)-}--// GetUpdater returns the underlying updater for manual operations-func (c *UpdateChecker) GetUpdater() *Updater {- return c.updater-}--// HasPendingUpdate returns true if an update is available-func (c *UpdateChecker) HasPendingUpdate() bool {- c.mu.Lock()- defer c.mu.Unlock()- return c.updatePending-}--// GetLatestVersion returns the latest available version-func (c *UpdateChecker) GetLatestVersion() string {- c.mu.Lock()- defer c.mu.Unlock()- return c.latestVersion-}--// GetLastCheck returns when the last check was performed-func (c *UpdateChecker) GetLastCheck() time.Time {- c.mu.Lock()- defer c.mu.Unlock()- return c.lastCheck-}diff --git a/agent/internal/updater/updater.go b/agent/internal/updater/updater.godeleted file mode 100644index 21cc3c1d..00000000--- a/agent/internal/updater/updater.go+++ /dev/null@@ -1,550 +0,0 @@-package updater--import (- "archive/tar"- "archive/zip"- "compress/gzip"- "context"- "crypto/sha256"- "encoding/hex"- "encoding/json"- "fmt"- "io"- "net/http"- "os"- "os/exec"- "path/filepath"- "runtime"- "strings"- "time"-- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"-)--// VersionInfo holds version check response-type VersionInfo struct {- UpdateAvailable bool `json:"update_available"`- CurrentVersion string `json:"current_version"`- LatestVersion string `json:"latest_version"`- DownloadURL string `json:"download_url"`- ChecksumsURL string `json:"checksums_url"`- ReleaseNotesURL string `json:"release_notes_url"`- PublishedAt string `json:"published_at"`-}--// Updater handles agent self-updates-type Updater struct {- cfg *config.Config- log *logger.Logger- currentVersion string- serverURL string- httpClient *http.Client-}--// New creates a new Updater instance-func New(cfg *config.Config, log *logger.Logger, currentVersion string) *Updater {- // Derive HTTP URL from WebSocket URL- serverURL := cfg.Server.URL- serverURL = strings.Replace(serverURL, "wss://", "https://", 1)- serverURL = strings.Replace(serverURL, "ws://", "http://", 1)- // Remove /agent/ws path if present- serverURL = strings.TrimSuffix(serverURL, "/agent/ws")- serverURL = strings.TrimSuffix(serverURL, "/agent")-- return &Updater{- cfg: cfg,- log: log,- currentVersion: currentVersion,- serverURL: serverURL,- httpClient: &http.Client{- Timeout: 30 * time.Second,- },- }-}--// UpdateTo performs an update to a specific version using provided URLs-func (u *Updater) UpdateTo(ctx context.Context, version, downloadURL, checksumsURL string) error {- u.log.Info("Updating to specific version", "version", version)-- info := &VersionInfo{- LatestVersion: version,- DownloadURL: downloadURL,- ChecksumsURL: checksumsURL,- }-- // Download update- newBinaryPath, err := u.DownloadUpdate(ctx, info)- if err != nil {- return fmt.Errorf("failed to download update: %w", err)- }-- // Install update- if err := u.InstallUpdate(newBinaryPath); err != nil {- return fmt.Errorf("failed to install update: %w", err)- }-- return nil-}--// CheckForUpdate checks if a new version is available-func (u *Updater) CheckForUpdate(ctx context.Context) (*VersionInfo, error) {- u.log.Debug("Checking for updates", "current_version", u.currentVersion)-- url := fmt.Sprintf("%s/api/servers/agent/version/check", u.serverURL)-- payload := map[string]string{- "current_version": u.currentVersion,- "os": runtime.GOOS,- "arch": runtime.GOARCH,- }-- body, err := json.Marshal(payload)- if err != nil {- return nil, fmt.Errorf("failed to marshal request: %w", err)- }-- req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(string(body)))- if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", u.currentVersion))-- resp, err := u.httpClient.Do(req)- if err != nil {- return nil, fmt.Errorf("failed to check for updates: %w", err)- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("update check failed with status: %d", resp.StatusCode)- }-- var info VersionInfo- if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {- return nil, fmt.Errorf("failed to decode response: %w", err)- }-- u.log.Debug("Update check complete",- "update_available", info.UpdateAvailable,- "latest_version", info.LatestVersion,- )-- return &info, nil-}--// DownloadUpdate downloads the new version-func (u *Updater) DownloadUpdate(ctx context.Context, info *VersionInfo) (string, error) {- if info.DownloadURL == "" {- return "", fmt.Errorf("no download URL available")- }- if err := requireSecureURL(info.DownloadURL); err != nil {- return "", err- }-- u.log.Info("Downloading update", "version", info.LatestVersion, "url", info.DownloadURL)-- // Create temp directory- tmpDir, err := os.MkdirTemp("", "serverkit-update-*")- if err != nil {- return "", fmt.Errorf("failed to create temp directory: %w", err)- }-- // Determine archive type- var archivePath string- if runtime.GOOS == "windows" {- archivePath = filepath.Join(tmpDir, "agent.zip")- } else {- archivePath = filepath.Join(tmpDir, "agent.tar.gz")- }-- // Download archive- if err := u.downloadFile(ctx, info.DownloadURL, archivePath); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to download update: %w", err)- }-- // Verify checksum — MANDATORY and fail-closed. Refuse to install an update- // that arrives without a checksums URL, or whose checksum we can't match,- // rather than running an unverified binary as the agent (often root).- // Cryptographic signing of releases is the recommended next layer; until- // then this at least prevents silent integrity bypass.- if info.ChecksumsURL == "" {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("refusing to install update: no checksums URL provided")- }- if err := u.verifyChecksum(ctx, archivePath, info.ChecksumsURL); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("checksum verification failed: %w", err)- }- u.log.Info("Checksum verified successfully")-- // Extract binary- binaryPath, err := u.extractBinary(archivePath, tmpDir)- if err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to extract update: %w", err)- }-- u.log.Info("Update downloaded and verified", "path", binaryPath)- return binaryPath, nil-}--// InstallUpdate installs the new binary and restarts the agent-func (u *Updater) InstallUpdate(newBinaryPath string) error {- u.log.Info("Installing update", "new_binary", newBinaryPath)-- // Get current binary path- currentBinary, err := os.Executable()- if err != nil {- return fmt.Errorf("failed to get current executable: %w", err)- }- currentBinary, err = filepath.EvalSymlinks(currentBinary)- if err != nil {- return fmt.Errorf("failed to resolve symlinks: %w", err)- }-- // Create backup path- backupPath := currentBinary + ".backup"-- // On Windows, we need to rename the current binary first- if runtime.GOOS == "windows" {- return u.installWindows(currentBinary, newBinaryPath, backupPath)- }-- return u.installUnix(currentBinary, newBinaryPath, backupPath)-}--func (u *Updater) installUnix(currentBinary, newBinaryPath, backupPath string) error {- // Remove old backup if exists- os.Remove(backupPath)-- // Backup current binary- if err := os.Rename(currentBinary, backupPath); err != nil {- return fmt.Errorf("failed to backup current binary: %w", err)- }-- // Copy new binary to target location- if err := copyFile(newBinaryPath, currentBinary); err != nil {- // Restore backup on failure- os.Rename(backupPath, currentBinary)- return fmt.Errorf("failed to copy new binary: %w", err)- }-- // Make executable- if err := os.Chmod(currentBinary, 0755); err != nil {- os.Rename(backupPath, currentBinary)- return fmt.Errorf("failed to set permissions: %w", err)- }-- u.log.Info("Update installed successfully, restarting agent...")-- // Restart via systemd if available- if u.isSystemd() {- cmd := exec.Command("systemctl", "restart", "serverkit-agent")- if err := cmd.Start(); err != nil {- u.log.Warn("Failed to restart via systemd", "error", err)- }- return nil- }-- // Self-restart- return u.selfRestart(currentBinary)-}--func (u *Updater) installWindows(currentBinary, newBinaryPath, backupPath string) error {- // On Windows, create a batch script to:- // 1. Wait for current process to exit- // 2. Replace the binary- // 3. Start the new binary/service-- batchScript := fmt.Sprintf(`@echo off-timeout /t 2 /nobreak > nul-del "%s.backup" 2>nul-move "%s" "%s.backup"-copy "%s" "%s"-net start ServerKitAgent-del "%%~f0"-`, currentBinary, currentBinary, currentBinary, newBinaryPath, currentBinary)-- scriptPath := filepath.Join(os.TempDir(), "serverkit-update.bat")- if err := os.WriteFile(scriptPath, []byte(batchScript), 0755); err != nil {- return fmt.Errorf("failed to create update script: %w", err)- }-- // Stop the service- exec.Command("net", "stop", "ServerKitAgent").Run()-- // Run the batch script detached- cmd := exec.Command("cmd", "/c", "start", "/b", scriptPath)- if err := cmd.Start(); err != nil {- return fmt.Errorf("failed to start update script: %w", err)- }-- u.log.Info("Update scheduled, agent will restart shortly")- return nil-}--func (u *Updater) downloadFile(ctx context.Context, url, destPath string) error {- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)- if err != nil {- return err- }-- req.Header.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", u.currentVersion))-- resp, err := u.httpClient.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("download failed with status: %d", resp.StatusCode)- }-- out, err := os.Create(destPath)- if err != nil {- return err- }- defer out.Close()-- _, err = io.Copy(out, resp.Body)- return err-}--func (u *Updater) verifyChecksum(ctx context.Context, filePath, checksumsURL string) error {- if err := requireSecureURL(checksumsURL); err != nil {- return err- }-- // Download checksums file- req, err := http.NewRequestWithContext(ctx, "GET", checksumsURL, nil)- if err != nil {- return err- }-- resp, err := u.httpClient.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()-- // A non-200 (e.g. a 404 HTML page) must not be treated as "no checksum- // available" — that previously degraded into skipping verification.- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("failed to fetch checksums: status %d", resp.StatusCode)- }-- checksumsData, err := io.ReadAll(resp.Body)- if err != nil {- return err- }-- // Stream the archive through SHA-256 so we don't buffer the whole file.- f, err := os.Open(filePath)- if err != nil {- return err- }- defer f.Close()-- hasher := sha256.New()- if _, err := io.Copy(hasher, f); err != nil {- return err- }- actualHash := hex.EncodeToString(hasher.Sum(nil))-- return matchChecksum(actualHash, string(checksumsData))-}--// matchChecksum verifies actualHash against the entry for this platform in a-// checksums.txt body. It FAILS CLOSED: an empty/unparseable body, no entry-// matching this GOOS/GOARCH, or a hash mismatch all return an error. The old-// implementation returned nil ("skip verification") when no entry matched,-// which let a crafted or truncated checksums file disable integrity entirely.-func matchChecksum(actualHash, checksumsBody string) error {- checksums := make(map[string]string)- for _, line := range strings.Split(checksumsBody, "\n") {- parts := strings.Fields(line)- if len(parts) >= 2 {- checksums[parts[1]] = parts[0]- }- }- if len(checksums) == 0 {- return fmt.Errorf("checksums file contained no usable entries")- }-- expected := ""- for name, hash := range checksums {- if strings.Contains(name, runtime.GOOS) && strings.Contains(name, runtime.GOARCH) {- expected = hash- break- }- }- if expected == "" {- return fmt.Errorf("no checksum entry for %s/%s in checksums file", runtime.GOOS, runtime.GOARCH)- }-- if !strings.EqualFold(actualHash, expected) {- return fmt.Errorf("checksum mismatch: expected %s, got %s", expected, actualHash)- }- return nil-}--// requireSecureURL rejects non-HTTPS update/checksum URLs so an on-path-// attacker can't serve a downgraded plaintext binary. The same-// SERVERKIT_INSECURE_TLS escape hatch the rest of the agent honours allows-// http:// for local development.-func requireSecureURL(raw string) error {- if strings.HasPrefix(strings.ToLower(raw), "https://") {- return nil- }- if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {- return nil- }- return fmt.Errorf("refusing non-HTTPS update URL: %s", raw)-}--func (u *Updater) extractBinary(archivePath, destDir string) (string, error) {- if runtime.GOOS == "windows" {- return u.extractZip(archivePath, destDir)- }- return u.extractTarGz(archivePath, destDir)-}--func (u *Updater) extractTarGz(archivePath, destDir string) (string, error) {- f, err := os.Open(archivePath)- if err != nil {- return "", err- }- defer f.Close()-- gzr, err := gzip.NewReader(f)- if err != nil {- return "", err- }- defer gzr.Close()-- tr := tar.NewReader(gzr)-- var binaryPath string- for {- header, err := tr.Next()- if err == io.EOF {- break- }- if err != nil {- return "", err- }-- // Look for the agent binary- if header.Typeflag == tar.TypeReg && strings.Contains(header.Name, "serverkit-agent") {- binaryPath = filepath.Join(destDir, "serverkit-agent")- outFile, err := os.Create(binaryPath)- if err != nil {- return "", err- }- if _, err := io.Copy(outFile, tr); err != nil {- outFile.Close()- return "", err- }- outFile.Close()- os.Chmod(binaryPath, 0755)- }- }-- if binaryPath == "" {- return "", fmt.Errorf("agent binary not found in archive")- }-- return binaryPath, nil-}--func (u *Updater) extractZip(archivePath, destDir string) (string, error) {- r, err := zip.OpenReader(archivePath)- if err != nil {- return "", err- }- defer r.Close()-- var binaryPath string- for _, f := range r.File {- if strings.Contains(f.Name, "serverkit-agent") && strings.HasSuffix(f.Name, ".exe") {- binaryPath = filepath.Join(destDir, "serverkit-agent.exe")-- rc, err := f.Open()- if err != nil {- return "", err- }-- outFile, err := os.Create(binaryPath)- if err != nil {- rc.Close()- return "", err- }-- _, err = io.Copy(outFile, rc)- outFile.Close()- rc.Close()-- if err != nil {- return "", err- }- }- }-- if binaryPath == "" {- return "", fmt.Errorf("agent binary not found in archive")- }-- return binaryPath, nil-}--func (u *Updater) isSystemd() bool {- if runtime.GOOS != "linux" {- return false- }- _, err := os.Stat("/run/systemd/system")- return err == nil-}--func (u *Updater) selfRestart(binaryPath string) error {- // Fork a new process and exit current one- cmd := exec.Command(binaryPath, "start")- cmd.Stdout = os.Stdout- cmd.Stderr = os.Stderr-- if err := cmd.Start(); err != nil {- return fmt.Errorf("failed to start new process: %w", err)- }-- u.log.Info("Restarting with new version...")- os.Exit(0)- return nil-}--func copyFile(src, dst string) error {- sourceFile, err := os.Open(src)- if err != nil {- return err- }- defer sourceFile.Close()-- destFile, err := os.Create(dst)- if err != nil {- return err- }- defer destFile.Close()-- _, err = io.Copy(destFile, sourceFile)- return err-}--// Cleanup removes temporary update files-func (u *Updater) Cleanup(tmpDir string) {- if tmpDir != "" {- os.RemoveAll(tmpDir)- }-}diff --git a/agent/internal/updater/updater_test.go b/agent/internal/updater/updater_test.godeleted file mode 100644index 181ee8eb..00000000--- a/agent/internal/updater/updater_test.go+++ /dev/null@@ -1,88 +0,0 @@-package updater--import (- "crypto/sha256"- "encoding/hex"- "fmt"- "os"- "runtime"- "strings"- "testing"-)--func hashOf(b []byte) string {- s := sha256.Sum256(b)- return hex.EncodeToString(s[:])-}--// platformName is a checksums.txt filename that matches the host this test-// runs on, so matchChecksum's GOOS/GOARCH substring match finds it.-func platformName() string {- return fmt.Sprintf("serverkit-agent-%s-%s.tar.gz", runtime.GOOS, runtime.GOARCH)-}--func TestMatchChecksum_ValidPasses(t *testing.T) {- data := []byte("pretend archive contents")- good := hashOf(data)- body := good + " " + platformName() + "\n"- if err := matchChecksum(good, body); err != nil {- t.Fatalf("expected verification to pass, got: %v", err)- }-}--func TestMatchChecksum_MismatchFails(t *testing.T) {- good := hashOf([]byte("the real archive"))- wrong := hashOf([]byte("a tampered archive"))- body := wrong + " " + platformName() + "\n"- if err := matchChecksum(good, body); err == nil {- t.Fatal("expected a mismatch error, got nil")- }-}--func TestMatchChecksum_NoMatchingEntryFailsClosed(t *testing.T) {- good := hashOf([]byte("archive"))- // An entry that cannot match this host's GOOS/GOARCH. The old code returned- // nil here ("skip verification") — the bug this guards against.- body := good + " serverkit-agent-xxos-yyarch.tar.gz\n"- if err := matchChecksum(good, body); err == nil {- t.Fatal("expected fail-closed when no entry matches the platform, got nil")- }-}--func TestMatchChecksum_EmptyBodyFails(t *testing.T) {- good := hashOf([]byte("archive"))- if err := matchChecksum(good, ""); err == nil {- t.Fatal("expected error on empty checksums body, got nil")- }- if err := matchChecksum(good, "not a valid checksums line\n"); err == nil {- t.Fatal("expected error on a body with no usable entries, got nil")- }-}--func TestMatchChecksum_CaseInsensitiveHash(t *testing.T) {- data := []byte("archive")- good := hashOf(data)- body := strings.ToUpper(good) + " " + platformName() + "\n"- if err := matchChecksum(good, body); err != nil {- t.Fatalf("expected case-insensitive hash comparison to pass, got: %v", err)- }-}--func TestRequireSecureURL(t *testing.T) {- if err := requireSecureURL("https://example.com/agent.tar.gz"); err != nil {- t.Fatalf("https URL should be accepted, got: %v", err)- }- if err := requireSecureURL("HTTPS://Example.com/x"); err != nil {- t.Fatalf("https scheme check should be case-insensitive, got: %v", err)- }-- // http must be rejected unless the insecure dev flag is set.- os.Unsetenv("SERVERKIT_INSECURE_TLS")- if err := requireSecureURL("http://example.com/agent.tar.gz"); err == nil {- t.Fatal("http URL should be rejected without SERVERKIT_INSECURE_TLS")- }- t.Setenv("SERVERKIT_INSECURE_TLS", "true")- if err := requireSecureURL("http://localhost:5000/agent.tar.gz"); err != nil {- t.Fatalf("http should be allowed when SERVERKIT_INSECURE_TLS=true, got: %v", err)- }-}diff --git a/agent/internal/wireguard/wireguard.go b/agent/internal/wireguard/wireguard.godeleted file mode 100644index 78a3d992..00000000--- a/agent/internal/wireguard/wireguard.go+++ /dev/null@@ -1,326 +0,0 @@-// Package wireguard manages a WireGuard interface on the agent host so-// the panel can pair two agents into a NAT-traversing tunnel (the-// "edge" agent on a public IP + a "private" agent behind NAT). See-// docs/REMOTE_ACCESS_ROADMAP.md.-//-// Split mirrors the cloudflared package:-// - wireguard.go — the platform-agnostic Manager interface,-// shared request/result types, key generation-// and validation.-// - wireguard_linux.go — the real backend (kernel WireGuard via the-// `wg` + `ip` tools).-// - wireguard_other.go — a stub that reports "unsupported" until the-// userspace wireguard-go backend (roadmap #6)-// lands for Windows/macOS private peers.-//-// Security model (stated once):-//-// Private keys NEVER leave the host. Keygen generates the keypair-// locally, persists the private key in a root-only file under the-// agent's key directory, and returns ONLY the public key in the-// command result. The panel brokers public keys + endpoints +-// allowed-IPs; it never sees, transmits or stores a private key.-package wireguard--import (- "crypto/ecdh"- "crypto/rand"- "encoding/base64"- "fmt"- "io"- "net"- "regexp"- "strconv"- "strings"-)--// Keypair is a WireGuard (Curve25519 / X25519) keypair, base64-encoded-// in the canonical `wg` format. PrivateKey is host-only and must never-// be serialized to the panel — it carries `json:"-"` for that reason.-type Keypair struct {- PrivateKey string `json:"-"`- PublicKey string `json:"public_key"`-}--// KeygenResult is what the wireguard:keygen command returns to the-// panel: the public key only.-type KeygenResult struct {- PublicKey string `json:"public_key"`-}--// InterfaceUpRequest brings up (or reconciles) a WireGuard interface.-// ListenPort is set only on the edge agent; the private agent dials-// out and lets the kernel pick an ephemeral source port.-type InterfaceUpRequest struct {- Name string `json:"name"` // e.g. "skwg0"- Address string `json:"address"` // CIDR, e.g. "10.88.0.2/24"- ListenPort int `json:"listen_port"` // 0 = unset (private side)-}--// PeerSetRequest adds or updates a single peer on an interface. On the-// private side, Endpoint points at the edge (`ip:port`) and-// PersistentKeepalive is set (typically 25s) to punch and hold the NAT-// mapping. On the edge side, Endpoint is empty (learned on handshake).-type PeerSetRequest struct {- Interface string `json:"interface"`- PublicKey string `json:"public_key"`- AllowedIPs []string `json:"allowed_ips"`- Endpoint string `json:"endpoint,omitempty"`- PersistentKeepalive int `json:"persistent_keepalive,omitempty"`-}--// PeerRemoveRequest removes a peer from an interface.-type PeerRemoveRequest struct {- Interface string `json:"interface"`- PublicKey string `json:"public_key"`-}--// PeerStatus mirrors one peer row from `wg show <iface> dump`.-type PeerStatus struct {- PublicKey string `json:"public_key"`- Endpoint string `json:"endpoint,omitempty"`- AllowedIPs []string `json:"allowed_ips,omitempty"`- LatestHandshake int64 `json:"latest_handshake"` // unix seconds; 0 = never- TransferRx int64 `json:"transfer_rx"` // bytes- TransferTx int64 `json:"transfer_tx"` // bytes- PersistentKeepalive int `json:"persistent_keepalive,omitempty"`-}--// InterfaceStatus is the wireguard:status result for one interface.-// Up=false (with a nil/empty Peers) means the interface doesn't exist-// yet — the panel polls this on a not-yet-built tunnel without it being-// an error.-type InterfaceStatus struct {- Name string `json:"name"`- PublicKey string `json:"public_key,omitempty"`- ListenPort int `json:"listen_port,omitempty"`- Up bool `json:"up"`- Peers []PeerStatus `json:"peers"`-}--// Manager is the platform-agnostic surface the agent's handlers call.-// The Linux build wires it to kernel WireGuard; non-Linux builds return-// "unsupported" until roadmap #6.-type Manager interface {- // Available reports whether this host can manage WireGuard (kernel- // tools present on Linux; userspace backend on others once #6 lands).- Available() bool- // Keygen generates a keypair for iface, persists the private key- // locally (root-only), and returns the public key.- Keygen(iface string) (*KeygenResult, error)- // InterfaceUp creates/reconciles the interface using the persisted- // private key. Idempotent.- InterfaceUp(req InterfaceUpRequest) error- // InterfaceDown tears the interface down. Idempotent (a missing- // interface is a no-op success).- InterfaceDown(iface string) error- // SetPeer adds or updates a peer. Idempotent.- SetPeer(req PeerSetRequest) error- // RemovePeer removes a peer. Idempotent.- RemovePeer(req PeerRemoveRequest) error- // Status returns the live interface + peer state.- Status(iface string) (*InterfaceStatus, error)- // Forward starts a TCP forwarder: it accepts connections arriving over- // the tunnel at ListenIP:ListenPort and proxies each to- // TargetHost:TargetPort on the host. This is how a service behind a- // userspace (netstack) peer is reached — and is uniform for the kernel- // backend. Idempotent per (interface, ListenPort): re-Forward replaces.- Forward(req ForwardRequest) error- // Unforward stops the forwarder for ListenPort on iface (idempotent).- Unforward(iface string, listenPort int) error-}--// ForwardRequest configures a tunnel→host TCP forwarder (roadmap #13).-// On the private peer, ListenIP is the peer's own WireGuard IP, and the-// service (e.g. Jellyfin) listens on TargetHost:TargetPort on the host.-type ForwardRequest struct {- Interface string `json:"interface"`- ListenIP string `json:"listen_ip"` // the WG IP to listen on, e.g. 10.88.3.2- ListenPort int `json:"listen_port"` // WG-side port the edge proxies to- TargetHost string `json:"target_host"` // default 127.0.0.1- TargetPort int `json:"target_port"` // default = ListenPort-}--func (r ForwardRequest) normalized() ForwardRequest {- if r.TargetHost == "" {- r.TargetHost = "127.0.0.1"- }- if r.TargetPort == 0 {- r.TargetPort = r.ListenPort- }- return r-}--func validateForward(req ForwardRequest) error {- if err := validIfaceName(req.Interface); err != nil {- return err- }- if net.ParseIP(req.ListenIP) == nil {- return fmt.Errorf("invalid listen_ip %q", req.ListenIP)- }- if req.ListenPort < 1 || req.ListenPort > 65535 {- return fmt.Errorf("invalid listen_port %d", req.ListenPort)- }- if req.TargetPort < 0 || req.TargetPort > 65535 {- return fmt.Errorf("invalid target_port %d", req.TargetPort)- }- return nil-}--// forwardKey identifies a forwarder by interface + listen port.-func forwardKey(iface string, port int) string {- return iface + ":" + strconv.Itoa(port)-}--// serveForward accepts on l and proxies each connection to-// targetHost:targetPort until l is closed. Backends create the listener-// (kernel: net.Listen on the real WG iface; userspace: tnet.ListenTCP)-// then hand it here.-func serveForward(l net.Listener, targetHost string, targetPort int) {- target := net.JoinHostPort(targetHost, strconv.Itoa(targetPort))- for {- conn, err := l.Accept()- if err != nil {- return // listener closed- }- go proxyConn(conn, target)- }-}--func proxyConn(client net.Conn, target string) {- defer client.Close()- server, err := net.Dial("tcp", target)- if err != nil {- return- }- defer server.Close()- done := make(chan struct{}, 2)- cp := func(dst, src net.Conn) { _, _ = io.Copy(dst, src); done <- struct{}{} }- go cp(server, client)- go cp(client, server)- <-done // first side to close ends the pair (defers close both)-}--// GenerateKeypair produces a fresh WireGuard keypair. X25519 via-// crypto/ecdh, which clamps the scalar exactly as WireGuard expects;-// the byte layout and base64 encoding match `wg genkey | wg pubkey`.-// Shared across all platforms — keygen is pure crypto and works even-// where interface management doesn't.-func GenerateKeypair() (*Keypair, error) {- priv, err := ecdh.X25519().GenerateKey(rand.Reader)- if err != nil {- return nil, fmt.Errorf("generate x25519 key: %w", err)- }- return &Keypair{- PrivateKey: base64.StdEncoding.EncodeToString(priv.Bytes()),- PublicKey: base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()),- }, nil-}--// PublicKeyFromPrivate derives the base64 WireGuard public key from a-// base64 private key (X25519 scalar-mult with the base point, matching-// `wg pubkey`). The userspace backend uses this for Status, where it-// only has the private key on hand.-func PublicKeyFromPrivate(privB64 string) (string, error) {- raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(privB64))- if err != nil || len(raw) != 32 {- return "", fmt.Errorf("invalid private key")- }- priv, err := ecdh.X25519().NewPrivateKey(raw)- if err != nil {- return "", err- }- return base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()), nil-}--// --- validation helpers (shared, so both backends and tests reuse) -----// ifaceNameRegex constrains interface names to what the Linux kernel-// accepts (IFNAMSIZ is 16 including the NUL, so 15 usable chars) and-// what won't trip shell/`ip` parsing.-var ifaceNameRegex = regexp.MustCompile(`^[A-Za-z0-9_-]{1,15}$`)--func validIfaceName(name string) error {- if !ifaceNameRegex.MatchString(name) {- return fmt.Errorf("invalid interface name %q (alphanumeric, -, _, max 15 chars)", name)- }- return nil-}--// validPublicKey checks a base64 WireGuard key decodes to 32 bytes.-func validPublicKey(key string) error {- raw, err := base64.StdEncoding.DecodeString(key)- if err != nil {- return fmt.Errorf("public key is not valid base64")- }- if len(raw) != 32 {- return fmt.Errorf("public key must be 32 bytes, got %d", len(raw))- }- return nil-}--// validCIDR checks a "addr/prefix" string parses.-func validCIDR(cidr string) error {- if _, _, err := net.ParseCIDR(cidr); err != nil {- return fmt.Errorf("invalid CIDR %q: %w", cidr, err)- }- return nil-}--// validEndpoint checks a "host:port" with a numeric, in-range port.-func validEndpoint(ep string) error {- host, port, err := net.SplitHostPort(ep)- if err != nil {- return fmt.Errorf("invalid endpoint %q (want host:port): %w", ep, err)- }- if host == "" {- return fmt.Errorf("invalid endpoint %q: empty host", ep)- }- p := 0- if _, err := fmt.Sscanf(port, "%d", &p); err != nil || p < 1 || p > 65535 {- return fmt.Errorf("invalid endpoint port %q", port)- }- return nil-}--// validateInterfaceUp validates an InterfaceUpRequest. Shared so the-// stub can reject bad input identically to the real backend.-func validateInterfaceUp(req InterfaceUpRequest) error {- if err := validIfaceName(req.Name); err != nil {- return err- }- if err := validCIDR(req.Address); err != nil {- return err- }- if req.ListenPort < 0 || req.ListenPort > 65535 {- return fmt.Errorf("invalid listen_port %d", req.ListenPort)- }- return nil-}--// validatePeerSet validates a PeerSetRequest.-func validatePeerSet(req PeerSetRequest) error {- if err := validIfaceName(req.Interface); err != nil {- return err- }- if err := validPublicKey(req.PublicKey); err != nil {- return err- }- if len(req.AllowedIPs) == 0 {- return fmt.Errorf("allowed_ips is required")- }- for _, ip := range req.AllowedIPs {- if err := validCIDR(strings.TrimSpace(ip)); err != nil {- return err- }- }- if req.Endpoint != "" {- if err := validEndpoint(req.Endpoint); err != nil {- return err- }- }- if req.PersistentKeepalive < 0 || req.PersistentKeepalive > 65535 {- return fmt.Errorf("invalid persistent_keepalive %d", req.PersistentKeepalive)- }- return nil-}diff --git a/agent/internal/wireguard/wireguard_dump_linux_test.go b/agent/internal/wireguard/wireguard_dump_linux_test.godeleted file mode 100644index 94586ecf..00000000--- a/agent/internal/wireguard/wireguard_dump_linux_test.go+++ /dev/null@@ -1,63 +0,0 @@-//go:build linux--package wireguard--import "testing"--// TestParseWgDump checks the `wg show <iface> dump` parser, and in-// particular guards the security-critical invariant: the interface-// line's field[0] is the PRIVATE key and must never surface — we read-// field[1] (public) for InterfaceStatus.PublicKey.-func TestParseWgDump(t *testing.T) {- dump := "PRIVATEKEYMUSTNOTLEAK=\tIFACEPUBKEY=\t51820\toff\n" +- "PEERPUBKEY=\t(none)\t203.0.113.5:51820\t10.88.0.2/32\t1700000000\t1024\t2048\t25\n" +- "PEER2PUBKEY=\t(none)\t(none)\t(none)\t0\t0\t0\toff\n"-- st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}- parseWgDump(dump, st)-- if st.PublicKey != "IFACEPUBKEY=" {- t.Errorf("interface PublicKey = %q, want field[1] IFACEPUBKEY=", st.PublicKey)- }- if st.PublicKey == "PRIVATEKEYMUSTNOTLEAK=" {- t.Fatal("LEAK: interface private key surfaced as PublicKey")- }- if st.ListenPort != 51820 {- t.Errorf("ListenPort = %d, want 51820", st.ListenPort)- }- if len(st.Peers) != 2 {- t.Fatalf("want 2 peers, got %d", len(st.Peers))- }-- p := st.Peers[0]- if p.PublicKey != "PEERPUBKEY=" {- t.Errorf("peer0 PublicKey = %q", p.PublicKey)- }- if p.Endpoint != "203.0.113.5:51820" {- t.Errorf("peer0 Endpoint = %q", p.Endpoint)- }- if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.2/32" {- t.Errorf("peer0 AllowedIPs = %v", p.AllowedIPs)- }- if p.LatestHandshake != 1700000000 {- t.Errorf("peer0 LatestHandshake = %d", p.LatestHandshake)- }- if p.TransferRx != 1024 || p.TransferTx != 2048 {- t.Errorf("peer0 transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)- }- if p.PersistentKeepalive != 25 {- t.Errorf("peer0 PersistentKeepalive = %d", p.PersistentKeepalive)- }-- // peer1: "(none)" endpoint → empty, "off" keepalive → 0- p2 := st.Peers[1]- if p2.Endpoint != "" {- t.Errorf("peer1 Endpoint = %q, want empty", p2.Endpoint)- }- if len(p2.AllowedIPs) != 0 {- t.Errorf("peer1 AllowedIPs = %v, want empty", p2.AllowedIPs)- }- if p2.PersistentKeepalive != 0 {- t.Errorf("peer1 PersistentKeepalive = %d, want 0", p2.PersistentKeepalive)- }-}diff --git a/agent/internal/wireguard/wireguard_linux.go b/agent/internal/wireguard/wireguard_linux.godeleted file mode 100644index 27aee77e..00000000--- a/agent/internal/wireguard/wireguard_linux.go+++ /dev/null@@ -1,291 +0,0 @@-//go:build linux--package wireguard--import (- "bytes"- "context"- "fmt"- "net"- "os"- "os/exec"- "path/filepath"- "strconv"- "strings"- "sync"- "time"-)--// defaultKeyDir is used when the agent didn't supply a data directory.-const defaultKeyDir = "/etc/serverkit-agent/wireguard"--// New returns a Linux Manager backed by kernel WireGuard (`wg` + `ip`).-// keyDir is where per-interface private keys are persisted (root-only);-// empty falls back to defaultKeyDir.-func New(keyDir string) Manager {- if keyDir == "" {- keyDir = defaultKeyDir- }- return &linuxManager{keyDir: keyDir, forwards: map[string]net.Listener{}}-}--type linuxManager struct {- keyDir string- mu sync.Mutex- forwards map[string]net.Listener-}--func (m *linuxManager) keyPath(iface string) string {- return filepath.Join(m.keyDir, iface+".key")-}--func (m *linuxManager) Available() bool {- return onPath("wg") && onPath("ip")-}--func onPath(bin string) bool {- _, err := exec.LookPath(bin)- return err == nil-}--// run executes a command with a short ceiling and returns stdout, with-// stderr folded into any error (the panel surfaces these directly).-func run(name string, args ...string) (string, error) {- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()- cmd := exec.CommandContext(ctx, name, args...)- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr- if err := cmd.Run(); err != nil {- return "", fmt.Errorf("%s %s: %w (%s)",- name, strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))- }- return stdout.String(), nil-}--func (m *linuxManager) Keygen(iface string) (*KeygenResult, error) {- if err := validIfaceName(iface); err != nil {- return nil, err- }- kp, err := GenerateKeypair()- if err != nil {- return nil, err- }- if err := os.MkdirAll(m.keyDir, 0o700); err != nil {- return nil, fmt.Errorf("create key dir: %w", err)- }- // 0600 + the key dir at 0700: the private key is readable only by- // the agent's (root) user. It never travels to the panel.- if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {- return nil, fmt.Errorf("persist private key: %w", err)- }- return &KeygenResult{PublicKey: kp.PublicKey}, nil-}--func (m *linuxManager) linkExists(iface string) bool {- _, err := run("ip", "link", "show", iface)- return err == nil-}--func (m *linuxManager) InterfaceUp(req InterfaceUpRequest) error {- if err := validateInterfaceUp(req); err != nil {- return err- }- keyPath := m.keyPath(req.Name)- if _, err := os.Stat(keyPath); err != nil {- return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)- }-- // 1. Create the interface if it doesn't already exist (idempotent).- if !m.linkExists(req.Name) {- if _, err := run("ip", "link", "add", "dev", req.Name, "type", "wireguard"); err != nil {- return err- }- }-- // 2. Apply the private key (+ listen port on the edge side).- wgArgs := []string{"set", req.Name}- if req.ListenPort > 0 {- wgArgs = append(wgArgs, "listen-port", strconv.Itoa(req.ListenPort))- }- wgArgs = append(wgArgs, "private-key", keyPath)- if _, err := run("wg", wgArgs...); err != nil {- return err- }-- // 3. Address — `replace` adds or updates, so re-running up is safe.- if _, err := run("ip", "address", "replace", req.Address, "dev", req.Name); err != nil {- return err- }-- // 4. Bring it up.- if _, err := run("ip", "link", "set", req.Name, "up"); err != nil {- return err- }- return nil-}--func (m *linuxManager) InterfaceDown(iface string) error {- if err := validIfaceName(iface); err != nil {- return err- }- m.closeForwards(iface)- if !m.linkExists(iface) {- return nil // already gone — idempotent- }- _, err := run("ip", "link", "del", "dev", iface)- return err-}--func (m *linuxManager) Forward(req ForwardRequest) error {- if err := validateForward(req); err != nil {- return err- }- req = req.normalized()- // The WG IP is a real address on the kernel interface, so a normal- // listen on it receives traffic arriving over the tunnel.- l, err := net.Listen("tcp", net.JoinHostPort(req.ListenIP, strconv.Itoa(req.ListenPort)))- if err != nil {- return fmt.Errorf("listen %s:%d: %w", req.ListenIP, req.ListenPort, err)- }- key := forwardKey(req.Interface, req.ListenPort)- m.mu.Lock()- if old, ok := m.forwards[key]; ok {- old.Close()- }- m.forwards[key] = l- m.mu.Unlock()- go serveForward(l, req.TargetHost, req.TargetPort)- return nil-}--func (m *linuxManager) Unforward(iface string, listenPort int) error {- if err := validIfaceName(iface); err != nil {- return err- }- key := forwardKey(iface, listenPort)- m.mu.Lock()- defer m.mu.Unlock()- if l, ok := m.forwards[key]; ok {- l.Close()- delete(m.forwards, key)- }- return nil-}--// closeForwards stops every forwarder bound to iface (called on teardown).-func (m *linuxManager) closeForwards(iface string) {- m.mu.Lock()- defer m.mu.Unlock()- for k, l := range m.forwards {- if strings.HasPrefix(k, iface+":") {- l.Close()- delete(m.forwards, k)- }- }-}--func (m *linuxManager) SetPeer(req PeerSetRequest) error {- if err := validatePeerSet(req); err != nil {- return err- }- args := []string{"set", req.Interface, "peer", req.PublicKey,- "allowed-ips", strings.Join(req.AllowedIPs, ",")}- if req.Endpoint != "" {- args = append(args, "endpoint", req.Endpoint)- }- if req.PersistentKeepalive > 0 {- args = append(args, "persistent-keepalive", strconv.Itoa(req.PersistentKeepalive))- }- _, err := run("wg", args...)- return err-}--func (m *linuxManager) RemovePeer(req PeerRemoveRequest) error {- if err := validIfaceName(req.Interface); err != nil {- return err- }- if err := validPublicKey(req.PublicKey); err != nil {- return err- }- _, err := run("wg", "set", req.Interface, "peer", req.PublicKey, "remove")- return err-}--func (m *linuxManager) Status(iface string) (*InterfaceStatus, error) {- if err := validIfaceName(iface); err != nil {- return nil, err- }- st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}-- out, err := run("wg", "show", iface, "dump")- if err != nil {- // The interface most likely doesn't exist yet — report "down"- // rather than erroring so the panel can poll a tunnel that's- // still being built.- return st, nil- }- st.Up = true- parseWgDump(out, st)- return st, nil-}--// parseWgDump parses `wg show <iface> dump`. Line 1 is the interface-// (private-key, public-key, listen-port, fwmark); subsequent lines are-// peers (public-key, preshared-key, endpoint, allowed-ips,-// latest-handshake, transfer-rx, transfer-tx, persistent-keepalive).-//-// IMPORTANT: field [0] of the interface line is the PRIVATE key. We-// read field [1] (public) and deliberately never surface field [0].-func parseWgDump(out string, st *InterfaceStatus) {- lines := strings.Split(strings.TrimSpace(out), "\n")- for i, line := range lines {- if line == "" {- continue- }- f := strings.Split(line, "\t")- if i == 0 {- // interface line- if len(f) >= 2 {- st.PublicKey = f[1]- }- if len(f) >= 3 {- st.ListenPort = atoiSafe(f[2])- }- continue- }- // peer line- if len(f) < 8 {- continue- }- p := PeerStatus{PublicKey: f[0]}- if f[2] != "(none)" {- p.Endpoint = f[2]- }- if f[3] != "(none)" && f[3] != "" {- for _, a := range strings.Split(f[3], ",") {- if a = strings.TrimSpace(a); a != "" {- p.AllowedIPs = append(p.AllowedIPs, a)- }- }- }- p.LatestHandshake = atoi64Safe(f[4])- p.TransferRx = atoi64Safe(f[5])- p.TransferTx = atoi64Safe(f[6])- if f[7] != "off" {- p.PersistentKeepalive = atoiSafe(f[7])- }- st.Peers = append(st.Peers, p)- }-}--func atoiSafe(s string) int {- n, _ := strconv.Atoi(strings.TrimSpace(s))- return n-}--func atoi64Safe(s string) int64 {- n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)- return n-}diff --git a/agent/internal/wireguard/wireguard_other.go b/agent/internal/wireguard/wireguard_other.godeleted file mode 100644index c46f0bc7..00000000--- a/agent/internal/wireguard/wireguard_other.go+++ /dev/null@@ -1,358 +0,0 @@-//go:build !linux--package wireguard--import (- "encoding/base64"- "encoding/hex"- "fmt"- "net"- "net/netip"- "os"- "path/filepath"- "strconv"- "strings"- "sync"-- "golang.zx2c4.com/wireguard/conn"- "golang.zx2c4.com/wireguard/device"- "golang.zx2c4.com/wireguard/tun/netstack"-)--// Userspace WireGuard backend (roadmap #6) — wireguard-go + gVisor-// netstack. Pure userspace: NO kernel module, NO TUN driver (no Wintun),-// NO admin. That's what makes it viable on a home Windows/macOS box-// (e.g. the user's Jellyfin host).-//-// Difference vs the Linux kernel backend: netstack is an in-process-// TCP/IP stack, not a transparent L3 interface. keygen / interface:up /-// peer:set / status are fully functional (the WireGuard handshake works),-// which is what Phases 0–1 need. Forwarding a host service over the-// tunnel happens in Phase 2 through the retained *netstack.Net (tnet);-// the iface struct keeps it for exactly that.--// New returns a userspace Manager. keyDir holds per-interface private-// keys (0600); empty falls back to the user-config dir.-func New(keyDir string) Manager {- if keyDir == "" {- keyDir = userspaceDefaultKeyDir()- }- return &userspaceManager{- keyDir: keyDir,- ifaces: map[string]*usIface{},- forwards: map[string]net.Listener{},- }-}--func userspaceDefaultKeyDir() string {- if dir, err := os.UserConfigDir(); err == nil {- return filepath.Join(dir, "serverkit-agent", "wireguard")- }- return filepath.Join(os.TempDir(), "serverkit-agent-wireguard")-}--type userspaceManager struct {- keyDir string- mu sync.Mutex- ifaces map[string]*usIface- forwards map[string]net.Listener-}--type usIface struct {- dev *device.Device- tnet *netstack.Net // retained for Phase 2 service forwarding- pubKey string // base64; derived at up, surfaced by Status- listen int-}--func (m *userspaceManager) keyPath(iface string) string {- return filepath.Join(m.keyDir, iface+".key")-}--func (m *userspaceManager) Available() bool { return true }--func (m *userspaceManager) Keygen(iface string) (*KeygenResult, error) {- if err := validIfaceName(iface); err != nil {- return nil, err- }- kp, err := GenerateKeypair()- if err != nil {- return nil, err- }- if err := os.MkdirAll(m.keyDir, 0o700); err != nil {- return nil, fmt.Errorf("create key dir: %w", err)- }- if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {- return nil, fmt.Errorf("persist private key: %w", err)- }- return &KeygenResult{PublicKey: kp.PublicKey}, nil-}--func (m *userspaceManager) InterfaceUp(req InterfaceUpRequest) error {- if err := validateInterfaceUp(req); err != nil {- return err- }- raw, err := os.ReadFile(m.keyPath(req.Name))- if err != nil {- return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)- }- privB64 := strings.TrimSpace(string(raw))- privHex, err := keyB64ToHex(privB64)- if err != nil {- return fmt.Errorf("bad stored private key: %w", err)- }- pub, err := PublicKeyFromPrivate(privB64)- if err != nil {- return fmt.Errorf("derive public key: %w", err)- }- prefix, err := netip.ParsePrefix(req.Address)- if err != nil {- return fmt.Errorf("bad address %q: %w", req.Address, err)- }-- m.mu.Lock()- defer m.mu.Unlock()- if _, ok := m.ifaces[req.Name]; ok {- return nil // idempotent: already up- }-- tunDev, tnet, err := netstack.CreateNetTUN([]netip.Addr{prefix.Addr()}, nil, device.DefaultMTU)- if err != nil {- return fmt.Errorf("create userspace tun: %w", err)- }- dev := device.NewDevice(tunDev, conn.NewDefaultBind(),- device.NewLogger(device.LogLevelError, "wg/"+req.Name+" "))-- var cfg strings.Builder- cfg.WriteString("private_key=" + privHex + "\n")- if req.ListenPort > 0 {- cfg.WriteString("listen_port=" + strconv.Itoa(req.ListenPort) + "\n")- }- if err := dev.IpcSet(cfg.String()); err != nil {- dev.Close()- return fmt.Errorf("configure device: %w", err)- }- if err := dev.Up(); err != nil {- dev.Close()- return fmt.Errorf("bring up device: %w", err)- }- m.ifaces[req.Name] = &usIface{dev: dev, tnet: tnet, pubKey: pub, listen: req.ListenPort}- return nil-}--func (m *userspaceManager) InterfaceDown(iface string) error {- if err := validIfaceName(iface); err != nil {- return err- }- m.mu.Lock()- defer m.mu.Unlock()- for k, l := range m.forwards {- if strings.HasPrefix(k, iface+":") {- l.Close()- delete(m.forwards, k)- }- }- if ifc, ok := m.ifaces[iface]; ok {- ifc.dev.Close()- delete(m.ifaces, iface)- }- return nil // idempotent-}--func (m *userspaceManager) Forward(req ForwardRequest) error {- if err := validateForward(req); err != nil {- return err- }- req = req.normalized()- m.mu.Lock()- ifc := m.ifaces[req.Interface]- m.mu.Unlock()- if ifc == nil {- return fmt.Errorf("interface %q is not up", req.Interface)- }- ip, err := netip.ParseAddr(req.ListenIP)- if err != nil {- return fmt.Errorf("invalid listen_ip %q: %w", req.ListenIP, err)- }- // Listen INSIDE the netstack on the WG IP — this receives the- // connections the edge proxies over the tunnel. serveForward then- // dials the real host service over the OS network.- l, err := ifc.tnet.ListenTCPAddrPort(netip.AddrPortFrom(ip, uint16(req.ListenPort)))- if err != nil {- return fmt.Errorf("netstack listen %s:%d: %w", req.ListenIP, req.ListenPort, err)- }- key := forwardKey(req.Interface, req.ListenPort)- m.mu.Lock()- if old, ok := m.forwards[key]; ok {- old.Close()- }- m.forwards[key] = l- m.mu.Unlock()- go serveForward(l, req.TargetHost, req.TargetPort)- return nil-}--func (m *userspaceManager) Unforward(iface string, listenPort int) error {- if err := validIfaceName(iface); err != nil {- return err- }- key := forwardKey(iface, listenPort)- m.mu.Lock()- defer m.mu.Unlock()- if l, ok := m.forwards[key]; ok {- l.Close()- delete(m.forwards, key)- }- return nil-}--func (m *userspaceManager) SetPeer(req PeerSetRequest) error {- if err := validatePeerSet(req); err != nil {- return err- }- m.mu.Lock()- ifc := m.ifaces[req.Interface]- m.mu.Unlock()- if ifc == nil {- return fmt.Errorf("interface %q is not up", req.Interface)- }- pubHex, err := keyB64ToHex(req.PublicKey)- if err != nil {- return fmt.Errorf("bad peer public key: %w", err)- }- var cfg strings.Builder- cfg.WriteString("public_key=" + pubHex + "\n")- cfg.WriteString("replace_allowed_ips=true\n")- for _, ip := range req.AllowedIPs {- cfg.WriteString("allowed_ip=" + strings.TrimSpace(ip) + "\n")- }- if req.Endpoint != "" {- cfg.WriteString("endpoint=" + req.Endpoint + "\n")- }- if req.PersistentKeepalive > 0 {- cfg.WriteString("persistent_keepalive_interval=" + strconv.Itoa(req.PersistentKeepalive) + "\n")- }- return ifc.dev.IpcSet(cfg.String())-}--func (m *userspaceManager) RemovePeer(req PeerRemoveRequest) error {- if err := validIfaceName(req.Interface); err != nil {- return err- }- if err := validPublicKey(req.PublicKey); err != nil {- return err- }- m.mu.Lock()- ifc := m.ifaces[req.Interface]- m.mu.Unlock()- if ifc == nil {- return nil // nothing to remove- }- pubHex, err := keyB64ToHex(req.PublicKey)- if err != nil {- return fmt.Errorf("bad peer public key: %w", err)- }- return ifc.dev.IpcSet("public_key=" + pubHex + "\nremove=true\n")-}--func (m *userspaceManager) Status(iface string) (*InterfaceStatus, error) {- if err := validIfaceName(iface); err != nil {- return nil, err- }- st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}- m.mu.Lock()- ifc := m.ifaces[iface]- m.mu.Unlock()- if ifc == nil {- return st, nil // down- }- st.Up = true- st.PublicKey = ifc.pubKey- st.ListenPort = ifc.listen- cfg, err := ifc.dev.IpcGet()- if err != nil {- return st, nil- }- parseUAPIStatus(cfg, st)- return st, nil-}--// parseUAPIStatus parses wireguard-go's IpcGet() output into peers.-// It deliberately ignores the interface's private_key line (never-// surfaced). Peer public keys are converted hex→base64 to match the-// panel and the kernel backend's `wg show dump` output.-func parseUAPIStatus(cfg string, st *InterfaceStatus) {- var cur *PeerStatus- flush := func() {- if cur != nil {- st.Peers = append(st.Peers, *cur)- cur = nil- }- }- for _, line := range strings.Split(cfg, "\n") {- line = strings.TrimSpace(line)- if line == "" {- continue- }- k, v, ok := strings.Cut(line, "=")- if !ok {- continue- }- switch k {- case "public_key": // begins a new peer section- flush()- cur = &PeerStatus{PublicKey: keyHexToB64(v)}- case "endpoint":- if cur != nil {- cur.Endpoint = v- }- case "allowed_ip":- if cur != nil {- cur.AllowedIPs = append(cur.AllowedIPs, v)- }- case "last_handshake_time_sec":- if cur != nil {- cur.LatestHandshake = atoi64u(v)- }- case "rx_bytes":- if cur != nil {- cur.TransferRx = atoi64u(v)- }- case "tx_bytes":- if cur != nil {- cur.TransferTx = atoi64u(v)- }- case "persistent_keepalive_interval":- if cur != nil {- cur.PersistentKeepalive = int(atoi64u(v))- }- }- // private_key / preshared_key / errno / protocol_version /- // last_handshake_time_nsec / listen_port / fwmark → ignored.- }- flush()-}--func keyB64ToHex(b64 string) (string, error) {- raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64))- if err != nil {- return "", err- }- if len(raw) != 32 {- return "", fmt.Errorf("key must be 32 bytes, got %d", len(raw))- }- return hex.EncodeToString(raw), nil-}--func keyHexToB64(h string) string {- raw, err := hex.DecodeString(strings.TrimSpace(h))- if err != nil {- return h // fall back to the raw value on parse failure- }- return base64.StdEncoding.EncodeToString(raw)-}--func atoi64u(s string) int64 {- n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)- return n-}diff --git a/agent/internal/wireguard/wireguard_test.go b/agent/internal/wireguard/wireguard_test.godeleted file mode 100644index 72dc95b1..00000000--- a/agent/internal/wireguard/wireguard_test.go+++ /dev/null@@ -1,149 +0,0 @@-package wireguard--import (- "encoding/base64"- "io"- "net"- "strconv"- "testing"- "time"-)--func TestGenerateKeypair(t *testing.T) {- kp, err := GenerateKeypair()- if err != nil {- t.Fatalf("GenerateKeypair: %v", err)- }- if err := validPublicKey(kp.PublicKey); err != nil {- t.Errorf("generated public key invalid: %v", err)- }- priv, err := base64.StdEncoding.DecodeString(kp.PrivateKey)- if err != nil || len(priv) != 32 {- t.Errorf("private key not 32 base64 bytes: err=%v len=%d", err, len(priv))- }- if kp.PrivateKey == kp.PublicKey {- t.Error("private and public key are identical")- }- kp2, _ := GenerateKeypair()- if kp.PrivateKey == kp2.PrivateKey {- t.Error("two keygens produced identical private keys")- }-}--func TestValidPublicKey(t *testing.T) {- kp, _ := GenerateKeypair()- if err := validPublicKey(kp.PublicKey); err != nil {- t.Errorf("valid key rejected: %v", err)- }- if validPublicKey("not base64!!!") == nil {- t.Error("non-base64 key accepted")- }- if validPublicKey(base64.StdEncoding.EncodeToString([]byte("short"))) == nil {- t.Error("wrong-length key accepted")- }-}--func TestValidateInterfaceUp(t *testing.T) {- ok := InterfaceUpRequest{Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 51820}- if err := validateInterfaceUp(ok); err != nil {- t.Errorf("valid request rejected: %v", err)- }- bad := []InterfaceUpRequest{- {Name: "bad iface!", Address: "10.88.0.1/24"},- {Name: "skwg0", Address: "not-a-cidr"},- {Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 70000},- {Name: "this-name-is-far-too-long", Address: "10.88.0.1/24"},- }- for i, b := range bad {- if validateInterfaceUp(b) == nil {- t.Errorf("invalid request %d was accepted", i)- }- }-}--func TestValidatePeerSet(t *testing.T) {- kp, _ := GenerateKeypair()- ok := PeerSetRequest{- Interface: "skwg0", PublicKey: kp.PublicKey,- AllowedIPs: []string{"10.88.0.2/32"},- Endpoint: "203.0.113.5:51820", PersistentKeepalive: 25,- }- if err := validatePeerSet(ok); err != nil {- t.Errorf("valid peer rejected: %v", err)- }- bad := []PeerSetRequest{- {Interface: "skwg0", PublicKey: "bad", AllowedIPs: []string{"10.88.0.2/32"}},- {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: nil},- {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"nope"}},- {Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"10.88.0.2/32"}, Endpoint: "no-port"},- }- for i, b := range bad {- if validatePeerSet(b) == nil {- t.Errorf("invalid peer %d was accepted", i)- }- }-}--func TestPublicKeyFromPrivate(t *testing.T) {- kp, _ := GenerateKeypair()- pub, err := PublicKeyFromPrivate(kp.PrivateKey)- if err != nil {- t.Fatalf("PublicKeyFromPrivate: %v", err)- }- if pub != kp.PublicKey {- t.Errorf("derived public key %s != keypair public key %s", pub, kp.PublicKey)- }- if _, err := PublicKeyFromPrivate("not-a-key"); err == nil {- t.Error("accepted an invalid private key")- }-}--// TestForwarder proves serveForward's accept loop + bidirectional proxy-// with real sockets (the listener-creation differs per backend, but the-// proxy plumbing is shared and is what carries the user's traffic).-func TestForwarder(t *testing.T) {- // Echo server standing in for the real local service (e.g. Jellyfin).- target, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("target listen: %v", err)- }- defer target.Close()- go func() {- for {- c, err := target.Accept()- if err != nil {- return- }- go func(c net.Conn) { _, _ = io.Copy(c, c); c.Close() }(c)- }- }()- _, tportStr, _ := net.SplitHostPort(target.Addr().String())- tport, _ := strconv.Atoi(tportStr)-- // Forwarder listener standing in for the WG-side listen.- fwd, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("forwarder listen: %v", err)- }- defer fwd.Close()- go serveForward(fwd, "127.0.0.1", tport)-- conn, err := net.Dial("tcp", fwd.Addr().String())- if err != nil {- t.Fatalf("dial forwarder: %v", err)- }- defer conn.Close()- _ = conn.SetDeadline(time.Now().Add(3 * time.Second))-- msg := []byte("hello-tunnel")- if _, err := conn.Write(msg); err != nil {- t.Fatalf("write: %v", err)- }- buf := make([]byte, len(msg))- if _, err := io.ReadFull(conn, buf); err != nil {- t.Fatalf("read: %v", err)- }- if string(buf) != string(msg) {- t.Errorf("echo mismatch: got %q want %q", buf, msg)- }-}diff --git a/agent/internal/wireguard/wireguard_userspace_test.go b/agent/internal/wireguard/wireguard_userspace_test.godeleted file mode 100644index 6da68c92..00000000--- a/agent/internal/wireguard/wireguard_userspace_test.go+++ /dev/null@@ -1,70 +0,0 @@-//go:build !linux--package wireguard--import "testing"--func TestKeyHexRoundTrip(t *testing.T) {- kp, _ := GenerateKeypair()- h, err := keyB64ToHex(kp.PublicKey)- if err != nil {- t.Fatalf("keyB64ToHex: %v", err)- }- if len(h) != 64 {- t.Errorf("hex key length = %d, want 64", len(h))- }- if back := keyHexToB64(h); back != kp.PublicKey {- t.Errorf("roundtrip mismatch: %s != %s", back, kp.PublicKey)- }-}--// TestParseUAPIStatus checks the wireguard-go IpcGet() parser and guards-// the no-leak invariant: the interface's private_key line must never end-// up in any surfaced field.-func TestParseUAPIStatus(t *testing.T) {- ifaceKp, _ := GenerateKeypair()- peerKp, _ := GenerateKeypair()- privHex, _ := keyB64ToHex(ifaceKp.PrivateKey)- peerHex, _ := keyB64ToHex(peerKp.PublicKey)-- cfg := "private_key=" + privHex + "\n" +- "listen_port=51820\n" +- "public_key=" + peerHex + "\n" +- "endpoint=203.0.113.5:51820\n" +- "allowed_ip=10.88.0.1/32\n" +- "last_handshake_time_sec=1700000000\n" +- "rx_bytes=1024\n" +- "tx_bytes=2048\n" +- "persistent_keepalive_interval=25\n" +- "protocol_version=1\n"-- st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}- parseUAPIStatus(cfg, st)-- if len(st.Peers) != 1 {- t.Fatalf("want 1 peer, got %d", len(st.Peers))- }- p := st.Peers[0]- if p.PublicKey != peerKp.PublicKey {- t.Errorf("peer PublicKey = %s, want %s (hex→base64)", p.PublicKey, peerKp.PublicKey)- }- if p.Endpoint != "203.0.113.5:51820" {- t.Errorf("Endpoint = %q", p.Endpoint)- }- if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.1/32" {- t.Errorf("AllowedIPs = %v", p.AllowedIPs)- }- if p.LatestHandshake != 1700000000 {- t.Errorf("LatestHandshake = %d", p.LatestHandshake)- }- if p.TransferRx != 1024 || p.TransferTx != 2048 {- t.Errorf("transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)- }- if p.PersistentKeepalive != 25 {- t.Errorf("PersistentKeepalive = %d", p.PersistentKeepalive)- }- // No-leak: the private key (as base64) must not appear in any field.- if p.PublicKey == ifaceKp.PrivateKey {- t.Fatal("LEAK: interface private key surfaced as a peer public key")- }-}diff --git a/agent/internal/ws/client.go b/agent/internal/ws/client.godeleted file mode 100644index 3fe21e03..00000000--- a/agent/internal/ws/client.go+++ /dev/null@@ -1,844 +0,0 @@-package ws--import (- "context"- "crypto/tls"- "encoding/json"- "fmt"- "net/http"- "net/url"- "os"- "strings"- "sync"- "time"-- "github.com/gorilla/websocket"- "github.com/serverkit/agent/internal/auth"- "github.com/serverkit/agent/internal/config"- "github.com/serverkit/agent/internal/logger"- "github.com/serverkit/agent/internal/transport"- "github.com/serverkit/agent/pkg/protocol"-)--// Version is the agent version string surfaced in the User-Agent-// header. Defaults to "dev"; main.go's init() mirrors the ldflags-set-// main.Version into this when a release build runs.-var Version = "dev"--func agentVersion() string { return Version }--// MessageHandler is the callback fired on inbound packets. Aliased to the-// transport package so ws.Client implements transport.Transport without-// adapter glue.-type MessageHandler = transport.MessageHandler--// Client is a Socket.IO client with auto-reconnect-type Client struct {- cfg config.ServerConfig- auth *auth.Authenticator- log *logger.Logger- conn *websocket.Conn- handler MessageHandler- session *auth.SessionToken-- mu sync.RWMutex- connected bool- reconnecting bool- lastErr error- everConnected bool-- sendCh chan []byte- doneCh chan struct{}-- reconnectCount int-- // Socket.IO namespace- namespace string- // Engine.IO ping interval from server- pingInterval time.Duration- pingTimeout time.Duration-}--// NewClient creates a new WebSocket client-func NewClient(cfg config.ServerConfig, authenticator *auth.Authenticator, log *logger.Logger) *Client {- return &Client{- cfg: cfg,- auth: authenticator,- log: log.WithComponent("websocket"),- sendCh: make(chan []byte, 100),- doneCh: make(chan struct{}),- namespace: "/agent",- }-}--// SetHandler sets the message handler-func (c *Client) SetHandler(handler MessageHandler) {- c.handler = handler-}--// buildSocketIOURL converts the configured server URL to a Socket.IO WebSocket URL.-// Input examples:-// - "wss://server.example.com/agent"-// - "ws://localhost:5000/agent"-//-// Output: "wss://server.example.com/socket.io/?EIO=4&transport=websocket"-func (c *Client) buildSocketIOURL() (string, error) {- rawURL := c.cfg.URL- if rawURL == "" {- return "", fmt.Errorf("server URL is empty")- }-- parsed, err := url.Parse(rawURL)- if err != nil {- return "", fmt.Errorf("invalid server URL: %w", err)- }-- // Keep the scheme (ws/wss), strip the path (e.g. /agent)- parsed.Path = "/socket.io/"- q := url.Values{}- q.Set("EIO", "4")- q.Set("transport", "websocket")- parsed.RawQuery = q.Encode()-- return parsed.String(), nil-}--// Connect establishes a Socket.IO connection over WebSocket-func (c *Client) Connect(ctx context.Context) error {- c.mu.Lock()- if c.connected {- c.mu.Unlock()- return nil- }- c.mu.Unlock()-- sioURL, err := c.buildSocketIOURL()- if err != nil {- return err- }-- // Compression default: off. Some tunnel intermediaries (free-tier ngrok,- // trycloudflare.com quick tunnels) corrupt compressed WebSocket frames —- // gorilla then rejects them with "RSV1 set, FIN not set on control". The- // env var override exists for users behind a *permanent* cf tunnel or a- // reverse proxy that handles WS compression cleanly: setting- // SERVERKIT_WS_COMPRESSION=true makes the agent negotiate permessage-- // deflate, which is necessary if the panel/proxy unconditionally sends- // compressed frames regardless of negotiation.- enableCompression := os.Getenv("SERVERKIT_WS_COMPRESSION") == "true"- dialer := websocket.Dialer{- HandshakeTimeout: 10 * time.Second,- EnableCompression: enableCompression,- }-- // Only allow insecure TLS when explicitly set via environment variable- if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {- dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}- }-- // Add authentication headers- headers := http.Header{}- headers.Set("X-Agent-ID", c.auth.AgentID())- headers.Set("X-API-Key-Prefix", c.auth.GetAPIKeyPrefix())- headers.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", agentVersion()))- // Bypass ngrok's interstitial / browser-warning behaviour for free-tier- // tunnels. Harmless when the panel isn't behind ngrok.- headers.Set("ngrok-skip-browser-warning", "true")-- c.log.Debug("Connecting to Socket.IO", "url", sioURL)-- conn, resp, err := dialer.DialContext(ctx, sioURL, headers)- if err != nil {- if resp != nil {- c.log.Error("Connection failed",- "error", err,- "status", resp.StatusCode,- )- }- return fmt.Errorf("failed to connect: %w", err)- }-- c.mu.Lock()- c.conn = conn- c.mu.Unlock()-- // Step 1: Read Engine.IO OPEN packet- if err := c.handleEngineIOOpen(); err != nil {- conn.Close()- // "RSV1 set, FIN not set on control" is the classic signature of a- // tunnel intermediary (cf quick tunnels, free-tier ngrok) injecting- // or corrupting WebSocket compression. The user can't fix the panel- // from the agent side — the only useful action is "try a different- // transport." Surface that explicitly so the error stops being- // cryptic.- if strings.Contains(err.Error(), "RSV1 set") {- c.log.Error("WebSocket frame compression conflict — likely caused by the tunnel between agent and panel",- "hint", "try SERVERKIT_WS_COMPRESSION=true, or switch from a Cloudflare quick tunnel (*.trycloudflare.com) to a permanent named tunnel, or front the panel with a direct HTTPS reverse proxy",- )- }- return fmt.Errorf("engine.io handshake failed: %w", err)- }-- // Step 2: Connect to Socket.IO namespace- if err := c.connectNamespace(); err != nil {- conn.Close()- return fmt.Errorf("namespace connect failed: %w", err)- }-- c.mu.Lock()- c.connected = true- c.reconnecting = false- c.reconnectCount = 0- c.mu.Unlock()-- c.log.Info("Connected to server via Socket.IO")-- // Step 3: Authenticate via Socket.IO event- if err := c.authenticate(); err != nil {- c.Close()- return fmt.Errorf("authentication failed: %w", err)- }-- return nil-}--// handleEngineIOOpen reads and processes the Engine.IO OPEN packet (type 0)-func (c *Client) handleEngineIOOpen() error {- c.conn.SetReadDeadline(time.Now().Add(10 * time.Second))- _, msg, err := c.conn.ReadMessage()- if err != nil {- return fmt.Errorf("failed to read OPEN packet: %w", err)- }- c.conn.SetReadDeadline(time.Time{})-- msgStr := string(msg)- c.log.Debug("Received Engine.IO packet", "raw", msgStr)-- // Engine.IO OPEN packet starts with '0'- if len(msgStr) < 2 || msgStr[0] != '0' {- return fmt.Errorf("expected OPEN packet (0), got: %s", msgStr)- }-- // Parse the JSON payload- var openData struct {- SID string `json:"sid"`- Upgrades []string `json:"upgrades"`- PingInterval int `json:"pingInterval"`- PingTimeout int `json:"pingTimeout"`- }- if err := json.Unmarshal([]byte(msgStr[1:]), &openData); err != nil {- return fmt.Errorf("failed to parse OPEN data: %w", err)- }-- c.pingInterval = time.Duration(openData.PingInterval) * time.Millisecond- c.pingTimeout = time.Duration(openData.PingTimeout) * time.Millisecond-- c.log.Debug("Engine.IO handshake complete",- "sid", openData.SID,- "pingInterval", c.pingInterval,- "pingTimeout", c.pingTimeout,- )-- return nil-}--// connectNamespace sends a Socket.IO CONNECT packet to the /agent namespace-func (c *Client) connectNamespace() error {- // Socket.IO CONNECT: packet type 4 (MESSAGE) + message type 0 (CONNECT) + namespace- // Wire format: "40/agent,"- connectMsg := fmt.Sprintf("40%s,", c.namespace)- c.log.Debug("Connecting to namespace", "namespace", c.namespace, "packet", connectMsg)-- if err := c.conn.WriteMessage(websocket.TextMessage, []byte(connectMsg)); err != nil {- return fmt.Errorf("failed to send CONNECT: %w", err)- }-- // Read namespace CONNECT ack- c.conn.SetReadDeadline(time.Now().Add(10 * time.Second))- _, msg, err := c.conn.ReadMessage()- if err != nil {- return fmt.Errorf("failed to read CONNECT ack: %w", err)- }- c.conn.SetReadDeadline(time.Time{})-- msgStr := string(msg)- c.log.Debug("Received namespace response", "raw", msgStr)-- // Expected: "40/agent,{\"sid\":\"...\"}"- // Or error: "44/agent,{\"message\":\"...\"}"- prefix := fmt.Sprintf("40%s,", c.namespace)- errorPrefix := fmt.Sprintf("44%s,", c.namespace)-- if strings.HasPrefix(msgStr, errorPrefix) {- return fmt.Errorf("namespace connection rejected: %s", msgStr)- }-- if !strings.HasPrefix(msgStr, prefix) {- return fmt.Errorf("unexpected namespace response: %s", msgStr)- }-- c.log.Info("Connected to namespace", "namespace", c.namespace)- return nil-}--// authenticate sends an "auth" Socket.IO event and waits for response-func (c *Client) authenticate() error {- timestamp := time.Now().UnixMilli()- nonce := auth.GenerateNonce()- signature := c.auth.SignMessageWithNonce(timestamp, nonce)-- authData := map[string]interface{}{- "type": "auth",- "agent_id": c.auth.AgentID(),- "api_key_prefix": c.auth.GetAPIKeyPrefix(),- "nonce": nonce,- "timestamp": timestamp,- "signature": signature,- }-- c.log.Debug("Sending authentication event")-- if err := c.emitEvent("auth", authData); err != nil {- return fmt.Errorf("failed to send auth event: %w", err)- }-- // Wait for auth response event- c.conn.SetReadDeadline(time.Now().Add(10 * time.Second))- defer c.conn.SetReadDeadline(time.Time{})-- for {- _, msg, err := c.conn.ReadMessage()- if err != nil {- return fmt.Errorf("failed to read auth response: %w", err)- }-- msgStr := string(msg)-- // Handle Engine.IO ping during auth- if msgStr == "2" {- c.conn.WriteMessage(websocket.TextMessage, []byte("3"))- continue- }-- eventName, eventData, err := c.parseEvent(msgStr)- if err != nil {- c.log.Debug("Ignoring non-event message during auth", "raw", msgStr)- continue- }-- switch eventName {- case "auth_ok":- var response struct {- Type string `json:"type"`- SessionToken string `json:"session_token"`- Expires int64 `json:"expires"`- ServerID string `json:"server_id"`- }- if err := json.Unmarshal(eventData, &response); err != nil {- return fmt.Errorf("failed to parse auth_ok: %w", err)- }-- c.session = &auth.SessionToken{- Token: response.SessionToken,- ExpiresAt: time.UnixMilli(response.Expires),- }-- c.log.Info("Authentication successful",- "expires_in", time.Until(c.session.ExpiresAt).Round(time.Second),- )- return nil-- case "auth_fail":- var response struct {- Type string `json:"type"`- Error string `json:"error"`- }- json.Unmarshal(eventData, &response)- return fmt.Errorf("authentication rejected: %s", response.Error)-- default:- c.log.Debug("Ignoring event during auth", "event", eventName)- }- }-}--// emitEvent sends a Socket.IO EVENT packet-// Wire format: 42/agent,["event_name",{data}]-func (c *Client) emitEvent(event string, data interface{}) error {- dataBytes, err := json.Marshal(data)- if err != nil {- return fmt.Errorf("failed to marshal event data: %w", err)- }-- // Build Socket.IO EVENT: 42/namespace,["event",data]- eventJSON := fmt.Sprintf(`42%s,["%s",%s]`, c.namespace, event, string(dataBytes))-- return c.conn.WriteMessage(websocket.TextMessage, []byte(eventJSON))-}--// parseEvent parses a Socket.IO EVENT packet and returns event name + data-// Expected format: 42/agent,["event_name",{data}]-func (c *Client) parseEvent(msg string) (string, json.RawMessage, error) {- prefix := fmt.Sprintf("42%s,", c.namespace)- if !strings.HasPrefix(msg, prefix) {- return "", nil, fmt.Errorf("not a Socket.IO EVENT for namespace %s", c.namespace)- }-- payload := msg[len(prefix):]-- // Parse as JSON array: ["event_name", data]- var arr []json.RawMessage- if err := json.Unmarshal([]byte(payload), &arr); err != nil {- return "", nil, fmt.Errorf("failed to parse event array: %w", err)- }-- if len(arr) < 1 {- return "", nil, fmt.Errorf("empty event array")- }-- // Extract event name (first element is a string)- var eventName string- if err := json.Unmarshal(arr[0], &eventName); err != nil {- return "", nil, fmt.Errorf("failed to parse event name: %w", err)- }-- // Data is the second element (may be absent)- var eventData json.RawMessage- if len(arr) > 1 {- eventData = arr[1]- }-- return eventName, eventData, nil-}--// Run starts the read/write loops and handles reconnection-func (c *Client) Run(ctx context.Context) error {- for {- select {- case <-ctx.Done():- c.Close()- return ctx.Err()- default:- }-- // Connect if not connected- c.mu.RLock()- connected := c.connected- c.mu.RUnlock()-- if !connected {- if err := c.Connect(ctx); err != nil {- c.log.Warn("Connection failed", "error", err)- c.mu.Lock()- c.lastErr = err- c.mu.Unlock()- c.handleReconnect(ctx)- continue- }- c.mu.Lock()- c.everConnected = true- c.lastErr = nil- c.mu.Unlock()- }-- // Per-iteration ctx so we can cancel readLoop/writeLoop/pingLoop- // together when any one of them errors. The previous code only- // read the first error off errCh and let the other two- // goroutines leak until the next reconnect's conn.Close- // happened to cause a read error in them — every flap leaked- // goroutines that, in tunnel-flap scenarios, accumulated- // quickly. With per-iteration cancellation each connection- // owns exactly three goroutines for its lifetime.- loopCtx, cancelLoop := context.WithCancel(ctx)- errCh := make(chan error, 3)-- var wg sync.WaitGroup- wg.Add(3)- go func() {- defer wg.Done()- errCh <- c.readLoop(loopCtx)- }()- go func() {- defer wg.Done()- errCh <- c.writeLoop(loopCtx)- }()- go func() {- defer wg.Done()- errCh <- c.pingLoop(loopCtx)- }()-- // Wait for error- err := <-errCh- c.log.Warn("Connection loop ended", "error", err)-- // Mark as disconnected before draining sendCh so any- // concurrent Send() callers see the disconnected state and- // fail fast rather than queueing onto a buffer about to- // be flushed.- c.mu.Lock()- c.connected = false- c.mu.Unlock()-- // Cancel siblings and close the conn so readLoop unblocks- // from its read deadline. Then wait for both siblings to- // drain their error onto errCh — leaving them running was- // the goroutine leak.- cancelLoop()- if c.conn != nil {- c.conn.Close()- }- wg.Wait()- // Drain the remaining errCh entries so the channel doesn't- // retain references to err values.- for len(errCh) > 0 {- <-errCh- }-- // Drain stale messages buffered while the previous connection- // was already failing. Replaying these on a fresh session- // would ship heartbeats/results from a dead WS to a new auth- // context — and worse, if the buffer ever filled mid-flap,- // every subsequent Send() would return "send channel full"- // permanently. Replace the channel with a fresh one so we- // also drop any blocked senders cleanly.- c.drainSendCh()-- // Check if context is cancelled- select {- case <-ctx.Done():- return ctx.Err()- default:- c.handleReconnect(ctx)- }- }-}--// drainSendCh empties any pending outbound messages from the previous-// connection. Called after a disconnect so we don't ship stale frames-// (heartbeats, command results) on the next session — they were-// computed against the old auth context and the panel will either-// reject them or attribute them to the wrong session window.-func (c *Client) drainSendCh() {- for {- select {- case <-c.sendCh:- default:- return- }- }-}--// readLoop reads Socket.IO messages from the WebSocket-func (c *Client) readLoop(ctx context.Context) error {- // Read deadline = pingInterval * 2.5 + 5s grace. Any inbound message- // (server ping, app frame, WS-level pong) resets the deadline. If- // nothing arrives within this window, the connection is presumed- // dead at the network layer and the read errors out, which is what- // the Manager's flap detector relies on. Without this, CF/ngrok- // killing the connection at the network layer (without sending a- // WS close frame) makes ReadMessage hang for minutes — exactly the- // "ws_disconnected every 2-3 min" pattern in the user's events.json.- readWait := c.pingInterval*5/2 + 5*time.Second- if readWait < 30*time.Second {- readWait = 30 * time.Second- }- resetDeadline := func() {- _ = c.conn.SetReadDeadline(time.Now().Add(readWait))- }- resetDeadline()- c.conn.SetPongHandler(func(string) error {- resetDeadline()- return nil- })-- for {- select {- case <-ctx.Done():- return ctx.Err()- default:- }-- _, msg, err := c.conn.ReadMessage()- if err != nil {- return fmt.Errorf("read error: %w", err)- }- // Any successful read = liveness signal. Reset the window.- resetDeadline()-- msgStr := string(msg)-- // Handle Engine.IO PING (server sends "2", we respond "3")- if msgStr == "2" {- if err := c.conn.WriteMessage(websocket.TextMessage, []byte("3")); err != nil {- return fmt.Errorf("failed to send pong: %w", err)- }- c.log.Debug("Responded to Engine.IO ping")- continue- }-- // Handle Engine.IO CLOSE- if msgStr == "1" {- return fmt.Errorf("server sent Engine.IO CLOSE")- }-- // Handle Socket.IO DISCONNECT for our namespace- disconnectPrefix := fmt.Sprintf("41%s,", c.namespace)- if strings.HasPrefix(msgStr, disconnectPrefix) || msgStr == "41" {- return fmt.Errorf("server disconnected namespace %s", c.namespace)- }-- // Parse Socket.IO EVENT- eventName, eventData, err := c.parseEvent(msgStr)- if err != nil {- c.log.Debug("Ignoring unrecognized message", "raw", msgStr)- continue- }-- // Map event name to protocol message type and dispatch- c.dispatchEvent(eventName, eventData)- }-}--// dispatchEvent maps a Socket.IO event to the agent's message handler-func (c *Client) dispatchEvent(eventName string, data json.RawMessage) {- c.log.Debug("Received event", "event", eventName)-- // Map Socket.IO event names to protocol message types- msgType := protocol.MessageType(eventName)-- // Handle heartbeat ack internally- if msgType == protocol.TypeHeartbeatAck {- c.log.Debug("Received heartbeat ack")- return- }-- // For events that carry data, we need to reconstruct the full message- // so the agent handler can unmarshal it as expected- if c.handler != nil && len(data) > 0 {- c.handler(msgType, data)- }-}--// writeLoop writes queued messages via Socket.IO events-func (c *Client) writeLoop(ctx context.Context) error {- for {- select {- case <-ctx.Done():- return ctx.Err()- case msg := <-c.sendCh:- // Parse the message to extract the type for the event name- var base protocol.Message- if err := json.Unmarshal(msg, &base); err != nil {- c.log.Warn("Failed to parse outgoing message", "error", err)- continue- }-- eventName := string(base.Type)- eventJSON := fmt.Sprintf(`42%s,["%s",%s]`, c.namespace, eventName, string(msg))-- if err := c.conn.WriteMessage(websocket.TextMessage, []byte(eventJSON)); err != nil {- return fmt.Errorf("write error: %w", err)- }- }- }-}--// pingLoop sends Engine.IO PING packets to keep the connection alive-func (c *Client) pingLoop(ctx context.Context) error {- if c.pingInterval <= 0 {- c.pingInterval = 25 * time.Second- }-- ticker := time.NewTicker(c.pingInterval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return ctx.Err()- case <-ticker.C:- c.mu.RLock()- connected := c.connected- c.mu.RUnlock()-- if !connected {- return fmt.Errorf("not connected")- }-- // Engine.IO PING from client side (type 3 = PONG in EIO4 client-initiated)- // Actually in EIO4, server sends PINGs (2) and client responds with PONGs (3)- // Client doesn't need to send its own pings, just respond to server's- // But we'll use this loop to detect stale connections via WriteControl- if err := c.conn.WriteControl(- websocket.PingMessage,- nil,- time.Now().Add(5*time.Second),- ); err != nil {- return fmt.Errorf("websocket ping failed: %w", err)- }- }- }-}--// handleReconnect implements exponential backoff reconnection-func (c *Client) handleReconnect(ctx context.Context) {- c.mu.Lock()- c.reconnecting = true- c.reconnectCount++- count := c.reconnectCount- c.mu.Unlock()-- // Calculate backoff duration- backoff := c.cfg.ReconnectInterval * time.Duration(1<<uint(count-1))- if backoff > c.cfg.MaxReconnectInterval {- backoff = c.cfg.MaxReconnectInterval- }-- c.log.Info("Reconnecting",- "attempt", count,- "backoff", backoff,- )-- select {- case <-ctx.Done():- return- case <-time.After(backoff):- return- }-}--// Send queues a message for sending-func (c *Client) Send(msg interface{}) error {- c.mu.RLock()- connected := c.connected- c.mu.RUnlock()- if !connected {- // Refuse to queue when there's nothing draining the channel.- // Otherwise a backlog accumulates while the agent is offline- // and floods the panel on reconnect with stale heartbeats.- return fmt.Errorf("not connected")- }-- data, err := json.Marshal(msg)- if err != nil {- return fmt.Errorf("failed to marshal message: %w", err)- }-- select {- case c.sendCh <- data:- return nil- default:- return fmt.Errorf("send channel full")- }-}--// SendHeartbeat sends a heartbeat message-func (c *Client) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {- msg := protocol.HeartbeatMessage{- Message: protocol.NewMessage(protocol.TypeHeartbeat, auth.GenerateNonce()),- Metrics: metrics,- }- return c.Send(msg)-}--// SendCommandResult sends a command result-func (c *Client) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {- var dataBytes json.RawMessage- if data != nil {- var err error- dataBytes, err = json.Marshal(data)- if err != nil {- return fmt.Errorf("failed to marshal data: %w", err)- }- }-- msg := protocol.CommandResult{- Message: protocol.NewMessage(protocol.TypeCommandResult, auth.GenerateNonce()),- CommandID: commandID,- Success: success,- Data: dataBytes,- Error: errMsg,- Duration: duration.Milliseconds(),- }- return c.Send(msg)-}--// SendStream sends streaming data-func (c *Client) SendStream(channel string, data interface{}) error {- dataBytes, err := json.Marshal(data)- if err != nil {- return fmt.Errorf("failed to marshal data: %w", err)- }-- msg := protocol.StreamMessage{- Message: protocol.NewMessage(protocol.TypeStream, auth.GenerateNonce()),- Channel: channel,- Data: dataBytes,- }- return c.Send(msg)-}--// SendError sends an error message-func (c *Client) SendError(code, details string) error {- msg := protocol.ErrorMessage{- Message: protocol.NewMessage(protocol.TypeError, auth.GenerateNonce()),- Code: code,- Details: details,- }- return c.Send(msg)-}--// IsConnected returns the connection status-func (c *Client) IsConnected() bool {- c.mu.RLock()- defer c.mu.RUnlock()- return c.connected-}--// Close closes the WebSocket connection-func (c *Client) Close() error {- c.mu.Lock()- defer c.mu.Unlock()-- if c.conn != nil {- // Send close message- c.conn.WriteMessage(- websocket.CloseMessage,- websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),- )- c.conn.Close()- c.conn = nil- }-- c.connected = false- return nil-}--// Session returns the current session token-// Mode reports this transport as WS so consumers (UI, log lines) can-// distinguish from the polling fallback.-func (c *Client) Mode() transport.Mode { return transport.ModeWS }--// LastError returns the most recent connect or runloop error, or nil-// when healthy. Used by the transport manager to decide whether to fall-// back to polling — specifically, RSV1/handshake errors indicate a-// tunnel intermediary that won't ever let WS through and we shouldn't-// keep retrying the same dial.-func (c *Client) LastError() error {- c.mu.RLock()- defer c.mu.RUnlock()- return c.lastErr-}--// EverConnected reports whether the client has successfully completed a-// handshake at least once during this Run. False after several seconds-// is the strongest signal that WS won't ever work for this network.-func (c *Client) EverConnected() bool {- c.mu.RLock()- defer c.mu.RUnlock()- return c.everConnected-}--func (c *Client) Session() *auth.SessionToken {- return c.session-}diff --git a/agent/packaging/deb/build.sh b/agent/packaging/deb/build.shdeleted file mode 100644index 4faad166..00000000--- a/agent/packaging/deb/build.sh+++ /dev/null@@ -1,250 +0,0 @@-#!/bin/bash-# Build .deb package for ServerKit Agent-# Usage: ./build.sh <version> <architecture> <binary_path>-# Example: ./build.sh 1.0.0 amd64 ../../dist/serverkit-agent-linux-amd64--set -e--VERSION="${1:-1.0.0}"-ARCH="${2:-amd64}"-BINARY_PATH="${3:-../../dist/serverkit-agent-linux-$ARCH}"-PACKAGE_NAME="serverkit-agent"-MAINTAINER="ServerKit <[email protected]>"-DESCRIPTION="ServerKit Agent - Remote server management agent"--# Map Go arch to Debian arch-case "$ARCH" in- amd64) DEB_ARCH="amd64" ;;- arm64) DEB_ARCH="arm64" ;;- arm) DEB_ARCH="armhf" ;;- *) DEB_ARCH="$ARCH" ;;-esac--echo "Building .deb package..."-echo " Version: $VERSION"-echo " Architecture: $DEB_ARCH"-echo " Binary: $BINARY_PATH"--# Create build directory-BUILD_DIR="$(mktemp -d)"-PKG_DIR="$BUILD_DIR/${PACKAGE_NAME}_${VERSION}_${DEB_ARCH}"--# Create directory structure-mkdir -p "$PKG_DIR/DEBIAN"-mkdir -p "$PKG_DIR/usr/local/bin"-mkdir -p "$PKG_DIR/etc/serverkit-agent"-mkdir -p "$PKG_DIR/var/log/serverkit-agent"-mkdir -p "$PKG_DIR/lib/systemd/system"--# Copy binary-cp "$BINARY_PATH" "$PKG_DIR/usr/local/bin/serverkit-agent"-chmod 755 "$PKG_DIR/usr/local/bin/serverkit-agent"--# Create control file-cat > "$PKG_DIR/DEBIAN/control" << EOF-Package: $PACKAGE_NAME-Version: $VERSION-Section: admin-Priority: optional-Architecture: $DEB_ARCH-Maintainer: $MAINTAINER-Description: $DESCRIPTION- ServerKit Agent connects your server to a ServerKit control plane,- enabling remote Docker management, monitoring, and more.- .- Features:- - Docker container management- - System metrics collection- - Secure WebSocket communication- - Auto-reconnect with exponential backoff-Depends: ca-certificates-Suggests: docker-ce | docker.io-Homepage: https://github.com/jhd3197/ServerKit-EOF--# Create conffiles (list of config files that shouldn't be overwritten)-cat > "$PKG_DIR/DEBIAN/conffiles" << EOF-/etc/serverkit-agent/config.yaml-EOF--# Create systemd service file-cat > "$PKG_DIR/lib/systemd/system/serverkit-agent.service" << EOF-[Unit]-Description=ServerKit Agent-Documentation=https://github.com/jhd3197/ServerKit-After=network-online.target docker.service-Wants=network-online.target-Requires=docker.service--[Service]-Type=simple-User=serverkit-agent-Group=serverkit-agent-ExecStart=/usr/local/bin/serverkit-agent start-Restart=always-RestartSec=10-StandardOutput=journal-StandardError=journal-SyslogIdentifier=serverkit-agent--# Security hardening — run as a dedicated unprivileged account, matching the-# script installer (agent/scripts/install.sh). In this mode the agent cannot-# overwrite its own root-owned binary, so self-update is disabled and updates-# flow through the OS package manager (apt) instead — the signature-checked-# path. systemd/package-management handlers need root; if you require them,-# deliberately run as root or configure passwordless sudo for this account.-NoNewPrivileges=yes-ProtectSystem=strict-ProtectHome=yes-PrivateTmp=yes-ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent /var/lib/serverkit /var/serverkit-# `register` is usually run via sudo (as root), so the credential files it-# writes can end up root-owned and unreadable by this service account. Fix-# ownership at start regardless of how the operator registered. The leading-# '+' runs this step as root even though the service drops to User= above.-ExecStartPre=+/usr/bin/chown -R serverkit-agent:serverkit-agent /etc/serverkit-agent--[Install]-WantedBy=multi-user.target-EOF--# Create default config file-cat > "$PKG_DIR/etc/serverkit-agent/config.yaml" << EOF-# ServerKit Agent Configuration-# This file is created during installation.-# Run 'serverkit-agent register' to configure the agent.--server:- url: ""- reconnect_interval: 5s- max_reconnect_interval: 5m- ping_interval: 30s--agent:- id: ""- name: ""--features:- docker: true- metrics: true- logs: true- file_access: false- exec: false--metrics:- enabled: true- interval: 10s--docker:- socket: /var/run/docker.sock- timeout: 30s--logging:- level: info- file: /var/log/serverkit-agent/agent.log- max_size_mb: 100- max_backups: 5- max_age_days: 30- compress: true-EOF--# Create postinst script-cat > "$PKG_DIR/DEBIAN/postinst" << 'EOF'-#!/bin/bash-set -e--case "$1" in- configure)- # Create the dedicated, unprivileged service account (idempotent).- if ! getent passwd serverkit-agent >/dev/null; then- useradd --system --no-create-home --shell /usr/sbin/nologin serverkit-agent- fi-- # Let the agent reach the Docker socket without root.- if getent group docker >/dev/null; then- usermod -aG docker serverkit-agent || true- fi-- # State/data directories the agent writes to, owned by the service- # account. Also re-chown the config dir so an existing root-owned- # agent.key (e.g. from a previous root install, or `sudo register`)- # becomes readable by the unprivileged service after upgrade.- mkdir -p /var/lib/serverkit/apps /var/serverkit/apps /var/log/serverkit-agent- chown -R serverkit-agent:serverkit-agent \- /var/lib/serverkit /var/serverkit /var/log/serverkit-agent /etc/serverkit-agent 2>/dev/null || true-- # Reload systemd- systemctl daemon-reload-- # Enable service (but don't start - user needs to register first)- systemctl enable serverkit-agent.service || true-- echo ""- echo "ServerKit Agent installed successfully!"- echo ""- echo "To complete setup:"- echo " 1. Register the agent (runs as the service account):"- echo " sudo -u serverkit-agent serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"- echo ""- echo " 2. Start the service:"- echo " sudo systemctl start serverkit-agent"- echo ""- echo " 3. Check status:"- echo " sudo systemctl status serverkit-agent"- echo ""- ;;-esac--exit 0-EOF-chmod 755 "$PKG_DIR/DEBIAN/postinst"--# Create prerm script-cat > "$PKG_DIR/DEBIAN/prerm" << 'EOF'-#!/bin/bash-set -e--case "$1" in- remove|upgrade)- # Stop service- systemctl stop serverkit-agent.service || true- systemctl disable serverkit-agent.service || true- ;;-esac--exit 0-EOF-chmod 755 "$PKG_DIR/DEBIAN/prerm"--# Create postrm script-cat > "$PKG_DIR/DEBIAN/postrm" << 'EOF'-#!/bin/bash-set -e--case "$1" in- purge)- # Remove config and log directories- rm -rf /etc/serverkit-agent- rm -rf /var/log/serverkit-agent- ;;- remove)- # Reload systemd- systemctl daemon-reload || true- ;;-esac--exit 0-EOF-chmod 755 "$PKG_DIR/DEBIAN/postrm"--# Build the package-OUTPUT_DIR="${4:-./output}"-mkdir -p "$OUTPUT_DIR"-dpkg-deb --build --root-owner-group "$PKG_DIR" "$OUTPUT_DIR/${PACKAGE_NAME}_${VERSION}_${DEB_ARCH}.deb"--# Cleanup-rm -rf "$BUILD_DIR"--echo ""-echo "Package built successfully!"-echo "Output: $OUTPUT_DIR/${PACKAGE_NAME}_${VERSION}_${DEB_ARCH}.deb"diff --git a/agent/packaging/icons/generate_icons.py b/agent/packaging/icons/generate_icons.pydeleted file mode 100644index 1c326dfb..00000000--- a/agent/packaging/icons/generate_icons.py+++ /dev/null@@ -1,86 +0,0 @@-"""Generate ServerKit icon set from the brand SVG.--Outputs:- agent/internal/setupui/serverkit.ico — main app/installer icon (embedded into the exe)- agent/internal/tray/icons/connected.ico — tray (full color)- agent/internal/tray/icons/disconnected.ico — tray (yellow tint)- agent/internal/tray/icons/error.ico — tray (red tint)- agent/internal/tray/icons/stopped.ico — tray (gray)--Run from repo root:- python agent/packaging/icons/generate_icons.py-"""-from __future__ import annotations--import io-from pathlib import Path--import cairosvg-from PIL import Image, ImageEnhance--REPO = Path(__file__).resolve().parents[3]-SVG = REPO / "frontend" / "src" / "assets" / "ServerKitLogo.svg"-SETUPUI_DIR = REPO / "agent" / "internal" / "setupui"-TRAY_DIR = REPO / "agent" / "internal" / "tray" / "icons"--SETUPUI_DIR.mkdir(parents=True, exist_ok=True)-TRAY_DIR.mkdir(parents=True, exist_ok=True)--APP_SIZES = [16, 24, 32, 48, 64, 128, 256]-TRAY_SIZES = [16, 24, 32, 48, 64]---def render_png(size: int) -> Image.Image:- png_bytes = cairosvg.svg2png(- url=str(SVG), output_width=size, output_height=size- )- return Image.open(io.BytesIO(png_bytes)).convert("RGBA")---def tint(img: Image.Image, rgb: tuple[int, int, int], strength: float = 0.65) -> Image.Image:- """Apply a hue shift by blending non-transparent pixels toward `rgb`."""- base = img.copy()- overlay = Image.new("RGBA", base.size, rgb + (0,))- alpha = base.split()[3]- overlay.putalpha(alpha)- blended = Image.blend(base, overlay, strength)- blended.putalpha(alpha)- return blended---def desaturate(img: Image.Image) -> Image.Image:- enhancer = ImageEnhance.Color(img)- return enhancer.enhance(0.0)---def write_ico(images: list[Image.Image], out: Path) -> None:- primary = images[-1]- primary.save(out, format="ICO", sizes=[(im.width, im.height) for im in images])- print(f" wrote {out.relative_to(REPO)} ({len(images)} sizes)")---def main() -> None:- print("Rendering brand PNGs…")- app_pngs = [render_png(s) for s in APP_SIZES]- tray_pngs = [render_png(s) for s in TRAY_SIZES]-- print("Building serverkit.ico…")- write_ico(app_pngs, SETUPUI_DIR / "serverkit.ico")-- print("Building wizard header PNG…")- header = render_png(96)- header_path = SETUPUI_DIR / "serverkit_header.png"- header.save(header_path, format="PNG")- print(f" wrote {header_path.relative_to(REPO)}")-- print("Building tray icons…")- write_ico(tray_pngs, TRAY_DIR / "connected.ico")- write_ico([tint(p, (245, 158, 11)) for p in tray_pngs], TRAY_DIR / "disconnected.ico")- write_ico([tint(p, (220, 38, 38)) for p in tray_pngs], TRAY_DIR / "error.ico")- write_ico([desaturate(p) for p in tray_pngs], TRAY_DIR / "stopped.ico")-- print("Done.")---if __name__ == "__main__":- main()diff --git a/agent/packaging/msi/Product.wxs b/agent/packaging/msi/Product.wxsdeleted file mode 100644index 2b3cdd5e..00000000--- a/agent/packaging/msi/Product.wxs+++ /dev/null@@ -1,248 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!--- ServerKit Agent - Windows MSI Installer- Built with WiX Toolset v5-- Build instructions:- 1. Install WiX Toolset v5 globally (pin to 5.0.2).- 2. Install WixToolset.Util.wixext/5.0.2 globally.- 3. Run: wix build Product.wxs -ext WixToolset.Util.wixext -o serverkit-agent.msi -define Version=1.0.0-- See agent/packaging/msi/build.ps1 for the exact commands used in CI.--->-<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs"- xmlns:util="http://wixtoolset.org/schemas/v4/wxs/util">-- <!-- Product definition -->- <Package- Name="ServerKit Agent"- Manufacturer="ServerKit"- Version="$(var.Version)"- UpgradeCode="E8B7F3A2-4C5D-4E6F-8A9B-0C1D2E3F4A5B"- Scope="perMachine">-- <SummaryInformation- Description="ServerKit Agent - Remote server management agent"- Keywords="ServerKit,Agent,Docker,Management"- Manufacturer="ServerKit" />-- <!-- Branding: icon shown in Add/Remove Programs and on the install banner. -->- <Icon Id="ServerKitAgentIco" SourceFile="serverkit.ico" />- <Property Id="ARPPRODUCTICON" Value="ServerKitAgentIco" />- <Property Id="ARPHELPLINK" Value="https://github.com/jhd3197/ServerKit" />-- <!-- Upgrade handling.- AllowSameVersionUpgrades=yes lets a rebuild of the same version- replace itself cleanly — handy during fast iteration where every- dev build is "1.6.7" until tagged.- Schedule=afterInstallInitialize uninstalls the old product right- after the new install begins, before any files are written, so- file replacement and ServiceControl Remove run in the right order. -->- <MajorUpgrade- AllowSameVersionUpgrades="yes"- DowngradeErrorMessage="A newer version of [ProductName] is already installed."- Schedule="afterInstallInitialize" />-- <!-- Close any user-context serverkit-agent.exe processes (tray, wizard- window) before the install validates file usage. The Windows- service is handled by ServiceControl below; this covers the- non-service instances. Without this, a running tray pins the .exe- and Windows defers replacement to next reboot — which is why- users were seeing "installed but still old version" reports. -->- <util:CloseApplication- Id="CloseAgentExe"- Target="serverkit-agent.exe"- CloseMessage="yes"- TerminateProcess="5"- RebootPrompt="no"- ElevatedCloseMessage="yes" />-- <!-- Media -->- <MediaTemplate EmbedCab="yes" />-- <!-- Feature -->- <Feature Id="ProductFeature" Title="ServerKit Agent" Level="1">- <ComponentGroupRef Id="ProductComponents" />- <ComponentRef Id="ConfigComponent" />- <ComponentRef Id="LauncherScript" />- <ComponentRef Id="TrayAutoStart" />- <ComponentRef Id="StartMenuShortcuts" />- </Feature>--- </Package>-- <!-- Directory Structure -->- <Fragment>- <StandardDirectory Id="ProgramFiles64Folder">- <Directory Id="INSTALLFOLDER" Name="ServerKit Agent">- <Directory Id="LogsFolder" Name="logs" />- </Directory>- </StandardDirectory>-- <StandardDirectory Id="CommonAppDataFolder">- <Directory Id="ServerKitDataFolder" Name="ServerKit">- <Directory Id="AgentDataFolder" Name="Agent" />- </Directory>- </StandardDirectory>-- <StandardDirectory Id="ProgramMenuFolder">- <Directory Id="ServerKitStartMenuFolder" Name="ServerKit Agent" />- </StandardDirectory>- </Fragment>-- <!-- Components -->- <Fragment>- <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">- <Component Id="MainExecutable" Guid="A1B2C3D4-E5F6-7890-ABCD-EF1234567890">- <File Id="ServerKitAgentExe"- Source="serverkit-agent.exe"- KeyPath="yes" />- <!-- Windows Service. Start="auto" so the service auto-starts on- boot — once paired, the agent comes up automatically without- requiring the user to push "Start Agent" from the tray. Until- pairing, it loops in retry-without-config mode harmlessly. -->- <ServiceInstall- Id="ServiceInstall"- Name="ServerKitAgent"- DisplayName="ServerKit Agent"- Description="ServerKit Agent - Remote server management service"- Type="ownProcess"- Start="auto"- ErrorControl="normal"- Arguments="start">- <!-- Grant BUILTIN\Users start/stop/query rights on the service.- Without this the user-launched wizard and the user-context tray- can't issue `sc start ServerKitAgent` after pairing — every- post-pair start attempt would silently fail with access denied. -->- <util:PermissionEx- User="Users"- ServiceQueryStatus="yes"- ServiceQueryConfig="yes"- ServiceChangeConfig="yes"- ServiceStart="yes"- ServiceStop="yes"- ServiceInterrogate="yes"- ServiceUserDefinedControl="yes"- ServiceEnumerateDependents="yes" />- </ServiceInstall>- <ServiceControl- Id="ServiceControl"- Name="ServerKitAgent"- Stop="both"- Remove="uninstall"- Wait="yes" />- </Component>- </ComponentGroup>-- <!-- Configuration. The wizard runs as the user (asInvoker) but writes- credentials, config, and the pairing key under ProgramData. Grant- BUILTIN\Users modify access on the dir + config file (additive ACL,- leaves SYSTEM/Administrators untouched) so the post-pairing save- doesn't fail with "Access is denied". -->- <Component Id="ConfigComponent" Directory="AgentDataFolder" Guid="C3D4E5F6-A7B8-9012-CDEF-345678901234">- <CreateFolder>- <util:PermissionEx User="Users" GenericAll="yes" />- </CreateFolder>- <File Id="ConfigYaml" Source="config.yaml" KeyPath="yes">- <util:PermissionEx User="Users" GenericAll="yes" />- </File>- <RemoveFile Id="RemoveConfig" Name="config.yaml" On="uninstall" />- <RemoveFile Id="RemoveKey" Name="agent.key" On="uninstall" />- <RemoveFile Id="RemovePairingKey" Name="pairing.key" On="uninstall" />- <RemoveFolder Id="RemoveAgentDataFolder" On="uninstall" />- </Component>-- <!-- VBS launcher: shortcuts run wscript.exe + this script, which then spawns- the unsigned exe. The Microsoft-signed wscript host bypasses the- Explorer-launch SmartScreen reputation check that otherwise silently- kills the agent process on some Windows configurations. -->- <Component Id="LauncherScript" Directory="INSTALLFOLDER" Guid="F1B2A3C4-D5E6-4071-8A8B-9C0D1E2F3A4B">- <File Id="LauncherVbs" Source="launcher.vbs" KeyPath="yes" />- </Component>-- <!-- Auto-start the desktop app on user login. Goes through the launcher- for the same SmartScreen-bypass reason as the Start menu shortcut. -->- <Component Id="TrayAutoStart" Directory="INSTALLFOLDER" Guid="E5F6A7B8-C9D0-1234-EF01-567890123456">- <RegistryValue- Root="HKCU"- Key="Software\Microsoft\Windows\CurrentVersion\Run"- Name="ServerKitAgent"- Type="string"- Value="wscript.exe "[INSTALLFOLDER]launcher.vbs""- KeyPath="yes" />- </Component>-- <!-- Start Menu shortcut: single entry that opens the desktop app via the- signed wscript.exe host so SmartScreen doesn't silently reap us. -->- <Component Id="StartMenuShortcuts" Directory="ServerKitStartMenuFolder" Guid="B7C8D9E0-F1A2-3456-7890-ABCDEF123456">- <Shortcut Id="AppShortcut"- Name="ServerKit Agent"- Description="Pair and manage this ServerKit Agent"- Target="[System64Folder]wscript.exe"- Arguments=""[INSTALLFOLDER]launcher.vbs""- WorkingDirectory="INSTALLFOLDER"- Icon="ServerKitAgentIco"- IconIndex="0" />- <RemoveFolder Id="RemoveStartMenuFolder" On="uninstall" />- <RegistryValue- Root="HKCU"- Key="Software\ServerKit\Agent"- Name="StartMenuShortcuts"- Type="integer"- Value="1"- KeyPath="yes" />- </Component>- </Fragment>-- <!-- Launch the desktop app at the end of installation so the user is taken- straight into the pairing wizard. Impersonate so it inherits the user's- session, not the elevated installer. -->- <Fragment>- <CustomAction Id="LaunchApp"- FileRef="ServerKitAgentExe"- ExeCommand=""- Impersonate="yes"- Return="asyncNoWait" />-- <!-- Hard-stop the service before file replacement. ServiceControl- already stops the service during a clean upgrade, but if the- service is hung or in a weird state, an ungraceful sc.exe stop- is a faster, more reliable cleanup. Errors are ignored — if- the service doesn't exist (fresh install) or already stopped,- that's fine.- deferred + impersonate=no = runs in the elevated installer- context, which is what you need to control services. -->- <CustomAction Id="StopServiceForce"- Directory="INSTALLFOLDER"- ExeCommand='[System64Folder]sc.exe stop ServerKitAgent'- Execute="deferred"- Impersonate="no"- Return="ignore" />-- <!-- Final safety net: kill any serverkit-agent.exe still running- (the service if sc stop didn't take, the tray if CloseApplication- missed it, a ghosted wizard window). /T kills the process tree.- Must be deferred + elevated to reach SYSTEM-context children. -->- <CustomAction Id="TaskkillAgent"- Directory="INSTALLFOLDER"- ExeCommand='[System64Folder]taskkill.exe /F /IM serverkit-agent.exe /T'- Execute="deferred"- Impersonate="no"- Return="ignore" />-- <InstallExecuteSequence>- <!-- Order: stop service → kill any lingering processes → MSI- replaces files. Both run only on install/upgrade, not on- uninstall (where ServiceControl already handles teardown).- InstallFiles is the standard action that writes our exe. -->- <Custom Action="StopServiceForce" Before="InstallFiles"- Condition="NOT REMOVE" />- <Custom Action="TaskkillAgent" After="StopServiceForce"- Condition="NOT REMOVE" />- <Custom Action="LaunchApp" After="InstallFinalize"- Condition="NOT Installed AND NOT REMOVE" />- </InstallExecuteSequence>- </Fragment>--</Wix>diff --git a/agent/packaging/msi/build.ps1 b/agent/packaging/msi/build.ps1deleted file mode 100644index 915604da..00000000--- a/agent/packaging/msi/build.ps1+++ /dev/null@@ -1,160 +0,0 @@-# Build MSI installer for ServerKit Agent-# Usage: .\build.ps1 -Version "1.0.0" -BinaryPath "..\dist\serverkit-agent-windows-amd64.exe"--param(- [string]$Version = "1.0.0",- [string]$BinaryPath = "..\..\dist\serverkit-agent-windows-amd64.exe",- [string]$OutputDir = ".\output",- [ValidateSet("x64", "arm64")]- [string]$Arch = "x64"-)--$ErrorActionPreference = "Stop"--Write-Host "Building MSI installer..."-Write-Host " Version: $Version"-Write-Host " Arch: $Arch"-Write-Host " Binary: $BinaryPath"--# Check for WiX Toolset-$wixPath = Get-Command wix -ErrorAction SilentlyContinue-if (-not $wixPath) {- Write-Host "WiX Toolset not found. Please install it first:"- Write-Host " dotnet tool install --global wix --version 5.0.2"- Write-Host " or download from: https://wixtoolset.org/"- exit 1-}--# The Product.wxs file requires the WiX Util extension. Verify it is installed-# so the failure message is actionable instead of the raw WiX WIX0144 error.-$extensionList = wix extension list --global 2>&1-if (-not ($extensionList -match "WixToolset\.Util\.wixext")) {- Write-Host "WiX Util extension not found. Install it with:"- Write-Host " wix extension add --global WixToolset.Util.wixext/5.0.2"- exit 1-}--# Create build directory-$buildDir = New-Item -ItemType Directory -Force -Path "$env:TEMP\serverkit-msi-build-$(Get-Random)"-Write-Host "Build directory: $buildDir"--try {- # Copy binary- Copy-Item $BinaryPath "$buildDir\serverkit-agent.exe"-- # Copy brand icon (used by the installer banner / Add-Remove Programs entry)- $iconSource = Join-Path $PSScriptRoot "..\..\internal\setupui\serverkit.ico"- if (-not (Test-Path $iconSource)) {- Write-Host "Brand icon not found at $iconSource - run agent/packaging/icons/generate_icons.py first."- exit 1- }- Copy-Item $iconSource "$buildDir\serverkit.ico"-- # Copy SmartScreen-bypass launcher script (see launcher.vbs for rationale).- Copy-Item (Join-Path $PSScriptRoot "launcher.vbs") "$buildDir\launcher.vbs"-- # Create default config file- $configContent = @"-# ServerKit Agent Configuration-# This file is created during installation.-# Run 'serverkit-agent register' to configure the agent.--server:- url: ""- reconnect_interval: 5s- max_reconnect_interval: 5m- ping_interval: 30s--agent:- id: ""- name: ""--features:- docker: true- metrics: true- logs: true- file_access: false- exec: false--metrics:- enabled: true- interval: 10s--docker:- socket: npipe:////./pipe/docker_engine- timeout: 30s--logging:- level: info- file: C:\ProgramData\ServerKit\Agent\logs\agent.log- max_size_mb: 100- max_backups: 5- max_age_days: 30- compress: true--ipc:- enabled: true- port: 19780- address: 127.0.0.1-"@- $configContent | Out-File -FilePath "$buildDir\config.yaml" -Encoding UTF8-- # Create license file (RTF format required by WiX)- $licenseContent = @"-{\rtf1\ansi\deff0-{\fonttbl{\f0 Consolas;}}-\f0\fs20-MIT License\par-\par-Copyright (c) 2024 ServerKit\par-\par-Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:\par-\par-The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.\par-\par-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\par-}-"@- $licenseContent | Out-File -FilePath "$buildDir\License.rtf" -Encoding ASCII-- # Copy WiX source- Copy-Item "Product.wxs" "$buildDir\"-- # Create output directory (resolve to absolute path so it survives Push-Location)- New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null- $absOutputDir = (Resolve-Path $OutputDir).Path-- # Build MSI- Push-Location $buildDir- try {- Write-Host "Running WiX build..."- wix build -arch $Arch Product.wxs -ext WixToolset.Util.wixext -o "$absOutputDir\serverkit-agent-$Version-$Arch.msi" -define Version=$Version- if ($LASTEXITCODE -ne 0) {- throw "WiX build failed with exit code $LASTEXITCODE"- }- }- finally {- Pop-Location- }-- $msiPath = "$absOutputDir\serverkit-agent-$Version-$Arch.msi"- if (-not (Test-Path $msiPath)) {- throw "MSI output not found at $msiPath"- }-- Write-Host ""- Write-Host "MSI built successfully!"- Write-Host "Output: $msiPath"-}-finally {- # Cleanup- Remove-Item -Recurse -Force $buildDir -ErrorAction SilentlyContinue-}diff --git a/agent/packaging/msi/launcher.vbs b/agent/packaging/msi/launcher.vbsdeleted file mode 100644index 25b9b285..00000000--- a/agent/packaging/msi/launcher.vbs+++ /dev/null@@ -1,40 +0,0 @@-' ServerKit Agent launcher-'-' Why this exists: Windows SmartScreen silently terminates the unsigned-' serverkit-agent.exe when it is launched directly from Explorer / the-' Start menu / Search. Launching PowerShell or cmd from those same places-' works, because the SmartScreen reputation check applies to the *initial*-' user-clicked process, not its children.-'-' wscript.exe is signed by Microsoft and always trusted. By having the-' shortcut launch wscript with this script, the agent inherits a clean-' trust chain and starts reliably regardless of code-signing state.-'-' wscript runs without a console window, so there is no visible flash.--Option Explicit--Dim shell, fso, scriptPath, installDir, exePath, args, i--Set shell = CreateObject("WScript.Shell")-Set fso = CreateObject("Scripting.FileSystemObject")--scriptPath = WScript.ScriptFullName-installDir = fso.GetParentFolderName(scriptPath)-exePath = fso.BuildPath(installDir, "serverkit-agent.exe")--' Forward any arguments wscript was given (so e.g. --repair still works-' if a shortcut or another launcher passes flags through).-args = ""-If WScript.Arguments.Count > 0 Then- For i = 0 To WScript.Arguments.Count - 1- If args <> "" Then args = args & " "- args = args & """" & WScript.Arguments(i) & """"- Next-End If--If args = "" Then- shell.Run """" & exePath & """", 0, False-Else- shell.Run """" & exePath & """ " & args, 0, False-End Ifdiff --git a/agent/packaging/rpm/build.sh b/agent/packaging/rpm/build.shdeleted file mode 100644index e1196a3f..00000000--- a/agent/packaging/rpm/build.sh+++ /dev/null@@ -1,242 +0,0 @@-#!/bin/bash-# Build .rpm package for ServerKit Agent-# Usage: ./build.sh <version> <architecture> <binary_path> <output_dir>-# Example: ./build.sh 1.0.0 x86_64 ../../dist/serverkit-agent-linux-amd64 ./packages--set -e--VERSION="${1:-1.0.0}"-ARCH="${2:-x86_64}"-BINARY_PATH="${3:-../../dist/serverkit-agent-linux-amd64}"-PACKAGE_NAME="serverkit-agent"--# Convert paths to absolute before any cd commands-BINARY_PATH="$(cd "$(dirname "$BINARY_PATH")" && pwd)/$(basename "$BINARY_PATH")"-OUTPUT_DIR="${4:-./output}"-mkdir -p "$OUTPUT_DIR"-OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"--# Map Go arch to RPM arch-case "$ARCH" in- amd64) RPM_ARCH="x86_64" ;;- arm64) RPM_ARCH="aarch64" ;;- *) RPM_ARCH="$ARCH" ;;-esac--echo "Building .rpm package..."-echo " Version: $VERSION"-echo " Architecture: $RPM_ARCH"-echo " Binary: $BINARY_PATH"-echo " Output: $OUTPUT_DIR"--# Create build directory structure-BUILD_ROOT="$(mktemp -d)"-mkdir -p "$BUILD_ROOT"/{BUILD,RPMS,SOURCES,SPECS,SRPMS}--# Create source tarball-SOURCE_DIR="$BUILD_ROOT/SOURCES/serverkit-agent-$VERSION"-mkdir -p "$SOURCE_DIR"--# Copy binary-cp "$BINARY_PATH" "$SOURCE_DIR/serverkit-agent"--# Create systemd service file-cat > "$SOURCE_DIR/serverkit-agent.service" << EOF-[Unit]-Description=ServerKit Agent-Documentation=https://github.com/jhd3197/ServerKit-After=network-online.target docker.service-Wants=network-online.target-Requires=docker.service--[Service]-Type=simple-User=serverkit-agent-Group=serverkit-agent-ExecStart=/usr/local/bin/serverkit-agent start-Restart=always-RestartSec=10-StandardOutput=journal-StandardError=journal-SyslogIdentifier=serverkit-agent--# Security hardening — run as a dedicated unprivileged account, matching the-# script installer (agent/scripts/install.sh). In this mode the agent cannot-# overwrite its own root-owned binary, so self-update is disabled and updates-# flow through the OS package manager (dnf/yum) instead — the signature-checked-# path. systemd/package-management handlers need root; if you require them,-# deliberately run as root or configure passwordless sudo for this account.-NoNewPrivileges=yes-ProtectSystem=strict-ProtectHome=yes-PrivateTmp=yes-ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent /var/lib/serverkit /var/serverkit-# \`register\` is usually run via sudo (as root), so the credential files it-# writes can end up root-owned and unreadable by this service account. Fix-# ownership at start regardless of how the operator registered. The leading-# '+' runs this step as root even though the service drops to User= above.-ExecStartPre=+/usr/bin/chown -R serverkit-agent:serverkit-agent /etc/serverkit-agent--[Install]-WantedBy=multi-user.target-EOF--# Create default config file-cat > "$SOURCE_DIR/config.yaml" << EOF-# ServerKit Agent Configuration-# This file is created during installation.-# Run 'serverkit-agent register' to configure the agent.--server:- url: ""- reconnect_interval: 5s- max_reconnect_interval: 5m- ping_interval: 30s--agent:- id: ""- name: ""--features:- docker: true- metrics: true- logs: true- file_access: false- exec: false--metrics:- enabled: true- interval: 10s--docker:- socket: /var/run/docker.sock- timeout: 30s--logging:- level: info- file: /var/log/serverkit-agent/agent.log- max_size_mb: 100- max_backups: 5- max_age_days: 30- compress: true-EOF--# Create tarball-cd "$BUILD_ROOT/SOURCES"-tar -czvf "serverkit-agent-$VERSION.tar.gz" "serverkit-agent-$VERSION"-rm -rf "serverkit-agent-$VERSION"--# Create spec file-cat > "$BUILD_ROOT/SPECS/serverkit-agent.spec" << EOF-Name: serverkit-agent-Version: $VERSION-Release: 1%{?dist}-Summary: ServerKit Agent - Remote server management agent--License: MIT-URL: https://github.com/jhd3197/ServerKit-Source0: serverkit-agent-%{version}.tar.gz--Requires: ca-certificates--%description-ServerKit Agent connects your server to a ServerKit control plane,-enabling remote Docker management, monitoring, and more.--Features:-- Docker container management-- System metrics collection-- Secure WebSocket communication-- Auto-reconnect with exponential backoff--%prep-%setup -q--%install-rm -rf %{buildroot}--# Install binary-install -D -m 755 serverkit-agent %{buildroot}/usr/local/bin/serverkit-agent--# Install systemd service-install -D -m 644 serverkit-agent.service %{buildroot}/usr/lib/systemd/system/serverkit-agent.service--# Install config directory and default config-install -D -m 644 config.yaml %{buildroot}/etc/serverkit-agent/config.yaml--# Create log directory-install -d -m 755 %{buildroot}/var/log/serverkit-agent--%files-%attr(755, root, root) /usr/local/bin/serverkit-agent-%attr(644, root, root) /usr/lib/systemd/system/serverkit-agent.service-%config(noreplace) %attr(640, serverkit-agent, serverkit-agent) /etc/serverkit-agent/config.yaml-%dir %attr(750, serverkit-agent, serverkit-agent) /etc/serverkit-agent-%dir %attr(750, serverkit-agent, serverkit-agent) /var/log/serverkit-agent--%pre-# Create the dedicated, unprivileged service account before files are laid-# down so the %files ownership attrs resolve. Idempotent across upgrades.-getent group serverkit-agent >/dev/null || groupadd --system serverkit-agent-getent passwd serverkit-agent >/dev/null || \- useradd --system --gid serverkit-agent --no-create-home --shell /sbin/nologin serverkit-agent--%post-%systemd_post serverkit-agent.service--# Let the agent reach the Docker socket without root.-if getent group docker >/dev/null; then- usermod -aG docker serverkit-agent || true-fi--# State/data dirs the agent writes to, owned by the service account. Also-# re-chown the config dir so an existing root-owned agent.key (previous root-# install, or \`sudo register\`) becomes readable by the unprivileged service.-mkdir -p /var/lib/serverkit/apps /var/serverkit/apps /var/log/serverkit-agent-chown -R serverkit-agent:serverkit-agent \- /var/lib/serverkit /var/serverkit /var/log/serverkit-agent /etc/serverkit-agent 2>/dev/null || true--echo ""-echo "ServerKit Agent installed successfully!"-echo ""-echo "To complete setup:"-echo " 1. Register the agent (runs as the service account):"-echo " sudo -u serverkit-agent serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"-echo ""-echo " 2. Start the service:"-echo " sudo systemctl start serverkit-agent"-echo ""-echo " 3. Check status:"-echo " sudo systemctl status serverkit-agent"-echo ""--%preun-%systemd_preun serverkit-agent.service--%postun-%systemd_postun_with_restart serverkit-agent.service--if [ \$1 -eq 0 ]; then- # Complete uninstall - remove config and logs- rm -rf /etc/serverkit-agent 2>/dev/null || true- rm -rf /var/log/serverkit-agent 2>/dev/null || true-fi--%changelog-* $(date '+%a %b %d %Y') ServerKit <[email protected]> - $VERSION-1-- Release $VERSION-EOF--# Build the RPM (disable build-id for Go binaries, use --target for cross-arch)-rpmbuild --define "_topdir $BUILD_ROOT" --define "_build_id_links none" --target "$RPM_ARCH" -bb "$BUILD_ROOT/SPECS/serverkit-agent.spec"--# Copy output-cp "$BUILD_ROOT/RPMS/$RPM_ARCH"/*.rpm "$OUTPUT_DIR/"--# Cleanup-rm -rf "$BUILD_ROOT"--echo ""-echo "Package built successfully!"-echo "Output: $OUTPUT_DIR/"-ls -la "$OUTPUT_DIR"/*.rpmdiff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.godeleted file mode 100644index ae254bf6..00000000--- a/agent/pkg/protocol/messages.go+++ /dev/null@@ -1,427 +0,0 @@-package protocol--import (- "encoding/json"- "time"-)--// MessageType defines the type of message-type MessageType string--const (- // Authentication- TypeAuth MessageType = "auth"- TypeAuthOK MessageType = "auth_ok"- TypeAuthFail MessageType = "auth_fail"-- // Heartbeat- TypeHeartbeat MessageType = "heartbeat"- TypeHeartbeatAck MessageType = "heartbeat_ack"-- // Commands- TypeCommand MessageType = "command"- TypeCommandResult MessageType = "command_result"-- // Streaming- TypeSubscribe MessageType = "subscribe"- TypeUnsubscribe MessageType = "unsubscribe"- TypeStream MessageType = "stream"-- // Errors- TypeError MessageType = "error"-- // System- TypeSystemInfo MessageType = "system_info"-- // Capabilities — agent reports which feature surfaces it can drive- // (cron, docker, systemd, …) so the panel can gate target pickers- // without round-tripping each click.- TypeCapabilities MessageType = "capabilities"-- // Discovery- TypeDiscovery MessageType = "discovery"- TypeDiscoveryRequest MessageType = "discovery_request"-- // Credential Rotation- TypeCredentialUpdate MessageType = "credential_update"- TypeCredentialUpdateAck MessageType = "credential_update_ack"-)--// Message is the base message structure-type Message struct {- Type MessageType `json:"type"`- ID string `json:"id"`- Timestamp int64 `json:"timestamp"`- Signature string `json:"signature,omitempty"`-}--// NewMessage creates a new message with timestamp-func NewMessage(msgType MessageType, id string) Message {- return Message{- Type: msgType,- ID: id,- Timestamp: time.Now().UnixMilli(),- }-}--// AuthMessage is sent by agent to authenticate-type AuthMessage struct {- Message- AgentID string `json:"agent_id"`- APIKeyPrefix string `json:"api_key_prefix"`- Nonce string `json:"nonce,omitempty"` // Unique nonce for replay protection-}--// AuthResponse is sent by server after authentication-type AuthResponse struct {- Message- SessionToken string `json:"session_token,omitempty"`- Expires int64 `json:"expires,omitempty"`- Error string `json:"error,omitempty"`-}--// HeartbeatMessage is sent periodically by agent-type HeartbeatMessage struct {- Message- Metrics HeartbeatMetrics `json:"metrics"`-}--// HeartbeatMetrics contains basic system metrics-type HeartbeatMetrics struct {- CPUPercent float64 `json:"cpu_percent"`- MemoryPercent float64 `json:"memory_percent"`- DiskPercent float64 `json:"disk_percent"`- ContainerCount int `json:"container_count"`- ContainerRunning int `json:"container_running"`-}--// HeartbeatAck is sent by server to acknowledge heartbeat-type HeartbeatAck struct {- Message-}--// CommandMessage is sent by server to execute a command-type CommandMessage struct {- Message- Action string `json:"action"`- Params json.RawMessage `json:"params"`- Timeout int `json:"timeout,omitempty"` // milliseconds-}--// CommandResult is sent by agent after executing a command-type CommandResult struct {- Message- CommandID string `json:"command_id"`- Success bool `json:"success"`- Data json.RawMessage `json:"data,omitempty"`- Error string `json:"error,omitempty"`- Duration int64 `json:"duration"` // milliseconds-}--// SubscribeMessage requests subscription to a data stream-type SubscribeMessage struct {- Message- Channel string `json:"channel"`-}--// UnsubscribeMessage cancels a subscription-type UnsubscribeMessage struct {- Message- Channel string `json:"channel"`-}--// StreamMessage contains streaming data-type StreamMessage struct {- Message- Channel string `json:"channel"`- Data json.RawMessage `json:"data"`-}--// ErrorMessage represents an error-type ErrorMessage struct {- Message- Code string `json:"code"`- Details string `json:"details,omitempty"`-}--// SystemInfoMessage contains system information-type SystemInfoMessage struct {- Message- Info SystemInfo `json:"info"`-}--// Capabilities is a flat dict of feature → bool reported by the agent on-// connect. The panel uses this to gate target pickers: an agent shows up-// in the Cron page's picker only if Capabilities["cron"] is true.-//-// Format is intentionally a map[string]bool rather than a struct so new-// keys can be added on the agent side and ignored by older panels (and-// vice versa) without protocol breakage.-type Capabilities map[string]bool--// CapabilitiesMessage is sent by the agent to advertise which feature-// surfaces it can drive. Panel echo-saves this on the in-memory-// ConnectedAgent record.-type CapabilitiesMessage struct {- Message- Capabilities Capabilities `json:"capabilities"`- Platform string `json:"platform"` // "linux", "windows", "darwin"- Distro string `json:"distro,omitempty"` // "ubuntu", "debian", "rhel", ...- DistroVersion string `json:"distro_version,omitempty"` // "22.04"- // Runtimes is a name → version map for language runtimes the agent- // detected at startup ("python": "3.11.4", "node": "20.10.0").- // Missing keys mean "not installed"; an empty string value means- // "installed but the version probe failed." Forward-compatible —- // new keys just light up in the panel without protocol changes.- Runtimes map[string]string `json:"runtimes,omitempty"`- // AllowedPaths advertises the file-access roots the agent is willing- // to expose. Sent only when capabilities["files"] is true so the- // panel's file manager can render the available browse roots without- // guessing. Empty/missing => the panel must hide remote file features.- AllowedPaths []string `json:"allowed_paths,omitempty"`- // Sudo describes how the agent escalates privileges for handlers- // that need root (systemd, packages). Values: "root" (already root),- // "passwordless" (sudo -n works), "unavailable" (no escalation —- // privileged handlers will fail). Empty/missing means the panel- // should treat it as "unavailable" for safety.- Sudo string `json:"sudo,omitempty"`- // RuntimeManagers reports which version manager (if any) is- // installed for each runtime, e.g. {"python": "pyenv"} on Linux or- // {"python": "pyenv-win"} on Windows. Empty/missing key means no- // manager installed; the panel can offer the bootstrap action.- RuntimeManagers map[string]string `json:"runtime_managers,omitempty"`- // SystemdJSON indicates whether `systemctl --output=json` is- // supported (systemd >= 244). When false, list_units falls back to- // parsing the plain --no-legend table.- SystemdJSON bool `json:"systemd_json,omitempty"`- // ProbedAt is the unix milliseconds timestamp when the capabilities- // payload was computed. Lets the panel distinguish a fresh re-probe- // from a cached set replayed on reconnect.- ProbedAt int64 `json:"probed_at,omitempty"`-}--// SystemInfo contains detailed system information-type SystemInfo struct {- Hostname string `json:"hostname"`- OS string `json:"os"`- OSVersion string `json:"os_version"`- Platform string `json:"platform,omitempty"`- Architecture string `json:"architecture"`- CPUModel string `json:"cpu_model,omitempty"`- CPUCores int `json:"cpu_cores"`- TotalMemory uint64 `json:"total_memory"`- TotalDisk uint64 `json:"total_disk"`- DockerVersion string `json:"docker_version,omitempty"`- AgentVersion string `json:"agent_version"`-}--// Command actions-const (- // Docker container actions- ActionDockerContainerList = "docker:container:list"- ActionDockerContainerInspect = "docker:container:inspect"- ActionDockerContainerCreate = "docker:container:create"- ActionDockerContainerStart = "docker:container:start"- ActionDockerContainerStop = "docker:container:stop"- ActionDockerContainerRestart = "docker:container:restart"- ActionDockerContainerRemove = "docker:container:remove"- ActionDockerContainerLogs = "docker:container:logs"- ActionDockerContainerStats = "docker:container:stats"- ActionDockerContainerExec = "docker:container:exec"-- // Docker image actions- ActionDockerImageList = "docker:image:list"- ActionDockerImagePull = "docker:image:pull"- ActionDockerImageRemove = "docker:image:remove"- ActionDockerImageBuild = "docker:image:build"-- // Docker volume actions- ActionDockerVolumeList = "docker:volume:list"- ActionDockerVolumeCreate = "docker:volume:create"- ActionDockerVolumeRemove = "docker:volume:remove"-- // Docker network actions- ActionDockerNetworkList = "docker:network:list"- ActionDockerNetworkCreate = "docker:network:create"- ActionDockerNetworkRemove = "docker:network:remove"-- // Docker compose actions- ActionDockerComposeList = "docker:compose:list"- ActionDockerComposePs = "docker:compose:ps"- ActionDockerComposeUp = "docker:compose:up"- ActionDockerComposeDown = "docker:compose:down"- ActionDockerComposeLogs = "docker:compose:logs"- ActionDockerComposeRestart = "docker:compose:restart"- ActionDockerComposePull = "docker:compose:pull"-- // System actions- ActionSystemMetrics = "system:metrics"- ActionSystemInfo = "system:info"- ActionSystemProcesses = "system:processes"- ActionSystemExec = "system:exec"-- // Package management actions — Phase 4 primitives the workflow- // engine sequences for "install Docker", "install LAMP" templates.- // Linux-only; the agent picks the right manager (apt/dnf/apk/…)- // based on what's on PATH. Calls are idempotent — installing an- // already-installed package is a no-op success.- //- // Install/Upgrade are long-running and stream progress on the- // returned job channel ("job:<id>") rather than blocking — the- // command result returns {job_id, channel} immediately.- ActionPackagesInstall = "packages:install"- ActionPackagesRemove = "packages:remove"- ActionPackagesListInstalled = "packages:list_installed"- ActionPackagesUpdateCache = "packages:update_cache"- // ActionPackagesInstallAsync is the streaming variant of- // ActionPackagesInstall: takes names[] (and/or a single name),- // returns {job_id, channel} immediately, and emits per-line install- // progress on the channel. Use this for the Packages tab UI; the- // synchronous variant is retained for the workflow engine's- // agent_command nodes which expect a structured result.- ActionPackagesInstallAsync = "packages:install_async"- ActionPackagesUpgrade = "packages:upgrade"- ActionPackagesSearch = "packages:search"- ActionPackagesInfo = "packages:info"-- // Systemd unit actions. Linux-only and require systemd as PID 1- // (the capability probe already gates this).- ActionSystemdStatus = "systemd:status"- ActionSystemdStart = "systemd:start"- ActionSystemdStop = "systemd:stop"- ActionSystemdRestart = "systemd:restart"- ActionSystemdEnable = "systemd:enable"- ActionSystemdDisable = "systemd:disable"- ActionSystemdDaemonReload = "systemd:daemon_reload"- ActionSystemdListUnits = "systemd:list_units"- ActionSystemdLogs = "systemd:logs"- ActionSystemdLogsFollow = "systemd:logs_follow"-- // Runtime version managers (Phase 5). Currently scoped to Python- // via pyenv on Linux and pyenv-win on Windows. Install/Bootstrap- // stream on a job channel like packages.- ActionRuntimesList = "runtimes:list"- ActionRuntimesPyenvBootstrap = "runtimes:pyenv:bootstrap"- ActionRuntimesPythonInstalled = "runtimes:python:installed"- ActionRuntimesPythonAvailable = "runtimes:python:available"- ActionRuntimesPythonInstall = "runtimes:python:install"- ActionRuntimesPythonUninstall = "runtimes:python:uninstall"- ActionRuntimesPythonSetGlobal = "runtimes:python:set_global"- ActionRuntimesPythonSetLocal = "runtimes:python:set_local"- ActionRuntimesPythonCurrent = "runtimes:python:current"-- // Cron actions — manage entries in the agent host's user crontab.- // Linux-only; non-Linux agents return an "unsupported" error.- ActionCronStatus = "cron:status"- ActionCronList = "cron:list"- ActionCronAdd = "cron:add"- ActionCronRemove = "cron:remove"- ActionCronToggle = "cron:toggle"-- // Cloudflared actions — manage Cloudflare named tunnels via the- // cloudflared CLI. The agent never stores Cloudflare API tokens;- // the user authenticates once on the host with- // `cloudflared tunnel login` (approach A from the design notes).- // Status reflects "is binary installed AND has cert.pem".- ActionCloudflaredStatus = "cloudflared:status"- ActionCloudflaredLogin = "cloudflared:login"- ActionCloudflaredTunnelList = "cloudflared:tunnel:list"- ActionCloudflaredTunnelCreate = "cloudflared:tunnel:create"- ActionCloudflaredTunnelRoute = "cloudflared:tunnel:route"- ActionCloudflaredTunnelDelete = "cloudflared:tunnel:delete"-- // WireGuard actions — manage a WireGuard interface so the panel can- // pair two agents into a NAT-traversing tunnel (edge ↔ private). The- // agent generates its keypair locally and returns ONLY the public- // key; private keys never reach the panel. Linux-only until the- // userspace backend (roadmap #6) lands. See- // docs/REMOTE_ACCESS_ROADMAP.md.- ActionWireguardKeygen = "wireguard:keygen"- ActionWireguardInterfaceUp = "wireguard:interface:up"- ActionWireguardInterfaceDown = "wireguard:interface:down"- ActionWireguardPeerSet = "wireguard:peer:set"- ActionWireguardPeerRemove = "wireguard:peer:remove"- ActionWireguardStatus = "wireguard:status"- // wireguard:forward starts a TCP forwarder on the private peer so a- // connection arriving over the tunnel reaches the real local service- // (roadmap #13). Essential for the userspace/netstack backend.- ActionWireguardForward = "wireguard:forward"- ActionWireguardUnforward = "wireguard:unforward"-- // Firewall actions — minimal host-firewall control so the tunnel- // broker can open the edge's inbound WireGuard UDP port (#10).- // Linux-only (ufw / firewalld / iptables).- ActionFirewallAllowPort = "firewall:allow_port"- ActionFirewallDenyPort = "firewall:deny_port"-- // File actions- ActionFileRead = "file:read"- ActionFileWrite = "file:write"- ActionFileList = "file:list"-- // Terminal/PTY actions- ActionTerminalCreate = "terminal:create"- ActionTerminalInput = "terminal:input"- ActionTerminalResize = "terminal:resize"- ActionTerminalClose = "terminal:close"-- // Agent actions- ActionAgentUpdate = "agent:update"- ActionAgentRecapabilities = "agent:recapabilities"-- // GUI / desktop capture actions. These are the agent-side primitives- // that panel extensions (e.g. serverkit-gui) call into. Implementation- // lives in agent/internal/gui — kept minimal so plugins composing- // remote-desktop / synthetic-UI features don't have to fork the- // agent.- ActionGUICapabilities = "gui:capabilities"- ActionGUIScreenshot = "gui:screenshot"-)--// Stream channels-const (- ChannelMetrics = "metrics"- ChannelContainerLogs = "container:%s:logs"- ChannelContainerStats = "container:%s:stats"- ChannelTerminal = "terminal:%s"- // ChannelSystemdLogs streams journalctl -fu <unit> events. Lifecycle- // mirrors ChannelContainerLogs: subscribe starts the follow, unsubscribe- // (or socket close) stops it.- ChannelSystemdLogs = "systemd:%s:logs"- // ChannelJob is used for long-running operations (package install,- // image build, pyenv install) that return {job_id, channel} from- // their command result and stream progress events on the channel.- // Late subscribers receive a replay of the last N buffered events.- ChannelJob = "job:%s"-)--// CredentialUpdateMessage is sent by server to rotate credentials.-//-// HMACSig is computed by the panel as-//-// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",-// current_api_secret))-//-// where current_api_secret is the agent's secret prior to rotation.-// The agent recomputes this with its own current secret and rejects-// the rotation if they don't match. This prevents a panel session-// hijack from silently rotating an agent's credential set to ones an-// attacker controls — the existing socket-level auth is necessary but-// not sufficient because the panel has many ways to issue messages-// downward and we want defence-in-depth specifically on the rotation-// path.-type CredentialUpdateMessage struct {- Message- RotationID string `json:"rotation_id"`- APIKey string `json:"api_key"`- APISecret string `json:"api_secret"`- HMACSig string `json:"hmac_sig"`-}--// CredentialUpdateAck is sent by agent after updating credentials-type CredentialUpdateAck struct {- Message- RotationID string `json:"rotation_id"`- Success bool `json:"success"`- Error string `json:"error,omitempty"`-}diff --git a/agent/scripts/build.ps1 b/agent/scripts/build.ps1deleted file mode 100644index 729dd1ec..00000000--- a/agent/scripts/build.ps1+++ /dev/null@@ -1,87 +0,0 @@-# Build script for ServerKit Agent (Windows PowerShell)-# Cross-compiles for multiple platforms--param(- [string]$Version = "",- [string]$Target = "all"-)--$ErrorActionPreference = "Stop"--# Get version from git or use default-if ($Version -eq "") {- try {- $Version = git describe --tags --always --dirty 2>$null- } catch {- $Version = "dev"- }-}--$BuildTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")-try {- $GitCommit = git rev-parse --short HEAD 2>$null-} catch {- $GitCommit = "unknown"-}--# Build flags-$LdFlags = "-s -w -X main.Version=$Version -X main.BuildTime=$BuildTime -X main.GitCommit=$GitCommit"--# Output directory-$DistDir = "dist"-if (-not (Test-Path $DistDir)) {- New-Item -ItemType Directory -Path $DistDir | Out-Null-}--Write-Host "Building ServerKit Agent $Version" -ForegroundColor Cyan-Write-Host "Build time: $BuildTime"-Write-Host "Git commit: $GitCommit"-Write-Host ""--# Build targets-$Targets = @(- @{GOOS="linux"; GOARCH="amd64"},- @{GOOS="linux"; GOARCH="arm64"},- @{GOOS="linux"; GOARCH="arm"},- @{GOOS="windows"; GOARCH="amd64"},- @{GOOS="windows"; GOARCH="arm64"},- @{GOOS="darwin"; GOARCH="amd64"},- @{GOOS="darwin"; GOARCH="arm64"}-)--# Filter targets if specific one requested-if ($Target -ne "all") {- $parts = $Target.Split("/")- $Targets = @(@{GOOS=$parts[0]; GOARCH=$parts[1]})-}--foreach ($t in $Targets) {- $goos = $t.GOOS- $goarch = $t.GOARCH-- $outputName = "serverkit-agent-$Version-$goos-$goarch"- if ($goos -eq "windows") {- $outputName = "$outputName.exe"- }-- Write-Host "Building $goos/$goarch..." -ForegroundColor Yellow-- $env:CGO_ENABLED = "0"- $env:GOOS = $goos- $env:GOARCH = $goarch-- go build -ldflags $LdFlags -o "$DistDir/$outputName" ./cmd/agent-- if ($LASTEXITCODE -ne 0) {- Write-Host "Build failed for $goos/$goarch" -ForegroundColor Red- exit 1- }-- # Calculate checksum- $hash = Get-FileHash -Path "$DistDir/$outputName" -Algorithm SHA256- Add-Content -Path "$DistDir/checksums.txt" -Value "$($hash.Hash.ToLower()) $outputName"-}--Write-Host ""-Write-Host "Build complete! Binaries in $DistDir/" -ForegroundColor Green-Get-ChildItem $DistDirdiff --git a/agent/scripts/build.sh b/agent/scripts/build.shdeleted file mode 100644index fdaabf05..00000000--- a/agent/scripts/build.sh+++ /dev/null@@ -1,60 +0,0 @@-#!/bin/bash--# Build script for ServerKit Agent-# Cross-compiles for multiple platforms--set -e--# Get version from git or use default-VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}-BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")-GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")--# Build flags-LDFLAGS="-s -w -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME} -X main.GitCommit=${GIT_COMMIT}"--# Output directory-DIST_DIR="dist"-mkdir -p ${DIST_DIR}--echo "Building ServerKit Agent ${VERSION}"-echo "Build time: ${BUILD_TIME}"-echo "Git commit: ${GIT_COMMIT}"-echo ""--# Build targets-TARGETS=(- "linux/amd64"- "linux/arm64"- "linux/arm"- "windows/amd64"- "windows/arm64"- "darwin/amd64"- "darwin/arm64"-)--for target in "${TARGETS[@]}"; do- GOOS=${target%/*}- GOARCH=${target#*/}-- OUTPUT_NAME="serverkit-agent-${VERSION}-${GOOS}-${GOARCH}"- if [ "${GOOS}" == "windows" ]; then- OUTPUT_NAME="${OUTPUT_NAME}.exe"- fi-- echo "Building ${GOOS}/${GOARCH}..."-- CGO_ENABLED=0 GOOS=${GOOS} GOARCH=${GOARCH} go build \- -ldflags "${LDFLAGS}" \- -o "${DIST_DIR}/${OUTPUT_NAME}" \- ./cmd/agent-- # Calculate checksum- if command -v sha256sum &> /dev/null; then- sha256sum "${DIST_DIR}/${OUTPUT_NAME}" >> "${DIST_DIR}/checksums.txt"- fi-done--echo ""-echo "Build complete! Binaries in ${DIST_DIR}/"-ls -la ${DIST_DIR}/diff --git a/agent/scripts/install.ps1 b/agent/scripts/install.ps1deleted file mode 100644index f3cf5e10..00000000--- a/agent/scripts/install.ps1+++ /dev/null@@ -1,242 +0,0 @@-#Requires -RunAsAdministrator-#-# ServerKit Agent Installation Script for Windows-# Usage: irm https://your-serverkit.com/install.ps1 | iex; Install-ServerKitAgent -Token "sk_reg_xxx" -Server "https://..."-#--function Install-ServerKitAgent {- [CmdletBinding()]- param(- [Parameter(Mandatory=$false)]- [string]$Token = "",-- [Parameter(Mandatory=$true)]- [string]$Server,-- [Parameter(Mandatory=$false)]- [string]$Name = "",-- [Parameter(Mandatory=$false)]- [string]$DownloadUrl = ""- )-- $ErrorActionPreference = "Stop"-- # Allow the token to come from the environment so it doesn't have to appear- # on the command line (visible to admins via Get-CimInstance Win32_Process).- # An explicit -Token wins.- if (-not $Token) { $Token = $env:SERVERKIT_REGISTRATION_TOKEN }- if (-not $Token) { $Token = $env:SERVERKIT_TOKEN }- if (-not $Token) {- throw "Registration token required: pass -Token or set SERVERKIT_REGISTRATION_TOKEN"- }-- # Configuration- $InstallDir = "$env:ProgramFiles\ServerKit Agent"- $ConfigDir = "$env:ProgramData\ServerKit\Agent"- $LogDir = "$env:ProgramData\ServerKit\Agent\logs"- $ServiceName = "ServerKitAgent"-- function Write-Info { param([string]$Message) Write-Host "[INFO] $Message" -ForegroundColor Cyan }- function Write-Success { param([string]$Message) Write-Host "[SUCCESS] $Message" -ForegroundColor Green }- function Write-Warn { param([string]$Message) Write-Host "[WARN] $Message" -ForegroundColor Yellow }- function Write-Err { param([string]$Message) Write-Host "[ERROR] $Message" -ForegroundColor Red }-- Write-Host ""- Write-Host "╔══════════════════════════════════════════╗" -ForegroundColor Green- Write-Host "║ ServerKit Agent Installation ║" -ForegroundColor Green- Write-Host "╚══════════════════════════════════════════╝" -ForegroundColor Green- Write-Host ""-- # Detect architecture- $Arch = if ([Environment]::Is64BitOperatingSystem) { "amd64" } else { "386" }- Write-Info "Detected architecture: windows/$Arch"-- # Create directories- Write-Info "Creating directories..."- New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null- New-Item -ItemType Directory -Path $ConfigDir -Force | Out-Null- New-Item -ItemType Directory -Path $LogDir -Force | Out-Null-- # Stop existing service if running- $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue- if ($service -and $service.Status -eq "Running") {- Write-Info "Stopping existing agent service..."- Stop-Service -Name $ServiceName -Force- Start-Sleep -Seconds 2- }-- # Construct download URL- if ([string]::IsNullOrEmpty($DownloadUrl)) {- $DownloadUrl = "$Server/api/v1/servers/agent/download/windows/$Arch"- }-- # Download agent- Write-Info "Downloading agent from $DownloadUrl..."- $AgentPath = "$InstallDir\serverkit-agent.exe"- try {- [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12- Invoke-WebRequest -Uri $DownloadUrl -OutFile $AgentPath -UseBasicParsing- } catch {- Write-Err "Failed to download agent: $_"- throw- }-- # Verify download- if (-not (Test-Path $AgentPath)) {- Write-Err "Agent binary not found after download"- throw "Download failed"- }-- Write-Success "Agent downloaded successfully"-- # Register with ServerKit- Write-Info "Registering agent with ServerKit..."- $RegisterArgs = @("register", "--server", $Server)- if (-not [string]::IsNullOrEmpty($Name)) {- $RegisterArgs += @("--name", $Name)- }-- # Pass the token via the environment, not -ArgumentList, so it isn't exposed- # on the child process command line. Start-Process inherits this session's- # environment; clear it again afterward.- $env:SERVERKIT_REGISTRATION_TOKEN = $Token- try {- $process = Start-Process -FilePath $AgentPath -ArgumentList $RegisterArgs -Wait -PassThru -NoNewWindow- } finally {- Remove-Item Env:\SERVERKIT_REGISTRATION_TOKEN -ErrorAction SilentlyContinue- }- if ($process.ExitCode -ne 0) {- Write-Err "Registration failed with exit code $($process.ExitCode)"- throw "Registration failed"- }-- Write-Success "Registration successful"-- # Install as Windows Service- Write-Info "Installing Windows service..."-- # Remove existing service if present- if ($service) {- Write-Info "Removing existing service..."- sc.exe delete $ServiceName | Out-Null- Start-Sleep -Seconds 2- }-- # Create service using sc.exe- $binPath = "`"$AgentPath`" start"- $result = sc.exe create $ServiceName binPath= $binPath start= auto displayname= "ServerKit Agent"- if ($LASTEXITCODE -ne 0) {- Write-Err "Failed to create service"- throw "Service creation failed"- }-- # Set service description- sc.exe description $ServiceName "ServerKit Agent - Remote server management agent" | Out-Null-- # Configure service recovery (restart on failure)- sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/10000/restart/30000 | Out-Null-- Write-Success "Service installed"-- # Configure firewall (optional)- Write-Info "Configuring Windows Firewall..."- try {- $firewallRule = Get-NetFirewallRule -DisplayName "ServerKit Agent" -ErrorAction SilentlyContinue- if (-not $firewallRule) {- New-NetFirewallRule -DisplayName "ServerKit Agent" `- -Direction Outbound `- -Action Allow `- -Program $AgentPath `- -Description "Allow ServerKit Agent outbound connections" | Out-Null- Write-Success "Firewall rule created"- } else {- Write-Info "Firewall rule already exists"- }- } catch {- Write-Warn "Could not configure firewall: $_"- }-- # Start service- Write-Info "Starting agent service..."- Start-Service -Name $ServiceName- Start-Sleep -Seconds 3-- $service = Get-Service -Name $ServiceName- if ($service.Status -eq "Running") {- Write-Success "Agent is running"- } else {- Write-Err "Agent failed to start"- Get-EventLog -LogName Application -Source $ServiceName -Newest 10 -ErrorAction SilentlyContinue | Format-List- throw "Agent failed to start"- }-- # Add to PATH- $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")- if ($currentPath -notlike "*$InstallDir*") {- Write-Info "Adding agent to system PATH..."- [Environment]::SetEnvironmentVariable("Path", "$currentPath;$InstallDir", "Machine")- }-- Write-Host ""- Write-Success "Installation complete!"- Write-Host ""- Write-Host "Agent Status: Get-Service $ServiceName"- Write-Host "View Logs: Get-Content '$LogDir\agent.log' -Tail 50"- Write-Host "Config File: $ConfigDir\config.yaml"- Write-Host "Uninstall: Uninstall-ServerKitAgent"- Write-Host ""-}--function Uninstall-ServerKitAgent {- [CmdletBinding()]- param()-- $ErrorActionPreference = "Stop"-- $InstallDir = "$env:ProgramFiles\ServerKit Agent"- $ConfigDir = "$env:ProgramData\ServerKit\Agent"- $ServiceName = "ServerKitAgent"-- Write-Host "Uninstalling ServerKit Agent..." -ForegroundColor Yellow-- # Stop and remove service- $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue- if ($service) {- if ($service.Status -eq "Running") {- Stop-Service -Name $ServiceName -Force- Start-Sleep -Seconds 2- }- sc.exe delete $ServiceName | Out-Null- Write-Host "Service removed" -ForegroundColor Green- }-- # Remove firewall rule- Remove-NetFirewallRule -DisplayName "ServerKit Agent" -ErrorAction SilentlyContinue-- # Remove installation directory- if (Test-Path $InstallDir) {- Remove-Item -Path $InstallDir -Recurse -Force- Write-Host "Installation directory removed" -ForegroundColor Green- }-- # Ask about config removal- $removeConfig = Read-Host "Remove configuration and logs? (y/N)"- if ($removeConfig -eq "y" -or $removeConfig -eq "Y") {- if (Test-Path $ConfigDir) {- Remove-Item -Path $ConfigDir -Recurse -Force- Write-Host "Configuration removed" -ForegroundColor Green- }- }-- # Remove from PATH- $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")- $newPath = ($currentPath.Split(';') | Where-Object { $_ -ne $InstallDir }) -join ';'- [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")-- Write-Host ""- Write-Host "ServerKit Agent has been uninstalled" -ForegroundColor Green-}--# Export functions-Export-ModuleMember -Function Install-ServerKitAgent, Uninstall-ServerKitAgentdiff --git a/agent/scripts/install.sh b/agent/scripts/install.shdeleted file mode 100644index f3569d3e..00000000--- a/agent/scripts/install.sh+++ /dev/null@@ -1,318 +0,0 @@-#!/bin/bash-#-# ServerKit Agent Installation Script-# Usage: curl -fsSL https://your-serverkit.com/install.sh | sudo bash -s -- --token "sk_reg_xxx"-#--set -e--# Colors-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-NC='\033[0m' # No Color--# Default values-INSTALL_DIR="/usr/local/bin"-CONFIG_DIR="/etc/serverkit-agent"-LOG_DIR="/var/log/serverkit-agent"-SERVICE_USER="serverkit-agent"-DOWNLOAD_URL="" # Will be set by ServerKit server-TOKEN=""-SERVER_URL=""-NAME=""--# Parse arguments-while [[ $# -gt 0 ]]; do- case $1 in- --token|-t)- TOKEN="$2"- shift 2- ;;- --server|-s)- SERVER_URL="$2"- shift 2- ;;- --name|-n)- NAME="$2"- shift 2- ;;- --download-url)- DOWNLOAD_URL="$2"- shift 2- ;;- --help|-h)- echo "ServerKit Agent Installer"- echo ""- echo "Usage: $0 [options]"- echo ""- echo "Options:"- echo " --token, -t TOKEN Registration token (required)"- echo " --server, -s URL ServerKit server URL (required)"- echo " --name, -n NAME Server display name (optional)"- echo " --download-url URL Custom download URL (optional)"- echo " --help, -h Show this help"- exit 0- ;;- *)- echo "Unknown option: $1"- exit 1- ;;- esac-done--# Allow the token / server URL to come from the environment. This lets callers-# avoid putting the token on the `curl ... | sudo bash -s -- --token <token>`-# line, which would otherwise land in shell history. An explicit --token wins.-TOKEN="${TOKEN:-${SERVERKIT_REGISTRATION_TOKEN:-$SERVERKIT_TOKEN}}"-SERVER_URL="${SERVER_URL:-$SERVERKIT_SERVER_URL}"--# Validate required arguments-if [ -z "$TOKEN" ]; then- echo -e "${RED}Error: Registration token is required${NC}"- echo "Usage: $0 --token TOKEN --server URL (or set SERVERKIT_REGISTRATION_TOKEN)"- exit 1-fi--if [ -z "$SERVER_URL" ]; then- echo -e "${RED}Error: Server URL is required${NC}"- echo "Usage: $0 --token TOKEN --server URL"- exit 1-fi--# Functions-log_info() {- echo -e "${BLUE}[INFO]${NC} $1"-}--log_success() {- echo -e "${GREEN}[SUCCESS]${NC} $1"-}--log_warn() {- echo -e "${YELLOW}[WARN]${NC} $1"-}--log_error() {- echo -e "${RED}[ERROR]${NC} $1"-}--# Check if running as root-check_root() {- if [ "$EUID" -ne 0 ]; then- log_error "This script must be run as root"- exit 1- fi-}--# Detect OS and architecture-detect_platform() {- OS=$(uname -s | tr '[:upper:]' '[:lower:]')- ARCH=$(uname -m)-- case $ARCH in- x86_64|amd64)- ARCH="amd64"- ;;- aarch64|arm64)- ARCH="arm64"- ;;- armv7l|armhf)- ARCH="arm"- ;;- *)- log_error "Unsupported architecture: $ARCH"- exit 1- ;;- esac-- log_info "Detected platform: $OS/$ARCH"-}--# Detect init system-detect_init_system() {- if [ -d /run/systemd/system ]; then- INIT_SYSTEM="systemd"- elif [ -f /etc/init.d/cron ] && [ ! -d /run/systemd/system ]; then- INIT_SYSTEM="sysvinit"- else- INIT_SYSTEM="unknown"- fi- log_info "Init system: $INIT_SYSTEM"-}--# Create service user-create_user() {- if id "$SERVICE_USER" &>/dev/null; then- log_info "Service user '$SERVICE_USER' already exists"- else- log_info "Creating service user '$SERVICE_USER'..."- useradd --system --no-create-home --shell /bin/false "$SERVICE_USER"- fi-- # Add user to docker group if it exists- if getent group docker > /dev/null; then- usermod -aG docker "$SERVICE_USER"- log_info "Added $SERVICE_USER to docker group"- fi-}--# Download the agent binary-download_agent() {- if [ -z "$DOWNLOAD_URL" ]; then- # Construct download URL from server- DOWNLOAD_URL="${SERVER_URL}/api/v1/servers/agent/download/${OS}/${ARCH}"- fi-- log_info "Downloading agent from $DOWNLOAD_URL..."-- # Try curl first, then wget- if command -v curl &> /dev/null; then- curl -fsSL -o /tmp/serverkit-agent "$DOWNLOAD_URL"- elif command -v wget &> /dev/null; then- wget -q -O /tmp/serverkit-agent "$DOWNLOAD_URL"- else- log_error "Neither curl nor wget is available"- exit 1- fi-- chmod +x /tmp/serverkit-agent-}--# Install the agent-install_agent() {- log_info "Installing agent to $INSTALL_DIR..."-- # Stop existing service if running- if [ "$INIT_SYSTEM" = "systemd" ] && systemctl is-active --quiet serverkit-agent; then- log_info "Stopping existing agent service..."- systemctl stop serverkit-agent- fi-- # Install binary- mv /tmp/serverkit-agent "$INSTALL_DIR/serverkit-agent"- chmod 755 "$INSTALL_DIR/serverkit-agent"-- # Create directories- mkdir -p "$CONFIG_DIR"- mkdir -p "$LOG_DIR"- mkdir -p /var/lib/serverkit/apps- mkdir -p /var/serverkit/apps- chown "$SERVICE_USER:$SERVICE_USER" "$LOG_DIR"- chown -R "$SERVICE_USER:$SERVICE_USER" /var/lib/serverkit- chown -R "$SERVICE_USER:$SERVICE_USER" /var/serverkit-}--# Register with ServerKit-register_agent() {- log_info "Registering agent with ServerKit..."-- # Pass the token through the environment, not argv: command-line arguments- # are world-readable via `ps` / /proc/<pid>/cmdline, while the environment- # of this root-run process is readable only by root. The server URL and- # name aren't secret, so they stay as flags. (Also drops the old `eval`.)- local reg_args=(register --server "$SERVER_URL")- if [ -n "$NAME" ]; then- reg_args+=(--name "$NAME")- fi-- if ! SERVERKIT_REGISTRATION_TOKEN="$TOKEN" "$INSTALL_DIR/serverkit-agent" "${reg_args[@]}"; then- log_error "Registration failed"- exit 1- fi-- # Set permissions on config- chown -R "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR"- chmod 600 "$CONFIG_DIR/config.yaml"- chmod 600 "$CONFIG_DIR/agent.key"-}--# Install systemd service-install_systemd_service() {- log_info "Installing systemd service..."-- cat > /etc/systemd/system/serverkit-agent.service << EOF-[Unit]-Description=ServerKit Agent-Documentation=https://github.com/serverkit/agent-After=network-online.target docker.service-Wants=network-online.target--[Service]-Type=simple-User=$SERVICE_USER-Group=$SERVICE_USER-ExecStart=$INSTALL_DIR/serverkit-agent start-Restart=always-RestartSec=5-StandardOutput=journal-StandardError=journal-SyslogIdentifier=serverkit-agent--# Security hardening-NoNewPrivileges=yes-ProtectSystem=strict-ProtectHome=yes-ReadWritePaths=$LOG_DIR $CONFIG_DIR /var/lib/serverkit /var/serverkit-PrivateTmp=yes--[Install]-WantedBy=multi-user.target-EOF-- systemctl daemon-reload- systemctl enable serverkit-agent-}--# Start the agent-start_agent() {- log_info "Starting agent..."-- if [ "$INIT_SYSTEM" = "systemd" ]; then- systemctl start serverkit-agent- sleep 2- if systemctl is-active --quiet serverkit-agent; then- log_success "Agent is running"- else- log_error "Agent failed to start"- journalctl -u serverkit-agent -n 20 --no-pager- exit 1- fi- else- log_warn "Please start the agent manually: $INSTALL_DIR/serverkit-agent start"- fi-}--# Main installation flow-main() {- echo ""- echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"- echo -e "${GREEN}║ ServerKit Agent Installation ║${NC}"- echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"- echo ""-- check_root- detect_platform- detect_init_system- create_user- download_agent- install_agent- register_agent-- if [ "$INIT_SYSTEM" = "systemd" ]; then- install_systemd_service- fi-- start_agent-- echo ""- log_success "Installation complete!"- echo ""- echo "Agent Status: serverkit-agent status"- echo "View Logs: journalctl -u serverkit-agent -f"- echo "Config File: $CONFIG_DIR/config.yaml"- echo ""-}--maindiff --git a/agent/ui/.gitignore b/agent/ui/.gitignoredeleted file mode 100644index a62c6b7a..00000000--- a/agent/ui/.gitignore+++ /dev/null@@ -1,4 +0,0 @@-node_modules-dist-.vite-*.logdiff --git a/agent/ui/index.html b/agent/ui/index.htmldeleted file mode 100644index fc89d814..00000000--- a/agent/ui/index.html+++ /dev/null@@ -1,58 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>ServerKit Agent</title>- <!--- Inline styles in <head> paint immediately, before main.scss loads.- Without this the WebView2 host shows a black rectangle for ~500ms- while the JS bundle hydrates — users reported it looked like the- app had hung. The loading shell matches the dark theme exactly so- there's no flash when React replaces it.- -->- <style>- html, body {- margin: 0;- height: 100%;- background: #09090b;- color: #f4f4f5;- font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;- }- #root { height: 100%; }- .splash {- display: flex;- align-items: center;- justify-content: center;- height: 100%;- flex-direction: column;- gap: 12px;- color: #a1a1aa;- }- .splash__spinner {- width: 28px;- height: 28px;- border: 2px solid #27272a;- border-top-color: #6366f1;- border-radius: 50%;- animation: splash-spin 0.8s linear infinite;- }- .splash__label {- font-size: 13px;- letter-spacing: 0.02em;- }- @keyframes splash-spin {- to { transform: rotate(360deg); }- }- </style>- </head>- <body>- <div id="root">- <div class="splash">- <div class="splash__spinner"></div>- <div class="splash__label">Starting ServerKit Agent…</div>- </div>- </div>- <script type="module" src="/src/main.jsx"></script>- </body>-</html>diff --git a/agent/ui/package-lock.json b/agent/ui/package-lock.jsondeleted file mode 100644index ff58ad8e..00000000--- a/agent/ui/package-lock.json+++ /dev/null@@ -1,2534 +0,0 @@-{- "name": "serverkit-agent-ui",- "version": "0.1.0",- "lockfileVersion": 3,- "requires": true,- "packages": {- "": {- "name": "serverkit-agent-ui",- "version": "0.1.0",- "dependencies": {- "lucide-react": "^0.363.0",- "react": "^18.3.1",- "react-dom": "^18.3.1",- "react-router-dom": "^6.22.3",- "recharts": "^2.12.3"- },- "devDependencies": {- "@vitejs/plugin-react": "^4.3.1",- "sass": "^1.86.0",- "vite": "^5.4.1"- }- },- "node_modules/@babel/code-frame": {- "version": "7.29.0",- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",- "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/helper-validator-identifier": "^7.28.5",- "js-tokens": "^4.0.0",- "picocolors": "^1.1.1"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/compat-data": {- "version": "7.29.0",- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",- "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/core": {- "version": "7.29.0",- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",- "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/code-frame": "^7.29.0",- "@babel/generator": "^7.29.0",- "@babel/helper-compilation-targets": "^7.28.6",- "@babel/helper-module-transforms": "^7.28.6",- "@babel/helpers": "^7.28.6",- "@babel/parser": "^7.29.0",- "@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.1.0",- "gensync": "^1.0.0-beta.2",- "json5": "^2.2.3",- "semver": "^6.3.1"- },- "engines": {- "node": ">=6.9.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/babel"- }- },- "node_modules/@babel/generator": {- "version": "7.29.1",- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",- "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/parser": "^7.29.0",- "@babel/types": "^7.29.0",- "@jridgewell/gen-mapping": "^0.3.12",- "@jridgewell/trace-mapping": "^0.3.28",- "jsesc": "^3.0.2"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-compilation-targets": {- "version": "7.28.6",- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",- "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/compat-data": "^7.28.6",- "@babel/helper-validator-option": "^7.27.1",- "browserslist": "^4.24.0",- "lru-cache": "^5.1.1",- "semver": "^6.3.1"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-globals": {- "version": "7.28.0",- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",- "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-module-imports": {- "version": "7.28.6",- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",- "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/traverse": "^7.28.6",- "@babel/types": "^7.28.6"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-module-transforms": {- "version": "7.28.6",- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",- "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/helper-module-imports": "^7.28.6",- "@babel/helper-validator-identifier": "^7.28.5",- "@babel/traverse": "^7.28.6"- },- "engines": {- "node": ">=6.9.0"- },- "peerDependencies": {- "@babel/core": "^7.0.0"- }- },- "node_modules/@babel/helper-plugin-utils": {- "version": "7.28.6",- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz",- "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-string-parser": {- "version": "7.27.1",- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",- "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-validator-identifier": {- "version": "7.28.5",- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",- "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helper-validator-option": {- "version": "7.27.1",- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",- "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/helpers": {- "version": "7.29.2",- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",- "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/template": "^7.28.6",- "@babel/types": "^7.29.0"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/parser": {- "version": "7.29.2",- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",- "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/types": "^7.29.0"- },- "bin": {- "parser": "bin/babel-parser.js"- },- "engines": {- "node": ">=6.0.0"- }- },- "node_modules/@babel/plugin-transform-react-jsx-self": {- "version": "7.27.1",- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz",- "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/helper-plugin-utils": "^7.27.1"- },- "engines": {- "node": ">=6.9.0"- },- "peerDependencies": {- "@babel/core": "^7.0.0-0"- }- },- "node_modules/@babel/plugin-transform-react-jsx-source": {- "version": "7.27.1",- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz",- "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/helper-plugin-utils": "^7.27.1"- },- "engines": {- "node": ">=6.9.0"- },- "peerDependencies": {- "@babel/core": "^7.0.0-0"- }- },- "node_modules/@babel/runtime": {- "version": "7.29.2",- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",- "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/template": {- "version": "7.28.6",- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",- "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/code-frame": "^7.28.6",- "@babel/parser": "^7.28.6",- "@babel/types": "^7.28.6"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/traverse": {- "version": "7.29.0",- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",- "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/code-frame": "^7.29.0",- "@babel/generator": "^7.29.0",- "@babel/helper-globals": "^7.28.0",- "@babel/parser": "^7.29.0",- "@babel/template": "^7.28.6",- "@babel/types": "^7.29.0",- "debug": "^4.3.1"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@babel/types": {- "version": "7.29.0",- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",- "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/helper-string-parser": "^7.27.1",- "@babel/helper-validator-identifier": "^7.28.5"- },- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/@esbuild/aix-ppc64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",- "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "aix"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-arm": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",- "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-arm64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",- "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/android-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",- "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/darwin-arm64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",- "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/darwin-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",- "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/freebsd-arm64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",- "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/freebsd-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",- "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-arm": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",- "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-arm64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",- "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-ia32": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",- "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-loong64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",- "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-mips64el": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",- "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",- "cpu": [- "mips64el"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-ppc64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",- "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-riscv64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",- "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-s390x": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",- "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/linux-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",- "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/netbsd-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",- "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "netbsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/openbsd-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",- "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/sunos-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",- "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "sunos"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-arm64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",- "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-ia32": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",- "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@esbuild/win32-x64": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",- "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">=12"- }- },- "node_modules/@jridgewell/gen-mapping": {- "version": "0.3.13",- "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",- "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@jridgewell/sourcemap-codec": "^1.5.0",- "@jridgewell/trace-mapping": "^0.3.24"- }- },- "node_modules/@jridgewell/remapping": {- "version": "2.3.5",- "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",- "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "@jridgewell/gen-mapping": "^0.3.5",- "@jridgewell/trace-mapping": "^0.3.24"- }- },- "node_modules/@jridgewell/resolve-uri": {- "version": "3.1.2",- "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",- "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.0.0"- }- },- "node_modules/@jridgewell/sourcemap-codec": {- "version": "1.5.5",- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",- "dev": true,- "license": "MIT"- },- "node_modules/@jridgewell/trace-mapping": {- "version": "0.3.31",- "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",- "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",- "dev": true,- "license": "MIT",- "dependencies": {- "@jridgewell/resolve-uri": "^3.1.0",- "@jridgewell/sourcemap-codec": "^1.4.14"- }- },- "node_modules/@parcel/watcher": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz",- "integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "dependencies": {- "detect-libc": "^2.0.3",- "is-glob": "^4.0.3",- "node-addon-api": "^7.0.0",- "picomatch": "^4.0.3"- },- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- },- "optionalDependencies": {- "@parcel/watcher-android-arm64": "2.5.6",- "@parcel/watcher-darwin-arm64": "2.5.6",- "@parcel/watcher-darwin-x64": "2.5.6",- "@parcel/watcher-freebsd-x64": "2.5.6",- "@parcel/watcher-linux-arm-glibc": "2.5.6",- "@parcel/watcher-linux-arm-musl": "2.5.6",- "@parcel/watcher-linux-arm64-glibc": "2.5.6",- "@parcel/watcher-linux-arm64-musl": "2.5.6",- "@parcel/watcher-linux-x64-glibc": "2.5.6",- "@parcel/watcher-linux-x64-musl": "2.5.6",- "@parcel/watcher-win32-arm64": "2.5.6",- "@parcel/watcher-win32-ia32": "2.5.6",- "@parcel/watcher-win32-x64": "2.5.6"- }- },- "node_modules/@parcel/watcher-android-arm64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.6.tgz",- "integrity": "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-darwin-arm64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.6.tgz",- "integrity": "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-darwin-x64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.6.tgz",- "integrity": "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-freebsd-x64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.6.tgz",- "integrity": "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-arm-glibc": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.6.tgz",- "integrity": "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-arm-musl": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.6.tgz",- "integrity": "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-arm64-glibc": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.6.tgz",- "integrity": "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-arm64-musl": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.6.tgz",- "integrity": "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-x64-glibc": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.6.tgz",- "integrity": "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-linux-x64-musl": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.6.tgz",- "integrity": "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-win32-arm64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.6.tgz",- "integrity": "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-win32-ia32": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.6.tgz",- "integrity": "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@parcel/watcher-win32-x64": {- "version": "2.5.6",- "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.6.tgz",- "integrity": "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">= 10.0.0"- },- "funding": {- "type": "opencollective",- "url": "https://opencollective.com/parcel"- }- },- "node_modules/@remix-run/router": {- "version": "1.23.2",- "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",- "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",- "license": "MIT",- "engines": {- "node": ">=14.0.0"- }- },- "node_modules/@rolldown/pluginutils": {- "version": "1.0.0-beta.27",- "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",- "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",- "dev": true,- "license": "MIT"- },- "node_modules/@rollup/rollup-android-arm-eabi": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.2.tgz",- "integrity": "sha512-dnlp69efPPg6Uaw2dVqzWRfAWRnYVb1XJ8CyyhIbZeaq4CA5/mLeZ1IEt9QqQxmbdvagjLIm2ZL8BxXv5lH4Yw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-android-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.2.tgz",- "integrity": "sha512-OqZTwDRDchGRHHm/hwLOL7uVPB9aUvI0am/eQuWMNyFHf5PSEQmyEeYYheA0EPPKUO/l0uigCp+iaTjoLjVoHg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "android"- ]- },- "node_modules/@rollup/rollup-darwin-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.2.tgz",- "integrity": "sha512-UwRE7CGpvSVEQS8gUMBe1uADWjNnVgP3Iusyda1nSRwNDCsRjnGc7w6El6WLQsXmZTbLZx9cecegumcitNfpmA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-darwin-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.2.tgz",- "integrity": "sha512-gjEtURKLCC5VXm1I+2i1u9OhxFsKAQJKTVB8WvDAHF+oZlq0GTVFOlTlO1q3AlCTE/DF32c16ESvfgqR7343/g==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ]- },- "node_modules/@rollup/rollup-freebsd-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.2.tgz",- "integrity": "sha512-Bcl6CYDeAgE70cqZaMojOi/eK63h5Me97ZqAQoh77VPjMysA/4ORQBRGo3rRy45x4MzVlU9uZxs8Uwy7ZaKnBw==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-freebsd-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.2.tgz",- "integrity": "sha512-LU+TPda3mAE2QB0/Hp5VyeKJivpC6+tlOXd1VMoXV/YFMvk/MNk5iXeBfB4MQGRWyOYVJ01625vjkr0Az98OJQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "freebsd"- ]- },- "node_modules/@rollup/rollup-linux-arm-gnueabihf": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.2.tgz",- "integrity": "sha512-2QxQrM+KQ7DAW4o22j+XZ6RKdxjLD7BOWTP0Bv0tmjdyhXSsr2Ul1oJDQqh9Zf5qOwTuTc7Ek83mOFaKnodPjg==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm-musleabihf": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.2.tgz",- "integrity": "sha512-TbziEu2DVsTEOPif2mKWkMeDMLoYjx95oESa9fkQQK7r/Orta0gnkcDpzwufEcAO2BLBsD7mZkXGFqEdMRRwfw==",- "cpu": [- "arm"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.2.tgz",- "integrity": "sha512-bO/rVDiDUuM2YfuCUwZ1t1cP+/yqjqz+Xf2VtkdppefuOFS2OSeAfgafaHNkFn0t02hEyXngZkxtGqXcXwO8Rg==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-arm64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.2.tgz",- "integrity": "sha512-hr26p7e93Rl0Za+JwW7EAnwAvKkehh12BU1Llm9Ykiibg4uIr2rbpxG9WCf56GuvidlTG9KiiQT/TXT1yAWxTA==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-loong64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.2.tgz",- "integrity": "sha512-pOjB/uSIyDt+ow3k/RcLvUAOGpysT2phDn7TTUB3n75SlIgZzM6NKAqlErPhoFU+npgY3/n+2HYIQVbF70P9/A==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-loong64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.2.tgz",- "integrity": "sha512-2/w+q8jszv9Ww1c+6uJT3OwqhdmGP2/4T17cu8WuwyUuuaCDDJ2ojdyYwZzCxx0GcsZBhzi3HmH+J5pZNXnd+Q==",- "cpu": [- "loong64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-ppc64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.2.tgz",- "integrity": "sha512-11+aL5vKheYgczxtPVVRhdptAM2H7fcDR5Gw4/bTcteuZBlH4oP9f5s9zYO9aGZvoGeBpqXI/9TZZihZ609wKw==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-ppc64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.2.tgz",- "integrity": "sha512-i16fokAGK46IVZuV8LIIwMdtqhin9hfYkCh8pf8iC3QU3LpwL+1FSFGej+O7l3E/AoknL6Dclh2oTdnRMpTzFQ==",- "cpu": [- "ppc64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.2.tgz",- "integrity": "sha512-49FkKS6RGQoriDSK/6E2GkAsAuU5kETFCh7pG4yD/ylj9rKhTmO3elsnmBvRD4PgJPds5W2PkhC82aVwmUcJ7A==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-riscv64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.2.tgz",- "integrity": "sha512-mjYNkHPfGpUR00DuM1ZZIgs64Hpf4bWcz9Z41+4Q+pgDx73UwWdAYyf6EG/lRFldmdHHzgrYyge5akFUW0D3mQ==",- "cpu": [- "riscv64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-s390x-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.2.tgz",- "integrity": "sha512-ALyvJz965BQk8E9Al/JDKKDLH2kfKFLTGMlgkAbbYtZuJt9LU8DW3ZoDMCtQpXAltZxwBHevXz5u+gf0yA0YoA==",- "cpu": [- "s390x"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.2.tgz",- "integrity": "sha512-UQjrkIdWrKI626Du8lCQ6MJp/6V1LAo2bOK9OTu4mSn8GGXIkPXk/Vsp4bLHCd9Z9Iz2OTEaokUE90VweJgIYQ==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-linux-x64-musl": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.2.tgz",- "integrity": "sha512-bTsRGj6VlSdn/XD4CGyzMnzaBs9bsRxy79eTqTCBsA8TMIEky7qg48aPkvJvFe1HyzQ5oMZdg7AnVlWQSKLTnw==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "linux"- ]- },- "node_modules/@rollup/rollup-openbsd-x64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.2.tgz",- "integrity": "sha512-6d4Z3534xitaA1FcMWP7mQPq5zGwBmGbhphh2DwaA1aNIXUu3KTOfwrWpbwI4/Gr0uANo7NTtaykFyO2hPuFLg==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openbsd"- ]- },- "node_modules/@rollup/rollup-openharmony-arm64": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.2.tgz",- "integrity": "sha512-NetAg5iO2uN7eB8zE5qrZ3CSil+7IJt4WDFLcC75Ymywq1VZVD6qJ6EvNLjZ3rEm6gB7XW5JdT60c6MN35Z85Q==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "openharmony"- ]- },- "node_modules/@rollup/rollup-win32-arm64-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.2.tgz",- "integrity": "sha512-NCYhOotpgWZ5kdxCZsv6Iudx0wX8980Q/oW4pNFNihpBKsDbEA1zpkfxJGC0yugsUuyDZ7gL37dbzwhR0VI7pQ==",- "cpu": [- "arm64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-ia32-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.2.tgz",- "integrity": "sha512-RXsaOqXxfoUBQoOgvmmijVxJnW2IGB0eoMO7F8FAjaj0UTywUO/luSqimWBJn04WNgUkeNhh7fs7pESXajWmkg==",- "cpu": [- "ia32"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-gnu": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.2.tgz",- "integrity": "sha512-qdAzEULD+/hzObedtmV6iBpdL5TIbKVztGiK7O3/KYSf+HIzU257+MX1EXJcyIiDbMAqmbwaufcYPvyRryeZtA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@rollup/rollup-win32-x64-msvc": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.2.tgz",- "integrity": "sha512-Nd/SgG27WoA9e+/TdK74KnHz852TLa94ovOYySo/yMPuTmpckK/jIF2jSwS3g7ELSKXK13/cVdmg1Z/DaCWKxA==",- "cpu": [- "x64"- ],- "dev": true,- "license": "MIT",- "optional": true,- "os": [- "win32"- ]- },- "node_modules/@types/babel__core": {- "version": "7.20.5",- "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",- "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/parser": "^7.20.7",- "@babel/types": "^7.20.7",- "@types/babel__generator": "*",- "@types/babel__template": "*",- "@types/babel__traverse": "*"- }- },- "node_modules/@types/babel__generator": {- "version": "7.27.0",- "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",- "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/types": "^7.0.0"- }- },- "node_modules/@types/babel__template": {- "version": "7.4.4",- "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",- "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/parser": "^7.1.0",- "@babel/types": "^7.0.0"- }- },- "node_modules/@types/babel__traverse": {- "version": "7.28.0",- "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",- "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/types": "^7.28.2"- }- },- "node_modules/@types/d3-array": {- "version": "3.2.2",- "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",- "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",- "license": "MIT"- },- "node_modules/@types/d3-color": {- "version": "3.1.3",- "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",- "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",- "license": "MIT"- },- "node_modules/@types/d3-ease": {- "version": "3.0.2",- "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",- "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",- "license": "MIT"- },- "node_modules/@types/d3-interpolate": {- "version": "3.0.4",- "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",- "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",- "license": "MIT",- "dependencies": {- "@types/d3-color": "*"- }- },- "node_modules/@types/d3-path": {- "version": "3.1.1",- "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",- "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",- "license": "MIT"- },- "node_modules/@types/d3-scale": {- "version": "4.0.9",- "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",- "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",- "license": "MIT",- "dependencies": {- "@types/d3-time": "*"- }- },- "node_modules/@types/d3-shape": {- "version": "3.1.8",- "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",- "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",- "license": "MIT",- "dependencies": {- "@types/d3-path": "*"- }- },- "node_modules/@types/d3-time": {- "version": "3.0.4",- "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",- "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",- "license": "MIT"- },- "node_modules/@types/d3-timer": {- "version": "3.0.2",- "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",- "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",- "license": "MIT"- },- "node_modules/@types/estree": {- "version": "1.0.8",- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",- "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",- "dev": true,- "license": "MIT"- },- "node_modules/@vitejs/plugin-react": {- "version": "4.7.0",- "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",- "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",- "dev": true,- "license": "MIT",- "dependencies": {- "@babel/core": "^7.28.0",- "@babel/plugin-transform-react-jsx-self": "^7.27.1",- "@babel/plugin-transform-react-jsx-source": "^7.27.1",- "@rolldown/pluginutils": "1.0.0-beta.27",- "@types/babel__core": "^7.20.5",- "react-refresh": "^0.17.0"- },- "engines": {- "node": "^14.18.0 || >=16.0.0"- },- "peerDependencies": {- "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"- }- },- "node_modules/baseline-browser-mapping": {- "version": "2.10.24",- "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.24.tgz",- "integrity": "sha512-I2NkZOOrj2XuguvWCK6OVh9GavsNjZjK908Rq3mIBK25+GD8vPX5w2WdxVqnQ7xx3SrZJiCiZFu+/Oz50oSYSA==",- "dev": true,- "license": "Apache-2.0",- "bin": {- "baseline-browser-mapping": "dist/cli.cjs"- },- "engines": {- "node": ">=6.0.0"- }- },- "node_modules/browserslist": {- "version": "4.28.2",- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",- "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/browserslist"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/browserslist"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "dependencies": {- "baseline-browser-mapping": "^2.10.12",- "caniuse-lite": "^1.0.30001782",- "electron-to-chromium": "^1.5.328",- "node-releases": "^2.0.36",- "update-browserslist-db": "^1.2.3"- },- "bin": {- "browserslist": "cli.js"- },- "engines": {- "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"- }- },- "node_modules/caniuse-lite": {- "version": "1.0.30001791",- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001791.tgz",- "integrity": "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/browserslist"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/caniuse-lite"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "CC-BY-4.0"- },- "node_modules/chokidar": {- "version": "4.0.3",- "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",- "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",- "dev": true,- "license": "MIT",- "dependencies": {- "readdirp": "^4.0.1"- },- "engines": {- "node": ">= 14.16.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },- "node_modules/clsx": {- "version": "2.1.1",- "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",- "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",- "license": "MIT",- "engines": {- "node": ">=6"- }- },- "node_modules/convert-source-map": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",- "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",- "dev": true,- "license": "MIT"- },- "node_modules/csstype": {- "version": "3.2.3",- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",- "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"- },- "node_modules/d3-array": {- "version": "3.2.4",- "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",- "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",- "license": "ISC",- "dependencies": {- "internmap": "1 - 2"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-color": {- "version": "3.1.0",- "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",- "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",- "license": "ISC",- "engines": {- "node": ">=12"- }- },- "node_modules/d3-ease": {- "version": "3.0.1",- "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",- "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",- "license": "BSD-3-Clause",- "engines": {- "node": ">=12"- }- },- "node_modules/d3-format": {- "version": "3.1.2",- "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",- "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",- "license": "ISC",- "engines": {- "node": ">=12"- }- },- "node_modules/d3-interpolate": {- "version": "3.0.1",- "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",- "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",- "license": "ISC",- "dependencies": {- "d3-color": "1 - 3"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-path": {- "version": "3.1.0",- "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",- "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",- "license": "ISC",- "engines": {- "node": ">=12"- }- },- "node_modules/d3-scale": {- "version": "4.0.2",- "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",- "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",- "license": "ISC",- "dependencies": {- "d3-array": "2.10.0 - 3",- "d3-format": "1 - 3",- "d3-interpolate": "1.2.0 - 3",- "d3-time": "2.1.1 - 3",- "d3-time-format": "2 - 4"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-shape": {- "version": "3.2.0",- "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",- "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",- "license": "ISC",- "dependencies": {- "d3-path": "^3.1.0"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-time": {- "version": "3.1.0",- "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",- "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",- "license": "ISC",- "dependencies": {- "d3-array": "2 - 3"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-time-format": {- "version": "4.1.0",- "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",- "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",- "license": "ISC",- "dependencies": {- "d3-time": "1 - 3"- },- "engines": {- "node": ">=12"- }- },- "node_modules/d3-timer": {- "version": "3.0.1",- "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",- "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",- "license": "ISC",- "engines": {- "node": ">=12"- }- },- "node_modules/debug": {- "version": "4.4.3",- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",- "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,- "license": "MIT",- "dependencies": {- "ms": "^2.1.3"- },- "engines": {- "node": ">=6.0"- },- "peerDependenciesMeta": {- "supports-color": {- "optional": true- }- }- },- "node_modules/decimal.js-light": {- "version": "2.5.1",- "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",- "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",- "license": "MIT"- },- "node_modules/detect-libc": {- "version": "2.1.2",- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",- "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",- "dev": true,- "license": "Apache-2.0",- "optional": true,- "engines": {- "node": ">=8"- }- },- "node_modules/dom-helpers": {- "version": "5.2.1",- "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",- "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",- "license": "MIT",- "dependencies": {- "@babel/runtime": "^7.8.7",- "csstype": "^3.0.2"- }- },- "node_modules/electron-to-chromium": {- "version": "1.5.344",- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.344.tgz",- "integrity": "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg==",- "dev": true,- "license": "ISC"- },- "node_modules/esbuild": {- "version": "0.21.5",- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",- "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "bin": {- "esbuild": "bin/esbuild"- },- "engines": {- "node": ">=12"- },- "optionalDependencies": {- "@esbuild/aix-ppc64": "0.21.5",- "@esbuild/android-arm": "0.21.5",- "@esbuild/android-arm64": "0.21.5",- "@esbuild/android-x64": "0.21.5",- "@esbuild/darwin-arm64": "0.21.5",- "@esbuild/darwin-x64": "0.21.5",- "@esbuild/freebsd-arm64": "0.21.5",- "@esbuild/freebsd-x64": "0.21.5",- "@esbuild/linux-arm": "0.21.5",- "@esbuild/linux-arm64": "0.21.5",- "@esbuild/linux-ia32": "0.21.5",- "@esbuild/linux-loong64": "0.21.5",- "@esbuild/linux-mips64el": "0.21.5",- "@esbuild/linux-ppc64": "0.21.5",- "@esbuild/linux-riscv64": "0.21.5",- "@esbuild/linux-s390x": "0.21.5",- "@esbuild/linux-x64": "0.21.5",- "@esbuild/netbsd-x64": "0.21.5",- "@esbuild/openbsd-x64": "0.21.5",- "@esbuild/sunos-x64": "0.21.5",- "@esbuild/win32-arm64": "0.21.5",- "@esbuild/win32-ia32": "0.21.5",- "@esbuild/win32-x64": "0.21.5"- }- },- "node_modules/escalade": {- "version": "3.2.0",- "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",- "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6"- }- },- "node_modules/eventemitter3": {- "version": "4.0.7",- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",- "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",- "license": "MIT"- },- "node_modules/fast-equals": {- "version": "5.4.0",- "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.0.tgz",- "integrity": "sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==",- "license": "MIT",- "engines": {- "node": ">=6.0.0"- }- },- "node_modules/fsevents": {- "version": "2.3.3",- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"- }- },- "node_modules/gensync": {- "version": "1.0.0-beta.2",- "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",- "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=6.9.0"- }- },- "node_modules/immutable": {- "version": "5.1.5",- "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.5.tgz",- "integrity": "sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==",- "dev": true,- "license": "MIT"- },- "node_modules/internmap": {- "version": "2.0.3",- "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",- "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",- "license": "ISC",- "engines": {- "node": ">=12"- }- },- "node_modules/is-extglob": {- "version": "2.1.1",- "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",- "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",- "dev": true,- "license": "MIT",- "optional": true,- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/is-glob": {- "version": "4.0.3",- "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",- "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "is-extglob": "^2.1.1"- },- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/js-tokens": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",- "license": "MIT"- },- "node_modules/jsesc": {- "version": "3.1.0",- "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",- "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",- "dev": true,- "license": "MIT",- "bin": {- "jsesc": "bin/jsesc"- },- "engines": {- "node": ">=6"- }- },- "node_modules/json5": {- "version": "2.2.3",- "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",- "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",- "dev": true,- "license": "MIT",- "bin": {- "json5": "lib/cli.js"- },- "engines": {- "node": ">=6"- }- },- "node_modules/lodash": {- "version": "4.18.1",- "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",- "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",- "license": "MIT"- },- "node_modules/loose-envify": {- "version": "1.4.0",- "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",- "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "license": "MIT",- "dependencies": {- "js-tokens": "^3.0.0 || ^4.0.0"- },- "bin": {- "loose-envify": "cli.js"- }- },- "node_modules/lru-cache": {- "version": "5.1.1",- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",- "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",- "dev": true,- "license": "ISC",- "dependencies": {- "yallist": "^3.0.2"- }- },- "node_modules/lucide-react": {- "version": "0.363.0",- "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.363.0.tgz",- "integrity": "sha512-AlsfPCsXQyQx7wwsIgzcKOL9LwC498LIMAo+c0Es5PkHJa33xwmYAkkSoKoJWWWSYQEStqu58/jT4tL2gi32uQ==",- "license": "ISC",- "peerDependencies": {- "react": "^16.5.1 || ^17.0.0 || ^18.0.0"- }- },- "node_modules/ms": {- "version": "2.1.3",- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,- "license": "MIT"- },- "node_modules/nanoid": {- "version": "3.3.11",- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",- "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",- "dev": true,- "funding": [- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "bin": {- "nanoid": "bin/nanoid.cjs"- },- "engines": {- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"- }- },- "node_modules/node-addon-api": {- "version": "7.1.1",- "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",- "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",- "dev": true,- "license": "MIT",- "optional": true- },- "node_modules/node-releases": {- "version": "2.0.38",- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",- "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==",- "dev": true,- "license": "MIT"- },- "node_modules/object-assign": {- "version": "4.1.1",- "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",- "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",- "license": "MIT",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/picocolors": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",- "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",- "dev": true,- "license": "ISC"- },- "node_modules/picomatch": {- "version": "4.0.4",- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",- "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",- "dev": true,- "license": "MIT",- "optional": true,- "engines": {- "node": ">=12"- },- "funding": {- "url": "https://github.com/sponsors/jonschlinkert"- }- },- "node_modules/postcss": {- "version": "8.5.12",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.12.tgz",- "integrity": "sha512-W62t/Se6rA0Az3DfCL0AqJwXuKwBeYg6nOaIgzP+xZ7N5BFCI7DYi1qs6ygUYT6rvfi6t9k65UMLJC+PHZpDAA==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/postcss/"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/postcss"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "dependencies": {- "nanoid": "^3.3.11",- "picocolors": "^1.1.1",- "source-map-js": "^1.2.1"- },- "engines": {- "node": "^10 || ^12 || >=14"- }- },- "node_modules/prop-types": {- "version": "15.8.1",- "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",- "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",- "license": "MIT",- "dependencies": {- "loose-envify": "^1.4.0",- "object-assign": "^4.1.1",- "react-is": "^16.13.1"- }- },- "node_modules/prop-types/node_modules/react-is": {- "version": "16.13.1",- "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",- "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",- "license": "MIT"- },- "node_modules/react": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",- "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",- "license": "MIT",- "dependencies": {- "loose-envify": "^1.1.0"- },- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/react-dom": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",- "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",- "license": "MIT",- "dependencies": {- "loose-envify": "^1.1.0",- "scheduler": "^0.23.2"- },- "peerDependencies": {- "react": "^18.3.1"- }- },- "node_modules/react-is": {- "version": "18.3.1",- "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",- "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",- "license": "MIT"- },- "node_modules/react-refresh": {- "version": "0.17.0",- "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",- "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/react-router": {- "version": "6.30.3",- "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",- "integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",- "license": "MIT",- "dependencies": {- "@remix-run/router": "1.23.2"- },- "engines": {- "node": ">=14.0.0"- },- "peerDependencies": {- "react": ">=16.8"- }- },- "node_modules/react-router-dom": {- "version": "6.30.3",- "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",- "integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",- "license": "MIT",- "dependencies": {- "@remix-run/router": "1.23.2",- "react-router": "6.30.3"- },- "engines": {- "node": ">=14.0.0"- },- "peerDependencies": {- "react": ">=16.8",- "react-dom": ">=16.8"- }- },- "node_modules/react-smooth": {- "version": "4.0.4",- "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",- "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",- "license": "MIT",- "dependencies": {- "fast-equals": "^5.0.1",- "prop-types": "^15.8.1",- "react-transition-group": "^4.4.5"- },- "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"- }- },- "node_modules/react-transition-group": {- "version": "4.4.5",- "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",- "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",- "license": "BSD-3-Clause",- "dependencies": {- "@babel/runtime": "^7.5.5",- "dom-helpers": "^5.0.1",- "loose-envify": "^1.4.0",- "prop-types": "^15.6.2"- },- "peerDependencies": {- "react": ">=16.6.0",- "react-dom": ">=16.6.0"- }- },- "node_modules/readdirp": {- "version": "4.1.2",- "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",- "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",- "dev": true,- "license": "MIT",- "engines": {- "node": ">= 14.18.0"- },- "funding": {- "type": "individual",- "url": "https://paulmillr.com/funding/"- }- },- "node_modules/recharts": {- "version": "2.15.4",- "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",- "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==",- "license": "MIT",- "dependencies": {- "clsx": "^2.0.0",- "eventemitter3": "^4.0.1",- "lodash": "^4.17.21",- "react-is": "^18.3.1",- "react-smooth": "^4.0.4",- "recharts-scale": "^0.4.4",- "tiny-invariant": "^1.3.1",- "victory-vendor": "^36.6.8"- },- "engines": {- "node": ">=14"- },- "peerDependencies": {- "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",- "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"- }- },- "node_modules/recharts-scale": {- "version": "0.4.5",- "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",- "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",- "license": "MIT",- "dependencies": {- "decimal.js-light": "^2.4.1"- }- },- "node_modules/rollup": {- "version": "4.60.2",- "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.2.tgz",- "integrity": "sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==",- "dev": true,- "license": "MIT",- "dependencies": {- "@types/estree": "1.0.8"- },- "bin": {- "rollup": "dist/bin/rollup"- },- "engines": {- "node": ">=18.0.0",- "npm": ">=8.0.0"- },- "optionalDependencies": {- "@rollup/rollup-android-arm-eabi": "4.60.2",- "@rollup/rollup-android-arm64": "4.60.2",- "@rollup/rollup-darwin-arm64": "4.60.2",- "@rollup/rollup-darwin-x64": "4.60.2",- "@rollup/rollup-freebsd-arm64": "4.60.2",- "@rollup/rollup-freebsd-x64": "4.60.2",- "@rollup/rollup-linux-arm-gnueabihf": "4.60.2",- "@rollup/rollup-linux-arm-musleabihf": "4.60.2",- "@rollup/rollup-linux-arm64-gnu": "4.60.2",- "@rollup/rollup-linux-arm64-musl": "4.60.2",- "@rollup/rollup-linux-loong64-gnu": "4.60.2",- "@rollup/rollup-linux-loong64-musl": "4.60.2",- "@rollup/rollup-linux-ppc64-gnu": "4.60.2",- "@rollup/rollup-linux-ppc64-musl": "4.60.2",- "@rollup/rollup-linux-riscv64-gnu": "4.60.2",- "@rollup/rollup-linux-riscv64-musl": "4.60.2",- "@rollup/rollup-linux-s390x-gnu": "4.60.2",- "@rollup/rollup-linux-x64-gnu": "4.60.2",- "@rollup/rollup-linux-x64-musl": "4.60.2",- "@rollup/rollup-openbsd-x64": "4.60.2",- "@rollup/rollup-openharmony-arm64": "4.60.2",- "@rollup/rollup-win32-arm64-msvc": "4.60.2",- "@rollup/rollup-win32-ia32-msvc": "4.60.2",- "@rollup/rollup-win32-x64-gnu": "4.60.2",- "@rollup/rollup-win32-x64-msvc": "4.60.2",- "fsevents": "~2.3.2"- }- },- "node_modules/sass": {- "version": "1.99.0",- "resolved": "https://registry.npmjs.org/sass/-/sass-1.99.0.tgz",- "integrity": "sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==",- "dev": true,- "license": "MIT",- "dependencies": {- "chokidar": "^4.0.0",- "immutable": "^5.1.5",- "source-map-js": ">=0.6.2 <2.0.0"- },- "bin": {- "sass": "sass.js"- },- "engines": {- "node": ">=14.0.0"- },- "optionalDependencies": {- "@parcel/watcher": "^2.4.1"- }- },- "node_modules/scheduler": {- "version": "0.23.2",- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",- "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",- "license": "MIT",- "dependencies": {- "loose-envify": "^1.1.0"- }- },- "node_modules/semver": {- "version": "6.3.1",- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",- "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",- "dev": true,- "license": "ISC",- "bin": {- "semver": "bin/semver.js"- }- },- "node_modules/source-map-js": {- "version": "1.2.1",- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",- "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",- "dev": true,- "license": "BSD-3-Clause",- "engines": {- "node": ">=0.10.0"- }- },- "node_modules/tiny-invariant": {- "version": "1.3.3",- "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",- "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",- "license": "MIT"- },- "node_modules/update-browserslist-db": {- "version": "1.2.3",- "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",- "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",- "dev": true,- "funding": [- {- "type": "opencollective",- "url": "https://opencollective.com/browserslist"- },- {- "type": "tidelift",- "url": "https://tidelift.com/funding/github/npm/browserslist"- },- {- "type": "github",- "url": "https://github.com/sponsors/ai"- }- ],- "license": "MIT",- "dependencies": {- "escalade": "^3.2.0",- "picocolors": "^1.1.1"- },- "bin": {- "update-browserslist-db": "cli.js"- },- "peerDependencies": {- "browserslist": ">= 4.21.0"- }- },- "node_modules/victory-vendor": {- "version": "36.9.2",- "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",- "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",- "license": "MIT AND ISC",- "dependencies": {- "@types/d3-array": "^3.0.3",- "@types/d3-ease": "^3.0.0",- "@types/d3-interpolate": "^3.0.1",- "@types/d3-scale": "^4.0.2",- "@types/d3-shape": "^3.1.0",- "@types/d3-time": "^3.0.0",- "@types/d3-timer": "^3.0.0",- "d3-array": "^3.1.6",- "d3-ease": "^3.0.1",- "d3-interpolate": "^3.0.1",- "d3-scale": "^4.0.2",- "d3-shape": "^3.1.0",- "d3-time": "^3.0.0",- "d3-timer": "^3.0.1"- }- },- "node_modules/vite": {- "version": "5.4.21",- "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",- "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",- "dev": true,- "license": "MIT",- "dependencies": {- "esbuild": "^0.21.3",- "postcss": "^8.4.43",- "rollup": "^4.20.0"- },- "bin": {- "vite": "bin/vite.js"- },- "engines": {- "node": "^18.0.0 || >=20.0.0"- },- "funding": {- "url": "https://github.com/vitejs/vite?sponsor=1"- },- "optionalDependencies": {- "fsevents": "~2.3.3"- },- "peerDependencies": {- "@types/node": "^18.0.0 || >=20.0.0",- "less": "*",- "lightningcss": "^1.21.0",- "sass": "*",- "sass-embedded": "*",- "stylus": "*",- "sugarss": "*",- "terser": "^5.4.0"- },- "peerDependenciesMeta": {- "@types/node": {- "optional": true- },- "less": {- "optional": true- },- "lightningcss": {- "optional": true- },- "sass": {- "optional": true- },- "sass-embedded": {- "optional": true- },- "stylus": {- "optional": true- },- "sugarss": {- "optional": true- },- "terser": {- "optional": true- }- }- },- "node_modules/yallist": {- "version": "3.1.1",- "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",- "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",- "dev": true,- "license": "ISC"- }- }-}diff --git a/agent/ui/package.json b/agent/ui/package.jsondeleted file mode 100644index f36c4655..00000000--- a/agent/ui/package.json+++ /dev/null@@ -1,23 +0,0 @@-{- "name": "serverkit-agent-ui",- "private": true,- "version": "0.1.0",- "type": "module",- "scripts": {- "dev": "vite",- "build": "vite build",- "preview": "vite preview"- },- "dependencies": {- "lucide-react": "^0.363.0",- "react": "^18.3.1",- "react-dom": "^18.3.1",- "react-router-dom": "^6.22.3",- "recharts": "^2.12.3"- },- "devDependencies": {- "@vitejs/plugin-react": "^4.3.1",- "sass": "^1.86.0",- "vite": "^5.4.1"- }-}diff --git a/agent/ui/src/App.jsx b/agent/ui/src/App.jsxdeleted file mode 100644index be93969a..00000000--- a/agent/ui/src/App.jsx+++ /dev/null@@ -1,79 +0,0 @@-import { useEffect, useState } from 'react';-import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';-import Shell from './components/Shell.jsx';-import Overview from './pages/Overview.jsx';-import Activity from './pages/Activity.jsx';-import Logs from './pages/Logs.jsx';-import Actions from './pages/Actions.jsx';-import About from './pages/About.jsx';-import Pair from './pages/Pair.jsx';-import { local } from './ipc/client.js';--// PairGate uses /local/status (authoritative — reads config.yaml in this-// process) as the single source of truth for registration. Earlier-// versions also consulted the agent service IPC, but that endpoint is-// silent on a fresh install (the service won't even start without a-// config), which let users wander into Overview / Actions before pairing-// — exactly the "let me click around an unconfigured app" report.-//-// We deliberately render NOTHING until the first /local/status resolves.-// The HTML splash from index.html stays on screen during that window, so-// the user sees a loading state instead of partial UI.-function PairGate({ children }) {- const [registered, setRegistered] = useState(null); // null=unknown- const location = useLocation();- const navigate = useNavigate();-- useEffect(() => {- let cancelled = false;- async function tick() {- try {- const s = await local.status();- if (!cancelled) setRegistered(Boolean(s && s.registered));- } catch {- // Same-process call — if this fails the asset server is- // gone and the window is closing.- }- }- tick();- const id = setInterval(tick, 2000);- return () => { cancelled = true; clearInterval(id); };- }, []);-- useEffect(() => {- if (registered === null) return; // wait for first answer- const onPair = location.pathname === '/pair';- if (!registered && !onPair) {- navigate('/pair', { replace: true });- }- }, [registered, location.pathname, navigate]);-- // Hold render until we know — prevents the unpaired user from seeing- // Overview / Actions for a beat before being kicked to /pair.- if (registered === null) return null;-- // Hard-deny the non-pair routes when unregistered. The navigate() in- // the effect handles the redirect; this keeps the children blank in- // the same render so we don't flash the wrong page.- if (!registered && location.pathname !== '/pair') return null;-- return children;-}--export default function App() {- return (- <PairGate>- <Routes>- <Route path="/pair" element={<Pair />} />- <Route element={<Shell />}>- <Route path="/overview" element={<Overview />} />- <Route path="/activity" element={<Activity />} />- <Route path="/logs" element={<Logs />} />- <Route path="/actions" element={<Actions />} />- <Route path="/about" element={<About />} />- </Route>- <Route path="*" element={<Navigate to="/overview" replace />} />- </Routes>- </PairGate>- );-}diff --git a/agent/ui/src/components/Shell.jsx b/agent/ui/src/components/Shell.jsxdeleted file mode 100644index 529f0da2..00000000--- a/agent/ui/src/components/Shell.jsx+++ /dev/null@@ -1,13 +0,0 @@-import { Outlet } from 'react-router-dom';-import Sidebar from './Sidebar.jsx';--export default function Shell() {- return (- <div className="shell">- <Sidebar />- <main className="shell__main">- <Outlet />- </main>- </div>- );-}diff --git a/agent/ui/src/components/Sidebar.jsx b/agent/ui/src/components/Sidebar.jsxdeleted file mode 100644index 086be7f9..00000000--- a/agent/ui/src/components/Sidebar.jsx+++ /dev/null@@ -1,61 +0,0 @@-import { NavLink } from 'react-router-dom';-import {- LayoutDashboard,- History,- FileText,- Wrench,- Info,- Server,-} from 'lucide-react';-import { useStatus } from '../ipc/hooks.js';--const NAV = [- { to: '/overview', label: 'Overview', icon: LayoutDashboard },- { to: '/activity', label: 'Activity', icon: History },- { to: '/logs', label: 'Logs', icon: FileText },- { to: '/actions', label: 'Actions', icon: Wrench },- { to: '/about', label: 'About', icon: Info },-];--export default function Sidebar() {- // Pulled lazily — sidebar renders on every page so this hook is a- // single shared subscription to /status. Errors are intentionally- // ignored; the sidebar shows '—' when the version isn't known yet- // rather than an error spinner.- const { status } = useStatus(5000);- return (- <aside className="sidebar">- <div className="sidebar__brand">- <div className="sidebar__brand-icon">- <Server size={18} />- </div>- <div>- <div className="sidebar__brand-name">ServerKit</div>- <div className="sidebar__brand-sub">Agent Console</div>- </div>- </div>- <nav className="sidebar__nav">- {NAV.map(({ to, label, icon: Icon }) => (- <NavLink- key={to}- to={to}- className={({ isActive }) =>- 'sidebar__link' + (isActive ? ' sidebar__link--active' : '')- }- >- <Icon size={16} />- <span>{label}</span>- </NavLink>- ))}- </nav>- <div className="sidebar__footer">- <div className="sidebar__version">v{status?.version || '—'}</div>- {status?.transport === 'poll' && (- <div className="sidebar__transport" title="Connected via REST polling fallback">- polling- </div>- )}- </div>- </aside>- );-}diff --git a/agent/ui/src/ipc/client.js b/agent/ui/src/ipc/client.jsdeleted file mode 100644index 92e7fa53..00000000--- a/agent/ui/src/ipc/client.js+++ /dev/null@@ -1,171 +0,0 @@-// Tiny client for the agent's local IPC server. Always 127.0.0.1 — the IPC-// server refuses non-loopback binds — and gates every endpoint except-// /health behind a bearer token. We fetch the token from the in-process-// asset server (/local/ipc-token), which reads it off disk: the React UI-// can't read filesystem paths, but the Go console process running it can.--const DEFAULT_PORT = 19780;--// Resolve the IPC base URL. The agent UI runs in WebView2 served from-// 127.0.0.1:<random>, so we can't get the IPC port from the document origin.-// We accept an override via an env var (Vite injects it at build time) and-// otherwise fall back to the default port baked into the agent's config.-const PORT =- Number(import.meta.env.VITE_AGENT_IPC_PORT) ||- Number(window.__SERVERKIT_IPC_PORT__) ||- DEFAULT_PORT;--const BASE = `http://127.0.0.1:${PORT}`;--// Cache the token in-module so we don't re-fetch on every IPC call.-// Refresh on 401 so a token rotation (rare; only if the file is wiped-// and the agent restarts) gets picked up without a UI reload.-let _tokenPromise = null;--async function fetchToken() {- const res = await fetch('/local/ipc-token');- if (!res.ok) {- // 503 means "agent service not running yet" — propagate so the- // hook can decide whether to retry.- const err = new Error(`token fetch failed: ${res.status}`);- err.status = res.status;- throw err;- }- const json = await res.json();- return json.token;-}--async function ipcToken() {- if (!_tokenPromise) {- _tokenPromise = fetchToken().catch((err) => {- // Don't cache failure — next call will retry.- _tokenPromise = null;- throw err;- });- }- return _tokenPromise;-}--function invalidateToken() {- _tokenPromise = null;-}--async function authedHeaders(extra) {- let headers = { Accept: 'application/json', ...(extra || {}) };- try {- const tok = await ipcToken();- if (tok) headers.Authorization = `Bearer ${tok}`;- } catch {- // Fall through with no Authorization header. /health still works- // and any other endpoint will return 401, which the hooks already- // surface as "agent unreachable".- }- return headers;-}--async function get(path) {- const headers = await authedHeaders();- let res = await fetch(`${BASE}${path}`, { method: 'GET', headers });- if (res.status === 401) {- // Token might be stale (file rewritten on agent restart). One- // retry with a freshly fetched token before bubbling the error.- invalidateToken();- const retryHeaders = await authedHeaders();- res = await fetch(`${BASE}${path}`, { method: 'GET', headers: retryHeaders });- }- if (!res.ok) {- const text = await res.text().catch(() => '');- throw new Error(`IPC ${path} ${res.status}: ${text || res.statusText}`);- }- return res.json();-}--async function post(path, body) {- const headers = await authedHeaders({ 'Content-Type': 'application/json' });- let res = await fetch(`${BASE}${path}`, {- method: 'POST',- headers,- body: body ? JSON.stringify(body) : null,- });- if (res.status === 401) {- invalidateToken();- const retryHeaders = await authedHeaders({ 'Content-Type': 'application/json' });- res = await fetch(`${BASE}${path}`, {- method: 'POST',- headers: retryHeaders,- body: body ? JSON.stringify(body) : null,- });- }- if (!res.ok) {- const text = await res.text().catch(() => '');- throw new Error(`IPC ${path} ${res.status}: ${text || res.statusText}`);- }- return res.json();-}--export const ipc = {- health: () => get('/health'),- status: () => get('/status'),- metricsHistory: () => get('/metrics/history'),- events: (since = 0) => get(`/events${since ? `?since=${since}` : ''}`),- connection: () => get('/connection'),- logs: (lines = 200) => get(`/logs?lines=${lines}`),- clearLogs: () => post('/logs/clear'),- restart: () => post('/restart'),-};--// "local" calls hit the asset server in the *console process*, not the-// agent service. These are the operations that have to happen even when-// the agent service is down (Start the service, Re-pair) or that need an-// interactive Windows session (Open in Explorer / browser).-async function localCall(path, body) {- const res = await fetch(path, {- method: 'POST',- headers: body ? { 'Content-Type': 'application/json' } : undefined,- body: body ? JSON.stringify(body) : null,- });- if (!res.ok) {- let msg = res.statusText;- try {- const j = await res.json();- if (j && j.error) msg = j.error;- } catch { /* keep statusText */ }- const err = new Error(msg);- err.status = res.status;- throw err;- }- return res.json();-}--async function localGet(path) {- const res = await fetch(path);- if (!res.ok) {- const err = new Error(res.statusText);- err.status = res.status;- throw err;- }- return res.json();-}--export const local = {- serviceStart: () => localCall('/local/service/start'),- serviceStop: () => localCall('/local/service/stop'),- serviceRestart: () => localCall('/local/service/restart'),- open: (target) => localCall('/local/open', target),- repair: () => localCall('/local/wizard'),- diag: () => localCall('/local/diag'),- // status reads config.yaml in the console process so we can route the- // wizard correctly even when the agent service isn't running (which is- // the default state on a fresh install — no config, no service).- status: () => localGet('/local/status'),- pairStart: (panelUrl, serverName) =>- localCall('/local/pair/start', { panel_url: panelUrl, server_name: serverName }),- pairState: () => localGet('/local/pair/state'),- pairCancel: () => localCall('/local/pair/cancel'),- // The single-string entry path. The agent decodes the string, calls- // /api/v1/servers/register on the panel, and lands on the same- // "claimed" state the pair-code flow ends in — so polling /state- // works unchanged.- pairConnectionString: (connectionString) =>- localCall('/local/pair/connection-string', { connection_string: connectionString }),-};diff --git a/agent/ui/src/ipc/hooks.js b/agent/ui/src/ipc/hooks.jsdeleted file mode 100644index 8a357afb..00000000--- a/agent/ui/src/ipc/hooks.js+++ /dev/null@@ -1,63 +0,0 @@-import { useEffect, useState, useRef } from 'react';-import { ipc } from './client.js';--// Generic polling hook. Calls fetcher() on mount and then every intervalMs.-// Cancels on unmount and treats overlapping requests defensively (last write-// wins, but a stale response can't overwrite the current one).-function usePolling(fetcher, intervalMs) {- const [data, setData] = useState(null);- const [error, setError] = useState(null);- const seq = useRef(0);-- useEffect(() => {- let cancelled = false;- async function tick() {- const mySeq = ++seq.current;- try {- const result = await fetcher();- if (cancelled || mySeq !== seq.current) return;- setData(result);- setError(null);- } catch (err) {- if (cancelled || mySeq !== seq.current) return;- setError(err.message || String(err));- }- }- tick();- const id = setInterval(tick, intervalMs);- return () => {- cancelled = true;- clearInterval(id);- };- // fetcher is captured by reference; in our use it's always a stable- // module-level function, so we deliberately exclude it from deps.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [intervalMs]);-- return { data, error };-}--export function useStatus(intervalMs = 2000) {- const { data, error } = usePolling(ipc.status, intervalMs);- return { status: data, error };-}--export function useMetricsHistory(intervalMs = 2000) {- const { data, error } = usePolling(ipc.metricsHistory, intervalMs);- return { samples: data?.samples || [], error };-}--export function useConnection(intervalMs = 5000) {- const { data, error } = usePolling(ipc.connection, intervalMs);- return { connection: data, error };-}--export function useEvents(intervalMs = 3000) {- const { data, error } = usePolling(() => ipc.events(0), intervalMs);- return { events: data?.events || [], error };-}--export function useLogs(lines = 500, intervalMs = 2000) {- const { data, error } = usePolling(() => ipc.logs(lines), intervalMs);- return { lines: data?.lines || [], count: data?.count || 0, error };-}diff --git a/agent/ui/src/main.jsx b/agent/ui/src/main.jsxdeleted file mode 100644index 69bcf9d7..00000000--- a/agent/ui/src/main.jsx+++ /dev/null@@ -1,74 +0,0 @@-import { StrictMode, Component } from 'react';-import { createRoot } from 'react-dom/client';-import { HashRouter } from 'react-router-dom';-import App from './App.jsx';-import './styles/main.scss';--// 1.6.2 had a class of "blank #root" bug reports where a render exception-// in App or any provider unmounted the index.html splash and left no-// fallback. The user saw nothing and we got a navReady signal that lied —-// the bundle ran, the listener fired, and *then* React crashed on mount.-// This boundary keeps the window from going blank on render errors and-// echoes the message back to the WebView2 host log via window.agentLog.-class RootErrorBoundary extends Component {- state = { error: null };- static getDerivedStateFromError(error) {- return { error };- }- componentDidCatch(error, info) {- try {- if (window.agentLog) {- window.agentLog('error', 'react root: ' + (error && error.stack ? error.stack : String(error)));- }- } catch { /* ignore — host bridge may not be present */ }- }- render() {- if (this.state.error) {- const msg = this.state.error && this.state.error.message- ? this.state.error.message- : String(this.state.error);- return (- <div style={{- height: '100%',- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- padding: '24px',- background: '#09090b',- color: '#f4f4f5',- fontFamily: 'Segoe UI, system-ui, sans-serif',- gap: '12px',- }}>- <div style={{ fontSize: 16, fontWeight: 600 }}>ServerKit Agent failed to start</div>- <div style={{ fontSize: 13, color: '#a1a1aa', maxWidth: 600, textAlign: 'center' }}>- Right-click anywhere and choose <strong>Inspect</strong> to see the full error in DevTools.- The message below has also been written to <code>desktop.log</code>.- </div>- <pre style={{- fontSize: 12,- color: '#fca5a5',- background: '#18181b',- border: '1px solid #27272a',- borderRadius: 6,- padding: '12px 16px',- maxWidth: '80%',- overflow: 'auto',- whiteSpace: 'pre-wrap',- }}>{msg}</pre>- </div>- );- }- return this.props.children;- }-}--createRoot(document.getElementById('root')).render(- <StrictMode>- <RootErrorBoundary>- <HashRouter>- <App />- </HashRouter>- </RootErrorBoundary>- </StrictMode>-);diff --git a/agent/ui/src/pages/About.jsx b/agent/ui/src/pages/About.jsxdeleted file mode 100644index a230423f..00000000--- a/agent/ui/src/pages/About.jsx+++ /dev/null@@ -1,30 +0,0 @@-import { useStatus } from '../ipc/hooks.js';--export default function About() {- const { status } = useStatus(5000);- return (- <div className="page">- <header className="page__header">- <h1 className="page__title">About</h1>- <p className="page__sub muted">ServerKit Agent Console</p>- </header>- <div className="card">- <div className="info-row">- <span className="info-row__label">Version</span>- <span className="info-row__value">{status?.version || '—'}</span>- </div>- <div className="info-row">- <span className="info-row__label">Agent ID</span>- <span className="info-row__value info-row__value--mono">{status?.agent_id || '—'}</span>- </div>- <div className="info-row">- <span className="info-row__label">Hostname</span>- <span className="info-row__value">{status?.agent_name || '—'}</span>- </div>- </div>- <div className="card empty-state">- Unpair and Uninstall actions will land here in the next milestone.- </div>- </div>- );-}diff --git a/agent/ui/src/pages/Actions.jsx b/agent/ui/src/pages/Actions.jsxdeleted file mode 100644index 2eb2e5a3..00000000--- a/agent/ui/src/pages/Actions.jsx+++ /dev/null@@ -1,163 +0,0 @@-import { useState } from 'react';-import { useNavigate } from 'react-router-dom';-import {- Power,- Square,- RefreshCw,- FolderOpen,- Globe,- KeyRound,- Package,-} from 'lucide-react';-import { useStatus } from '../ipc/hooks.js';-import { local } from '../ipc/client.js';--// Actions are bucketed so the most-common operations sit on top and the-// destructive / re-pair ones live further down. A shared ActionRow renders-// them with icon + label + description + button.--function ActionRow({ icon: Icon, title, desc, action, label = 'Run', danger }) {- const [busy, setBusy] = useState(false);- const [feedback, setFeedback] = useState(null);-- async function onClick() {- if (busy) return;- setBusy(true);- setFeedback(null);- try {- await action();- setFeedback({ ok: true, msg: 'Done' });- } catch (err) {- setFeedback({ ok: false, msg: err.message || 'Failed' });- } finally {- setBusy(false);- setTimeout(() => setFeedback(null), 3000);- }- }-- return (- <div className="action">- <div className="action__icon">- <Icon size={18} />- </div>- <div className="action__body">- <div className="action__title">{title}</div>- <div className="action__desc">{desc}</div>- </div>- <div className="action__buttons">- {feedback && (- <span- className={- 'action__feedback ' +- (feedback.ok ? 'action__feedback--ok' : 'action__feedback--err')- }- >- {feedback.msg}- </span>- )}- <button- type="button"- className={'btn' + (danger ? ' btn--danger' : '')}- onClick={onClick}- disabled={busy}- >- {busy ? '…' : label}- </button>- </div>- </div>- );-}--export default function Actions() {- const { status } = useStatus(5000);- const navigate = useNavigate();- const dashboardUrl = status?.server_url- ? status.server_url.replace(/^wss?:\/\//, 'https://').replace(/\/agent$/, '')- : '';-- return (- <div className="page">- <header className="page__header">- <div>- <h1 className="page__title">Actions</h1>- <p className="page__sub muted">Service controls, recovery, and quick-open shortcuts.</p>- </div>- </header>-- <section className="card card--padded">- <div className="action-group__heading">Service</div>- <ActionRow- icon={RefreshCw}- title="Restart agent"- desc="Stops then starts the ServerKitAgent service. Use this after re-pairing or changing config."- action={local.serviceRestart}- label="Restart"- />- <ActionRow- icon={Power}- title="Start agent"- desc="Starts the service if it's not running."- action={local.serviceStart}- label="Start"- />- <ActionRow- icon={Square}- title="Stop agent"- desc="Stops the service. The console window stays open."- action={local.serviceStop}- label="Stop"- danger- />- </section>-- <section className="card card--padded">- <div className="action-group__heading">Quick open</div>- <ActionRow- icon={FolderOpen}- title="Open log folder"- desc="Opens C:\\ProgramData\\ServerKit\\Agent\\logs in Explorer."- action={() => local.open({ path: 'C:\\ProgramData\\ServerKit\\Agent\\logs' })}- label="Open"- />- <ActionRow- icon={Globe}- title="Open dashboard"- desc={dashboardUrl ? `Opens ${dashboardUrl} in your browser.` : 'Opens the panel URL once the agent is paired.'}- action={() => local.open({ url: dashboardUrl })}- label="Open"- />- </section>-- <section className="card card--padded">- <div className="action-group__heading">Pairing</div>- <ActionRow- icon={KeyRound}- title="Re-pair this server"- desc="Reopens the pairing wizard in this window. Useful when the panel URL changes (e.g. switching tunnels) or to rotate credentials."- action={async () => { navigate('/pair'); }}- label="Open wizard"- />- </section>-- <section className="card card--padded">- <div className="action-group__heading">Support</div>- <ActionRow- icon={Package}- title="Generate diagnostic bundle"- desc="Zips agent.log, recent backups, redacted config, events, and system info to your Desktop. Safe to share — credentials are stripped."- action={async () => {- const res = await local.diag();- if (res?.path) {- // Open the parent folder so the user sees the- // newly-created zip in Explorer rather than- // opening the zip itself.- const parent = res.path.replace(/[\\/][^\\/]*$/, '');- await local.open({ path: parent });- }- }}- label="Generate"- />- </section>- </div>- );-}diff --git a/agent/ui/src/pages/Activity.jsx b/agent/ui/src/pages/Activity.jsxdeleted file mode 100644index 8f74fb93..00000000--- a/agent/ui/src/pages/Activity.jsx+++ /dev/null@@ -1,134 +0,0 @@-import { useMemo, useState } from 'react';-import {- Power,- Square,- RefreshCw,- Plug,- PlugZap,- AlertTriangle,- XCircle,- Info,-} from 'lucide-react';-import { useEvents } from '../ipc/hooks.js';--// Maps backend event Kind → React icon. Anything unrecognized falls through-// to the Info bubble so future kinds render gracefully without a UI patch.-const KIND_ICON = {- service_start: Power,- service_stop: Square,- restart_requested: RefreshCw,- ws_connected: PlugZap,- ws_disconnected: Plug,- ws_reconnecting: RefreshCw,- auth_failed: XCircle,- error: AlertTriangle,- info: Info,-};--const SEVERITIES = ['all', 'info', 'warn', 'error'];--function formatRelative(ts) {- const diffMs = Date.now() - ts;- const sec = Math.floor(diffMs / 1000);- if (sec < 5) return 'just now';- if (sec < 60) return `${sec}s ago`;- const min = Math.floor(sec / 60);- if (min < 60) return `${min}m ago`;- const hr = Math.floor(min / 60);- if (hr < 24) return `${hr}h ago`;- const day = Math.floor(hr / 24);- return `${day}d ago`;-}--function formatAbsolute(ts) {- const d = new Date(ts);- return d.toLocaleString();-}--function EventRow({ event }) {- const Icon = KIND_ICON[event.kind] || Info;- return (- <li className={`event event--${event.sev || 'info'}`}>- <div className="event__icon">- <Icon size={16} />- </div>- <div className="event__body">- <div className="event__msg">{event.msg}</div>- {event.meta && Object.keys(event.meta).length > 0 && (- <div className="event__meta">- {Object.entries(event.meta).map(([k, v]) => (- <span key={k} className="event__meta-item">- <strong>{k}:</strong> {String(v)}- </span>- ))}- </div>- )}- </div>- <time className="event__time" title={formatAbsolute(event.t)}>- {formatRelative(event.t)}- </time>- </li>- );-}--export default function Activity() {- const { events, error } = useEvents(3000);- const [filter, setFilter] = useState('all');-- const visible = useMemo(() => {- const list = filter === 'all'- ? events- : events.filter((e) => (e.sev || 'info') === filter);- // Newest first reads better as a timeline.- return [...list].reverse();- }, [events, filter]);-- return (- <div className="page">- <header className="page__header">- <div>- <h1 className="page__title">Activity</h1>- <p className="page__sub muted">- Lifecycle events from this agent — service starts, connection changes, and operator actions.- </p>- </div>- <div className="filter-group">- {SEVERITIES.map((sev) => (- <button- key={sev}- type="button"- className={- 'chip' + (filter === sev ? ' chip--active' : '')- }- onClick={() => setFilter(sev)}- >- {sev}- </button>- ))}- </div>- </header>-- {error && (- <div className="banner banner--warn">- Can't reach the agent IPC server. ({error})- </div>- )}-- <section className="card card--padded">- {visible.length === 0 ? (- <div className="empty-state">- {events.length === 0- ? 'No events yet — they\'ll appear here as the agent connects, restarts, or hits errors.'- : `Nothing matches the “${filter}” filter.`}- </div>- ) : (- <ul className="event-list">- {visible.map((ev) => (- <EventRow key={ev.id} event={ev} />- ))}- </ul>- )}- </section>- </div>- );-}diff --git a/agent/ui/src/pages/Logs.jsx b/agent/ui/src/pages/Logs.jsxdeleted file mode 100644index 9cd44833..00000000--- a/agent/ui/src/pages/Logs.jsx+++ /dev/null@@ -1,185 +0,0 @@-import { useEffect, useMemo, useRef, useState } from 'react';-import { Trash2, Search } from 'lucide-react';-import { useLogs } from '../ipc/hooks.js';-import { ipc } from '../ipc/client.js';--const LEVELS = ['all', 'info', 'warn', 'error'];--// Each line is one JSON object emitted by slog. Tolerate plain text too —-// during early boot the lumberjack rotation can produce a mixed file.-function parseLine(raw) {- try {- const obj = JSON.parse(raw);- return {- time: obj.time || '',- level: (obj.level || 'INFO').toLowerCase(),- msg: obj.msg || '',- component: obj.component || '',- extras: extractExtras(obj),- raw,- };- } catch {- return { time: '', level: 'info', msg: raw, component: '', extras: {}, raw };- }-}--function extractExtras(obj) {- const skip = new Set(['time', 'level', 'msg', 'component']);- const out = {};- for (const [k, v] of Object.entries(obj)) {- if (!skip.has(k)) out[k] = v;- }- return out;-}--function formatTime(iso) {- if (!iso) return '';- // ISO strings are long; surface only HH:MM:SS plus milliseconds.- const m = /T(\d{2}:\d{2}:\d{2}\.\d{3})/.exec(iso);- return m ? m[1] : iso;-}--function LogRow({ entry }) {- const lvl = entry.level || 'info';- return (- <div className={`logrow logrow--${lvl}`}>- <span className="logrow__time">{formatTime(entry.time)}</span>- <span className={`logrow__level logrow__level--${lvl}`}>{lvl}</span>- {entry.component && <span className="logrow__component">{entry.component}</span>}- <span className="logrow__msg">{entry.msg}</span>- {Object.keys(entry.extras).length > 0 && (- <span className="logrow__extras">- {Object.entries(entry.extras).map(([k, v]) => (- <span key={k}>- <em>{k}=</em>- <code>{typeof v === 'string' ? v : JSON.stringify(v)}</code>- </span>- ))}- </span>- )}- </div>- );-}--export default function Logs() {- const { lines, error } = useLogs(500, 2000);- const [filter, setFilter] = useState('all');- const [query, setQuery] = useState('');- const [autoScroll, setAutoScroll] = useState(true);- const [clearing, setClearing] = useState(false);- const scrollerRef = useRef(null);-- const parsed = useMemo(() => lines.map(parseLine), [lines]);-- const visible = useMemo(() => {- const q = query.trim().toLowerCase();- return parsed.filter((e) => {- if (filter !== 'all' && e.level !== filter) return false;- if (q && !e.raw.toLowerCase().includes(q)) return false;- return true;- });- }, [parsed, filter, query]);-- // Auto-scroll on new lines unless the user has scrolled up. Conservative- // heuristic: if the scroller is within 100 px of the bottom we treat the- // user as "following" the tail.- useEffect(() => {- if (!autoScroll || !scrollerRef.current) return;- const el = scrollerRef.current;- el.scrollTop = el.scrollHeight;- }, [visible.length, autoScroll]);-- function onScroll() {- if (!scrollerRef.current) return;- const el = scrollerRef.current;- const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 100;- setAutoScroll(atBottom);- }-- async function handleClear() {- if (clearing) return;- setClearing(true);- try {- await ipc.clearLogs();- } catch (err) {- // Surface the failure on the auto-scroll banner area; full error- // reporting comes when we add toast notifications later.- console.error('clearLogs failed', err);- } finally {- setClearing(false);- }- }-- return (- <div className="page page--full">- <header className="page__header">- <div>- <h1 className="page__title">Logs</h1>- <p className="page__sub muted">- Live tail of agent.log — last {lines.length} lines.- </p>- </div>- <div className="filter-group">- {LEVELS.map((l) => (- <button- key={l}- type="button"- className={'chip' + (filter === l ? ' chip--active' : '')}- onClick={() => setFilter(l)}- >- {l}- </button>- ))}- </div>- </header>-- <div className="toolbar">- <div className="search">- <Search size={14} />- <input- type="text"- placeholder="Search…"- value={query}- onChange={(e) => setQuery(e.target.value)}- spellCheck={false}- />- </div>- <div className="toolbar__spacer" />- <button- type="button"- className="btn btn--danger"- onClick={handleClear}- disabled={clearing}- title="Rotates agent.log to a backup file"- >- <Trash2 size={14} />- {clearing ? 'Clearing…' : 'Clear'}- </button>- </div>-- {error && (- <div className="banner banner--warn">- Can't reach the agent IPC server. ({error})- </div>- )}-- <div className="log-viewer" ref={scrollerRef} onScroll={onScroll}>- {visible.length === 0 ? (- <div className="empty-state empty-state--log">- {lines.length === 0- ? 'Waiting for log lines…'- : `No matches for "${query}" / ${filter}`}- </div>- ) : (- visible.map((entry, i) => <LogRow key={i} entry={entry} />)- )}- </div>-- {!autoScroll && (- <div className="follow-pill" onClick={() => setAutoScroll(true)}>- Resume tail ↓- </div>- )}- </div>- );-}diff --git a/agent/ui/src/pages/Overview.jsx b/agent/ui/src/pages/Overview.jsxdeleted file mode 100644index 21a2379e..00000000--- a/agent/ui/src/pages/Overview.jsx+++ /dev/null@@ -1,154 +0,0 @@-import { useEffect, useState } from 'react';-import { Copy, Check } from 'lucide-react';-import { LineChart, Line, ResponsiveContainer, YAxis } from 'recharts';-import { useStatus, useMetricsHistory } from '../ipc/hooks.js';--function StatusPill({ status }) {- if (!status) return <span className="pill pill--muted">Loading…</span>;- if (!status.registered) return <span className="pill pill--warn">Not paired</span>;- if (status.connected) return <span className="pill pill--ok">Connected</span>;- if (status.running) return <span className="pill pill--warn">Reconnecting</span>;- return <span className="pill pill--muted">Stopped</span>;-}--function CopyButton({ value }) {- const [copied, setCopied] = useState(false);- if (!value) return null;- return (- <button- type="button"- className="copy-btn"- onClick={() => {- navigator.clipboard.writeText(value);- setCopied(true);- setTimeout(() => setCopied(false), 1200);- }}- title={copied ? 'Copied!' : 'Copy'}- >- {copied ? <Check size={14} /> : <Copy size={14} />}- </button>- );-}--function formatUptime(seconds) {- if (!seconds || seconds < 0) return '—';- const s = Math.floor(seconds);- const days = Math.floor(s / 86400);- const hours = Math.floor((s % 86400) / 3600);- const minutes = Math.floor((s % 3600) / 60);- if (days > 0) return `${days}d ${hours}h`;- if (hours > 0) return `${hours}h ${minutes}m`;- if (minutes > 0) return `${minutes}m ${s % 60}s`;- return `${s}s`;-}--function Sparkline({ data, dataKey, accent }) {- if (!data || data.length === 0) {- return <div className="sparkline sparkline--empty">collecting samples…</div>;- }- return (- <div className="sparkline">- <ResponsiveContainer width="100%" height={64}>- <LineChart data={data} margin={{ top: 4, right: 4, bottom: 4, left: 4 }}>- <YAxis hide domain={[0, 100]} />- <Line- type="monotone"- dataKey={dataKey}- stroke={accent}- strokeWidth={2}- dot={false}- isAnimationActive={false}- />- </LineChart>- </ResponsiveContainer>- </div>- );-}--export default function Overview() {- const { status, error: statusError } = useStatus(2000);- const { samples } = useMetricsHistory(2000);-- // Recharts wants plain objects; flatten the IPC payload.- const chartData = samples.map((s) => ({- t: s.t,- cpu: s.cpu,- mem: s.mem,- }));-- const lastCpu = chartData.length ? chartData[chartData.length - 1].cpu : status?.cpu_percent;- const lastMem = chartData.length ? chartData[chartData.length - 1].mem : status?.mem_percent;-- return (- <div className="page">- <header className="page__header">- <div>- <h1 className="page__title">{status?.agent_name || 'Agent'}</h1>- <div className="page__sub">- <StatusPill status={status} />- {status?.version && <span className="muted">v{status.version}</span>}- </div>- </div>- </header>-- {statusError && (- <div className="banner banner--warn">- Can't reach the agent IPC server. Is the service running? ({statusError})- </div>- )}-- <section className="card">- <h2 className="card__title">Connection</h2>- <div className="info-row">- <span className="info-row__label">Server URL</span>- <span className="info-row__value info-row__value--mono">- {status?.server_url || '—'}- <CopyButton value={status?.server_url} />- </span>- </div>- <div className="info-row">- <span className="info-row__label">Agent ID</span>- <span className="info-row__value info-row__value--mono">- {status?.agent_id || '—'}- <CopyButton value={status?.agent_id} />- </span>- </div>- <div className="info-row">- <span className="info-row__label">Transport</span>- <span className="info-row__value">- {status?.transport === 'poll' ? 'Polling (REST fallback)' : 'WebSocket'}- </span>- </div>- <div className="info-row">- <span className="info-row__label">Agent version</span>- <span className="info-row__value">{status?.version ? `v${status.version}` : '—'}</span>- </div>- <div className="info-row">- <span className="info-row__label">Uptime</span>- <span className="info-row__value">{formatUptime(status?.uptime_seconds)}</span>- </div>- </section>-- <section className="metrics">- <div className="card metric-card">- <div className="metric-card__head">- <h2 className="card__title">CPU</h2>- <span className="metric-card__value">- {lastCpu != null ? `${lastCpu.toFixed(1)}%` : '—'}- </span>- </div>- <Sparkline data={chartData} dataKey="cpu" accent="#6366f1" />- </div>- <div className="card metric-card">- <div className="metric-card__head">- <h2 className="card__title">Memory</h2>- <span className="metric-card__value">- {lastMem != null ? `${lastMem.toFixed(1)}%` : '—'}- </span>- </div>- <Sparkline data={chartData} dataKey="mem" accent="#10b981" />- </div>- </section>- </div>- );-}diff --git a/agent/ui/src/pages/Pair.jsx b/agent/ui/src/pages/Pair.jsxdeleted file mode 100644index 34d49eec..00000000--- a/agent/ui/src/pages/Pair.jsx+++ /dev/null@@ -1,356 +0,0 @@-import { useEffect, useRef, useState } from 'react';-import { useNavigate } from 'react-router-dom';-import { Copy, Check, Server, ArrowRight, Loader2, CircleCheck, AlertTriangle } from 'lucide-react';-import { local } from '../ipc/client.js';--// Three-stage React port of the legacy walk wizard. The actual pairing-// protocol still runs in Go via internal/pairdriver — this component just-// drives the form, kicks off /local/pair/start, polls /local/pair/state,-// and renders whatever stage the backend reports.--function CopyValue({ value, large }) {- const [copied, setCopied] = useState(false);- return (- <div className={'copy-value ' + (large ? 'copy-value--large' : '')}>- <span className="copy-value__text">{value}</span>- <button- type="button"- className="copy-btn"- onClick={() => {- navigator.clipboard.writeText(value);- setCopied(true);- setTimeout(() => setCopied(false), 1200);- }}- title={copied ? 'Copied!' : 'Copy'}- >- {copied ? <Check size={16} /> : <Copy size={16} />}- </button>- </div>- );-}--function FormStage({ onConnectionString, onPairCode, busy, defaultName }) {- // Default to the connection-string tab — that's the modern entry path- // (one paste, one click). The legacy pair-code form stays available- // for users who already started from the panel's "Pair existing- // agent" tab, or who can't paste from clipboard for some reason.- const [mode, setMode] = useState('connection-string');- const [connString, setConnString] = useState('');- const [panelUrl, setPanelUrl] = useState('');- const [name, setName] = useState(defaultName || '');- const [error, setError] = useState('');-- function submitConnString(e) {- e.preventDefault();- const trimmed = connString.trim();- if (!trimmed) {- setError('Paste the connection string from your panel.');- return;- }- if (!trimmed.startsWith('sk1://')) {- setError('That doesn’t look like a connection string. Generate one from the panel’s Add Server screen.');- return;- }- setError('');- onConnectionString(trimmed);- }-- function submitPairCode(e) {- e.preventDefault();- if (!panelUrl.trim()) {- setError('Panel URL is required');- return;- }- setError('');- onPairCode(panelUrl.trim(), name.trim());- }-- return (- <div className="wizard">- <div className="wizard__head">- <div className="wizard__brand">- <Server size={28} />- </div>- <h1 className="wizard__title">Pair this server</h1>- <p className="wizard__sub">Connect this machine to your ServerKit panel.</p>- </div>-- <div className="wizard__tabs" role="tablist">- <button- type="button"- role="tab"- aria-selected={mode === 'connection-string'}- className={'wizard__tab ' + (mode === 'connection-string' ? 'is-active' : '')}- onClick={() => { setMode('connection-string'); setError(''); }}- >- Connection string- </button>- <button- type="button"- role="tab"- aria-selected={mode === 'pair-code'}- className={'wizard__tab ' + (mode === 'pair-code' ? 'is-active' : '')}- onClick={() => { setMode('pair-code'); setError(''); }}- >- Pair code- </button>- </div>-- {mode === 'connection-string' ? (- <form onSubmit={submitConnString} className="wizard__body">- <label className="field">- <span className="field__label">Connection string</span>- <textarea- className="field__input field__input--mono"- rows={4}- placeholder="sk1://panel.example.com/sk_reg_..."- value={connString}- onChange={(e) => setConnString(e.target.value)}- autoFocus- spellCheck={false}- />- <span className="field__hint">- Generate it in the panel: <strong>Add Server → Connection string</strong>.- The hostname of this machine becomes the server name automatically.- </span>- </label>-- {error && <div className="banner banner--warn">{error}</div>}-- <button type="submit" className="btn btn--primary btn--large" disabled={busy}>- {busy ? (- <><Loader2 size={16} className="spin" /> Connecting…</>- ) : (- <>Connect <ArrowRight size={16} /></>- )}- </button>- </form>- ) : (- <form onSubmit={submitPairCode} className="wizard__body">- <label className="field">- <span className="field__label">Panel URL</span>- <input- type="text"- className="field__input"- placeholder="https://panel.example.com"- value={panelUrl}- onChange={(e) => setPanelUrl(e.target.value)}- autoFocus- spellCheck={false}- />- <span className="field__hint">The full URL of your ServerKit control panel.</span>- </label>-- <label className="field">- <span className="field__label">Server name <span className="muted">(optional)</span></span>- <input- type="text"- className="field__input"- placeholder="Defaults to hostname"- value={name}- onChange={(e) => setName(e.target.value)}- spellCheck={false}- />- <span className="field__hint">How this machine appears in your panel.</span>- </label>-- {error && <div className="banner banner--warn">{error}</div>}-- <button type="submit" className="btn btn--primary btn--large" disabled={busy}>- {busy ? (- <><Loader2 size={16} className="spin" /> Connecting…</>- ) : (- <>Connect <ArrowRight size={16} /></>- )}- </button>- </form>- )}- </div>- );-}--function PairCodeStage({ state, onCancel }) {- return (- <div className="wizard">- <div className="wizard__head">- <h1 className="wizard__title">Enter both values in your panel</h1>- <p className="wizard__sub">- On your panel, open <strong>Add Server → Pair existing agent</strong>, then type these in.- </p>- </div>-- <div className="wizard__body">- <div className="pair-display">- <div className="pair-display__label">Pair code</div>- <CopyValue value={state.code_formatted || state.code} large />- </div>- <div className="pair-display">- <div className="pair-display__label">Passphrase</div>- <CopyValue value={state.passphrase} />- </div>-- <div className="wizard__status">- <Loader2 size={14} className="spin" />- <span>Waiting for the panel to claim this server…</span>- </div>-- <button type="button" className="btn" onClick={onCancel}>- Cancel- </button>- </div>- </div>- );-}--function DoneStage({ state, onContinue }) {- return (- <div className="wizard">- <div className="wizard__head">- <div className="wizard__brand wizard__brand--ok">- <CircleCheck size={28} />- </div>- <h1 className="wizard__title">Successfully paired</h1>- <p className="wizard__sub">- This machine is now connected to ServerKit as <strong>{state.server_name || 'this server'}</strong>.- </p>- </div>-- <div className="wizard__body">- <p className="muted" style={{ textAlign: 'center', margin: 0 }}>- The agent service has been restarted with the new configuration.- </p>- <button type="button" className="btn btn--primary btn--large" onClick={onContinue}>- Open console <ArrowRight size={16} />- </button>- </div>- </div>- );-}--function ErrorStage({ state, onRetry }) {- return (- <div className="wizard">- <div className="wizard__head">- <div className="wizard__brand wizard__brand--err">- <AlertTriangle size={28} />- </div>- <h1 className="wizard__title">Pairing failed</h1>- </div>-- <div className="wizard__body">- <div className="banner banner--warn">{state.error || 'Unknown error'}</div>- <button type="button" className="btn btn--primary btn--large" onClick={onRetry}>- Try again- </button>- </div>- </div>- );-}--export default function Pair() {- const navigate = useNavigate();- const [state, setState] = useState({ state: 'idle' });- const [busy, setBusy] = useState(false);- const pollRef = useRef(null);-- // Poll /local/pair/state once a second while the wizard is open. The- // initial fetch on mount also covers the case where the user closed and- // reopened the console mid-pairing — we land back on the right stage.- useEffect(() => {- let cancelled = false;- async function tick() {- try {- const s = await local.pairState();- if (!cancelled) setState(s);- } catch {- // Asset server is in the same process — if it's gone, the- // window is closing anyway.- }- }- tick();- pollRef.current = setInterval(tick, 1000);- return () => {- cancelled = true;- clearInterval(pollRef.current);- };- }, []);-- async function handlePairCode(panelUrl, name) {- setBusy(true);- try {- await local.pairStart(panelUrl, name);- const s = await local.pairState();- setState(s);- } catch (err) {- setState({ state: 'error', error: err.message });- } finally {- setBusy(false);- }- }-- async function handleConnectionString(value) {- setBusy(true);- try {- await local.pairConnectionString(value);- // Optimistic transition: the agent's poll loop will catch up- // and report claimed/error within a second or two, but moving- // off the form right away keeps the UI from feeling stuck.- setState({ state: 'enrolling' });- } catch (err) {- setState({ state: 'error', error: err.message });- } finally {- setBusy(false);- }- }-- async function handleCancel() {- await local.pairCancel();- setState({ state: 'idle' });- }-- if (state.state === 'claimed') {- return <DoneStage state={state} onContinue={() => navigate('/overview')} />;- }- if (state.state === 'error') {- return <ErrorStage state={state} onRetry={() => setState({ state: 'idle' })} />;- }- if (state.state === 'enrolling' || state.state === 'waiting') {- // The pair-code wizard shows a code+passphrase pane, but the- // connection-string flow has nothing for the user to copy at this- // stage — it's just "wait for /register to come back." Pick the- // pane based on whether we have a code yet.- if (state.code || state.code_formatted) {- return <PairCodeStage state={state} onCancel={handleCancel} />;- }- return <ConnectingStage onCancel={handleCancel} />;- }- return (- <FormStage- onConnectionString={handleConnectionString}- onPairCode={handlePairCode}- busy={busy}- />- );-}--function ConnectingStage({ onCancel }) {- return (- <div className="wizard">- <div className="wizard__head">- <h1 className="wizard__title">Registering this server…</h1>- <p className="wizard__sub">- Talking to the panel and saving credentials. This usually takes a few seconds.- </p>- </div>- <div className="wizard__body">- <div className="wizard__status">- <Loader2 size={14} className="spin" />- <span>Waiting for the panel to confirm registration…</span>- </div>- <button type="button" className="btn" onClick={onCancel}>- Cancel- </button>- </div>- </div>- );-}diff --git a/agent/ui/src/styles/_tokens.scss b/agent/ui/src/styles/_tokens.scssdeleted file mode 100644index ed086e3e..00000000--- a/agent/ui/src/styles/_tokens.scss+++ /dev/null@@ -1,34 +0,0 @@-// Agent console design tokens. Mirrors the panel's dark theme so the two-// products feel like one. The agent UI is dark-only for now — the wizard and-// console live in the system tray context where consistent contrast matters-// more than user theme preference.--$bg-body: #09090b;-$bg-sidebar: #0f0f11;-$bg-card: #18181b;-$bg-elevated: #1f1f23;-$bg-hover: #27272a;--$border-default: #27272a;-$border-subtle: #1f1f23;-$border-active: #3f3f46;--$text-primary: #f4f4f5;-$text-secondary: #a1a1aa;-$text-tertiary: #71717a;--$accent: #6366f1;-$accent-hover: #818cf8;-$success: #10b981;-$warning: #f59e0b;-$danger: #ef4444;--$radius-sm: 6px;-$radius-md: 10px;-$radius-lg: 14px;--$space-xs: 4px;-$space-sm: 8px;-$space-md: 16px;-$space-lg: 24px;-$space-xl: 32px;diff --git a/agent/ui/src/styles/main.scss b/agent/ui/src/styles/main.scssdeleted file mode 100644index 06f35b8f..00000000--- a/agent/ui/src/styles/main.scss+++ /dev/null@@ -1,940 +0,0 @@-@use './tokens' as *;--* {- box-sizing: border-box;-}--html,-body,-#root {- margin: 0;- height: 100%;- width: 100%;- background: $bg-body;- color: $text-primary;- font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;- font-size: 14px;- line-height: 1.5;- -webkit-font-smoothing: antialiased;-}--button {- font-family: inherit;-}--a {- color: $accent;- text-decoration: none;-}--.muted {- color: $text-tertiary;-}--// ─── App shell ───────────────────────────────────────────────────────────--.shell {- display: grid;- grid-template-columns: 220px 1fr;- height: 100vh;- width: 100vw;- overflow: hidden;-}--.shell__main {- overflow-y: auto;- background: $bg-body;-}--// ─── Sidebar ─────────────────────────────────────────────────────────────--.sidebar {- background: $bg-sidebar;- border-right: 1px solid $border-default;- display: flex;- flex-direction: column;- padding: $space-md;- gap: $space-lg;-}--.sidebar__brand {- display: flex;- align-items: center;- gap: $space-sm;- padding: $space-sm 4px;-}--.sidebar__brand-icon {- width: 32px;- height: 32px;- border-radius: $radius-sm;- background: linear-gradient(135deg, $accent, #8b5cf6);- display: grid;- place-items: center;- color: white;-}--.sidebar__brand-name {- font-weight: 600;- color: $text-primary;- line-height: 1.2;-}--.sidebar__brand-sub {- font-size: 11px;- color: $text-tertiary;- text-transform: uppercase;- letter-spacing: 0.08em;- line-height: 1.2;- margin-top: 2px;-}--.sidebar__nav {- display: flex;- flex-direction: column;- gap: 2px;-}--.sidebar__link {- display: flex;- align-items: center;- gap: $space-sm;- padding: 8px 10px;- border-radius: $radius-sm;- color: $text-secondary;- font-size: 13px;- font-weight: 500;- transition: background 120ms, color 120ms;-- &:hover {- background: $bg-hover;- color: $text-primary;- }-- &--active {- background: $bg-elevated;- color: $text-primary;- }-}--.sidebar__footer {- margin-top: auto;- padding: $space-sm 4px 4px;- display: flex;- align-items: center;- justify-content: space-between;- gap: $space-sm;-}--.sidebar__version {- font-size: 11px;- color: $text-tertiary;- letter-spacing: 0.04em;-}--.sidebar__transport {- font-size: 10px;- text-transform: uppercase;- letter-spacing: 0.08em;- color: #c7d2fe;- background: #312e81;- border: 1px solid #4338ca;- padding: 2px 6px;- border-radius: $radius-sm;-}--// ─── Page ────────────────────────────────────────────────────────────────--.page {- padding: $space-xl;- max-width: 980px;- margin: 0 auto;- display: flex;- flex-direction: column;- gap: $space-lg;-- &--full {- max-width: none;- height: 100vh;- padding: $space-lg $space-xl;- }-}--.page__header {- display: flex;- align-items: flex-start;- justify-content: space-between;- gap: $space-md;-}--.page__title {- margin: 0 0 6px;- font-size: 22px;- font-weight: 600;- letter-spacing: -0.01em;-}--.page__sub {- margin: 0;- display: flex;- gap: $space-sm;- align-items: center;- font-size: 13px;-}--// ─── Cards ───────────────────────────────────────────────────────────────--.card {- background: $bg-card;- border: 1px solid $border-default;- border-radius: $radius-md;- padding: $space-lg;- display: flex;- flex-direction: column;- gap: $space-md;-}--.card__title {- margin: 0;- font-size: 12px;- font-weight: 600;- color: $text-tertiary;- text-transform: uppercase;- letter-spacing: 0.08em;-}--.empty-state {- color: $text-secondary;- font-size: 13px;- line-height: 1.6;-}--// ─── Pills ───────────────────────────────────────────────────────────────--.pill {- display: inline-flex;- align-items: center;- gap: 6px;- padding: 3px 10px;- border-radius: 999px;- font-size: 12px;- font-weight: 500;- line-height: 1.4;-- &::before {- content: '';- width: 6px;- height: 6px;- border-radius: 50%;- background: currentColor;- }-- &--ok {- background: rgba($success, 0.12);- color: $success;- }- &--warn {- background: rgba($warning, 0.15);- color: $warning;- }- &--muted {- background: $bg-hover;- color: $text-tertiary;- }-}--// ─── Banner ──────────────────────────────────────────────────────────────--.banner {- border-radius: $radius-md;- padding: 12px 16px;- font-size: 13px;- border: 1px solid;- display: flex;- gap: $space-sm;- align-items: flex-start;-- &--warn {- background: rgba($warning, 0.08);- border-color: rgba($warning, 0.3);- color: lighten($warning, 12%);- }-}--// ─── Info rows ───────────────────────────────────────────────────────────--.info-row {- display: flex;- align-items: center;- justify-content: space-between;- gap: $space-md;- padding: 10px 0;- border-bottom: 1px solid $border-subtle;-- &:last-child {- border-bottom: none;- }-}--.info-row__label {- font-size: 12px;- color: $text-tertiary;- text-transform: uppercase;- letter-spacing: 0.06em;-}--.info-row__value {- color: $text-primary;- font-size: 13px;- display: flex;- align-items: center;- gap: 6px;- text-align: right;- word-break: break-all;-- &--mono {- font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;- font-size: 12px;- }-}--.copy-btn {- background: transparent;- border: 1px solid $border-default;- color: $text-tertiary;- border-radius: $radius-sm;- padding: 4px 6px;- cursor: pointer;- display: inline-flex;- align-items: center;- transition: color 120ms, border-color 120ms;-- &:hover {- color: $text-primary;- border-color: $border-active;- }-}--// ─── Metrics ─────────────────────────────────────────────────────────────--.metrics {- display: grid;- grid-template-columns: 1fr 1fr;- gap: $space-md;-}--.metric-card {- gap: $space-sm;-}--.metric-card__head {- display: flex;- justify-content: space-between;- align-items: baseline;-}--.metric-card__value {- font-size: 24px;- font-weight: 600;- font-variant-numeric: tabular-nums;- color: $text-primary;-}--.sparkline {- margin: 0 -8px;-- &--empty {- height: 64px;- display: grid;- place-items: center;- color: $text-tertiary;- font-size: 12px;- }-}--// ─── Filter chips ────────────────────────────────────────────────────────--.filter-group {- display: flex;- gap: 4px;-}--.chip {- background: $bg-card;- border: 1px solid $border-default;- color: $text-secondary;- border-radius: 999px;- padding: 4px 12px;- font-size: 12px;- font-weight: 500;- cursor: pointer;- text-transform: capitalize;- transition: all 120ms;-- &:hover {- color: $text-primary;- border-color: $border-active;- }-- &--active {- background: $bg-elevated;- color: $text-primary;- border-color: $border-active;- }-}--// ─── Activity timeline ───────────────────────────────────────────────────--.card--padded {- padding: 0;- overflow: hidden;-}--.event-list {- list-style: none;- margin: 0;- padding: 0;-}--.event {- display: grid;- grid-template-columns: 32px 1fr auto;- gap: $space-md;- padding: 14px 18px;- border-bottom: 1px solid $border-subtle;- align-items: flex-start;-- &:last-child {- border-bottom: none;- }-- &__icon {- width: 32px;- height: 32px;- border-radius: $radius-sm;- display: grid;- place-items: center;- background: $bg-elevated;- color: $text-secondary;- flex-shrink: 0;- }-- &__body {- min-width: 0;- }-- &__msg {- color: $text-primary;- font-size: 13px;- line-height: 1.4;- }-- &__meta {- display: flex;- flex-wrap: wrap;- gap: 8px 14px;- margin-top: 4px;- font-size: 11px;- color: $text-tertiary;- }-- &__meta-item {- word-break: break-all;-- strong {- font-weight: 600;- color: $text-secondary;- margin-right: 4px;- }- }-- &__time {- font-size: 11px;- color: $text-tertiary;- white-space: nowrap;- font-variant-numeric: tabular-nums;- }-- &--warn {- .event__icon {- background: rgba($warning, 0.1);- color: $warning;- }- }-- &--error {- .event__icon {- background: rgba($danger, 0.1);- color: $danger;- }- }-}--// ─── Buttons ─────────────────────────────────────────────────────────────--.btn {- background: $bg-elevated;- color: $text-primary;- border: 1px solid $border-default;- border-radius: $radius-sm;- padding: 7px 14px;- font-size: 13px;- font-weight: 500;- display: inline-flex;- align-items: center;- gap: 6px;- cursor: pointer;- transition: all 120ms;-- &:hover:not(:disabled) {- border-color: $border-active;- background: $bg-hover;- }-- &:disabled {- opacity: 0.5;- cursor: not-allowed;- }-- &--primary {- background: $accent;- color: white;- border-color: $accent;-- &:hover:not(:disabled) {- background: $accent-hover;- border-color: $accent-hover;- }- }-- &--danger {- color: $danger;-- &:hover:not(:disabled) {- border-color: rgba($danger, 0.5);- background: rgba($danger, 0.08);- }- }-}--// ─── Toolbar (Logs page top strip) ───────────────────────────────────────--.toolbar {- display: flex;- align-items: center;- gap: $space-sm;-}--.toolbar__spacer {- flex: 1;-}--.search {- display: flex;- align-items: center;- gap: 6px;- background: $bg-card;- border: 1px solid $border-default;- border-radius: $radius-sm;- padding: 6px 10px;- color: $text-tertiary;- flex: 0 0 280px;-- input {- background: transparent;- border: none;- outline: none;- color: $text-primary;- flex: 1;- font-size: 13px;- font-family: inherit;- }-}--// ─── Log viewer ──────────────────────────────────────────────────────────--.log-viewer {- flex: 1;- background: $bg-card;- border: 1px solid $border-default;- border-radius: $radius-md;- overflow-y: auto;- font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;- font-size: 12px;- line-height: 1.5;- padding: 10px 12px;-}--.empty-state--log {- padding: 32px 0;- text-align: center;- color: $text-tertiary;- font-family: 'Segoe UI', system-ui, sans-serif;-}--.logrow {- display: grid;- grid-template-columns: 92px 60px auto auto 1fr;- gap: 8px;- padding: 4px 0;- border-bottom: 1px solid rgba($border-default, 0.4);- align-items: baseline;-- &:last-child {- border-bottom: none;- }-- &__time {- color: $text-tertiary;- font-variant-numeric: tabular-nums;- }-- &__level {- text-transform: uppercase;- font-size: 10px;- font-weight: 600;- letter-spacing: 0.04em;- padding: 1px 6px;- border-radius: 4px;- text-align: center;-- &--info {- background: rgba($accent, 0.12);- color: $accent-hover;- }- &--warn {- background: rgba($warning, 0.12);- color: $warning;- }- &--error {- background: rgba($danger, 0.12);- color: $danger;- }- }-- &__component {- color: $text-tertiary;- font-size: 11px;- white-space: nowrap;- }-- &__msg {- color: $text-primary;- word-break: break-word;- }-- &__extras {- grid-column: 5;- color: $text-tertiary;- font-size: 11px;-- > span {- margin-right: 12px;-- em {- font-style: normal;- color: $text-tertiary;- }- code {- color: $text-secondary;- }- }- }-- &--warn .logrow__msg {- color: lighten($warning, 12%);- }- &--error .logrow__msg {- color: lighten($danger, 8%);- }-}--.follow-pill {- position: fixed;- bottom: 24px;- right: 32px;- background: $accent;- color: white;- padding: 8px 14px;- border-radius: 999px;- font-size: 12px;- font-weight: 500;- cursor: pointer;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);-- &:hover {- background: $accent-hover;- }-}--// ─── Actions tab ─────────────────────────────────────────────────────────--.action-group__heading {- padding: 14px 18px 8px;- font-size: 11px;- font-weight: 600;- color: $text-tertiary;- text-transform: uppercase;- letter-spacing: 0.08em;-}--// ─── Wizard ──────────────────────────────────────────────────────────────--.wizard {- width: 100%;- height: 100vh;- display: grid;- place-items: center;- padding: $space-xl;- background:- radial-gradient(1200px 600px at 50% -10%, rgba($accent, 0.08), transparent),- $bg-body;-}--.wizard > .wizard__head + .wizard__body,-.wizard > .wizard__head,-.wizard > .wizard__body {- width: 100%;-}--.wizard__head {- text-align: center;- margin-bottom: $space-lg;-}--.wizard__brand {- width: 56px;- height: 56px;- border-radius: $radius-md;- background: linear-gradient(135deg, $accent, #8b5cf6);- color: white;- display: grid;- place-items: center;- margin: 0 auto 16px;-- &--ok {- background: linear-gradient(135deg, $success, #34d399);- }-- &--err {- background: linear-gradient(135deg, $danger, #f87171);- }-}--.wizard__title {- font-size: 24px;- font-weight: 600;- margin: 0 0 8px;- letter-spacing: -0.01em;-}--.wizard__sub {- color: $text-secondary;- margin: 0;- line-height: 1.55;-}--.wizard__body {- background: $bg-card;- border: 1px solid $border-default;- border-radius: $radius-lg;- padding: $space-xl;- display: flex;- flex-direction: column;- gap: $space-md;- max-width: 460px;- margin: 0 auto;-}--.wizard__status {- display: flex;- align-items: center;- justify-content: center;- gap: 8px;- color: $text-tertiary;- font-size: 13px;- padding: $space-sm 0;-}--// Tabs sit above the wizard body — let the user pick between the-// connection-string and pair-code entry paths. Keep them visually quiet-// so the form below remains the focal point.-.wizard__tabs {- display: flex;- gap: 4px;- max-width: 460px;- margin: 0 auto $space-sm;- padding: 4px;- background: $bg-elevated;- border: 1px solid $border-default;- border-radius: $radius-md;-}--.wizard__tab {- flex: 1;- padding: 8px 12px;- border: 0;- border-radius: $radius-sm;- background: transparent;- color: $text-tertiary;- font-size: 13px;- font-weight: 600;- cursor: pointer;- transition: background 120ms, color 120ms;-- &:hover {- color: $text-primary;- }-- &.is-active {- background: $bg-card;- color: $text-primary;- box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2);- }-}--.field__input--mono {- font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;- font-size: 12px;- line-height: 1.5;- resize: vertical;- min-height: 80px;- word-break: break-all;-}--// Form fields used by the wizard-.field {- display: flex;- flex-direction: column;- gap: 6px;-}--.field__label {- font-size: 12px;- font-weight: 600;- color: $text-secondary;-}--.field__input {- background: $bg-elevated;- border: 1px solid $border-default;- border-radius: $radius-sm;- padding: 10px 12px;- color: $text-primary;- font-size: 14px;- font-family: inherit;- outline: none;- transition: border-color 120ms;-- &:focus {- border-color: $accent;- }-}--.field__hint {- font-size: 12px;- color: $text-tertiary;-}--// Inline copy-able value (pair code, passphrase)-.copy-value {- display: flex;- align-items: center;- justify-content: space-between;- background: $bg-elevated;- border: 1px solid $border-default;- border-radius: $radius-md;- padding: 14px 16px;- font-family: 'JetBrains Mono', 'Consolas', ui-monospace, monospace;-- &__text {- font-size: 18px;- font-weight: 600;- letter-spacing: 0.12em;- color: $text-primary;- }-- &--large {- .copy-value__text {- font-size: 28px;- color: $accent-hover;- letter-spacing: 0.2em;- }- }-}--.pair-display {- display: flex;- flex-direction: column;- gap: 6px;-- &__label {- font-size: 11px;- font-weight: 600;- color: $text-tertiary;- text-transform: uppercase;- letter-spacing: 0.08em;- }-}--.btn--large {- padding: 12px 20px;- font-size: 14px;- justify-content: center;-}--.spin {- animation: wizard-spin 0.9s linear infinite;-}--@keyframes wizard-spin {- to { transform: rotate(360deg); }-}--.action {- display: grid;- grid-template-columns: 36px 1fr auto;- gap: $space-md;- padding: 14px 18px;- border-top: 1px solid $border-subtle;- align-items: center;-- &__icon {- width: 36px;- height: 36px;- border-radius: $radius-sm;- background: $bg-elevated;- color: $text-secondary;- display: grid;- place-items: center;- }-- &__title {- font-size: 13px;- font-weight: 500;- color: $text-primary;- }-- &__desc {- font-size: 12px;- color: $text-tertiary;- margin-top: 2px;- }-- &__buttons {- display: flex;- align-items: center;- gap: 10px;- }-- &__feedback {- font-size: 12px;-- &--ok {- color: $success;- }- &--err {- color: $danger;- }- }-}diff --git a/agent/ui/vite.config.js b/agent/ui/vite.config.jsdeleted file mode 100644index 8edd47bb..00000000--- a/agent/ui/vite.config.js+++ /dev/null@@ -1,24 +0,0 @@-import { defineConfig } from 'vite';-import react from '@vitejs/plugin-react';--// The agent embeds the built dist directly into the Go binary via embed.FS,-// then serves it from a localhost HTTP server inside WebView2. Assets are-// referenced relatively so the served base URL doesn't matter.-export default defineConfig({- plugins: [react()],- base: './',- server: {- port: 5174,- strictPort: true,- },- build: {- // Output directly into the Go package that embeds it, so the only- // build orchestration is "npm run build" then "go build" — no- // separate copy step. The dir is gitignored; embed requires it to- // exist at compile time, so the Makefile / docs make the order- // explicit.- outDir: '../internal/agentui/dist',- emptyOutDir: true,- chunkSizeWarningLimit: 800,- },-});diff --git a/docs/AGENT_AUDIT.md b/docs/AGENT_AUDIT.mdindex 6778d5d9..f6c338f8 100644--- a/docs/AGENT_AUDIT.md+++ b/docs/AGENT_AUDIT.md@@ -1,5 +1,10 @@# ServerKit Agent Subsystem — Security & Completeness Audit+> **Migration note:** The Go agent source code has moved to its own repository at+> [`github.com/jhd3197/serverkit-agent`](https://github.com/jhd3197/serverkit-agent).+> This audit remains historically accurate but the file paths it references under+> `agent/` no longer exist in the ServerKit monorepo.+**Date:** 2026-06-12**Scope:** The multi-server agent fleet end-to-end — Go agent (`agent/`), panelgateway/registry/long-poll (`backend/app/agent_gateway.py`,diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex 217dca91..03896ba2 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -7,8 +7,9 @@ configures SELinux for the nginx reverse proxy. The manual steps below useUbuntu/Debian (`apt`) as the primary example — on Fedora/RHEL substitute `dnf`and the docker-ce RHEL repo.-To connect additional servers to this panel, install the agent — see-[agent/README.md](../agent/README.md) and [pairing.md](pairing.md). ServerKit is a modern server management panel for managing web applications, databases, Docker containers, and more.+To connect additional servers to this panel, install the agent — see the+[serverkit-agent README](https://github.com/jhd3197/serverkit-agent/blob/main/README.md)+and [pairing.md](pairing.md). ServerKit is a modern server management panel for managing web applications, databases, Docker containers, and more.## Table of Contentsdiff --git a/docs/README.md b/docs/README.mdindex 656d743f..3124c545 100644--- a/docs/README.md+++ b/docs/README.md@@ -14,7 +14,7 @@ Welcome to the ServerKit documentation. This guide will help you install, config| [Local Development](LOCAL_DEVELOPMENT.md) | Run the panel locally for development || [API Reference](API.md) | REST API documentation with examples || [Multi-Environment Guide](MULTI_ENVIRONMENT.md) | Set up prod/dev WordPress pairs with shared database |-| [Multi-Server & Agent](../agent/README.md) | Install the agent and connect remote servers (see also [pairing](pairing.md)) |+| [Multi-Server & Agent](https://github.com/jhd3197/serverkit-agent/blob/main/README.md) | Install the agent and connect remote servers (see also [pairing](pairing.md)) |---diff --git a/scripts/test/agent-test.ps1 b/scripts/test/agent-test.ps1deleted file mode 100644index 69b84a13..00000000--- a/scripts/test/agent-test.ps1+++ /dev/null@@ -1,92 +0,0 @@-#requires -Version 5.1-<#-.SYNOPSIS- Test Windows agent pairing against one of the test VMs.--.DESCRIPTION- Optional follow-on to full-stack-test.ps1 (which must be run with -Keep).- - Discovers a running sk-test-* VM- - Registers admin + obtains JWT- - Builds the agent (go build) and runs it against the VM- - Verifies pairing short-code flow and that capabilities arrive-- This is intentionally minimal -- it exercises the pairing happy path so- regressions in the agent <-> panel handshake get caught.--.PARAMETER VmName- Specific VM to target. Default: first sk-test-* VM found.-#>-[CmdletBinding()]-param(- [string] $VmName-)--$ErrorActionPreference = 'Stop'-$RepoRoot = (Resolve-Path "$PSScriptRoot\..\..").Path--if (-not (Get-Command multipass -ErrorAction SilentlyContinue)) {- Write-Error "Multipass not installed."- exit 2-}-if (-not (Get-Command go -ErrorAction SilentlyContinue)) {- Write-Error "Go is required to build the agent."- exit 2-}--if (-not $VmName) {- $VmName = (& multipass list --format csv | Select-String '^sk-test-' | Select-Object -First 1).ToString().Split(',')[0]-}-if (-not $VmName) {- Write-Error "No sk-test-* VM found. Run full-stack-test.ps1 -Keep first."- exit 2-}--$vmIp = (& multipass info $VmName --format csv | Select-String "^$VmName,").ToString().Split(',')[2]-Write-Host "Targeting VM: $VmName ($vmIp)" -ForegroundColor Cyan--# 1. Register admin and grab token-$cred = @{- email = "agent-test-$(Get-Random -Maximum 99999)@test.local"- username = "agentuser$(Get-Random -Maximum 99999)"- password = 'Test12345!'-}-$resp = Invoke-RestMethod -Uri "http://${vmIp}:5000/api/v1/auth/register" `- -Method Post -ContentType 'application/json' -Body ($cred | ConvertTo-Json)-$token = $resp.access_token-Write-Host " [OK] Admin registered, got JWT" -ForegroundColor Green--# 2. Build agent-$agentDir = Join-Path $RepoRoot 'agent'-if (-not (Test-Path $agentDir)) { Write-Error "agent/ not found at $agentDir"; exit 2 }-$agentBin = Join-Path $env:TEMP "serverkit-agent-test.exe"-Push-Location $agentDir-try {- Write-Host " Building agent..." -ForegroundColor Yellow- & go build -o $agentBin ./cmd/serverkit-agent- if ($LASTEXITCODE -ne 0) { throw "go build failed" }-} finally { Pop-Location }-Write-Host " [OK] Agent built: $agentBin" -ForegroundColor Green--# 3. Generate pairing short-code by enrolling from "agent side"-# (Normally the agent does this itself; here we drive it explicitly to test API.)-$enrollBody = @{- pubkey = ([System.BitConverter]::ToString((New-Object byte[] 32 | ForEach-Object { Get-Random -Maximum 256 })) -replace '-','').ToLower()- passphrase = 'test-passphrase'- machine_id = "test-$(Get-Random -Maximum 999999)"- system_info = @{ os = 'Windows'; hostname = $env:COMPUTERNAME }-} | ConvertTo-Json -Depth 5--$enroll = Invoke-RestMethod -Uri "http://${vmIp}:5000/api/v1/pairing/enroll" `- -Method Post -ContentType 'application/json' -Body $enrollBody-Write-Host " [OK] Enrolled, short-code: $($enroll.code)" -ForegroundColor Green--# 4. Operator-side claim-$claim = Invoke-RestMethod -Uri "http://${vmIp}:5000/api/v1/pairing/claim" `- -Method Post `- -Headers @{ Authorization = "Bearer $token" } `- -ContentType 'application/json' `- -Body (@{ code = $enroll.code; passphrase = 'test-passphrase'; name = $VmName } | ConvertTo-Json)-Write-Host " [OK] Server claimed, id=$($claim.server_id)" -ForegroundColor Green--Write-Host "`nPairing API end-to-end OK." -ForegroundColor Green-Write-Host "Note: this exercises the API handshake; full agent process lifecycle test is TODO."