Phase 0: turn Supermarket into a Dockerized local web app
Replace the old Go TUI with a web app (port 8470) that runs in a container as a CoreDesktop sibling: - cmd/supermarket server with htmx web UI: dashboard, company profile, inventory (partners/competitors), AI and credential settings, and a Core & Hermes page - SQLite storage and a secrets store under ~/.local/share/supermarket - AI providers (Anthropic, OpenAI-compatible) behind one interface - MCP server and a Hermes bridge to the Federated Core MCP hub - Import of the old Coremarketing TUI's state - install.sh / update.sh / lib.sh, Dockerfile, compose.yaml, the bin/supermarket launcher and hermes/setup.sh Posting is not wired back up yet; that comes in Phase 1. See PLAN.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
// Package ai sends prompts to the configured model provider: Anthropic, or
|
||||
// any server that speaks the OpenAI chat-completions API (Ollama, LM Studio,
|
||||
// llama.cpp, vLLM, OpenRouter, ...).
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
// Providers.
|
||||
const (
|
||||
ProviderAnthropic = "anthropic"
|
||||
ProviderOpenAI = "openai" // OpenAI-compatible server
|
||||
)
|
||||
|
||||
// DefaultAnthropicModel is the model used until the user picks another.
|
||||
const DefaultAnthropicModel = "claude-opus-5-5"
|
||||
|
||||
// Tasks the app asks a model to do. Each can use its own model.
|
||||
const (
|
||||
TaskProfile = "profile" // drafting the company profile from a website
|
||||
TaskContent = "content" // writing posts
|
||||
)
|
||||
|
||||
// Tasks lists the tasks with a description, for the settings page.
|
||||
var Tasks = []struct{ ID, Label string }{
|
||||
{TaskProfile, "Drafting the company profile"},
|
||||
{TaskContent, "Writing posts"},
|
||||
}
|
||||
|
||||
// Config is the AI setting.
|
||||
type Config struct {
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
BaseURL string `json:"base_url,omitempty"` // OpenAI-compatible servers only
|
||||
Effort string `json:"effort,omitempty"` // Anthropic: low, medium, high, xhigh, max
|
||||
// TaskModels overrides the model for a task, on the same provider.
|
||||
TaskModels map[string]string `json:"task_models,omitempty"`
|
||||
}
|
||||
|
||||
const settingKey = "ai"
|
||||
|
||||
// LoadConfig returns the saved AI config, or Anthropic's defaults.
|
||||
func LoadConfig(d *db.DB) (Config, error) {
|
||||
c := Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel, Effort: "medium"}
|
||||
if _, err := d.GetJSON(settingKey, &c); err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// SaveConfig stores the AI config.
|
||||
func SaveConfig(d *db.DB, c Config) error {
|
||||
return d.PutJSON(settingKey, c)
|
||||
}
|
||||
|
||||
// ModelFor is the model to use for task.
|
||||
func (c Config) ModelFor(task string) string {
|
||||
if m := strings.TrimSpace(c.TaskModels[task]); m != "" {
|
||||
return m
|
||||
}
|
||||
return c.Model
|
||||
}
|
||||
|
||||
// Request is one prompt.
|
||||
type Request struct {
|
||||
Task string // picks the model; see Config.TaskModels
|
||||
System string
|
||||
Prompt string
|
||||
MaxTokens int
|
||||
// Schema, if set, asks for JSON matching this JSON Schema; the reply's
|
||||
// text is then that JSON.
|
||||
Schema map[string]any
|
||||
}
|
||||
|
||||
// Client is a provider with its config.
|
||||
type Client interface {
|
||||
Generate(ctx context.Context, req Request) (string, error)
|
||||
}
|
||||
|
||||
// ErrNotConfigured means the provider can't be used yet (no key, no server).
|
||||
var ErrNotConfigured = errors.New("AI provider not configured")
|
||||
|
||||
// New returns a client for the config, using keys from the secrets store.
|
||||
func New(c Config, sec *secrets.Store) (Client, error) {
|
||||
switch c.Provider {
|
||||
case ProviderAnthropic, "":
|
||||
key := sec.Get(secrets.AnthropicAPIKey)
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("%w: add an Anthropic API key in Settings", ErrNotConfigured)
|
||||
}
|
||||
return newAnthropic(key, c), nil
|
||||
case ProviderOpenAI:
|
||||
if strings.TrimSpace(c.BaseURL) == "" {
|
||||
return nil, fmt.Errorf("%w: set the server's address in Settings", ErrNotConfigured)
|
||||
}
|
||||
return newOpenAI(c.BaseURL, sec.Get(secrets.OpenAIAPIKey), c), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown AI provider %q", c.Provider)
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateJSON runs req (which must have a Schema) and decodes the reply into
|
||||
// out. Servers that ignore the schema sometimes wrap the JSON in prose or a
|
||||
// code fence, so the outermost {...} is decoded.
|
||||
func GenerateJSON(ctx context.Context, c Client, req Request, out any) error {
|
||||
if req.Schema == nil {
|
||||
return errors.New("GenerateJSON needs a schema")
|
||||
}
|
||||
text, err := c.Generate(ctx, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return decodeJSON(text, out)
|
||||
}
|
||||
|
||||
func decodeJSON(text string, out any) error {
|
||||
start := strings.Index(text, "{")
|
||||
end := strings.LastIndex(text, "}")
|
||||
if start < 0 || end < start {
|
||||
return fmt.Errorf("the model didn't return JSON: %.200q", text)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(text[start:end+1]), out); err != nil {
|
||||
return fmt.Errorf("the model returned invalid JSON: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
func TestNormalizeBaseURL(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"llm.lan:11434": "http://llm.lan:11434/v1",
|
||||
"http://llm.lan:11434/": "http://llm.lan:11434/v1",
|
||||
"https://openrouter.ai/api/v1": "https://openrouter.ai/api/v1",
|
||||
" ": "",
|
||||
} {
|
||||
if got := NormalizeBaseURL(in); got != want {
|
||||
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONToleratesFences(t *testing.T) {
|
||||
var out struct{ Name string }
|
||||
if err := decodeJSON("Here you go:\n```json\n{\"Name\": \"Acme\"}\n```", &out); err != nil || out.Name != "Acme" {
|
||||
t.Errorf("%+v %v", out, err)
|
||||
}
|
||||
if err := decodeJSON("no json here", &out); err == nil {
|
||||
t.Error("expected an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAICompatible(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/v1/models":
|
||||
w.Write([]byte(`{"data":[{"id":"qwen3"},{"id":"llama3.3"}]}`))
|
||||
case "/v1/chat/completions":
|
||||
json.NewDecoder(r.Body).Decode(&got)
|
||||
w.Write([]byte(`{"choices":[{"message":{"content":" {\"ok\": true} "},"finish_reason":"stop"}]}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
models, err := ListModels(context.Background(), srv.URL, "")
|
||||
if err != nil || len(models) != 2 || models[0] != "llama3.3" {
|
||||
t.Fatalf("models: %v %v", models, err)
|
||||
}
|
||||
|
||||
cfg := Config{Provider: ProviderOpenAI, Model: "qwen3", BaseURL: srv.URL, TaskModels: map[string]string{TaskProfile: "llama3.3"}}
|
||||
c, err := New(cfg, mustSecrets(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out struct{ OK bool }
|
||||
err = GenerateJSON(context.Background(), c, Request{Task: TaskProfile, System: "s", Prompt: "p", Schema: map[string]any{"type": "object"}}, &out)
|
||||
if err != nil || !out.OK {
|
||||
t.Fatalf("%+v %v", out, err)
|
||||
}
|
||||
if got["model"] != "llama3.3" {
|
||||
t.Errorf("task model not used: %v", got["model"])
|
||||
}
|
||||
if msgs := got["messages"].([]any); len(msgs) != 2 {
|
||||
t.Errorf("messages: %v", msgs)
|
||||
}
|
||||
if got["response_format"] == nil {
|
||||
t.Error("schema not sent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewNeedsCredentials(t *testing.T) {
|
||||
sec := mustSecrets(t)
|
||||
if _, err := New(Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel}, sec); err == nil {
|
||||
t.Error("anthropic without a key should fail")
|
||||
}
|
||||
if _, err := New(Config{Provider: ProviderOpenAI, Model: "m"}, sec); err == nil {
|
||||
t.Error("openai without an address should fail")
|
||||
}
|
||||
sec.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
|
||||
if _, err := New(Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel}, sec); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigDefaults(t *testing.T) {
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
c, err := LoadConfig(d)
|
||||
if err != nil || c.Provider != ProviderAnthropic || c.Model != DefaultAnthropicModel || c.Effort != "medium" {
|
||||
t.Errorf("%+v %v", c, err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustSecrets(t *testing.T) *secrets.Store {
|
||||
t.Helper()
|
||||
s, err := secrets.Open(filepath.Join(t.TempDir(), "secrets.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/anthropics/anthropic-sdk-go/v2"
|
||||
"github.com/anthropics/anthropic-sdk-go/v2/option"
|
||||
)
|
||||
|
||||
type anthropicClient struct {
|
||||
client anthropic.Client
|
||||
cfg Config
|
||||
}
|
||||
|
||||
func newAnthropic(apiKey string, cfg Config) *anthropicClient {
|
||||
return &anthropicClient{
|
||||
client: anthropic.NewClient(option.WithAPIKey(apiKey)),
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
// Models that accept server-side refusal fallbacks. On these, a request a
|
||||
// safety classifier declines is re-served by another model in the same call
|
||||
// instead of failing.
|
||||
var fallbackModels = map[string]bool{
|
||||
"claude-fable-5-2": true,
|
||||
"claude-fable-5-1": true,
|
||||
"claude-opus-5-5": true,
|
||||
"claude-opus-5": true,
|
||||
"claude-sonnet-5-5": true,
|
||||
}
|
||||
|
||||
func (a *anthropicClient) Generate(ctx context.Context, req Request) (string, error) {
|
||||
model := a.cfg.ModelFor(req.Task)
|
||||
maxTokens := req.MaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 16000
|
||||
}
|
||||
|
||||
params := anthropic.BetaMessageNewParams{
|
||||
Model: anthropic.Model(model),
|
||||
MaxTokens: int64(maxTokens),
|
||||
Messages: []anthropic.BetaMessageParam{
|
||||
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(req.Prompt)),
|
||||
},
|
||||
}
|
||||
if req.System != "" {
|
||||
params.System = []anthropic.BetaTextBlockParam{{Text: req.System}}
|
||||
}
|
||||
// Thinking is left unset: on current models it runs adaptively, and effort
|
||||
// is the control. Set effort explicitly, since defaults differ by model.
|
||||
if effort := a.cfg.Effort; effort != "" {
|
||||
params.OutputConfig.Effort = anthropic.BetaOutputConfigEffort(effort)
|
||||
}
|
||||
if req.Schema != nil {
|
||||
params.OutputConfig.Format = anthropic.BetaJSONOutputFormatParam{Schema: req.Schema}
|
||||
}
|
||||
if fallbackModels[model] {
|
||||
params.Betas = append(params.Betas, anthropic.AnthropicBetaServerSideFallback2026_07_01)
|
||||
params.Fallbacks = anthropic.BetaFallbacksParamOfDefault()
|
||||
}
|
||||
|
||||
msg, err := a.client.Beta.Messages.New(ctx, params)
|
||||
if err != nil {
|
||||
var apierr *anthropic.Error
|
||||
if errors.As(err, &apierr) {
|
||||
switch apierr.StatusCode {
|
||||
case 401:
|
||||
return "", fmt.Errorf("Anthropic rejected the API key (401); check it in Settings")
|
||||
case 404:
|
||||
return "", fmt.Errorf("Anthropic doesn't know the model %q (404); choose another in Settings", model)
|
||||
case 429:
|
||||
return "", fmt.Errorf("Anthropic rate limit reached (429); try again shortly")
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("Anthropic: %w", err)
|
||||
}
|
||||
|
||||
switch msg.StopReason {
|
||||
case anthropic.BetaStopReasonRefusal:
|
||||
return "", fmt.Errorf("the model declined this request (%s)", msg.StopDetails.Category)
|
||||
case anthropic.BetaStopReasonMaxTokens:
|
||||
return "", fmt.Errorf("the reply was cut off at %d tokens", maxTokens)
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
for _, block := range msg.Content {
|
||||
if t, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
|
||||
b.WriteString(t.Text)
|
||||
}
|
||||
}
|
||||
text := strings.TrimSpace(b.String())
|
||||
if text == "" {
|
||||
return "", fmt.Errorf("the model returned no text (stop reason %s)", msg.StopReason)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// openAIClient talks to a server with the OpenAI chat-completions API, such
|
||||
// as Ollama or LM Studio.
|
||||
type openAIClient struct {
|
||||
base string // ends in /v1
|
||||
apiKey string
|
||||
cfg Config
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func newOpenAI(baseURL, apiKey string, cfg Config) *openAIClient {
|
||||
return &openAIClient{
|
||||
base: NormalizeBaseURL(baseURL),
|
||||
apiKey: apiKey,
|
||||
cfg: cfg,
|
||||
// Local models can take minutes on long prompts.
|
||||
http: &http.Client{Timeout: 10 * time.Minute},
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeBaseURL turns "llm.lan:11434", "http://llm.lan:11434" or
|
||||
// "http://llm.lan:11434/v1/" into "http://llm.lan:11434/v1".
|
||||
func NormalizeBaseURL(u string) string {
|
||||
u = strings.TrimRight(strings.TrimSpace(u), "/")
|
||||
if u == "" {
|
||||
return ""
|
||||
}
|
||||
if !strings.Contains(u, "://") {
|
||||
u = "http://" + u
|
||||
}
|
||||
if !strings.HasSuffix(u, "/v1") {
|
||||
u += "/v1"
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func (o *openAIClient) Generate(ctx context.Context, req Request) (string, error) {
|
||||
type message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
body := map[string]any{
|
||||
"model": o.cfg.ModelFor(req.Task),
|
||||
}
|
||||
var msgs []message
|
||||
if req.System != "" {
|
||||
msgs = append(msgs, message{"system", req.System})
|
||||
}
|
||||
msgs = append(msgs, message{"user", req.Prompt})
|
||||
body["messages"] = msgs
|
||||
if req.MaxTokens > 0 {
|
||||
body["max_tokens"] = req.MaxTokens
|
||||
}
|
||||
if req.Schema != nil {
|
||||
body["response_format"] = map[string]any{
|
||||
"type": "json_schema",
|
||||
"json_schema": map[string]any{
|
||||
"name": "reply",
|
||||
"schema": req.Schema,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
var out struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
if err := o.do(ctx, http.MethodPost, "/chat/completions", body, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(out.Choices) == 0 {
|
||||
return "", fmt.Errorf("%s returned no reply", o.base)
|
||||
}
|
||||
text := strings.TrimSpace(out.Choices[0].Message.Content)
|
||||
if text == "" {
|
||||
return "", fmt.Errorf("%s returned an empty reply (finish reason %s)", o.base, out.Choices[0].FinishReason)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// ListModels asks an OpenAI-compatible server which models it has.
|
||||
func ListModels(ctx context.Context, baseURL, apiKey string) ([]string, error) {
|
||||
o := newOpenAI(baseURL, apiKey, Config{})
|
||||
o.http.Timeout = 10 * time.Second
|
||||
var out struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := o.do(ctx, http.MethodGet, "/models", nil, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, 0, len(out.Data))
|
||||
for _, m := range out.Data {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (o *openAIClient) do(ctx context.Context, method, path string, body, out any) error {
|
||||
var rd io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rd = bytes.NewReader(raw)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, o.base+path, rd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if o.apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+o.apiKey)
|
||||
}
|
||||
res, err := o.http.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't reach %s: %w", o.base, err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, _ := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s%s: HTTP %d: %.300s", o.base, path, res.StatusCode, raw)
|
||||
}
|
||||
if err := json.Unmarshal(raw, out); err != nil {
|
||||
return fmt.Errorf("%s%s: unexpected reply: %w", o.base, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user