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.
This commit is contained in:
Andrew S Erwin
2026-10-31 19:09:44 -05:00
parent 1dfd41986c
commit 09f8a5d933
10 changed files with 272 additions and 81 deletions
+16 -10
View File
@@ -68,13 +68,18 @@ var ErrNoAI = errors.New("ai: no configuration available for this user")
// Resolved is one usable endpoint. Source is "user" (BYO) or "server"
// (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 {
Provider string
BaseURL string
Model string
APIKey string
Source string
UserID string
Provider string
BaseURL string
Model string
APIKey string
Instructions string
Source string
UserID string
}
// client dials through netguard for every provider (public ranges +
@@ -128,11 +133,11 @@ func serverConfig() (Resolved, bool) {
// ResolveForUser applies the resolution chain: the user's enabled BYO
// 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) {
var id, provider, baseURL, model, encKey string
var id, provider, baseURL, model, encKey, instructions string
var enabled bool
err := d.QueryRowContext(ctx,
`SELECT id, provider, "baseUrl", model, "apiKey", enabled FROM "UserAiConfig" WHERE "ownerId"=$1`,
userID).Scan(&id, &provider, &baseURL, &model, &encKey, &enabled)
`SELECT id, provider, "baseUrl", model, "apiKey", instructions, enabled FROM "UserAiConfig" WHERE "ownerId"=$1`,
userID).Scan(&id, &provider, &baseURL, &model, &encKey, &instructions, &enabled)
if err == nil && enabled && encKey != "" {
key, decErr := crypt.Decrypt(encKey, config.Load().EncryptionSecret())
if decErr != nil {
@@ -140,7 +145,8 @@ func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, err
}
return Resolved{
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
}
if err != nil && !errors.Is(err, sql.ErrNoRows) {
+43 -12
View File
@@ -1,11 +1,13 @@
package handlers
// Per-user AI configuration (Settings → AI): provider, model, base URL and
// a bring-your-own API key. Config is data; internal/ai is the
// implementation. The key is encrypted at rest (internal/crypto, the same
// versioned format as every other stored credential), masked in every
// response, and a PUT echoing the mask keeps the stored key. The server
// env key remains the plan-gated fallback (entitlements.AllowServerAI).
// Per-user AI configuration (Settings → AI): provider, model, base URL,
// optional custom instructions and a bring-your-own API key. Config is
// data; internal/ai is the implementation. The key is encrypted at rest
// (internal/crypto, the same versioned format as every other stored
// credential), masked in every response, and a PUT echoing the mask keeps
// the stored key. Instructions ride along on the assistant chat prompt
// only. The server env key remains the plan-gated fallback
// (entitlements.AllowServerAI).
import (
"context"
@@ -43,11 +45,16 @@ func aiConfigProjection(row object) object {
}
return object{
"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"],
}
}
// 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.
func HandleAiConfigGet(w http.ResponseWriter, r *http.Request) {
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"))
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")
existing, e := db.One(r.Context(), database(r),
@@ -122,7 +137,8 @@ func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
row, e := db.Insert(r.Context(), database(r), "UserAiConfig", object{
"id": db.NewID(), "ownerId": user(r), "provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"), "model": model,
"apiKey": encKey, "enabled": enabled,
"instructions": instructions,
"apiKey": encKey, "enabled": enabled,
})
if e != nil {
respond(w, 0, nil, e)
@@ -153,9 +169,10 @@ func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
}
}
updates := object{
"provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"),
"model": model,
"provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"),
"model": model,
"instructions": instructions,
}
if 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": "<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
// optional automation proposals. The browser keeps the history; the server
// 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)
return
}
reply, e := ai.CompleteMessages(ctx, resolved, chatSystem, msgs)
reply, e := ai.CompleteMessages(ctx, resolved, chatSystemWith(resolved.Instructions), msgs)
if e != nil {
respond(w, 502, Error{Error: "The AI provider could not be reached"}, nil)
return
+15 -5
View File
@@ -15,11 +15,12 @@ import (
// fakeOpenAI is a loopback OpenAI-compatible chat-completions server with a
// programmable reply, standing in for OpenRouter in tests.
type fakeOpenAI struct {
ln net.Listener
srv *http.Server
mu sync.Mutex
next string // canned assistant message content
hits int
ln net.Listener
srv *http.Server
mu sync.Mutex
next string // canned assistant message content
lastBody string // raw JSON of the most recent request body
hits int
}
func newFakeOpenAI(t *testing.T) *fakeOpenAI {
@@ -38,6 +39,7 @@ func newFakeOpenAI(t *testing.T) *fakeOpenAI {
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
f.hits++
f.lastBody = string(body)
reply := f.next
f.mu.Unlock()
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()
}
// 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.
func fakeWatchTarget(t *testing.T) string {
t.Helper()
+21
View File
@@ -4,6 +4,7 @@ import (
"net"
"net/http"
"net/http/cookiejar"
"strings"
"testing"
)
@@ -90,6 +91,26 @@ func TestAiChat(t *testing.T) {
t.Setenv("AI_API_KEY", "")
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.
anon, _ := cookiejar.New(nil)
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.
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{
"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)
if 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.
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 {
@@ -116,6 +124,10 @@ func TestAiConfig(t *testing.T) {
"provider": "anthropic", "baseUrl": base, "model": "claude-x",
"apiKey": "••••••••", "version": int(created["version"].(float64)),
}, 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)
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)
@@ -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": "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", "apiKey": "k", "instructions": strings.Repeat("x", 4001), "version": 3}, 400)
// --- Plan gate on the SERVER key ---
// Selfhosted (the harness default) may spend the operator's key.