// SPDX-License-Identifier: AGPL-3.0-or-later package ai import ( "context" "crypto/rand" "encoding/hex" "fmt" "slices" "sort" "strings" "time" "unicode" "unicode/utf8" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/directory" "docwell/server/internal/store/pocketbase" ) // ---- Chat sessions ----------------------------------------------------------------- // Scopes a session can ask about. const ( ScopeWorkspace = "workspace" ScopeSpace = "space" ScopePage = "page" ) // Citation is a numbered source of an answer: a page (and block in it) or // an extra file. type Citation struct { N int `json:"n"` Page string `json:"page,omitempty"` Block string `json:"block,omitempty"` File string `json:"file,omitempty"` Title string `json:"title"` Snippet string `json:"snippet"` text string } // ChatMessage is one turn of a session. type ChatMessage struct { ID string `json:"id"` Role string `json:"role"` Content string `json:"content"` Citations []Citation `json:"citations,omitempty"` Error string `json:"error,omitempty"` Created string `json:"created"` } type sessionRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` User string `json:"user"` Title string `json:"title"` Scope string `json:"scope"` ScopeID string `json:"scope_id"` Messages []ChatMessage `json:"messages"` Created string `json:"created"` Updated string `json:"updated"` } // SessionSummary is a session in a list. type SessionSummary struct { ID string `json:"id"` Title string `json:"title"` Scope string `json:"scope"` ScopeID string `json:"scopeId"` Created string `json:"created"` Updated string `json:"updated"` } // Session is a session with its messages. type Session struct { SessionSummary Workspace string `json:"workspace"` Messages []ChatMessage `json:"messages"` } func (r sessionRecord) summary() SessionSummary { scope := r.Scope if scope == "" { scope = ScopeWorkspace } return SessionSummary{ID: r.ID, Title: r.Title, Scope: scope, ScopeID: r.ScopeID, Created: r.Created, Updated: r.Updated} } func (r sessionRecord) view() Session { msgs := r.Messages if msgs == nil { msgs = []ChatMessage{} } return Session{SessionSummary: r.summary(), Workspace: r.Workspace, Messages: msgs} } // SessionInput creates or changes a session. type SessionInput struct { Title *string `json:"title"` Scope *string `json:"scope"` ScopeID *string `json:"scopeId"` } const ( maxSessions = 200 maxMessages = 200 ) func newID() string { b := make([]byte, 8) _, _ = rand.Read(b) return hex.EncodeToString(b) } func now() string { return time.Now().UTC().Format(time.RFC3339) } // checkScope makes sure c can read what a session asks about. func (s *Service) checkScope(ctx context.Context, c access.Caller, wsID, scope, id string) error { switch scope { case ScopeWorkspace: return nil case ScopeSpace: r, err := s.dir.Readable(ctx, c, wsID) if err != nil { return err } if _, ok := r.Spaces[id]; !ok { return apperr.InvalidFields(map[string]string{"scopeId": "That space is not in this workspace."}) } return nil case ScopePage: p, err := s.dir.ReadPage(ctx, c, id) if err != nil || p.Workspace != wsID { return apperr.InvalidFields(map[string]string{"scopeId": "That page is not in this workspace."}) } return nil } return apperr.InvalidFields(map[string]string{"scope": "Scope must be workspace, space or page."}) } // ListSessions lists c's sessions in a workspace, newest first. func (s *Service) ListSessions(ctx context.Context, c access.Caller, wsID string) ([]SessionSummary, error) { if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil { return nil, err } res, err := pocketbase.List[sessionRecord](ctx, s.pb, "ai_sessions", pocketbase.ListOptions{ PerPage: 100, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, c.ID), Sort: "-updated", Fields: "id,title,scope,scope_id,created,updated", }) if err != nil { return nil, err } out := make([]SessionSummary, 0, len(res.Items)) for _, r := range res.Items { out = append(out, r.summary()) } return out, nil } // CreateSession starts a session. func (s *Service) CreateSession(ctx context.Context, c access.Caller, wsID string, in SessionInput) (Session, error) { if _, _, err := s.ready(ctx, c, wsID); err != nil { return Session{}, err } scope, id := ScopeWorkspace, "" if in.Scope != nil && *in.Scope != "" { scope = *in.Scope } if in.ScopeID != nil { id = *in.ScopeID } if scope == ScopeWorkspace { id = "" } if err := s.checkScope(ctx, c, wsID, scope, id); err != nil { return Session{}, err } title := "" if in.Title != nil { title = truncate(strings.TrimSpace(*in.Title), 200) } n, err := pocketbase.List[sessionRecord](ctx, s.pb, "ai_sessions", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, c.ID), Fields: "id", }) if err != nil { return Session{}, err } if n.TotalItems >= maxSessions { return Session{}, apperr.Invalid("You have as many chats as allowed here; delete some first.") } rec, err := pocketbase.Create[sessionRecord](ctx, s.pb, "ai_sessions", map[string]any{ "workspace": wsID, "user": c.ID, "title": title, "scope": scope, "scope_id": id, "messages": []ChatMessage{}, }) if err != nil { return Session{}, err } return rec.view(), nil } func (s *Service) sessionFor(ctx context.Context, c access.Caller, id string) (sessionRecord, error) { if !validID(id) { return sessionRecord{}, apperr.NotFound("chat not found") } rec, err := pocketbase.Get[sessionRecord](ctx, s.pb, "ai_sessions", id) if err != nil { if pocketbase.IsNotFound(err) { return rec, apperr.NotFound("chat not found") } return rec, err } if rec.User != c.ID { return rec, apperr.NotFound("chat not found") } if _, err := s.dir.WorkspaceRole(ctx, c, rec.Workspace); err != nil { return rec, apperr.NotFound("chat not found") } return rec, nil } // GetSession returns one of c's sessions with its messages. func (s *Service) GetSession(ctx context.Context, c access.Caller, id string) (Session, error) { rec, err := s.sessionFor(ctx, c, id) return rec.view(), err } // UpdateSession renames a session or changes what it asks about. func (s *Service) UpdateSession(ctx context.Context, c access.Caller, id string, in SessionInput) (Session, error) { rec, err := s.sessionFor(ctx, c, id) if err != nil { return Session{}, err } body := map[string]any{} if in.Title != nil { body["title"] = truncate(strings.TrimSpace(*in.Title), 200) } if in.Scope != nil { scope, sid := *in.Scope, rec.ScopeID if in.ScopeID != nil { sid = *in.ScopeID } if scope == ScopeWorkspace { sid = "" } if err := s.checkScope(ctx, c, rec.Workspace, scope, sid); err != nil { return Session{}, err } body["scope"], body["scope_id"] = scope, sid } rec, err = pocketbase.Update[sessionRecord](ctx, s.pb, "ai_sessions", id, body) return rec.view(), err } // DeleteSession deletes one of c's sessions. func (s *Service) DeleteSession(ctx context.Context, c access.Caller, id string) error { if _, err := s.sessionFor(ctx, c, id); err != nil { return err } return s.pb.Delete(ctx, "ai_sessions", id) } // ForkSession copies a session up to and including message upTo ("" = all). func (s *Service) ForkSession(ctx context.Context, c access.Caller, id, upTo string) (Session, error) { rec, err := s.sessionFor(ctx, c, id) if err != nil { return Session{}, err } msgs := rec.Messages if upTo != "" { i := slices.IndexFunc(msgs, func(m ChatMessage) bool { return m.ID == upTo }) if i < 0 { return Session{}, apperr.InvalidFields(map[string]string{"message": "That message is not in this chat."}) } msgs = msgs[:i+1] } title := rec.Title if title == "" { title = "Chat" } fork, err := pocketbase.Create[sessionRecord](ctx, s.pb, "ai_sessions", map[string]any{ "workspace": rec.Workspace, "user": c.ID, "title": truncate(title+" (fork)", 200), "scope": rec.Scope, "scope_id": rec.ScopeID, "messages": msgs, }) return fork.view(), err } // ---- Retrieval --------------------------------------------------------------------- const ( maxSources = 8 maxSourceChars = 2400 maxPageChars = 24000 ) // retrieve finds the sources for a question in a scope, only from what c // may read. It uses the embeddings when the workspace has them, else search. func (s *Service) retrieve(ctx context.Context, c access.Caller, wsID, scope, scopeID, question string, st Settings, chain []profileRecord) ([]Citation, error) { r, err := s.dir.Readable(ctx, c, wsID) if err != nil { return nil, err } ignored, err := s.ignoredSet(ctx, wsID, st.Ignored) if err != nil { return nil, err } var sources []Citation add := func(cit Citation) { cit.N = len(sources) + 1 cit.text = truncate(cit.text, maxSourceChars) cit.Snippet = truncate(strings.Join(strings.Fields(cit.text), " "), 200) sources = append(sources, cit) } if scope == ScopePage { p, err := s.dir.ReadPage(ctx, c, scopeID) if err != nil { return nil, err } pieces := chunkDoc(p.Title, p.Doc) total := 0 for _, pc := range pieces { total += utf8.RuneCountInString(pc.Text) } if total > maxPageChars { pieces = rankPieces(pieces, question, maxSources) } for _, pc := range pieces { add(Citation{Page: p.ID, Block: pc.Block, Title: p.Title, text: pc.Text}) } if len(pieces) == 0 { add(Citation{Page: p.ID, Title: p.Title, text: "(This page is empty.)"}) } return sources, nil } if prof, ok := embedProfile(chain); ok && st.Index { meta, _ := s.store.Meta(wsID) if meta.Model == prof.ID+":"+prof.EmbedModel { p, err := s.provider(prof) if err == nil { vecs, usage, err := p.Embed(ctx, prof.EmbedModel, []string{question}) s.record(wsID, prof, usage, err) if err == nil && len(vecs) == 1 { hits, err := s.store.Search(wsID, normalize(vecs[0]), maxSources, func(ch Chunk) bool { if ch.File != "" { return scope == ScopeWorkspace } if scope == ScopeSpace && ch.Space != scopeID { return false } return !ignored[ch.Page] && r.Can(ch.Space, ch.Page) }) if err == nil && len(hits) > 0 { for _, h := range hits { add(Citation{Page: h.Page, Block: h.Block, File: h.File, Title: h.Title, text: h.Text}) } return sources, nil } } } } } // No embeddings: the best search hits, and their best pieces. q := directory.SearchQuery{Text: truncate(question, 190), Limit: 5} if scope == ScopeSpace { q.Space = scopeID } res, err := s.dir.Search(ctx, c, wsID, q) if err != nil { return nil, err } for _, h := range res.Items { if ignored[h.ID] { continue } p, err := s.dir.ReadPage(ctx, c, h.ID) if err != nil { continue } for _, pc := range rankPieces(chunkDoc(p.Title, p.Doc), question, 2) { if len(sources) < maxSources { add(Citation{Page: p.ID, Block: pc.Block, Title: p.Title, text: pc.Text}) } } } return sources, nil } func words(s string) []string { return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) } // rankPieces keeps the n pieces sharing the most words with the question, // in document order. func rankPieces(pieces []piece, question string, n int) []piece { if len(pieces) <= n { return pieces } q := map[string]bool{} for _, w := range words(question) { if utf8.RuneCountInString(w) > 2 { q[w] = true } } type scored struct{ i, score int } all := make([]scored, len(pieces)) for i, p := range pieces { all[i].i = i for _, w := range words(p.Text) { if q[w] { all[i].score++ } } } sort.SliceStable(all, func(a, b int) bool { return all[a].score > all[b].score }) keep := all[:n] sort.Slice(keep, func(a, b int) bool { return keep[a].i < keep[b].i }) out := make([]piece, n) for i, k := range keep { out[i] = pieces[k.i] } return out } // ---- Answering ------------------------------------------------------------------- const chatSystem = `You are the assistant built into Docwell, a team wiki. You answer questions about the user's workspace from the numbered sources that come with each question. - Base what you say about the workspace on the sources. After each statement that uses a source, cite it as [1], or [2][3] for several. - If the sources do not answer the question, say so plainly, and only then add what you know in general, marked as such. - Answer in the language of the question. Use Markdown. Be concise: lead with the answer, then the details that matter.` const historyTurns = 12 func sourcesBlock(sources []Citation) string { if len(sources) == 0 { return "Sources: none were found for this question.\n\n" } var b strings.Builder b.WriteString("Sources:\n\n") for _, src := range sources { fmt.Fprintf(&b, "[%d] %s\n%s\n\n", src.N, src.Title, src.text) } return b.String() } // Event is one server-sent event of a streamed answer. type Event struct { Name string Data any } // Ask adds a question to a session and streams the answer to emit: first // "sources" (the citations), then "delta" pieces of text, then "done" with // the stored message, or "error". func (s *Service) Ask(ctx context.Context, c access.Caller, id, question string, emit func(Event)) error { question = strings.TrimSpace(question) if question == "" || utf8.RuneCountInString(question) > 8000 { return apperr.InvalidFields(map[string]string{"content": "Ask a question of up to 8 000 characters."}) } rec, err := s.sessionFor(ctx, c, id) if err != nil { return err } if len(rec.Messages) >= maxMessages { return apperr.Invalid("This chat is full; start a new one or fork it.") } st, chain, err := s.ready(ctx, c, rec.Workspace) if err != nil { return err } scope := rec.Scope if scope == "" { scope = ScopeWorkspace } sources, err := s.retrieve(ctx, c, rec.Workspace, scope, rec.ScopeID, question, st, chain) if err != nil { return err } emit(Event{Name: "sources", Data: map[string]any{"citations": nonNil(sources)}}) msgs := []Message{} start := max(0, len(rec.Messages)-historyTurns) for _, m := range rec.Messages[start:] { if m.Content != "" && (m.Role == "user" || m.Role == "assistant") { msgs = append(msgs, Message{Role: m.Role, Content: m.Content}) } } msgs = append(msgs, Message{Role: "user", Content: sourcesBlock(sources) + "Question: " + question}) var answer strings.Builder _, chatErr := s.chat(ctx, rec.Workspace, chain, ChatRequest{System: chatSystem, Messages: msgs, MaxTokens: 8000}, func(d string) { answer.WriteString(d) emit(Event{Name: "delta", Data: map[string]string{"text": d}}) }) user := ChatMessage{ID: newID(), Role: "user", Content: question, Created: now()} reply := ChatMessage{ID: newID(), Role: "assistant", Content: answer.String(), Citations: sources, Created: now()} if chatErr != nil { reply.Error = userError(chatErr) } body := map[string]any{"messages": append(rec.Messages, user, reply)} if rec.Title == "" { body["title"] = truncate(question, 60) } // Store the turn even when the client went away mid-answer. saveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) defer cancel() if _, err := pocketbase.Update[sessionRecord](saveCtx, s.pb, "ai_sessions", rec.ID, body); err != nil { return err } if chatErr != nil { emit(Event{Name: "error", Data: map[string]string{"message": reply.Error}}) return nil } emit(Event{Name: "done", Data: map[string]any{"user": user, "message": reply}}) return nil } func nonNil(c []Citation) []Citation { if c == nil { return []Citation{} } return c } // userError is the message people see for a failed call. func userError(err error) string { if e, ok := apperr.As(err); ok { return e.Message } switch { case err == ErrRefused: return "The model declined to answer this." case strings.Contains(err.Error(), "context deadline exceeded"), strings.Contains(err.Error(), "context canceled"): return "The answer took too long and was stopped." } return "The AI provider failed: " + truncate(err.Error(), 300) } // Answer asks a one-off question without a session (MCP's ask tool). func (s *Service) Answer(ctx context.Context, c access.Caller, wsID, scope, scopeID, question string) (string, []Citation, error) { st, chain, err := s.ready(ctx, c, wsID) if err != nil { return "", nil, err } if scope == "" { scope = ScopeWorkspace } if err := s.checkScope(ctx, c, wsID, scope, scopeID); err != nil { return "", nil, err } sources, err := s.retrieve(ctx, c, wsID, scope, scopeID, question, st, chain) if err != nil { return "", nil, err } var answer strings.Builder _, err = s.chat(ctx, wsID, chain, ChatRequest{ System: chatSystem, MaxTokens: 8000, Messages: []Message{{Role: "user", Content: sourcesBlock(sources) + "Question: " + question}}, }, func(d string) { answer.WriteString(d) }) if err != nil { return "", nil, apperr.Invalid(userError(err)) } return answer.String(), nonNil(sources), nil }