Compare commits

...
4 Commits
Author SHA1 Message Date
Andrew S Erwin 09f8a5d933 BYO AI settings: custom instructions, model picker, key show/hide
release gate / check (push) Failing after 6m26s
release / smoke (push) Successful in 10m16s
release / publish (push) Failing after 9m57s
Mirrors the BYOK dialog suggested in issue #2:
- UserAiConfig gains an optional instructions column (schema.sql +
  migration 016); PUT validates (<=4000 chars) and full-replaces it.
- Instructions ride along on the assistant chat system prompt only
  (chatSystemWith); the automation compiler and page-extraction prompts
  stay server-owned contracts.
- Settings -> AI: labeled fields, per-provider suggested-model dropdown
  with a custom-model escape hatch, API key show/hide toggle, and the
  instructions textarea.
- Tests: projection echo, omission clears, cap validation, and the
  system-prompt assertion via a recorded fake provider body.
2026-10-31 19:09:44 -05:00
carly 1dfd41986c Ship install/update scripts in the migrate image; no repo clone on hosts
release gate / check (push) Failing after 6m45s
release / smoke (push) Successful in 10m18s
release / publish (push) Failing after 9m55s
2026-10-30 12:03:07 -06:00
Andrew S Erwin fc9b6c2c42 README: how to publish the release images to Docker Hub
release gate / check (push) Failing after 6m57s
DevOps asked for the create/import path from the Gitea repo. Documents
both routes: Option A, the tag-triggered Gitea Actions release workflow
(smoke-gated publish; prerequisites: act_runner + DOCKERHUB_USERNAME/
DOCKERHUB_TOKEN secrets), and Option B, a fully manual buildx build+push
from a clone of the tag — including the one-time builder/qemu setup, a
migrate-image smoke test mirroring the CI gate, exact contexts and files
for all three images, and the shared-tag + latest convention. Plus the
post-publish step: bump VERSION in deploy/federated/service so the house
upgrade flow picks releases up. Records the constraints learned while
building this: semver without v prefix (VERSION_RX), never move a pushed
tag, keep the repos public for anonymous pulls, arm64 web builds are the
slow qemu step, and the app Dockerfile must stay legacy-builder
compatible.
2026-10-29 14:27:10 -05:00
Andrew S Erwin d914a87e98 update.sh: migrate source-mode installs to registry mode
release gate / check (push) Failing after 6m19s
Interim installs carry IMAGE_VERSION=local + IMAGE_VERSION_HOLD=1: the
hold makes upgrade_app skip the app, and the re-rendered registry compose
would pull a nonexistent :local tag. update.sh now detects the hold, drops
it, and pins IMAGE_VERSION to the service file's VERSION before invoking
the house upgrade flow.
2026-10-29 10:25:16 -05:00
17 changed files with 474 additions and 159 deletions
+10 -1
View File
@@ -55,8 +55,15 @@ jobs:
go vet ./internal/... . go vet ./internal/... .
go test ./internal/... go test ./internal/...
- uses: docker/setup-buildx-action@v3
- name: Build the migrate image - name: Build the migrate image
run: docker build -t superbrain-migrate:smoke db/ run: |
docker buildx build --load --build-context deploy=deploy/federated \
-t superbrain-migrate:smoke db/
# Hosts install/update from these baked files — they must be there.
docker run --rm superbrain-migrate:smoke sh -c \
'for f in install.sh update.sh lib-superbrain.sh service upgrade-pre; do test -f /deploy/$f || { echo "missing /deploy/$f"; exit 1; }; done'
- name: Bootstrap a fresh database with the image - name: Bootstrap a fresh database with the image
run: | run: |
@@ -119,6 +126,8 @@ jobs:
with: with:
context: db context: db
file: db/Dockerfile file: db/Dockerfile
build-contexts: |
deploy=deploy/federated
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
push: true push: true
tags: | tags: |
+1 -1
View File
@@ -295,7 +295,7 @@ BYO-only) → else 428. Budgets are per user (`ai:user:<id>`) or shared
| Method | Path | Body / Returns | | Method | Path | Body / Returns |
|---|---|---| |---|---|---|
| GET | `/api/ai/config` | The caller's masked config or `null` | | GET | `/api/ai/config` | The caller's masked config or `null` |
| PUT | `/api/ai/config` | `{provider,baseUrl?,model,apiKey,enabled?,version?}` → 201/200 masked; `version` required once a row exists (409 stale) | | PUT | `/api/ai/config` | `{provider,baseUrl?,model,apiKey,enabled?,instructions?,version?}` → 201/200 masked; `version` required once a row exists (409 stale). `instructions` (≤4000 chars) are the user's custom assistant system instructions — full-replacement like `model`/`baseUrl`: omit to clear. They are appended to the assistant chat prompt only, never to the compiler/extraction prompts |
| DELETE | `/api/ai/config` | `{ok:true}` | | DELETE | `/api/ai/config` | `{ok:true}` |
| POST | `/api/ai/test` | One probe completion through the resolved config → `{ok,source,model,reply}`; 428 when nothing is available; 502 with a truncated provider error | | POST | `/api/ai/test` | One probe completion through the resolved config → `{ok,source,model,reply}`; 428 when nothing is available; 502 with a truncated provider error |
| GET | `/api/ai/status` | `{userConfigured,userEnabled,serverAvailable,effective,plan}` — `serverAvailable` is already plan-gated; no secrets | | GET | `/api/ai/status` | `{userConfigured,userEnabled,serverAvailable,effective,plan}` — `serverAvailable` is already plan-gated; no secrets |
+109 -14
View File
@@ -187,10 +187,12 @@ install it); the index-backed page search depends on it.
set (no logins, no bookings, no deletes, no multi-step chains yet), set (no logins, no bookings, no deletes, no multi-step chains yet),
every fetch goes through the same private-range network guard as every fetch goes through the same private-range network guard as
previews, and email actions are hard-capped. AI is **bring-your-own-key** previews, and email actions are hard-capped. AI is **bring-your-own-key**
per user (Settings → AI: provider, model, key — encrypted at rest) with per user (Settings → AI: provider, model picker, key with show/hide —
an optional server-wide key for plans that include it; without any key, encrypted at rest — plus optional **custom instructions** that refine the
AI features report "not configured" and everything else keeps working. in-app assistant's tone and focus; the automation and page-reading prompts
Details: RUNNING.md → "AI automations". stay server-owned) with an optional server-wide key for plans that include
it; without any key, AI features report "not configured" and everything
else keeps working. Details: RUNNING.md → "AI automations".
### Connecting Authelia (OIDC) ### Connecting Authelia (OIDC)
@@ -352,13 +354,13 @@ Authelia + shared postgres + pdns + superpanel), Superbrain is a
first-class suite app. On the **core host**, as root: first-class suite app. On the **core host**, as root:
```bash ```bash
git clone https://gitea.federated.computer/Federated_Computer/brain.git /tmp/superbrain-repo sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/install.sh)"
sudo bash /tmp/superbrain-repo/deploy/federated/install.sh
``` ```
(Use whichever repository location you were given access to; the installer No clone and nothing to copy: the installer and the suite integration files
re-clones it onto the host by default — override with `SUPERBRAIN_REPO`, ship inside the migrate image at `/deploy`. Pin a release with
`SUPERBRAIN_REF`, or stage a local tree with `SUPERBRAIN_SRC`.) `SUPERBRAIN_VERSION=1.2.3` (default `latest`), or use a local checkout's
files instead with `SUPERBRAIN_SRC=/path/to/repo`.
The installer: The installer:
@@ -393,19 +395,112 @@ history: [deploy/federated/STRATEGY.md](deploy/federated/STRATEGY.md).
in `/federated/services/superbrain/service` to the new release tag and run in `/federated/services/superbrain/service` to the new release tag and run
`/federated/bin/upgrade superbrain` (the pre-hook backs up the database `/federated/bin/upgrade superbrain` (the pre-hook backs up the database
and pulls all three images). Or one command, which also syncs the suite and pulls all three images). Or one command, which also syncs the suite
files from the repo: files from the release's migrate image (version defaults to `latest`):
```bash ```bash
git clone https://gitea.federated.computer/Federated_Computer/brain.git /tmp/superbrain-repo sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/update.sh)" update.sh [version]
sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref]
``` ```
Releases are semver tags without a `v` prefix (`1.0.0`); CI builds and Releases are semver tags without a `v` prefix (`1.0.0`); CI builds and
pushes all three images under the same tag (plus `:latest`) for pushes all three images under the same tag (plus `:latest`) for
linux/amd64 and linux/arm64. The migrate image is self-contained: it linux/amd64 and linux/arm64. The migrate image is self-contained: it
detects an empty database, applies `schema.sql` as the superbrain user, detects an empty database, applies `schema.sql` as the superbrain user,
then runs the checksummed migration ledger — the host never needs the then runs the checksummed migration ledger, and it carries
source tree. `deploy/federated/` at `/deploy` — the host never needs the source tree.
## Publishing release images (Docker Hub)
Releases are three multi-arch images sharing **one semver tag without a `v`
prefix** (the suite's `VERSION_RX` is `^[0-9][0-9\.]*$`), plus `:latest`:
```
federatedcomputer/superbrain-app:<version> Go API (context ., Dockerfile)
federatedcomputer/superbrain-web:<version> Next.js UI (context web, web/Dockerfile)
federatedcomputer/superbrain-migrate:<version> DB bootstrap (context db, db/Dockerfile)
```
Platforms: `linux/amd64,linux/arm64`. Source of truth: this Gitea repo
(`https://gitea.federated.computer/Federated_Computer/brain.git`) at the
matching tag. The repositories auto-create on first push under the
`federatedcomputer` namespace; keep them **public** so cores can pull
without registry credentials. Never move an existing tag — cut a new
version instead.
### Option A — CI (preferred): push a tag
`.github/workflows/release.yml` runs on Gitea Actions for tags matching
`[0-9]+.[0-9]+.[0-9]+`. A smoke job first builds the migrate image and
bootstraps a throwaway PostgreSQL with it (fresh schema, complete ledger,
idempotent re-run) and runs Go build/vet/unit tests; only then does the
publish job build and push all three images. Prerequisites (one-time,
instance admin):
1. An **act_runner** registered against `https://gitea.federated.computer`
with access to a docker socket.
2. Repo/org **Actions secrets** `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN`
(an access token with write permission on the `federatedcomputer`
namespace).
Then releasing is:
```bash
git checkout main && git pull
git tag -a 1.2.3 -m "release 1.2.3"
git push origin 1.2.3
```
Watch the run under the repo's Actions tab; verify with
`docker manifest inspect federatedcomputer/superbrain-app:1.2.3`.
### Option B — manual build & push (no runner required)
From any Linux machine with Docker, buildx and login rights:
```bash
git clone https://gitea.federated.computer/Federated_Computer/brain.git
cd brain && git checkout 1.2.3 # always build from the tag
# One-time per machine: buildx builder + cross-arch emulation
docker buildx create --use --name multiarch
docker run --privileged --rm tonistiigi/binfmt --install arm64
docker login -u <dockerhub-user> # token prompt
# Smoke the migrate image BEFORE publishing (mirrors the CI gate):
docker buildx build --load --build-context deploy=deploy/federated -t sb-migrate:smoke db/
docker run -d --name sb-smoke-pg -e POSTGRES_USER=superbrain \
-e POSTGRES_PASSWORD=x -e POSTGRES_DB=superbrain postgres:16.15-alpine
docker run --rm --link sb-smoke-pg -e DB_HOST=sb-smoke-pg -e PGPASSWORD=x sb-migrate:smoke
docker run --rm --link sb-smoke-pg -e DB_HOST=sb-smoke-pg -e PGPASSWORD=x sb-migrate:smoke # re-run: "up to date"
docker rm -f sb-smoke-pg
# Build + push all three (each command pushes <version> and latest):
V=1.2.3
docker buildx build --platform linux/amd64,linux/arm64 --push \
-t federatedcomputer/superbrain-app:$V -t federatedcomputer/superbrain-app:latest .
docker buildx build --platform linux/amd64,linux/arm64 --push \
-t federatedcomputer/superbrain-web:$V -t federatedcomputer/superbrain-web:latest web
docker buildx build --platform linux/amd64,linux/arm64 --push \
--build-context deploy=deploy/federated \
-t federatedcomputer/superbrain-migrate:$V -t federatedcomputer/superbrain-migrate:latest db
```
Notes: the arm64 web build runs under qemu and is the slow step (tens of
minutes on modest hardware); the app image is a static Go binary and the
migrate image is `postgres:16.15-alpine` + `db/` + `deploy/federated/`
(supplied as the named `deploy` build context), both quick. Go builds
must stay legacy-builder compatible (no `$BUILDPLATFORM` tricks) so local
`docker compose build` keeps working on hosts without BuildKit defaults.
### After publishing
Bump `VERSION=` in `deploy/federated/service` to the new tag (commit it —
and release it — hosts sync the service file via `update.sh` from the
migrate image), then on each
core: `/federated/bin/upgrade superbrain` (or update.sh, which syncs the
service file first). The pre-upgrade hook takes a pg_dump and pulls all
three images; `upgrade_app` snapshots, redeploys and rewrites
`IMAGE_VERSION` in the app `.env`.
## Environment variable reference ## Environment variable reference
+9 -1
View File
@@ -3,13 +3,21 @@
# the source tree. Entrypoint: bootstrap.sh (empty database => schema.sql as # the source tree. Entrypoint: bootstrap.sh (empty database => schema.sql as
# DB_USER, then always the checksummed migration ledger). # DB_USER, then always the checksummed migration ledger).
# #
# Also ships deploy/federated/ at /deploy (install.sh, update.sh and the
# suite integration files), so a core host needs nothing but this image:
# docker run --rm federatedcomputer/superbrain-migrate cat /deploy/install.sh
# The files arrive via a named build context (BuildKit/buildx only; the dev
# compose never builds this image):
# docker buildx build --build-context deploy=deploy/federated db/
#
# Base image = the same postgres alpine the dev stack's migrate service uses; # Base image = the same postgres alpine the dev stack's migrate service uses;
# only the psql client is exercised. Client 16 against a newer server (the # only the psql client is exercised. Client 16 against a newer server (the
# federated suite runs 17.x) is the supported direction. # federated suite runs 17.x) is the supported direction.
FROM postgres:16.15-alpine FROM postgres:16.15-alpine
COPY . /db COPY . /db
RUN chmod +x /db/bootstrap.sh /db/migrate.sh COPY --from=deploy . /deploy
RUN chmod +x /db/bootstrap.sh /db/migrate.sh /deploy/install.sh /deploy/update.sh
WORKDIR /db WORKDIR /db
CMD ["sh", "/db/bootstrap.sh"] CMD ["sh", "/db/bootstrap.sh"]
+11
View File
@@ -0,0 +1,11 @@
-- 016_ai_instructions.sql — optional custom system instructions per user
-- (Settings → AI, mirroring the BYOK "instructions" field). Additive and
-- idempotent; schema.sql carries the identical column, so db-converge lands
-- the same shape on both paths.
--
-- Applied ONLY to the in-app assistant chat prompt. The server-owned
-- automation compiler and page-extraction prompts deliberately never
-- include user instructions: those are contracts (ValidateSpec, untrusted
-- fetched content), not personas.
ALTER TABLE "UserAiConfig" ADD COLUMN IF NOT EXISTS instructions text NOT NULL DEFAULT '';
+4 -1
View File
@@ -453,13 +453,16 @@ CREATE INDEX "AgentRun_taskId_createdAt_idx" ON "AgentRun"("taskId", "createdAt"
-- internal/crypto (same versioned format as IMAP passwords and -- internal/crypto (same versioned format as IMAP passwords and
-- notification channel secrets) and masked in every API response. The -- notification channel secrets) and masked in every API response. The
-- server-wide env key (AI_API_KEY) is the fallback and is plan-gated by -- server-wide env key (AI_API_KEY) is the fallback and is plan-gated by
-- entitlements.AllowServerAI. -- entitlements.AllowServerAI. "instructions" holds the user's optional
-- custom system instructions for the in-app assistant; server-owned
-- prompts (automation compiler, page extraction) never include them.
CREATE TABLE "UserAiConfig" ( CREATE TABLE "UserAiConfig" (
id text PRIMARY KEY, id text PRIMARY KEY,
"ownerId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE, "ownerId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
provider text NOT NULL CHECK (provider IN ('openai-compatible','anthropic','gemini')), provider text NOT NULL CHECK (provider IN ('openai-compatible','anthropic','gemini')),
"baseUrl" text NOT NULL DEFAULT '', "baseUrl" text NOT NULL DEFAULT '',
model text NOT NULL, model text NOT NULL,
instructions text NOT NULL DEFAULT '',
"apiKey" text NOT NULL, "apiKey" text NOT NULL,
enabled boolean NOT NULL DEFAULT true, enabled boolean NOT NULL DEFAULT true,
version integer NOT NULL DEFAULT 1, version integer NOT NULL DEFAULT 1,
+6 -3
View File
@@ -71,11 +71,14 @@ Authelia required, fcore SMTP credential, fixed-IP collisions with
`SUPERBRAIN_*_IP` overrides; installs lib/service/hook; runs `SUPERBRAIN_*_IP` overrides; installs lib/service/hook; runs
`/federated/bin/installapp superbrain`; verifies containers, Authelia `/federated/bin/installapp superbrain`; verifies containers, Authelia
client + claims markers, HTTPS login) and `deploy/federated/update.sh` client + claims markers, HTTPS login) and `deploy/federated/update.sh`
(clone at ref → sync lib/service/hook with parse-checks and backups → (extract /deploy from the migrate image at VERSION, default latest →
sync lib/service/hook with parse-checks and backups →
re-render compose via `render_superbrain_compose` → `/federated/bin/ re-render compose via `render_superbrain_compose` → `/federated/bin/
upgrade superbrain` → same-version compose safety pass → health probe). upgrade superbrain` → same-version compose safety pass → health probe).
The registry-mode app dir holds ONLY compose + .env — update.sh therefore The registry-mode app dir holds ONLY compose + .env, so both scripts ship
runs from a repo clone, not from the app dir (the source-mode inside the migrate image at `/deploy` (since 1.0.1) and run via
`bash -c "$(docker run --rm federatedcomputer/superbrain-migrate cat
/deploy/<script>)"` — no repo clone on the host (the source-mode
self-location of the old update.sh died with interim mode). self-location of the old update.sh died with interim mode).
A deliberate non-goal remains: an in-app "update" button — the scratch A deliberate non-goal remains: an in-app "update" button — the scratch
+29 -32
View File
@@ -3,10 +3,10 @@
# Install Superbrain into a federated "core" suite host (REGISTRY mode). # Install Superbrain into a federated "core" suite host (REGISTRY mode).
# #
# For operators running their own copy of the federated suite. On the # For operators running their own copy of the federated suite. On the
# CORE HOST, as root: # CORE HOST, as root — no clone, no copying files around; this script and
# the deploy files ship inside the migrate image at /deploy:
# #
# git clone <this-repo> /tmp/superbrain-repo # sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/install.sh)"
# sudo bash /tmp/superbrain-repo/deploy/federated/install.sh
# #
# No source is built or stored on the host: the three release images # No source is built or stored on the host: the three release images
# (federatedcomputer/superbrain-{app,web,migrate}, one shared version tag, # (federatedcomputer/superbrain-{app,web,migrate}, one shared version tag,
@@ -18,7 +18,7 @@
# 1. Preflights the suite (installapp, functions.sh, /etc/federated, the # 1. Preflights the suite (installapp, functions.sh, /etc/federated, the
# core docker network, Authelia — REQUIRED because the core tier is # core docker network, Authelia — REQUIRED because the core tier is
# Authelia-only — and the fcore SMTP credential for notification mail). # Authelia-only — and the fcore SMTP credential for notification mail).
# 2. Gets the deploy files from a repo clone (or $SUPERBRAIN_SRC). # 2. Gets the deploy files from the migrate image (or $SUPERBRAIN_SRC).
# 3. Installs the suite integration: /federated/lib/superbrain.sh, # 3. Installs the suite integration: /federated/lib/superbrain.sh,
# /federated/services/superbrain/{service,upgrade/pre}, with fixed-IP # /federated/services/superbrain/{service,upgrade/pre}, with fixed-IP
# collision checks and SUPERBRAIN_*_IP overrides. # collision checks and SUPERBRAIN_*_IP overrides.
@@ -29,21 +29,21 @@
# 5. Verifies and prints first-login steps. # 5. Verifies and prints first-login steps.
# #
# Environment overrides: # Environment overrides:
# SUPERBRAIN_REPO git URL to clone (default: this repo's origin) # SUPERBRAIN_VERSION release whose deploy files to use (default: latest;
# SUPERBRAIN_REF branch/tag to clone (default: main) # the service file inside it pins the image version)
# SUPERBRAIN_SRC local repo checkout to take the deploy files from # SUPERBRAIN_SRC local repo checkout to take the deploy files from
# instead of the image (development)
# SUPERBRAIN_WEB_IP / SUPERBRAIN_APP_IP / SUPERBRAIN_MIGRATE_IP # SUPERBRAIN_WEB_IP / SUPERBRAIN_APP_IP / SUPERBRAIN_MIGRATE_IP
# fixed core-network IPs (default .93/.94/.95 — the # fixed core-network IPs (default .93/.94/.95 — the
# installer refuses if they are already allocated) # installer refuses if they are already allocated)
# SKIP_VERIFY=1 skip the post-install HTTPS probe # SKIP_VERIFY=1 skip the post-install HTTPS probe
# #
# Updates after install: sudo bash <repo>/deploy/federated/update.sh # Updates after install: update.sh from the same image (syncs the service
# (syncs the service file's VERSION, then runs the house upgrade flow). # file's VERSION, then runs the house upgrade flow).
# #
set -euo pipefail set -euo pipefail
REPO_DEFAULT="https://gitea.federated.computer/Federated_Computer/brain.git" IMAGE="federatedcomputer/superbrain-migrate:${SUPERBRAIN_VERSION:-latest}"
CLONE=/tmp/superbrain-install-src
LIB_DST=/federated/lib/superbrain.sh LIB_DST=/federated/lib/superbrain.sh
SVC_DST_DIR=/federated/services/superbrain SVC_DST_DIR=/federated/services/superbrain
@@ -56,7 +56,7 @@ warn() { printf '\033[1;33mwarning:\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
# --- 0. Preflights ----------------------------------------------------------- # --- 0. Preflights -----------------------------------------------------------
[ "$(id -u)" = 0 ] || die "run as root on the core host (sudo bash $0)" [ "$(id -u)" = 0 ] || die "run as root on the core host"
[ -x /federated/bin/installapp ] || die "/federated/bin/installapp missing — this does not look like a federated suite host" [ -x /federated/bin/installapp ] || die "/federated/bin/installapp missing — this does not look like a federated suite host"
[ -f /federated/lib/functions.sh ] || die "/federated/lib/functions.sh missing" [ -f /federated/lib/functions.sh ] || die "/federated/lib/functions.sh missing"
[ -f /etc/federated ] || die "/etc/federated missing" [ -f /etc/federated ] || die "/etc/federated missing"
@@ -87,27 +87,25 @@ ip_taken() { # $1 = ip
} }
for ip in "$WEB_IP" "$APP_IP" "$MIGRATE_IP"; do for ip in "$WEB_IP" "$APP_IP" "$MIGRATE_IP"; do
if ip_taken "$ip"; then if ip_taken "$ip"; then
die "IP $ip is already allocated on this host. Pick free addresses and re-run with e.g.: die "IP $ip is already allocated on this host. Pick free addresses and re-run with them in the environment, e.g.:
sudo SUPERBRAIN_WEB_IP=192.168.0.193 SUPERBRAIN_APP_IP=192.168.0.194 SUPERBRAIN_MIGRATE_IP=192.168.0.195 bash $0" sudo SUPERBRAIN_WEB_IP=192.168.0.193 SUPERBRAIN_APP_IP=192.168.0.194 SUPERBRAIN_MIGRATE_IP=192.168.0.195 bash -c \"\$(docker run --rm $IMAGE cat /deploy/install.sh)\""
fi fi
done done
# --- 2. Get the deploy files ---------------------------------------------------- # --- 2. Get the deploy files ----------------------------------------------------
if [ -n "${SUPERBRAIN_SRC:-}" ]; then if [ -n "${SUPERBRAIN_SRC:-}" ]; then
SRC="$SUPERBRAIN_SRC" DEPLOY="$SUPERBRAIN_SRC/deploy/federated"
[ -f "$SRC/deploy/federated/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC=$SRC lacks deploy/federated files" [ -f "$DEPLOY/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC=$SUPERBRAIN_SRC lacks deploy/federated files"
else else
command -v git >/dev/null || die "git not found (or set SUPERBRAIN_SRC=/path/to/repo)" say "Pulling $IMAGE for the deploy files"
REPO="${SUPERBRAIN_REPO:-$REPO_DEFAULT}" docker pull -q "$IMAGE" >/dev/null || die "could not pull $IMAGE — does the release exist on Docker Hub?"
REF="${SUPERBRAIN_REF:-main}" DEPLOY=$(mktemp -d)
say "Cloning $REPO ($REF) for the deploy files" trap 'rm -rf "$DEPLOY"' EXIT
rm -rf "$CLONE" docker run --rm "$IMAGE" tar -C /deploy -c . | tar -x -C "$DEPLOY" \
git clone --depth 1 --branch "$REF" "$REPO" "$CLONE" \ || die "could not extract /deploy from $IMAGE"
|| die "git clone failed — check repository access/credentials"
SRC="$CLONE"
fi fi
for f in deploy/federated/lib-superbrain.sh deploy/federated/service deploy/federated/upgrade-pre; do for f in lib-superbrain.sh service upgrade-pre; do
[ -e "$SRC/$f" ] || die "source is missing $f — wrong repo/ref?" [ -e "$DEPLOY/$f" ] || die "deploy files are missing $f — wrong image/version?"
done done
# --- 3. Install the suite integration files -------------------------------------- # --- 3. Install the suite integration files --------------------------------------
@@ -116,11 +114,11 @@ if [ -f "$LIB_DST" ]; then
cp -a "$LIB_DST" "$LIB_DST.bak-$(date +%Y%m%d-%H%M%S)" cp -a "$LIB_DST" "$LIB_DST.bak-$(date +%Y%m%d-%H%M%S)"
warn "backed up an existing $LIB_DST" warn "backed up an existing $LIB_DST"
fi fi
cp "$SRC/deploy/federated/lib-superbrain.sh" "$LIB_DST" cp "$DEPLOY/lib-superbrain.sh" "$LIB_DST"
mkdir -p "$SVC_DST_DIR/upgrade" mkdir -p "$SVC_DST_DIR/upgrade"
[ -f "$SVC_DST_DIR/service" ] && cp -a "$SVC_DST_DIR/service" "$SVC_DST_DIR/service.bak-$(date +%Y%m%d-%H%M%S)" [ -f "$SVC_DST_DIR/service" ] && cp -a "$SVC_DST_DIR/service" "$SVC_DST_DIR/service.bak-$(date +%Y%m%d-%H%M%S)"
cp "$SRC/deploy/federated/service" "$SVC_DST_DIR/service" cp "$DEPLOY/service" "$SVC_DST_DIR/service"
cp "$SRC/deploy/federated/upgrade-pre" "$SVC_DST_DIR/upgrade/pre" cp "$DEPLOY/upgrade-pre" "$SVC_DST_DIR/upgrade/pre"
chmod 755 "$SVC_DST_DIR/upgrade/pre" chmod 755 "$SVC_DST_DIR/upgrade/pre"
# Apply IP overrides (defaults match the shipped files, so this is a no-op # Apply IP overrides (defaults match the shipped files, so this is a no-op
@@ -190,8 +188,7 @@ $(say "Superbrain installed (registry mode, version $WANT_VERSION)")
Other users are provisioned upstream (Superpanel -> LDAP -> Authelia) and Other users are provisioned upstream (Superpanel -> LDAP -> Authelia) and
appear in Superbrain on their first SSO login. appear in Superbrain on their first SSO login.
Updates: bump VERSION in $SVC_DST_DIR/service (or sync it from a repo Updates: bump VERSION in $SVC_DST_DIR/service and run
clone) and run /federated/bin/upgrade superbrain — or one command: /federated/bin/upgrade superbrain — or one command (default: latest):
git clone <repo> /tmp/superbrain-repo sudo bash -c "\\$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/update.sh)" update.sh [version]
sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref]
EOF EOF
+1 -1
View File
@@ -48,7 +48,7 @@ SUPERBRAIN_APP_IP="192.168.0.94"
SUPERBRAIN_MIGRATE_IP="192.168.0.95" SUPERBRAIN_MIGRATE_IP="192.168.0.95"
# Release to install; the generic `upgrade` flow keeps .env in step with the # Release to install; the generic `upgrade` flow keeps .env in step with the
# service file's VERSION afterwards. # service file's VERSION afterwards.
SUPERBRAIN_IMAGE_VERSION="1.0.0" SUPERBRAIN_IMAGE_VERSION="1.0.1"
# render_superbrain_compose writes the app-dir compose file. Called by # render_superbrain_compose writes the app-dir compose file. Called by
# config_superbrain (install) and by deploy/federated/update.sh after a lib # config_superbrain (install) and by deploy/federated/update.sh after a lib
+1 -1
View File
@@ -2,7 +2,7 @@ NAME=superbrain
DESCRIPTION="Bookmark & Knowledge Base" DESCRIPTION="Bookmark & Knowledge Base"
DOCS=https://github.com/andrew/superbrain DOCS=https://github.com/andrew/superbrain
CONTAINER=federatedcomputer/superbrain-app CONTAINER=federatedcomputer/superbrain-app
VERSION=1.0.0 VERSION=1.0.1
INTERNAL_IP=192.168.0.93 INTERNAL_IP=192.168.0.93
DEPENDS="postgresql" DEPENDS="postgresql"
PORTS=3000 PORTS=3000
+43 -29
View File
@@ -2,14 +2,14 @@
# #
# Update Superbrain on a federated core host (REGISTRY mode). # Update Superbrain on a federated core host (REGISTRY mode).
# #
# The app dir holds only compose + .env (no source), so this script runs # The app dir holds only compose + .env (no source); this script and the
# from a repo clone: # deploy files ship inside the migrate image at /deploy, so no clone:
# #
# git clone <repo> /tmp/superbrain-repo # sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/update.sh)" update.sh [version]
# sudo bash /tmp/superbrain-repo/deploy/federated/update.sh [git-ref]
# #
# What it does: # What it does:
# 1. Clones the repo at REF (default main) — or uses $SUPERBRAIN_SRC. # 1. Pulls federatedcomputer/superbrain-migrate:VERSION (default latest)
# and extracts its /deploy files — or uses $SUPERBRAIN_SRC.
# 2. Syncs the suite integration files (lib, service file, upgrade/pre # 2. Syncs the suite integration files (lib, service file, upgrade/pre
# hook) with backups and a parse check — the service file carries the # hook) with backups and a parse check — the service file carries the
# desired VERSION, which is how a release reaches the host. # desired VERSION, which is how a release reaches the host.
@@ -21,14 +21,14 @@
# 5. compose up -d safety pass (applies same-version compose-only # 5. compose up -d safety pass (applies same-version compose-only
# changes), then health-probes app + web. # changes), then health-probes app + web.
# #
# Environment: SUPERBRAIN_REPO, SUPERBRAIN_REF (or $1), SUPERBRAIN_SRC. # Environment: SUPERBRAIN_VERSION (or $1), SUPERBRAIN_SRC (local repo
# checkout instead of the image; development).
# #
set -euo pipefail set -euo pipefail
REPO_DEFAULT="https://gitea.federated.computer/Federated_Computer/brain.git"
APP_DIR=/federated/apps/superbrain APP_DIR=/federated/apps/superbrain
CLONE=/tmp/superbrain-update-src IMAGE="federatedcomputer/superbrain-migrate:${1:-${SUPERBRAIN_VERSION:-latest}}"
REF="${1:-${SUPERBRAIN_REF:-main}}" STAMP=$(date +%Y%m%d-%H%M%S)
say() { printf '\033[1;34m==>\033[0m %s\n' "$*"; } say() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
@@ -40,32 +40,33 @@ die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
|| die "$APP_DIR does not look installed (compose/.env missing) — run deploy/federated/install.sh first" || die "$APP_DIR does not look installed (compose/.env missing) — run deploy/federated/install.sh first"
if [ -n "${SUPERBRAIN_SRC:-}" ]; then if [ -n "${SUPERBRAIN_SRC:-}" ]; then
SRC="$SUPERBRAIN_SRC" DEPLOY="$SUPERBRAIN_SRC/deploy/federated"
[ -f "$SRC/deploy/federated/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC lacks deploy/federated files" [ -f "$DEPLOY/lib-superbrain.sh" ] || die "SUPERBRAIN_SRC lacks deploy/federated files"
SOURCE="$SUPERBRAIN_SRC"
else else
command -v git >/dev/null || die "git not found (or set SUPERBRAIN_SRC=/path/to/repo)" say "Pulling $IMAGE for the deploy files"
say "Fetching ${SUPERBRAIN_REPO:-$REPO_DEFAULT} @ $REF" docker pull -q "$IMAGE" >/dev/null || die "could not pull $IMAGE — does the release exist on Docker Hub?"
rm -rf "$CLONE" DEPLOY=$(mktemp -d)
if ! git clone --quiet --depth 1 --branch "$REF" "${SUPERBRAIN_REPO:-$REPO_DEFAULT}" "$CLONE" 2>/dev/null; then trap 'rm -rf "$DEPLOY"' EXIT
git clone --quiet "${SUPERBRAIN_REPO:-$REPO_DEFAULT}" "$CLONE" || die "git clone failed — check repository access" docker run --rm "$IMAGE" tar -C /deploy -c . | tar -x -C "$DEPLOY" \
git -C "$CLONE" checkout --quiet "$REF" || die "ref $REF not found" || die "could not extract /deploy from $IMAGE"
fi SOURCE="$IMAGE"
SRC="$CLONE"
fi fi
NEW_REV=$(git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo "$REF") for f in lib-superbrain.sh service upgrade-pre; do
[ -e "$DEPLOY/$f" ] || die "deploy files are missing $f — wrong image/version?"
done
# --- 2. Sync suite files (parse-checked, backed up) ------------------------------ # --- 2. Sync suite files (parse-checked, backed up) ------------------------------
say "Syncing suite integration files (revision $NEW_REV)" say "Syncing suite integration files from $SOURCE"
LIB=/federated/lib/superbrain.sh LIB=/federated/lib/superbrain.sh
cp "$SRC/deploy/federated/lib-superbrain.sh" /tmp/lib-superbrain.sh.new bash -n "$DEPLOY/lib-superbrain.sh" || die "staged lib-superbrain.sh does not parse — aborting"
bash -n /tmp/lib-superbrain.sh.new || die "staged lib-superbrain.sh does not parse — aborting" [ -f "$LIB" ] && cp -a "$LIB" "$LIB.bak-$STAMP"
[ -f "$LIB" ] && cp -a "$LIB" "$LIB.bak-$NEW_REV" cp "$DEPLOY/lib-superbrain.sh" "$LIB"
mv /tmp/lib-superbrain.sh.new "$LIB"
mkdir -p /federated/services/superbrain/upgrade mkdir -p /federated/services/superbrain/upgrade
[ -f /federated/services/superbrain/service ] && cp -a /federated/services/superbrain/service "/federated/services/superbrain/service.bak-$NEW_REV" [ -f /federated/services/superbrain/service ] && cp -a /federated/services/superbrain/service "/federated/services/superbrain/service.bak-$STAMP"
cp "$SRC/deploy/federated/service" /federated/services/superbrain/service cp "$DEPLOY/service" /federated/services/superbrain/service
cp "$SRC/deploy/federated/upgrade-pre" /federated/services/superbrain/upgrade/pre cp "$DEPLOY/upgrade-pre" /federated/services/superbrain/upgrade/pre
chmod 755 /federated/services/superbrain/upgrade/pre chmod 755 /federated/services/superbrain/upgrade/pre
# --- 3. Re-render the compose from the fresh lib ---------------------------------- # --- 3. Re-render the compose from the fresh lib ----------------------------------
@@ -79,6 +80,19 @@ grep -q "container_name: superbrain-app" "$APP_DIR/docker-compose.yml" \
# --- 4. House upgrade flow ---------------------------------------------------------- # --- 4. House upgrade flow ----------------------------------------------------------
WANT_VERSION=$(sed -n 's/^VERSION=//p' /federated/services/superbrain/service | tr -d '"' | head -1) WANT_VERSION=$(sed -n 's/^VERSION=//p' /federated/services/superbrain/service | tr -d '"' | head -1)
# Source-mode migration: interim installs (2026-10-25..29) carry
# IMAGE_VERSION=local plus IMAGE_VERSION_HOLD=1, which makes upgrade_app
# skip the app entirely — and the re-rendered compose would try to pull a
# nonexistent :local tag. Convert .env to the registry version the service
# file wants before upgrading.
if grep -q '^IMAGE_VERSION_HOLD=' "$APP_DIR/.env"; then
say "Migrating .env from source-build mode to registry mode ($WANT_VERSION)"
sed -i '/^IMAGE_VERSION_HOLD=/d' "$APP_DIR/.env"
sed -i "s#^IMAGE_VERSION=.*#IMAGE_VERSION=\"$WANT_VERSION\"#" "$APP_DIR/.env"
fi
grep -q '^IMAGE_VERSION=' "$APP_DIR/.env" || echo "IMAGE_VERSION=\"$WANT_VERSION\"" >> "$APP_DIR/.env"
HAVE_VERSION=$(sed -n 's/^IMAGE_VERSION=//p' "$APP_DIR/.env" | tr -d '"' | tail -1) HAVE_VERSION=$(sed -n 's/^IMAGE_VERSION=//p' "$APP_DIR/.env" | tr -d '"' | tail -1)
say "Running the house upgrade flow (have $HAVE_VERSION, service file wants $WANT_VERSION)" say "Running the house upgrade flow (have $HAVE_VERSION, service file wants $WANT_VERSION)"
/federated/bin/upgrade superbrain || die "upgrade failed — inspect the output above" /federated/bin/upgrade superbrain || die "upgrade failed — inspect the output above"
@@ -102,4 +116,4 @@ if [ "$healthy" != 1 ]; then
fi fi
NOW_VERSION=$(sed -n 's/^IMAGE_VERSION=//p' "$APP_DIR/.env" | tr -d '"' | tail -1) NOW_VERSION=$(sed -n 's/^IMAGE_VERSION=//p' "$APP_DIR/.env" | tr -d '"' | tail -1)
say "Superbrain is at image version $NOW_VERSION (repo revision $NEW_REV), healthy" say "Superbrain is at image version $NOW_VERSION (deploy files from $SOURCE), healthy"
+10 -4
View File
@@ -68,11 +68,16 @@ var ErrNoAI = errors.New("ai: no configuration available for this user")
// Resolved is one usable endpoint. Source is "user" (BYO) or "server" // Resolved is one usable endpoint. Source is "user" (BYO) or "server"
// (env); it feeds budget keys and the status endpoint, never prompts. // (env); it feeds budget keys and the status endpoint, never prompts.
// Instructions carries the user's optional custom system instructions
// (BYO configs only; the server key has none). They apply to the in-app
// assistant persona — server-owned contracts (automation compiler, page
// extraction) must never include them.
type Resolved struct { type Resolved struct {
Provider string Provider string
BaseURL string BaseURL string
Model string Model string
APIKey string APIKey string
Instructions string
Source string Source string
UserID string UserID string
} }
@@ -128,11 +133,11 @@ func serverConfig() (Resolved, bool) {
// ResolveForUser applies the resolution chain: the user's enabled BYO // ResolveForUser applies the resolution chain: the user's enabled BYO
// config first, then the server key iff the user's plan may spend it. // config first, then the server key iff the user's plan may spend it.
func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, error) { func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, error) {
var id, provider, baseURL, model, encKey string var id, provider, baseURL, model, encKey, instructions string
var enabled bool var enabled bool
err := d.QueryRowContext(ctx, err := d.QueryRowContext(ctx,
`SELECT id, provider, "baseUrl", model, "apiKey", enabled FROM "UserAiConfig" WHERE "ownerId"=$1`, `SELECT id, provider, "baseUrl", model, "apiKey", instructions, enabled FROM "UserAiConfig" WHERE "ownerId"=$1`,
userID).Scan(&id, &provider, &baseURL, &model, &encKey, &enabled) userID).Scan(&id, &provider, &baseURL, &model, &encKey, &instructions, &enabled)
if err == nil && enabled && encKey != "" { if err == nil && enabled && encKey != "" {
key, decErr := crypt.Decrypt(encKey, config.Load().EncryptionSecret()) key, decErr := crypt.Decrypt(encKey, config.Load().EncryptionSecret())
if decErr != nil { if decErr != nil {
@@ -140,7 +145,8 @@ func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, err
} }
return Resolved{ return Resolved{
Provider: provider, BaseURL: strings.TrimRight(baseURL, "/"), Provider: provider, BaseURL: strings.TrimRight(baseURL, "/"),
Model: model, APIKey: key, Source: "user", UserID: userID, Model: model, APIKey: key, Instructions: instructions,
Source: "user", UserID: userID,
}, nil }, nil
} }
if err != nil && !errors.Is(err, sql.ErrNoRows) { if err != nil && !errors.Is(err, sql.ErrNoRows) {
+39 -8
View File
@@ -1,11 +1,13 @@
package handlers package handlers
// Per-user AI configuration (Settings → AI): provider, model, base URL and // Per-user AI configuration (Settings → AI): provider, model, base URL,
// a bring-your-own API key. Config is data; internal/ai is the // optional custom instructions and a bring-your-own API key. Config is
// implementation. The key is encrypted at rest (internal/crypto, the same // data; internal/ai is the implementation. The key is encrypted at rest
// versioned format as every other stored credential), masked in every // (internal/crypto, the same versioned format as every other stored
// response, and a PUT echoing the mask keeps the stored key. The server // credential), masked in every response, and a PUT echoing the mask keeps
// env key remains the plan-gated fallback (entitlements.AllowServerAI). // the stored key. Instructions ride along on the assistant chat prompt
// only. The server env key remains the plan-gated fallback
// (entitlements.AllowServerAI).
import ( import (
"context" "context"
@@ -43,11 +45,16 @@ func aiConfigProjection(row object) object {
} }
return object{ return object{
"id": row["id"], "provider": row["provider"], "baseUrl": row["baseUrl"], "id": row["id"], "provider": row["provider"], "baseUrl": row["baseUrl"],
"model": row["model"], "apiKey": masked, "enabled": row["enabled"], "model": row["model"], "instructions": row["instructions"],
"apiKey": masked, "enabled": row["enabled"],
"version": row["version"], "createdAt": row["createdAt"], "version": row["version"], "createdAt": row["createdAt"],
} }
} }
// aiInstructionsMax bounds the custom system instructions (runes). They
// ride along in every assistant chat request, so they stay short by design.
const aiInstructionsMax = 4000
// HandleAiConfigGet returns the caller's stored config (masked) or null. // HandleAiConfigGet returns the caller's stored config (masked) or null.
func HandleAiConfigGet(w http.ResponseWriter, r *http.Request) { func HandleAiConfigGet(w http.ResponseWriter, r *http.Request) {
row, e := db.One(r.Context(), database(r), row, e := db.One(r.Context(), database(r),
@@ -88,6 +95,14 @@ func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
respond(w, 0, nil, bad("baseUrl must be an absolute http(s) URL")) respond(w, 0, nil, bad("baseUrl must be an absolute http(s) URL"))
return return
} }
// Optional custom system instructions (BYOK "instructions" field).
// Full-replacement like provider/model/baseUrl: a PUT that omits them
// clears them.
instructions := strings.TrimSpace(str(b, "instructions"))
if len([]rune(instructions)) > aiInstructionsMax {
respond(w, 0, nil, bad("instructions must be at most 4000 characters"))
return
}
submittedKey := str(b, "apiKey") submittedKey := str(b, "apiKey")
existing, e := db.One(r.Context(), database(r), existing, e := db.One(r.Context(), database(r),
@@ -122,6 +137,7 @@ func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
row, e := db.Insert(r.Context(), database(r), "UserAiConfig", object{ row, e := db.Insert(r.Context(), database(r), "UserAiConfig", object{
"id": db.NewID(), "ownerId": user(r), "provider": provider, "id": db.NewID(), "ownerId": user(r), "provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"), "model": model, "baseUrl": strings.TrimRight(baseURL, "/"), "model": model,
"instructions": instructions,
"apiKey": encKey, "enabled": enabled, "apiKey": encKey, "enabled": enabled,
}) })
if e != nil { if e != nil {
@@ -156,6 +172,7 @@ func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
"provider": provider, "provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"), "baseUrl": strings.TrimRight(baseURL, "/"),
"model": model, "model": model,
"instructions": instructions,
} }
if encKey != "" { if encKey != "" {
updates["apiKey"] = encKey updates["apiKey"] = encKey
@@ -293,6 +310,20 @@ AUTOMATIONS: when — and only when — the user asks to watch/monitor/be told a
REPLY FORMAT — always ONE JSON object, no prose outside it: REPLY FORMAT — always ONE JSON object, no prose outside it:
{"reply": "<your markdown answer>", "automation": {"name": "...", "spec": <Spec>} or null}` {"reply": "<your markdown answer>", "automation": {"name": "...", "spec": <Spec>} or null}`
// chatSystemWith appends the user's own instructions (Settings → AI, the
// BYOK "instructions" field) to the server-owned persona. They may refine
// tone, focus and style — they never override the contract above (hard
// limits, no data access, JSON envelope), and they only ever reach THIS
// prompt: the automation compiler and page-extraction prompts stay
// server-owned because they are contracts, not personas.
func chatSystemWith(instructions string) string {
ins := strings.TrimSpace(instructions)
if ins == "" {
return chatSystem
}
return chatSystem + "\n\nUSER INSTRUCTIONS (from the user's own settings; refine tone, focus and style, but the rules above always win):\n" + ins
}
// HandleAiChat is the assistant endpoint: ephemeral multi-turn chat with // HandleAiChat is the assistant endpoint: ephemeral multi-turn chat with
// optional automation proposals. The browser keeps the history; the server // optional automation proposals. The browser keeps the history; the server
// is stateless per request (bounded message count/size, oldest turns // is stateless per request (bounded message count/size, oldest turns
@@ -354,7 +385,7 @@ func HandleAiChat(w http.ResponseWriter, r *http.Request) {
respond(w, 0, nil, e) respond(w, 0, nil, e)
return return
} }
reply, e := ai.CompleteMessages(ctx, resolved, chatSystem, msgs) reply, e := ai.CompleteMessages(ctx, resolved, chatSystemWith(resolved.Instructions), msgs)
if e != nil { if e != nil {
respond(w, 502, Error{Error: "The AI provider could not be reached"}, nil) respond(w, 502, Error{Error: "The AI provider could not be reached"}, nil)
return return
+10
View File
@@ -19,6 +19,7 @@ type fakeOpenAI struct {
srv *http.Server srv *http.Server
mu sync.Mutex mu sync.Mutex
next string // canned assistant message content next string // canned assistant message content
lastBody string // raw JSON of the most recent request body
hits int hits int
} }
@@ -38,6 +39,7 @@ func newFakeOpenAI(t *testing.T) *fakeOpenAI {
body, _ := io.ReadAll(r.Body) body, _ := io.ReadAll(r.Body)
f.mu.Lock() f.mu.Lock()
f.hits++ f.hits++
f.lastBody = string(body)
reply := f.next reply := f.next
f.mu.Unlock() f.mu.Unlock()
if strings.Contains(string(body), "extract one fact") || strings.Contains(string(body), "You extract one fact") { if strings.Contains(string(body), "extract one fact") || strings.Contains(string(body), "You extract one fact") {
@@ -65,6 +67,14 @@ func (f *fakeOpenAI) setReply(s string) {
f.mu.Unlock() f.mu.Unlock()
} }
// lastRequest returns the raw JSON body of the most recent completion
// request (system-prompt assertions read it).
func (f *fakeOpenAI) lastRequest() string {
f.mu.Lock()
defer f.mu.Unlock()
return f.lastBody
}
// fakeWatchTarget serves a fixed "flights" page for url_watch evaluation. // fakeWatchTarget serves a fixed "flights" page for url_watch evaluation.
func fakeWatchTarget(t *testing.T) string { func fakeWatchTarget(t *testing.T) string {
t.Helper() t.Helper()
+21
View File
@@ -4,6 +4,7 @@ import (
"net" "net"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"strings"
"testing" "testing"
) )
@@ -90,6 +91,26 @@ func TestAiChat(t *testing.T) {
t.Setenv("AI_API_KEY", "") t.Setenv("AI_API_KEY", "")
alice.request("POST", "/api/ai/chat", msgs("anything"), 428) alice.request("POST", "/api/ai/chat", msgs("anything"), 428)
// --- user instructions ride along on the assistant system prompt ---
// A BYO config resolves even with the server key unset. Instructions
// apply to THIS prompt only — never to the compiler/extraction contracts.
alice.request("PUT", "/api/ai/config", map[string]any{
"provider": "openai-compatible", "baseUrl": "http://" + host + ":" + port + "/v1",
"model": "byo-model", "apiKey": "sk-byo-chat", "instructions": "Answer like a pirate.",
}, 201)
fake.setReply(`{"reply":"Arr.","automation":null}`)
out = alice.request("POST", "/api/ai/chat", msgs("hello"), 200)
if out["reply"] != "Arr." {
t.Fatalf("byo chat reply = %v", out["reply"])
}
body := fake.lastRequest()
if !strings.Contains(body, "Answer like a pirate.") {
t.Fatal("user instructions missing from the assistant system prompt")
}
if !strings.Contains(body, "USER INSTRUCTIONS") {
t.Fatal("instructions must be appended as a delimited user section")
}
// The chat route is session-authenticated like every /api/ai route. // The chat route is session-authenticated like every /api/ai route.
anon, _ := cookiejar.New(nil) anon, _ := cookiejar.New(nil)
stranger := apiClient{t, &http.Client{Jar: anon}, srv.URL} stranger := apiClient{t, &http.Client{Jar: anon}, srv.URL}
+15 -2
View File
@@ -80,14 +80,22 @@ func TestAiConfig(t *testing.T) {
// Compile inherits the same precondition. // Compile inherits the same precondition.
alice.request("POST", "/api/agent/compile", map[string]any{"text": "x"}, 428) alice.request("POST", "/api/agent/compile", map[string]any{"text": "x"}, 428)
// --- PUT create: openai-compatible with a BYO key --- // --- PUT create: openai-compatible with a BYO key + instructions ---
created := alice.request("PUT", "/api/ai/config", map[string]any{ created := alice.request("PUT", "/api/ai/config", map[string]any{
"provider": "openai-compatible", "baseUrl": base + "/v1", "model": "test-model", "provider": "openai-compatible", "baseUrl": base + "/v1", "model": "test-model",
"apiKey": "sk-byo-secret-123", "apiKey": "sk-byo-secret-123", "instructions": "Answer like a pirate.",
}, 201) }, 201)
if created["apiKey"] != "••••••••" { if created["apiKey"] != "••••••••" {
t.Fatalf("key leaked in response: %v", created["apiKey"]) t.Fatalf("key leaked in response: %v", created["apiKey"])
} }
if created["instructions"] != "Answer like a pirate." {
t.Fatalf("instructions not echoed: %v", created["instructions"])
}
// GET returns the same projection (instructions are not a secret).
gotCfg := alice.request("GET", "/api/ai/config", nil, 200)
if gotCfg["instructions"] != "Answer like a pirate." || gotCfg["apiKey"] != "••••••••" {
t.Fatalf("GET projection wrong: %v", gotCfg)
}
// Encrypted at rest, decryptable with the server secret. // Encrypted at rest, decryptable with the server secret.
var storedKey string var storedKey string
if e := d.QueryRow(`SELECT "apiKey" FROM "UserAiConfig" WHERE "ownerId"=(SELECT id FROM "User" WHERE email='alice@superbrain.test')`).Scan(&storedKey); e != nil { if e := d.QueryRow(`SELECT "apiKey" FROM "UserAiConfig" WHERE "ownerId"=(SELECT id FROM "User" WHERE email='alice@superbrain.test')`).Scan(&storedKey); e != nil {
@@ -116,6 +124,10 @@ func TestAiConfig(t *testing.T) {
"provider": "anthropic", "baseUrl": base, "model": "claude-x", "provider": "anthropic", "baseUrl": base, "model": "claude-x",
"apiKey": "••••••••", "version": int(created["version"].(float64)), "apiKey": "••••••••", "version": int(created["version"].(float64)),
}, 200) }, 200)
// Full-replacement semantics: omitting instructions clears them.
if updated["instructions"] != "" {
t.Fatalf("instructions must clear when omitted: %v", updated["instructions"])
}
alice.request("POST", "/api/ai/test", nil, 200) alice.request("POST", "/api/ai/test", nil, 200)
if got := fake.lastAuth["anthropic"]; got != "sk-byo-secret-123|2023-06-01" { if got := fake.lastAuth["anthropic"]; got != "sk-byo-secret-123|2023-06-01" {
t.Fatalf("anthropic adapter headers = %q (mask must preserve the stored key)", got) t.Fatalf("anthropic adapter headers = %q (mask must preserve the stored key)", got)
@@ -136,6 +148,7 @@ func TestAiConfig(t *testing.T) {
alice.request("PUT", "/api/ai/config", map[string]any{"provider": "skynet", "model": "x", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "skynet", "model": "x", "apiKey": "k", "version": 3}, 400)
alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "", "apiKey": "k", "version": 3}, 400)
alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "m", "baseUrl": "ftp://x", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "m", "baseUrl": "ftp://x", "apiKey": "k", "version": 3}, 400)
alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "m", "apiKey": "k", "instructions": strings.Repeat("x", 4001), "version": 3}, 400)
// --- Plan gate on the SERVER key --- // --- Plan gate on the SERVER key ---
// Selfhosted (the harness default) may spend the operator's key. // Selfhosted (the harness default) may spend the operator's key.
+122 -28
View File
@@ -1,45 +1,66 @@
'use client' 'use client'
// Settings → AI: per-user BYO provider configuration. Config is data // Settings → AI: per-user BYO provider configuration ("Bring Your Own AI").
// (UserAiConfig row), implementation is server-side adapters — the UI only // Config is data (UserAiConfig row), implementation is server-side adapters
// ever sees masked keys and the resolved availability status. The server // — the UI only ever sees masked keys and the resolved availability status.
// key (operator env) shows as a fallback the user's plan may or may not // The server key (operator env) shows as a fallback the user's plan may or
// include; the UI never learns whether the key itself exists beyond that. // may not include; the UI never learns whether the key itself exists beyond
// that. The optional instructions field is the user's own system-prompt
// refinement for the in-app assistant (server contracts stay server-owned).
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch' import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Bot, Loader2, Trash2, PlugZap } from 'lucide-react' import { Bot, Loader2, Trash2, PlugZap, Eye, EyeOff } from 'lucide-react'
import { toast } from 'sonner' import { toast } from 'sonner'
const KEY_MASK = '••••••••' const KEY_MASK = '••••••••'
const INSTRUCTIONS_MAX = 4000 // mirrors the server cap (handlers/ai.go)
type AiConfig = { type AiConfig = {
id: string; provider: string; baseUrl: string; model: string id: string; provider: string; baseUrl: string; model: string
apiKey: string; enabled: boolean; version: number instructions: string; apiKey: string; enabled: boolean; version: number
} }
type AiStatus = { type AiStatus = {
userConfigured: boolean; userEnabled: boolean userConfigured: boolean; userEnabled: boolean
serverAvailable: boolean; effective: string; plan: string serverAvailable: boolean; effective: string; plan: string
} }
const PROVIDERS: Record<string, { label: string; defaultBase: string; modelHint: string }> = { const PROVIDERS: Record<string, { label: string; defaultBase: string; models: string[] }> = {
'openai-compatible': { 'openai-compatible': {
label: 'OpenAI-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, …)', label: 'OpenAI-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, …)',
defaultBase: 'https://openrouter.ai/api/v1', defaultBase: 'https://openrouter.ai/api/v1',
modelHint: 'e.g. recursive/flint-v1.0:free or gpt-4o-mini', models: ['gpt-4o-mini', 'gpt-4o', 'recursive/flint-v1.0:free'],
},
anthropic: {
label: 'Anthropic (Claude)',
defaultBase: 'https://api.anthropic.com',
models: ['claude-sonnet-4-5', 'claude-opus-4-1', 'claude-3-5-haiku-latest'],
},
gemini: {
label: 'Google Gemini',
defaultBase: 'https://generativelanguage.googleapis.com',
models: ['gemini-2.5-flash', 'gemini-2.5-pro', 'gemini-2.0-flash'],
}, },
anthropic: { label: 'Anthropic (Claude)', defaultBase: 'https://api.anthropic.com', modelHint: 'e.g. claude-sonnet-4-5' },
gemini: { label: 'Google Gemini', defaultBase: 'https://generativelanguage.googleapis.com', modelHint: 'e.g. gemini-2.0-flash' },
} }
// Sentinel for "none of the suggested models — type your own" (OpenRouter
// catalogs, local Ollama names, …). The API itself accepts any model string;
// the dropdown is a convenience, not an allowlist.
const CUSTOM_MODEL = '__custom__'
async function api(path: string, init?: RequestInit): Promise<Response> { async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
} }
function FieldLabel({ children }: { children: React.ReactNode }) {
return <label className="text-xs font-medium">{children}</label>
}
export function AiSettings() { export function AiSettings() {
const [config, setConfig] = useState<AiConfig | null>(null) const [config, setConfig] = useState<AiConfig | null>(null)
const [status, setStatus] = useState<AiStatus | null>(null) const [status, setStatus] = useState<AiStatus | null>(null)
@@ -49,8 +70,10 @@ export function AiSettings() {
const [provider, setProvider] = useState('openai-compatible') const [provider, setProvider] = useState('openai-compatible')
const [baseUrl, setBaseUrl] = useState('') const [baseUrl, setBaseUrl] = useState('')
const [model, setModel] = useState('') const [model, setModel] = useState(PROVIDERS['openai-compatible'].models[0])
const [apiKey, setApiKey] = useState('') const [apiKey, setApiKey] = useState('')
const [showKey, setShowKey] = useState(false)
const [instructions, setInstructions] = useState('')
// Promise-chain loading (house pattern: no synchronous setState in // Promise-chain loading (house pattern: no synchronous setState in
// effects — the SSR lint refuses cascading renders). // effects — the SSR lint refuses cascading renders).
@@ -65,6 +88,7 @@ export function AiSettings() {
setProvider(cfg.provider) setProvider(cfg.provider)
setBaseUrl(cfg.baseUrl ?? '') setBaseUrl(cfg.baseUrl ?? '')
setModel(cfg.model ?? '') setModel(cfg.model ?? '')
setInstructions(cfg.instructions ?? '')
setApiKey('') // never prefill secrets; empty keeps the stored key setApiKey('') // never prefill secrets; empty keeps the stored key
} else { } else {
setConfig(null) setConfig(null)
@@ -76,6 +100,14 @@ export function AiSettings() {
useEffect(() => { reload() }, [reload]) useEffect(() => { reload() }, [reload])
const changeProvider = (v: string) => {
setProvider(v)
setBaseUrl('')
// The suggested-model list is per provider; fall back to its first entry
// when the current model belongs to the old provider.
if (!PROVIDERS[v].models.includes(model)) setModel(PROVIDERS[v].models[0])
}
const save = async () => { const save = async () => {
if (!model.trim()) { toast.error('Model is required'); return } if (!model.trim()) { toast.error('Model is required'); return }
if (!config && !apiKey.trim()) { toast.error('API key is required'); return } if (!config && !apiKey.trim()) { toast.error('API key is required'); return }
@@ -85,6 +117,7 @@ export function AiSettings() {
provider, provider,
baseUrl: baseUrl.trim() || PROVIDERS[provider].defaultBase, baseUrl: baseUrl.trim() || PROVIDERS[provider].defaultBase,
model: model.trim(), model: model.trim(),
instructions: instructions.trim(),
// Empty input on an existing config keeps the stored key (same // Empty input on an existing config keeps the stored key (same
// write-only contract as the mask). // write-only contract as the mask).
apiKey: apiKey.trim() || (config ? KEY_MASK : ''), apiKey: apiKey.trim() || (config ? KEY_MASK : ''),
@@ -94,6 +127,7 @@ export function AiSettings() {
if (res.ok) { if (res.ok) {
toast.success('AI settings saved') toast.success('AI settings saved')
setApiKey('') setApiKey('')
setShowKey(false)
await reload() await reload()
} else { } else {
const data = await res.json().catch(() => null) const data = await res.json().catch(() => null)
@@ -119,7 +153,8 @@ export function AiSettings() {
const res = await api('/api/ai/config', { method: 'DELETE' }) const res = await api('/api/ai/config', { method: 'DELETE' })
if (res.ok) { if (res.ok) {
toast.success('Your AI key was removed') toast.success('Your AI key was removed')
setConfig(null); setApiKey(''); setModel(''); setBaseUrl('') setConfig(null); setApiKey(''); setShowKey(false); setInstructions('')
setBaseUrl(''); setModel(PROVIDERS[provider].models[0])
await reload() await reload()
} else { } else {
const data = await res.json().catch(() => null) const data = await res.json().catch(() => null)
@@ -133,6 +168,7 @@ export function AiSettings() {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ body: JSON.stringify({
provider: config.provider, baseUrl: config.baseUrl, model: config.model, provider: config.provider, baseUrl: config.baseUrl, model: config.model,
instructions: config.instructions,
apiKey: KEY_MASK, enabled, version: config.version, apiKey: KEY_MASK, enabled, version: config.version,
}), }),
}) })
@@ -147,14 +183,17 @@ export function AiSettings() {
return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading AI settings…</div> return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading AI settings…</div>
} }
const suggested = PROVIDERS[provider].models
const modelChoice = suggested.includes(model) ? model : CUSTOM_MODEL
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="rounded-lg border p-4 space-y-3"> <div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Bot className="h-4 w-4" /> Your AI provider</h3> <h3 className="font-medium flex items-center gap-2"><Bot className="h-4 w-4" /> Bring your own AI</h3>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Superbrain uses AI for <strong>Automations</strong> (compiling “hey superbrain” requests and Connect your own LLM API key so Superbrain can run AI features for your account. Your key
reading watched pages). Bring your own provider and key — it is stored encrypted, never is stored encrypted in the server database — it is never shown again in the browser and is
shown again, and used only for your requests. only ever sent to the provider you choose.
{status?.serverAvailable {status?.serverAvailable
? ' This server also provides a shared AI key included in your plan; your own key takes precedence.' ? ' This server also provides a shared AI key included in your plan; your own key takes precedence.'
: ' Your plan is bring-your-own-key, so automations need a key here.'} : ' Your plan is bring-your-own-key, so automations need a key here.'}
@@ -173,8 +212,10 @@ export function AiSettings() {
)} )}
</div> </div>
<div className="space-y-2 border-t pt-3"> <div className="space-y-3 border-t pt-3">
<Select value={provider} onValueChange={(v: string) => { setProvider(v); setBaseUrl('') }}> <div className="space-y-1">
<FieldLabel>Model providers</FieldLabel>
<Select value={provider} onValueChange={changeProvider}>
<SelectTrigger aria-label="Provider"><SelectValue /></SelectTrigger> <SelectTrigger aria-label="Provider"><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
{Object.entries(PROVIDERS).map(([k, p]) => ( {Object.entries(PROVIDERS).map(([k, p]) => (
@@ -182,26 +223,79 @@ export function AiSettings() {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
</div>
<div className="space-y-1">
<FieldLabel>Base URL (optional)</FieldLabel>
<Input <Input
placeholder={`Base URL (blank = ${PROVIDERS[provider].defaultBase})`} placeholder={`blank = ${PROVIDERS[provider].defaultBase}`}
value={baseUrl} value={baseUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBaseUrl(e.target.value)} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBaseUrl(e.target.value)}
aria-label="Base URL" aria-label="Base URL"
/> />
</div>
<div className="space-y-1">
<FieldLabel>API key {config && <span className="text-muted-foreground">(leave blank to keep the current key)</span>}</FieldLabel>
<div className="relative">
<Input <Input
placeholder={`Model — ${PROVIDERS[provider].modelHint}`} type={showKey ? 'text' : 'password'}
value={model} className="pr-10"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModel(e.target.value)} placeholder={config ? KEY_MASK : 'sk-…'}
aria-label="Model"
/>
<Input
type="password"
placeholder={config ? 'API key (leave blank to keep the current key)' : 'API key'}
value={apiKey} value={apiKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setApiKey(e.target.value)} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setApiKey(e.target.value)}
aria-label="API key" aria-label="API key"
autoComplete="off" autoComplete="off"
/> />
<button
type="button"
onClick={() => setShowKey(v => !v)}
aria-label={showKey ? 'Hide API key' : 'Show API key'}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground"
>
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="space-y-1">
<FieldLabel>Default model</FieldLabel>
<Select value={modelChoice} onValueChange={(v: string) => setModel(v === CUSTOM_MODEL ? '' : v)}>
<SelectTrigger aria-label="Default model"><SelectValue /></SelectTrigger>
<SelectContent>
{suggested.map(m => (
<SelectItem key={m} value={m}>{m}</SelectItem>
))}
<SelectItem value={CUSTOM_MODEL}>Custom model…</SelectItem>
</SelectContent>
</Select>
{modelChoice === CUSTOM_MODEL && (
<Input
className="mt-2"
placeholder={`Model ID — e.g. ${suggested[0]}`}
value={model}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModel(e.target.value)}
aria-label="Custom model"
/>
)}
</div>
<div className="space-y-1">
<FieldLabel>Instructions (optional)</FieldLabel>
<Textarea
placeholder="Custom system instructions for the AI. Leave empty for defaults."
value={instructions}
rows={3}
maxLength={INSTRUCTIONS_MAX}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setInstructions(e.target.value.slice(0, INSTRUCTIONS_MAX))}
aria-label="Instructions"
/>
<p className="text-xs text-muted-foreground">
Refines the in-app assistant&rsquo;s tone and focus. Automation and page-reading prompts
stay server-owned, so hard limits always apply.
</p>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
<Button size="sm" onClick={save} loading={saving}>{config ? 'Save changes' : 'Save AI settings'}</Button> <Button size="sm" onClick={save} loading={saving}>{config ? 'Save changes' : 'Save AI settings'}</Button>
<Button size="sm" variant="outline" onClick={test} loading={testing} className="gap-1.5"> <Button size="sm" variant="outline" onClick={test} loading={testing} className="gap-1.5">