d7a3ab000f
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
443 lines
16 KiB
Go
443 lines
16 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"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). cancel_followup removes one the agent no longer needs.
|
|
//
|
|
// A run-triggered follow-up (run_id with on) is queued the same way with the
|
|
// longest allowed send_at as its deadline, and its operation id names the run
|
|
// and condition (chatRunFollowupPrefix). The run event hub tells the service
|
|
// when a run changes; once the run meets the condition the prompt is requeued
|
|
// as due now, with the run's state appended. The queue row is the durable
|
|
// record: after a restart resumeRunFollowups re-arms the watches from it.
|
|
|
|
// chatFollowupClient is the sender label of an agent's follow-up prompt.
|
|
const chatFollowupClient = "Agent follow-up"
|
|
|
|
// chatRunFollowupPrefix starts a run-triggered follow-up's operation id:
|
|
// followup-run-<run id>-<on>-<random>.
|
|
const chatRunFollowupPrefix = chatFollowupPrefix + "run-"
|
|
|
|
// runFollowupWatches maps a run to the follow-ups (operation id to session)
|
|
// waiting on it. mu also serialises every count-then-queue, cancel and trigger
|
|
// of the follow-ups, so concurrent calls cannot exceed the pending bound or
|
|
// deliver one twice.
|
|
type runFollowupWatches struct {
|
|
mu sync.Mutex
|
|
items map[int64]map[string]string
|
|
timers map[int64]*time.Timer
|
|
}
|
|
|
|
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes, runID *int64, on string) 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
|
|
var run *protocol.RunSummary
|
|
switch {
|
|
case runID != nil && (at != "" || afterMinutes != nil):
|
|
return fail("give run_id or a time (at or after_minutes), not both.")
|
|
case runID == nil && on != "":
|
|
return fail("on needs run_id.")
|
|
case runID != nil:
|
|
if on == "" {
|
|
on = chattools.FollowupOnFinished
|
|
}
|
|
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("%v", err)
|
|
}
|
|
if !found {
|
|
return fail("there is no run %d.", *runID)
|
|
}
|
|
if runFollowupDue(summary, on) {
|
|
return fail("run %d is already %s; act on it now (pipelines inspect %d).", *runID, runStateText(summary), *runID)
|
|
}
|
|
run = &summary
|
|
sendAt = now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute)
|
|
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), after_minutes, or run_id.")
|
|
}
|
|
if s.hub == nil || s.broker == nil {
|
|
return fail("follow-ups are not available on this server.")
|
|
}
|
|
w := &s.followups
|
|
w.mu.Lock()
|
|
pending := s.pendingFollowups(sessionID)
|
|
if len(pending) >= chattools.MaxPendingFollowups {
|
|
w.mu.Unlock()
|
|
return fail("this chat already has %d follow-ups pending (the limit is %d); cancel one with cancel_followup, or wait for one to be delivered.%s", len(pending), chattools.MaxPendingFollowups, followupListText(pending, now))
|
|
}
|
|
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 run != nil {
|
|
operationID = fmt.Sprintf("%s%d-%s-%s", chatRunFollowupPrefix, run.ID, on, hex.EncodeToString(token[:]))
|
|
text = fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s",
|
|
now.UTC().Format(time.RFC3339), run.ID, runFollowupCondition(on), sendAt.UTC().Format(time.RFC3339), message)
|
|
}
|
|
if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil {
|
|
w.mu.Unlock()
|
|
return fail("%v", err)
|
|
}
|
|
if run != nil {
|
|
s.watchRunFollowupLocked(run.ID, sessionID, operationID)
|
|
}
|
|
pending = s.pendingFollowups(sessionID)
|
|
w.mu.Unlock()
|
|
if run != nil {
|
|
// The run may have changed between the check above and the watch:
|
|
// look again once, as an event would.
|
|
s.scheduleRunFollowupCheck(run.ID)
|
|
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up when run %d %s (it is %s now), or at %s at the latest, when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s",
|
|
operationID, run.ID, runFollowupCondition(on), runStateText(*run), sendAt.UTC().Format(time.RFC3339), followupListText(pending, now))}
|
|
}
|
|
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: 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.%s",
|
|
operationID, sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute), followupListText(pending, now))}
|
|
}
|
|
|
|
// runCancelFollowup removes one of this chat's pending follow-ups.
|
|
func (s *chatToolService) runCancelFollowup(ctx context.Context, sessionID, id string) chattools.Result {
|
|
id = strings.TrimSpace(id)
|
|
if s.hub == nil {
|
|
return chattools.Result{Text: "Nothing was canceled: follow-ups are not available on this server.", IsError: true}
|
|
}
|
|
w := &s.followups
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
if !strings.HasPrefix(id, chatFollowupPrefix) {
|
|
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: %q is not a follow-up id (they start with %s).%s", id, chatFollowupPrefix, followupListText(s.pendingFollowups(sessionID), s.now())), IsError: true}
|
|
}
|
|
found, err := s.hub.unqueue(ctx, sessionID, id)
|
|
if err != nil {
|
|
return chattools.Result{Text: "Nothing was canceled: " + err.Error(), IsError: true}
|
|
}
|
|
if runID, _, ok := parseRunFollowupID(id); ok {
|
|
s.unwatchRunFollowupLocked(runID, id)
|
|
}
|
|
pending := s.pendingFollowups(sessionID)
|
|
if !found {
|
|
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: this chat has no pending follow-up %s (it may have been delivered or removed already).%s", id, followupListText(pending, s.now())), IsError: true}
|
|
}
|
|
return chattools.Result{Text: fmt.Sprintf("Canceled follow-up %s.%s", id, followupListText(pending, s.now()))}
|
|
}
|
|
|
|
// pendingFollowups are the chat's follow-ups still waiting in its queue.
|
|
func (s *chatToolService) pendingFollowups(sessionID string) []protocol.ChatQueuedPrompt {
|
|
var pending []protocol.ChatQueuedPrompt
|
|
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
|
|
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
|
|
pending = append(pending, prompt)
|
|
}
|
|
}
|
|
return pending
|
|
}
|
|
|
|
// followupListText lists pending follow-ups for a tool result, or says there
|
|
// are none.
|
|
func followupListText(pending []protocol.ChatQueuedPrompt, now time.Time) string {
|
|
if len(pending) == 0 {
|
|
return " No follow-ups are pending in this chat."
|
|
}
|
|
parts := make([]string, 0, len(pending))
|
|
for _, prompt := range pending {
|
|
when := "when the chat is free"
|
|
if runID, on, ok := parseRunFollowupID(prompt.OperationID); ok && prompt.SendAt > now.UnixMilli() {
|
|
when = fmt.Sprintf("when run %d %s", runID, runFollowupCondition(on))
|
|
} else if prompt.SendAt > now.UnixMilli() {
|
|
when = "at " + time.UnixMilli(prompt.SendAt).UTC().Format(time.RFC3339)
|
|
}
|
|
parts = append(parts, prompt.OperationID+" ("+when+")")
|
|
}
|
|
return fmt.Sprintf(" Pending follow-ups (%d of %d): %s.", len(pending), chattools.MaxPendingFollowups, strings.Join(parts, "; "))
|
|
}
|
|
|
|
// parseRunFollowupID reads the run and condition from a run-triggered
|
|
// follow-up's operation id.
|
|
func parseRunFollowupID(operationID string) (int64, string, bool) {
|
|
rest, ok := strings.CutPrefix(operationID, chatRunFollowupPrefix)
|
|
if !ok {
|
|
return 0, "", false
|
|
}
|
|
fields := strings.SplitN(rest, "-", 3)
|
|
if len(fields) != 3 {
|
|
return 0, "", false
|
|
}
|
|
runID, err := strconv.ParseInt(fields[0], 10, 64)
|
|
if err != nil || runID <= 0 || (fields[1] != chattools.FollowupOnFinished && fields[1] != chattools.FollowupOnAttention) {
|
|
return 0, "", false
|
|
}
|
|
return runID, fields[1], true
|
|
}
|
|
|
|
func runFollowupCondition(on string) string {
|
|
if on == chattools.FollowupOnAttention {
|
|
return "needs the operator or finishes"
|
|
}
|
|
return "finishes"
|
|
}
|
|
|
|
// runFollowupDue reports whether a run meets a follow-up's condition: it ended,
|
|
// or (for attention) it waits on a human decision.
|
|
func runFollowupDue(summary protocol.RunSummary, on string) bool {
|
|
if shownRunTerminal(summary.Status) {
|
|
return true
|
|
}
|
|
return on == chattools.FollowupOnAttention && summary.Status == protocol.RunStatusWaiting && summary.ExportPendingSequence == 0
|
|
}
|
|
|
|
// runStateText describes a run's state in one phrase.
|
|
func runStateText(summary protocol.RunSummary) string {
|
|
text := summary.Status
|
|
if outcome := strings.TrimSpace(summary.Outcome); outcome != "" {
|
|
text += " (" + outcome + ")"
|
|
}
|
|
if stage := strings.TrimSpace(summary.CurrentStage); stage != "" {
|
|
if summary.Status == protocol.RunStatusWaiting {
|
|
text += " waiting at stage " + stage
|
|
} else {
|
|
text += " at stage " + stage
|
|
}
|
|
}
|
|
return text
|
|
}
|
|
|
|
func (s *chatToolService) watchRunFollowupLocked(runID int64, sessionID, operationID string) {
|
|
w := &s.followups
|
|
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][operationID] = sessionID
|
|
}
|
|
|
|
func (s *chatToolService) unwatchRunFollowupLocked(runID int64, operationID string) {
|
|
w := &s.followups
|
|
delete(w.items[runID], operationID)
|
|
if len(w.items[runID]) == 0 {
|
|
delete(w.items, runID)
|
|
}
|
|
}
|
|
|
|
// observeRunFollowups is the run event hub's observer for run-triggered
|
|
// follow-ups: a watched run's change is checked once its burst settles.
|
|
func (s *chatToolService) observeRunFollowups(frame protocol.RunEventFrame) {
|
|
s.followups.mu.Lock()
|
|
watched := len(s.followups.items[frame.RunID]) > 0
|
|
s.followups.mu.Unlock()
|
|
if watched {
|
|
s.scheduleRunFollowupCheck(frame.RunID)
|
|
}
|
|
}
|
|
|
|
// scheduleRunFollowupCheck checks runID's follow-ups after the coalescing
|
|
// delay, at most once at a time.
|
|
func (s *chatToolService) scheduleRunFollowupCheck(runID int64) {
|
|
w := &s.followups
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
if w.timers == nil {
|
|
w.timers = map[int64]*time.Timer{}
|
|
}
|
|
if w.timers[runID] != nil {
|
|
return
|
|
}
|
|
w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() {
|
|
w.mu.Lock()
|
|
delete(w.timers, runID)
|
|
w.mu.Unlock()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
s.checkRunFollowups(ctx, runID)
|
|
})
|
|
}
|
|
|
|
// checkRunFollowups delivers runID's follow-ups whose condition the run now
|
|
// meets: each is requeued as due now with the run's state appended. One that
|
|
// is no longer queued (delivered at its deadline, or removed) is forgotten.
|
|
func (s *chatToolService) checkRunFollowups(ctx context.Context, runID int64) {
|
|
if s.runs == nil || s.hub == nil {
|
|
return
|
|
}
|
|
summary, found, err := s.runs.RunSummaryByID(ctx, runID)
|
|
if err != nil {
|
|
log.Printf("chat follow-ups run=%d: %v", runID, err)
|
|
return
|
|
}
|
|
w := &s.followups
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
for operationID, sessionID := range w.items[runID] {
|
|
_, on, ok := parseRunFollowupID(operationID)
|
|
if !ok {
|
|
s.unwatchRunFollowupLocked(runID, operationID)
|
|
continue
|
|
}
|
|
state := ""
|
|
switch {
|
|
case !found:
|
|
state = fmt.Sprintf("run %d no longer exists", runID)
|
|
case runFollowupDue(summary, on):
|
|
state = fmt.Sprintf("run %d is now %s", runID, runStateText(summary))
|
|
default:
|
|
continue
|
|
}
|
|
s.unwatchRunFollowupLocked(runID, operationID)
|
|
var text string
|
|
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
|
|
if prompt.OperationID == operationID {
|
|
text = prompt.Text
|
|
}
|
|
}
|
|
if text == "" {
|
|
continue
|
|
}
|
|
removed, err := s.hub.unqueue(ctx, sessionID, operationID)
|
|
if err != nil || !removed {
|
|
if err != nil {
|
|
log.Printf("chat follow-ups session=%s run=%d: %v", sessionID, runID, err)
|
|
}
|
|
continue
|
|
}
|
|
text += "\n\n[Pipelines: " + state + "; read it with pipelines inspect " + strconv.FormatInt(runID, 10) + ".]"
|
|
// The chat already shows this follow-up from when it was scheduled, so
|
|
// the requeue is not announced as a second user message.
|
|
if _, err := s.hub.admitFollowup(ctx, s.broker, sessionID, operationID, text, time.Time{}); err != nil {
|
|
log.Printf("chat follow-ups session=%s run=%d: requeue: %v", sessionID, runID, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// resumeRunFollowups re-arms the run-triggered follow-ups the restored queues
|
|
// hold, and delivers those whose run already meets the condition (it may have
|
|
// finished while the server was down).
|
|
func (s *chatToolService) resumeRunFollowups(ctx context.Context) {
|
|
if s.hub == nil {
|
|
return
|
|
}
|
|
s.hub.mu.Lock()
|
|
type waiting struct {
|
|
runID int64
|
|
sessionID, opID string
|
|
}
|
|
var found []waiting
|
|
for sessionID, room := range s.hub.rooms {
|
|
for _, p := range room.queue {
|
|
if runID, _, ok := parseRunFollowupID(p.operationID); ok && p.sendAt.After(s.hub.clock()) {
|
|
found = append(found, waiting{runID, sessionID, p.operationID})
|
|
}
|
|
}
|
|
}
|
|
s.hub.mu.Unlock()
|
|
runs := map[int64]bool{}
|
|
s.followups.mu.Lock()
|
|
for _, f := range found {
|
|
s.watchRunFollowupLocked(f.runID, f.sessionID, f.opID)
|
|
runs[f.runID] = true
|
|
}
|
|
s.followups.mu.Unlock()
|
|
for runID := range runs {
|
|
s.checkRunFollowups(ctx, runID)
|
|
}
|
|
}
|
|
|
|
// 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 {
|
|
// An agent's tool call can arrive while start-up recovery still restores
|
|
// the durable queue (see awaitRecovery). admitFollowup itself is not
|
|
// gated: recovery's own run-follow-up re-check (queueResumed) calls it
|
|
// before the gate opens.
|
|
if !h.awaitRecovery(ctx) {
|
|
return ctx.Err()
|
|
}
|
|
messageID, err := h.admitFollowup(ctx, broker, sessionID, operationID, text, sendAt)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
h.broadcastUser(protocol.ChatEventFrame{
|
|
SessionID: sessionID,
|
|
MessageID: messageID,
|
|
Kind: protocol.ChatEventUser,
|
|
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
|
|
Client: chatFollowupClient,
|
|
OperationID: operationID,
|
|
}, "")
|
|
return nil
|
|
}
|
|
|
|
// admitFollowup queues a follow-up prompt without announcing it and returns
|
|
// its message id.
|
|
func (h *chatHub) admitFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) (string, 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
|
|
}
|
|
return p.messageID, nil
|
|
}
|