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
- Variables
- func AddressOf(kind, id, caller string) string
- func CaptureText(m jobstore.Mail, cands []Candidate) string
- func IsRateLimited(err error) bool
- func RenderLetter(l Letter) string
- func RenderWake(count int) string
- func Summarize(text string, n int) string
- func SummarizeBytes(text string, n int) string
- func WakeDue(a jobstore.AgentSession, letters []jobstore.Mail, now time.Time, ...) bool
- type Address
- type BroadcastInput
- type BroadcastRecipient
- type BroadcastResult
- type Candidate
- type CaptureBox
- type CaptureInput
- type Deliverer
- type DelivererOptions
- type JobSayer
- type Letter
- type Limits
- type Origin
- type ReaddressInput
- type ReplyInput
- type SendInput
- type SendResult
- type Service
- func (s *Service) Broadcast(in BroadcastInput) (BroadcastResult, error)
- func (s *Service) CancelMail(id int64, reason string) (jobstore.Mail, bool, error)
- func (s *Service) HoldLetter(id int64, reason string) (jobstore.Mail, bool, error)
- func (s *Service) Readdress(in ReaddressInput) (SendResult, error)
- func (s *Service) RecordHeld(held []jobstore.Mail) error
- func (s *Service) Reply(in ReplyInput) (SendResult, error)
- func (s *Service) Send(in SendInput) (SendResult, error)
- func (s *Service) SetBroadcastLimits(maxRecipients, rate int, window time.Duration)
- func (s *Service) SetCaptureBox(b CaptureBox)
- func (s *Service) SetClock(fn func() time.Time)
- func (s *Service) SetDeliverBy(d time.Duration)
- func (s *Service) Store() *jobstore.Store
- type SessionFinder
- type SessionSender
- type Settings
- type Target
Constants ¶
const ( SchemeSession = "session" SchemeJob = "job" SchemeTopic = "topic" SchemePath = "path" SchemeCaller = "caller" SchemeAgent = "agent" // SchemeProject addresses every deliverable session of one project (each: only). SchemeProject = "project" )
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.
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.
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.
const EachPrefix = "each:"
EachPrefix turns an address into a selector for ALL it matches (设计 2026-10-22「D1」): `each:topic:login` is every session the topic matches, not "exactly one or park it". An address without the prefix keeps its meaning exactly (several matches still park).
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 ¶
var ( // ErrNoRecipients: the addresses resolved to nobody deliverable — nothing is stored. ErrNoRecipients = fmt.Errorf("mail: broadcast has no recipient") // ErrBroadcastTooMany: more recipients than mail.broadcast_max_recipients. ErrBroadcastTooMany = fmt.Errorf("mail: broadcast has too many recipients") // ErrUrgentBroadcast: urgent and a broadcast are incompatible (nothing wakes a group at once). ErrUrgentBroadcast = fmt.Errorf("mail: an urgent broadcast is not supported") // ErrBroadcastAmbiguous: an address of a broadcast did not name exactly one recipient. ErrBroadcastAmbiguous = fmt.Errorf("mail: broadcast address is not a single recipient") )
Broadcast-limit sentinels; the entry layer maps them onto 4xx.
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.
var DefaultLimits = Limits{ MaxBodyBytes: 32 * 1024, PerMinute: 10, PerHour: 100, MaxThreadLetters: 20, DeliverBy: jobstore.DefaultMailDeliverBy, BroadcastMaxRecipients: 20, BroadcastRate: 5, BroadcastWindow: 10 * time.Minute, }
DefaultLimits is the design's default number table, in code.
Functions ¶
func AddressOf ¶
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 ¶
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 ¶
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
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
RenderWake renders the wake prompt for count pending letters.
func SummarizeBytes ¶
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
// Each marks the `each:` prefix: the address fans out to every deliverable match instead
// of requiring exactly one.
Each bool
}
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 ¶
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 BroadcastInput ¶ added in v0.184.0
type BroadcastInput struct {
To []string
Body string
Urgent bool
Origin Origin
Project string
Visible func(jobstore.AgentSession) bool
Roots func(projectKey string) []string
// Authorize is SendInput.Authorize, applied to EVERY recipient: an explicitly named one
// without permission refuses the whole broadcast, a selector's is skipped and counted.
Authorize func(Target) error
}
BroadcastInput is one broadcast to send. To is every address given (repeated --to); an address with the each: prefix fans out to every match.
type BroadcastRecipient ¶ added in v0.184.0
type BroadcastRecipient struct {
// Address is the address that selected this recipient (one of BroadcastInput.To).
Address string
Kind string
ID string
MailID int64
State string
// Skipped marks a selector match the sender may not deliver to; Reason says why.
Skipped bool
Reason string
}
BroadcastRecipient is one addressee of a broadcast as the sender sees it afterwards.
type BroadcastResult ¶ added in v0.184.0
type BroadcastResult struct {
Mails []jobstore.Mail
Recipients []BroadcastRecipient
ThreadID string
BroadcastID int64
Matched int
Skipped int
}
BroadcastResult is what a broadcast produced: the copies (one letter each) and the addressee table. Matched counts the sessions the addresses selected, Skipped the ones dropped by permission.
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.
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
Configure replaces the timing numbers (config hot reload); zero fields take the defaults.
func (*Deliverer) Drain ¶ added in v0.174.0
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.
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
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
// BroadcastID / Recipients mark a copy of a broadcast (设计 2026-10-22「D2」): the agent then
// knows it is one of several recipients instead of the only one. 0 / 0 = a single letter.
BroadcastID int64
Recipients int
}
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
// BroadcastMaxRecipients is 单次广播最多收件人数 (20, 设计 2026-10-22「D6」).
BroadcastMaxRecipients int
// BroadcastRate / BroadcastWindow are 广播频率 per sender (5 per 10 minutes): a broadcast is
// counted once, whatever its recipient count.
BroadcastRate int
BroadcastWindow 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 (Origin) Address ¶
Address is the address this origin can be reached at, i.e. what a reply is sent to.
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) Broadcast ¶ added in v0.184.0
func (s *Service) Broadcast(in BroadcastInput) (BroadcastResult, error)
Broadcast stores one letter per recipient. It is Send for several recipients: the addresses are resolved first (an explicit address must name exactly one deliverable recipient), then judged per recipient, then written — so a refused broadcast leaves no letter behind.
func (*Service) CancelMail ¶ added in v0.178.0
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
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
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) SetBroadcastLimits ¶ added in v0.184.0
SetBroadcastLimits installs the `mail:` block's broadcast numbers (0 = keep Limits').
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) SetDeliverBy ¶ added in v0.174.0
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.
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).