Separate AI config from implementation: BYO provider, model and key per user
release gate / check (push) Failing after 6m42s

The plan matrix's 'use your own AI' rows, made real. internal/ai is now
pure implementation: three provider adapters — openai-compatible
(OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native
Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent;
the key travels in the x-goog-api-key HEADER, never the URL, because Go's
HTTP error strings include URLs and errors get logged). One netguard-dialed
client, per-source outbound budgets (ai:user:<id> vs ai:server).

Configuration is data: UserAiConfig (migration 015) — one row per user
with provider, base URL, model and an API key encrypted at rest via
internal/crypto (the IMAP-password format), masked in every response; a
PUT echoing the mask or leaving the key blank keeps the stored value;
version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config,
POST /api/ai/test (one probe completion through the resolved config),
GET /api/ai/status (plan-gated availability, no secrets).

Resolution chain (ai.ResolveForUser): the user's enabled BYO config first
on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/
AI_PROVIDER) only when the tenant's plan may spend it — new
entitlements.AllowServerAI: premium (credits), core (house gateway) and
selfhosted (operator IS the user); free/standard are BYO-only, exactly the
matrix. No AI available => 428 with a pointer to Settings -> AI (was a
global 503): the precondition is per-user now. Agent compile and url_watch
extraction resolve per owner, so different users' tasks can run on
different providers.

Web: Settings -> AI tab (provider picker with per-provider defaults and
model hints, write-only key input, Test button, effective-source badge
with plan context, enable switch, remove). The Automations tab reads
/api/ai/status for a proactive banner and treats 428 as 'not configured'.

Preparatory refactors (behavior-preserving): agent.AutomationSchema
extracted as the single spec text shared by the compiler prompt (and the
upcoming chat assistant), and ai.CompleteMessages for multi-turn
conversations with per-provider role mapping (assistant -> model on
Gemini).

Tests: all three adapters against one loopback fake (asserting each
provider's auth-header shape), masked-key lifecycle incl. mask-echo
preservation across a provider switch, encrypted-at-rest verification,
plan gate both directions (free refuses the server key, premium/core/
selfhosted allow it), BYO precedence over the server key, validation
rejects, 428 paths, and compile resolution through a BYO config.
Full suite green (-race), converge green (015), web lint/SSR/build clean.

Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first +
plan-gated server fallback, .env.example (AI_PROVIDER + the precedence
story), compose passthrough, AGENTS.md invariant (config vs
implementation, Gemini key-in-header rule).
This commit is contained in:
Andrew S Erwin
2026-10-28 19:16:17 -05:00
parent 19531cf8b9
commit 167f74c6b4
18 changed files with 1188 additions and 126 deletions
+30 -13
View File
@@ -295,19 +295,36 @@ without that confirmation.
### Setup
Add to `.env` (the Compose stack passes these to the Go container):
AI configuration is **separate from the implementation**: the server ships
provider adapters (any OpenAI-compatible endpoint — OpenRouter, OpenAI,
Grok, Groq, Ollama, house gateways — plus native Anthropic and Google
Gemini); who pays for the tokens is configuration:
```env
AI_API_KEY=... # required for AI features
AI_MODEL=recursive/flint-v1.0:free # any model your provider serves
AI_BASE_URL=https://openrouter.ai/api/v1 # any OpenAI-compatible endpoint
```
1. **Per user (bring your own key)** — **Settings → AI**: pick a provider,
model, optional base URL, and paste your API key. The key is encrypted
at rest, never echoed back (blank/masked input keeps the stored key),
and used only for *your* requests. There is a **Test** button. This
works on every plan.
2. **Server-wide fallback** — `.env` (optional):
OpenRouter is the default provider; point `AI_BASE_URL` at any
OpenAI-compatible gateway (a house LLM proxy, Ollama, ...). **Without
`AI_API_KEY` the AI parts answer "not configured" and everything else
keeps working** — including signal-condition automations, which need no AI
at run time at all. The key lives in `.env` only; never commit it.
```env
AI_API_KEY=... # operator's key
AI_MODEL=recursive/flint-v1.0:free # any model the provider serves
AI_BASE_URL=https://openrouter.ai/api/v1 # any OpenAI-compatible endpoint
AI_PROVIDER=openai-compatible # or anthropic / gemini
```
The server key is used only when the user has no own config **and** the
user's plan includes it (`premium` credits, `core`, and self-hosted —
the plan matrix's "built-in AI" rows; `free`/`standard` are
bring-your-own-key). Recreate containers after changing `.env`
(`docker compose up -d --force-recreate app`).
With neither configured, compilation and page-watching answer "AI is not
configured" (HTTP 428 with a pointer to Settings → AI) and **everything
else keeps working** — including signal-condition automations, which need
no AI at run time. Keys live in `.env`/encrypted rows only; never commit
them.
### Using it
@@ -369,9 +386,9 @@ hotels *then* bundle") — the compiler says so plainly instead of faking it
| Symptom | Fix |
|---|---|
| "AI is not configured on this server" | `AI_API_KEY` missing in `.env`, or containers not recreated after adding it (`docker compose up -d --force-recreate app`) |
| "AI is not configured" (428) on compile/test | No BYO config in Settings → AI **and** no plan-permitted server key (`AI_API_KEY` missing, or the plan is BYO-only). Self-hosted/core/premium may use the server key; free/standard cannot |
| Compile refuses with an explanation | Working as intended — one condition + one action per task; rephrase, or split into two tasks |
| Compile returns a provider error | Check `AI_MODEL` exists on your provider and the key has credit; free models can be slow or rate-limited |
| Compile returns a provider error | Check the model id exists at your provider and the key has credit; free models can be slow or rate-limited |
| Run outcome `failed: fetch …` | The watched URL blocked the fetch, moved, or is not public HTML/JSON |
| Run outcome `failed: extract …` | The model could not answer the question from the page; rephrase the watch question more concretely |
| Run outcome `skipped` | A cap was reached (emails/day, budget) or the channel was disabled — the detail column says which |