persistent

package
v0.6.173 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package persistent runs a persistent agent: a built-in QuickAgent the runner keeps between the person's conversations. Each start-to-stop is a segment, an ordinary session of the engine with its own run id, receipts and envelope; what outlives a segment is the agent's state folder under the runner home and its two volumes, which carry no run label, so neither a segment's teardown nor the sweep of a dead run removes them.

One process owns a running agent, its supervisor: the desktop in-process, or the detached process `agentry agent start` launches. The supervisor holds the agent's owner lock and serves its owner socket, through which a chat in another process attaches, sends turns, reads the status and stops it. A second supervisor is refused, naming the holder.

Index

Constants

View Source
const (
	MaxNameBytes        = 64
	MaxPersonalityBytes = 32 << 10
)

The bounds of what a person writes for the agent.

View Source
const (
	EntryCommands = "commands"
	EntryEgress   = "egress"
	EntryBrowser  = "browser"
	EntryDevHost  = "devhost"
)

The Coding agent's entries.

View Source
const (
	ClientCLI     = "cli"
	ClientDesktop = "desktop"
)

The clients that own a running agent.

View Source
const (
	GrantedByBuiltin = "built-in"
	GrantedByYou     = "you"
)

Who granted an entry.

View Source
const (
	EntryShare = "share"
	EntryData  = "data"
)

The ids of the folder entries.

View Source
const (
	MaxSecrets     = 32
	MinSecretBytes = 8
	MaxSecretBytes = 16 << 10
)

The bounds of an agent's stored secrets. A value is at least MinSecretBytes so the engine's redactor, which leaves shorter values alone, masks it wherever it would appear.

View Source
const (
	SkillCheckedClamAV = "clamav"
	SkillUnchecked     = "unchecked"
)

How an added skill was checked when it was added.

View Source
const (
	RefusedBusy                     = protocol.RefusedBusy
	RefusedEnded   protocol.Refusal = "ended"
	RefusedChange  protocol.Refusal = "change"
	RefusedConsent protocol.Refusal = "consent"
	RefusedTask    protocol.Refusal = "task"
)

The refusal classes the owner socket adds to the session protocol's.

View Source
const (
	MaxTasks           = 25
	MinTaskInterval    = 15 * time.Minute
	MaxTaskFiresPerDay = 96
	MaxTaskNameBytes   = 80
	MaxInstruction     = 4096
)

The task limits: how many an agent keeps, how often one may fire, how many fires a day all of them may make, and the sizes of a name and an instruction.

View Source
const (
	TaskOn     = "on"
	TaskPaused = "paused"
)

Task states.

View Source
const (
	TaskOpPause  = "pause"
	TaskOpResume = "resume"
	TaskOpRemove = "remove"
)

The person's task operations.

View Source
const ConfigVersion = 6

ConfigVersion is the version of config.yaml this build writes. Version 2 added the share folder, the person's servers and packs, the switches and the consents, version 3 the Coding agent's dev server, version 4 its published ports, version 5 the skills the person added and version 6 the secrets they stored; a build that reads an older version alone refuses a newer one rather than drop what it does not know on its next save.

View Source
const EntryHeartbeat = "heartbeat"

EntryHeartbeat is the roster's switch for an agent's heartbeat.

View Source
const EntryMemory = "memory"

EntryMemory is the memory's roster entry: fixed on, for an agent that keeps one.

View Source
const KindSegmentStart session.Kind = "segment_start"

KindSegmentStart is the transcript's mark of a segment's start: Text says whether the conversation continued and, when it did not, why.

View Source
const MaxAddedSkills = 50

MaxAddedSkills is how many skills the person may add to an agent.

View Source
const MaxPorts = 8

MaxPorts bounds the Coding agent's published ports.

View Source
const StateRunning = "running"

StateRunning is a running agent's state.

View Source
const TaskMadeByAgent = "agent"

TaskMadeByAgent says the agent registered the task.

Variables

View Source
var ErrBusy = session.ErrBusy

ErrBusy refuses a turn sent while another is in flight.

View Source
var ErrDesktopOnly = errors.New("runs only in Agentry Desktop")

ErrDesktopOnly refuses an agent that runs only in Agentry Desktop.

View Source
var ErrNoTask = errors.New("no such task")

ErrNoTask refuses a change to a task the agent does not have.

View Source
var ErrNotRunning = errors.New("not running")

ErrNotRunning says no supervisor answers on the agent's socket.

Functions

func AddedSkillsPath

func AddedSkillsPath(home, name string) string

AddedSkillsPath is where the agent's added skills are kept, one folder each.

func AgreeToRoster

func AgreeToRoster(home string, a Agent, client string) error

AgreeToRoster records the person's agreement to everything the agent's roster has on, as a start asks for it: under the owner lock, so a running agent is refused.

func AppSocketPath

func AppSocketPath(home, name string) string

AppSocketPath is the socket an agent's supervisor answers its app link on, beside its owner socket.

func ApplyChange

func ApplyChange(home string, a Agent, c *Config, ch Change) (restart bool, err error)

ApplyChange applies ch to c for the agent a, under the runner home home. It answers whether the change alters what a segment is given, so a running agent's next turn starts a new segment, and refuses with a ConsentError a change that turns on what the person has not agreed to, unless ch.Consent says they have. The sentences it asks with say the malware check is off, as BuildRoster's do.

func Attach

func Attach(ctx context.Context, home, name string, history []session.Event) (session.Session, error)

Attach connects a chat to the running agent: a session.Session whose events are the segment's from now on, after history, and whose End leaves the agent running. A file is never added this way.

func CheckSecretName

func CheckSecretName(name string) error

CheckSecretName refuses a name that is not an environment variable's ([A-Z][A-Z0-9_]{0,63}), or one the runner and the programs it runs set themselves (spec.CheckStoredSecretName).

func CheckSecretValue

func CheckSecretValue(v string) error

CheckSecretValue refuses a value the segment cannot carry or mask: one shorter than MinSecretBytes or longer than MaxSecretBytes, one that is not UTF-8 text, and one holding a line break or another control character, which the gateway's secrets file cannot hold.

func CheckShareFolder

func CheckShareFolder(home, dir string) error

CheckShareFolder refuses a share folder that would hand the agent more than the person meant: a path that is not absolute and clean, one reached through a link, a filesystem root, the home folder or a folder holding it, a hidden folder of the home folder (where keys and settings live) or one beneath it, the runner's own folders or the configuration's, a folder that holds any of them, and the system's folders. A path holding a colon beyond a drive's is refused too: the gateway's bind lists are joined with one. A folder that does not exist yet passes, beneath a parent that does.

func DataVolume

func DataVolume(name string) string

DataVolume is the agent's data volume under the earlier name.

func DataVolumeIn

func DataVolumeIn(home, name string) string

DataVolumeIn is the agent's volume for its own files in the runner home home.

func Dir

func Dir(home, name string) string

Dir is the agent's state folder under the runner home.

func DiscardSkill

func DiscardSkill(home string, a Agent, name string) error

DiscardSkill removes an added skill's files once it is not on the agent's roster: after it is removed, or after the change that would have added it was refused.

func HistoryEvents

func HistoryEvents(entries []Entry) []session.Event

HistoryEvents is the transcript as session events a chat shows before the live ones: each turn, tool call and error, and a line where each segment began.

func HomeID

func HomeID(home string) string

HomeID identifies a runner home among the homes that use one container engine: a short hash of its absolute path, links followed. The volumes of the agent a home runs carry it in their names and a label, so two homes (two people on one computer, a scratch home beside the person's own) never share a conversation or a data volume. A home moved to another path is a different home to the engine: its agents start on volumes of their own.

func HomeMalwareCheck

func HomeMalwareCheck(home string) bool

HomeMalwareCheck is the malware-check setting of the policy in the runner home home, for a roster built while the agent is not running; off when that policy is missing or unreadable, as a new one has it.

func KnowledgeEntryID

func KnowledgeEntryID(pack string) string

KnowledgeEntryID is a pack's roster id.

func LogPath

func LogPath(home, name string) string

LogPath is where a detached supervisor writes what it prints.

func MemoryVolumeIn

func MemoryVolumeIn(home, name string) string

MemoryVolumeIn is the agent's memory volume in the runner home home.

func PortEntryID

func PortEntryID(name string) string

PortEntryID is the roster id of a published port.

func ReadSecrets

func ReadSecrets(keys Secrets, agent string, names []string) (map[string]string, error)

ReadSecrets reads the values of the named secrets of the agent from keys: every one must be there.

func RecordConsent

func RecordConsent(r Roster, c *Config)

RecordConsent records the person's agreement to every entry that is on.

func Reset

func Reset(ctx context.Context, home, name string, d dockerx.Client) error

Reset puts a stopped agent back to its defaults, as it was when first enabled: its volumes, its transcript, its lifetime usage, its share verdicts, its share mirror, its installed servers, its tasks, the skills the person added and the secrets they stored, from the keychain too, are removed; its configuration keeps only whether it is enabled, so its built-in skills are on again and its next start is a first segment that asks its consents again. The segments' receipts and the files in its share folder, which are the person's, are kept; so is a dev server's sign-in in the keychain, where a schedule of the same host may read it. It refuses a running agent, and holds the agent's lock while it works so none starts meanwhile. The containers of a segment whose supervisor died still hold the session volume, so they are swept first.

func SaveConfig

func SaveConfig(home, name string, c Config) error

SaveConfig writes the agent's config.yaml (0600), replacing it whole.

func SecretAccount

func SecretAccount(agent, name string) string

SecretAccount is the keychain account a stored secret's value is kept under, apart from every other agent's and from the person's other keys.

func SecretEntryID

func SecretEntryID(name string) string

SecretEntryID is a stored secret's roster id.

func ServerEntryID

func ServerEntryID(srv manifest.MCPServer) string

ServerEntryID is a server's roster id: its store id, which names its package or its address.

func ServerMaySeeShare

func ServerMaySeeShare(srv manifest.MCPServer) error

ServerMaySeeShare refuses a server the share is never given to: a remote server, which is another party's; a package server that reaches a host, which could send the person's files there; and one that signs in by OAuth, which a persistent agent cannot be given.

func ServerShareID

func ServerShareID(srv manifest.MCPServer) string

ServerShareID is the id of a server's switch that lets it see the agent's share folder: its roster id and ":share". It is a switch of the server's entry, not an entry of its own: it changes what the server's sentence says.

func SessionVolume

func SessionVolume(name string) string

SessionVolume and DataVolume are the legacy names of the agent's two volumes, by the agent alone: every runner home on one engine could use the same two. A home that has run the agent keeps its conversation by copying them into its own volumes at its next start, and leaves them be.

func SessionVolumeIn

func SessionVolumeIn(home, name string) string

SessionVolumeIn is the agent's volume for the harness's conversation store in the runner home home, and DataVolumeIn the agent's volume for its own files.

func ShareFolder

func ShareFolder(a Agent, c Config) (string, error)

ShareFolder is the agent's share folder: config.yaml's, else its default under ~/agentry.

func SharedVolumes

func SharedVolumes(ctx context.Context, d dockerx.Client, name string) []string

SharedVolumes are the volumes of the agent that exist under the legacy names (SessionVolume, DataVolume), which every runner home on the engine could use. A reset leaves them, as another home may still need them; nothing else removes them. A failed listing answers none.

func SkillEntryID

func SkillEntryID(name string) string

SkillEntryID is a skill's roster id.

func SocketPath

func SocketPath(home, name string) string

SocketPath is the agent's owner socket. It lives beside the runs' sockets under the runner home rather than in the state folder, so its path stays short of the kernel's limit for a socket's name.

Types

type AddedSkill

type AddedSkill struct {
	Name        string    `yaml:"name" json:"name"`
	Description string    `yaml:"description" json:"description"`
	Digest      string    `yaml:"digest" json:"digest"`
	Check       string    `yaml:"check" json:"check"`
	Added       time.Time `yaml:"added" json:"added"`
}

AddedSkill is a skill the person added: its name and description from its SKILL.md, the digest of its files as they were checked, how they were checked, and when.

func InstallSkill

func InstallSkill(ctx context.Context, home string, a Agent, src string, check SkillCheck) (AddedSkill, error)

InstallSkill takes the skill at src, a folder or a .zip on this computer, holds it to the skill bounds, runs check over its files and keeps it among the agent's added skills, not yet on its roster: the change that adds it (Change.AddSkill) does that, and asks the person first. A skill of a name the agent has already is refused.

type Agent

type Agent struct {
	// Name is the agent's name, its built-in's name: what the commands and
	// the state folder are keyed by.
	Name string
	// Title is how the agent is named to a person until they name it.
	Title string
	// DesktopOnly says the agent runs only in Agentry Desktop; the CLI
	// lists it and refuses to start, chat with or configure it.
	DesktopOnly bool
	// Builtin is the package it runs.
	Builtin localrun.Builtin
	// ShareName is the default share folder's name, under ~/agentry.
	ShareName string
}

Agent is one persistent agent this build knows.

func Agents

func Agents() []Agent

Agents are the persistent agents this build knows, in the order they are listed.

func Lookup

func Lookup(name string) (Agent, error)

Lookup is the agent named name.

func (Agent) DisplayName

func (a Agent) DisplayName(c Config) string

DisplayName is the name the agent goes by: the person's for it, else its title.

type AppLinkHandler

type AppLinkHandler func(ctx context.Context, req applink.Request) applink.Answer

AppLinkHandler answers an app link's tool call other than self_configure.

type Applied

type Applied struct {
	On []string `json:"on"`
}

Applied is what a segment was given: the ids of the roster's entries that were on.

func Apply

func Apply(ctx context.Context, home string, a Agent, c Config, r Roster, open Packs, ready HostReady, keys Secrets) (g localrun.Grants, applied Applied, done func(), err error)

Apply turns the roster into what a segment is given: the share folder when it is on, the packs that are on and the servers that are on and ready (a server the agent's store does not hold yet, one being installed and one whose install failed are left out: serverReady), and the Coding agent's grant, its dev server readied by ready, and the stored secrets that are on, their values read from keys. It is the one place a switch takes effect, so the tools server's spec, the gateway's allowlist, catalogue and secrets file, the bind lists and the driver's permit set, all compiled and rendered from what it returns, agree. applied names what the segment is given. done closes the packs it opened.

type Change

type Change struct {
	// Name and Personality are the person's for the agent; "" clears one.
	Name        *string `json:"name,omitempty"`
	Personality *string `json:"personality,omitempty"`
	// Share is the share folder, absolute; "" is the agent's default.
	Share *string `json:"share,omitempty"`
	// RunOnStart starts the agent when its client starts.
	RunOnStart *bool `json:"runOnStart,omitempty"`
	// AddServer adds an MCP server, on; RemoveServer removes one by its
	// roster id or its store id.
	AddServer    *manifest.MCPServer `json:"addServer,omitempty"`
	RemoveServer string              `json:"removeServer,omitempty"`
	// AddKnowledge adds a pack of the local store by name, on;
	// RemoveKnowledge removes one.
	AddKnowledge    string `json:"addKnowledge,omitempty"`
	RemoveKnowledge string `json:"removeKnowledge,omitempty"`
	// Switch turns a roster entry on or off.
	Switch *Switch `json:"switch,omitempty"`
	// DevHost saves the Coding agent's dev server, on; ClearDevHost removes
	// it. Its sign-in is saved in the keychain before, by the client that
	// asked the person for it.
	DevHost      *DevHost `json:"devHost,omitempty"`
	ClearDevHost bool     `json:"clearDevHost,omitempty"`
	// AddPort publishes one of the Coding agent's ports, on; RemovePort
	// takes one away by its name.
	AddPort    *Port  `json:"addPort,omitempty"`
	RemovePort string `json:"removePort,omitempty"`
	// AddSkill adds a skill InstallSkill kept, on; RemoveSkill takes away
	// one the person added, by its name. A built-in skill is switched, not
	// removed.
	AddSkill    *AddedSkill `json:"addSkill,omitempty"`
	RemoveSkill string      `json:"removeSkill,omitempty"`
	// SetSecret records a secret the person stored, on, its value already
	// kept in the keychain by the client that asked them for it, or one set
	// again; RemoveSecret takes one away, by its name. Neither carries a
	// value.
	SetSecret    *StoredSecret `json:"setSecret,omitempty"`
	RemoveSecret string        `json:"removeSecret,omitempty"`
	// Consent says the person consented to what this change turns on, as
	// the lines a ConsentError listed say it.
	Consent bool `json:"consent,omitempty"`
}

Change is one change to an agent's configuration; a field left unset is left as it is.

type Command

type Command struct {
	Attach *struct{}      `json:"attach,omitempty"`
	Send   *protocol.Send `json:"send,omitempty"`
	Status *struct{}      `json:"status,omitempty"`
	Roster *struct{}      `json:"roster,omitempty"`
	Change *Change        `json:"change,omitempty"`
	Stop   *struct{}      `json:"stop,omitempty"`
	Tasks  *struct{}      `json:"tasks,omitempty"`
	// TaskChange is a person's change to one of the agent's tasks.
	TaskChange *TaskOp `json:"task_change,omitempty"`
}

Command is one line a client sends.

type Config

type Config struct {
	Version int `yaml:"version" json:"version"`
	// Enabled says the agent exists for the person: it may be started, and
	// a client lists it as theirs. Disabling it keeps its volumes.
	Enabled bool `yaml:"enabled" json:"enabled"`
	// RunOnStart starts the agent when its client starts.
	RunOnStart bool `yaml:"runOnStart" json:"runOnStart"`
	// DisplayName and Personality are the person's for the agent.
	DisplayName string `yaml:"displayName,omitempty" json:"displayName,omitempty"`
	Personality string `yaml:"personality,omitempty" json:"personality,omitempty"`
	// Conversation is the harness's conversation the last segment was in.
	Conversation *Conversation `yaml:"conversation,omitempty" json:"conversation,omitempty"`
	// Segments counts the segments started.
	Segments int `yaml:"segments" json:"segments"`
	// Share is the share folder, absolute; empty is the agent's default,
	// ~/agentry/<ShareName>.
	Share string `yaml:"share,omitempty" json:"share,omitempty"`
	// Servers are the MCP servers the person added, in the manifest's own
	// shape; each is a roster entry.
	Servers []manifest.MCPServer `yaml:"servers,omitempty" json:"servers,omitempty"`
	// Knowledge names the knowledge packs the person added, from the local
	// store; each is a roster entry.
	Knowledge []string `yaml:"knowledge,omitempty" json:"knowledge,omitempty"`
	// Switches are the roster's switches the person set, by entry id; an
	// entry with none takes its default.
	Switches map[string]bool `yaml:"switches,omitempty" json:"switches,omitempty"`
	// Consented records, by entry id, the line the person consented to
	// when they turned the entry on: turning on an entry whose line differs
	// from it, or that has none, asks again.
	Consented map[string]string `yaml:"consented,omitempty" json:"consented,omitempty"`
	// PersonaGiven is the digest of the name and personality the agent was
	// last given, so a change reaches it at the next turn.
	PersonaGiven string `yaml:"personaGiven,omitempty" json:"personaGiven,omitempty"`
	// DevHost is the Coding agent's dev server, which the person saved; it
	// is a roster entry.
	DevHost *DevHost `yaml:"devHost,omitempty" json:"devHost,omitempty"`
	// Ports are the Coding agent's published ports, which the person
	// named; each is a roster entry.
	Ports []Port `yaml:"ports,omitempty" json:"ports,omitempty"`
	// ServerFailures are the servers the person added whose install failed,
	// by roster id: each stays failed, left out of every segment, until the
	// person switches it or removes it. A build that does not know the field
	// drops it on its next save, and the server is installed again at the
	// next start, so the field needs no version of its own.
	ServerFailures map[string]ServerFailure `yaml:"serverFailures,omitempty" json:"serverFailures,omitempty"`
	// Skills are the skills the person added, as they were checked; each is
	// a roster entry, its files in the agent's skills-added folder.
	Skills []AddedSkill `yaml:"skills,omitempty" json:"skills,omitempty"`
	// Secrets are the secrets the person stored for the agent, by name;
	// each is a roster entry, its value in the keychain (SecretAccount).
	Secrets []StoredSecret `yaml:"secrets,omitempty" json:"secrets,omitempty"`
}

Config is the agent's config.yaml: what the person chose for it, and the conversation its next segment continues.

func LoadConfig

func LoadConfig(home, name string) (Config, error)

LoadConfig reads the agent's config.yaml; an agent never configured has the zero Config at this version.

type ConsentError

type ConsentError struct {
	Agent   string
	Entries []RosterEntry
}

ConsentError refuses a change, or a start, that turns on entries the person has not consented to on this machine: Entries are their lines.

func (*ConsentError) Error

func (e *ConsentError) Error() string

type Conversation

type Conversation struct {
	Adapter string `yaml:"adapter" json:"adapter"`
	ID      string `yaml:"id" json:"id"`
}

Conversation names a harness's stored conversation: the adapter that stored it, since another harness cannot read it, and its id.

type Cron

type Cron struct {
	// contains filtered or unexported fields
}

Cron is a parsed five-field expression.

func ParseCron

func ParseCron(expr string) (Cron, error)

ParseCron reads a five-field expression.

func (Cron) CloserThan

func (c Cron) CloserThan(from time.Time, loc *time.Location, d time.Duration) (bool, error)

CloserThan says two of the expression's times in loc, over the year after from, are less than d apart: it fires more often than every d.

func (Cron) Count

func (c Cron) Count(from, to time.Time, loc *time.Location, limit int) int

Count is how many times the expression names in loc after from and up to to, counting at most limit+1.

func (Cron) Next

func (c Cron) Next(after time.Time, loc *time.Location) (time.Time, error)

Next is the first time after after, to the minute, that the expression names in loc; errNoNext when none comes within cronHorizon. A wall-clock minute a change to summer time skips does not come; one a change back to winter time repeats comes once, the first time.

type DevHost

type DevHost struct {
	// Host is user@host[:port].
	Host string `yaml:"host" json:"host"`
	// HostKey is the SHA256 fingerprint of the host key the person
	// trusted: a segment that finds another refuses.
	HostKey string `yaml:"hostKey" json:"hostKey"`
}

DevHost is the Coding agent's dev server, as config.yaml keeps it: where it is and as whom, and the host key the person trusted. Its sign-in is in the system keychain, saved when the person configured it, never here.

type Entry

type Entry struct {
	Segment int    `json:"segment"`
	Run     string `json:"run"`
	session.Event
	// Resumed is set on a segment_start entry.
	Resumed *bool `json:"resumed,omitempty"`
	// Task is, on a user turn the heartbeat sent, the task it was for.
	Task string `json:"task,omitempty"`
}

Entry is one line of the agent's transcript.ndjson: a session event of a segment, as the engine emitted it (redacted), without the harness's raw message.

func Transcript

func Transcript(home, name string, n int) ([]Entry, error)

Transcript is the last n lines of the agent's transcript (every line for n <= 0). A line that does not parse is skipped.

type EntryKind

type EntryKind string

EntryKind is what a roster entry grants.

const (
	KindTools EntryKind = "tools"
	KindHost  EntryKind = "host"
	KindPort  EntryKind = "port"
)

The kinds of the Coding agent's entries.

const (
	KindFiles     EntryKind = "files"
	KindKnowledge EntryKind = "knowledge"
	KindServer    EntryKind = "server"
)

The kinds of entry.

const KindMemory EntryKind = "memory"

KindMemory is the memory's roster entry kind.

const KindSecret EntryKind = "secret"

KindSecret is a stored secret's roster entry.

const KindSkill EntryKind = "skill"

KindSkill is a skill's roster entry.

const KindTasks EntryKind = "tasks"

KindTasks is the kind of the heartbeat's entry.

type EntryState

type EntryState string

EntryState is a roster entry's state.

const (
	StateOn  EntryState = "on"
	StateOff EntryState = "off"
	// StatePending: switched since the running segment started; the next
	// turn starts the segment that applies it.
	StatePending EntryState = "pending"
	// StateNeedsSignIn: a server that signs in by OAuth, which an agent
	// cannot be given in this version.
	StateNeedsSignIn EntryState = "needs-sign-in"
	// StateInstalling: a server that is on and that the agent's store does
	// not hold yet. It is installed in the background while the agent runs
	// without it; once installed it is pending, and the next turn's segment
	// has it.
	StateInstalling EntryState = "installing"
	// StateFailed: a server whose install failed (Reason says why). The
	// agent runs without it until the person switches it off and on.
	StateFailed EntryState = "failed"
)

The states.

type Exported

type Exported struct {
	Files   int   `json:"files"`
	Bytes   int64 `json:"bytes"`
	Skipped int   `json:"skipped,omitempty"`
}

Exported is what an export wrote: the files, their bytes, and the entries of the volume it left out because they were neither a file nor a folder.

func ExportMemory

func ExportMemory(ctx context.Context, d dockerx.Client, home string, a Agent, image, runtime string, lim policy.Limits, dir string) (Exported, error)

ExportMemory copies the agent's memory into dir, a new folder it makes beneath a folder that exists: its files and folders as the volume holds them at that moment, read by a one-shot of image (the runner image) under runtime and lim. A link or any other entry is left out, and nothing is written outside dir. A failed export removes dir.

type HeldError

type HeldError struct {
	Agent  string
	Holder *Holder // nil when the holder's record could not be read
}

HeldError is the refusal of a second owner.

func (*HeldError) Error

func (e *HeldError) Error() string

type Holder

type Holder struct {
	Client string    `json:"client"`
	PID    int       `json:"pid"`
	Since  time.Time `json:"since"`
}

Holder is who owns a running agent: written beside the lock once it is held, and read by a client that is refused it.

func Held

func Held(home, name string) (bool, *Holder)

Held reports whether some process holds the agent's owner lock, and who.

func ReadHolder

func ReadHolder(home, name string) (*Holder, error)

ReadHolder is the record of the agent's current owner, nil when there is none. A record left by an owner that died is stale; Held says whether the lock is actually held.

func (Holder) Where

func (h Holder) Where() string

Where names the holder's client to a person.

type HostReady

type HostReady func(ctx context.Context, d DevHost) (*targethost.Host, error)

HostReady readies the Coding agent's dev server for a segment: its address, its host key held to the pinned one, its sign-in from the keychain. No one is asked anything: a supervisor has no terminal.

func ReadyDevHost

func ReadyDevHost(home string, pol *policy.Policy) HostReady

ReadyDevHost is the HostReady of a supervisor under the runner home home and the policy pol: the policy's host lists, the runner's and the person's known_hosts files, the sign-in the person saved.

type InstallServer

type InstallServer func(ctx context.Context, srv manifest.MCPServer, storeDir string, logw io.Writer) error

InstallServer installs one package server into a persistent agent's store, storeDir, writing its progress to logw (localrun.InstallServer).

type KeychainSecrets

type KeychainSecrets struct{}

KeychainSecrets is the system keychain under Agentry's service. A start with a sealed credential (a headless start a client prepared) reads from it alone, as the model key is read.

func (KeychainSecrets) Delete

func (KeychainSecrets) Delete(account string) error

Delete implements Secrets. A missing entry is not an error.

func (KeychainSecrets) Get

func (KeychainSecrets) Get(account string) (string, error)

Get implements Secrets.

func (KeychainSecrets) Set

func (KeychainSecrets) Set(account, value string) error

Set implements Secrets.

type Options

type Options struct {
	Home  string
	Agent Agent
	// Client is who supervises: ClientCLI or ClientDesktop.
	Client     string
	Policy     *policy.Policy
	PolicySHA  string
	PolicyFile *policy.File
	// Build is the client's build identity.
	Build  string
	Docker dockerx.Client
	// Stderr gets the segment's progress (image builds, sweeps).
	Stderr io.Writer
	// OnStage, when set, is called as each segment's start reaches each of
	// its steps (Stage; Stage.Words is how a person is shown it): the
	// agent's first segment, and each a roster change or a restart starts.
	// A server installed in the background while the agent runs is
	// reported too, as its install begins, on that install's goroutine. It
	// is called on the reporting goroutine, so it returns quickly; nil does
	// nothing.
	OnStage func(Stage)
	// Packs opens the knowledge packs the roster has on, for each segment;
	// nil refuses a roster with one on.
	Packs Packs
	// DevHost readies the Coding agent's dev server for each segment; nil
	// readies it under Home and Policy (ReadyDevHost).
	DevHost HostReady
	// Secrets is where the stored secrets' values are read for each
	// segment; nil is the keychain (KeychainSecrets).
	Secrets Secrets
	// AppLink answers the agent's app link calls other than self_configure,
	// which the supervisor answers itself: the desktop's. Nil answers them
	// as Agentry Desktop's.
	AppLink AppLinkHandler
	// StartSegment starts a segment; nil starts it with localrun. Tests
	// put a session of their own here.
	StartSegment func(ctx context.Context, seg localrun.Segment) (engine.PersistentSession, error)
	// InstallServer installs a server in the background; nil installs it
	// with localrun under Docker and Policy. Tests put an install of their
	// own here.
	InstallServer InstallServer
	// Now is the clock the heartbeat and the time frame read; nil is the
	// computer's. Tick is how often the heartbeat looks; 0 is a minute.
	// Tests set both.
	Now  func() time.Time
	Tick time.Duration
}

Options start a supervisor.

type Owner

type Owner struct {
	// contains filtered or unexported fields
}

Owner is a held owner lock. The kernel releases it when the process ends however it ends, so an agent whose supervisor died can be started again.

func Acquire

func Acquire(home, name, client string) (*Owner, error)

Acquire takes the agent's owner lock for client, or refuses with a HeldError naming the holder.

func (*Owner) Release

func (o *Owner) Release()

Release lets the lock go and removes the holder's record.

type Packs

type Packs func(ctx context.Context, names []string) (packs []engine.AttachedPack, done func(), err error)

Packs opens the knowledge packs a segment searches, by name; done closes what it opened once the segment ends.

type Port

type Port struct {
	Name string `yaml:"name" json:"name"`
	Port int    `yaml:"port" json:"port"`
}

Port is one of the Coding agent's published ports, as config.yaml keeps it: a name the person gives it and the number its programs serve on, published on this computer at 127.0.0.1 and the same number.

func (Port) Address

func (p Port) Address() string

Address is where the port is published on this computer.

type Reply

type Reply struct {
	Event   *protocol.Event `json:"event,omitempty"`
	Status  *Status         `json:"status,omitempty"`
	Roster  Roster          `json:"roster,omitempty"`
	Stopped *Stopped        `json:"stopped,omitempty"`
	Tasks   *[]Task         `json:"tasks,omitempty"`
	// Consent lists what a refused change would turn on, for the person to
	// agree to before it is sent again with Consent set.
	Consent []RosterEntry `json:"consent,omitempty"`
}

Reply is one line the supervisor sends.

type Roster

type Roster []RosterEntry

Roster is an agent's entries, in a fixed order: its folders, its packs, its servers.

func BuildRoster

func BuildRoster(a Agent, c Config, applied *Applied) Roster

BuildRoster is the agent's roster from its config, its share's sentence saying the malware check is off, as the default policy has it; a client that knows the policy the agent runs under builds it with BuildRosterUnder. applied, when set, is what the running segment was given (Applied): an entry whose switch differs from it is pending.

func BuildRosterUnder

func BuildRosterUnder(a Agent, c Config, applied *Applied, malwareCheck bool) Roster

BuildRosterUnder is BuildRoster for an agent that runs under a policy whose malware check is malwareCheck: the share's sentence of an agent that checks its share says whether ClamAV checks its files. Changing the setting changes the sentence and asks nothing: an agreement to the share under either setting is an agreement to it under the other (Unconsented).

func Configure

func Configure(ctx context.Context, home string, a Agent, client string, ch Change) (r Roster, running bool, err error)

Configure applies a change to an agent: through its supervisor when it runs, which then writes its config alone, and under its owner lock when it does not, so no start reads a config half changed. running says which.

func QueryRoster

func QueryRoster(ctx context.Context, home, name string) (Roster, error)

QueryRoster asks the running agent's supervisor for its roster.

func RequestChange

func RequestChange(ctx context.Context, home, name string, ch Change) (Roster, error)

RequestChange sends a change to the running agent's supervisor, which writes it, and answers the roster after it.

func (Roster) Entry

func (r Roster) Entry(id string) (RosterEntry, bool)

RosterEntry is the roster's entry with id.

func (Roster) Receipt

func (r Roster) Receipt() []receipt.RosterEntry

Receipt is the roster as a segment's envelope records it.

type RosterEntry

type RosterEntry struct {
	// ID is how a switch names the entry: "share", "data",
	// "knowledge:<pack>", "server:<id>".
	ID        string     `json:"id"`
	Kind      EntryKind  `json:"kind"`
	Name      string     `json:"name"`
	GrantedBy string     `json:"grantedBy"`
	State     EntryState `json:"state"`
	// On is the entry's switch as config.yaml holds it; State says what a
	// running segment has.
	On bool `json:"on"`
	// Line is the consent sentence for the entry.
	Line string `json:"line"`
	// Fixed is an entry no switch changes.
	Fixed bool `json:"fixed,omitempty"`
	// Reason is why a failed entry failed.
	Reason string `json:"reason,omitempty"`
	// ShareSwitch is, for a server that may see the agent's share folder
	// (a package server with no network), the id of its switch for that:
	// "server:<id>:share". Share says the switch is on: the server sees
	// the share, read only, while the agent has its share on. ShareLine is
	// the server's sentence with the switch on, the one turning it on asks
	// the person to agree to.
	ShareSwitch string `json:"shareSwitch,omitempty"`
	Share       bool   `json:"share,omitempty"`
	ShareLine   string `json:"shareLine,omitempty"`
	// contains filtered or unexported fields
}

RosterEntry is one line of the roster.

func Unconsented

func Unconsented(r Roster, c Config) []RosterEntry

Unconsented are the roster's entries that are on and whose consent sentence the person has not agreed to as it stands.

type Secrets

type Secrets interface {
	Get(account string) (string, error)
	Set(account, value string) error
	Delete(account string) error
}

Secrets is where stored secrets' values are kept.

type ServerFailure

type ServerFailure struct {
	// Reason is the install's error and the builder's last lines, cut.
	Reason string    `yaml:"reason" json:"reason"`
	At     time.Time `yaml:"at" json:"at"`
	// Told says the agent was told, at a turn, that it does not have the
	// server.
	Told bool `yaml:"told,omitempty" json:"told,omitempty"`
}

ServerFailure is why a server the person added could not be installed.

type SkillCheck

type SkillCheck func(ctx context.Context, dir string) (clamav bool, err error)

SkillCheck checks a staged skill's files as the share's are checked; it says whether ClamAV checked every file and found nothing, and refuses a finding with an error.

type Stage

type Stage = engine.Stage

Stage is a step a segment's start has reached (engine.Stage).

type Status

type Status struct {
	Agent        string        `json:"agent"`
	State        string        `json:"state"`
	Client       string        `json:"client"`
	PID          int           `json:"pid"`
	Since        time.Time     `json:"since"`
	Segment      int           `json:"segment"`
	Run          string        `json:"run"`
	SegmentDir   string        `json:"segmentDir"`
	Adapter      string        `json:"adapter"`
	Model        string        `json:"model"`
	Resumed      bool          `json:"resumed"`
	ResumeReason string        `json:"resumeReason,omitempty"`
	Busy         bool          `json:"busy"`
	Usage        receipt.Usage `json:"usage"`
	// Pending says a change waits for the next turn's segment.
	Pending bool `json:"pending,omitempty"`
}

Status is a running agent's state, as `agentry agent show` prints it.

func QueryStatus

func QueryStatus(ctx context.Context, home, name string) (Status, error)

QueryStatus asks the running agent's supervisor for its status.

type Stopped

type Stopped struct {
	Status     string `json:"status"`
	ResultFile string `json:"resultFile,omitempty"`
	Error      string `json:"error,omitempty"`
}

Stopped is the answer to a stop: where the segment's envelope is and how it ended.

func RequestStop

func RequestStop(ctx context.Context, home, name string) (Stopped, error)

RequestStop asks the running agent's supervisor to stop it, and returns once the segment's envelope is written.

type StoredSecret

type StoredSecret struct {
	Name string    `yaml:"name" json:"name"`
	Set  time.Time `yaml:"set" json:"set"`
}

StoredSecret is a secret the person stored for the agent: its name, and when its value was last set, so setting it again reaches the next turn.

type Supervisor

type Supervisor struct {
	// contains filtered or unexported fields
}

Supervisor owns one running agent: its lock, its segment, its socket.

func Start

func Start(ctx context.Context, opts Options) (*Supervisor, error)

Start takes the agent's owner lock and starts a segment: the conversation the last segment was in is continued where the harness can, and otherwise the new conversation's first turn carries the last exchange of the transcript, which the envelope records. It refuses an agent whose roster turns on what the person has not agreed to on this computer (ConsentError). It serves the owner socket until Stop, or until the segment ends by itself.

func (*Supervisor) Change

func (s *Supervisor) Change(ch Change) (Roster, error)

Change applies a change to the running agent's config, the supervisor alone writing it while it runs. A change to what the segment is given takes effect at the next turn, which starts the next segment; the roster answered shows it pending until then.

func (*Supervisor) ChangeTask

func (s *Supervisor) ChangeTask(op TaskOp) ([]Task, error)

ChangeTask applies a person's pause, resume or remove to the running agent's task.

func (*Supervisor) Done

func (s *Supervisor) Done() <-chan struct{}

Done is closed once the supervisor has finished: the segment ended, its envelope written, the socket closed and the lock released.

func (*Supervisor) Roster

func (s *Supervisor) Roster() Roster

Roster is the running agent's roster: an entry switched since the segment started is pending.

func (*Supervisor) Send

func (s *Supervisor) Send(ctx context.Context, text string) error

Send sends one turn and returns when the agent has answered it. When the roster changed since the segment started, the segment is ended and the next started first, so the turn reaches an agent given the change. The first turn of a conversation that did not continue starts with the last exchange; the first turn after a change says what it switched on and off since the agent was last told, since the conversation the agent continues was had with what it had before; and a turn after the person named the agent or changed its personality starts with them. An agent that keeps time is told the time at every turn, and, at its first turn after a start, the tasks that came due while it was stopped.

func (*Supervisor) Status

func (s *Supervisor) Status() Status

Status is the agent's state now.

func (*Supervisor) Stop

func (s *Supervisor) Stop(ctx context.Context) (*receipt.Envelope, error)

Stop ends the segment without a final result, writes its receipts and envelope, adds its usage to the agent's, and lets the agent go. The volumes stay. Safe to call more than once and after the segment ended by itself; every call returns the segment's envelope.

func (*Supervisor) Subscribe

func (s *Supervisor) Subscribe() (<-chan session.Event, func())

Subscribe hands every event from now on to a channel, until cancel or the agent's end closes it.

func (*Supervisor) Tasks

func (s *Supervisor) Tasks() ([]Task, error)

Tasks are the running agent's tasks, each with its next fire.

type Switch

type Switch struct {
	ID string `json:"id"`
	On bool   `json:"on"`
}

Switch is a roster switch.

type Task

type Task struct {
	ID          string    `yaml:"id" json:"id"`
	Name        string    `yaml:"name" json:"name"`
	Cron        string    `yaml:"cron" json:"cron"`
	Zone        string    `yaml:"zone" json:"zone"`
	Instruction string    `yaml:"instruction" json:"instruction"`
	State       string    `yaml:"state" json:"state"`
	MadeBy      string    `yaml:"madeBy" json:"madeBy"`
	Created     time.Time `yaml:"created" json:"created"`
	// LastFire is when the task last fired, and LastResult the first line
	// of that turn's answer, or why it did not answer.
	LastFire   time.Time `yaml:"lastFire,omitempty" json:"lastFire,omitzero"`
	LastResult string    `yaml:"lastResult,omitempty" json:"lastResult,omitempty"`
	// Next is when it fires next; set when the task is listed, not kept.
	Next time.Time `yaml:"-" json:"next,omitzero"`
}

Task is one registered task.

func ChangeTaskOf

func ChangeTaskOf(ctx context.Context, home string, a Agent, client string, op TaskOp) ([]Task, bool, error)

ChangeTaskOf applies a person's pause, resume or remove to an agent's task: through its supervisor while it runs, under its owner lock while it does not.

func RequestTaskChange

func RequestTaskChange(ctx context.Context, home, name string, op TaskOp) ([]Task, error)

RequestTaskChange asks the running agent's supervisor to pause, resume or remove one of its tasks.

func RequestTasks

func RequestTasks(ctx context.Context, home, name string) ([]Task, error)

RequestTasks asks the running agent's supervisor for its tasks.

func TaskList

func TaskList(home string, a Agent) ([]Task, error)

TaskList is the agent's tasks while it is not running, each with its next fire.

func TasksOf

func TasksOf(ctx context.Context, home string, a Agent) ([]Task, bool, error)

TasksOf are an agent's tasks: its supervisor's while it runs, its file's while it does not.

type TaskOp

type TaskOp struct {
	ID string `json:"id"`
	Op string `json:"op"`
}

TaskOp is a person's change to a task: pause, resume or remove.

type TaskSpec

type TaskSpec struct {
	Name        *string `json:"name,omitempty"`
	Cron        *string `json:"cron,omitempty"`
	Zone        *string `json:"zone,omitempty"`
	Instruction *string `json:"instruction,omitempty"`
	Paused      *bool   `json:"paused,omitempty"`
}

TaskSpec is what the agent gives to add or update a task; an update sets only what it names.

type Tasks

type Tasks struct {
	Version int `yaml:"version"`
	// Checked is the last time the heartbeat looked for tasks that came
	// due: the next start names the ones that came due after it.
	Checked time.Time `yaml:"checked,omitempty"`
	// Fires are the times of the fires of the last day, for the day's cap.
	Fires  []time.Time `yaml:"fires,omitempty"`
	NextID int         `yaml:"nextId"`
	Tasks  []Task      `yaml:"tasks"`
}

Tasks is an agent's tasks file.

func LoadTasks

func LoadTasks(home, name string) (Tasks, error)

LoadTasks reads the agent's tasks; none when it has no file.

func (*Tasks) AddTask

func (ts *Tasks) AddTask(spec TaskSpec, now time.Time) (Task, error)

AddTask registers a task the agent made.

func (*Tasks) ApplyOp

func (ts *Tasks) ApplyOp(op TaskOp, now time.Time) error

ApplyOp applies a person's pause, resume or remove.

func (Tasks) Listed

func (ts Tasks) Listed(now time.Time) []Task

Listed are the tasks with each one's next fire set, from now.

func (*Tasks) RemoveTask

func (ts *Tasks) RemoveTask(id string) (Task, error)

RemoveTask removes the task id.

func (*Tasks) UpdateTask

func (ts *Tasks) UpdateTask(id string, spec TaskSpec, now time.Time) (Task, error)

UpdateTask changes the task id as spec says.

type Usage

type Usage struct {
	Segments     int       `json:"segments"`
	InputTokens  int64     `json:"inputTokens"`
	OutputTokens int64     `json:"outputTokens"`
	TotalTokens  int64     `json:"totalTokens"`
	UserTurns    int       `json:"userTurns"`
	ToolCalls    int       `json:"toolCalls"`
	Updated      time.Time `json:"updated"`
}

Usage is the agent's lifetime usage, summed over its segments' envelopes (usage.json).

func LoadUsage

func LoadUsage(home, name string) (Usage, error)

LoadUsage reads usage.json; none is the zero Usage.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL