mail

package
v0.173.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 9 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 mail is the gofer 信箱's business layer (design 2026-10-16-session-topics-mailbox-and-inbox-design.md 「二、gofer 信箱」): sending a letter to an address, resolving that address to the ONE session / job / caller it names, stamping where the letter came from, and parking what cannot be delivered in the capture box.

It owns no transport: delivery is the hook's (SessionStart / UserPromptSubmit / PreToolUse), the relay's ladder and the server deliverer's job, all of which read the letters through jobstore and the CLI / MCP. The mailbox does not import httpapi, commands or the hooks (G022); the entry layer authenticates the caller and vouches for the session it claims, while this package checks only that the resulting origin is a legal combination.

Index

Constants

View Source
const (
	SchemeSession = "session"
	SchemeJob     = "job"
	SchemeTopic   = "topic"
	SchemePath    = "path"
	SchemeCaller  = "caller"
	SchemeAgent   = "agent"
)

Addresses (设计「地址写法」): where a letter is sent. "session:<sid>" and "job:<id>" name one recipient directly; "topic:<kw>" and "path:<sub>" find one by what a session works on; "caller" (or no address at all) is the sender's own capture box; "agent:" belongs to the third phase and is refused for now.

View Source
const MailSummaryRunes = 200

MailSummaryRunes is how much of a letter's body a capture-box item keeps (设计「敏感信息」: 条目只存信件 id 与正文前若干字摘要 — the body itself is never copied).

Variables

View Source
var (
	// ErrInvalidAddress: the address is malformed (an unknown scheme, an empty value).
	ErrInvalidAddress = fmt.Errorf("mail: invalid address")
	// ErrUnsupportedAddress: a well-formed address whose scheme this version does not
	// deliver to yet — `agent:` (host agents) is the third phase.
	ErrUnsupportedAddress = fmt.Errorf("mail: address not supported yet")
	// ErrInvalidOrigin: the sender's (kind, id, caller) combination is not legal.
	ErrInvalidOrigin = fmt.Errorf("mail: invalid sender origin")
	// ErrMailTooLong: the body exceeds the single-letter limit.
	ErrMailTooLong = fmt.Errorf("mail: body too long")
	// ErrRateLimited: the sender passed its per-minute / per-hour ceiling.
	ErrRateLimited = fmt.Errorf("mail: send rate limited")
	// ErrMailNotFound: no letter with that id.
	ErrMailNotFound = fmt.Errorf("mail: letter not found")
	// ErrInvalidBody: an empty body (there is nothing to deliver).
	ErrInvalidBody = fmt.Errorf("mail: body required")
)

The mailbox's error vocabulary. ErrRateLimited is the one the entry layer maps to 429.

View Source
var DefaultLimits = Limits{
	MaxBodyBytes:     32 * 1024,
	PerMinute:        10,
	PerHour:          100,
	MaxThreadLetters: 20,
	DeliverBy:        jobstore.DefaultMailDeliverBy,
}

DefaultLimits is the design's default number table, in code.

Functions

func AddressOf

func AddressOf(kind, id, caller string) string

AddressOf spells the address of a stored letter's end ("session:sess-a", "job:job-7", "caller:alice") — what a reply's to_address carries.

func CaptureText

func CaptureText(m jobstore.Mail, cands []Candidate) string

CaptureText is the text of the capture-box item a held letter becomes: what the letter is, who sent it, why it is parked (with the candidates), and the HEAD of its body — the letter's id and a summary, never the body itself.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err is (or wraps) the send-rate sentinel — the entry layer's 429 decision without importing the wording.

func Summarize

func Summarize(text string, n int) string

Summarize returns the first n runes of text, with an ellipsis when it was cut.

func SummarizeBytes

func SummarizeBytes(text string, n int) string

SummarizeBytes truncates text to at most n BYTES on a rune boundary, with an ellipsis when it had to cut. A budget too small for even one rune yields no preview at all.

Types

type Address

type Address struct {
	Raw    string
	Scheme string
	Value  string
}

Address is one parsed address: the scheme and the value after its first colon (a path may itself contain colons — a Windows drive letter, say — so only the FIRST one separates).

func ParseAddress

func ParseAddress(raw string) (Address, error)

ParseAddress parses what a caller addressed a letter to. An empty (or blank) address and the bare word "caller" both mean the sender's own capture box; an unknown scheme is ErrInvalidAddress; agent: is ErrUnsupportedAddress (the third phase).

type Candidate

type Candidate struct {
	Kind    string
	ID      string
	Topic   string
	Source  string
	Offline bool
	// Why lists why the session matched (sessionrelay's hit kinds: scope / scope_weak / topic
	// / peer_name / project).
	Why []string
}

Candidate is a session a topic: / path: address almost named: the letter goes to the capture box with these, so a person (or its author) can pick one instead of the mailbox guessing.

func (Candidate) Display

func (c Candidate) Display() string

Display is the candidate as a person reads it: 「会话 sess-a(gofer 开发,可能不在线)」.

type CaptureBox

type CaptureBox interface {
	// CaptureWork records one captured item and returns its id.
	CaptureWork(CaptureInput) (string, error)
}

CaptureBox is the 收集箱 seam (CAP-03): the captured work item a letter that nobody could be handed to becomes. The default implementation is the metadata store's own capture function (internal/work.Capture is a thin wrapper over it, adding the default kind); it stays an interface because the dispatch direction comes back the other way later — a capture-box item dispatched to a session sends a LETTER (M6), which would be a cycle if the mailbox imported internal/work.

type CaptureInput

type CaptureInput struct {
	Text string
	Kind string
	By   string
	// SourceSession / SourceJob are recorded as fields only (who wrote the letter down).
	SourceSession string
	SourceJob     string
}

CaptureInput is one captured work item (the collection box's own input).

type Limits

type Limits struct {
	// MaxBodyBytes is 单封正文 (32 KB): long enough for a log or a diff summary, short enough
	// that a letter cannot be a bulk payload.
	MaxBodyBytes int
	// PerMinute / PerHour are 发件限速 per sender (10 / 100). Exceeding them is
	// ErrRateLimited, which the entry layer answers with 429.
	PerMinute int
	PerHour   int
	// MaxThreadLetters is 对话串自动往返 (20): once a thread has that many letters, the next
	// one is parked in the capture box instead of delivered, so two agents answering each
	// other stop and a person takes over.
	MaxThreadLetters int
	// DeliverBy is 送达期限: how long a letter may stay undelivered before the sweep parks it
	// in the capture box.
	DeliverBy time.Duration
}

Limits are the mailbox's default numbers.

type Origin

type Origin struct {
	// Kind is jobstore.MailKindSession / MailKindCaller / MailKindJob.
	Kind string
	// ID is the session id or the job id; empty for a caller.
	ID string
	// Caller is the authenticated caller behind the letter (the session's owner, the caller
	// itself, or the caller that owns the job credential).
	Caller string
}

Origin is who sent a letter.

func OriginOf

func OriginOf(m jobstore.Mail) Origin

OriginOf reads the origin of a stored letter.

func (Origin) Address

func (o Origin) Address() string

Address is the address this origin can be reached at, i.e. what a reply is sent to.

func (Origin) Display

func (o Origin) Display() string

Display is the human label of an origin: 「会话 sess-a(调用方 alice)」, 「job job-7」 or 「调用方 alice」.

func (Origin) Validate

func (o Origin) Validate() (Origin, error)

Validate normalises the origin and refuses a combination the mailbox cannot stamp: a session or job sender needs its id, everything needs a known kind. It returns the normalised origin.

type ReaddressInput

type ReaddressInput struct {
	ID        int64
	To        string
	Origin    Origin
	Project   string
	Visible   func(jobstore.AgentSession) bool
	Roots     func(projectKey string) []string
	Authorize func(Target) error
}

ReaddressInput hands a held letter to a new address.

type ReplyInput

type ReplyInput struct {
	ID     int64
	Body   string
	Urgent bool
	Origin Origin
	// Authorize is SendInput.Authorize for the reply's recipient (the original sender).
	Authorize func(Target) error
}

ReplyInput is one answer to an existing letter.

type SendInput

type SendInput struct {
	To      string
	Body    string
	Urgent  bool
	Origin  Origin
	Project string
	Visible func(jobstore.AgentSession) bool
	Roots   func(projectKey string) []string
	// ThreadID puts the letter into an existing conversation thread (a readdressed letter
	// keeps its thread); empty starts a new one.
	ThreadID string
	// CaptureItemID marks the letter as one that came OUT of the capture box: the item id is
	// recorded on the letter (mail.capture_item_id), so whatever happens to the letter can be
	// written back into that item (收集箱「交给会话」, design §3). Empty for a letter that was
	// written by hand.
	CaptureItemID string
	// Authorize is the entry layer's permission / ceiling judgement on the RESOLVED
	// recipient (the mailbox never reads permissions itself). It runs after the address is
	// resolved and BEFORE anything is stored, so a refused letter leaves no trace; its error
	// is returned as is. It is not called when the address resolved to nobody.
	Authorize func(Target) error
}

SendInput is one letter to send. Visible is the reader-permission judgement the entry layer passes in (a topic: / path: candidate the sender may not see is not a candidate at all — the mailbox never reads permissions itself); Roots are a project's root paths for the finder.

type SendResult

type SendResult struct {
	Mail          jobstore.Mail
	Target        Target
	Candidates    []Candidate
	CaptureItemID string
	Held          bool
}

SendResult is what a send / reply produced. Held means the letter could not be delivered and went to the capture box (Candidates lists the sessions a topic: / path: address matched); CaptureItemID is that item.

type Service

type Service struct {

	// Limits are the send limits (见 limits.go); DefaultLimits at construction.
	Limits Limits
	// contains filtered or unexported fields
}

Service sends and replies to letters over the shared metadata store.

func NewService

func NewService(store *jobstore.Store, finder SessionFinder) *Service

NewService builds the mailbox over the store, resolving topic: / path: through finder (nil = those addresses cannot be resolved).

func (*Service) Readdress

func (s *Service) Readdress(in ReaddressInput) (SendResult, error)

Readdress is the capture box's 「改投」: a held (待指派) letter is sent again to a new address — same body, same urgency, same thread, the caller as the sender — and the held one is cancelled with the new address as the reason. It is a fresh send for every purpose (resolution, limits, authorization on the NEW recipient). A letter that is not held cannot be readdressed (jobstore.ErrMailState).

func (*Service) Reply

func (s *Service) Reply(in ReplyInput) (SendResult, error)

Reply stores an answer inside the original letter's thread and marks the original answered. The answer goes back to the original sender's address, and the thread's automatic round-trip ceiling parks it in the capture box instead of sending it when two agents would otherwise keep answering each other.

func (*Service) Send

func (s *Service) Send(in SendInput) (SendResult, error)

Send stores one letter, resolving its address first: exactly one recipient is delivered to, none or several are parked in the capture box with the candidates.

func (*Service) SetCaptureBox

func (s *Service) SetCaptureBox(b CaptureBox)

SetCaptureBox replaces the collection-box seam (tests, and a deployment whose capture box is not the metadata store).

func (*Service) SetClock

func (s *Service) SetClock(fn func() time.Time)

SetClock overrides the service clock (tests).

type SessionFinder

type SessionFinder interface {
	Find(sessionrelay.FindQuery) ([]sessionrelay.FindResult, error)
}

SessionFinder is the session lookup a topic: / path: address is resolved with. It IS sessionrelay.Service.Find — the matching, the ranking and the "offline still counts, but is flagged" rule live there (设计「会话主题与查找」), never here.

type Target

type Target struct {
	Kind    string
	ID      string
	Caller  string
	Address string
	Topic   string
	Source  string
	Offline bool
	Deliver bool
}

Target is the recipient an address resolved to. Deliver is false when there is no delivery path for it (a caller has no session and no job to be sent into — its mail is the capture box). Topic / Offline describe the session it names (设计: an offline session still takes part in resolution, flagged as possibly gone).

Jump to

Keyboard shortcuts

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