Files
Docwell/Server/internal/ai/service.go
T
tajniak81andClaude Opus 5.5 8c39b0aacb
CI / go (Media) (push) Successful in 11m59s
CI / go (Server) (push) Failing after 18m26s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m35s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m6s
CI / mobile (push) Failing after 3m43s
CI / docker (push) Successful in 1h2m44s
Docs / build (push) Successful in 11m58s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Run ffmpeg in its own docwell-media service
ffmpeg parses untrusted uploads, so it moves out of the server image
into a container of its own (ADR-15):

- Media/: docwell-media, a small Go wrapper around ffmpeg.
  POST /v1/split takes a recording and returns the 16 kHz mono MP3
  pieces as multipart/mixed. ffmpeg may only open local files and
  common audio/video demuxers (no playlists); optional shared token,
  a job limit, a timeout and a 1 GB cap.
- Server: DOCWELL_MEDIA_URL and DOCWELL_MEDIA_TOKEN send recordings
  over 25 MB to the service. When it is blank or unreachable, the
  server uses a local ffmpeg if it has one, else cuts MP3 and WAV in
  Go. The server image no longer installs ffmpeg; the all-in-one
  image keeps it to stay one container.
- Compose: a media service in every stack, read-only, no
  capabilities, on an internal network only docwell-server joins.
- CI tests the new module and checks that only the server reaches
  media; the release workflow publishes docwell-media.
- Docs, ADR-15 and the .env examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:52:34 +01:00

171 lines
4.9 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"context"
"log/slog"
"net"
"net/http"
"regexp"
"sync"
"syscall"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/webhooks"
)
// Options configure the service.
type Options struct {
// Secret encrypts provider keys (DOCWELL_SECRET_KEY, or a value derived
// from the PocketBase password).
Secret string
// DataDir holds the vector store (ai.db).
DataDir string
// AllowLocal lets workspace profiles reach loopback and private
// addresses, like webhooks. Instance profiles always may.
AllowLocal bool
// MediaURL is docwell-media's address (DOCWELL_MEDIA_URL), which cuts
// long recordings with ffmpeg; "" cuts them on the server. MediaToken is
// its shared secret (DOCWELL_MEDIA_TOKEN), if it has one.
MediaURL string
MediaToken string
}
// Service is the AI layer.
type Service struct {
pb *pocketbase.Client
dir *directory.Service
keys *sealer
guarded *http.Client
open *http.Client
store *Store
log *slog.Logger
media *mediaClient
usageMu sync.Mutex
passMu sync.Mutex // one indexing pass at a time
wakeCh chan struct{}
track func(name string, run func() error) error
mu sync.Mutex
status map[string]*indexState // workspace → indexer progress
}
// New opens the vector store and returns the service.
func New(pb *pocketbase.Client, dir *directory.Service, log *slog.Logger, o Options) (*Service, error) {
store, err := OpenStore(o.DataDir)
if err != nil {
return nil, err
}
return newService(pb, dir, log, o, store), nil
}
func newService(pb *pocketbase.Client, dir *directory.Service, log *slog.Logger, o Options, store *Store) *Service {
transport := func(control func(network, address string, c syscall.RawConn) error) *http.Client {
d := &net.Dialer{Timeout: 15 * time.Second}
if control != nil {
d.Control = control
}
return &http.Client{Transport: &http.Transport{
DialContext: d.DialContext, Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 5 * time.Minute,
MaxIdleConnsPerHost: 4, IdleConnTimeout: 90 * time.Second,
}}
}
return &Service{
pb: pb, dir: dir, keys: newSealer(o.Secret), log: log, store: store,
guarded: transport(webhooks.Guard(o.AllowLocal)),
open: transport(nil),
media: newMediaClient(o.MediaURL, o.MediaToken),
wakeCh: make(chan struct{}, 1),
status: map[string]*indexState{},
}
}
// Close closes the vector store.
func (s *Service) Close() error { return s.store.Close() }
// Track reports each indexing pass to fn (the admin panel's job list).
func (s *Service) Track(fn func(name string, run func() error) error) { s.track = fn }
func (s *Service) wake() {
select {
case s.wakeCh <- struct{}{}:
default:
}
}
var idPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
func validID(id string) bool { return idPattern.MatchString(id) }
// ---- What a member sees --------------------------------------------------------
// Availability tells a workspace member what AI can do there.
type Availability struct {
// Chat is true when a profile with a chat model is set up and AI is on.
Chat bool `json:"chat"`
// Embeddings is true when the workspace is indexed for retrieval.
Embeddings bool `json:"embeddings"`
// Transcribe is true when a profile can turn audio into text.
Transcribe bool `json:"transcribe"`
CanManage bool `json:"canManage"`
}
// Available reports what AI offers in a workspace to c.
func (s *Service) Available(ctx context.Context, c access.Caller, wsID string) (Availability, error) {
role, err := s.dir.WorkspaceRole(ctx, c, wsID)
if err != nil {
return Availability{}, err
}
st, err := s.settings(ctx, wsID)
if err != nil {
return Availability{}, err
}
out := Availability{CanManage: access.AtLeast(role, access.WorkspaceAdmin)}
if !st.Enabled {
return out, nil
}
chain, err := s.chain(ctx, wsID, st)
if err != nil {
return out, err
}
for _, r := range chain {
if r.ChatModel != "" {
out.Chat = true
}
if r.TranscribeModel != "" {
out.Transcribe = true
}
}
_, hasEmbed := embedProfile(chain)
out.Embeddings = st.Index && hasEmbed
return out, nil
}
// ready loads what a chat or writing action in a workspace needs, checking
// that c is a member and AI is on.
func (s *Service) ready(ctx context.Context, c access.Caller, wsID string) (Settings, []profileRecord, error) {
if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil {
return Settings{}, nil, err
}
st, err := s.settings(ctx, wsID)
if err != nil {
return st, nil, err
}
if !st.Enabled {
return st, nil, apperr.Forbidden("AI is turned off in this workspace")
}
chain, err := s.chain(ctx, wsID, st)
if err != nil {
return st, nil, err
}
chain, err = s.limit(ctx, wsID, st, chain)
return st, chain, err
}