agent

package
v0.78.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 69 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent is a person's agent: the worker that does its processing with nobody present, and — in later milestones — the conversation it holds with the person and the tools it reaches everything through.

It knows mail and the database; it knows nothing about HTTP. Everything it does for a person is measured against the person and recorded with the source beside it. Nothing here is constructed while the agent is off: the server passes a nil registry and builds no worker.

Index

Constants

View Source
const (
	CommandStop    = "stop"
	CommandAnswer  = "answer"
	CommandResolve = "resolve"
)
View Source
const (
	AnswerFromMemory  = "memory"  // the facts recall carries, as a turn would get them
	AnswerFromSources = "sources" // passages from the documents, as the search tool finds them
	AnswerFromBoth    = "both"    // both, the way a turn that searches has them

	// AnswerFromAgent is a turn of the agent itself, with its tools, the
	// way a person asking in a conversation is answered; "agent@high"
	// asks it to think at that effort.
	AnswerFromAgent = "agent"
)

What an evaluation answers from. The recall evaluation says whether the facts a question needs reach the model; this says whether the answer is right, and comparing the three says what extracted memory is worth over the raw sources it was read from.

View Source
const (
	AnswerCorrect  = "correct"
	AnswerPartial  = "partial"
	AnswerStale    = "stale"
	AnswerNotKnown = "not_known"
	AnswerInvented = "invented"
	AnswerWrong    = "wrong"

	// AnswerMissed is "not known" where the person gave an answer: what
	// the answer was given did not hold the fact, which is recall's
	// failure rather than the model's, and is told apart from a wrong
	// answer so the two can be worked on apart.
	AnswerMissed = "missed"

	// AnswerUngraded is a grader whose answer could not be read. It counts
	// as nothing, rather than as a wrong answer the model did not give.
	AnswerUngraded = "ungraded"
)

The verdicts a graded answer can have. See prompts/evaluate_grade.txt.

View Source
const (
	AnsweringMarker = "[answering]"
	ApprovedMarker  = "[approved]"
	DeclinedMarker  = "[declined]"
)

The markers a turn resumed by a late answer begins with. They are the person's word, not turns of the agent's own, so they are not in models.OwnTurnMarkers.

View Source
const (
	SpeakFirstOnboarding  = "onboarding"
	SpeakFirstMemoryCheck = "memory_check"
	SpeakFirstIdea        = "idea"
)

The reasons the agent speaks first, which are also the subjects of its speak_first jobs.

View Source
const (
	RiskRead        = tools.RiskRead
	RiskWrite       = tools.RiskWrite
	RiskDestructive = tools.RiskDestructive
	RiskOutward     = tools.RiskOutward
	RiskGranting    = tools.RiskGranting

	FamilyMailbox  = tools.FamilyMailbox
	FamilyDomains  = tools.FamilyDomains
	FamilyAudit    = tools.FamilyAudit
	FamilyPeople   = tools.FamilyPeople
	FamilyServer   = tools.FamilyServer
	FamilyAccount  = tools.FamilyAccount
	FamilyGeneral  = tools.FamilyGeneral
	FamilyServers  = tools.FamilyServers
	FamilySkills   = tools.FamilySkills
	FamilyBrowser  = tools.FamilyBrowser
	FamilyComputer = tools.FamilyComputer
)
View Source
const ShareFor = 30 * 24 * time.Hour

ShareFor is how long a shared artifact's address stays good: long enough to find in a chat's history, not forever.

View Source
const ShareToOpenFor = 6 * time.Hour

ShareToOpenFor is how long an address made to open a file now stays good: one the drawer draws, or one handed to a program over MCP to fetch. Short, because it is made afresh each time, and an address that opens a file without a sign-in should not outlive the moment it was made for.

Variables

View Source
var (
	NewCatalog        = tools.NewCatalog
	RenameTools       = tools.Rename
	ActionsOf         = tools.ActionsOf
	NeedsConfirmation = tools.NeedsConfirmation
	Split             = tools.Split
	Search            = tools.Search

	// Location and the time helpers moved to the kit with the datetime tool.
	Location = tools.Location

	// The text and cron helpers moved to the kit too.
	HTMLToText = tools.HTMLToText
)
View Source
var ErrDeviceDetached = errors.New("was detached")

ErrDeviceDetached is the computer leaving while a question was open. A caller that can wait treats it like the computer not being there.

View Source
var ErrLeftOpen = tools.ErrLeftOpen

ErrLeftOpen says a card was not answered while the turn waited, and is still open for the person to answer later.

View Source
var ErrNotGranted = errors.New("agent: not granted for this mailbox")

ErrNotGranted says the person has not let their agent do this with this source.

View Source
var ErrUnavailable = errors.New("agent: unavailable")

ErrUnavailable says the agent cannot do this here: agents are off, the feature is off for the deployment, or there is no model to ask.

View Source
var FeatureAllowed = tools.FeatureAllowed

FeatureAllowed says whether the deployment offers a feature at all.

Functions

func BriefPrompt

func BriefPrompt(found *models.Agent, owner *models.User) string

BriefPrompt is the daily brief's standing instruction, as the person's own words, because the person is who turned it on.

Written here rather than in a template file because it is a starting point rather than a fixed thing: it goes into an ordinary schedule row, where the Schedules card shows it and anybody can rewrite it to say what they actually want to hear each morning.

func CountMessages

func CountMessages(items []*models.MailboxItem) int

CountMessages is how many messages a set of items is, which is not how many items it is: one message can be filed twice.

A message somebody sends to themselves is the plain case -- a copy in Sent and a copy in the Inbox, one message, two items -- and so is a message filed in two folders by two rules. Anything asking "is this a conversation yet" has to count messages, or a note to oneself is two.

func DayStart

func DayStart(owner *models.User, now time.Time) time.Time

DayStart is midnight in the person's own zone, which is when the panel says their budget resets and so when every share of a day turns over.

func DecodedSessionData

func DecodedSessionData(data json.RawMessage) string

DecodedSessionData is what a session message carries, for the websocket handler that has it as raw JSON.

func DocumentBytes

func DocumentBytes(ctx context.Context, files storage.Files, document *models.AgentDocument) ([]byte, error)

DocumentBytes is an attachment document's bytes, out of the store.

The work is in the tools package, because the memory tool's `look` reads the same bytes for the person and a tool cannot import this one. Kept here as well so that every caller in this package and in the API says the same name for the same thing.

func DraftPrompt

func DraftPrompt(input *DraftInput) ([]llm.ChatMessage, error)

DraftPrompt builds the messages for one draft call.

func ExtractAttachmentText

func ExtractAttachmentText(name, contentType string, content []byte) string

ExtractAttachmentText is what a model reads of a file: its text when it is a text file, valid UTF-8, capped; empty otherwise. Called once, when the file is uploaded, and kept on the row.

func ForgetAttachments

func ForgetAttachments(ctx context.Context, tx db.Transaction, store storage.Storage, agentId string) error

ForgetAttachments removes every file a person's agent holds, for the person forgetting their agent.

func InterpretExtraction

func InterpretExtraction(answer *ExtractAnswer) []models.MailProposal

InterpretExtraction turns the model's answer into proposals, refusing what is not usable: an event with no summary or no start is not an appointment, and a contact with neither an address nor a number is not a person.

func InterpretTriage

func InterpretTriage(answer *TriageAnswer, agent *models.Agent) (*models.MailInsight, error)

InterpretTriage turns the model's answer into an insight, refusing values outside the vocabulary the way a rule would refuse them.

func IsImageAttachment

func IsImageAttachment(contentType string) bool

IsImageAttachment says whether a file is a picture a model can look at.

func IsMediaAttachment

func IsMediaAttachment(contentType string) bool

IsMediaAttachment says whether a file is a video or a sound a browser plays in the page.

func KnowledgeLanguage added in v0.58.0

func KnowledgeLanguage(agent *models.Agent, user *models.User) string

KnowledgeLanguage is what the agent writes in when nobody is talking to it: its notes, and the triage, summaries, research, drafts and briefs it makes on its own. The agent's own setting for it, else the language the agent or the account was set to, never the one the dashboard happens to be shown in, so that switching the dashboard's language does not switch what the agent keeps; else empty for the model's default.

func Language

func Language(agent *models.Agent, user *models.User) string

Language is what the agent talks to a person in, in a conversation: the agent's own setting, else the account's chosen locale, else the one the dashboard said, else empty for the model's default. Only conversations use it; work the agent does on its own uses KnowledgeLanguage.

func LoadHeaders

func LoadHeaders(ctx context.Context, store storage.Storage, mail *models.Mail) error

LoadHeaders fills a message's headers from the spool, where they live; the row carries the envelope and a few named fields but not the header block. Nothing is changed when the message is no longer stored.

func MailFacts

func MailFacts(mail *models.Mail) []string

MailFacts is what the server already knows about a message, said plainly: how it authenticated, what the spam filter made of it, whether it came from a list or a machine, and the two headers a forgery shows itself in — a Reply-To or a Return-Path pointing somewhere else than the From.

func MinimumMessages

func MinimumMessages(source *models.AgentMailbox) int

MinimumMessages is how long a conversation in this source is before it is summarized unasked.

func Money

func Money(amount float64, currency string) string

Money is an amount as it is written for a person to read: the amount, and the currency the operator says the prices are in.

func MonthBounds

func MonthBounds(when time.Time, owner *models.User) (time.Time, time.Time)

MonthBounds is the first moment of a month and the first of the next, in the person's own zone: what "June 2023" means to them.

func NextRun

func NextRun(schedule *models.AgentSchedule, owner *models.User, now time.Time) (time.Time, error)

NextRun is when a schedule next runs for a person, from now.

func PeriodPath

func PeriodPath(when time.Time, month bool) string

PeriodPath is where a month or a year lives in the graph.

func RecordFiled

func RecordFiled(tx db.Transaction, agentId, mailboxId string, mail *models.Mail, insight *models.MailInsight, folderName string) error

RecordFiled records that the person filed a sorted message somewhere the agent's sorting did not put it.

func RecordReplyDeclined

func RecordReplyDeclined(tx db.Transaction, reply *models.AgentReply, how string) error

RecordReplyDeclined records that a reply the agent wrote did not go.

func RecordSorted

func RecordSorted(tx db.Transaction, agentId, mailboxId string, mail *models.Mail, before, after *models.MailInsight) error

RecordSorted records that the person sorted a message themselves, differently from the agent: the category, the priority, whether it needs a reply.

func RecordUsage

func RecordUsage(database db.Database, agentId, mailboxId, model, kind string, usage llm.Usage)

RecordUsage adds what one model call cost to the hourly rows for this agent, source, model and kind of run. Best effort: a row that cannot be written loses accounting, never a run.

func RecordUsageIn

func RecordUsageIn(tx db.Transaction, agentId, mailboxId, model, kind string, usage llm.Usage) error

RecordUsageIn is RecordUsage inside a transaction the caller already holds.

func RenderConduct

func RenderConduct(configuration *config.Configuration, agent *models.Agent, owner *models.User, short bool) (string, error)

RenderConduct renders the system message for a run nobody is present for, in the language of the agent's own work.

func ReplyPrompt

func ReplyPrompt(input *DraftInput, guidance string) ([]llm.ChatMessage, error)

ReplyPrompt builds the messages for one auto-reply call. The draft input carries everything but the guidance, which is the policy's.

func RequireBudget

func RequireBudget(tx db.Transaction, configuration *config.Configuration, agent *models.Agent, owner *models.User, now time.Time) error

RequireBudget is what a run calls before its first model call: it returns a Deferral to the next reset when nothing is left.

func SettleSchedule

func SettleSchedule(schedule *models.AgentSchedule, owner *models.User, now time.Time) (time.Time, error)

SettleSchedule settles a schedule's time and says when it next runs. A distance from now ("@in 20m") becomes the moment it means, so that what is stored does not move every time it is read. The agent's own tool has always done this; a schedule written from the dashboard or the command line was refused instead, being told it wanted five cron fields.

func SkillRunsCommands

func SkillRunsCommands(declared *skills.Tool) bool

SkillRunsCommands says whether carrying this tool out runs anything on a computer, which is what decides that it asks first and that a run with nobody present never reaches it.

func SourceActive

func SourceActive(agent *models.Agent, mailbox *models.Mailbox) bool

SourceActive says whether a mailbox is a source anything happens for: granted, of an agent that is on and not switched off by an operator.

func SumSpend

func SumSpend(tx db.Transaction, configuration *config.Configuration, agentId string, since time.Time) (int64, float64, error)

SumSpend is what a period came to, in tokens and in money. Usage is kept per model, and each model is priced by its own provider, so a deployment with two providers adds up properly — and grouping by model gives both numbers from the one query, which is why the budget check does not read the same rows twice. An agent id of "" is the whole server.

func SumSpendOfKind

func SumSpendOfKind(tx db.Transaction, agentId, kind string, since time.Time) (int64, error)

SumSpendOfKind is what one kind of run has spent since a time, in tokens.

SumSpend prices everything an agent did, by model, because a budget has to say what it cost. This answers the narrower question a run asks about its own share -- how much of today has already gone on this kind of work -- and the usage rows carry the kind, so it is the same one grouped query with a different key.

func SummarizePrompt

func SummarizePrompt(input *SummarizeInput) ([]llm.ChatMessage, error)

SummarizePrompt builds the messages for one summarize call.

func TriagePrompt

func TriagePrompt(input *TriageInput) ([]llm.ChatMessage, error)

TriagePrompt renders the two messages a triage call sends.

func UnwantedCategory

func UnwantedCategory(category string) bool

UnwantedCategory says whether the sorting put a message in the two categories nobody wants, which is what the rule every mailbox starts with matches.

Types

type Agent

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

Agent is the worker and, for the rest of the server, the way to hand it work.

func New

func New(settings *Settings) *Agent

New builds the agent. Register handlers, then Start.

func (*Agent) Apply

func (self *Agent) Apply(run *AskRun, command RunCommand) bool

Apply gives the run the word here. It says whether anything was waiting for it: a stop always is.

func (*Agent) Ask

func (self *Agent) Ask(settings *AskSettings) (*AskRun, error)

Ask starts a turn. It returns at once; the run streams what happens.

func (*Agent) AttachComputer

func (self *Agent) AttachComputer(agentId string, connection DeviceConnection, identity ComputerIdentity)

AttachComputer records a person's computer by its name; a second attach under the same name replaces the first, and a different name is another computer beside it.

func (*Agent) AttachTab

func (self *Agent) AttachTab(agentId string, connection TabConnection, title, url string)

AttachTab records a person's tab; a second attach replaces the first.

func (*Agent) BackgroundCommands added in v0.57.0

func (self *Agent) BackgroundCommands(ctx context.Context, agentId string) ([]*BackgroundCommand, error)

BackgroundCommands are the background commands on a person's computers, newest first on each.

func (*Agent) BrowserConnected added in v0.69.0

func (self *Agent) BrowserConnected(agentId string) bool

BrowserConnected says whether a person's browser is connected through the extension, with a tab to act in or not.

func (*Agent) CallDirect

func (self *Agent) CallDirect(
	ctx context.Context,
	owner *models.User,
	person *models.Agent,
	operations tools.Operations,
	surface string,
	origin string,
	name string,
	arguments json.RawMessage,
) (*tools.Result, error)

CallDirect runs one tool by name, as this person, outside a conversation. The tool decides what it may do; the person's permissions decided whether it was offered at all.

func (*Agent) Catalog

func (self *Agent) Catalog() *Catalog

Catalog is every tool the server knows.

func (*Agent) ComputerAnswered

func (self *Agent) ComputerAnswered(agentId string, connection DeviceConnection, id int64, ok bool, data json.RawMessage, failure string)

ComputerAnswered is a computer answering a request.

func (*Agent) ComputerBackgroundEnded added in v0.57.0

func (self *Agent) ComputerBackgroundEnded(agentId string, connection DeviceConnection, data json.RawMessage)

ComputerBackgroundEnded is a computer saying a background command ended.

func (*Agent) ComputerSessionSaid

func (self *Agent) ComputerSessionSaid(agentId string, connection DeviceConnection, id, event, stream, data string, code int)

ComputerSessionSaid routes what a computer said about a session.

func (*Agent) ComputersAttached

func (self *Agent) ComputersAttached(agentId string) []AttachedComputer

ComputersAttached are the computers a person has attached, for the API.

func (*Agent) ConnectBrowser added in v0.69.0

func (self *Agent) ConnectBrowser(agentId string, connection TabConnection, title, url string, hasTab bool)

ConnectBrowser records a person's browser, connected through the extension, with a tab to act in or with none yet; a second connection replaces the first.

func (*Agent) DetachComputer

func (self *Agent) DetachComputer(agentId string, connection DeviceConnection)

DetachComputer forgets a person's computer, if this connection is the one attached under its name.

func (*Agent) DetachTab

func (self *Agent) DetachTab(agentId string, connection TabConnection)

DetachTab forgets a person's tab, if this connection is the one attached.

func (*Agent) Digest

func (self *Agent) Digest(ctx context.Context, agent *models.Agent, owner *models.User, from, until time.Time) (string, error)

Digest is what happened between two moments, as text for a prompt.

Empty when nothing happened, which is the answer for a quiet month and is not an error.

func (*Agent) DirectTools

func (self *Agent) DirectTools(ctx context.Context, person *models.Agent, operations tools.Operations) []*tools.Tool

DirectTools is the catalog as this person sees it, for a caller that will choose a tool itself rather than have a model choose one.

It is built the way a turn's catalog is built -- what their permissions allow, less what the operator switched off, plus the tools of the servers they have connected and the skills the operator installed -- with two left out.

ask_user goes because there is nobody at this end to answer it; see Ask above. tool_search goes because it exists to keep a long catalog out of a model's request until it is wanted, and a caller that lists tools once and keeps the list is better served by the list.

func (*Agent) DraftReply

func (self *Agent) DraftReply(ctx context.Context, request *models.AgentDraftRequest) (*models.AgentDraft, error)

DraftReply writes a reply to a message for the person to read. It is the one thing the agent does in the request rather than from the queue, because the person is sitting in the composer waiting for it.

func (*Agent) EmbedGraph

func (self *Agent) EmbedGraph(ctx context.Context, agent *models.Agent, limit int) (int, error)

EmbedGraph gives vectors to pages and facts that have none, or whose vector an older model made, and says how many it wrote.

func (*Agent) Enqueue

func (self *Agent) Enqueue(tx db.Transaction, kind models.AgentJobKind, agentId, mailboxId, subjectId string) (*models.AgentJob, error)

Enqueue adds a job inside the caller's transaction. A job for the same agent, kind and subject that is already queued or running is returned instead of a second one.

func (*Agent) EnsureVectorIndexes

func (self *Agent) EnsureVectorIndexes(ctx context.Context) error

EnsureVectorIndexes builds the vector index for every table and every model that has written a vector. Called at start, and again whenever a model writes its first vector, so that the index exists before a corpus arrives rather than having to be built over one.

func (*Agent) EvaluateAnswer added in v0.60.0

func (self *Agent) EvaluateAnswer(ctx context.Context, found *models.Agent, owner *models.User, question, expectedAnswer, outdatedAnswer, answerFrom string) (*AnswerEvaluation, error)

EvaluateAnswer answers a question from one kind of context, with the model a conversation uses, and grades the answer against the one the person gave. Both calls are runs of kind evaluate, so they are listed and priced like any other call and never touch the conversations or the graph.

func (*Agent) FindRun

func (self *Agent) FindRun(runId string) *AskRun

FindRun is a run in flight or recently finished, or nil.

func (*Agent) FoldByWordsIntoWhatThePageSays

func (self *Agent) FoldByWordsIntoWhatThePageSays(tx db.Transaction, written *models.AgentFact, node *models.AgentNode) (*models.AgentFact, error)

FoldByWordsIntoWhatThePageSays is the fold without the fact's meaning: the twin is found by names and words alone. For a caller that is already inside a transaction it cannot leave -- a dashboard request, which runs whole inside one -- and must not hold it, and the page's row lock, through a provider call.

func (*Agent) FoldIntoWhatThePageSays

func (self *Agent) FoldIntoWhatThePageSays(ctx context.Context, tx db.Transaction, written *models.AgentFact, node *models.AgentNode) (*models.AgentFact, error)

FoldIntoWhatThePageSays merges a fact just written into the one already on the page that says the same thing, and reports which it became.

Every writer needs this and for the same reason: nobody writing a fact has read the page first. A conversation that comes back to a subject is filed by two runs a day apart, neither knowing of the other, and both doing their job; a person adding a line by hand is not going to reread thirteen of them. Left to itself a page ends up saying one thing nine ways, which is worse than saying it once and worse than not saying it, because every answer drawn from it is a little different.

The older one stays: its number is what anything else cites. It gains whatever evidence the new one brought, and the new one goes dormant behind it -- kept, searchable, out of the page -- so a fold the person disagrees with is there to be undone. What happened is in the page's history either way.

What it will not do is guess. Folding with nobody watching is only safe where the two are the same sentence twice; anything that reads alike but says something different is left standing beside its twin, so that the newer is recalled as well as the older. See whatToFold.

func (*Agent) ForeignRun

func (self *Agent) ForeignRun(runId string) (string, bool)

ForeignRun is the conversation of a run another instance is running, as heard through the feed, and whether it is known at all.

func (*Agent) ForgetConnection

func (self *Agent) ForgetConnection(serverName, agentId string)

ForgetConnection drops a person's session with a server, after a disconnect or a new credential.

Every session with that server as that person goes, whichever computer it was through: a new credential or a new reach is true of all of them.

func (*Agent) ForgetSkills

func (self *Agent) ForgetSkills()

ForgetSkills makes the next look read the rows again, for when one has just been installed or taken away.

func (*Agent) Forward

func (self *Agent) Forward(command RunCommand) error

Forward says the word to the other instances, for the one running the turn to apply. Whether anything was waiting for it is not known here.

func (*Agent) ForwardAuthorization added in v0.73.0

func (self *Agent) ForwardAuthorization(ctx context.Context, agentId string, server *config.AgentMCPServer, forwardURL, computerName string) (string, error)

ForwardAuthorization asks the person's attached computer to listen on its loopback interface for a server's authorization and send the browser that brings it on to forwardURL. The answer is the loopback address to give the service, which only a browser on that computer can reach.

The computer is the one the person named, since it is the one they are signing in on; else the server's reach; else the only one attached.

func (*Agent) KnowledgeMeaning

func (self *Agent) KnowledgeMeaning(agentId string) indexed.Meaning

KnowledgeMeaning is the meaning half of a search of what was indexed, for a caller that is not in a turn: the API, and the command line and the dashboard through it.

The person searching their own documents is ranked the same way their agent's tool is, which is the whole point of one search shared between the surfaces. It embeds the question, which a turn does once and keeps; there is nothing to keep here, so each search pays for its own.

func (*Agent) LatestIn

func (self *Agent) LatestIn(conversationId string) *AskRun

LatestIn is the last turn of a conversation, running or just finished, for a caller that asked, could not wait to the end, and has come back for the rest.

A finished run is handed back rather than withheld, because the caller coming back a second late would otherwise be told there is nothing to wait for and never hear the answer. Subscribing to a finished run replays what it said and closes, which is exactly what they want. A run is forgotten ten minutes after it ends, and after that there is nothing to hand back and the conversation itself is where the answer is.

func (*Agent) ListIdeas added in v0.76.0

func (self *Agent) ListIdeas(ctx context.Context, tx db.Transaction, agent *models.Agent, owner *models.User, statuses []models.AgentIdeaStatus, kinds []models.AgentIdeaKind, language string) ([]*models.AgentIdea, error)

ListIdeas is the agent's ideas in the statuses and kinds asked for, or in all, brought up to date first, in the language asked for where the catalog has it.

func (*Agent) MarkIdeasShown added in v0.76.0

func (self *Agent) MarkIdeasShown(tx db.Transaction, agent *models.Agent, ideaIds []string) error

MarkIdeasShown notes that ideas were put in front of the person.

func (*Agent) MeaningSearch

func (self *Agent) MeaningSearch(ctx context.Context, agent *models.Agent, mailboxId, query string, limit int) ([]string, error)

MeaningSearch is meaningSearch for the API and for tests.

func (*Agent) MigrateMemories

func (self *Agent) MigrateMemories(ctx context.Context, agent *models.Agent) error

MigrateMemories moves an agent's flat memories onto the graph, once.

Done here rather than in the migration because a page and a fact need identifiers this package makes, and because doing it lazily means the old table is untouched: a deployment that goes back a release finds its memories exactly as they were.

func (*Agent) OAuthSettings

func (self *Agent) OAuthSettings(server *config.AgentMCPServer, redirectURL string) *mcp.OAuthSettings

OAuthSettings is the flow for a server, from the configuration.

func (*Agent) OnMailboxDelivery

func (self *Agent) OnMailboxDelivery(tx db.Transaction, mailbox *models.Mailbox, item *models.MailboxItem, mail *models.Mail)

OnMailboxDelivery is the delivery hook: a message has just been placed in a mailbox, inside the delivery transaction. If the mailbox is a granted source of an active agent, the processing jobs are queued in the same transaction — and nothing else happens here, because a model call inside the SMTP transaction would be a model outage bouncing mail.

func (*Agent) OpenSecret

func (self *Agent) OpenSecret(value string) (string, error)

OpenSecret opens what SealSecret sealed.

func (*Agent) OperationsFor

func (self *Agent) OperationsFor(ctx context.Context, owner *models.User) (Operations, error)

OperationsFor is what a run made for a person outside a request — a scheduled run, a turn from a chat app — may do: what the person may.

func (*Agent) Probe

func (self *Agent) Probe(ctx context.Context, server *config.AgentMCPServer, agentId string) (int, error)

Probe connects to a server as a person once and reports what it found: how the Agent page checks a credential the person just gave.

func (*Agent) ProposeIdea added in v0.76.0

func (self *Agent) ProposeIdea(ctx context.Context, tx db.Transaction, agent *models.Agent, owner *models.User, idea *models.AgentIdea) (*models.AgentIdea, error)

ProposeIdea keeps an idea found for the person, once it passes the check every idea passes, whoever proposed it: the words and the tools (checkIdea), what prompted it (checkEvidence), that it is not one already kept (repeatedIdea), and a model's judgment that it promises nothing its tools cannot do (judgeIdea).

func (*Agent) QueueEvaluation added in v0.61.0

func (self *Agent) QueueEvaluation(tx db.Transaction, agent *models.Agent) (*models.AgentEvaluationRun, error)

QueueEvaluation starts a run of the memory check and queues the job that fills it; one already queued or running is left to run, and is what is returned.

func (*Agent) ReadBackgroundCommand added in v0.57.0

func (self *Agent) ReadBackgroundCommand(ctx context.Context, agentId, computerName, id string, tailBytes int) (*BackgroundCommand, error)

ReadBackgroundCommand is one of this agent's, with the last tailBytes of each stream.

func (*Agent) RecallForQuestion

func (self *Agent) RecallForQuestion(ctx context.Context, found *models.Agent, owner *models.User, question string) ([]*RecalledPage, error)

RecallForQuestion answers what the graph would put in front of the model for a question, without asking it anything.

The same two steps a turn takes -- the fused search, then the choice of blocks under the token budget -- so that what this reports is what a turn would carry and not a second implementation of it that drifts. What it deliberately leaves out is the turn's bookkeeping: no `used_at` is moved and no vectors are backfilled, because an evaluation that changed importance and decay as it ran would be measuring its own last pass.

func (*Agent) Register

func (self *Agent) Register(kind models.AgentJobKind, handler Handler)

Register sets the handler for a kind of job.

func (*Agent) ReportPresence added in v0.61.0

func (self *Agent) ReportPresence(userId string, isVisible bool, idleSeconds int, now time.Time)

ReportPresence records a tab's report for a person: whether it is visible, and how long since their last keypress, click or scroll.

func (*Agent) ResumeInteraction added in v0.61.4

func (self *Agent) ResumeInteraction(settings *ResumeSettings, chatAboutIt string) (*AskRun, error)

ResumeInteraction starts the turn a late answer brings: the answer to the question, or the word on the approval, as the person's message, and for an approval the one call it allows. The card must already have been claimed for this answer. Nil and no turn for an answer that asks for none: the person chose to chat about it instead.

func (*Agent) SealSecret

func (self *Agent) SealSecret(value string) (string, error)

SealSecret seals a credential with the server secret, for storing.

func (*Agent) Server

func (self *Agent) Server(name string) *config.AgentMCPServer

Server is a declared server by name, or nil.

func (*Agent) SetIdeaStatus added in v0.76.0

func (self *Agent) SetIdeaStatus(tx db.Transaction, agent *models.Agent, ideaId string, status models.AgentIdeaStatus) (*models.AgentIdea, error)

SetIdeaStatus is the person saying what became of an idea: done, dismissed, or open again. Started is StartIdea's, which needs a conversation, and expired is the clock's.

func (*Agent) SetMailer

func (self *Agent) SetMailer(sender mailer.Mailer)

SetMailer hands the worker the mailer, once there is one.

func (*Agent) SetOperationsFactory

func (self *Agent) SetOperationsFactory(factory OperationsFactory)

SetOperationsFactory hands the worker the way to act as a person.

func (*Agent) SetTabHeld added in v0.69.0

func (self *Agent) SetTabHeld(agentId string, hasTab bool)

SetTabHeld is the browser saying whether it has a tab the actions go to.

func (*Agent) ShareAttachment

func (self *Agent) ShareAttachment(attachmentId string, until time.Time) string

ShareAttachment is the query value that opens the file until the time given, or "" when the server has no secret to sign with.

func (*Agent) SharedAttachment

func (self *Agent) SharedAttachment(attachmentId, share string) bool

SharedAttachment says whether the query value opens the file now.

func (*Agent) SkillTools

func (self *Agent) SkillTools(ctx context.Context) []*Tool

SkillTools is every tool the installed skills declare.

func (*Agent) SpeakFirstNow added in v0.61.0

func (self *Agent) SpeakFirstNow(tx db.Transaction, agent *models.Agent, reason string) error

SpeakFirstNow queues the agent to speak first for a reason now, outside the sweep's rules: the person asked, from the dashboard or the command line. One already queued or running is left to run.

func (*Agent) Start

func (self *Agent) Start()

Start begins claiming work.

func (*Agent) StartIdea added in v0.76.0

func (self *Agent) StartIdea(ctx context.Context, tx db.Transaction, agent *models.Agent, ideaId, conversationId, language string) (*models.AgentIdea, *models.AgentConversation, error)

StartIdea records that a conversation carries an idea out: the one given, when the agent took it up where it was talking, or a new one named after the idea, whose first message the person then sends. Nothing is said in it here: starting an idea never acts.

func (*Agent) Stop

func (self *Agent) Stop()

Stop ends the worker and waits for the runs in flight.

func (*Agent) StopBackgroundCommand added in v0.57.0

func (self *Agent) StopBackgroundCommand(ctx context.Context, agentId, computerName, id string) (*BackgroundCommand, error)

StopBackgroundCommand stops one of this agent's for the person. The agent is told it ended, as it is of any ending it did not ask for.

func (*Agent) StopConversation

func (self *Agent) StopConversation(conversationId string)

StopConversation ends every run of a conversation, for the conversation being deleted under them.

func (*Agent) SubscribeConversation

func (self *Agent) SubscribeConversation(conversationId string) (<-chan Event, func())

SubscribeConversation is the feed of a conversation: the turns in flight on this instance are replayed first, then whatever happens until the returned function is called. The channel closes then.

func (*Agent) TabAnswered

func (self *Agent) TabAnswered(agentId string, connection TabConnection, id int64, ok bool, data json.RawMessage, failure string)

TabAnswered is the extension answering a request: the extension on this connection, so that a replaced tab's late answers reach nobody.

func (*Agent) TabAttached

func (self *Agent) TabAttached(agentId string) (bool, string, string)

TabAttached says whether a person has a tab to act in, for the API.

func (*Agent) Tick

func (self *Agent) Tick(ctx context.Context) error

Tick releases stale claims, claims what is due, and runs it. The worker calls it on its interval; a test calls it by hand.

func (*Agent) TickAt

func (self *Agent) TickAt(ctx context.Context, now time.Time) error

TickAt is Tick as of a moment, for a test that cannot wait for a hold to end.

func (*Agent) ToolRisks added in v0.76.0

func (self *Agent) ToolRisks(ctx context.Context, agent *models.Agent, owner *models.User) (map[string]tools.Risk, error)

ToolRisks is the person's tools, by name, with what each can do: what an idea may promise.

func (*Agent) UpdateTab

func (self *Agent) UpdateTab(agentId, title, url string)

UpdateTab is the tab saying where it went.

func (*Agent) Wait

func (self *Agent) Wait()

Wait blocks until every run in flight has finished. For tests and for Stop.

type AnswerEvaluation added in v0.60.0

type AnswerEvaluation struct {
	AnswerText    string
	AnswerVerdict string
	VerdictReason string

	// FactCount and PassageCount are what the answer was given.
	FactCount    int
	PassageCount int

	// What the answer and its grading cost, together, and how long the
	// answer took, which is what a person waits for; the grading is not.
	Cost             float64
	AnswerDurationMS int64
}

AnswerEvaluation is one question answered and graded.

type AskRun

type AskRun struct {
	ID string
	// contains filtered or unexported fields
}

AskRun is one turn in flight.

func (*AskRun) Agent

func (self *AskRun) Agent() *models.Agent

func (*AskRun) Answer

func (self *AskRun) Answer(callId, answer string) bool

Answer answers a question card. It says whether there was one.

func (*AskRun) Ask

func (self *AskRun) Ask(ctx context.Context, callId, question string, choices []string) (string, error)

Ask shows the question card and waits for the person's words.

func (*AskRun) AttachedComputers

func (self *AskRun) AttachedComputers() []tools.Computer

func (*AskRun) AttachedTab

func (self *AskRun) AttachedTab() tools.Tab

func (*AskRun) BrowserPage

func (self *AskRun) BrowserPage(ctx context.Context) (*browser.Context, error)

func (*AskRun) CanAsk added in v0.61.3

func (self *AskRun) CanAsk() bool

func (*AskRun) ComputersAllowed

func (self *AskRun) ComputersAllowed() bool

func (*AskRun) ComputersUnattended

func (self *AskRun) ComputersUnattended() bool

ComputersUnattended is the night, and nothing else.

Every other run with nobody present is refused the machine, because the confirmation card is what stands between the agent and the shapes that cannot be taken back, and a card cannot be shown to an empty room. The owner read that reasoning and accepted the risk for the night alone, so it is named here rather than inferred from the shape of the settings: widening it to scheduled turns or goals is a decision somebody should have to make on purpose.

func (*AskRun) Configuration

func (self *AskRun) Configuration() *config.Configuration

func (*AskRun) Conversation

func (self *AskRun) Conversation() *models.AgentConversation

Conversation is the conversation the run belongs to.

func (*AskRun) Database

func (self *AskRun) Database() db.Database

func (*AskRun) DiscardDraft

func (self *AskRun) DiscardDraft(ctx context.Context, tx db.Transaction, itemId string) error

func (*AskRun) DraftReply

func (self *AskRun) DraftReply(ctx context.Context, request *models.AgentDraftRequest) (*models.AgentDraft, error)

func (*AskRun) Enqueue

func (self *AskRun) Enqueue(tx db.Transaction, kind models.AgentJobKind, mailboxId, subjectId string) error

func (*AskRun) Headless

func (self *AskRun) Headless() bool

func (*AskRun) IsLinkInPlaceOfPath added in v0.74.0

func (self *AskRun) IsLinkInPlaceOfPath() bool

IsLinkInPlaceOfPath is false: the dashboard shows a file by its path with the person's session, and a link is for when they ask for one.

func (*AskRun) Load

func (self *AskRun) Load(name string)

func (*AskRun) Loaded

func (self *AskRun) Loaded() map[string]bool

func (*AskRun) MeaningSearch

func (self *AskRun) MeaningSearch(ctx context.Context, mailboxId, query string, limit int) ([]string, error)

func (*AskRun) NoteFact

func (self *AskRun) NoteFact(ctx context.Context, fact *models.AgentFact) []*models.AgentFact

func (*AskRun) NoteNode

func (self *AskRun) NoteNode(ctx context.Context, node *models.AgentNode)

func (*AskRun) Offered

func (self *AskRun) Offered() []*tools.Tool

func (*AskRun) Operations

func (self *AskRun) Operations() tools.Operations

func (*AskRun) Owner

func (self *AskRun) Owner() *models.User

Owner is the person.

func (*AskRun) PreparePage added in v0.48.0

func (self *AskRun) PreparePage(ctx context.Context, path string, kind models.AgentNodeKind, name string) tools.PreparedPage

func (*AskRun) Queued

func (self *AskRun) Queued() bool

Queued says whether the run is still waiting for the turn before it.

func (*AskRun) RankChunksByMeaning

func (self *AskRun) RankChunksByMeaning(ctx context.Context, words string, chunks []*models.AgentChunk, limit int) []*models.AgentChunk

RankChunksByMeaning puts a set the words found into the order the meaning wants. What a deployment with no vector index does instead of a vector search: it finds everything the words find, in a better order, and misses a paraphrase that shares no word with the question.

func (*AskRun) ReadOnly

func (self *AskRun) ReadOnly() bool

func (*AskRun) Recall

func (self *AskRun) Recall(line string)

Recall keeps what a memory search found, for the overlay.

func (*AskRun) Recalled

func (self *AskRun) Recalled() []string

func (*AskRun) Resolve

func (self *AskRun) Resolve(callId string, approve bool) bool

Resolve answers a confirmation card. It says whether there was one.

func (*AskRun) SearchGraphByMeaning

func (self *AskRun) SearchGraphByMeaning(ctx context.Context, words string, limit int) ([]*models.AgentNode, []*models.AgentFact)

SearchGraphByMeaning is what the memory tool's search adds to its own word search. Part of tools.GraphSearching.

func (*AskRun) SearchKnowledgeByMeaning

func (self *AskRun) SearchKnowledgeByMeaning(ctx context.Context, sourceIds []string, words string, limit int) ([]*models.AgentChunk, bool)

SearchKnowledgeByMeaning is the passages nearest some words, and whether the database ranked them itself.

Part of tools.KnowledgeSearching. False means this deployment has no vector index, and the caller should fall back to re-ranking what the words found: reading half a million vectors into memory to sort them is not a search.

func (self *AskRun) SharedLink(attachmentId string) string

SharedLink is an address that opens one file with no sign-in, on the dashboard the turn came through (tools.Linking), for a person who asked for a link to open elsewhere; empty when the turn did not come through the dashboard.

func (*AskRun) SteeredInto added in v0.71.5

func (self *AskRun) SteeredInto() *AskRun

SteeredInto is the running turn this message was handed to, or nil when it is a turn of its own.

func (*AskRun) Stop

func (self *AskRun) Stop()

Stop ends the run; the turn stays where it got to.

func (*AskRun) StopByPerson added in v0.61.4

func (self *AskRun) StopByPerson()

StopByPerson ends the run because the person asked, closing the cards it was waiting on.

func (*AskRun) Storage

func (self *AskRun) Storage() storage.Storage

func (*AskRun) Subscribe

func (self *AskRun) Subscribe() (<-chan Event, func())

Subscribe replays what happened so far and then follows the run. The channel closes when the run is over.

func (*AskRun) Surface

func (self *AskRun) Surface() string

func (*AskRun) TabsAllowed

func (self *AskRun) TabsAllowed() bool

func (*AskRun) Usage

func (self *AskRun) Usage() llm.Usage

Usage is what the turn has spent so far, every round added up.

type AskSettings

type AskSettings struct {
	Agent      *models.Agent
	Owner      *models.User
	Operations Operations

	// Conversation is where the turn goes; the caller made or found it.
	Conversation *models.AgentConversation

	// Message is what the person said.
	Message string

	// Viewing is what they have open, when the drawer knows.
	Viewing *Viewing

	// Attachments are the files that came with the message, uploaded
	// already; References the threads the person pointed at.
	Attachments []*models.AgentAttachment
	References  []models.AgentReference

	// Pictures are images the caller puts in the turn itself rather than
	// files of the person's: a night looking at an attachment whose bytes
	// it fetched out of the store. They are shown to the model as the
	// same image parts a person's own picture is, and they belong to this
	// turn alone -- nothing stores them, so a later round names nothing.
	Pictures []llm.ContentPart

	// Surface is where the answer goes: drawer, phone, cli, api or mail.
	Surface string

	// Origin is the address the dashboard was reached at, scheme and host,
	// for a link to a file that has to open somewhere else; empty where the
	// turn did not come through it.
	Origin string

	// ReadOnly leaves out every tool that changes anything, for a
	// read-only credential.
	ReadOnly bool

	// ReadOnlyTools names the tools this turn may only look with, while
	// the rest of its kit acts as usual. Each call to one of them is
	// judged as it is made, so a tool whose actions differ -- memory,
	// which both reads a page and rewrites one -- keeps the half that
	// reads instead of going altogether.
	//
	// The night is what this is for: it has the person's whole kit, and
	// its changes to the graph are still said in the object it ends with
	// so that code files them with their evidence. That was enforced by
	// the whole turn being read-only until the turn stopped being
	// read-only, and a rule the frame merely asks for is a rule only
	// until a model reads the memory tool's description and takes it at
	// its word.
	ReadOnlyTools map[string]bool

	// Allow, when set, is the only tools offered by name; Headless adds
	// the remote tools marked for runs with nobody present. MaxRounds
	// overrides the limit; UsageKind names the usage rows.
	Allow     map[string]bool
	Headless  bool
	MaxRounds int

	// PreApproved is the calls the person approved on a card whose turn
	// had ended, by tool name and arguments: this turn may make each once
	// without asking again. See interaction.go.
	PreApproved map[string]bool

	// CanAsk says that a turn nobody typed may still put a question card
	// to the person: they have the dashboard open, and the turn is the
	// agent starting a conversation with them. Everything else about a
	// headless turn stands; only ask_user and confirmations may wait for
	// them.
	CanAsk    bool
	UsageKind string

	// Effort is how hard the model thinks before each round: "low",
	// "medium" or "high", or empty for the provider's default, which for
	// a newer model with tools is no reasoning at all.
	Effort string

	// Research gives the turn a procedure for answering a question about
	// the person's own work: search more than once and everywhere, read
	// the whole thread, prefer what their people wrote over what is
	// generally true, and say where the sources do not answer.
	Research bool

	// Work is the kind of work this turn is, which chooses the model: a
	// dream runs on the operator's scan model, sorting on the triage one.
	// Empty means the person's own choice, or the ask model, which is
	// what a turn somebody typed gets.
	Work config.AgentWork

	// ReadThenAnswer is a run that looks things up and then answers once:
	// a dream reading a batch, an ingest describing a checkout. Its
	// history is never compacted, because a compaction note would stand
	// in for the very documents it was given to read; when the history
	// fills, the run is told to answer now instead. ResultCharacters
	// bounds each lookup's answer for such a run, so a long page does not
	// fill the window by itself; zero means the usual bound.
	ReadThenAnswer   bool
	ResultCharacters int

	// Short asks for the one-paragraph conduct rather than the full rules.
	// A run with nobody present and six tools does not need the page about
	// how to talk to somebody, and sorting runs on every message that
	// arrives, so what the prompt costs is what sorting costs.
	Short bool
	// contains filtered or unexported fields
}

AskSettings is one turn of a conversation.

type AttachedComputer

type AttachedComputer struct {
	Name        string
	System      string
	Description string
	Since       time.Time
}

AttachedComputer is one attached computer of a person, for the API.

type BackgroundCommand added in v0.57.0

type BackgroundCommand struct {
	Computer string
	*computer.BackgroundStatus
	Origin tools.BackgroundOrigin
}

BackgroundCommand is one background command on one of a person's computers, for the API.

type Budget

type Budget struct {
	Used     int64
	Limit    int64 // 0 = unlimited
	ResetsAt time.Time

	// ServerUsed and ServerLimit are the monthly cap for the whole server.
	ServerUsed  int64
	ServerLimit int64

	// Cost and CostLimit are the same day said in money, at the prices
	// the providers are configured with; ServerCost and ServerCostLimit
	// the same for the month and the whole server. Currency is what the
	// operator says those prices are in, for whoever shows them.
	Cost            float64
	CostLimit       float64
	ServerCost      float64
	ServerCostLimit float64
	Currency        string
}

Budget is what a person may still spend today, and when the day turns. A budget can be said in tokens, in money, or in both; where both are set, whichever runs out first stops the day.

func CheckBudget

func CheckBudget(tx db.Transaction, configuration *config.Configuration, agent *models.Agent, owner *models.User, now time.Time) (*Budget, error)

CheckBudget reads today's spend for a person against their limit, and the month's against the server's. "Today" is midnight to midnight in the person's own zone, which is when the panel says it resets.

func (*Budget) Exhausted

func (self *Budget) Exhausted() bool

Exhausted says whether the next call should wait.

func (*Budget) NearlySpent

func (self *Budget) NearlySpent() string

NearlySpent is a line about the budget for the model, once four fifths of whichever cap binds first is gone, and "" while there is room. Money and tokens are said the way they are counted.

type Call

type Call = tools.Call

type Catalog

type Catalog = tools.Catalog

func FullCatalog

func FullCatalog() *Catalog

FullCatalog is every tool the agent can be given, before permissions and policy narrow it: what the worker runs with, and what the operator's tool policy lists.

type ComputerIdentity added in v0.50.0

type ComputerIdentity struct {
	Name   string
	System string
	Home   string

	// Description is the person's sentence about what the computer is for,
	// which the agent reads to choose between several; empty when they gave
	// none.
	Description string

	// Terminal is the session of the terminal the person attached it from,
	// when they did.
	Terminal string

	// Features are what the program offers beyond its protocol, such as
	// background commands.
	Features []string
}

ComputerIdentity is what a computer says about itself when it attaches.

type ConductData

type ConductData struct {
	AgentName         string
	PersonName        string
	ServerName        string
	Language          string
	Short             bool
	HouseInstructions string
	Instructions      string
	Voice             string
}

ConductData is what the conduct is rendered with.

type Deferral

type Deferral struct {
	Until  time.Time
	Reason string
}

Deferral is what a handler returns when a run must wait — for a budget, for a hold window — rather than fail.

func (*Deferral) Error

func (self *Deferral) Error() string

type DeviceConnection

type DeviceConnection interface {
	Send(message []byte) error
}

DeviceConnection is what the relay needs of a device's websocket.

type DraftInput

type DraftInput struct {
	Configuration *config.Configuration
	Agent         *models.Agent
	Owner         *models.User
	Mailbox       *models.Mailbox
	Source        *models.AgentMailbox
	Subject       string
	Instructions  string

	// Message is the one being answered; Earlier are the ones before it,
	// oldest first, as many as fit.
	Message *MessageContext
	Earlier []*MessageContext

	// Summary and Notes are what the agent already worked out about the
	// conversation and the message, when it has.
	Summary  string
	Notes    string
	Memories []string

	// Corrections are the replies this agent wrote that the person would
	// not let go: cancelled, or rewritten before they went. Shown as
	// examples of what not to write again.
	Corrections []string

	// Exemplars are the person's own past messages nearest in meaning to
	// this one: how they actually write to somebody about something like
	// this. Empty unless they have pointed the agent at their sent mail.
	//
	// Their own words rather than a description of them. A voice
	// described in fields says "friendly, brief"; five of their own
	// replies say how they open, how much they explain, and whether they
	// sign off at all.
	Exemplars []string
}

DraftInput is everything the draft prompt is built from.

type Event

type Event struct {
	Kind           EventKind `json:"kind"`
	RunID          string    `json:"runId"`
	ConversationID string    `json:"conversationId"`
	Sequence       int       `json:"sequence"`
	Text           string    `json:"text,omitempty"`
	Tool           string    `json:"tool,omitempty"`
	CallID         string    `json:"callId,omitempty"`
	Arguments      string    `json:"arguments,omitempty"`
	Risk           string    `json:"risk,omitempty"`
	Note           string    `json:"note,omitempty"`
	// NoteKind and NoteDetail are a note's kind and detail, for a client
	// that words it in the person's language; Note is it in English.
	NoteKind   string    `json:"noteKind,omitempty"`
	NoteDetail string    `json:"noteDetail,omitempty"`
	Error      string    `json:"error,omitempty"`
	At         time.Time `json:"at"`
}

Event is one thing that happened in a run.

type EventKind

type EventKind string

EventKind is what an event of a run carries.

const (
	EventAsked        EventKind = "asked"        // a turn began: what the person said, and where from
	EventText         EventKind = "text"         // a piece of the answer
	EventMessage      EventKind = "message"      // the whole answer, once it is
	EventToolCall     EventKind = "tool_call"    // the model asked for a tool
	EventToolResult   EventKind = "tool_result"  // the tool answered
	EventConfirmation EventKind = "confirmation" // waiting for the person
	EventQuestion     EventKind = "question"     // the agent asked something
	EventNote         EventKind = "note"         // compaction and the like
	EventTitled       EventKind = "titled"       // the conversation was given a title: Text
	EventDone         EventKind = "done"
	EventError        EventKind = "error"
)

The events a run emits, in the order a drawer shows them.

type ExtractAnswer

type ExtractAnswer struct {
	Events   []ExtractedEvent   `json:"events"`
	Contacts []ExtractedContact `json:"contacts"`
}

ExtractAnswer is the object the run answers with.

type ExtractedContact

type ExtractedContact struct {
	Name         string   `json:"name"`
	Organization string   `json:"organization"`
	Title        string   `json:"title"`
	Emails       []string `json:"emails"`
	Phones       []string `json:"phones"`
	Note         string   `json:"note"`
	ContactID    string   `json:"contact_id"`
	Because      string   `json:"because"`
}

ExtractedContact is somebody the words describe, usually a signature.

type ExtractedEvent

type ExtractedEvent struct {
	Summary  string `json:"summary"`
	Starts   string `json:"starts"`
	Ends     string `json:"ends"`
	Location string `json:"location"`
	AllDay   bool   `json:"all_day"`
	Because  string `json:"because"`
}

ExtractedEvent is an appointment the words describe.

type Family

type Family = tools.Family

type Handler

type Handler func(ctx context.Context, run *Run) error

Handler runs one kind of job. It returns nil when the job is done, a Deferral to wait for a budget, or an error to retry.

type MessageContext

type MessageContext struct {
	MailID      string
	From        string
	To          string
	Cc          string
	Date        string
	Subject     string
	ListKey     string
	Attachments []string
	Text        string
	Truncated   bool

	// Facts the server already established, in a line the model can use:
	// authentication results, whether the sender is a contact, whether a
	// filter flagged it.
	Facts []string
}

MessageContext is one message, reduced.

func BuildMessageContext

func BuildMessageContext(ctx context.Context, store storage.Storage, mail *models.Mail, maximumCharacters int, includeQuoted bool) (*MessageContext, error)

BuildMessageContext reads a stored message and reduces it.

func (*MessageContext) Render

func (self *MessageContext) Render() string

Render writes the context the way the prompts include it.

type Operations

type Operations = tools.Operations

Operations is the server as the person: every tool that touches the server goes through it, so a tool can do exactly what the person can do and nothing else. It is the API — the same operations the dashboard and the command line call, with the same permissions, validation and audit — handed to the agent by the package that owns them, executed as the person with the audit trail saying the agent did it.

type OperationsFactory

type OperationsFactory func(ctx context.Context, owner *models.User) (Operations, error)

OperationsFactory makes the API as a person, for a run nobody started from a request. The API package provides it.

type Proposal

type Proposal struct {
	Kind   string `json:"kind"`
	Path   string `json:"path"`
	To     string `json:"to"`
	Reason string `json:"reason"`
}

Proposal is something the night wants the person to decide.

type RecalledPage

type RecalledPage struct {
	Path string

	// Summary is the page's opening as the overlay carried it, or empty
	// where it carried none: a page the prompt's index already names.
	Summary string

	Facts []*models.AgentFact
}

RecalledPage is one page recall would carry and the facts it would carry from it.

type RememberAnswer

type RememberAnswer struct {
	Facts      []RememberedFact `json:"facts"`
	Links      []RememberedLink `json:"links"`
	Supersedes []SupersededFact `json:"supersedes"`
}

RememberAnswer is what the run answers with.

type RememberedFact

type RememberedFact struct {
	Path      string `json:"path"`
	NodeKind  string `json:"node_kind"`
	NodeName  string `json:"node_name"`
	Kind      string `json:"kind"`
	Text      string `json:"text"`
	Happened  string `json:"happened"`
	Quote     string `json:"quote"`
	MessageID string `json:"message_id"`
}

RememberedFact is one thing the conversation taught.

type RememberedLink struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Relation string `json:"relation"`

	// Note is the sentence that justifies the link, in the words somebody
	// would use to say it, including details the relation alone cannot carry.
	Note string `json:"note"`
}

RememberedLink joins two pages.

type ReplyAnswer

type ReplyAnswer struct {
	Reply  *string `json:"reply"`
	Reason *string `json:"reason"`
}

ReplyAnswer is what the model answers: a reply, or a reason not to.

type Result

type Result = tools.Result

type ResumeSettings added in v0.61.4

type ResumeSettings struct {
	Interaction  *models.AgentInteraction
	Answer       string
	Agent        *models.Agent
	Owner        *models.User
	Operations   Operations
	Conversation *models.AgentConversation
}

ResumeSettings is what a late answer needs to carry on: the card, what the person said, and who they are to the API.

type Risk

type Risk = tools.Risk

type Run

type Run struct {
	Job     *models.AgentJob
	Agent   *models.Agent
	Owner   *models.User
	Mailbox *models.Mailbox
	Source  *models.AgentMailbox

	// Now is the moment the tick that claimed the job ran as of, so that a
	// hold or a deferral is judged against the same clock that claimed it.
	Now time.Time

	// Subject is what a run no job queued is about -- the message a draft
	// answers, the conversation being titled or compacted -- so that its
	// transcript names it as a job's would.
	Subject string
	// contains filtered or unexported fields
}

Run is one job with what every handler needs resolved: the agent, its owner, and the mailbox the job is about.

func (*Run) Configuration

func (self *Run) Configuration() *config.Configuration

Configuration is the operator's configuration as of this tick.

func (*Run) Database

func (self *Run) Database() db.Database

Database is the run's database.

func (*Run) Registry

func (self *Run) Registry() *llm.Registry

Registry is the run's models.

func (*Run) Storage

func (self *Run) Storage() storage.Storage

Storage is the run's message store.

type RunCommand

type RunCommand struct {
	// Instance is who said it, filled in on the way out.
	Instance string `json:"instance"`
	RunID    string `json:"runId"`
	// Action is "stop", "answer" or "resolve".
	Action  string `json:"action"`
	CallID  string `json:"callId,omitempty"`
	Answer  string `json:"answer,omitempty"`
	Approve bool   `json:"approve,omitempty"`
}

RunCommand is one word to a run.

type Settings

type Settings struct {
	Database db.Database
	Storage  storage.Storage
	Registry *llm.Registry

	// Exchange runs the rules that wait for an insight, and climbs the
	// out-of-office ladder for the agent. Nil in tests that have no mail
	// path.
	Exchange mx.Exchange

	// Mailer composes and sends what the agent writes. Set after the
	// mailer exists, which is after the worker does; nil until then.
	Mailer mailer.Mailer

	// Configuration is read at the start of every tick, so an operator's
	// change to a limit or a feature applies without a restart.
	Configuration func() *config.Configuration

	// Instance names this server instance on the jobs it claims.
	Instance string

	// Tick is how often the worker looks for work. Zero means five seconds.
	Tick time.Duration
}

Settings is what the agent needs.

type SummarizeInput

type SummarizeInput struct {
	Configuration *config.Configuration
	Agent         *models.Agent
	Owner         *models.User
	Mailbox       *models.Mailbox
	Source        *models.AgentMailbox
	Subject       string

	// Previous is the summary so far, empty the first time; Messages are
	// the ones it does not cover, oldest first.
	Previous string
	Messages []*MessageContext
	Memories []string
}

SummarizeInput is everything the summarize prompt is built from.

type SupersededFact

type SupersededFact struct {
	Path   string `json:"path"`
	Number int    `json:"number"`

	// ReplacedBy is which of this answer's facts replaces it, counting
	// from 1. Without it, any fact the answer filed on the page stood in
	// for the line being retired, whatever it said: a fact about something
	// else retired a true one. Nil for a retraction, which carries a quote
	// instead.
	ReplacedBy *int `json:"replaced_by"`

	// Quote and MessageID are what says the line is no longer true, for a
	// retirement that files nothing in its place.
	//
	// "I go to a different dentist now" retires what the page says about
	// the dentist without saying who the new one is, and that is a real
	// thing for somebody to say. What it cannot be is a retirement nobody
	// said: without these, an answer naming a fact retired it on the
	// strength of naming it, and an answer carrying nothing else could
	// empty a page. Checked exactly as a fact's citation is -- the words
	// have to occur in something the run was actually shown.
	Quote     string `json:"quote"`
	MessageID string `json:"message_id"`
}

SupersededFact is a fact this conversation has replaced.

type TabConnection

type TabConnection = DeviceConnection

TabConnection is what the relay needs of the extension's websocket.

type Tool

type Tool = tools.Tool

type TriageAnswer

type TriageAnswer struct {
	Category    string   `json:"category"`
	Priority    string   `json:"priority"`
	NeedsReply  bool     `json:"needs_reply"`
	Research    bool     `json:"research"`
	Extract     bool     `json:"extract"`
	Summary     string   `json:"summary"`
	ActionItems []string `json:"action_items"`
}

TriageAnswer is the JSON the model is asked for.

type TriageInput

type TriageInput struct {
	Configuration *config.Configuration
	Agent         *models.Agent
	Owner         *models.User
	Mailbox       *models.Mailbox
	Source        *models.AgentMailbox
	Message       *MessageContext
	Memories      []string
	Corrections   []string
	ResearchNotes []string

	// Tools says the run may look things up before it answers, which
	// changes what the prompt asks for: the same object, after as many
	// lookups as it needs.
	Tools bool
}

TriageInput is everything the prompt is built from, so the prompt can be rendered and tested without a database.

type Viewing

type Viewing struct {
	ItemID      string `json:"itemId,omitempty" graphapi:"nullable"`
	ThreadID    string `json:"threadId,omitempty" graphapi:"nullable"`
	Subject     string `json:"subject,omitempty" graphapi:"nullable"`
	MailboxID   string `json:"mailboxId,omitempty" graphapi:"nullable"`
	MailboxName string `json:"mailboxName,omitempty" graphapi:"nullable"`
	FolderID    string `json:"folderId,omitempty" graphapi:"nullable"`
	FolderName  string `json:"folderName,omitempty" graphapi:"nullable"`
	Page        string `json:"page,omitempty" graphapi:"nullable"`

	// ListKey and ListName are the mailing list open on the subscriptions
	// page, which the subscription tool acts on by key.
	ListKey  string `json:"listKey,omitempty" graphapi:"nullable"`
	ListName string `json:"listName,omitempty" graphapi:"nullable"`
}

Viewing is what the person has open in the dashboard.

Source Files

Directories

Path Synopsis
Package feedback records corrections for subsequent agent work.
Package feedback records corrections for subsequent agent work.
Package indexed is searching and reading what a person's sources put in front of their agent: the documents a pass read, and the passages they were cut into.
Package indexed is searching and reading what a person's sources put in front of their agent: the documents a pass read, and the passages they were cut into.
Package reading is how far the night has got through what was indexed: one measure that the API, the command line and the knowledge tool share, in a package of its own because the tool cannot import the agent.
Package reading is how far the night has got through what was indexed: one measure that the API, the command line and the knowledge tool share, in a package of its own because the tool cannot import the agent.
Package tools is the agent's tool kit: what a tool is, what a call and a result are, the catalog with its permissions and policy, and the registry every tool package registers into from its own init.
Package tools is the agent's tool kit: what a tool is, what a call and a result are, the catalog with its permissions and policy, and the registry every tool package registers into from its own init.
account
Package account is the person's own account: profile, tokens, sessions, app passwords, and what their permissions let them do.
Package account is the person's own account: profile, tokens, sessions, app passwords, and what their permissions let them do.
agentprofile
Package agentprofile is the agent's own profile, as the person tells it in conversation: what it is called, which language it talks in, and the lines the person wants added to its standing instructions.
Package agentprofile is the agent's own profile, as the person tells it in conversation: what it is called, which language it talks in, and the lines the person wants added to its standing instructions.
all
Package all imports every tool package, so that importing it is importing the catalog.
Package all imports every tool package, so that importing it is importing the catalog.
artifact
Package artifact is what the agent makes for the person to open beside the conversation: a page, a drawing or a document it wrote, kept as a file of the conversation, served to its owner alone and in a sandbox.
Package artifact is what the agent makes for the person to open beside the conversation: a page, a drawing or a document it wrote, kept as a file of the conversation, served to its owner alone and in a sandbox.
askuser
Package askuser is the question to the person, for when the answer changes what happens.
Package askuser is the question to the person, for when the answer changes what happens.
browser
Package browser is the agent's browser: a page in the operator's headless Chrome, signed in as nobody, read as a tree with [ref=N] on everything that can be acted on; or, with target tab, the person's own attached tab, with their session, while they watch.
Package browser is the agent's browser: a page in the operator's headless Chrome, signed in as nobody, read as a tree with [ref=N] on everything that can be acted on; or, with target tab, the person's own attached tab, with their session, while they watch.
calendar
Package calendar is what the agent knows about its person's diary: what they have on, when they are free, and -- asking first -- putting something in.
Package calendar is what the agent knows about its person's diary: what they have on, when they are free, and -- asking first -- putting something in.
coding
Package coding hands a piece of work to a coding agent on the person's own computer.
Package coding hands a piece of work to a coding agent on the person's own computer.
computer
Package computer is the person's own computer, when they attached one with `teanode computer`: a shell to run a command in, and its files to read, write, list and search, as the person, anywhere on it.
Package computer is the person's own computer, when they attached one with `teanode computer`: a shell to run a command in, and its files to read, write, list and search, as the person, anywhere on it.
connected
Package connected is the tool for the servers that speak the Model Context Protocol: what the operator has declared, what this person has connected, and the two steps of setting one up.
Package connected is the tool for the servers that speak the Model Context Protocol: what the operator has declared, what this person has connected, and the two steps of setting one up.
contact
Package contact is the person's address book: the people they keep.
Package contact is the person's address book: the people they keep.
conversation
Package conversation is how the agent reaches what was said before: the other conversations this person has with it, and the transcripts of the runs nobody watched.
Package conversation is how the agent reaches what was said before: the other conversations this person has with it, and the transcripts of the runs nobody watched.
datetime
Package datetime is the agent's time arithmetic: now, a conversion between zones, a duration added, the difference between two times, a phrase such as "next Tuesday 3pm" read in the person's zone.
Package datetime is the agent's time arithmetic: now, a conversion between zones, a duration added, the difference between two times, a phrase such as "next Tuesday 3pm" read in the person's zone.
domain
Package domain is the operator's domains and their delivery: domains, addresses, sending credentials, the queue.
Package domain is the operator's domains and their delivery: domains, addresses, sending credentials, the queue.
folder
Package folder lists and manages a mailbox's folders.
Package folder lists and manages a mailbox's folders.
goal
Package goal is the conversation's standing instruction: the sentence the agent keeps working toward across turns of its own, and the one tool that says where it is with it.
Package goal is the conversation's standing instruction: the sentence the agent keeps working toward across turns of its own, and the one tool that says where it is with it.
idea
Package idea is the agent's list of ideas for the person, as the agent manages it in conversation: what is on offer, one it found for them, one they took up, finished or do not want.
Package idea is the agent's list of ideas for the person, as the agent manages it in conversation: what is on offer, one it found for them, one they took up, finished or do not want.
knowledge
Package knowledge is the tool for what the person pointed their agent at: their checkout, their chat archive, their notes, their wiki.
Package knowledge is the tool for what the person pointed their agent at: their checkout, their chat archive, their notes, their wiki.
mailact
Package mailact acts on messages: marks, stars, files, junks, trashes.
Package mailact acts on messages: marks, stars, files, junks, trashes.
mailaudit
Package mailaudit is the mail audit as tools: search, one message, its content, marks, and the reports.
Package mailaudit is the mail audit as tools: search, one message, its content, marks, and the reports.
mailbox
Package mailbox is what the mailbox tools share: the person's mailboxes and folders as the API lists them, a conversation and a message's content as the tools read them.
Package mailbox is what the mailbox tools share: the person's mailboxes and folders as the API lists them, a conversation and a message's content as the tools read them.
mailboxsettings
Package mailboxsettings renames a mailbox or sets its signature.
Package mailboxsettings renames a mailbox or sets its signature.
mailcomposehelp
Package mailcomposehelp writes the body of a reply for the person to use, without saving anything.
Package mailcomposehelp writes the body of a reply for the person to use, without saving anything.
maildraft
Package maildraft writes a draft into Drafts for the person to send.
Package maildraft writes a draft into Drafts for the person to send.
mailread
Package mailread reads a message, or the conversation it belongs to, as text the model can weigh.
Package mailread reads a message, or the conversation it belongs to, as text the model can weigh.
mailsearch
Package mailsearch finds messages by words, by meaning where it exists, and by what the agent decided about them.
Package mailsearch finds messages by words, by meaning where it exists, and by what the agent decided about them.
mailsend
Package mailsend sends a draft, with the person's word.
Package mailsend sends a draft, with the person's word.
memory
Package memory is the tool the agent keeps what it knows about the person with: a graph of pages, each addressed by a path, with facts on them and links between them.
Package memory is the tool the agent keeps what it knows about the person with: a graph of pages, each addressed by a path, with facts on them and links between them.
memorycheck
Package memorycheck is the memory check as the agent runs it in conversation: drafting questions from what it remembers about the person, putting them one at a time, and recording what the person says.
Package memorycheck is the memory check as the agent runs it in conversation: drafting questions from what it remembers about the person, putting them one at a time, and recording what the person says.
note
Package note is the person's notes, as the agent keeps them for them: the ones their phone's Notes app keeps in their mailbox.
Package note is the person's notes, as the agent keeps them for them: the ones their phone's Notes app keeps in their mailbox.
operator
Package operator is what the operator's tools share: a document run as the person with its answer as a map, and the domains the person manages as the API lists them.
Package operator is what the operator's tools share: a document run as the person with its answer as a map, and the domains the person manages as the API lists them.
people
Package people is the operator's people and access: accounts, groups, roles, and the audit log.
Package people is the operator's people and access: accounts, groups, roles, and the audit log.
reminder
Package reminder is the person's reminders list, as the agent keeps it for them: the list beside their calendar that their phone's Reminders app syncs.
Package reminder is the person's reminders list, as the agent keeps it for them: the list beside their calendar that their phone's Reminders app syncs.
replyqueue
Package replyqueue is the replies the agent holds on the person's behalf, and the <pending> overlay that lists them.
Package replyqueue is the replies the agent holds on the person's behalf, and the <pending> overlay that lists them.
rule
Package rule is the mailbox's rules as tools: listed, added, changed, removed, tried and applied.
Package rule is the mailbox's rules as tools: listed, added, changed, removed, tried and applied.
schedule
Package schedule is the tool the agent keeps its own times with: a prompt run on a cron line, at one moment, or a distance from now, in the person's zone, with nobody present.
Package schedule is the tool the agent keeps its own times with: a prompt run on a cron line, at one moment, or a distance from now, in the person's zone, with nobody present.
server
Package server is the server itself: its status, its settings, an upgrade.
Package server is the server itself: its status, its settings, an upgrade.
share
Package share is how the agent hands the person a file: the photo on a message, a file from their computer, something already in the conversation.
Package share is how the agent hands the person a file: the photo on a message, a file from their computer, something already in the conversation.
subscription
Package subscription is the mailing lists a mailbox receives and the ways out of each.
Package subscription is the mailing lists a mailbox receives and the ways out of each.
todo
Package todo is a conversation's task list: the agent's own, laid out when a piece of work has several steps and kept as it goes, so the agent keeps its place and the person watches its progress.
Package todo is a conversation's task list: the agent's own, laid out when a piece of work has several steps and kept as it goes, so the agent keeps its place and the person watches its progress.
toolsearch
Package toolsearch loads tools that are listed but not sent, when the catalog is long: the model names what it wants to do and the matching tools join the request from the next round.
Package toolsearch loads tools that are listed but not sent, when the catalog is long: the model names what it wants to do and the matching tools join the request from the next round.
webfetch
Package webfetch reads a web page as text for the agent: a public one through this server, with the same guarded fetcher the rest of the server uses, or any one through a computer the person attached, on the networks that computer is on.
Package webfetch reads a web page as text for the agent: a public one through this server, with the same guarded fetcher the rest of the server uses, or any one through a computer the person attached, on the networks that computer is on.
websearch
Package websearch asks the search service the operator configured.
Package websearch asks the search service the operator configured.

Jump to

Keyboard shortcuts

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