Files
pipelines/internal/server/chat_tools_files.go
T
alan c8541f29b7 Notify: an agent's notify reaches every connected app
The notify tool now records a chat_notify app notification with its own
id per call (no dedupe of repeated words) and the tool's priority, so
every subscribed client gets it and a reconnecting client replays it.
ntfy delivery is unchanged; the tool result names where it went.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:44:39 +00:00

197 lines
6.6 KiB
Go

package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"log"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// shownFile is a resolved file inside the operator's home.
type shownFile struct {
path string
name string
size int64
mime string
}
func (f shownFile) item(kind, title string) protocol.ChatShownItem {
return protocol.ChatShownItem{Kind: kind, Title: title, Path: f.path, Name: f.name, Size: f.size, Mime: f.mime}
}
// resolveShownFile applies the /files endpoint's containment rules to a model
// supplied path: it must name an existing regular file whose real path (every
// symlink resolved) is inside the operator's home and not on a special
// filesystem. A relative path is taken from the chat's working directory.
func (s *chatToolService) resolveShownFile(ctx context.Context, sessionID, requested string) (shownFile, error) {
requested = strings.TrimSpace(requested)
if requested == "" {
return shownFile{}, errors.New("a path is required")
}
home, err := s.home()
if err != nil {
return shownFile{}, err
}
home = filepath.Clean(home)
realHome, err := filepath.EvalSymlinks(home)
if err != nil {
return shownFile{}, errors.New("the operator's home directory is not available")
}
if !filepath.IsAbs(requested) && !strings.HasPrefix(requested, "~") {
directory := s.chatSessionDirectory(ctx, sessionID)
if directory == "" {
return shownFile{}, errors.New("path " + requested + " is relative and this chat has no recorded working directory; pass an absolute path")
}
requested = filepath.Join(directory, requested)
}
target, err := expandHomePath(home, requested)
if err != nil {
return shownFile{}, err
}
_, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
if strings.Contains(err.Error(), "outside the home directory") {
return shownFile{}, errors.New("path " + requested + " is outside the operator's home directory; only files inside home can be shown")
}
return shownFile{}, err
}
info, err := os.Stat(realTarget)
if err != nil {
return shownFile{}, describePathError(requested, err)
}
if info.IsDir() {
return shownFile{}, errors.New(requested + " is a directory; show one file")
}
if !info.Mode().IsRegular() || specialFilesystem(realTarget) {
return shownFile{}, errors.New(requested + " is not a regular file")
}
return shownFile{path: realTarget, name: filepath.Base(realTarget), size: info.Size(), mime: shownFileMime(realTarget)}, nil
}
// shownFileMime is the type the /files endpoint will serve: by extension, else
// sniffed from the first bytes.
func shownFileMime(path string) string {
if byExtension := mime.TypeByExtension(filepath.Ext(path)); byExtension != "" {
media, _, err := mime.ParseMediaType(byExtension)
if err == nil {
return media
}
}
file, err := os.Open(path)
if err != nil {
return "application/octet-stream"
}
defer file.Close()
var sample [512]byte
n, err := file.Read(sample[:])
if err != nil && !errors.Is(err, io.EOF) {
return "application/octet-stream"
}
media, _, _ := mime.ParseMediaType(http.DetectContentType(sample[:n]))
if media == "" {
return "application/octet-stream"
}
return media
}
// shownImageURL accepts only an absolute https URL without credentials.
func shownImageURL(raw string) (string, error) {
if len(raw) > 2048 {
return "", errors.New("the image URL is longer than 2048 characters")
}
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" {
return "", errors.New("the image URL is not a valid absolute URL")
}
if parsed.Scheme != "https" {
return "", errors.New("only https:// image URLs can be shown")
}
if parsed.User != nil {
return "", errors.New("the image URL must not carry credentials")
}
return parsed.String(), nil
}
// chatToolNotice is one model-requested notification. ID is the chat's shown
// item id, so every call is its own notification even with repeated words.
type chatToolNotice struct {
ID string
Title string
Message string
Priority string // low, default or high
}
// chatToolDelivery reports where a chat tool notification went: App when it
// was recorded on the app notification stream (every connected Pipelines app
// receives it and a reconnecting one replays it), Phone when ntfy accepted it.
// Detail explains a phone delivery that was skipped or refused.
type chatToolDelivery struct {
App bool
Phone bool
Detail string
}
// chatToolNotifier delivers one model-requested notification for a chat.
type chatToolNotifier func(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery
// chatNotifyPriority maps the tool's priority word to the app stream's
// ntfy-style 1-5 priority.
func chatNotifyPriority(priority string) int {
switch priority {
case "low":
return 2
case "high":
return 4
}
return protocol.DefaultNotificationPriority
}
// publishToolNotification records the notification on the app notification
// stream (kind chat_notify), which is pushed to every subscribed client and
// replayed to one that reconnects while it is still active, then publishes it
// through the operator's existing "system" ntfy destination (the one chat
// attention uses), honoring their ntfy switch. Tapping it opens the chat
// (pipelines://chat/<id>).
func (h *chatHub) publishToolNotification(ctx context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
title := truncateUTF8(notice.Title, 256)
message := truncateUTF8(notice.Message, 2000)
click, views := chatAttentionLinks(sessionID)
id := notice.ID
if id == "" {
digest := sha256.Sum256([]byte(title + "\x00" + message))
id = hex.EncodeToString(digest[:8])
}
var delivery chatToolDelivery
if h.notes != nil {
delivery.App = h.notes.record(ctx, pipeline.AppNotificationRecord{
AppNotification: protocol.AppNotification{ID: "chat:" + sessionID + ":notify:" + id, Kind: protocol.NotificationChatNotify, Title: title, Message: message, Click: click, Priority: chatNotifyPriority(notice.Priority), Tags: []string{}, Group: "chat:" + sessionID},
SessionID: sessionID,
})
}
switch {
case !chatAttentionConfigured():
delivery.Detail = "phone notifications (ntfy) are not configured"
case !chatNotificationSettings(ctx, h.settings).NtfyEnabled:
delivery.Detail = "phone notifications (ntfy) are turned off"
default:
if _, err := chatAttentionPublish(ctx, "system", title, message, "", nil, click, views...); err != nil {
log.Printf("chat tool notification session=%s: %v", sessionID, err)
delivery.Detail = "the phone notification service refused it: " + err.Error()
} else {
delivery.Phone = true
}
}
return delivery
}