package server import ( "context" "encoding/json" "fmt" "strings" "unicode/utf8" "git.a-wan.net/alan/pipelines/internal/chattools" "git.a-wan.net/alan/pipelines/internal/protocol" ) // run executes one tool for sessionID, whose arguments already passed // chattools.ValidateArguments. id is the shown item's id (a replaced item's // own); a non-nil item is recorded and shown, and the result is the short // text the model reads. func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, arguments json.RawMessage) (*protocol.ChatShownItem, chattools.Result) { fail := func(format string, args ...any) (*protocol.ChatShownItem, chattools.Result) { return nil, chattools.Result{Text: fmt.Sprintf(format, args...), IsError: true} } decode := func(into any) error { return json.Unmarshal(arguments, into) } switch tool { case chattools.ToolShowFile: var in struct { Path string `json:"path"` Title string `json:"title"` } if err := decode(&in); err != nil { return fail("Nothing was shown: %v", err) } file, err := s.resolveShownFile(ctx, sessionID, in.Path) if err != nil { return fail("Nothing was shown: %v", err) } item := s.fileItem(sessionID, id, file, protocol.ChatShownFile, boundedLine(in.Title, 200)) return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: %s (%s%s).", file.name, humanBytes(file.size), shownKeptNote(item))} case chattools.ToolShowImage: var in struct { URLOrPath string `json:"url_or_path"` Title string `json:"title"` Alt string `json:"alt"` } if err := decode(&in); err != nil { return fail("Nothing was shown: %v", err) } title, alt := boundedLine(in.Title, 200), boundedLine(in.Alt, 500) source := strings.TrimSpace(in.URLOrPath) if strings.Contains(source, "://") { item, err := s.fetchShownImage(ctx, sessionID, id, source) if err != nil { return fail("Nothing was shown: %v", err) } item.Title, item.Alt = title, alt return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image at %s (%s, %s, downloaded by Pipelines).", item.URL, item.Mime, humanBytes(item.Size))} } file, err := s.resolveShownFile(ctx, sessionID, source) if err != nil { return fail("Nothing was shown: %v", err) } if !strings.HasPrefix(file.mime, "image/") { return fail("Nothing was shown: %s is %s, not an image; use show_file for documents.", file.name, file.mime) } item := s.fileItem(sessionID, id, file, protocol.ChatShownImage, title) item.Alt = alt return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image %s (%s%s).", file.name, humanBytes(file.size), shownKeptNote(item))} case chattools.ToolShowHTML: var in struct { HTML string `json:"html"` Title string `json:"title"` HeightHint int `json:"height_hint"` } if err := decode(&in); err != nil { return fail("Nothing was shown: %v", err) } if strings.TrimSpace(in.HTML) == "" { return fail("Nothing was shown: html is empty.") } if len(in.HTML) > chattools.MaxHTMLBytes { return fail("Nothing was shown: the document is %s; the limit is 512 KiB. Simplify it (inline SVG, fewer data points) and call show_html again.", humanBytes(int64(len(in.HTML)))) } if !utf8.ValidString(in.HTML) { return fail("Nothing was shown: html is not valid UTF-8.") } item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: boundedLine(in.Title, 200), HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)} return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))} case chattools.ToolShowDiff: var in struct { Path string `json:"path"` Base string `json:"base"` Head string `json:"head"` Paths []string `json:"paths"` Committed bool `json:"committed_only"` Title string `json:"title"` } if err := decode(&in); err != nil { return fail("Nothing was shown: %v", err) } return s.runShowDiff(ctx, sessionID, showDiffRequest{Path: in.Path, Base: in.Base, Head: in.Head, Paths: in.Paths, CommittedOnly: in.Committed, Title: boundedLine(in.Title, 200)}) case chattools.ToolShowRun: var in struct { RunID int64 `json:"run_id"` Title string `json:"title"` } if err := decode(&in); err != nil { return fail("Nothing was shown: %v", err) } return s.runShowRun(ctx, in.RunID, boundedLine(in.Title, 200)) case chattools.ToolScheduleFollowup: var in struct { Message string `json:"message"` At string `json:"at"` AfterMinutes *int64 `json:"after_minutes"` } if err := decode(&in); err != nil { return fail("Nothing was scheduled: %v", err) } return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes) case chattools.ToolNotify: var in struct { Title string `json:"title"` Message string `json:"message"` Priority string `json:"priority"` } if err := decode(&in); err != nil { return fail("Not sent: %v", err) } return s.runNotify(ctx, sessionID, boundedLine(in.Title, 200), in.Message, in.Priority) } return fail("Unknown tool %s.", tool) } // shownKeptNote says how a shown file is kept: a copy, or the live file. func shownKeptNote(item protocol.ChatShownItem) string { if item.Snapshot { return "; Pipelines keeps a copy of this version" } return "; shown from the live file, so the card notes later changes" } func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, message, priority string) (*protocol.ChatShownItem, chattools.Result) { message = boundedLine(message, 2000) if title == "" || message == "" { return nil, chattools.Result{Text: "Not sent: title and message are both required.", IsError: true} } switch priority { case "": priority = "default" case "low", "default", "high": default: return nil, chattools.Result{Text: "Not sent: priority must be low, default or high.", IsError: true} } if !s.limiter.allow(sessionID, s.now()) { return nil, chattools.Result{Text: "Not sent: this chat already sent 5 notifications in the last minute. Wait before notifying again.", IsError: true} } id := newChatShownID() delivery := s.notify(ctx, sessionID, chatToolNotice{ID: id, Title: title, Message: message, Priority: priority}) item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownNotify, Title: title, Message: message, Priority: priority, Delivered: delivery.App || delivery.Phone, Detail: delivery.Detail} switch { case delivery.App && delivery.Phone: return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps and phone notifications."} case delivery.App: return &item, chattools.Result{Text: "Delivered to the operator's Pipelines apps; " + delivery.Detail + "."} case delivery.Phone: return &item, chattools.Result{Text: "Delivered to the operator's phone notifications."} } return &item, chattools.Result{Text: "Not delivered: " + delivery.Detail + ".", IsError: true} } // boundedLine folds text to one line of at most limit bytes. func boundedLine(text string, limit int) string { return truncateUTF8(singleLine(text), limit) } func clampHeightHint(hint int) int { switch { case hint <= 0: return 0 case hint < 120: return 120 case hint > 600: return 600 } return hint } func humanBytes(n int64) string { switch { case n >= 1<<20: return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20)) case n >= 1<<10: return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10)) } return fmt.Sprintf("%d bytes", n) }