Moves the agent model out of env-only config into an admin-editable Settings
section, and enforces is_admin for the first time — it has been in the schema
since migration 0001, plumbed to the client, and checked nowhere.
Backend:
- Migration 0010: instance_settings, a single-row (CHECK id=1) table — pansy's
first instance-level state. Holds agent_model ('' = inherit env) and
agent_enabled (NULL = inherit env), version-guarded like every mutable row.
SECRETS STAY IN ENV: OLLAMA_CLOUD_API_KEY is never stored here.
- requireAdmin at the service seam (authoritative) plus a cheap middleware
early-403. Non-admin gets 403, not 404 — settings existence isn't masked.
- EffectiveAgent resolves DB-over-env (model, enabled); key always from env.
- The live Runner is hot-swapped, not built once. agentHolder holds it behind
an atomic.Pointer; the chat routes are now registered UNCONDITIONALLY and
nil-check agent.get(), so a settings change turns the assistant on/off/onto a
new model with no restart and no race against in-flight readers. /capabilities
reads the pointer, so it reports what's live, not what booted.
- internal/agentmodel is a new leaf package holding the one place that knows how
to turn a spec into a model. Both agent (to run) and service (to validate a
spec before storing it) import it; it can't live in agent, which imports
service. Settings PATCH validates the spec via Parse, so a typo is a 400 now
rather than a broken assistant on the next turn.
Frontend:
- /settings route (admin guard), a Settings page (model field, tri-state
enabled, live status), nav link shown only to admins.
- useCapabilities drops staleTime:Infinity — the assistant can now change under
a running page — and the settings save invalidates it.
Contract change: chat routes always exist, so "assistant off" is a runtime 503
+ capabilities:false, not a missing route. Updated the test that asserted the
old shape.
Verified live against the built binary: disable flips capabilities to false and
logs it; re-enable with a new model swaps it back; a bad spec is rejected 400;
the setting persists across a restart. Swap is race-clean under `go test -race`.
Docs: README (precedence + key-stays-in-env), DESIGN (decision + routes),
CLAUDE (don't re-add conditional route registration; key never in the DB).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01H3zbym8Doka2d7D48maSgZ
89 lines
3.7 KiB
Go
89 lines
3.7 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"sync"
|
|
"sync/atomic"
|
|
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/agent"
|
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
|
|
)
|
|
|
|
// agentHolder owns the live assistant Runner and lets an admin swap it at
|
|
// runtime when the model settings change (#79).
|
|
//
|
|
// The Runner used to be a plain handlers field set once at boot, with the chat
|
|
// routes registered only when it existed. That made the assistant permanently
|
|
// whatever the environment said at startup. Now the routes are always
|
|
// registered and the Runner lives behind an atomic pointer, so a settings change
|
|
// can turn the assistant on, off, or onto a different model without a restart —
|
|
// and without a data race against in-flight requests reading the pointer.
|
|
//
|
|
// A nil pointer means "no assistant right now"; handlers nil-check get() rather
|
|
// than assuming a Runner is present.
|
|
type agentHolder struct {
|
|
svc *service.Service
|
|
// apiKey is the OLLAMA_CLOUD_API_KEY from the environment. It never changes at
|
|
// runtime — only the model spec and the enabled flag are settings — and it is
|
|
// deliberately not something the settings UI can read or write.
|
|
apiKey string
|
|
|
|
ptr atomic.Pointer[agent.Runner]
|
|
// rebuildMu serializes rebuilds so two concurrent settings saves can't
|
|
// interleave into a torn "resolve A, resolve B, store A, store B" swap. The
|
|
// read path (get) stays lock-free on the atomic pointer.
|
|
rebuildMu sync.Mutex
|
|
}
|
|
|
|
// newAgentHolder builds the holder and resolves the initial Runner from whatever
|
|
// the settings + environment currently say. A resolution failure is logged and
|
|
// left as "no assistant", never fatal: a garden planner must still boot.
|
|
func newAgentHolder(ctx context.Context, svc *service.Service, apiKey string) *agentHolder {
|
|
h := &agentHolder{svc: svc, apiKey: apiKey}
|
|
h.rebuild(ctx)
|
|
return h
|
|
}
|
|
|
|
// get returns the current Runner, or nil if the assistant is off.
|
|
func (h *agentHolder) get() *agent.Runner { return h.ptr.Load() }
|
|
|
|
// rebuild resolves the effective agent configuration and swaps the Runner to
|
|
// match: a new one when the assistant should be on, nil when it shouldn't. It is
|
|
// safe to call at boot and from a settings save; concurrent calls serialize.
|
|
//
|
|
// It logs what it did rather than returning an error, because every caller wants
|
|
// the same thing — best-effort apply, keep serving either way — and a settings
|
|
// save must not fail just because the new model won't resolve. The save already
|
|
// validated the spec; a rebuild failure here means the environment changed under
|
|
// it, and "assistant off, with a reason in the log" is the right outcome.
|
|
func (h *agentHolder) rebuild(ctx context.Context) {
|
|
h.rebuildMu.Lock()
|
|
defer h.rebuildMu.Unlock()
|
|
|
|
eff, err := h.svc.EffectiveAgent(ctx)
|
|
if err != nil {
|
|
slog.Error("api: could not resolve agent settings; leaving assistant unchanged", "error", err)
|
|
return
|
|
}
|
|
// The env key is authoritative; EffectiveAgent reports it, but the holder was
|
|
// handed it directly at construction, so use that.
|
|
if !eff.Enabled || h.apiKey == "" || eff.Model == "" {
|
|
if h.ptr.Swap(nil) != nil {
|
|
slog.Info("api: garden assistant turned off", "enabled", eff.Enabled, "hasModel", eff.Model != "")
|
|
}
|
|
return
|
|
}
|
|
runner, err := agent.NewRunner(h.svc, h.apiKey, eff.Model)
|
|
if err != nil {
|
|
// Configured but unusable. Turn the assistant off rather than leaving a
|
|
// stale Runner on the old model — an admin who just pointed it at a broken
|
|
// spec should see it stop, not silently keep answering on the previous one.
|
|
slog.Error("api: garden assistant disabled (model won't resolve)", "error", err, "model", eff.Model)
|
|
h.ptr.Store(nil)
|
|
return
|
|
}
|
|
h.ptr.Store(runner)
|
|
slog.Info("api: garden assistant ready", "model", eff.Model)
|
|
}
|