Merge branch 'worktree-agent-abc9e7b0a4e0a0f54'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -92,6 +92,9 @@ type chatHub struct {
|
||||
// shown holds the items chats showed through the Pipelines tools; the
|
||||
// subscribe reply carries a chat's retained list. nil records none.
|
||||
shown chatShownStore
|
||||
// shownRefresh brings listed items up to date (file states, followed
|
||||
// runs) before a subscribe reply carries them; nil leaves them as stored.
|
||||
shownRefresh func(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem
|
||||
// autoSwitch records the usage-limit refusals the server already
|
||||
// continued on another Claude account (chat_auto_switch.go).
|
||||
autoSwitch chatAutoSwitchState
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"log"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
@@ -100,8 +101,10 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat
|
||||
}
|
||||
// A prompt scheduled for later is always queued: never run or steered now.
|
||||
scheduled := p.sendAt.After(h.clock())
|
||||
busy := scheduled || room.running || len(room.queue) > 0 || room.observedTurn
|
||||
queuedAhead := scheduled || len(room.queue) > 0
|
||||
// Agent follow-ups that are not due yet hold nothing up.
|
||||
head, _ := chatQueueHead(room.queue, h.clock())
|
||||
busy := scheduled || room.running || head >= 0 || room.observedTurn
|
||||
queuedAhead := scheduled || head >= 0
|
||||
h.mu.Unlock()
|
||||
if !busy {
|
||||
busy = brokerTurnRunning(broker, sessionID)
|
||||
@@ -154,6 +157,35 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat
|
||||
return chatAdmitQueued, nil
|
||||
}
|
||||
|
||||
// chatFollowupPrefix starts the operation id of a prompt an agent scheduled
|
||||
// for itself (schedule_followup). Such a prompt is the one exception to the
|
||||
// queue's FIFO order: until it is due it steps aside, so the operator's own
|
||||
// prompts are never held behind an agent's reminder for hours.
|
||||
const chatFollowupPrefix = "followup-"
|
||||
|
||||
// isFollowup reports whether p is an agent's scheduled follow-up.
|
||||
func (p *chatQueuedPrompt) isFollowup() bool {
|
||||
return strings.HasPrefix(p.operationID, chatFollowupPrefix)
|
||||
}
|
||||
|
||||
// chatQueueHead is the index of the prompt the runner considers next: the
|
||||
// first one that is not an agent follow-up still waiting for its time, or -1
|
||||
// when there is none. followupWait is how long until the earliest of the
|
||||
// skipped follow-ups is due (zero when none was skipped).
|
||||
func chatQueueHead(queue []*chatQueuedPrompt, now time.Time) (int, time.Duration) {
|
||||
var followupWait time.Duration
|
||||
for i, p := range queue {
|
||||
if p.isFollowup() && p.sendAt.After(now) {
|
||||
if wait := p.sendAt.Sub(now); followupWait == 0 || wait < followupWait {
|
||||
followupWait = wait
|
||||
}
|
||||
continue
|
||||
}
|
||||
return i, followupWait
|
||||
}
|
||||
return -1, followupWait
|
||||
}
|
||||
|
||||
func errChatQueueFull(sessionID string) error {
|
||||
return errors.New("session " + sessionID + " already has the maximum number of prompts queued")
|
||||
}
|
||||
|
||||
@@ -801,12 +801,20 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
|
||||
return nil, nil, false
|
||||
}
|
||||
var wait time.Duration
|
||||
head, followupWait := chatQueueHead(room.queue, h.clock())
|
||||
if len(room.queue) > 0 {
|
||||
switch now := h.clock(); {
|
||||
case room.queue[0].sendAt.After(now):
|
||||
case head < 0:
|
||||
// Only agent follow-ups that are not due yet: sleep until the
|
||||
// first of them.
|
||||
wait = min(followupWait, chatQueueScheduleRecheck)
|
||||
case room.queue[head].sendAt.After(now):
|
||||
// A scheduled head waits for its time; the queue is FIFO, so
|
||||
// later prompts wait behind it. A timer wakes the runner then.
|
||||
wait = min(room.queue[0].sendAt.Sub(now), chatQueueScheduleRecheck)
|
||||
wait = min(room.queue[head].sendAt.Sub(now), chatQueueScheduleRecheck)
|
||||
if followupWait > 0 {
|
||||
wait = min(wait, followupWait)
|
||||
}
|
||||
case room.observedTurn:
|
||||
wait = chatQueueBusyPoll
|
||||
if !room.running {
|
||||
@@ -826,9 +834,9 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
|
||||
h.mu.Lock()
|
||||
if busy {
|
||||
wait = chatQueueBusyPoll
|
||||
} else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[0].sendAt.After(h.clock()) {
|
||||
p := room.queue[0]
|
||||
room.queue = room.queue[1:]
|
||||
} else if index, _ := chatQueueHead(room.queue, h.clock()); index >= 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[index].sendAt.After(h.clock()) {
|
||||
p := room.queue[index]
|
||||
room.queue = append(room.queue[:index:index], room.queue[index+1:]...)
|
||||
room.running = true
|
||||
room.nativeTurnID = ""
|
||||
room.turnDone = make(chan struct{})
|
||||
|
||||
@@ -32,10 +32,56 @@ const (
|
||||
type showDiffRequest struct {
|
||||
Path string
|
||||
Base string
|
||||
Head string
|
||||
Paths []string
|
||||
CommittedOnly bool
|
||||
Title string
|
||||
}
|
||||
|
||||
// showDiffMaxPaths bounds the paths argument.
|
||||
const showDiffMaxPaths = 50
|
||||
|
||||
// showDiffPathspecs turns the model's paths into Git pathspecs confined to the
|
||||
// repository: each must be relative, without a .. component, option prefix,
|
||||
// pathspec magic or control character. A path with glob characters matches as
|
||||
// a glob (":(glob)"), any other literally.
|
||||
func showDiffPathspecs(paths []string) ([]string, []string, error) {
|
||||
if len(paths) > showDiffMaxPaths {
|
||||
return nil, nil, fmt.Errorf("paths has %d entries; the limit is %d", len(paths), showDiffMaxPaths)
|
||||
}
|
||||
var specs, kept []string
|
||||
for _, raw := range paths {
|
||||
path := strings.TrimSpace(raw)
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
if len(path) > 500 || strings.HasPrefix(path, "-") || strings.HasPrefix(path, ":") || filepath.IsAbs(path) || strings.HasPrefix(path, "~") {
|
||||
return nil, nil, fmt.Errorf("paths entry %q must be a path inside the repository, relative to its top", raw)
|
||||
}
|
||||
for _, r := range path {
|
||||
if unicode.IsControl(r) {
|
||||
return nil, nil, fmt.Errorf("paths entry %q contains a control character", raw)
|
||||
}
|
||||
}
|
||||
for _, part := range strings.Split(filepath.ToSlash(path), "/") {
|
||||
if part == ".." {
|
||||
return nil, nil, fmt.Errorf("paths entry %q leaves the repository", raw)
|
||||
}
|
||||
}
|
||||
path = strings.TrimSuffix(filepath.ToSlash(filepath.Clean(path)), "/")
|
||||
if path == "." {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, path)
|
||||
if strings.ContainsAny(path, "*?[") {
|
||||
specs = append(specs, ":(glob)"+path)
|
||||
} else {
|
||||
specs = append(specs, ":(literal)"+path)
|
||||
}
|
||||
}
|
||||
return specs, kept, nil
|
||||
}
|
||||
|
||||
// runShowDiff compares a repository inside the operator's home and records
|
||||
// the per-file patches as one diff item.
|
||||
func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in showDiffRequest) (*protocol.ChatShownItem, chattools.Result) {
|
||||
@@ -49,6 +95,17 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in
|
||||
if base != "" && !validGitRevision(base) {
|
||||
return fail(fmt.Errorf("base %q is not a branch, tag or commit name", base))
|
||||
}
|
||||
headName := strings.TrimSpace(in.Head)
|
||||
if headName != "" && !validGitRevision(headName) {
|
||||
return fail(fmt.Errorf("head %q is not a branch, tag or commit name", headName))
|
||||
}
|
||||
if headName != "" && in.CommittedOnly {
|
||||
return fail(errors.New("committed_only does not apply with head, which is always committed"))
|
||||
}
|
||||
pathspecs, paths, err := showDiffPathspecs(in.Paths)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
directory, err := s.resolveDiffDirectory(ctx, sessionID, in.Path)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
@@ -70,8 +127,23 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in
|
||||
} else if head != "" {
|
||||
body.Head = shortCommit(head)
|
||||
}
|
||||
current := head
|
||||
if headName != "" {
|
||||
target, err := git.output("rev-parse", "--verify", "--quiet", "--end-of-options", headName+"^{commit}")
|
||||
if err != nil {
|
||||
return fail(fmt.Errorf("head %q is not a commit in %s", headName, git.directory))
|
||||
}
|
||||
head, headErr = strings.TrimSpace(target), nil
|
||||
body.Head, body.HeadRevision = headName, headName
|
||||
}
|
||||
body.Paths = paths
|
||||
var compare string
|
||||
switch {
|
||||
case headName != "" && base == "":
|
||||
if current == "" {
|
||||
return fail(errors.New("this repository has no HEAD commit to compare " + headName + " with; pass base"))
|
||||
}
|
||||
compare = current
|
||||
case base != "":
|
||||
if headErr != nil || head == "" {
|
||||
return fail(errors.New("this repository has no commits yet, so there is nothing to compare with " + base))
|
||||
@@ -94,11 +166,12 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in
|
||||
body.BaseCommit = shortCommit(compare)
|
||||
}
|
||||
revisions := []string{compare}
|
||||
if in.CommittedOnly {
|
||||
worktree := !in.CommittedOnly && headName == ""
|
||||
if !worktree {
|
||||
revisions = append(revisions, head)
|
||||
}
|
||||
|
||||
changes, err := collectGitDiff(git, revisions, !in.CommittedOnly)
|
||||
changes, err := collectGitDiff(git, revisions, worktree, pathspecs)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
@@ -118,6 +191,10 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in
|
||||
func showDiffSummary(body protocol.ChatShownDiffBody) string {
|
||||
against := "HEAD"
|
||||
switch {
|
||||
case body.HeadRevision != "" && body.Base != "":
|
||||
against = fmt.Sprintf("%s (merge base %s), showing %s", body.Base, body.BaseCommit, body.HeadRevision)
|
||||
case body.HeadRevision != "":
|
||||
against = fmt.Sprintf("HEAD (%s), showing %s", body.BaseCommit, body.HeadRevision)
|
||||
case body.Base != "" && body.CommittedOnly:
|
||||
against = fmt.Sprintf("%s (merge base %s), committed changes only", body.Base, body.BaseCommit)
|
||||
case body.Base != "":
|
||||
@@ -125,6 +202,9 @@ func showDiffSummary(body protocol.ChatShownDiffBody) string {
|
||||
case body.BaseCommit == "":
|
||||
against = "an empty repository"
|
||||
}
|
||||
if len(body.Paths) > 0 {
|
||||
against += ", limited to " + strings.Join(body.Paths, ", ")
|
||||
}
|
||||
if body.Files == 0 {
|
||||
return fmt.Sprintf("Shown in the operator's Pipelines chat: no changes in %s against %s.", body.Repo, against)
|
||||
}
|
||||
|
||||
@@ -20,15 +20,15 @@ type gitDiffEntry struct {
|
||||
// work tree against it; two: those commits) plus, when includeUntracked, the
|
||||
// untracked files Git does not ignore, and reads each file's patch within the
|
||||
// show_diff bounds.
|
||||
func collectGitDiff(git gitRunner, revisions []string, includeUntracked bool) (*protocol.StageFileChanges, error) {
|
||||
func collectGitDiff(git gitRunner, revisions []string, includeUntracked bool, pathspecs []string) (*protocol.StageFileChanges, error) {
|
||||
nameArgs := append([]string{"diff", "--name-status", "-z", "--no-renames"}, revisions...)
|
||||
names, err := git.output(append(nameArgs, "--")...)
|
||||
names, err := git.output(append(append(nameArgs, "--"), pathspecs...)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries := parseNameStatus(names)
|
||||
if includeUntracked {
|
||||
others, err := git.output("ls-files", "--others", "--exclude-standard", "-z")
|
||||
others, err := git.output(append([]string{"ls-files", "--others", "--exclude-standard", "-z", "--"}, pathspecs...)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestShowDiffHeadAndPaths(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
repo := showDiffRepo(t, f.home)
|
||||
token := f.token(t, chatToolSessionScope+"ses_o")
|
||||
if out, err := exec.Command("git", "-C", repo, "switch", "-q", "--discard-changes", "main").CombinedOutput(); err != nil {
|
||||
t.Fatalf("switch to main: %v %s", err, out)
|
||||
}
|
||||
|
||||
// head instead of the work tree: feature against HEAD (main).
|
||||
r := f.call(token, "show_diff", `{"path":"`+repo+`","head":"feature"}`)
|
||||
if r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
item := diffItem(t, f, "ses_o")
|
||||
if got := diffPaths(item); len(got) != 2 || got["a.txt"] != "modified" || got["b.txt"] != "added" {
|
||||
t.Fatalf("head compares the revision, without untracked files: %v", got)
|
||||
}
|
||||
if item.Diff.HeadRevision != "feature" || item.Diff.Head != "feature" || !strings.Contains(r.Text, "showing feature") {
|
||||
t.Fatalf("summary: %+v %s", item.Diff, r.Text)
|
||||
}
|
||||
|
||||
// head against a base, limited to a path and a glob.
|
||||
if r := f.call(token, "show_diff", `{"path":"`+repo+`","head":"feature","base":"main","paths":["b.txt"]}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
item = diffItem(t, f, "ses_o")
|
||||
if got := diffPaths(item); len(got) != 1 || got["b.txt"] != "added" || len(item.Diff.Paths) != 1 {
|
||||
t.Fatalf("paths limits the diff: %v %+v", got, item.Diff)
|
||||
}
|
||||
if r := f.call(token, "show_diff", `{"path":"`+repo+`","paths":["*.txt"]}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if got := diffPaths(diffItem(t, f, "ses_o")); len(got) != 1 || got["u.txt"] != "added" {
|
||||
t.Fatalf("a glob matches untracked work too: %v", got)
|
||||
}
|
||||
|
||||
for _, tc := range []struct{ args, want string }{
|
||||
{`{"path":"` + repo + `","head":"--output=/tmp/x"}`, "head \"--output=/tmp/x\" is not a branch"},
|
||||
{`{"path":"` + repo + `","head":"nope"}`, "is not a commit"},
|
||||
{`{"path":"` + repo + `","head":"feature","base":"main","committed_only":true}`, "committed_only does not apply"},
|
||||
{`{"path":"` + repo + `","paths":["../outside"]}`, "leaves the repository"},
|
||||
{`{"path":"` + repo + `","paths":["/etc/passwd"]}`, "must be a path inside the repository"},
|
||||
{`{"path":"` + repo + `","paths":[":(top)x"]}`, "must be a path inside the repository"},
|
||||
{`{"path":"` + repo + `","paths":["-x"]}`, "must be a path inside the repository"},
|
||||
{`{"path":"` + repo + `","paths":"a.txt"}`, "paths must be an array of strings"},
|
||||
} {
|
||||
r := f.call(token, "show_diff", tc.args)
|
||||
if !r.IsError || !strings.Contains(r.Text, tc.want) {
|
||||
t.Errorf("%s: want refusal %q, got %+v", tc.args, tc.want, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// show_image downloads a web image on the server, so the operator's device
|
||||
// never has to fetch a cross-origin address (which many hosts refuse), and
|
||||
// keeps the bytes as the item's snapshot. The download is SSRF-safe: https
|
||||
// only, every connection (redirects included) to a public unicast address
|
||||
// checked after DNS resolution, no proxy, no credentials, a timeout, at most
|
||||
// chattools.MaxFetchedImageBytes, and only raster image types whose bytes
|
||||
// agree with the declared type.
|
||||
|
||||
const shownImageFetchTimeout = 20 * time.Second
|
||||
|
||||
// shownImageTypes are the image types fetched, by extension. SVG is refused:
|
||||
// served from the app's origin it could carry script.
|
||||
var shownImageTypes = map[string]string{
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
"image/avif": ".avif",
|
||||
"image/bmp": ".bmp",
|
||||
}
|
||||
|
||||
// shownImageFetcher downloads web images. allowed decides which resolved
|
||||
// addresses may be dialed; tlsConfig is for tests.
|
||||
type shownImageFetcher struct {
|
||||
allowed func(netip.Addr) bool
|
||||
tlsConfig *tls.Config
|
||||
}
|
||||
|
||||
// publicAddress admits only global unicast addresses that are not private,
|
||||
// loopback, link-local, shared (CGNAT), documentation or otherwise special.
|
||||
func publicAddress(addr netip.Addr) bool {
|
||||
addr = addr.Unmap()
|
||||
if !addr.IsValid() || !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() ||
|
||||
addr.IsLinkLocalUnicast() || addr.IsMulticast() || addr.IsUnspecified() {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range shownBlockedPrefixes {
|
||||
if prefix.Contains(addr) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var shownBlockedPrefixes = []netip.Prefix{
|
||||
netip.MustParsePrefix("0.0.0.0/8"),
|
||||
netip.MustParsePrefix("100.64.0.0/10"),
|
||||
netip.MustParsePrefix("192.0.0.0/24"),
|
||||
netip.MustParsePrefix("192.0.2.0/24"),
|
||||
netip.MustParsePrefix("198.18.0.0/15"),
|
||||
netip.MustParsePrefix("198.51.100.0/24"),
|
||||
netip.MustParsePrefix("203.0.113.0/24"),
|
||||
netip.MustParsePrefix("240.0.0.0/4"),
|
||||
netip.MustParsePrefix("64:ff9b::/96"),
|
||||
netip.MustParsePrefix("64:ff9b:1::/48"),
|
||||
netip.MustParsePrefix("2001::/23"),
|
||||
netip.MustParsePrefix("2001:db8::/32"),
|
||||
netip.MustParsePrefix("2002::/16"),
|
||||
}
|
||||
|
||||
var errShownAddressRefused = errors.New("the image host resolves to a private or local address, which Pipelines does not fetch from")
|
||||
|
||||
func (f shownImageFetcher) client() *http.Client {
|
||||
allowed := f.allowed
|
||||
if allowed == nil {
|
||||
allowed = publicAddress
|
||||
}
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: func(_, address string, _ syscall.RawConn) error {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr, err := netip.ParseAddr(host)
|
||||
if err != nil || !allowed(addr) {
|
||||
return errShownAddressRefused
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: dialer.DialContext,
|
||||
TLSClientConfig: f.tlsConfig,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
MaxIdleConns: 1,
|
||||
DisableKeepAlives: true,
|
||||
}
|
||||
return &http.Client{Transport: transport, Timeout: shownImageFetchTimeout, CheckRedirect: func(request *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
return errors.New("the image URL redirects too many times")
|
||||
}
|
||||
if request.URL.Scheme != "https" {
|
||||
return fmt.Errorf("the image URL redirects to a non-https address (%s)", request.URL.Redacted())
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// fetchShownImage downloads the https image at raw and records it as a
|
||||
// snapshot image item (id is the item's id).
|
||||
func (s *chatToolService) fetchShownImage(ctx context.Context, sessionID, id, raw string) (protocol.ChatShownItem, error) {
|
||||
address, err := shownImageURL(raw)
|
||||
if err != nil {
|
||||
return protocol.ChatShownItem{}, err
|
||||
}
|
||||
data, mediaType, err := s.fetch.get(ctx, address)
|
||||
if err != nil {
|
||||
return protocol.ChatShownItem{}, err
|
||||
}
|
||||
name := shownImageName(address, shownImageTypes[mediaType])
|
||||
path, size, err := s.writeSnapshot(sessionID, id, name, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return protocol.ChatShownItem{}, fmt.Errorf("Pipelines downloaded the image but could not keep it: %v", err)
|
||||
}
|
||||
return protocol.ChatShownItem{Kind: protocol.ChatShownImage, Path: path, Name: name, Size: size, Mime: mediaType, Snapshot: true, URL: address}, nil
|
||||
}
|
||||
|
||||
// get downloads one image and returns its bytes and media type.
|
||||
func (f shownImageFetcher) get(ctx context.Context, address string) ([]byte, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, shownImageFetchTimeout)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
|
||||
if err != nil {
|
||||
return nil, "", errors.New("the image URL is not valid")
|
||||
}
|
||||
request.Header.Set("Accept", "image/png,image/jpeg,image/gif,image/webp,image/avif,image/bmp;q=0.9")
|
||||
request.Header.Set("User-Agent", "Pipelines-image-fetch/1")
|
||||
response, err := f.client().Do(request)
|
||||
if err != nil {
|
||||
if errors.Is(err, errShownAddressRefused) {
|
||||
return nil, "", errShownAddressRefused
|
||||
}
|
||||
var redirect *url.Error
|
||||
if errors.As(err, &redirect) && redirect.Err != nil && strings.Contains(redirect.Err.Error(), "redirect") {
|
||||
return nil, "", redirect.Err
|
||||
}
|
||||
return nil, "", fmt.Errorf("the image could not be downloaded: %v", shownFetchError(err))
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, "", fmt.Errorf("the image host answered %s", response.Status)
|
||||
}
|
||||
mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type"))
|
||||
if _, ok := shownImageTypes[mediaType]; !ok {
|
||||
if mediaType == "" {
|
||||
mediaType = "no content type"
|
||||
}
|
||||
return nil, "", fmt.Errorf("the URL is %s, not a PNG, JPEG, GIF, WebP, AVIF or BMP image", mediaType)
|
||||
}
|
||||
if response.ContentLength > chattools.MaxFetchedImageBytes {
|
||||
return nil, "", fmt.Errorf("the image is %s; the limit is 10 MiB", humanBytes(response.ContentLength))
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, chattools.MaxFetchedImageBytes+1))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("the image download failed: %v", shownFetchError(err))
|
||||
}
|
||||
if len(data) > chattools.MaxFetchedImageBytes {
|
||||
return nil, "", errors.New("the image is larger than the 10 MiB limit")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, "", errors.New("the image is empty")
|
||||
}
|
||||
if sniffed := http.DetectContentType(data); strings.HasPrefix(sniffed, "text/") || sniffed == "application/octet-stream" && mediaType != "image/avif" {
|
||||
return nil, "", fmt.Errorf("the URL says it is %s but its content is not an image", mediaType)
|
||||
}
|
||||
return data, mediaType, nil
|
||||
}
|
||||
|
||||
func shownFetchError(err error) error {
|
||||
var urlErr *url.Error
|
||||
if errors.As(err, &urlErr) {
|
||||
return urlErr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// shownImageName is the image's file name from its URL path, with the
|
||||
// extension of its type.
|
||||
func shownImageName(address, extension string) string {
|
||||
base := "image"
|
||||
if parsed, err := url.Parse(address); err == nil {
|
||||
if name := path.Base(parsed.Path); name != "." && name != "/" && name != "" {
|
||||
base = strings.TrimSuffix(name, path.Ext(name))
|
||||
}
|
||||
}
|
||||
base = safeSnapshotName(base)
|
||||
if len(base) > 120 {
|
||||
base = truncateUTF8(base, 120)
|
||||
}
|
||||
return base + extension
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
)
|
||||
|
||||
var testPNG = append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{0}, 32)...)
|
||||
|
||||
// imageServer is a loopback https host the fixture's fetcher may reach.
|
||||
func (f *chatToolFixture) imageServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/a.png", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(testPNG)
|
||||
})
|
||||
mux.HandleFunc("/page", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte("<html></html>"))
|
||||
})
|
||||
mux.HandleFunc("/drawing.svg", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/svg+xml")
|
||||
_, _ = w.Write([]byte("<svg/>"))
|
||||
})
|
||||
mux.HandleFunc("/fake.png", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write([]byte("<html><script>alert(1)</script></html>"))
|
||||
})
|
||||
mux.HandleFunc("/big.png", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(chattools.MaxFetchedImageBytes+1))
|
||||
_, _ = w.Write(append(testPNG, make([]byte, chattools.MaxFetchedImageBytes+1-len(testPNG))...))
|
||||
})
|
||||
mux.HandleFunc("/to-http", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://"+r.Host+"/a.png", http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/to-png", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/a.png", http.StatusFound)
|
||||
})
|
||||
server := httptest.NewTLSServer(mux)
|
||||
t.Cleanup(server.Close)
|
||||
f.service.fetch = shownImageFetcher{
|
||||
allowed: func(addr netip.Addr) bool { return addr.IsLoopback() },
|
||||
tlsConfig: server.Client().Transport.(*http.Transport).TLSClientConfig,
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
func TestShowImageFetchesOnlyRealImagesWithinBounds(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_w")
|
||||
web := f.imageServer(t)
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/to-png"}`); r.IsError {
|
||||
t.Fatalf("an https redirect is followed: %v", r)
|
||||
}
|
||||
for path, want := range map[string]string{
|
||||
"/page": "text/html, not a PNG",
|
||||
"/drawing.svg": "image/svg+xml, not a PNG",
|
||||
"/fake.png": "content is not an image",
|
||||
"/big.png": "the limit is 10 MiB",
|
||||
"/to-http": "redirects to a non-https address",
|
||||
"/missing.png": "answered 404",
|
||||
} {
|
||||
r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+path+`"}`)
|
||||
if !r.IsError || !strings.Contains(r.Text, want) {
|
||||
t.Errorf("%s: got %v, want %q", path, r, want)
|
||||
}
|
||||
}
|
||||
if got := f.items(t, "ses_w"); len(got) != 1 {
|
||||
t.Fatalf("only the real image is recorded: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowImageRefusesPrivateAndLocalHosts(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_s")
|
||||
web := f.imageServer(t)
|
||||
f.service.fetch.allowed = publicAddress
|
||||
r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/a.png"}`)
|
||||
if !r.IsError || !strings.Contains(r.Text, "private or local address") {
|
||||
t.Fatalf("a loopback host must be refused: %v", r)
|
||||
}
|
||||
for _, refused := range []string{"127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "224.0.0.1", "::1", "fc00::1", "fe80::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "2001:db8::1", "198.18.0.1"} {
|
||||
if publicAddress(netip.MustParseAddr(refused)) {
|
||||
t.Errorf("%s must not be fetched from", refused)
|
||||
}
|
||||
}
|
||||
for _, allowed := range []string{"93.184.216.34", "1.1.1.1", "2606:4700:4700::1111"} {
|
||||
if !publicAddress(netip.MustParseAddr(allowed)) {
|
||||
t.Errorf("%s is a public address", allowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// schedule_followup puts a prompt into the calling chat's own durable queue
|
||||
// with a send_at, under the sender label chatFollowupClient. The operator sees
|
||||
// it as a scheduled message from the agent and can remove it like any queued
|
||||
// prompt; until it is due it does not hold the operator's prompts back
|
||||
// (chatQueueHead).
|
||||
|
||||
// chatFollowupClient is the sender label of an agent's follow-up prompt.
|
||||
const chatFollowupClient = "Agent follow-up"
|
||||
|
||||
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes *int64) chattools.Result {
|
||||
fail := func(format string, args ...any) chattools.Result {
|
||||
return chattools.Result{Text: "Nothing was scheduled: " + fmt.Sprintf(format, args...), IsError: true}
|
||||
}
|
||||
message = strings.TrimSpace(message)
|
||||
if message == "" {
|
||||
return fail("message is empty.")
|
||||
}
|
||||
if len(message) > chattools.MaxFollowupTextBytes {
|
||||
return fail("message is %s; the limit is 8 KiB.", humanBytes(int64(len(message))))
|
||||
}
|
||||
at = strings.TrimSpace(at)
|
||||
now := s.now()
|
||||
var sendAt time.Time
|
||||
switch {
|
||||
case at != "" && afterMinutes != nil:
|
||||
return fail("give either at or after_minutes, not both.")
|
||||
case afterMinutes != nil:
|
||||
if *afterMinutes < chattools.MinFollowupMinutes || *afterMinutes > chattools.MaxFollowupMinutes {
|
||||
return fail("after_minutes must be between %d and %d (7 days).", chattools.MinFollowupMinutes, chattools.MaxFollowupMinutes)
|
||||
}
|
||||
sendAt = now.Add(time.Duration(*afterMinutes) * time.Minute)
|
||||
case at != "":
|
||||
parsed, err := time.Parse(time.RFC3339, at)
|
||||
if err != nil {
|
||||
return fail("at must be an RFC 3339 time with a zone, such as %s.", now.Add(time.Hour).UTC().Format(time.RFC3339))
|
||||
}
|
||||
// A few seconds of slack for a time computed as "one minute from now".
|
||||
if parsed.Before(now.Add(time.Duration(chattools.MinFollowupMinutes)*time.Minute - 5*time.Second)) {
|
||||
return fail("at must be at least %d minute from now (it is %s).", chattools.MinFollowupMinutes, now.UTC().Format(time.RFC3339))
|
||||
}
|
||||
if parsed.After(now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute)) {
|
||||
return fail("at must be at most 7 days from now.")
|
||||
}
|
||||
sendAt = parsed
|
||||
default:
|
||||
return fail("give at (an RFC 3339 time) or after_minutes.")
|
||||
}
|
||||
if s.hub == nil || s.broker == nil {
|
||||
return fail("follow-ups are not available on this server.")
|
||||
}
|
||||
pending := 0
|
||||
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
|
||||
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
if pending >= chattools.MaxPendingFollowups {
|
||||
return fail("this chat already has %d follow-ups pending (the limit is %d); the operator can remove one, or wait for one to be delivered.", pending, chattools.MaxPendingFollowups)
|
||||
}
|
||||
var token [8]byte
|
||||
_, _ = rand.Read(token[:])
|
||||
operationID := chatFollowupPrefix + hex.EncodeToString(token[:])
|
||||
text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message)
|
||||
if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil {
|
||||
return fail("%v", err)
|
||||
}
|
||||
return chattools.Result{Text: fmt.Sprintf("Scheduled: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.",
|
||||
sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute))}
|
||||
}
|
||||
|
||||
// queueFollowup queues an agent's follow-up prompt for sendAt: durably, under
|
||||
// the follow-up sender label, shown to every attached client as scheduled.
|
||||
func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
|
||||
p := &chatQueuedPrompt{
|
||||
text: text,
|
||||
operationID: operationID,
|
||||
messageID: h.nextUserMessageID(),
|
||||
client: chatFollowupClient,
|
||||
noSteer: true,
|
||||
sendAt: sendAt,
|
||||
}
|
||||
h.rememberOp(sessionID, operationID)
|
||||
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
|
||||
if admission == chatAdmitRefused {
|
||||
h.forgetOp(sessionID, operationID)
|
||||
return err
|
||||
}
|
||||
h.broadcastUser(protocol.ChatEventFrame{
|
||||
SessionID: sessionID,
|
||||
MessageID: p.messageID,
|
||||
Kind: protocol.ChatEventUser,
|
||||
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
|
||||
Client: chatFollowupClient,
|
||||
OperationID: operationID,
|
||||
}, "")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// schedule_followup queues a durable, removable prompt under the agent's
|
||||
// follow-up label, and a pending follow-up never holds the operator's own
|
||||
// prompt back.
|
||||
func TestScheduleFollowupQueuesWithoutBlockingTheOperator(t *testing.T) {
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
broker := newChannelChat()
|
||||
server := startQueueServer(t, broker, store)
|
||||
token, err := store.ChatToolToken(context.Background(), chatToolSessionScope+"ses_1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(arguments string) map[string]any {
|
||||
body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"schedule_followup","arguments":` + arguments + `}}`
|
||||
request, _ := http.NewRequestWithContext(server.ctx, http.MethodPost, server.srv.URL+chatToolPath+token, strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var out struct {
|
||||
Result map[string]any `json:"result"`
|
||||
}
|
||||
_ = json.NewDecoder(response.Body).Decode(&out)
|
||||
return out.Result
|
||||
}
|
||||
if result := call(`{"message":"check the run","after_minutes":30}`); result["isError"] != false {
|
||||
t.Fatalf("schedule_followup = %v", result)
|
||||
}
|
||||
rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1")
|
||||
if err != nil || len(rows) != 1 || !strings.HasPrefix(rows[0].OperationID, chatFollowupPrefix) || rows[0].Client != chatFollowupClient || rows[0].SendAt.IsZero() || !strings.Contains(rows[0].Text, "check the run") {
|
||||
t.Fatalf("stored follow-up = %+v %v", rows, err)
|
||||
}
|
||||
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
if ack := sendPrompt(t, server.ctx, conn, "p1", "hello", "op-1"); ack.ChatQueued {
|
||||
t.Fatalf("the operator's prompt waited behind a pending follow-up: %+v", ack)
|
||||
}
|
||||
waitFor(t, "operator prompt delivered", func() bool { return broker.promptCount() == 1 })
|
||||
endTurn(broker)
|
||||
|
||||
call(`{"message":"two","after_minutes":60}`)
|
||||
call(`{"message":"three","after_minutes":90}`)
|
||||
if result := call(`{"message":"four","after_minutes":120}`); result["isError"] != true {
|
||||
t.Fatalf("a fourth pending follow-up must be refused: %v", result)
|
||||
}
|
||||
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: rows[0].OperationID}})
|
||||
if removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue); removed.ChatQueue == nil || removed.ChatQueue.Removed != rows[0].OperationID || len(removed.ChatQueue.Prompts) != 2 {
|
||||
t.Fatalf("the operator removes a follow-up: %+v", removed.ChatQueue)
|
||||
}
|
||||
if n := broker.promptCount(); n != 1 {
|
||||
t.Fatalf("no follow-up is delivered before its time: %v", broker.promptTexts())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func shownID(t *testing.T, r chattools.Result) string {
|
||||
t.Helper()
|
||||
_, rest, ok := strings.Cut(r.Text, "Item id: ")
|
||||
if r.IsError || !ok {
|
||||
t.Fatalf("the result names the item id: %v", r)
|
||||
}
|
||||
return strings.Fields(rest)[0]
|
||||
}
|
||||
|
||||
func TestUnknownOrMisnamedArgumentsAreRefused(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_v")
|
||||
for _, tc := range []struct{ tool, args, want string }{
|
||||
{"show_file", `{"file":"a.txt"}`, `unknown argument "file"; show_file takes path (required), replace, title`},
|
||||
{"show_html", `{"html":"<p>","heigth_hint":200}`, `unknown argument "heigth_hint"`},
|
||||
{"show_image", `{"path":"a.png"}`, "show_image takes url_or_path (required)"},
|
||||
{"show_run", `{"run_id":"7"}`, "run_id must be an integer"},
|
||||
{"notify", `{"title":"t","body":"m"}`, `unknown argument "body"`},
|
||||
} {
|
||||
r := f.call(token, tc.tool, tc.args)
|
||||
if !r.IsError || !strings.Contains(r.Text, tc.want) {
|
||||
t.Errorf("%s %s: got %v, want %q", tc.tool, tc.args, r, tc.want)
|
||||
}
|
||||
}
|
||||
if len(f.items(t, "ses_v")) != 0 || len(f.notified) != 0 {
|
||||
t.Fatal("a refused call does nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceUpdatesAnItemInPlace(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_p")
|
||||
other := f.token(t, chatToolSessionScope+"ses_q")
|
||||
first := shownID(t, f.call(token, "show_html", `{"html":"<p>v1</p>","title":"Chart"}`))
|
||||
shownID(t, f.call(token, "show_html", `{"html":"<p>later</p>"}`))
|
||||
created := f.items(t, "ses_p")[0].CreatedAt
|
||||
f.service.now = func() time.Time { return time.UnixMilli(created + 5000) }
|
||||
|
||||
r := f.call(token, "show_html", `{"html":"<p>v2</p>","title":"Chart","replace":"`+first+`"}`)
|
||||
if r.IsError || !strings.Contains(r.Text, "Updated item "+first+" in place") {
|
||||
t.Fatalf("replace: %v", r)
|
||||
}
|
||||
items := f.items(t, "ses_p")
|
||||
if len(items) != 2 || items[0].ID != first || items[0].HTML != "<p>v2</p>" || items[0].CreatedAt != created || items[0].UpdatedAt != created+5000 {
|
||||
t.Fatalf("the replaced item keeps its id and place: %+v", items)
|
||||
}
|
||||
for _, tc := range []struct{ token, tool, args, want string }{
|
||||
{token, "show_diff", `{"replace":"` + first + `"}`, "is a html item; show_diff can only replace diff"},
|
||||
{token, "show_html", `{"html":"x","replace":"shown_nope"}`, "is not an item shown in this chat"},
|
||||
{other, "show_html", `{"html":"x","replace":"` + first + `"}`, "is not an item shown in this chat"},
|
||||
} {
|
||||
if r := f.call(tc.token, tc.tool, tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) {
|
||||
t.Errorf("%s: got %v, want %q", tc.args, r, tc.want)
|
||||
}
|
||||
}
|
||||
if len(f.items(t, "ses_q")) != 0 {
|
||||
t.Fatal("another chat's item cannot be replaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShownFilesAreSnapshotsOrTrackedForChanges(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolSessionScope+"ses_n")
|
||||
small := filepath.Join(f.home, "small.txt")
|
||||
large := filepath.Join(f.home, "large.log")
|
||||
gone := filepath.Join(f.home, "gone.log")
|
||||
write := func(path string, size int, fill byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(strings.Repeat(string(fill), size)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write(small, 10, 'a')
|
||||
write(large, chattools.MaxSnapshotBytes+1, 'b')
|
||||
write(gone, chattools.MaxSnapshotBytes+1, 'c')
|
||||
smallID := shownID(t, f.call(token, "show_file", `{"path":"`+small+`"}`))
|
||||
shownID(t, f.call(token, "show_file", `{"path":"`+large+`"}`))
|
||||
shownID(t, f.call(token, "show_file", `{"path":"`+gone+`"}`))
|
||||
items := f.items(t, "ses_n")
|
||||
if !items[0].Snapshot || items[1].Snapshot || items[1].SHA256 == "" || items[1].ModTime == 0 {
|
||||
t.Fatalf("small files are copied, large ones tracked: %+v", items)
|
||||
}
|
||||
|
||||
write(small, 12, 'z')
|
||||
later := time.Now().Add(time.Minute)
|
||||
write(large, chattools.MaxSnapshotBytes+1, 'B')
|
||||
if err := os.Chtimes(large, later, later); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(gone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frame := f.hub.shownFrame("ses_n")
|
||||
if frame == nil || len(frame.Items) != 3 {
|
||||
t.Fatalf("frame = %+v", frame)
|
||||
}
|
||||
if got := []string{frame.Items[0].State, frame.Items[1].State, frame.Items[2].State}; got[0] != "" || got[1] != protocol.ChatShownFileChanged || got[2] != protocol.ChatShownFileMissing {
|
||||
t.Fatalf("states = %q (the snapshot still shows what was shown)", got)
|
||||
}
|
||||
if data, _ := os.ReadFile(frame.Items[0].Path); string(data) != strings.Repeat("a", 10) {
|
||||
t.Fatalf("the snapshot keeps the shown version: %q", data)
|
||||
}
|
||||
|
||||
// Replacing a snapshot item copies the new version; the old copy is swept
|
||||
// once it is past the grace period.
|
||||
oldDir := filepath.Dir(items[0].Path)
|
||||
f.service.now = func() time.Time { return time.Now().Add(2 * shownSnapshotGrace) }
|
||||
if r := f.call(token, "show_file", `{"path":"`+small+`","replace":"`+smallID+`"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
replaced := f.items(t, "ses_n")[0]
|
||||
if data, _ := os.ReadFile(replaced.Path); replaced.ID != smallID || string(data) != strings.Repeat("z", 12) {
|
||||
t.Fatalf("replaced snapshot = %+v %q", replaced, data)
|
||||
}
|
||||
if _, err := os.Stat(oldDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("the replaced snapshot is swept: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeShownRuns map[int64]protocol.RunSummary
|
||||
|
||||
func (f fakeShownRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) {
|
||||
run, ok := f[id]
|
||||
return run, ok, nil
|
||||
}
|
||||
|
||||
func TestShowRunFollowsTheRun(t *testing.T) {
|
||||
previous := shownRunRefreshDelay
|
||||
shownRunRefreshDelay = 10 * time.Millisecond
|
||||
t.Cleanup(func() { shownRunRefreshDelay = previous })
|
||||
f := newChatToolFixture(t)
|
||||
runs := fakeShownRuns{7: {ID: 7, Name: "feature", Title: "Add the run card", Status: "running", CurrentStage: "implement", CreatedAt: "2026-12-01T10:00:00Z"}}
|
||||
f.service.runs = runs
|
||||
token := f.token(t, chatToolSessionScope+"ses_r")
|
||||
if r := f.call(token, "show_run", `{"run_id":99}`); !r.IsError || !strings.Contains(r.Text, "there is no run 99") {
|
||||
t.Fatalf("an unknown run is refused: %v", r)
|
||||
}
|
||||
r := f.call(token, "show_run", `{"run_id":7}`)
|
||||
if r.IsError || !strings.Contains(r.Text, "run 7 of feature, running at stage implement") {
|
||||
t.Fatalf("show_run: %v", r)
|
||||
}
|
||||
item := f.items(t, "ses_r")[0]
|
||||
if item.Kind != protocol.ChatShownRun || item.Run == nil || item.Run.Title != "Add the run card" || item.Run.StartedAt != time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC).UnixMilli() {
|
||||
t.Fatalf("run item = %+v", item)
|
||||
}
|
||||
|
||||
runs[7] = protocol.RunSummary{ID: 7, Name: "feature", Title: "Add the run card", Status: "succeeded", Outcome: "done", CreatedAt: "2026-12-01T10:00:00Z", FinishedAt: "2026-12-01T10:30:00Z"}
|
||||
f.service.observeRun(protocol.RunEventFrame{RunID: 7, Status: "succeeded"})
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
item = f.items(t, "ses_r")[0]
|
||||
if item.Run.Status == "succeeded" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the run item was not updated: %+v", item.Run)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if item.Run.FinishedAt == 0 || item.Run.Outcome != "done" {
|
||||
t.Fatalf("finished run = %+v", item.Run)
|
||||
}
|
||||
f.service.watch.mu.Lock()
|
||||
followed := len(f.service.watch.items[7])
|
||||
f.service.watch.mu.Unlock()
|
||||
if followed != 0 {
|
||||
t.Fatal("a finished run is no longer followed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleFollowupBounds(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
now := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC)
|
||||
f.service.now = func() time.Time { return now }
|
||||
token := f.token(t, chatToolSessionScope+"ses_b")
|
||||
for _, tc := range []struct{ args, want string }{
|
||||
{`{"message":"check","after_minutes":0}`, "after_minutes must be between 1 and 10080"},
|
||||
{`{"message":"check","after_minutes":10081}`, "after_minutes must be between 1 and 10080"},
|
||||
{`{"message":"check","at":"2026-12-02T12:00:30Z"}`, "at least 1 minute from now"},
|
||||
{`{"message":"check","at":"2026-12-09T12:01:00Z"}`, "at most 7 days"},
|
||||
{`{"message":"check","at":"tomorrow"}`, "RFC 3339"},
|
||||
{`{"message":"check","at":"2026-12-02T13:00:00Z","after_minutes":5}`, "not both"},
|
||||
{`{"message":"check"}`, "give at"},
|
||||
{`{"message":" ","after_minutes":5}`, "message is empty"},
|
||||
{`{"message":"check","after_minutes":5}`, "not available on this server"},
|
||||
} {
|
||||
if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) {
|
||||
t.Errorf("%s: got %v, want %q", tc.args, r, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFollowupsStepAsideUntilDue(t *testing.T) {
|
||||
now := time.Now()
|
||||
followup := &chatQueuedPrompt{operationID: chatFollowupPrefix + "a", sendAt: now.Add(time.Hour)}
|
||||
operator := &chatQueuedPrompt{operationID: "op-1"}
|
||||
scheduled := &chatQueuedPrompt{operationID: "op-2", sendAt: now.Add(time.Minute)}
|
||||
if head, wait := chatQueueHead([]*chatQueuedPrompt{followup, operator}, now); head != 1 || wait != time.Hour {
|
||||
t.Fatalf("a pending follow-up lets the operator's prompt through: %d %v", head, wait)
|
||||
}
|
||||
if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now); head != -1 {
|
||||
t.Fatal("a queue of pending follow-ups has nothing to deliver")
|
||||
}
|
||||
if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now.Add(2*time.Hour)); head != 0 {
|
||||
t.Fatal("a due follow-up is delivered")
|
||||
}
|
||||
if head, _ := chatQueueHead([]*chatQueuedPrompt{scheduled, operator}, now); head != 0 {
|
||||
t.Fatal("an operator's scheduled prompt still holds the queue (FIFO)")
|
||||
}
|
||||
}
|
||||
@@ -11,46 +11,48 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// run executes one tool for sessionID. A non-nil item is recorded and shown;
|
||||
// the result is the short text the model reads.
|
||||
func (s *chatToolService) run(ctx context.Context, sessionID, tool string, arguments json.RawMessage) (*protocol.ChatShownItem, chattools.Result) {
|
||||
// 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}
|
||||
}
|
||||
var in struct {
|
||||
Path string `json:"path"`
|
||||
URLOrPath string `json:"url_or_path"`
|
||||
Title string `json:"title"`
|
||||
Alt string `json:"alt"`
|
||||
HTML string `json:"html"`
|
||||
HeightHint int `json:"height_hint"`
|
||||
Message string `json:"message"`
|
||||
Priority string `json:"priority"`
|
||||
Base string `json:"base"`
|
||||
Committed bool `json:"committed_only"`
|
||||
}
|
||||
if err := json.Unmarshal(arguments, &in); err != nil {
|
||||
return fail("The arguments must be a JSON object matching the %s schema: %v", tool, err)
|
||||
}
|
||||
title := boundedLine(in.Title, 200)
|
||||
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 := file.item(protocol.ChatShownFile, title)
|
||||
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: %s (%s).", file.name, humanBytes(file.size))}
|
||||
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)
|
||||
alt := boundedLine(in.Alt, 500)
|
||||
if strings.Contains(source, "://") {
|
||||
address, err := shownImageURL(source)
|
||||
item, err := s.fetchShownImage(ctx, sessionID, id, source)
|
||||
if err != nil {
|
||||
return fail("Nothing was shown: %v", err)
|
||||
}
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownImage, Title: title, URL: address, Alt: alt}
|
||||
return &item, chattools.Result{Text: "Shown in the operator's Pipelines chat: the image at " + address + "."}
|
||||
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 {
|
||||
@@ -59,10 +61,18 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum
|
||||
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 := file.item(protocol.ChatShownImage, title)
|
||||
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).", file.name, humanBytes(file.size))}
|
||||
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.")
|
||||
}
|
||||
@@ -72,16 +82,62 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum
|
||||
if !utf8.ValidString(in.HTML) {
|
||||
return fail("Nothing was shown: html is not valid UTF-8.")
|
||||
}
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: title, 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).", humanBytes(int64(len(in.HTML))))}
|
||||
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:
|
||||
return s.runShowDiff(ctx, sessionID, showDiffRequest{Path: in.Path, Base: in.Base, CommittedOnly: in.Committed, Title: title})
|
||||
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:
|
||||
return s.runNotify(ctx, sessionID, title, in.Message, in.Priority)
|
||||
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 == "" {
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// show_run records a card that follows one run. Its body is the run's summary
|
||||
// when shown; the run event hub tells the service when a followed run changes
|
||||
// (observeRun), and the service rereads the run, stores the new body over the
|
||||
// item and pushes it to the chat. A subscribe reply rereads every followed
|
||||
// run too, so a card is current after a restart that lost the watches.
|
||||
|
||||
// shownRunRefreshDelay coalesces a run's bursts of events into one reread.
|
||||
var shownRunRefreshDelay = 400 * time.Millisecond
|
||||
|
||||
// runWatches maps a followed run to the items (id to session) showing it.
|
||||
type runWatches struct {
|
||||
mu sync.Mutex
|
||||
items map[int64]map[string]string
|
||||
timers map[int64]*time.Timer
|
||||
}
|
||||
|
||||
func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title string) (*protocol.ChatShownItem, chattools.Result) {
|
||||
fail := func(text string) (*protocol.ChatShownItem, chattools.Result) {
|
||||
return nil, chattools.Result{Text: "Nothing was shown: " + text, IsError: true}
|
||||
}
|
||||
if runID <= 0 {
|
||||
return fail("run_id must be a positive run number.")
|
||||
}
|
||||
if s.runs == nil {
|
||||
return fail("this server does not record runs.")
|
||||
}
|
||||
summary, found, err := s.runs.RunSummaryByID(ctx, runID)
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
if !found {
|
||||
return fail(fmt.Sprintf("there is no run %d.", runID))
|
||||
}
|
||||
body := shownRunBody(summary)
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body}
|
||||
text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status)
|
||||
if body.CurrentStage != "" && !shownRunTerminal(body.Status) {
|
||||
text += " at stage " + body.CurrentStage
|
||||
}
|
||||
return &item, chattools.Result{Text: text + "; the card follows the run live."}
|
||||
}
|
||||
|
||||
func shownRunBody(summary protocol.RunSummary) protocol.ChatShownRunBody {
|
||||
return protocol.ChatShownRunBody{
|
||||
ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome,
|
||||
CurrentStage: summary.CurrentStage, Workspace: summary.Workspace,
|
||||
StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func shownRunTime(value string) int64 {
|
||||
for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} {
|
||||
if parsed, err := time.Parse(layout, value); err == nil {
|
||||
return parsed.UnixMilli()
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func shownRunTerminal(status string) bool {
|
||||
switch status {
|
||||
case "succeeded", "failed", "canceled", "interrupted":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// watchRun follows runID for the item.
|
||||
func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) {
|
||||
w := &s.watch
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.items == nil {
|
||||
w.items = map[int64]map[string]string{}
|
||||
}
|
||||
if w.items[runID] == nil {
|
||||
w.items[runID] = map[string]string{}
|
||||
}
|
||||
w.items[runID][itemID] = sessionID
|
||||
}
|
||||
|
||||
// observeRun is the run event hub's observer: a followed run's change is
|
||||
// reread once its burst of events settles.
|
||||
func (s *chatToolService) observeRun(frame protocol.RunEventFrame) {
|
||||
w := &s.watch
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if len(w.items[frame.RunID]) == 0 {
|
||||
return
|
||||
}
|
||||
if w.timers == nil {
|
||||
w.timers = map[int64]*time.Timer{}
|
||||
}
|
||||
if w.timers[frame.RunID] != nil {
|
||||
return
|
||||
}
|
||||
runID := frame.RunID
|
||||
w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() {
|
||||
w.mu.Lock()
|
||||
delete(w.timers, runID)
|
||||
followers := make(map[string]string, len(w.items[runID]))
|
||||
for id, session := range w.items[runID] {
|
||||
followers[id] = session
|
||||
}
|
||||
w.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
for itemID, sessionID := range followers {
|
||||
if s.shown == nil {
|
||||
return
|
||||
}
|
||||
item, found, err := s.shown.ChatShownItem(ctx, sessionID, itemID)
|
||||
if err != nil || !found || item.Run == nil {
|
||||
s.unwatchRun(runID, itemID)
|
||||
continue
|
||||
}
|
||||
s.refreshRunItem(ctx, sessionID, item, true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *chatToolService) unwatchRun(runID int64, itemID string) {
|
||||
s.watch.mu.Lock()
|
||||
defer s.watch.mu.Unlock()
|
||||
delete(s.watch.items[runID], itemID)
|
||||
if len(s.watch.items[runID]) == 0 {
|
||||
delete(s.watch.items, runID)
|
||||
}
|
||||
}
|
||||
|
||||
// refreshRunItem rereads a run item's run; a changed body is stored and pushed
|
||||
// to the chat. A finished run is no longer followed.
|
||||
func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string, item protocol.ChatShownItem, push bool) protocol.ChatShownItem {
|
||||
if item.Run == nil || s.runs == nil {
|
||||
return item
|
||||
}
|
||||
summary, found, err := s.runs.RunSummaryByID(ctx, item.Run.ID)
|
||||
if err != nil || !found {
|
||||
return item
|
||||
}
|
||||
body := shownRunBody(summary)
|
||||
if shownRunTerminal(body.Status) {
|
||||
s.unwatchRun(body.ID, item.ID)
|
||||
} else {
|
||||
s.watchRun(body.ID, sessionID, item.ID)
|
||||
}
|
||||
if body == *item.Run {
|
||||
return item
|
||||
}
|
||||
item.Run = &body
|
||||
if s.shown != nil {
|
||||
if _, err := s.shown.ReplaceChatShownItem(ctx, sessionID, item); err != nil {
|
||||
log.Printf("chat tools session=%s: update run item %s: %v", sessionID, item.ID, err)
|
||||
return item
|
||||
}
|
||||
}
|
||||
if push && s.hub != nil {
|
||||
s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown,
|
||||
ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{item}}}, "")
|
||||
}
|
||||
return item
|
||||
}
|
||||
@@ -5,8 +5,11 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,6 +22,13 @@ import (
|
||||
type chatShownStore interface {
|
||||
AppendChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) error
|
||||
ChatShownItems(ctx context.Context, sessionID string) ([]protocol.ChatShownItem, error)
|
||||
ChatShownItem(ctx context.Context, sessionID, id string) (protocol.ChatShownItem, bool, error)
|
||||
ReplaceChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) (bool, error)
|
||||
}
|
||||
|
||||
// chatShownRunStore reads the runs show_run follows (pipeline.Store).
|
||||
type chatShownRunStore interface {
|
||||
RunSummaryByID(ctx context.Context, id int64) (protocol.RunSummary, bool, error)
|
||||
}
|
||||
|
||||
// chatToolCorrelationWait is how long a call on a shared (instance) endpoint
|
||||
@@ -37,11 +47,25 @@ type chatToolService struct {
|
||||
notify chatToolNotifier
|
||||
limiter *chatNotifyLimiter
|
||||
now func() time.Time
|
||||
// runs reads the runs show_run follows; broker delivers follow-ups.
|
||||
runs chatShownRunStore
|
||||
broker chatBroker
|
||||
// snapshotRoot is where shown files are copied; it must lie inside the
|
||||
// operator's home, where /files serves it.
|
||||
snapshotRoot func() (string, error)
|
||||
// fetch is how web images are downloaded (tests replace its guard).
|
||||
fetch shownImageFetcher
|
||||
watch runWatches
|
||||
}
|
||||
|
||||
func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService {
|
||||
return &chatToolService{tokens: tokens, shown: shown, hub: hub, registry: registry, home: OperatorHomeDirectory,
|
||||
notify: hub.publishToolNotification, limiter: newChatNotifyLimiter(5, time.Minute), now: time.Now}
|
||||
s := &chatToolService{tokens: tokens, shown: shown, hub: hub, registry: registry, home: OperatorHomeDirectory,
|
||||
notify: hub.publishToolNotification, limiter: newChatNotifyLimiter(5, time.Minute), now: time.Now,
|
||||
snapshotRoot: defaultSnapshotRoot, fetch: shownImageFetcher{allowed: publicAddress}}
|
||||
if hub != nil {
|
||||
hub.shownRefresh = s.refreshShown
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// registerChatTools serves the MCP endpoint on mux. The route exists only on
|
||||
@@ -67,27 +91,93 @@ func (s *chatToolService) Call(ctx context.Context, token, tool string, argument
|
||||
if refusal != "" {
|
||||
return chattools.Result{Text: refusal, IsError: true}
|
||||
}
|
||||
item, result := s.run(ctx, sessionID, tool, arguments)
|
||||
if err := chattools.ValidateArguments(tool, arguments); err != nil {
|
||||
return chattools.Result{Text: "Nothing was done: " + err.Error() + ".", IsError: true}
|
||||
}
|
||||
var common struct {
|
||||
Replace string `json:"replace"`
|
||||
}
|
||||
_ = json.Unmarshal(arguments, &common)
|
||||
id := newChatShownID()
|
||||
var previous *protocol.ChatShownItem
|
||||
if replace := strings.TrimSpace(common.Replace); replace != "" {
|
||||
target, err := s.replaceTarget(ctx, sessionID, tool, replace)
|
||||
if err != nil {
|
||||
return chattools.Result{Text: "Nothing was shown: " + err.Error(), IsError: true}
|
||||
}
|
||||
previous, id = &target, target.ID
|
||||
}
|
||||
item, result := s.run(ctx, sessionID, tool, id, arguments)
|
||||
if item == nil {
|
||||
return result
|
||||
}
|
||||
if item.ID == "" {
|
||||
item.ID = newChatShownID()
|
||||
item.ID = id
|
||||
}
|
||||
now := s.now().UnixMilli()
|
||||
item.CreatedAt = now
|
||||
if previous != nil {
|
||||
item.CreatedAt, item.UpdatedAt = previous.CreatedAt, now
|
||||
}
|
||||
item.CreatedAt = s.now().UnixMilli()
|
||||
if s.shown != nil {
|
||||
if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil {
|
||||
var err error
|
||||
if previous != nil {
|
||||
var found bool
|
||||
if found, err = s.shown.ReplaceChatShownItem(ctx, sessionID, *item); err == nil && !found {
|
||||
err = errors.New("the item to replace is no longer retained")
|
||||
}
|
||||
} else {
|
||||
err = s.shown.AppendChatShownItem(ctx, sessionID, *item)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("chat tools session=%s: record %s: %v", sessionID, tool, err)
|
||||
return chattools.Result{Text: "Pipelines could not record this item: " + err.Error(), IsError: true}
|
||||
}
|
||||
s.sweepSnapshots(ctx, sessionID)
|
||||
}
|
||||
if item.Run != nil {
|
||||
s.watchRun(item.Run.ID, sessionID, item.ID)
|
||||
}
|
||||
if s.hub != nil {
|
||||
s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown,
|
||||
ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{*item}}}, "")
|
||||
}
|
||||
if tool != chattools.ToolNotify {
|
||||
if previous != nil {
|
||||
result.Text += " Updated item " + item.ID + " in place."
|
||||
} else {
|
||||
result.Text += " Item id: " + item.ID + " (pass it as replace to update this card)."
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// replaceTarget is the item a replace id names: one this chat's model showed,
|
||||
// of a kind the tool can update.
|
||||
func (s *chatToolService) replaceTarget(ctx context.Context, sessionID, tool, id string) (protocol.ChatShownItem, error) {
|
||||
if s.shown == nil {
|
||||
return protocol.ChatShownItem{}, errors.New("items cannot be replaced on this server")
|
||||
}
|
||||
item, found, err := s.shown.ChatShownItem(ctx, sessionID, id)
|
||||
if err != nil {
|
||||
return protocol.ChatShownItem{}, err
|
||||
}
|
||||
if !found {
|
||||
return protocol.ChatShownItem{}, fmt.Errorf("replace %q is not an item shown in this chat (use the id from an earlier show_* result here)", id)
|
||||
}
|
||||
kinds := map[string][]string{
|
||||
chattools.ToolShowFile: {protocol.ChatShownFile, protocol.ChatShownImage},
|
||||
chattools.ToolShowImage: {protocol.ChatShownFile, protocol.ChatShownImage},
|
||||
chattools.ToolShowHTML: {protocol.ChatShownHTML},
|
||||
chattools.ToolShowDiff: {protocol.ChatShownDiff},
|
||||
chattools.ToolShowRun: {protocol.ChatShownRun},
|
||||
}[tool]
|
||||
if !slices.Contains(kinds, item.Kind) {
|
||||
return protocol.ChatShownItem{}, fmt.Errorf("replace %q is a %s item; %s can only replace %s", id, item.Kind, tool, strings.Join(kinds, " or "))
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
// session resolves the chat a call belongs to. A session token names it; a
|
||||
// shared harness instance token is attributed to the one chat whose stream
|
||||
// shows this exact call running, and refused when none or several do.
|
||||
@@ -188,5 +278,8 @@ func (h *chatHub) shownFrame(sessionID string) *protocol.ChatShownFrame {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
if h.shownRefresh != nil {
|
||||
items = h.shownRefresh(ctx, sessionID, items)
|
||||
}
|
||||
return &protocol.ChatShownFrame{SessionID: sessionID, Items: items}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/paths"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// A shown file up to chattools.MaxSnapshotBytes is copied into the chat's
|
||||
// snapshot directory (<root>/<session>/<item id>-<nonce>/<name>) when it is
|
||||
// shown, so the card keeps showing that version however the file changes
|
||||
// later. The copy lives inside the operator's home, so the /files endpoint
|
||||
// serves it like any other file. A larger file stays linked: the item records
|
||||
// its size, modification time and hash, and the subscribe reply says when it
|
||||
// changed or no longer exists.
|
||||
|
||||
// shownHashLimit bounds the live files whose content hash is recorded and
|
||||
// rechecked; a larger one is compared by size and modification time alone.
|
||||
const shownHashLimit = 64 << 20
|
||||
|
||||
// shownSnapshotGrace keeps an unreferenced snapshot directory this long, so a
|
||||
// copy taken for an item that is being recorded is never swept.
|
||||
const shownSnapshotGrace = time.Minute
|
||||
|
||||
func defaultSnapshotRoot() (string, error) {
|
||||
data, err := paths.Data()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(data, "chat-shown"), nil
|
||||
}
|
||||
|
||||
// fileItem records file as a shown item: a snapshot copy when it is small
|
||||
// enough and the copy succeeds, else the live file with what identifies it.
|
||||
func (s *chatToolService) fileItem(sessionID, id string, file shownFile, kind, title string) protocol.ChatShownItem {
|
||||
item := protocol.ChatShownItem{Kind: kind, Title: title, Path: file.path, Name: file.name, Size: file.size, Mime: file.mime}
|
||||
if file.size <= chattools.MaxSnapshotBytes {
|
||||
source, err := os.Open(file.path)
|
||||
if err == nil {
|
||||
path, size, copyErr := s.writeSnapshot(sessionID, id, file.name, io.LimitReader(source, chattools.MaxSnapshotBytes+1))
|
||||
source.Close()
|
||||
if copyErr == nil {
|
||||
item.Path, item.Size, item.Snapshot, item.Source = path, size, true, file.path
|
||||
return item
|
||||
}
|
||||
err = copyErr
|
||||
}
|
||||
log.Printf("chat tools session=%s: snapshot %s: %v; showing the live file", sessionID, file.path, err)
|
||||
}
|
||||
if info, err := os.Stat(file.path); err == nil {
|
||||
item.ModTime = info.ModTime().UnixMilli()
|
||||
}
|
||||
if file.size <= shownHashLimit {
|
||||
item.SHA256, _ = fileSHA256(file.path)
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// writeSnapshot stores content as a new snapshot of item id and returns its
|
||||
// path and size. It refuses content over the snapshot bound and a root that
|
||||
// is not inside the operator's home.
|
||||
func (s *chatToolService) writeSnapshot(sessionID, id, name string, content io.Reader) (string, int64, error) {
|
||||
if sessionID == "" || filepath.Base(sessionID) != sessionID || filepath.Base(id) != id || id == "" {
|
||||
return "", 0, errors.New("invalid snapshot owner")
|
||||
}
|
||||
if s.snapshotRoot == nil {
|
||||
return "", 0, errors.New("no snapshot directory")
|
||||
}
|
||||
root, err := s.snapshotRoot()
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
var nonce [4]byte
|
||||
_, _ = rand.Read(nonce[:])
|
||||
dir := filepath.Join(root, sessionID, id+"-"+hex.EncodeToString(nonce[:]))
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
if err := s.insideHome(dir); err != nil {
|
||||
_ = os.RemoveAll(dir)
|
||||
return "", 0, err
|
||||
}
|
||||
path := filepath.Join(dir, safeSnapshotName(name))
|
||||
out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
_ = os.RemoveAll(dir)
|
||||
return "", 0, err
|
||||
}
|
||||
size, err := io.Copy(out, content)
|
||||
if err == nil && size > chattools.MaxSnapshotBytes {
|
||||
err = fmt.Errorf("the file grew past %s while it was copied", humanBytes(chattools.MaxSnapshotBytes))
|
||||
}
|
||||
if closeErr := out.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.RemoveAll(dir)
|
||||
return "", 0, err
|
||||
}
|
||||
return path, size, nil
|
||||
}
|
||||
|
||||
// insideHome refuses a directory /files would not serve.
|
||||
func (s *chatToolService) insideHome(dir string) error {
|
||||
home, err := s.home()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
realHome, err := filepath.EvalSymlinks(filepath.Clean(home))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, _, err := resolveInsideHome(realHome, dir); err != nil {
|
||||
return errors.New("the snapshot directory " + dir + " is not inside the operator's home")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeSnapshotName(name string) string {
|
||||
name = strings.Map(func(r rune) rune {
|
||||
if r == '/' || r == '\\' || r < 0x20 || r == 0x7f {
|
||||
return '_'
|
||||
}
|
||||
return r
|
||||
}, strings.TrimSpace(name))
|
||||
if name == "" || name == "." || name == ".." {
|
||||
return "file"
|
||||
}
|
||||
return truncateUTF8(name, 200)
|
||||
}
|
||||
|
||||
func fileSHA256(path string) (string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
digest := sha256.New()
|
||||
if _, err := io.Copy(digest, io.LimitReader(file, shownHashLimit+1)); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(digest.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// sweepSnapshots removes a chat's snapshot directories that no retained item
|
||||
// references any more (pruned by the item limit, or replaced).
|
||||
func (s *chatToolService) sweepSnapshots(ctx context.Context, sessionID string) {
|
||||
if s.snapshotRoot == nil || s.shown == nil || filepath.Base(sessionID) != sessionID {
|
||||
return
|
||||
}
|
||||
root, err := s.snapshotRoot()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dir := filepath.Join(root, sessionID)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
items, err := s.shown.ChatShownItems(ctx, sessionID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
kept := map[string]bool{}
|
||||
for _, item := range items {
|
||||
if item.Snapshot && item.Path != "" {
|
||||
kept[filepath.Dir(item.Path)] = true
|
||||
}
|
||||
}
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(dir, entry.Name())
|
||||
info, err := entry.Info()
|
||||
if err != nil || kept[path] || s.now().Sub(info.ModTime()) < shownSnapshotGrace {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Printf("chat tools session=%s: remove snapshot %s: %v", sessionID, path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// shownFileState says whether a file item's file still shows what was shown:
|
||||
// missing when it (or its snapshot) is gone, changed when the live file's
|
||||
// size, or modification time and content, differ.
|
||||
func shownFileState(item protocol.ChatShownItem) string {
|
||||
if item.Path == "" || (item.Kind != protocol.ChatShownFile && item.Kind != protocol.ChatShownImage) {
|
||||
return ""
|
||||
}
|
||||
info, err := os.Stat(item.Path)
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return protocol.ChatShownFileMissing
|
||||
}
|
||||
if item.Snapshot {
|
||||
return ""
|
||||
}
|
||||
if info.Size() != item.Size {
|
||||
return protocol.ChatShownFileChanged
|
||||
}
|
||||
if item.ModTime == 0 || info.ModTime().UnixMilli() == item.ModTime {
|
||||
return ""
|
||||
}
|
||||
if item.SHA256 != "" && info.Size() <= shownHashLimit {
|
||||
if digest, err := fileSHA256(item.Path); err == nil && digest == item.SHA256 {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return protocol.ChatShownFileChanged
|
||||
}
|
||||
|
||||
// refreshShown brings a chat's listed items up to date for its subscribe
|
||||
// reply: each file's state, and each followed run's latest summary.
|
||||
func (s *chatToolService) refreshShown(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem {
|
||||
out := make([]protocol.ChatShownItem, len(items))
|
||||
for i, item := range items {
|
||||
item.State = shownFileState(item)
|
||||
if item.Run != nil {
|
||||
item = s.refreshRunItem(ctx, sessionID, item, false)
|
||||
}
|
||||
out[i] = item
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -33,6 +33,9 @@ func newChatToolFixture(t *testing.T) *chatToolFixture {
|
||||
f.hub.shown = store
|
||||
f.service = newChatToolService(store, store, f.hub, store)
|
||||
f.service.home = func() (string, error) { return f.home, nil }
|
||||
f.service.snapshotRoot = func() (string, error) {
|
||||
return filepath.Join(f.home, ".local", "share", "pipelines", "chat-shown"), nil
|
||||
}
|
||||
f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery {
|
||||
f.notified = append(f.notified, sessionID+": "+notice.Title)
|
||||
return chatToolDelivery{App: true, Phone: true}
|
||||
@@ -135,9 +138,12 @@ func TestShowFileStaysInsideHome(t *testing.T) {
|
||||
}
|
||||
realHome, _ := filepath.EvalSymlinks(f.home)
|
||||
got := f.items(t, "ses_f")
|
||||
if len(got) != 1 || got[0].Path != filepath.Join(realHome, "work", "report.md") || got[0].Name != "report.md" || got[0].Size != 9 || !strings.HasPrefix(got[0].Mime, "text/") {
|
||||
if len(got) != 1 || got[0].Source != filepath.Join(realHome, "work", "report.md") || !got[0].Snapshot || got[0].Name != "report.md" || got[0].Size != 9 || !strings.HasPrefix(got[0].Mime, "text/") {
|
||||
t.Fatalf("item = %+v", got)
|
||||
}
|
||||
if copied, err := os.ReadFile(got[0].Path); err != nil || string(copied) != "# Report\n" || !strings.HasPrefix(got[0].Path, f.home) {
|
||||
t.Fatalf("the snapshot %s inside home holds the shown content: %q %v", got[0].Path, copied, err)
|
||||
}
|
||||
if r := f.call(token, "show_file", `{"path":"report.md"}`); r.IsError {
|
||||
t.Fatalf("a relative path resolves against the chat's directory: %v", r)
|
||||
}
|
||||
@@ -167,7 +173,8 @@ func TestShowImageAcceptsHomeImagesAndHTTPSOnly(t *testing.T) {
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"`+image+`","alt":"A plot"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"https://example.com/a.png","title":"Remote"}`); r.IsError {
|
||||
web := f.imageServer(t)
|
||||
if r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/a.png","title":"Remote"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
for _, refused := range []string{"http://example.com/a.png", "https://user:pw@example.com/a.png", "javascript:alert(1)", "file:///etc/passwd", filepath.Join(f.home, "notes.txt")} {
|
||||
@@ -176,9 +183,12 @@ func TestShowImageAcceptsHomeImagesAndHTTPSOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
got := f.items(t, "ses_i")
|
||||
if len(got) != 2 || got[0].Kind != protocol.ChatShownImage || got[0].Mime != "image/png" || got[0].Alt != "A plot" || got[1].URL != "https://example.com/a.png" || got[1].Path != "" {
|
||||
if len(got) != 2 || got[0].Kind != protocol.ChatShownImage || got[0].Mime != "image/png" || got[0].Alt != "A plot" || got[1].URL != web.URL+"/a.png" || !got[1].Snapshot || got[1].Name != "a.png" || got[1].Mime != "image/png" {
|
||||
t.Fatalf("items = %+v", got)
|
||||
}
|
||||
if data, err := os.ReadFile(got[1].Path); err != nil || string(data) != string(testPNG) {
|
||||
t.Fatalf("the fetched image is kept as a snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowHTMLSizeLimitAndRetention(t *testing.T) {
|
||||
|
||||
@@ -40,6 +40,19 @@ type runEventHub struct {
|
||||
runs map[int64]*runCoalescer
|
||||
now func() time.Time
|
||||
interval time.Duration
|
||||
// observer sees every emitted delta, subscribed or not (the chat tools'
|
||||
// run cards follow runs through it). It must not block.
|
||||
observer func(protocol.RunEventFrame)
|
||||
}
|
||||
|
||||
// observe installs the delta observer.
|
||||
func (h *runEventHub) observe(observer func(protocol.RunEventFrame)) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.observer = observer
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// runCoalescer merges a run's rapid field updates into the latest pending delta
|
||||
@@ -180,6 +193,11 @@ func (h *runEventHub) emit(frame protocol.RunEventFrame, terminal bool) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
if observer := h.observer; observer != nil {
|
||||
h.mu.Unlock()
|
||||
observer(frame)
|
||||
h.mu.Lock()
|
||||
}
|
||||
if !h.anySubscriberLocked(frame.Workspace) {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
|
||||
@@ -187,7 +187,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
if len(stores) > 0 {
|
||||
// The Pipelines chat tools' MCP endpoint, for harnesses on this machine.
|
||||
hub.shown = stores[0]
|
||||
registerChatTools(mux, newChatToolService(stores[0], stores[0], hub, registry), build.Version)
|
||||
tools := newChatToolService(stores[0], stores[0], hub, registry)
|
||||
tools.runs = stores[0]
|
||||
tools.broker = options.Chat
|
||||
events.observe(tools.observeRun)
|
||||
registerChatTools(mux, tools, build.Version)
|
||||
}
|
||||
mux.HandleFunc("GET /discovery", serveServerDiscovery)
|
||||
mux.HandleFunc("GET /files", serveHomeFile)
|
||||
|
||||
Reference in New Issue
Block a user