Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

8.6 KB
Raw Blame
// Package handoff finds agent sessions on this machine so they can be picked up again, in the same
// runtime or a different one.
//
// A handoff reads the runtime's own session store, never Beacon's runtime log alone: the store is
// what the runtime itself resumes from, and it keeps content that the runtime log truncates. Every
// read is local and read-only.
package handoff

import (
	"errors"
	"fmt"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

// Session is one resumable agent session as its runtime recorded it.
type Session struct {
	Harness    string `json:"harness"`
	ID         string `json:"id"`
	Title      string `json:"title,omitempty"`
	Directory  string `json:"directory,omitempty"`
	Branch     string `json:"branch,omitempty"`
	SourcePath string `json:"source_path,omitempty"`
	// Store names which of a runtime's stores holds the session when it has more than one, such as
	// Cline's CLI sessions and its older task history.
	Store string `json:"store,omitempty"`
	// Key is the name the runtime's CLI reopens the session by when that is not its id: an OpenClaw
	// Gateway session key. Empty when the store does not say.
	Key       string    `json:"key,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
	// Subagent marks a child session a runtime spawned for delegated work. Those are listed only on
	// request, because resuming one resumes a fragment of the parent's task.
	Subagent bool   `json:"subagent,omitempty"`
	ParentID string `json:"parent_id,omitempty"`
}

// Source lists the sessions one runtime has stored locally.
type Source interface {
	Harness() string
	List() ([]Session, error)
}

// Filter narrows a session listing. The zero value lists every top-level session.
type Filter struct {
	Harness          string
	Directory        string
	IncludeSubagents bool
	Limit            int
}

// SourceError reports a runtime whose store could not be read. The other runtimes still list.
type SourceError struct {
	Harness string
	Err     error
}

func (e *SourceError) Error() string { return fmt.Sprintf("%s: %v", e.Harness, e.Err) }
func (e *SourceError) Unwrap() error { return e.Err }

// List returns the sessions every source has stored, newest first. A source that fails is reported
// in the returned error while the sessions from the others are still returned.
func List(sources []Source, filter Filter) ([]Session, error) {
	sessions, unreadable := listSessions(sources, filter)
	errs := make([]error, 0, len(unreadable))
	for _, err := range unreadable {
		errs = append(errs, err)
	}
	return sessions, errors.Join(errs...)
}

func listSessions(sources []Source, filter Filter) ([]Session, []*SourceError) {
	var sessions []Session
	var errs []*SourceError
	within := directoryMatcher(filter.Directory)
	for _, source := range sources {
		if filter.Harness != "" && source.Harness() != filter.Harness {
			continue
		}
		found, err := source.List()
		if err != nil {
			errs = append(errs, &SourceError{Harness: source.Harness(), Err: err})
		}
		for _, session := range found {
			if session.ID == "" {
				continue
			}
			if session.Subagent && !filter.IncludeSubagents {
				continue
			}
			if filter.Directory != "" && !within(session.Directory) {
				continue
			}
			sessions = append(sessions, session)
		}
	}
	sort.SliceStable(sessions, func(i, j int) bool {
		if !sessions[i].UpdatedAt.Equal(sessions[j].UpdatedAt) {
			return sessions[i].UpdatedAt.After(sessions[j].UpdatedAt)
		}
		if sessions[i].Harness != sessions[j].Harness {
			return sessions[i].Harness < sessions[j].Harness
		}
		return sessions[i].ID < sessions[j].ID
	})
	if filter.Limit > 0 && len(sessions) > filter.Limit {
		sessions = sessions[:filter.Limit]
	}
	return sessions, errs
}

// MinPrefixLength is the shortest session id prefix Find accepts, so a stray short argument cannot
// silently pick one of many sessions.
const MinPrefixLength = 6

// ErrNotFound reports that no stored session has the requested id.
var ErrNotFound = errors.New("session not found")

// NotFoundError is the ErrNotFound Find returns. Unreadable names the stores that could not be
// searched, so a caller does not mistake "this store could not be read" for "this store does not
// have the session".
type NotFoundError struct {
	ID         string
	Unreadable []*SourceError
}

func (e *NotFoundError) Error() string {
	if len(e.Unreadable) == 0 {
		return fmt.Sprintf("%v: %s", ErrNotFound, e.ID)
	}
	parts := make([]string, 0, len(e.Unreadable))
	for _, err := range e.Unreadable {
		parts = append(parts, err.Error())
	}
	return fmt.Sprintf("%v: %s (some session stores could not be read: %s)", ErrNotFound, e.ID, strings.Join(parts, "; "))
}

func (e *NotFoundError) Is(target error) bool { return target == ErrNotFound }

// UnreadableStore returns the error for harness's store when it could not be read.
func (e *NotFoundError) UnreadableStore(harness string) *SourceError {
	for _, err := range e.Unreadable {
		if err.Harness == harness {
			return err
		}
	}
	return nil
}

// AmbiguousError reports an id or prefix that names more than one stored session.
type AmbiguousError struct {
	ID         string
	Candidates []Session
}

func (e *AmbiguousError) Error() string {
	names := make([]string, 0, len(e.Candidates))
	for _, candidate := range e.Candidates {
		names = append(names, candidate.Harness+" "+candidate.ID)
	}
	return fmt.Sprintf("session %q matches %d sessions (%s); pass the full id or --harness", e.ID, len(e.Candidates), strings.Join(names, ", "))
}

// Find returns the one session whose id is id, or, failing an exact match, the one session whose id
// starts with id. Subagent sessions are searched too, since naming one explicitly is deliberate.
func Find(sources []Source, harness, id string) (Session, error) {
	id = strings.TrimSpace(id)
	if id == "" {
		return Session{}, errors.New("session id is required")
	}
	sessions, unreadable := listSessions(sources, Filter{Harness: harness, IncludeSubagents: true})
	var exact, prefixed []Session
	for _, session := range sessions {
		switch {
		case session.ID == id:
			exact = append(exact, session)
		case len(id) >= MinPrefixLength && strings.HasPrefix(session.ID, id):
			prefixed = append(prefixed, session)
		}
	}
	matches := exact
	if len(matches) == 0 {
		matches = prefixed
	}
	switch len(matches) {
	case 1:
		return matches[0], nil
	case 0:
		return Session{}, &NotFoundError{ID: id, Unreadable: unreadable}
	default:
		return Session{}, &AmbiguousError{ID: id, Candidates: matches}
	}
}

// directoryMatcher returns a test for whether a session directory is root or below it. A runtime
// records the directory it resolved, and a shell reports the one the user typed: on macOS /var and
// /tmp are symlinks into /private, Windows has short 8.3 names, and home directories are often
// symlinked. When the paths do not match as written, both are compared with symlinks resolved.
func directoryMatcher(root string) func(dir string) bool {
	if root == "" {
		return func(string) bool { return true }
	}
	resolvedRoot := resolveExisting(root)
	return func(dir string) bool {
		if dir == "" {
			return false
		}
		if withinDirectory(dir, root) {
			return true
		}
		if resolvedRoot == "" {
			return false
		}
		if withinDirectory(dir, resolvedRoot) {
			return true
		}
		resolved := resolveExisting(dir)
		return resolved != "" && withinDirectory(resolved, resolvedRoot)
	}
}

// DirectoryWithin reports whether dir is root or below it, compared the way session listings
// compare directories (directoryMatcher): as written, then with symlinks resolved.
func DirectoryWithin(dir, root string) bool {
	return root != "" && directoryMatcher(root)(dir)
}

// SameDirectory reports whether a and b name the same directory, compared as DirectoryWithin
// compares them.
func SameDirectory(a, b string) bool {
	return DirectoryWithin(a, b) && DirectoryWithin(b, a)
}

// resolveExisting resolves the symlinks in path. A path that no longer exists (a deleted project
// directory) resolves through its nearest existing ancestor, with the rest rejoined as written.
func resolveExisting(path string) string {
	path = filepath.Clean(path)
	var rest []string
	for {
		if resolved, err := filepath.EvalSymlinks(path); err == nil {
			return filepath.Join(append([]string{resolved}, rest...)...)
		}
		parent := filepath.Dir(path)
		if parent == path {
			return ""
		}
		rest = append([]string{filepath.Base(path)}, rest...)
		path = parent
	}
}

// withinDirectory reports whether dir is root or below it, comparing the paths as written.
func withinDirectory(dir, root string) bool {
	if dir == "" {
		return false
	}
	dir = filepath.Clean(dir)
	root = filepath.Clean(root)
	if dir == root {
		return true
	}
	rel, err := filepath.Rel(root, dir)
	return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}