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

169 lines
3.9 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 (
"encoding/json"
"strings"
"unicode/utf8"
"docwell/server/internal/convert"
)
// chunkSize is the target length of one chunk in characters.
const chunkSize = 1200
// piece is a chunk before it has a vector: Text is shown as a source,
// Embed is what gets embedded (with the page title and heading for context).
type piece struct {
Block string
Text string
Embed string
}
// blockText is a block's text with line breaks between its child blocks,
// so list items and table cells do not run together.
func blockText(n convert.Node) string {
if n.Type == "text" {
return n.Text
}
if n.Type == "hardBreak" {
return "\n"
}
inline := true
for _, c := range n.Content {
if c.Type != "text" && c.Type != "hardBreak" && c.Type != "mention" && c.Type != "inlineMath" {
inline = false
}
}
var parts []string
for _, c := range n.Content {
if t := blockText(c); t != "" {
parts = append(parts, t)
}
}
if n.Type == "mention" || n.Type == "pageLink" {
if l, ok := n.Attrs["label"].(string); ok {
return l
}
if l, ok := n.Attrs["title"].(string); ok {
return l
}
}
if inline {
return strings.Join(parts, "")
}
return strings.Join(parts, "\n")
}
func blockID(n convert.Node) string {
id, _ := n.Attrs["blockId"].(string)
return id
}
// chunkDoc cuts a page into pieces along its top-level blocks: a heading
// starts a new piece, and pieces stay near chunkSize. A piece remembers the
// first linkable block it covers, for citations.
func chunkDoc(title string, raw json.RawMessage) []piece {
doc, err := convert.Parse(raw)
if err != nil {
return nil
}
var out []piece
var buf strings.Builder
block, heading := "", ""
flush := func() {
text := strings.TrimSpace(buf.String())
buf.Reset()
if text == "" {
return
}
for _, part := range splitLong(text, chunkSize*3/2) {
ctx := title
if heading != "" && heading != title {
ctx += " › " + heading
}
out = append(out, piece{Block: block, Text: part, Embed: ctx + "\n\n" + part})
}
block = ""
}
for _, n := range doc.Content {
text := strings.TrimSpace(blockText(n))
if n.Type == "heading" {
flush()
heading = text
}
if text == "" {
continue
}
if buf.Len() > 0 && utf8.RuneCountInString(buf.String())+utf8.RuneCountInString(text) > chunkSize {
flush()
}
if block == "" {
block = blockID(n)
}
buf.WriteString(text)
buf.WriteString("\n\n")
}
flush()
return out
}
// chunkText cuts plain text (an extra file) into pieces at blank lines.
func chunkText(title, text string) []piece {
var out []piece
var buf strings.Builder
flush := func() {
t := strings.TrimSpace(buf.String())
buf.Reset()
for _, part := range splitLong(t, chunkSize*3/2) {
out = append(out, piece{Text: part, Embed: title + "\n\n" + part})
}
}
for _, para := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n\n") {
para = strings.TrimSpace(para)
if para == "" {
continue
}
if buf.Len() > 0 && utf8.RuneCountInString(buf.String())+utf8.RuneCountInString(para) > chunkSize {
flush()
}
buf.WriteString(para)
buf.WriteString("\n\n")
}
flush()
return out
}
// splitLong breaks text longer than max runes at whitespace.
func splitLong(text string, max int) []string {
if text == "" {
return nil
}
var out []string
for utf8.RuneCountInString(text) > max {
runes := []rune(text)
cut := max
for i := max; i > max/2; i-- {
if runes[i] == '\n' || runes[i] == ' ' {
cut = i
break
}
}
out = append(out, strings.TrimSpace(string(runes[:cut])))
text = strings.TrimSpace(string(runes[cut:]))
}
if text != "" {
out = append(out, text)
}
return out
}
// truncate shortens s to at most n runes, with an ellipsis.
func truncate(s string, n int) string {
if utf8.RuneCountInString(s) <= n {
return s
}
return strings.TrimSpace(string([]rune(s)[:n])) + "…"
}