Files
Docwell/Server/internal/directory/ai.go
T
tajniak81andClaude Opus 5.5 78b7710090 Add AI chat, writing actions, workspace embeddings and an MCP server
Phase E of the AFFiNE parity plan (ADR-15):

- internal/ai: OpenAI-compatible, Anthropic (official Go SDK) and Ollama
  drivers; BYOK profiles per workspace and for the instance, with keys
  encrypted by DOCWELL_SECRET_KEY, failover order, a test call and usage
  counters.
- Embeddings: an indexer that follows PocketBase like the search index,
  chunks pages along their blocks and keeps vectors in a bbolt file in
  the data dir (no cgo); progress, ignored pages and extra files.
- Chat sessions scoped to a page, space or workspace, streamed as
  server-sent events, with citations to pages and blocks, fork and
  history; retrieval only from pages the asker can read.
- Writing actions (rewrite, fix, shorter, longer, summarise, translate,
  continue, custom) in the editor's selection toolbar.
- POST /mcp: MCP over Streamable HTTP with personal API tokens; read
  tokens search and read pages, write tokens also create and update them.
- Web app chat panel (Ctrl+J), workspace AI settings, an admin AI page,
  OpenAPI, generated clients, migration and translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:58:22 +01:00

175 lines
5.2 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"fmt"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/convert"
"docwell/server/internal/store/pocketbase"
)
// ---- What the AI layer (ADR-15) needs from the directory ----------------------
// WorkspaceRole is c's effective role in a workspace; a workspace c cannot
// open is not found.
func (s *Service) WorkspaceRole(ctx context.Context, c access.Caller, wsID string) (string, error) {
_, role, err := s.workspaceFor(ctx, c, wsID)
return role, err
}
// Readable answers which pages of one workspace a caller may read. It is
// built once per request, so filtering many retrieval hits stays cheap.
type Readable struct {
Workspace string
// Spaces are the spaces the caller can open, by id, with their names.
Spaces map[string]string
rules map[string]pageRules
}
// Can reports whether the caller may read page in space.
func (r *Readable) Can(space, page string) bool {
rules, ok := r.rules[space]
return ok && rules.role(page) != ""
}
// Readable loads the caller's reading rights in a workspace.
func (s *Service) Readable(ctx context.Context, c access.Caller, wsID string) (*Readable, error) {
spaces, err := s.ListSpaces(ctx, c, wsID)
if err != nil {
return nil, err
}
r := &Readable{Workspace: wsID, Spaces: map[string]string{}, rules: map[string]pageRules{}}
for _, sp := range spaces {
_, rules, err := s.spaceRules(ctx, c, sp.ID)
if err != nil {
return nil, err
}
r.Spaces[sp.ID], r.rules[sp.ID] = sp.Name, rules
}
return r, nil
}
// PageText is a page as the AI layer reads it.
type PageText struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Updated string `json:"updated"`
// Markdown is the page body; Doc is the same as Tiptap JSON.
Markdown string `json:"markdown"`
Doc json.RawMessage `json:"-"`
CanEdit bool `json:"canEdit"`
}
// ReadPage returns a page c may read, with its body as Markdown.
func (s *Service) ReadPage(ctx context.Context, c access.Caller, id string) (PageText, error) {
if !validID(id) {
return PageText{}, apperr.NotFound("page not found")
}
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return PageText{}, err
}
if p.DeletedAt != "" {
return PageText{}, apperr.NotFound("page not found")
}
doc, err := s.docs.Content(ctx, p.ID)
if err != nil {
return PageText{}, err
}
node, err := convert.Parse(doc)
if err != nil {
return PageText{}, err
}
return PageText{
ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon,
Updated: p.Updated, Markdown: convert.Markdown(node, convert.Options{}), Doc: doc,
CanEdit: access.SpaceAtLeast(a.role, access.SpaceEditor) && p.ArchivedAt == "",
}, nil
}
// PageSummary is one page in a listing for the AI layer.
type PageSummary struct {
ID string `json:"id"`
Space string `json:"space"`
Title string `json:"title"`
Updated string `json:"updated"`
}
// RecentPages lists the pages of a workspace c may read, most recently
// changed first (a space narrows it).
func (s *Service) RecentPages(ctx context.Context, c access.Caller, wsID, space string, limit int) ([]PageSummary, error) {
r, err := s.Readable(ctx, c, wsID)
if err != nil {
return nil, err
}
filter := fmt.Sprintf("workspace = '%s' && deleted_at = '' && archived_at = ''", wsID)
if space != "" {
if _, ok := r.Spaces[space]; !ok {
return []PageSummary{}, nil
}
filter += fmt.Sprintf(" && space = '%s'", filterValue(space))
}
out := []PageSummary{}
for page := 1; len(out) < limit; page++ {
res, err := pocketbase.List[pageRecord](ctx, s.pb, "pages", pocketbase.ListOptions{
Page: page, PerPage: 200, Filter: filter, Sort: "-updated", Fields: "id,space,title,updated",
})
if err != nil {
return nil, err
}
for _, p := range res.Items {
if r.Can(p.Space, p.ID) && len(out) < limit {
out = append(out, PageSummary{ID: p.ID, Space: p.Space, Title: p.Title, Updated: p.Updated})
}
}
if page >= res.TotalPages || len(res.Items) == 0 {
break
}
}
return out, nil
}
// WriteMarkdown replaces a page's body with Markdown, or (appendTo) adds it
// at the end (editor). Open editors receive the change live.
func (s *Service) WriteMarkdown(ctx context.Context, c access.Caller, id, md string, appendTo bool) (PageText, error) {
p, err := s.editablePage(ctx, c, id)
if err != nil {
return PageText{}, err
}
add, err := convert.FromMarkdown(md)
if err != nil {
return PageText{}, apperr.Invalid("The Markdown could not be read.")
}
doc := add
if appendTo {
raw, err := s.docs.Content(ctx, p.ID)
if err != nil {
return PageText{}, err
}
if doc, err = convert.Parse(raw); err != nil {
return PageText{}, err
}
doc.Content = append(doc.Content, add.Content...)
}
raw, err := json.Marshal(doc)
if err != nil {
return PageText{}, err
}
if len(raw) > maxContentBytes {
return PageText{}, apperr.Invalid("The page is too large to save.")
}
if err := s.docs.Replace(ctx, p.ID, c.ID, raw, "before-replace"); err != nil {
return PageText{}, err
}
return s.ReadPage(ctx, c, p.ID)
}