Files
Docwell/Server/internal/ai/store.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

364 lines
9.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"container/heap"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"time"
bolt "go.etcd.io/bbolt"
)
// Store keeps embedding vectors per workspace in a bbolt file (ADR-15). It
// can always be thrown away and rebuilt from PocketBase.
//
// Layout: bucket "ws" → one bucket per workspace → "meta" (JSON),
// "docs" (source key → hash and chunk count) and "chunks" (source key + "/" +
// number → vector and metadata). A source key is "page/<id>" or "file/<id>".
type Store struct{ db *bolt.DB }
// Chunk is one piece of a source with its vector.
type Chunk struct {
Source string `json:"-"`
Space string `json:"space,omitempty"`
Page string `json:"page,omitempty"`
File string `json:"file,omitempty"`
Block string `json:"block,omitempty"`
Title string `json:"title"`
Text string `json:"text"`
Vector []float32 `json:"-"`
}
// Meta is a workspace's index state.
type Meta struct {
// Model is the profile and model the vectors come from ("<profile>:<model>").
Model string `json:"model"`
Dims int `json:"dims"`
Checkpoint string `json:"checkpoint"`
FilesAt string `json:"filesAt"`
}
var (
bucketWS = []byte("ws")
bucketMeta = []byte("meta")
bucketDocs = []byte("docs")
bucketChunks = []byte("chunks")
keyMeta = []byte("meta")
)
// OpenStore opens (or creates) dir/ai.db.
func OpenStore(dir string) (*Store, error) {
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, err
}
path := filepath.Join(dir, "ai.db")
db, err := bolt.Open(path, 0o600, &bolt.Options{Timeout: 5 * time.Second})
if err != nil {
return nil, fmt.Errorf("ai store %s: %w", path, err)
}
if err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(bucketWS)
return err
}); err != nil {
_ = db.Close()
return nil, err
}
return &Store{db: db}, nil
}
func (s *Store) Close() error { return s.db.Close() }
func wsBucket(tx *bolt.Tx, ws string, create bool) (*bolt.Bucket, error) {
root := tx.Bucket(bucketWS)
if !create {
return root.Bucket([]byte(ws)), nil
}
b, err := root.CreateBucketIfNotExists([]byte(ws))
if err != nil {
return nil, err
}
for _, name := range [][]byte{bucketMeta, bucketDocs, bucketChunks} {
if _, err := b.CreateBucketIfNotExists(name); err != nil {
return nil, err
}
}
return b, nil
}
// Meta returns a workspace's index state (zero when it has none).
func (s *Store) Meta(ws string) (Meta, error) {
var m Meta
err := s.db.View(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
if raw := b.Bucket(bucketMeta).Get(keyMeta); raw != nil {
return json.Unmarshal(raw, &m)
}
return nil
})
return m, err
}
// SetMeta saves a workspace's index state.
func (s *Store) SetMeta(ws string, m Meta) error {
raw, _ := json.Marshal(m)
return s.db.Update(func(tx *bolt.Tx) error {
b, err := wsBucket(tx, ws, true)
if err != nil {
return err
}
return b.Bucket(bucketMeta).Put(keyMeta, raw)
})
}
// DropWorkspace forgets a workspace's vectors and state.
func (s *Store) DropWorkspace(ws string) error {
return s.db.Update(func(tx *bolt.Tx) error {
err := tx.Bucket(bucketWS).DeleteBucket([]byte(ws))
if errors.Is(err, bolt.ErrBucketNotFound) {
return nil
}
return err
})
}
// Workspaces lists the workspaces the store has state for.
func (s *Store) Workspaces() ([]string, error) {
var out []string
err := s.db.View(func(tx *bolt.Tx) error {
return tx.Bucket(bucketWS).ForEachBucket(func(k []byte) error {
out = append(out, string(k))
return nil
})
})
return out, err
}
type docEntry struct {
Hash string `json:"hash"`
Chunks int `json:"chunks"`
}
// Hash returns the hash a source was last indexed with ("" when it was not).
func (s *Store) Hash(ws, source string) (string, error) {
var d docEntry
err := s.db.View(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
if raw := b.Bucket(bucketDocs).Get([]byte(source)); raw != nil {
return json.Unmarshal(raw, &d)
}
return nil
})
return d.Hash, err
}
// Sources lists the indexed source keys of a workspace.
func (s *Store) Sources(ws string) ([]string, error) {
var out []string
err := s.db.View(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
return b.Bucket(bucketDocs).ForEach(func(k, _ []byte) error {
out = append(out, string(k))
return nil
})
})
return out, err
}
// Counts is how many sources and chunks a workspace has indexed.
func (s *Store) Counts(ws string) (pages, files, chunks int, err error) {
err = s.db.View(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
err := b.Bucket(bucketDocs).ForEach(func(k, v []byte) error {
if strings.HasPrefix(string(k), "file/") {
files++
} else {
pages++
}
return nil
})
chunks = b.Bucket(bucketChunks).Stats().KeyN
return err
})
return pages, files, chunks, err
}
// Put replaces the chunks of one source.
func (s *Store) Put(ws, source, hash string, chunks []Chunk) error {
return s.db.Update(func(tx *bolt.Tx) error {
b, err := wsBucket(tx, ws, true)
if err != nil {
return err
}
if err := dropChunks(b, source); err != nil {
return err
}
cb := b.Bucket(bucketChunks)
for i, c := range chunks {
if err := cb.Put(chunkKey(source, i), encodeChunk(c)); err != nil {
return err
}
}
raw, _ := json.Marshal(docEntry{Hash: hash, Chunks: len(chunks)})
return b.Bucket(bucketDocs).Put([]byte(source), raw)
})
}
// Drop removes a source.
func (s *Store) Drop(ws, source string) error {
return s.db.Update(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
if err := dropChunks(b, source); err != nil {
return err
}
return b.Bucket(bucketDocs).Delete([]byte(source))
})
}
func chunkKey(source string, n int) []byte { return fmt.Appendf(nil, "%s/%05d", source, n) }
func dropChunks(b *bolt.Bucket, source string) error {
c := b.Bucket(bucketChunks).Cursor()
prefix := []byte(source + "/")
var keys [][]byte
for k, _ := c.Seek(prefix); k != nil && strings.HasPrefix(string(k), string(prefix)); k, _ = c.Next() {
keys = append(keys, append([]byte(nil), k...))
}
for _, k := range keys {
if err := b.Bucket(bucketChunks).Delete(k); err != nil {
return err
}
}
return nil
}
// encodeChunk is: uint32 dims, dims × float32 (little endian), JSON metadata.
func encodeChunk(c Chunk) []byte {
meta, _ := json.Marshal(c)
out := make([]byte, 4+4*len(c.Vector), 4+4*len(c.Vector)+len(meta))
binary.LittleEndian.PutUint32(out, uint32(len(c.Vector)))
for i, f := range c.Vector {
binary.LittleEndian.PutUint32(out[4+4*i:], math.Float32bits(f))
}
return append(out, meta...)
}
// dot scores a stored chunk against q without decoding its metadata.
func dot(raw []byte, q []float32) (float32, bool) {
if len(raw) < 4 {
return 0, false
}
n := int(binary.LittleEndian.Uint32(raw))
if n != len(q) || len(raw) < 4+4*n {
return 0, false
}
var sum float32
for i := range n {
sum += math.Float32frombits(binary.LittleEndian.Uint32(raw[4+4*i:])) * q[i]
}
return sum, true
}
func decodeMeta(raw []byte) (Chunk, error) {
n := int(binary.LittleEndian.Uint32(raw))
var c Chunk
err := json.Unmarshal(raw[4+4*n:], &c)
return c, err
}
// normalize scales v to unit length in place (cosine = dot product).
func normalize(v []float32) []float32 {
var sum float64
for _, f := range v {
sum += float64(f) * float64(f)
}
if sum == 0 {
return v
}
inv := float32(1 / math.Sqrt(sum))
for i := range v {
v[i] *= inv
}
return v
}
// Scored is a chunk with its similarity to the query.
type Scored struct {
Chunk
Score float32 `json:"score"`
}
type minHeap []Scored
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].Score < h[j].Score }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any) { *h = append(*h, x.(Scored)) }
func (h *minHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
// Search returns the k chunks of ws most similar to q (normalised) that
// allow accepts, best first. Metadata is decoded only for chunks that would
// make the list.
func (s *Store) Search(ws string, q []float32, k int, allow func(Chunk) bool) ([]Scored, error) {
h := &minHeap{}
err := s.db.View(func(tx *bolt.Tx) error {
b, _ := wsBucket(tx, ws, false)
if b == nil {
return nil
}
return b.Bucket(bucketChunks).ForEach(func(key, raw []byte) error {
score, ok := dot(raw, q)
if !ok || (h.Len() >= k && score <= (*h)[0].Score) {
return nil
}
c, err := decodeMeta(raw)
if err != nil {
return nil
}
if parts := strings.SplitN(string(key), "/", 3); len(parts) == 3 {
c.Source = parts[0] + "/" + parts[1]
}
if allow != nil && !allow(c) {
return nil
}
heap.Push(h, Scored{Chunk: c, Score: score})
if h.Len() > k {
heap.Pop(h)
}
return nil
})
})
out := make([]Scored, h.Len())
for i := len(out) - 1; i >= 0; i-- {
out[i] = heap.Pop(h).(Scored)
}
return out, err
}