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

95 lines
3.5 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"context"
"strings"
"unicode/utf8"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
)
// ---- Writing actions on a selection --------------------------------------------------
// WriteInput is a writing action. Text is the selection; Before is the text
// in front of it (for "continue"); Language is the target of "translate";
// Instruction is the request of "custom".
type WriteInput struct {
Action string `json:"action"`
Text string `json:"text"`
Before string `json:"before"`
Language string `json:"language"`
Instruction string `json:"instruction"`
}
const writeSystem = `You are a writing assistant inside Docwell, a team wiki. You get a piece of a page and a task. Reply with the resulting text only, in Markdown, ready to put into the page: no preamble, no quotes around it, no remarks about what you changed. Keep the meaning, facts, names, links and formatting (lists, headings, emphasis) unless the task asks otherwise. Unless told to translate, write in the language of the text.`
var writeTasks = map[string]string{
"rewrite": "Rewrite the text so it reads clearly and naturally.",
"summarize": "Summarise the text in a few sentences or a short list of the key points.",
"translate": "Translate the text into %s.",
"continue": "Continue writing after the text, in the same voice and format. Reply with the continuation only.",
"shorter": "Make the text shorter, keeping what matters.",
"longer": "Expand the text with more detail and explanation, without inventing facts.",
"fix": "Fix spelling, grammar and punctuation. Change nothing else.",
"custom": "%s",
}
// Write streams the result of a writing action to onDelta.
func (s *Service) Write(ctx context.Context, c access.Caller, wsID string, in WriteInput, onDelta func(string)) error {
task, ok := writeTasks[in.Action]
if !ok {
return apperr.InvalidFields(map[string]string{"action": "Unknown writing action."})
}
text := strings.TrimSpace(in.Text)
if text == "" && in.Action != "continue" {
return apperr.InvalidFields(map[string]string{"text": "Select some text first."})
}
if utf8.RuneCountInString(text) > 20000 {
return apperr.InvalidFields(map[string]string{"text": "Select at most 20 000 characters."})
}
switch in.Action {
case "translate":
lang := strings.TrimSpace(in.Language)
if lang == "" || len(lang) > 60 {
return apperr.InvalidFields(map[string]string{"language": "Choose a language."})
}
task = strings.Replace(task, "%s", lang, 1)
case "custom":
ins := strings.TrimSpace(in.Instruction)
if ins == "" || utf8.RuneCountInString(ins) > 2000 {
return apperr.InvalidFields(map[string]string{"instruction": "Say what to do, in up to 2 000 characters."})
}
task = ins
}
_, chain, err := s.ready(ctx, c, wsID)
if err != nil {
return err
}
var prompt strings.Builder
prompt.WriteString("Task: " + task + "\n\n")
if in.Action == "continue" {
before := in.Before
if utf8.RuneCountInString(before) > 6000 {
r := []rune(before)
before = string(r[len(r)-6000:])
}
prompt.WriteString("Text so far:\n<text>\n" + strings.TrimSpace(before+"\n"+text) + "\n</text>")
} else {
prompt.WriteString("Text:\n<text>\n" + text + "\n</text>")
}
_, err = s.chat(ctx, chain, ChatRequest{
System: writeSystem, MaxTokens: 8000,
Messages: []Message{{Role: "user", Content: prompt.String()}},
}, onDelta)
if err != nil {
if _, ok := apperr.As(err); ok {
return err
}
return apperr.Invalid(userError(err))
}
return nil
}