// SPDX-License-Identifier: AGPL-3.0-or-later package httpapi import ( "context" "encoding/json" "fmt" "io" "net/http" "strings" "docwell/server/internal/access" "docwell/server/internal/ai" "docwell/server/internal/apperr" "docwell/server/internal/audit" "docwell/server/internal/auth" ) // AIService is the AI layer (ADR-15). type AIService interface { Available(ctx context.Context, c access.Caller, wsID string) (ai.Availability, error) GetSettings(ctx context.Context, c access.Caller, wsID string) (ai.Settings, error) SaveSettings(ctx context.Context, c access.Caller, wsID string, in ai.Settings) (ai.Settings, error) ListProfiles(ctx context.Context, c access.Caller, wsID string) ([]ai.Profile, error) CreateProfile(ctx context.Context, c access.Caller, wsID string, in ai.ProfileInput) (ai.Profile, error) UpdateProfile(ctx context.Context, c access.Caller, id string, in ai.ProfileInput) (ai.Profile, error) DeleteProfile(ctx context.Context, c access.Caller, id string) error OrderProfiles(ctx context.Context, c access.Caller, wsID string, ids []string) ([]ai.Profile, error) TestProfile(ctx context.Context, c access.Caller, id string) (ai.TestResult, error) IndexStatus(ctx context.Context, c access.Caller, wsID string) (ai.IndexStatus, error) RebuildIndex(ctx context.Context, c access.Caller, wsID string) error ListFiles(ctx context.Context, c access.Caller, wsID string) ([]ai.File, error) AddFile(ctx context.Context, c access.Caller, wsID, name string, data []byte) (ai.File, error) DeleteFile(ctx context.Context, c access.Caller, id string) error ListSessions(ctx context.Context, c access.Caller, wsID string) ([]ai.SessionSummary, error) CreateSession(ctx context.Context, c access.Caller, wsID string, in ai.SessionInput) (ai.Session, error) GetSession(ctx context.Context, c access.Caller, id string) (ai.Session, error) UpdateSession(ctx context.Context, c access.Caller, id string, in ai.SessionInput) (ai.Session, error) DeleteSession(ctx context.Context, c access.Caller, id string) error ForkSession(ctx context.Context, c access.Caller, id, upTo string) (ai.Session, error) Ask(ctx context.Context, c access.Caller, id, question string, emit func(ai.Event)) error Write(ctx context.Context, c access.Caller, wsID string, in ai.WriteInput, onDelta func(string)) error MCP(ctx context.Context, c access.Caller, canWrite bool, body []byte, onWrite func(tool, page string)) ([]byte, error) Usage(ctx context.Context, c access.Caller, wsID string) (ai.UsageView, error) AllUsage(ctx context.Context, c access.Caller) ([]ai.UsageView, error) GetInstanceSettings(ctx context.Context, c access.Caller) (ai.InstanceSettings, error) SaveInstanceSettings(ctx context.Context, c access.Caller, in ai.InstanceSettings) (ai.InstanceSettings, error) Transcribe(ctx context.Context, c access.Caller, fileID string, summarize bool) (ai.Transcript, error) } var errNoAI = apperr.NotFound("AI is not available on this server") // withAI answers 404 when the server runs without the AI layer. func (a *api) withAI(next http.HandlerFunc) http.HandlerFunc { return a.requireUser(func(w http.ResponseWriter, r *http.Request) { if a.ai == nil { a.writeError(w, errNoAI) return } next(w, r) }) } // sse streams server-sent events. Errors before the first event are sent // as plain JSON errors, so clients can show them like any other. type sse struct { w http.ResponseWriter rc *http.ResponseController started bool } func newSSE(w http.ResponseWriter) *sse { return &sse{w: w, rc: http.NewResponseController(w)} } func (s *sse) send(event string, data any) { if !s.started { h := s.w.Header() h.Set("Content-Type", "text/event-stream") h.Set("Cache-Control", "no-cache") h.Set("X-Accel-Buffering", "no") // nginx: do not buffer the stream s.w.WriteHeader(http.StatusOK) s.started = true } raw, _ := json.Marshal(data) fmt.Fprintf(s.w, "event: %s\ndata: %s\n\n", event, raw) _ = s.rc.Flush() } func (a *api) aiRoutes(mux *routeMux) { ws := func(path string) string { return "/api/v1/workspaces/{id}/ai" + path } mux.HandleFunc("GET "+ws(""), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.Available(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("GET "+ws("/settings"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.GetSettings(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("PUT "+ws("/settings"), a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.Settings if !a.decode(w, r, &in) { return } v, err := a.ai.SaveSettings(r.Context(), caller(r), r.PathValue("id"), in) a.respond(w, v, err) })) // Profiles: a workspace's, and the instance's (superadmins). mux.HandleFunc("GET "+ws("/profiles"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.ListProfiles(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("POST "+ws("/profiles"), a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.ProfileInput if !a.decode(w, r, &in) { return } v, err := a.ai.CreateProfile(r.Context(), caller(r), r.PathValue("id"), in) a.respondStatus(w, http.StatusCreated, v, err) })) mux.HandleFunc("PUT "+ws("/profiles/order"), a.withAI(func(w http.ResponseWriter, r *http.Request) { var in struct { IDs []string `json:"ids"` } if !a.decode(w, r, &in) { return } v, err := a.ai.OrderProfiles(r.Context(), caller(r), r.PathValue("id"), in.IDs) a.respond(w, v, err) })) mux.HandleFunc("GET /api/v1/admin/ai/profiles", a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.ListProfiles(r.Context(), caller(r), "") a.respond(w, v, err) })) mux.HandleFunc("POST /api/v1/admin/ai/profiles", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.ProfileInput if !a.decode(w, r, &in) { return } v, err := a.ai.CreateProfile(r.Context(), caller(r), "", in) a.respondStatus(w, http.StatusCreated, v, err) })) mux.HandleFunc("PUT /api/v1/admin/ai/profiles/order", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in struct { IDs []string `json:"ids"` } if !a.decode(w, r, &in) { return } v, err := a.ai.OrderProfiles(r.Context(), caller(r), "", in.IDs) a.respond(w, v, err) })) mux.HandleFunc("PATCH /api/v1/ai/profiles/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.ProfileInput if !a.decode(w, r, &in) { return } v, err := a.ai.UpdateProfile(r.Context(), caller(r), r.PathValue("id"), in) a.respond(w, v, err) })) mux.HandleFunc("DELETE /api/v1/ai/profiles/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { a.respondNoContent(w, a.ai.DeleteProfile(r.Context(), caller(r), r.PathValue("id"))) })) mux.HandleFunc("POST /api/v1/ai/profiles/{id}/test", a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.TestProfile(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) // Monthly usage and its caps. mux.HandleFunc("GET "+ws("/usage"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.Usage(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("GET /api/v1/admin/ai/usage", a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.AllUsage(r.Context(), caller(r)) a.respond(w, v, err) })) mux.HandleFunc("GET /api/v1/admin/ai/settings", a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.GetInstanceSettings(r.Context(), caller(r)) a.respond(w, v, err) })) mux.HandleFunc("PUT /api/v1/admin/ai/settings", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.InstanceSettings if !a.decode(w, r, &in) { return } v, err := a.ai.SaveInstanceSettings(r.Context(), caller(r), in) a.respond(w, v, err) })) // Audio and video attachments → transcript and summary. mux.HandleFunc("POST /api/v1/files/{id}/transcribe", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in struct { Summarize bool `json:"summarize"` } if !a.decode(w, r, &in) { return } v, err := a.ai.Transcribe(r.Context(), caller(r), r.PathValue("id"), in.Summarize) a.respond(w, v, err) })) // Embeddings index and extra files. mux.HandleFunc("GET "+ws("/index"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.IndexStatus(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("POST "+ws("/index/rebuild"), a.withAI(func(w http.ResponseWriter, r *http.Request) { a.respondNoContent(w, a.ai.RebuildIndex(r.Context(), caller(r), r.PathValue("id"))) })) mux.HandleFunc("GET "+ws("/files"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.ListFiles(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("POST "+ws("/files"), a.withAI(func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, ai.MaxFileBytes+1<<20) if err := r.ParseMultipartForm(ai.MaxFileBytes); err != nil { a.writeError(w, apperr.Invalid("Files can be up to 10 MB.")) return } f, h, err := r.FormFile("file") if err != nil { a.writeError(w, apperr.InvalidFields(map[string]string{"file": "Choose a file."})) return } defer f.Close() data, err := io.ReadAll(io.LimitReader(f, ai.MaxFileBytes+1)) if err != nil { a.writeError(w, err) return } v, err := a.ai.AddFile(r.Context(), caller(r), r.PathValue("id"), h.Filename, data) a.respondStatus(w, http.StatusCreated, v, err) })) mux.HandleFunc("DELETE /api/v1/ai/files/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { a.respondNoContent(w, a.ai.DeleteFile(r.Context(), caller(r), r.PathValue("id"))) })) // Chat sessions. mux.HandleFunc("GET "+ws("/sessions"), a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.ListSessions(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("POST "+ws("/sessions"), a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.SessionInput if !a.decode(w, r, &in) { return } v, err := a.ai.CreateSession(r.Context(), caller(r), r.PathValue("id"), in) a.respondStatus(w, http.StatusCreated, v, err) })) mux.HandleFunc("GET /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { v, err := a.ai.GetSession(r.Context(), caller(r), r.PathValue("id")) a.respond(w, v, err) })) mux.HandleFunc("PATCH /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.SessionInput if !a.decode(w, r, &in) { return } v, err := a.ai.UpdateSession(r.Context(), caller(r), r.PathValue("id"), in) a.respond(w, v, err) })) mux.HandleFunc("DELETE /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { a.respondNoContent(w, a.ai.DeleteSession(r.Context(), caller(r), r.PathValue("id"))) })) mux.HandleFunc("POST /api/v1/ai/sessions/{id}/fork", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in struct { Message string `json:"message"` } if !a.decode(w, r, &in) { return } v, err := a.ai.ForkSession(r.Context(), caller(r), r.PathValue("id"), in.Message) a.respondStatus(w, http.StatusCreated, v, err) })) mux.HandleFunc("POST /api/v1/ai/sessions/{id}/messages", a.withAI(func(w http.ResponseWriter, r *http.Request) { var in struct { Content string `json:"content"` } if !a.decode(w, r, &in) { return } out := newSSE(w) err := a.ai.Ask(r.Context(), caller(r), r.PathValue("id"), in.Content, func(e ai.Event) { out.send(e.Name, e.Data) }) a.streamError(w, out, err) })) // Writing actions. mux.HandleFunc("POST "+ws("/write"), a.withAI(func(w http.ResponseWriter, r *http.Request) { var in ai.WriteInput if !a.decodeMax(w, r, &in, 4<<20) { return } out := newSSE(w) err := a.ai.Write(r.Context(), caller(r), r.PathValue("id"), in, func(d string) { out.send("delta", map[string]string{"text": d}) }) if err == nil { out.send("done", map[string]any{}) } a.streamError(w, out, err) })) } // streamError reports err as JSON before a stream started, else as an // "error" event. func (a *api) streamError(w http.ResponseWriter, out *sse, err error) { if err == nil { return } if !out.started { a.writeError(w, err) return } msg := "Something went wrong." if e, ok := apperr.As(err); ok { msg = e.Message } else if r := err.Error(); r != "" && !strings.Contains(r, "context canceled") { a.log.Warn("ai stream failed", "err", err) } out.send("error", map[string]string{"message": msg}) } // mcpRoute serves the MCP endpoint. Its clients send API tokens (or // session tokens); a write token also gets the write tools. func (a *api) mcpRoute(mux *routeMux) { mux.HandleFunc("POST /mcp", func(w http.ResponseWriter, r *http.Request) { if a.ai == nil { a.writeError(w, errNoAI) return } token := auth.BearerToken(r) var u auth.User var err error canWrite := true if strings.HasPrefix(token, auth.TokenPrefix) { var scope string u, scope, err = a.auth.VerifyAPIToken(r.Context(), token) canWrite = scope == auth.ScopeWrite } else { u, err = a.auth.Verify(r.Context(), token) } if err != nil { w.Header().Set("WWW-Authenticate", `Bearer realm="docwell", error="invalid_token"`) a.writeError(w, err) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<20)) if err != nil { writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too_large"}) return } onWrite := func(tool, page string) { if a.audit != nil { a.audit.Record(audit.Entry{ Action: "mcp." + tool, ActorID: u.ID, ActorEmail: u.Email, Org: u.Organization, TargetType: "page", TargetID: page, Status: http.StatusOK, IP: audit.ClientIP(r), UserAgent: r.UserAgent(), }) } } out, err := a.ai.MCP(r.Context(), u.Caller(), canWrite, body, onWrite) if err != nil { a.writeError(w, err) return } if out == nil { w.WriteHeader(http.StatusAccepted) return } w.Header().Set("Content-Type", "application/json") _, _ = w.Write(out) }) }