tools

package
v0.252.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 26 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 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. A tool reaches the run it is part of — the person, the agent, the database, the operations — through the context, never through the loop's own types, so a tool package imports this package and nothing above it.

Index

Constants

View Source
const AttachmentPageCharacters = 60000

AttachmentPageCharacters is how much of a file's text one view of it holds: what a turn shows of a file the person attached, and what one read_attachment gives. The rest is read on from next_offset, so a long file is read through, never cut.

View Source
const CutNoteKey = "cutNote"

CutNoteKey is the field a fitted answer says what was left out in.

View Source
const DeferralThreshold = 40

DeferralThreshold is how many definitions go in a request before the rest wait behind tool_search: forty is what a model keeps straight, as measured by replaying real tool searches. It is not a cap on what the agent can use: every tool past it is one tool_search away.

View Source
const HerdrFileBytes = 32 << 20

HerdrFileBytes bounds the files one herdr send carries, together: they cross to the computer in the request itself.

View Source
const HiddenPrivateWords = "[hidden: from a turn that used Health or Passwords]"

HiddenPrivateWords stands for what the agent or one of its tools said in a private turn, wherever a run is shown the conversation without it.

View Source
const IntentionArgument = "intention"

IntentionArgument is the argument every tool is offered for those words. It is taken off the call before the tool runs, so no tool sees it.

View Source
const PictureLargest = 8 << 20

PictureLargest is the largest picture this program sends to a model.

Smaller than the twenty-five megabytes a scan will carry off a person's machine, because carrying a file and paying to look at it are different questions: a four-thousand-pixel screenshot costs several times what a thousand-pixel one does and says the same thing. Anything above this is passed over with its reason rather than spent on.

One number for the night and for the conversation on purpose. A look the person asked for costs what the night's own look costs, so a picture the night was willing to open is one the agent can open again when they ask about it, and a picture it refused is refused the same way to their face rather than silently costing more.

View Source
const ResultCharacters = 24000

ResultCharacters bounds a tool's answer as the history keeps it and as a tab's answer is cut.

View Source
const ResultMoreName = "result_more"

ResultMoreName is the tool that reads on in a result that was too long for one answer.

View Source
const (
	// SearchLoadedLimit is how many tools a ranked search loads when the
	// model does not say how many. A model that asks for more gets more,
	// and one that names its tools gets every one it names.
	SearchLoadedLimit = 5
)

How tool_search ranks the catalog.

A word counts by how rare it is in the catalog: "get", "search" and "list" are in most descriptions, so they say little, while "calendar" or "dns" picks out the few tools that are about it. A word in a tool's name counts for more than one in its family, and that for more than one in its description (BM25F). A query that names a tool, by its whole name or by every word of it, puts that tool first, since the prompt lists the tools that wait by name and a model often asks for one of them.

What is loaded is only the matches close to the best one. Every tool loaded is in every request for the rest of the turn, and a search used to load every tool sharing a word with the query: six a search, of which the model called about one in ten. When the best match is a tool the model holds already, a weak match behind it is not worth a definition in every request, so it is measured against that tool too.

View Source
const SharedPageMarker = "[from a page another person shared with you: cite it, never write it down]"

SharedPageMarker begins a tool result that carries words from a page another person shared. The line is in the result the model reads and in the message the conversation stores, which is how the run that files what a conversation taught can tell shared words from the person's own: it refuses a fact whose only evidence is text after the marker, because shared knowledge is read where it lives and never copied.

View Source
const SharedPageRefusal = "this came from a page another person shared; cite it instead of writing it down"

SharedPageRefusal is what a note resting on a shared page is refused with, by the memory tool and by the run that files a conversation.

View Source
const SharedRecordingMarker = "[from a recording another person shared with you: cite it, never write it down]"

SharedRecordingMarker begins a tool result that carries words from a recording another person shared, which are read where they live and never copied, like a shared page. The run that files what a conversation taught treats what follows it as it treats what follows SharedPageMarker.

Variables

View Source
var ErrDeviceDetached = errors.New("was detached")

ErrDeviceDetached is a device's connection ending while a request to it was open, or before the request could be sent: whether the device did what it was asked is not known.

View Source
var ErrLeftOpen = errors.New("the person has not answered yet; the card stays open")

ErrLeftOpen is what Run.Ask answers when the person did not answer while the turn waited: the question card stays open for them, and a late answer starts a new turn with it.

View Source
var Renamed = map[string]string{
	"domain_list": "domain", "domain_get": "domain", "domain_add": "domain",
	"domain_update": "domain", "domain_remove": "domain", "domain_dns_check": "domain",
	"alias_list": "alias", "alias_match": "alias", "alias_add": "alias",
	"alias_update": "alias", "alias_remove": "alias",
	"credential_list": "credential", "credential_create": "credential",
	"credential_update": "credential", "credential_remove": "credential",
	"queue_list": "queue", "queue_retry": "queue",
	"rule_list": "rule", "rule_add": "rule", "rule_update": "rule",
	"rule_remove": "rule", "rule_test": "rule", "rule_apply": "rule",
	"user_list": "user", "user_add": "user", "user_update": "user", "user_remove": "user",
	"calendar_agenda": "calendar", "calendar_free": "calendar", "calendar_add": "calendar",
	"calendar_edit": "calendar", "calendar_remove": "calendar",
	"mail_audit_search": "mail_audit", "mail_audit_get": "mail_audit",
	"mail_audit_content": "mail_audit", "mail_audit_mark": "mail_audit",
	"account_get": "account", "account_update": "account",
	"settings_get": "settings", "settings_update": "settings",
}

Renamed maps the names the catalog used before its tools were merged to what they are called now.

An operator's policy and a person's own "always ask me" list are written down by name (agent.tools.disabled, agent.tools.confirm, and the agent's Confirm), and those lists were written when every verb had a name of its own. A list naming domain_remove means what it meant: do not let this happen. Because the verb is an action now, the whole tool is what the name resolves to -- so a policy that switched one verb off switches its tool off. That is broader than what was asked for and never narrower, which is the direction a policy may safely be wrong in, and the release notes say so.

Functions

func ActionOf

func ActionOf(arguments json.RawMessage) string

ActionOf is the "action" of a call's arguments, lowercased, for a tool whose risk depends on it. Read from the JSON, never by looking for the word inside it: a name or a title containing "delete" is not a delete.

func ActionsOf

func ActionsOf(tool *Tool) []string

ActionsOf is the verbs a tool takes, read out of its own schema: the values of its "action" enumeration, in the order they are offered.

From the schema rather than from a field, because a tool is action-shaped whether it was merged out of several tools or written that way in the first place. The policy page listed the verbs of the merged ones and nothing beside group_manage, which takes add, update and remove of its own -- so the page looked as though the two kinds of tool differed, and they do not.

Empty for a tool that is one thing, and for one whose action is free text rather than a choice.

func AllowedByPermissions

func AllowedByPermissions(tool *Tool, permissions *models.EffectivePermissions) bool

AllowedByPermissions says whether the person holds one of the permissions a tool asks for.

func AnswersSkillShareCall added in v0.170.0

func AnswersSkillShareCall(commandLine string) bool

AnswersSkillShareCall says a command line, as typed into a shell, looks like `teanode agent skill approve` or `teanode agent skill decline`, the commands that answer a call somebody's agent made through a skill the person shared, which waits for the person's own word and spends their money when approved.

A courtesy and not the guard. It is a guess over words and not a parse of the shell: quotes, separators and substitutions are turned into spaces, and the words agent, skill and approve or decline must come in that order with a few words between them. It errs toward asking, so that a shell that looks like it is answering a call asks the person first, as money. What it cannot see, a command assembled from pieces or typed into a terminal a key at a time, it cannot hold, and it does not have to: the server refuses to approve a call, or to lend money, to anything but the dashboard's session or the phone app's own sign-in (AnswerSkillShareCall, ShareSkill), whoever typed the command and however they wrote it.

func ArrayProperty

func ArrayProperty(description string, items map[string]any) map[string]any

func BooleanProperty

func BooleanProperty(description string) map[string]any

func CanLeaveRunning added in v0.112.0

func CanLeaveRunning(run Run) bool

CanLeaveRunning says the run may leave a command running past its wait: any run but one whose conversation is a run's own transcript, which has nothing to be woken in when the command ends. A schedule's or a goal's turn is woken where it ran, as the person's is; a call with no conversation at all -- a harness, the command line -- is told the command's id and reads it itself.

func CleanIntention added in v0.236.0

func CleanIntention(words string) string

CleanIntention is the words fit to show, or "": one line, short, with nothing in it that reads as markup or a link.

func ConfirmationReasons added in v0.113.0

func ConfirmationReasons(tool *Tool, arguments json.RawMessage, policy *config.AgentTools, agent *models.Agent) []models.UnattendedRisk

ConfirmationReasons are why a call must wait for the person, in the words the person allows them by for when they are not there: its risk class, and whether it is on their own list or the operator's, which no person can allow. None when it need not wait.

func ConversationIDOf added in v0.49.0

func ConversationIDOf(run Run) string

ConversationIDOf is the conversation a run is part of, or empty when it is part of none: the night, and a call from a harness over the protocol.

Every tool reads it through here rather than as Conversation().ID. That form dereferenced a nil conversation, and through the protocol it took down the request: the harness saw its connection dropped, with no answer and no error.

func CutText added in v0.120.2

func CutText(text string, budget int) string

CutText is text within budget bytes, cut where a character starts, with a mark saying how many more characters there were.

func DecodeArguments

func DecodeArguments[T any](call *Call) (T, error)

DecodeArguments reads a call's arguments, repairing what a model mangled.

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 whole reason the bytes are kept rather than fetched when they are wanted: this answers with the laptop they came from shut and the person asleep, which is when the reading happens.

func DurationWords

func DurationWords(difference time.Duration) string

func EncodeJSON added in v0.120.2

func EncodeJSON(value any) string

EncodeJSON writes a value as JSON without escaping <, > and &, which would make markup six times its length for nothing. A tool that measures its answer against a budget measures it with this, so that what it measured is what is sent.

func EnumProperty

func EnumProperty(description string, values ...string) map[string]any

func FeatureAllowed

func FeatureAllowed(configuration *config.Configuration, feature string) bool

FeatureAllowed says whether the deployment offers a feature at all: the agent switched on, and the feature not switched off by the operator.

func FirstWords

func FirstWords(text string, count int) string

FirstWords is the first few words of a text, with a mark where it goes on.

func FitJSON added in v0.120.2

func FitJSON(answer []byte, budget int) string

FitJSON is an answer within budget bytes and still JSON. Whole when it fits. Otherwise, for an object, its largest strings are cut and its largest lists shortened, at any depth, each marked and named in the cutNote field, and every other field is kept as it was. A list is never shortened past one entry: that entry is cut instead. What is not an object is cut as text, with a mark saying how much more there was.

func GranteeWords added in v0.170.0

func GranteeWords(ctx context.Context, with string) string

GranteeWords says who a with argument names, for a confirmation card: the username, or the circle with its name in quotes and how many people it is, so that a circle's id is never what the person is asked to approve. When it cannot be looked up the argument is quoted as it was given.

func HTMLToText

func HTMLToText(html string) string

HTMLToText reduces HTML to the text a person would read: block elements become line breaks, links keep their text, everything in a script or a style goes.

func HeldToChat added in v0.170.0

func HeldToChat(run Run) string

HeldToChat is the id of the only conversation the run may read, or empty when the run is not held to a chat.

func HerdrFilesOf added in v0.164.0

func HerdrFilesOf(ctx context.Context, database db.Database, files storage.Storage, agentId, conversationId string, attachmentIds []string) ([]*computer.HerdrFile, error)

HerdrFilesOf reads the agent's files a herdr send carries, by attachment id. With a conversation, only that conversation's files and those not yet given to any are the agent's to send, as for the filesystem tool's put; the person's own call names any of their agent's files.

func HoldsAll added in v0.172.0

func HoldsAll(permissions *models.EffectivePermissions, required []models.Permission) bool

HoldsAll says whether the person holds every one of the permissions.

func In

func In(where string) string

In is " in <where>", or nothing: where a call names a mailbox or a domain the card says which, and where it does not there is only one to mean.

func IntegerProperty

func IntegerProperty(description string) map[string]any

func IntentionOf added in v0.236.0

func IntentionOf(arguments string) string

IntentionOf is the cleaned intention a call's arguments carry, or "".

func IsAnsweringInChat added in v0.170.0

func IsAnsweringInChat(run Run) bool

IsAnsweringInChat says the run's words go to the room of a chat, so that a tool does not tell it to say in them what is for the person alone.

func IsImage

func IsImage(contentType string) bool

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

func IsOneMoment added in v0.58.7

func IsOneMoment(expression string) bool

IsOneMoment says a schedule's line is a single moment, "@at" and a time, rather than one that repeats.

func IsPrivateToolCall added in v0.193.0

func IsPrivateToolCall(call models.AgentToolCall) bool

IsPrivateToolCall says whether a tool call is one of the private tools, as the model calls it (health, or passwords with an action) or by the name of one of its actions (health_summary, passwords_read_note).

func IsStartedByPerson added in v0.193.0

func IsStartedByPerson(run Run) bool

IsStartedByPerson says whether the person started the run. A run that cannot say is taken not to be theirs.

func IsStartedByPersonOrProgram added in v0.207.2

func IsStartedByPersonOrProgram(run Run) bool

IsStartedByPersonOrProgram says the person started the run, or a program they connected over MCP called it. A run that cannot say is neither.

func IsTurnStart added in v0.193.0

func IsTurnStart(messages []*models.AgentMessage, index int) bool

IsTurnStart says whether the message at index begins a turn: it is a message of the person, and not one they steered into the running turn.

func Listed

func Listed(entries []string, tool *Tool) bool

Listed says whether a policy list names the tool, by name or family, or by a name one of its actions used to have.

func LocalReadOnly added in v0.120.0

func LocalReadOnly() *mcp.ToolAnnotations

LocalReadOnly are the annotations of a tool an MCP client should run without asking: read-only, and reaching only the person's own machines. Claimed only where the person asked for it of a tool that does more.

func Location

func Location(user *models.User) *time.Location

Location is the zone a person's times are told in: their own, or the server's when they have none yet.

func MarkRecordingEvidence added in v0.144.4

func MarkRecordingEvidence(run Run)

MarkRecordingEvidence signals trusted recording provenance without parsing model text.

func MustJSON

func MustJSON(value any) json.RawMessage

MustJSON encodes a value the code built itself.

func Named

func Named(value, stand string) string

Named is how a card points at a thing: what the person calls it, in quotes, or a stand-in when the call gives no name.

func NeedsConfirmation

func NeedsConfirmation(tool *Tool, arguments json.RawMessage, policy *config.AgentTools, agent *models.Agent) bool

NeedsConfirmation says whether a call must wait for the person: the risk class first, then the operator's list, then the person's own. Without arguments it answers for the tool as a whole.

func NextCron

func NextCron(expression string, after time.Time, location *time.Location) (time.Time, error)

NextCron is the first moment after the given one that a cron line admits, in the zone, or zero when none is found in four years.

func NormalizeText

func NormalizeText(text string) string

NormalizeText squares the line endings, trims trailing blanks and collapses runs of blank lines.

func NumberProperty added in v0.175.0

func NumberProperty(description string) map[string]any

func Object

func Object(properties map[string]any, required ...string) map[string]any

func OpenWorldRead added in v0.74.4

func OpenWorldRead() *mcp.ToolAnnotations

OpenWorldRead are the annotations of a tool that changes nothing and reaches beyond this server to read: the web, a search service.

func PageOfText added in v0.242.0

func PageOfText(text string, offset, limit int) (string, int)

PageOfText is the part of a text from offset, at most limit characters, and where the next part starts, or zero when this is the end. Counted in characters, so a part never ends inside one.

func PageResult added in v0.242.0

func PageResult(ctx context.Context, run Run, text string, isUntrusted, isError bool) string

PageResult is a tool's text as one answer carries it. A text within what the run keeps of a result (ResultCharactersOf) comes back whole. A longer one is held whole, and what comes back is its first page, cut at a character and preferably at a line break, and a line saying how long the whole result is and how to read on with result_more. Nothing is dropped.

The holder is the agent, so that a result can be read on in a later turn of the same conversation and never by anybody else. When the result cannot be held (a database that cannot be written, a result larger than one holder may keep) the line says so, rather than promising a way on.

func ParseDuration

func ParseDuration(value string) (time.Duration, error)

ParseDuration reads 3d, 2h30m, -1w and Go's own forms.

func ParseMoment

func ParseMoment(text string, location *time.Location) (time.Time, error)

ParseMoment reads a date and time the way a person writes one, in their zone unless the text carries its own offset.

func ParsePhrase

func ParsePhrase(text string, location *time.Location, now time.Time) (time.Time, error)

ParsePhrase reads the phrases people write: today, tomorrow, yesterday, next Monday, in 3 days, 3pm, and a clock time after any of them.

func ParseTime

func ParseTime(value string, location *time.Location, now time.Time) (time.Time, error)

ParseTime reads an ISO time, or a date, or a date and a time, in the given zone; empty is now.

func PermissionWords

func PermissionWords(permissions *models.EffectivePermissions) string

PermissionWords says what the person may do, in words.

func PreviewOf

func PreviewOf[T any](say func(T) string) func(json.RawMessage) string

PreviewOf builds a tool's Preview from a function of its arguments, so that a card is written as the sentence it is rather than as JSON handling. Arguments that will not decode give the tool's own words back through the fallback, because a card is shown before anything runs and must say something either way.

func PrivateTurns added in v0.193.0

func PrivateTurns(messages []*models.AgentMessage) []bool

PrivateTurns says, for each message, whether it belongs to a turn in which a private tool was called. A turn runs from a message of the person to the next one, and one call of such a tool anywhere in it makes every assistant and tool message of it private: the text it read, and what the agent said about it. The first stretch, before any message of the person, is a turn too: a window that starts after a mark may begin in the middle of one.

func ReadResultMore added in v0.242.0

func ReadResultMore(ctx context.Context, run Run, id string, offset int) (page string, isUntrusted bool, err error)

ReadResultMore is the next page of a result PageResult held: from offset, as long as a page is, with the line saying how to read on when there is more. isUntrusted says whether the result came from outside, for the caller to mark.

func RecordGoalArtifact added in v0.111.0

func RecordGoalArtifact(ctx context.Context, goalArtifactKind models.AgentGoalArtifactKind, artifactReference, artifactTitle string)

RecordGoalArtifact notes that a turn on a goal made something that carries no conversation of its own -- a mail rule, a reminder, an alert mute -- so the goal can show it among what it made. Nothing is written for a turn in any other conversation, and a failure to note it is logged rather than failing what was made.

func RecordingEvidenceOf added in v0.144.4

func RecordingEvidenceOf(transaction db.Transaction, agentId string, evidence []models.Evidence) (bool, error)

RecordingEvidenceOf refuses missing or unreadable provenance instead of treating it as trusted authority.

func Register

func Register(factory func() []*Tool)

Register adds a factory. Called from a tool package's init.

func Rename

func Rename(names []string) []string

Rename maps a list of tool names onto what those tools are called now, keeping the order and dropping the duplicates a merge creates: a policy naming rule_add and rule_remove names the rule tool once.

func ReplySubject

func ReplySubject(subject string) string

ReplySubject is the answer's subject: the original's with one Re:.

func RequireServices added in v0.139.0

func RequireServices(tool *Tool, configuration *config.Configuration) error

RequireServices checks current operator choices again at invocation.

func RequiredServices added in v0.139.0

func RequiredServices(tool *Tool) []models.Service

RequiredServices is the hosted policy of an internal tool. Remote tools do not inherit hosted-service requirements from their names.

func Reset

func Reset()

Reset forgets every factory, for a test that registers its own.

func ResolveRelative

func ResolveRelative(expression string, now time.Time, location *time.Location) (string, error)

ResolveRelative turns "@in 5m" into the "@at" moment it means from now, so the schedule stores a moment and not a distance that would move with every look. Anything else is returned as it came.

func ResultCharactersOf added in v0.106.1

func ResultCharactersOf(run Run) int

ResultCharactersOf is how much of a tool's result a run keeps, in bytes, as the run measures it.

func SearchMode

func SearchMode(configuration *config.Configuration, source *models.AgentMailbox) string

SearchMode says how a mailbox is searched: by meaning where it can be.

func SenderNameOf added in v0.210.0

func SenderNameOf(ctx context.Context) string

SenderNameOf is the name WithSenderName gave, or "".

func SettledArguments

func SettledArguments(arguments json.RawMessage) json.RawMessage

SettledArguments are a call's arguments as everything that reads them must see them: repaired once, so that what a call is judged by and what it does cannot be two different things.

Arguments that are already JSON are returned untouched, which is nearly every call. Anything else is put through the same repair the tool's own decoding would have done, and what will not parse even then is given back as it came, for the tool to refuse in its own words.

func ShareableCircles added in v0.170.0

func ShareableCircles(ctx context.Context, operations Operations) ([]models.ShareableCircle, error)

ShareableCircles are the circles the person is in, with their sizes: what a circle named in words is looked up among, so that every tool counts the same circles as ResolveGrantee does.

func Some

func Some(values []string, limit int) string

Some is a few things named in a line, with the rest counted.

func SplitIntention added in v0.236.0

func SplitIntention(arguments json.RawMessage) (json.RawMessage, string)

SplitIntention takes the intention off a call's arguments, and answers the arguments the tool is to run with and the words, cleaned, or "" when there were none fit to show. Arguments that are not an object, or carry no intention, are answered as they came.

func StringProperty

func StringProperty(description string) map[string]any

func StripQuoted

func StripQuoted(text string) string

StripQuoted cuts the quoted history: everything from the first line that introduces it, and any line quoted with ">" before that.

func TellReaction added in v0.134.0

func TellReaction(run Run, conversationId, messageId, reactionEmoji string, reactorKind models.AgentReactorKind)

TellReaction tells the watchers of a conversation about a reaction, when the run can; a run in a test cannot, and nothing is told.

func TextFromSharedPages added in v0.170.0

func TextFromSharedPages(content string) string

TextFromSharedPages is the part of a stored tool result that came from shared pages or shared recordings: everything from the first marker on, or empty when the result has none. A result that mixes the person's own pages with shared ones puts the shared ones last, after the marker.

func ThreadSubject

func ThreadSubject(subject string) string

ThreadSubject is a conversation's subject without the Re: and Fwd: its answers added.

func WithIntention added in v0.236.0

func WithIntention(parameters map[string]any, language string) map[string]any

WithIntention is a tool's parameters with the intention argument added, not required: a call without it still runs and is shown by its name. language is the person's, by name ("English"). The parameters themselves are not changed, since a tool's are shared by every run.

func WithRun

func WithRun(ctx context.Context, run Run) context.Context

WithRun puts the run into the context for the tools called in it.

func WithSenderName added in v0.210.0

func WithSenderName(ctx context.Context, name string) context.Context

WithSenderName is the context of a call made by a program the person connected, under the name it was approved by, so that a file it sends to the main chat says who sent it.

Types

type Action

type Action struct {
	Name string
	Tool *Tool
}

Action is one verb of a merged tool: the word the model passes as "action", and the tool it stands for.

type BackgroundHolder added in v0.57.0

type BackgroundHolder interface {
	HasBackground() bool
}

BackgroundHolder is a computer whose program keeps commands running in the background: one started that way, and one left running when its wait ran out. A program that predates them is not one.

type BackgroundOrigin added in v0.57.0

type BackgroundOrigin struct {
	AgentID        string `json:"agentId"`
	ConversationID string `json:"conversationId"`
	IsUnwakeable   bool   `json:"isUnwakeable,omitempty"`
}

BackgroundOrigin is who started a background command, as the shell tool hands it to the computer and the computer hands it back when the command ends: which agent and conversation to wake, and IsUnwakeable when the conversation is a run's own transcript, such as a night's, which no turn is woken in. The computer keeps it without reading it.

type BrowserLocation added in v0.125.0

type BrowserLocation struct {
	LatitudeDegrees  float64   `json:"latitudeDegrees"`
	LongitudeDegrees float64   `json:"longitudeDegrees"`
	AccuracyMeters   float64   `json:"accuracyMeters"`
	MeasuredAt       time.Time `json:"measuredAt"`
}

BrowserLocation is where the person's browser said it is, as the browser's geolocation reports it.

type Browsing

type Browsing interface {
	// BrowserPage is the turn's page, opened on first use.
	BrowserPage(ctx context.Context) (*browser.Context, error)

	// AttachedTab is the person's tab, or nil.
	AttachedTab() Tab

	// TabsAllowed says whether the operator lets people attach a tab.
	TabsAllowed() bool

	// ReconnectedTab waits up to wait for the person's browser to connect
	// again after the connection behind dropped went, and is the new one,
	// or nil when none came. It only waits: connecting again is the
	// extension's own doing.
	ReconnectedTab(ctx context.Context, dropped Tab, wait time.Duration) Tab
}

Browsing is what a run offers the browser tool: a page of its own in the operator's headless browser, and the person's own attached tab when they attached one. A run that has no browser does not implement it.

type Call

type Call struct {
	ID        string
	Arguments json.RawMessage

	// Confirmed says the person approved this call, and
	// IsConfirmedUnattended that it was not the person but what they allow
	// the agent to do when they are not there: a call that changes what
	// they allow refuses to be confirmed that way.
	Confirmed             bool
	IsConfirmedUnattended bool
}

Call is one use of a tool. The run it is part of — the person, the agent, the database, the operations — is in the context, through RunFrom, so a tool package needs nothing of the loop's own types.

type Catalog

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

Catalog is every tool the server knows.

func Build

func Build() *Catalog

Build is a catalog of everything registered, in registration order.

func NewCatalog

func NewCatalog() *Catalog

NewCatalog is an empty catalog.

func (*Catalog) All

func (self *Catalog) All() []*Tool

All is every tool, in registration order.

func (*Catalog) Get

func (self *Catalog) Get(name string) *Tool

Get is a tool by name, or nil.

func (*Catalog) Offered

func (self *Catalog) Offered(permissions *models.EffectivePermissions, policy *config.AgentTools, serviceSettings ...*config.Services) []*Tool

Offered is the catalog as one person sees it: what their permissions admit, minus what the operator switched off.

func (*Catalog) Register

func (self *Catalog) Register(tool *Tool)

Register adds a tool; a second tool of the same name is a programming error.

type CharacterPage added in v0.242.0

type CharacterPage struct {
	// Text is the page itself.
	Text string
	// NextOffset is where the next page starts, in characters; it is zero
	// when this page reaches the end.
	NextOffset int
	// TotalCharacters is the length of the whole text, in characters.
	TotalCharacters int
	// HasMore is true when characters follow this page.
	HasMore bool
}

CharacterPage is one page of a text read in characters (runes), so a page never ends inside a multi-byte character.

func PageCharacters added in v0.242.0

func PageCharacters(text string, offset, limit int) CharacterPage

PageCharacters is the page of text that starts at offset characters in and is at most limit characters long. A limit of zero or less is the rest of the text; an offset past the end is an empty last page.

type ChatAnswering added in v0.170.0

type ChatAnswering interface {
	IsAnsweringInChat() bool
}

ChatAnswering is a run whose words are posted to the people of a chat: any turn in a chat, the owner's own as well as one somebody else started.

type ChatHolding added in v0.170.0

type ChatHolding interface {
	HeldToChatConversation() string
}

ChatHolding is a run held to what everybody in one chat may see: a turn the owner of an agent allowed somebody else in a chat to start. It names the one conversation the conversation tool may read, which it reads as the people of the chat said it, without what the owner's own agent did there.

type CodingRemembering added in v0.124.0

type CodingRemembering interface {
	CodingMemory(ctx context.Context, directory, computerName, prompt string) (string, error)

	// CaptureCodingSession asks the sources reading a coding tool's
	// transcripts on a computer to read again now, so that a session's
	// latest answer is searchable within a minute. False where no source
	// fits. assistant is claude-code or codex.
	CaptureCodingSession(ctx context.Context, computerName, assistant string) (bool, error)
}

CodingRemembering is what a coding session (Claude Code, Codex) in a checkout is shown of memory by the hooks the person installs: with a prompt, what that prompt recalls from the checkout's project; without one, what a session starting there sees. Empty where memory knows no checkout holding the directory.

type Computer

type Computer interface {
	// Ask sends a request and waits up to wait for the answer.
	Ask(ctx context.Context, action string, args any, wait time.Duration) (json.RawMessage, error)
	Name() string
	System() string
	// Home is the person's home directory there, which ~ and a relative
	// path are from.
	Home() string
	// Description is the person's sentence about what the computer is for,
	// or empty; it is how the agent tells several apart.
	Description() string
}

Computer is the attached computer as a tool reaches it: a request sent across, and the answer it gives.

type Computing

type Computing interface {
	// AttachedComputers are the person's computers, by name; none when
	// none is attached.
	AttachedComputers() []Computer

	// ComputersAllowed says whether the operator lets people attach a
	// computer.
	ComputersAllowed() bool
}

Computing is what a run offers the shell and filesystem tools: the person's own computer, when they attached one with `teanode computer`. A run that has no such thing does not implement it.

type Family

type Family string

Family is a tool's group, which is also what the operator's policy can name to switch the whole group off.

const (
	FamilyMailbox  Family = "mailbox"
	FamilyDomains  Family = "domains"
	FamilyAudit    Family = "audit"
	FamilyPeople   Family = "people"
	FamilyServer   Family = "server"
	FamilyAccount  Family = "account"
	FamilyGeneral  Family = "general"
	FamilyServers  Family = "servers"
	FamilyBrowser  Family = "browser"
	FamilyComputer Family = "computer"
	FamilySkills   Family = "skills"
	FamilyFinance  Family = "finance"
)

The families.

type FeatureHolder added in v0.120.0

type FeatureHolder interface {
	HasFeature(name string) bool
}

FeatureHolder is a computer whose program says which features beyond its protocol it offers, such as the person's herdr sessions. A program that predates a feature does not name it.

type Grantee added in v0.170.0

type Grantee struct {
	// UserID is set for a person and CircleID for a circle, never both.
	UserID   string
	CircleID string

	// Description says who it is in words, for a result and for a card the
	// person approves: the username, or the circle with its name in quotes and
	// how many people it is.
	Description string
}

Grantee is who a share is for: one person, or every member of one circle.

func ResolveGrantee added in v0.170.0

func ResolveGrantee(ctx context.Context, operations Operations, with string) (*Grantee, error)

ResolveGrantee finds who the with argument of a sharing tool names: the username of somebody the person shares a circle with, or a circle they are in by its id or its name. A username wins over a circle of the same name; circle names are not unique, so a name more than one circle has is refused with the ids and sizes of the circles it could be. A username that is nobody's and a circle that is not theirs are refused alike, so the answer does not say which accounts exist.

type GraphSearching

type GraphSearching interface {
	SearchGraphByMeaning(ctx context.Context, words string, limit int) ([]*models.AgentNode, []*models.AgentFact)
}

GraphSearching is finding a page or a fact by what it means rather than by the words it happens to use. A person asking about "the boat" means the page that says "Marigold", and no word of theirs appears in it.

As with Remembering, a run on a deployment with no embedding model does not implement it and the search is by words alone.

type Group

type Group struct {
	Name        string
	Family      Family
	Description string
	Guidance    string
	Core        bool
	Members     []Member
}

Group is a merged tool described by the names of its parts, so that a package can go on declaring its tools exactly as it does and say, in one line at the end, which of them are one tool.

type KnowledgeSearching

type KnowledgeSearching interface {
	// SearchKnowledgeByMeaning is the passages nearest the words, and
	// whether the database ranked them itself. False means the caller
	// should fall back to re-ranking.
	SearchKnowledgeByMeaning(ctx context.Context, sourceIds []string, documentPrefix string, words string, limit int) ([]*models.AgentChunk, bool)

	// RankChunksByMeaning puts a set the words found into the order the
	// meaning wants.
	RankChunksByMeaning(ctx context.Context, words string, chunks []*models.AgentChunk, limit int) []*models.AgentChunk
}

KnowledgeSearching is searching what the person pointed their agent at by meaning as well as by words.

Two methods rather than one because the two paths are genuinely different. Where the database can rank vectors it does, and the words and the meaning are separate searches fused by rank. Where it cannot, reading a few hundred thousand vectors into memory to sort them is not a search, it is a memory leak with a result -- so the words find a bounded set and the meaning re-ranks that.

type Linking added in v0.50.0

type Linking interface {
	// SharedLink is a full address that opens the file, or "" when the run
	// cannot make one; the caller keeps the plain path then.
	SharedLink(attachmentId string) string

	// IsLinkInPlaceOfPath says every file this run hands out goes by its
	// shared link, because whoever reads the answer has no session here: a
	// program over MCP. A conversation hands one out only when asked.
	IsLinkInPlaceOfPath() bool
}

Linking is a run that can hand out an address for a file which opens by itself: signed for that one file, expiring, and needing no sign-in.

The dashboard fetches a file with the person's own session, so a plain path is enough to show one there. A program using the agent tools over MCP has neither the session nor, usually, a token that works outside the tools endpoint, so a plain path was a file it could see and not fetch; one fell back to copying five megabytes through the shell in base64 chunks. And a person who asks for a link to open on their phone has no session there either: a conversation hands one out when asked.

type Locating added in v0.125.0

type Locating interface {
	// CanLocate says whether there is a browser or an app to ask at all in
	// this turn. A turn written anywhere else has none, and the location tool
	// answers from the positions kept instead.
	CanLocate() bool

	// Locate asks the browser and waits for its answer. The error says
	// why there is none: no browser to ask, the person did not allow it,
	// or the browser did not answer in time.
	Locate(ctx context.Context, callId string) (*BrowserLocation, error)
}

Locating is a run that can ask the browser the person is writing in where it is. A run anywhere else -- a terminal, a chat app, a mail, a run with nobody present -- says so instead of guessing.

type MainChatSending added in v0.210.0

type MainChatSending interface {
	// SendToMainChat marks one of the agent's files as sent to the main chat,
	// with the line sent with it and who sent it, and posts it there now, or
	// once a turn running there ends.
	SendToMainChat(ctx context.Context, attachmentId, caption, sentBy string) error

	// UploadLink is a full address that takes one PUT of the bytes of a
	// file waiting for them, signed for that file and expiring; "" when the
	// run cannot make one.
	UploadLink(attachmentId string) string

	// SendToFeed keeps one of the agent's files for a card of the person's
	// feed, with the line sent with it and who sent it, and posts the card:
	// its id.
	SendToFeed(ctx context.Context, attachmentId, caption, sentBy string) (string, error)
}

MainChatSending is a run that can send a file to the person's main chat, the conversation the dashboard and the phone open on, or to their feed, whichever conversation the run is in, or none.

type Member

type Member struct {
	Action string
	Tool   string
}

Member names one tool a group is made of: the word the model will pass as the action, and the name the tool is registered under today.

type MergedTool

type MergedTool struct {
	Name        string
	Family      Family
	Description string
	Guidance    string
	Core        bool
	Actions     []Action
}

MergedTool is what to build: the merged tool's own name and family, the sentence that introduces it, and its actions in the order they should be read.

type NarrowableOperations added in v0.81.0

type NarrowableOperations interface {
	Operations
	NarrowedTo(limit *models.EffectivePermissions) Operations
}

NarrowableOperations is Operations that can be held to fewer permissions than the person's: every call is refused what the limit does not allow, and Permissions says the narrower set.

type Operations

type Operations interface {
	// Execute runs one document of the API as the person and decodes the
	// data into result.
	Execute(ctx context.Context, document string, variables map[string]any, result any) error

	// Permissions is what the person may do.
	Permissions() *models.EffectivePermissions
}

Operations is the API as the person, for a tool: every call runs in its own transaction with the person's permissions, and the audit trail names the person with the agent as the actor.

type PersonStarting added in v0.193.0

type PersonStarting interface {
	IsStartedByPerson() bool
}

PersonStarting is a run that can say whether the person started it: they typed or spoke the turn, or a schedule they wrote themselves woke it. A run that something else started (an inbound mail, a chat app, a webhook, a goal, a dream, a command left running, a schedule the agent wrote) is not theirs, since what such a run does is steered by content the person did not write.

type PreparedPage added in v0.48.0

type PreparedPage func(tx db.Transaction) (*models.AgentNode, error)

PreparedPage resolves a page using model input prepared before the transaction.

type ProgramCalling added in v0.207.2

type ProgramCalling interface {
	IsCalledByPersonsProgram() bool
}

ProgramCalling is a run that can say whether a program the person connected over the Model Context Protocol called it, with a credential only they could have given it: a token they made, or an app they approved. Such a program acts for them, as they would at a screen, though it is not their tap.

type ReactionTelling added in v0.134.0

type ReactionTelling interface {
	TellReaction(conversationId, messageId, reactionEmoji string, reactorKind models.AgentReactorKind)
}

ReactionTelling is a run that can tell whoever watches a conversation that a reaction on one of its messages changed, as the API does when the person reacts, so a drawer open on it shows the agent's reaction at once.

type RecordingEvidenceObserver added in v0.144.4

type RecordingEvidenceObserver interface{ ObserveRecordingEvidence() }

RecordingEvidenceObserver holds unattended turns to lookups after trusted evidence is shown.

type Remembering

type Remembering interface {
	// NoteFact gives a fact its vector as it is written and answers the
	// facts already on the same page that are near enough in meaning to be
	// the same thing said twice, nearest first. Nothing comes back where
	// there is no embedding model, or where nothing is that near.
	//
	// Merging stays within one page on purpose. Two short sentences about
	// two different people sit closer together than either does to a long
	// one about its own subject, so "near in meaning" is only evidence of
	// a duplicate when the two are already about the same thing.
	NoteFact(ctx context.Context, fact *models.AgentFact) []*models.AgentFact

	// NoteNode gives a page its vector when its words change.
	NoteNode(ctx context.Context, node *models.AgentNode)

	// PreparePage obtains any model input before a write transaction begins.
	// The returned resolver only reads or writes through the supplied transaction.
	PreparePage(ctx context.Context, path string, kind models.AgentNodeKind, name string) PreparedPage
}

Remembering is what a run offers the memory tool beyond the store: the meaning of what is written, where the deployment has a model that can say it. A run without one does not implement it, and the tool works as it always did -- by words.

type Rendering added in v0.168.2

type Rendering interface {
	RenderingPage(ctx context.Context) (*browser.Context, func(), error)
}

Rendering is a run that can open a page of its own in the operator's headless browser for one read, apart from the turn's page, so that a read never moves what the browser tool is on. The function closes it.

type RequestLedger added in v0.192.3

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

RequestLedger is what the server remembers of the requests a person's tab made, so that the agent is shown only the ones the server saw created with an address that is not the server's own.

The tab's network events arrive in windows, and a page can push a request's first events out of the window while the request goes on: a WebSocket opened by a frame of the server's origin, whose Authorization header is in a later frame event, is no longer recognized as a request to the server once its creation event is gone. So a request is shown only when its creation was seen, and what was never seen created is not shown.

A session is one debugging session of one tab in the extension; its key comes with the extension's answer. The zero value is ready to use.

func (*RequestLedger) PlacesOf added in v0.192.3

func (self *RequestLedger) PlacesOf(requestID string) ([]string, bool)

PlacesOf are the places named by the events of a request in any session, and whether the request is known in any of them.

func (*RequestLedger) Reset added in v0.192.3

func (self *RequestLedger) Reset()

Reset forgets every session, as when the agent lets the protocol go.

func (*RequestLedger) With added in v0.192.3

func (self *RequestLedger) With(sessionKey string, function func(session *RequestSession))

With runs the function on the session with this key, made empty when the ledger has not seen the key before, while holding the ledger's lock.

type RequestSession added in v0.192.3

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

RequestSession is the requests one debugging session has shown the server, each with the places (hostnames, or the markers the browser tool uses for what it cannot place) its events named.

func (*RequestSession) Add added in v0.192.3

func (self *RequestSession) Add(requestID, place string)

Add gives a request that is known one more place, and does nothing for a request whose creation was not seen.

func (*RequestSession) Create added in v0.192.3

func (self *RequestSession) Create(requestID, place string)

Create remembers a request whose creation was seen, with the place it was created for. A request already known only gains the place.

func (*RequestSession) Places added in v0.192.3

func (self *RequestSession) Places(requestID string) ([]string, bool)

Places are the places a request's events named, and whether it is known.

type Result

type Result struct {
	// Content is what the model reads: JSON, or plain text.
	Content string

	// Untrusted marks content that came from outside — a message, a page —
	// so the loop wraps it as data that never instructs.
	Untrusted bool

	// HasRecordingEvidence is trusted source provenance, never inferred from model text.
	HasRecordingEvidence bool

	// ShowVerbatim marks a secret the person asked to see: relayed once,
	// exactly, never kept.
	ShowVerbatim bool

	// Note is a line for the drawer, saying what was done.
	Note string

	// SearchedAddresses are the web addresses a search returned, for a run
	// held to fetching only those.
	SearchedAddresses []string

	// Images are pictures the model asked to look at, given to it as a
	// turn of its own after this round's results; not kept.
	Images []llm.ContentPart
}

Result is what a tool answers, for the model and for the person.

func JSONResult

func JSONResult(value any) (*Result, error)

JSONResult encodes a value as a tool's content.

func TextResult

func TextResult(format string, arguments ...any) *Result

TextResult is a plain-text tool answer.

func WithRecordingDocumentEvidence added in v0.144.4

func WithRecordingDocumentEvidence(ctx context.Context, run Run, result *Result, documentIds []string) (*Result, error)

WithRecordingDocumentEvidence checks owned provenance before a document result is shown.

func WithRecordingMemoryEvidence added in v0.144.4

func WithRecordingMemoryEvidence(ctx context.Context, run Run, result *Result, nodes []*models.AgentNode, facts []*models.AgentFact, evidence []models.Evidence) (*Result, error)

WithRecordingMemoryEvidence follows owned facts and overview citations, with bounded traversal.

func WithRecordingRevisionEvidence added in v0.144.4

func WithRecordingRevisionEvidence(ctx context.Context, run Run, result *Result, node *models.AgentNode, revisions []*models.AgentRevision) (*Result, error)

WithRecordingRevisionEvidence preserves provenance from retained history after a fact is deleted.

type ResultBudgeting added in v0.106.1

type ResultBudgeting interface {
	ResultCharacters() int
}

ResultBudgeting is a run that keeps less of a tool's result than ResultCharacters, such as one with nobody present; a tool that pages its answer fits a page to it rather than have the run cut the page short.

type Risk

type Risk string

Risk is what a tool can cost.

const (
	RiskRead        Risk = "read"
	RiskWrite       Risk = "write"
	RiskDestructive Risk = "destructive"
	RiskOutward     Risk = "outward"
	RiskGranting    Risk = "granting"
	RiskMoney       Risk = "money"
)

The risk classes. Read changes nothing; write changes something the person can change back; destructive cannot be undone; outward leaves the server — a message sent, a request made on the person's behalf; granting hands out a way in, or changes who may do what; money spends or moves somebody's money, which is how a tool of a skill another person shared is held: the person whose agent calls it is shown what will be paid first.

Granting is its own class because it is neither of the two it kept being filed under. Minting an API token is not destructive -- nothing is lost -- and it is not outward -- nothing leaves. It was therefore an ordinary write, so an agent following instructions it read in a message could mint a token for the whole account, and the person was never asked. What a credential costs is not measured by what it changes; it is measured by what somebody holding it can do afterwards.

type Run

type Run interface {
	Owner() *models.User
	Agent() *models.Agent
	Conversation() *models.AgentConversation
	Operations() Operations
	Database() db.Database
	Configuration() *config.Configuration

	// Surface is where the person is: drawer, cli, api, mail, phone, or
	// empty for a run with nobody present.
	Surface() string
	Headless() bool

	// CanAsk says a question card may be put to the person and waited on:
	// they are there, whether or not they started the turn.
	CanAsk() bool
	ReadOnly() bool

	// Offered is every tool this run may use; Loaded is which of the
	// deferred ones tool_search has loaded; Load marks one loaded.
	Offered() []*Tool
	Loaded() map[string]bool
	Load(name string)

	// Storage is where a file the agent makes is kept.
	Storage() storage.Storage

	// Recall keeps a line a memory search found, for the <recalled>
	// overlay; Recalled is what has been kept this turn.
	Recall(line string)
	Recalled() []string

	// Ask puts a question to the person and waits for the answer.
	Ask(ctx context.Context, callId, question string, choices []string) (string, error)

	// Enqueue queues a job of the agent's, in the transaction given.
	Enqueue(tx db.Transaction, kind models.AgentJobKind, mailboxId, subjectId string) error

	// DraftReply writes a reply the way the draft pipeline does; DiscardDraft
	// removes a draft the agent holds; MeaningSearch finds messages that say
	// the same thing in other words, or nothing where search by meaning is
	// off.
	DraftReply(ctx context.Context, request *models.AgentDraftRequest) (*models.AgentDraft, error)
	DiscardDraft(ctx context.Context, tx db.Transaction, itemId string) error
	MeaningSearch(ctx context.Context, mailboxId, query string, limit int) ([]string, error)
}

Run is the turn a tool is called in, as a tool sees it: who it is for, what it may reach, and what has been loaded so far. The loop puts its run into the context with WithRun; a tool takes it out with RunFrom. What a family of tools needs beyond this — a browser, an attached tab, a question put to the person — is an interface of its own that the run may also satisfy.

func MustRun

func MustRun(ctx context.Context) Run

MustRun is the run a tool was called in, for a tool the loop calls — the loop always puts one in. A test that calls a tool directly puts one in with WithRun; a call without one is a programming error and panics with RunFrom's message.

func RunFrom

func RunFrom(ctx context.Context) (Run, error)

RunFrom is the run a tool was called in. A tool called with none is a programming error, said plainly rather than dereferenced.

type Screen

type Screen struct {
	Columns int    `json:"columns"`
	Rows    int    `json:"rows"`
	Text    string `json:"text"`
	CursorX int    `json:"cursorX"`
	CursorY int    `json:"cursorY"`
	// Changed says it differs from the last read.
	Changed bool `json:"changed"`
	// Ended says the program finished, with Code; the screen is what it left.
	Ended bool `json:"ended"`
	Code  int  `json:"code"`
}

Screen is what a terminal shows at one moment.

type SessionHolder

type SessionHolder interface {
	// StartSession runs a program and returns the session's identifier.
	// kind is "stdio" or "pty"; columns and rows size a terminal.
	StartSession(ctx context.Context, kind, command string, arguments []string,
		directory string, environment map[string]string, columns, rows int) (string, error)
	// WriteSession writes to its input.
	WriteSession(ctx context.Context, id string, data []byte) error
	// ReadScreen is a terminal's screen as it stands.
	ReadScreen(ctx context.Context, id string) (*Screen, error)
	// ResizeSession changes a terminal's size.
	ResizeSession(ctx context.Context, id string, columns, rows int) error
	// SignalSession sends int, term, kill or hup.
	SignalSession(ctx context.Context, id, signal string) error
	// CloseSession ends it.
	CloseSession(ctx context.Context, id string) error
	// AttachedTerminal is the session of a terminal the person is sitting
	// in themselves, or empty when they attached none.
	AttachedTerminal() string
}

SessionHolder is a computer that can hold a program open: a terminal the agent drives, a server spoken to over its standard input. Separate from Computer so that what only asks and answers need not pretend to.

type SharedMemory added in v0.170.0

type SharedMemory interface {
	// CanReadSharedPages says whether this run may read them: the person
	// is present, the run is not a dream and not a chat of several people,
	// and they may use circles.
	CanReadSharedPages() bool

	// SharedPages are the roots shared with the person, by owner and path.
	SharedPages(ctx context.Context) ([]*models.SharedRoot, error)

	// ReadSharedPage is one page of one owner's graph as the person is
	// shown it, or nil when none is shared with them there.
	ReadSharedPage(ctx context.Context, ownerUserId, path string) (*models.SharedPage, error)

	// SearchSharedPages finds pages and facts of shared pages by words.
	SearchSharedPages(ctx context.Context, query string, limit int) ([]*models.SharedHit, error)

	// RestsOnSharedPages says whether a fact about to be noted repeats what
	// a shared page showed this conversation, and nothing the person said:
	// the same test the run that files a conversation applies afterwards,
	// applied to the memory tool's own note.
	RestsOnSharedPages(ctx context.Context, text string) bool
}

SharedMemory is what a run offers the memory tool to read the pages other people shared with the person. A run that is not a conversation with the person, or that is a dream, does not implement it or answers CanReadSharedPages with false, and the tool reads the person's own graph alone.

Every method reads through internal/agent/shared_memory.go, the only code that reads another agent's graph.

type Showing added in v0.84.0

type Showing interface {
	// CanShowPages says the person reads this run in the dashboard, so a
	// page it shows reaches them. A tool that can say where to go instead
	// says so when this is false.
	CanShowPages() bool

	// ShowPage has the dashboard open a path of its own. The caller has
	// checked the path; the dashboard checks it again.
	ShowPage(path string)
}

Showing is a run that can move the dashboard to a page of itself, when the person reads the run there: the drawer, on a desk or a phone. A run anywhere else -- a chat app, a terminal, a program over MCP, a run with nobody present -- either does not implement it or says it cannot show a page, and a tool that would move the dashboard is not offered there (Tool.DashboardOnly).

type Tab

type Tab interface {
	Ask(ctx context.Context, action string, args any) (json.RawMessage, error)
	Title() string
	URL() string
	// HasTab says there is a tab to act in: a browser connected through
	// the extension may have none until one is opened or attached.
	HasTab() bool
	// IsTakenOver says the person has taken the tab over from the
	// dashboard: it may be read, not acted in, until they hand it back.
	IsTakenOver() bool
	// IsWatchable says the person can watch and take the tab over from the
	// dashboard: their extension is new enough.
	IsWatchable() bool
	// CanFillPasswords says the extension can fill a login, a one-time code
	// or a passkey that the server builds the arguments for (protocol 5).
	CanFillPasswords() bool
	// Filled is what the agent's sign-in put into the person's browser, kept
	// in memory: the values to hide from the model and which tabs are
	// locked against what could read a field back.
	Filled() *browser.FilledValues
	// CurrentTabID is the number the extension gave the tab the actions go
	// to, or empty when it did not say. A lock is kept for a tab by it.
	CurrentTabID() string
	// NoteCurrentTab records that an answer of the extension said the
	// actions now go to this tab, without waiting for its next update.
	NoteCurrentTab(tab string)
	// ServerHost is the host, with its port, that the person's browser
	// reached this server by when it connected: a name the person is signed
	// in to, whatever the configuration calls the server.
	ServerHost() string
	// ListedTabs are the tabs the person's browser last listed as ones the
	// agent may act in, each with the address it shows.
	ListedTabs() []TabAddress
	// WatchedRequests is what this connection has shown the server of the
	// requests the person's tab made: the agent is shown only the requests
	// it saw created.
	WatchedRequests() *RequestLedger
}

Tab is a person's attached browser tab as the tool drives it.

type TabAddress added in v0.192.2

type TabAddress struct {
	Tab       string
	Title     string
	URL       string
	IsOwn     bool
	IsCurrent bool
}

TabAddress is one tab the person's browser listed: its number, as the browser tool names it, and what it shows.

type TakeOverAsker added in v0.189.0

type TakeOverAsker interface {
	AskToTakeOver(ctx context.Context, callId, request string) (string, error)
}

TakeOverAsker is a turn that can ask the person to take their browser tab over from the dashboard and wait until they hand it back. Only a turn the person can answer is one.

type Tool

type Tool struct {
	Name        string
	Family      Family
	Description string
	Risk        Risk

	// Annotations are what the tool says about its effects in the Model
	// Context Protocol's terms, where they are given rather than read off
	// the risk: a connected server's, carried through as the server gave
	// them, and a tool that reads the open web. Nil derives them; see Hints.
	Annotations *mcp.ToolAnnotations

	// Parameters is the JSON schema of the arguments.
	Parameters map[string]any

	// Permissions are what the person must hold for the tool to be offered
	// at all: any one of them. Empty means anybody signed in.
	Permissions []models.Permission

	// ActionRequires names, for an action of the tool, permissions the
	// person must all hold on top of Permissions, which admit the tool by
	// any one. An action they lack is left out of what the person is
	// offered, so the model is not given a verb that always fails.
	ActionRequires map[string][]models.Permission

	// Services lists hosted dependencies independent of permissions.
	Services []models.Service

	// ForServices keeps available actions of a merged tool in discovery.
	ForServices func(*config.Services) *Tool

	// Core tools are always in the request; the rest may be deferred
	// behind tool_search when the catalog is long.
	Core bool

	// Headless says a run with nobody present may use it: a remote tool
	// the operator marked read-only on a headless server.
	Headless bool

	// DashboardOnly says it is offered only where the person reads the
	// turn in the dashboard (Showing): it moves the dashboard, and
	// anywhere else there is none to move.
	DashboardOnly bool

	// Guidance is put in the prompt when the tool is in the request, so a
	// person who cannot manage domains is not told how to.
	Guidance string

	// Preview says what a call would do, in a line, for the confirmation
	// card. Nil uses the tool's name and arguments.
	//
	// The card is the one moment a person decides, and it has to say what
	// will happen in the words they would use -- "Send \"Thursday?\" to
	// maria@example.net", not the call. A card that prints the arguments
	// makes the person parse JSON to decide, and the identifiers in it
	// mean nothing to them.
	Preview func(arguments json.RawMessage) string

	// PreviewIn is the same line for a tool that has to look something up
	// to say it: mail_send is handed a draft id, and what the person needs
	// to see is the subject and who it goes to. The run is in the context.
	// Set one or the other; this wins where both are set.
	PreviewIn func(ctx context.Context, arguments json.RawMessage) string

	// RiskOf, when set, says what one call would cost, for a tool whose
	// actions differ: mail_act is a write until it is delete_forever.
	RiskOf func(arguments json.RawMessage) Risk

	// IsPersonsAnswer, when set, says one call gives an answer that is the
	// person's to give: approving or declining what waits for them. Such a
	// call always asks, with money as its risk, and no allowance for when
	// the person is not there covers it
	// (models.UnattendedRiskPersonsAnswer).
	IsPersonsAnswer func(arguments json.RawMessage) bool

	// JudgedCall, when set, is what one call would do, written out for a
	// fast model to judge whether it only reads or changes something on the
	// person's own machine, and so runs, or speaks for them or destroys
	// something, and so asks. Empty says there is nothing to judge.
	JudgedCall func(arguments json.RawMessage) string

	// Run does it.
	Run func(ctx context.Context, call *Call) (*Result, error)

	// Overlay, when set, is asked each round for what is true now; the run
	// is in the context.
	Overlay func(ctx context.Context) string
}

Tool is one entry of the catalog.

func Grouped

func Grouped(all []*Tool, groups ...Group) []*Tool

Grouped merges what the groups name and keeps everything else as it is.

A group naming a tool that is not there is a wiring mistake, and it panics: this runs while the catalog is being built, and a capability that quietly disappears because somebody renamed a tool is worse than a server that will not start. Every package that registers tools is imported by internal/agent/tools/all, so any test that builds the catalog finds it.

func Merge

func Merge(merged MergedTool) *Tool

Merge builds the merged tool.

Three things are carried over from the actions rather than written again.

The parameters are an "action" enumeration and the union of what the actions take; where two actions use the same field for different things, both descriptions are kept, so "for save: ..." and "for remove: ..." read as they do in the tools that were written this way by hand.

The risk is the gentlest of the actions, and RiskOf raises it for the call in hand. That is what lets a read-only run offer a tool whose other actions write: the loop keeps a tool with a RiskOf and refuses the call itself if the action turns out not to be a read. Arguments that cannot be read at all take the strictest risk any action carries, never the gentlest -- a call nobody can parse is not a call anybody should wave through.

The permissions are the union, because they decide only whether the tool is offered; each action checks its own before it runs, and says so in words the model can relay when it does not hold.

Each action's guidance and overlay are kept too, after the merged tool's own: a tool says what the prompt needs to know about it whether or not it was folded into another, and a folded rule_add lost its advice to prefer a rule over remembering to do it by hand.

func Split

func Split(offered []*Tool, loaded map[string]bool, compact bool) (sent, deferred []*Tool)

Split divides the offered tools into the ones sent this round and the ones only listed: everything when the catalog is short; the core set plus whatever was loaded when it is long.

func (*Tool) Definition

func (self *Tool) Definition() llm.ToolDefinition

Definition is the tool as a model is given it.

func (*Tool) Hints added in v0.74.4

func (self *Tool) Hints() *mcp.ToolAnnotations

Hints are the tool's annotations: its own where it has them, else read off its risk, which stays the one place a built-in tool says what it does.

A read changes nothing and reaches nothing beyond what the person may see here; a write changes something here and can be undone; a destructive one cannot; an outward one speaks to the world as the person. A tool whose risk depends on the call (RiskOf) is only read-only when every call is, so it keeps the protocol's cautious defaults for whatever it may raise to.

func (*Tool) PreviewLine

func (self *Tool) PreviewLine(ctx context.Context, arguments json.RawMessage) string

PreviewLine is what the confirmation card says.

func (*Tool) RiskFor

func (self *Tool) RiskFor(arguments json.RawMessage) Risk

RiskFor is what a call would cost: the call's own class when the tool tells them apart, the tool's otherwise.

Judged from the arguments as the tool will read them, which is why they are settled first. Read strictly here and repaired there, the two disagreed about the same call: a RiskOf that cannot parse what it is given falls back to the tool's own class, and the tool then repaired the braces and did the thing. Writing the arguments sloppily was enough to turn an outward call into an ordinary write and walk past the question -- a rule that forwards every message to a stranger, an invitation to a list of them, a token, a command. The gate and the act have to read the same bytes.

func (*Tool) WithHeldActions added in v0.172.0

func (self *Tool) WithHeldActions(permissions *models.EffectivePermissions) *Tool

WithHeldActions is the tool as one person is offered it: the actions that ask for more than they hold (ActionRequires) are taken out of the "action" choices. It is the tool itself when nothing is taken out.

func (*Tool) WithReadingActions added in v0.193.6

func (self *Tool) WithReadingActions() *Tool

WithReadingActions is the tool as a run that may only read it is offered it: the actions that would change something are taken out of the "action" choices, judged as a call naming only that action is. The run refuses such a call anyway; offered the verb, the model kept making the call and spent a round on the refusal. It is the tool itself when nothing is taken out, or when nothing would be left.

type ToolSearchFound added in v0.187.1

type ToolSearchFound struct {
	Loadable []*Tool
	Held     []*Tool
}

ToolSearchFound is what a search found: the tools waiting behind tool_search to load, best first, and the tools the model holds already that the query names, which it should call rather than search again.

func SearchTools added in v0.187.1

func SearchTools(held, deferred []*Tool, query string, limit int) ToolSearchFound

SearchTools ranks the held and the deferred tools against the query. Limit is how many a ranked search loads when the model gave a number; zero is SearchLoadedLimit. A select: query loads every tool it names, unless the model gave a smaller number.

Directories

Path Synopsis
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.
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.
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.
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.
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.
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.
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.
Package circle is what the agent knows about its person's circles: the family, friends or colleagues on this server they belong to, who else is in them, and the invitations to join one.
Package circle is what the agent knows about its person's circles: the family, friends or colleagues on this server they belong to, who else is in them, and the invitations to join one.
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.
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.
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.
Package contact is the person's address book: the people they keep.
Package contact is the person's address book: the people they keep.
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.
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.
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.
Package feed is the agent's feed: the cards it posts to the person for what they did not ask, each a headline, a few lines, sometimes a table of facts and buttons they answer with a tap.
Package feed is the agent's feed: the cards it posts to the person for what they did not ask, each a headline, a few lines, sometimes a table of facts and buttons they answer with a tap.
Package finance is the person's money as the agent reads and keeps it for them: their finance sources (logins at banks, card issuers, brokerages and lenders, linked through a provider), finance accounts, transactions and trades, exchange rates, net worth, spending categories and rules, budgets and savings targets.
Package finance is the person's money as the agent reads and keeps it for them: their finance sources (logins at banks, card issuers, brokerages and lenders, linked through a provider), finance accounts, transactions and trades, exchange rates, net worth, spending categories and rules, budgets and savings targets.
Package folder lists and manages a mailbox's folders.
Package folder lists and manages a mailbox's folders.
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.
Package health is what the agent knows about the person's Apple Health data: the kinds of data they have, their days, weeks and months added up, and, for a question about particular readings, the readings themselves.
Package health is what the agent knows about the person's Apple Health data: the kinds of data they have, their days, weeks and months added up, and, for a question about particular readings, the readings themselves.
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.
Package journal is what the agent can do with the person's journal: read a day, a week, a month or a year of it, list and search its days, and, in a conversation the person started or for a program they connected over MCP, add to their words, set their mood, ask for their words to be touched up, tell a narrative what is wrong with it, and pin a record to a day.
Package journal is what the agent can do with the person's journal: read a day, a week, a month or a year of it, list and search its days, and, in a conversation the person started or for a program they connected over MCP, add to their words, set their mood, ask for their words to be touched up, tell a narrative what is wrong with it, and pin a record to a day.
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.
Package location is what the agent knows about where its person is and where they have been: where they are now, the places they go and when they were there, the places OpenStreetMap knows near them, keeping places and check-ins, and sharing where they are with the people in their circles.
Package location is what the agent knows about where its person is and where they have been: where they are now, the places they go and when they were there, the places OpenStreetMap knows near them, keeping places and check-ins, and sharing where they are with the people in their circles.
Package mailact acts on messages: marks, stars, files, junks, trashes.
Package mailact acts on messages: marks, stars, files, junks, trashes.
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.
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.
Package mailboxsettings renames a mailbox or sets its signature.
Package mailboxsettings renames a mailbox or sets its signature.
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.
Package maildraft writes a draft into Drafts for the person to send.
Package maildraft writes a draft into Drafts for the person to send.
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.
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.
Package mailsend sends a draft, with the person's word.
Package mailsend sends a draft, with the person's word.
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.
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.
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.
Package openpage moves the dashboard the person is reading the agent in to a page of itself: a page of the agent's memory, a message, a settings tab.
Package openpage moves the dashboard the person is reading the agent in to a page of itself: a page of the agent's memory, a message, a settings tab.
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.
Package passwords is what the agent may do with the person's Passwords: see which items they let it use, read a note they let it use, and make up a new password.
Package passwords is what the agent may do with the person's Passwords: see which items they let it use, read a note they let it use, and make up a new password.
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.
Package phone is the person's phones running the TeaNode app, for the agent: which there are and whether notifications reach them, naming them, choosing what each is told, a test notification, and removing one.
Package phone is the person's phones running the TeaNode app, for the agent: which there are and whether notifications reach them, naming them, choosing what each is told, a test notification, and removing one.
Package photo is the person's library of photos and videos, as the agent sees it: finding photos by date, place, camera and file name, looking at them (which also gets them described, so that a later search finds them by what is in them), showing them to the person in the conversation, marking favorites, moving them to the Trash and deleting them from it for good, correcting the date and the place a photo was taken, keeping a picture from a conversation, a message or the person's computer, and organizing photos into albums.
Package photo is the person's library of photos and videos, as the agent sees it: finding photos by date, place, camera and file name, looking at them (which also gets them described, so that a later search finds them by what is in them), showing them to the person in the conversation, marking favorites, moving them to the Trash and deleting them from it for good, correcting the date and the place a photo was taken, keeping a picture from a conversation, a message or the person's computer, and organizing photos into albums.
Package recording exposes account-owned passive evidence through the API.
Package recording exposes account-owned passive evidence through the API.
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.
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.
Package resultmore reads on in a tool's result that was too long for one answer.
Package resultmore reads on in a tool's result that was too long for one answer.
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.
Package searcheverything is the agent's search tool: the person's words looked for across their chats, mail, contacts, photos, memory, documents, recordings, places and finance at once.
Package searcheverything is the agent's search tool: the person's words looked for across their chats, mail, contacts, photos, memory, documents, recordings, places and finance at once.
Package server is the server itself: its status, its settings, an upgrade.
Package server is the server itself: its status, its settings, an upgrade.
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.
Package shopping is the person's shopping lists as the agent sees them: named lists of things to buy, shared with the people and circles the person chooses, checked off live at the store, matched to receipts and remembered with their prices.
Package shopping is the person's shopping lists as the agent sees them: named lists of things to buy, shared with the people and circles the person chooses, checked off live at the store, matched to receipts and remembered with their prices.
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.
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.
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.
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.
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