mail

package
v0.182.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 14 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 (
	// DefaultTick is how often the deliverer sweeps.
	DefaultTick = 30 * time.Second
	// DefaultWakeIdle is the idle age (now - last_seen_at) a session needs before it is woken.
	DefaultWakeIdle = 5 * time.Minute
	// DefaultWakeInterval is the minimum gap between two wakes of one session.
	DefaultWakeInterval = 10 * time.Minute
	// DefaultLease is the claim lease of the deliverer's own claims.
	DefaultLease = jobstore.DefaultMailClaimTTL

	// PtyHoldReason is why a letter to a pty session job is parked.
	PtyHoldReason = "pty session jobs cannot receive mail"
)

Delivery numbers (设计「默认数值」). Settings overrides them from the server config.

View Source
const (
	// TagLetter is the element wrapping one injected letter: `<gofer-mail ...>body</gofer-mail>`.
	TagLetter = "gofer-mail"
	// TagWake is the self-closing wake marker: `<gofer-mail-wake count="N"/>`.
	TagWake = "gofer-mail-wake"
	// WakeNotice is the fixed one-line notice following the wake tag.
	WakeNotice = "有待读信件,将在本轮开始时注入,无需回复"
)

The injected-letter tags (mailbox design §二). Letters are NOT user input: the hook and the server deliverer both render them from here — the single source of truth — and hookrelay.IsHarnessPrompt recognises them, so a mail turn never counts as the human returning (no relay auto-off, no title rewrite). hookrelay re-exports these names.

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")
	// ErrSessionNotFound: a session: address names no session (no id equals it, none starts with it).
	ErrSessionNotFound = fmt.Errorf("mail: session not found")
	// ErrSessionAmbiguous: a session: address is a prefix of several sessions.
	ErrSessionAmbiguous = fmt.Errorf("mail: session id prefix is ambiguous")
	// 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 RenderLetter added in v0.174.0

func RenderLetter(l Letter) string

RenderLetter renders one letter as the fixed harness tag, so the model (and IsHarnessPrompt) can tell a letter from something a person typed. Attribute values are escaped; a body that contains the closing tag cannot end the element early.

func RenderWake added in v0.174.0

func RenderWake(count int) string

RenderWake renders the wake prompt for count pending letters.

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.

func WakeDue added in v0.174.0

func WakeDue(a jobstore.AgentSession, letters []jobstore.Mail, now time.Time, idle time.Duration) bool

WakeDue is the wake condition for a session with pending letters (设计「送达点」): the session is idle or offline (a running session injects at its next turn start anyway; waiting_reply waits for a person; ended / handed_off / needs_attention are not woken), and its last_seen_at is older than idle — except that an URGENT letter wakes an idle session at once. The per-session wake interval is the caller's (wakeAllowed).

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 Deliverer added in v0.174.0

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

Deliverer is the sweep itself. Start launches the loop, Stop / Drain end it.

func NewDeliverer added in v0.174.0

func NewDeliverer(o DelivererOptions) *Deliverer

NewDeliverer builds the deliverer (not started).

func (*Deliverer) Configure added in v0.174.0

func (d *Deliverer) Configure(s Settings)

Configure replaces the timing numbers (config hot reload); zero fields take the defaults.

func (*Deliverer) Drain added in v0.174.0

func (d *Deliverer) Drain(ctx context.Context) error

Drain stops the loop and waits for a sweep in flight to finish, or for ctx. Safe to call more than once, and before Start.

func (*Deliverer) Start added in v0.174.0

func (d *Deliverer) Start()

Start launches the sweep loop (idempotent). The loop ends at Stop / Drain.

func (*Deliverer) Stop added in v0.174.0

func (d *Deliverer) Stop()

Stop ends the loop and waits (bounded) for it.

func (*Deliverer) Tick added in v0.174.0

func (d *Deliverer) Tick(ctx context.Context)

Tick runs one sweep now.

type DelivererOptions added in v0.174.0

type DelivererOptions struct {
	Svc    *Service
	Sender SessionSender
	Jobs   JobSayer
	// IsSuga says whether a session's agent key is suga (its letters go to `suga send`);
	// nil = the key is "suga".
	IsSuga   func(agentKey string) bool
	Settings Settings
	// Now overrides the clock (tests).
	Now func() time.Time
}

DelivererOptions assembles a Deliverer. Svc is the mailbox the HTTP server uses too.

type JobSayer added in v0.174.0

type JobSayer interface {
	SaySession(id, message string) error
}

JobSayer is the ACP session job's input seam; *job.Service satisfies it.

type Letter added in v0.174.0

type Letter struct {
	ID        int64
	From      string
	Topic     string
	Urgent    bool
	Body      string
	Truncated bool
}

Letter is what the tag shows of one letter: the id (so a recipient can tell a repeat of an at-least-once delivery), the sender's display and topic, the urgency and the body.

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) CancelMail added in v0.178.0

func (s *Service) CancelMail(id int64, reason string) (jobstore.Mail, bool, error)

CancelMail withdraws a letter. When the letter was held, the capture-box item it was recorded as is dropped with it: the item only stood for "this letter needs an address", and a withdrawn letter needs nothing, so leaving it captured would be noise a person has to triage by hand. Dropping (not deleting) matches the box's own 「丢弃」 and keeps the journal line saying why. changed is false when the letter's state no longer allowed a cancel. Closing the item is best effort: the letter is already cancelled, and an item that was triaged meanwhile (no longer captured) is left alone.

func (*Service) HoldLetter added in v0.174.0

func (s *Service) HoldLetter(id int64, reason string) (jobstore.Mail, bool, error)

HoldLetter parks a letter that cannot be delivered (a pty job, a delivery deadline that passed) in the capture box: the letter becomes held with reason, and the box gets the item that points back at it (the same shape a send-time hold has). ok=false means the letter had already moved on (delivered, cancelled …) and nothing was recorded.

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) RecordHeld added in v0.174.0

func (s *Service) RecordHeld(held []jobstore.Mail) error

RecordHeld records letters the sweep already moved to held (ExpireOverdue) in the capture box. It keeps going after a failure so one broken item does not strand the others, and returns the first error.

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).

func (*Service) SetDeliverBy added in v0.174.0

func (s *Service) SetDeliverBy(d time.Duration)

SetDeliverBy changes the delivery deadline new letters get (mail.deliver_by_sec, hot reload); d <= 0 returns to Limits.DeliverBy. Safe to call while letters are being sent.

func (*Service) Store added in v0.174.0

func (s *Service) Store() *jobstore.Store

Store exposes the metadata store the mailbox works over (the deliverer reads letters with it; there is one store per process).

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 SessionSender added in v0.174.0

type SessionSender interface {
	// DeliverLetter hands text to the session's live process through its agent's
	// deliver_command (exit 3 = ReasonNotRunning). by is the display label, origin the
	// caller-scope ceiling owner of the delivery (the letter's sender).
	DeliverLetter(ctx context.Context, sid, text, by, origin string) (sessionrelay.RawResult, error)
	// Wake sends the wake prompt through the relay's transports without any web semantics.
	Wake(ctx context.Context, sid, text, by, origin string) (sessionrelay.RawResult, error)
}

SessionSender is the relay's raw send seam; *sessionrelay.Service satisfies it.

type Settings added in v0.174.0

type Settings struct {
	Tick         time.Duration
	WakeIdle     time.Duration
	WakeInterval time.Duration
	Lease        time.Duration
}

Settings are the deliverer's timing numbers (config mail.*).

func DefaultSettings added in v0.174.0

func DefaultSettings() Settings

DefaultSettings returns the design's defaults.

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