mail

package
v0.195.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 17 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"
	// 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; "agent:<名字>[@<项目>]" sends to the resident session gofer keeps for that agent (设计 2026-10-22 mail-agent-address); "caller" (or no address at all) is the sender's own capture box.

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

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 (
	// 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.

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 (kept for the entry layers' wording; `agent:` is delivered since
	// 2026-10-22).
	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")
	// ErrJobNotFound: a job: address names no job at all (a typo, a deleted row).
	ErrJobNotFound = fmt.Errorf("mail: job not found")
	// ErrJobCannotReceive: a job: address names a job that can never take a letter — an ended
	// job, or a one-off run (no ACP session, so nothing can be said into it). The send is
	// refused instead of storing a letter that would hang until the delivery deadline.
	ErrJobCannotReceive = fmt.Errorf("mail: job cannot receive mail")
	// ErrNotAnswerable: the letter was written by gofer itself (a 退信), so there is no sender
	// to answer.
	ErrNotAnswerable = fmt.Errorf("mail: letter cannot be answered")
	// 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,

	BroadcastMaxRecipients: 20,
	BroadcastRate:          5,
	BroadcastWindow:        10 * time.Minute,
}

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

View Source
var ErrAgentNotResident = fmt.Errorf("mail: no resident session for that agent")

ErrAgentNotResident: the address has no resident session row, so there is nothing to end.

View Source
var ErrUnknownAgent = fmt.Errorf("mail: unknown mail agent")

ErrUnknownAgent: an `agent:` address names a name that `mail.agents` does not configure. The entry layer maps it to 400 and the message lists the names that would have worked.

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 BounceText added in v0.192.0

func BounceText(m jobstore.Mail, reason, where string) string

BounceText is the body of a returned letter: which letter, why it came back, where it is now, and the head of what it said (the sender does not have to open the original to recognize it).

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 OpeningPrompt added in v0.185.0

func OpeningPrompt(spec ResidentAgentSpec, project string) string

OpeningPrompt is the text a resident session starts with (设计「D2」): what this session is, how letters arrive, and how to answer — then the configured prompt.

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
	// Project is the `@<项目>` of an agent: address (empty = the sender's own project).
	Project 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

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

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
	// 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 LiveResident added in v0.185.0

type LiveResident struct {
	jobstore.MailResidentAgent
	// Spec is the configuration the row was started from (Name / Agent / Idle / MaxLetters…).
	Spec ResidentAgentSpec
	// Configured is false when the row's name is no longer in mail.agents.
	Configured bool
	// Pending is how many letters wait for this address.
	Pending int
	// IdleSince is when the session last took a letter or started (unix seconds).
	IdleSince int64
}

LiveResident is one resident session as the HTTP / CLI listing shows it.

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 ResidentAgentSpec added in v0.185.0

type ResidentAgentSpec struct {
	// Name is the configured name, as written in the address.
	Name string
	// Agent is the agent definition the resident session runs (an acp-agent).
	Agent string
	// Args are extra args appended to the agent's argv.
	Args []string
	// Runner is the job runner; "" = the project default.
	Runner string
	// Idle is how long the session may sit idle before gofer ends it.
	Idle time.Duration
	// MaxLetters / MaxHours rotate the session (0 = that axis is unlimited).
	MaxLetters int
	MaxHours   int
	// Prompt is appended to gofer's own opening prompt.
	Prompt string
	// Approval is this resident session's own ACP approval gate
	// (mail.agents.<名字>.approval): nil = the project's policy.
	Approval *config.ApprovalConfig
}

ResidentAgentSpec is one configured 收件 agent (config `mail.agents.<名字>`).

func (ResidentAgentSpec) Identity added in v0.185.0

func (a ResidentAgentSpec) Identity() string

Identity returns the agent definition key, or "" when the spec names none.

type ResidentHost added in v0.185.0

type ResidentHost interface {
	// StartSession submits the resident session job and returns its id ('live' informs the
	// caller the job started asynchronously: the letters wait for awaiting_input).
	StartSession(spec ResidentSpec) (jobID string, err error)
	// Job looks a job up (ok=false: unknown).
	Job(jobID string) (ResidentJob, bool)
	// End stops a session job (already gone is not an error).
	End(jobID string) error
}

ResidentHost is the job seam of the resident sessions: *job.Service behind an adapter built in the entry / orchestration layer (the mailbox never imports internal/job's service).

type ResidentJob added in v0.185.0

type ResidentJob struct {
	// ID is the job id.
	ID string
	// Agent is the agent key the job runs.
	Agent string
	// SessionID is the ACP session id (a later job resumes it).
	SessionID string
	// Status is the job status string (job.StatusAwaitingInput etc.).
	Status string
	// Live is false once the job is terminal.
	Live bool
	// AwaitingInput is true when the session sits at its input prompt (a letter can be said
	// into it now).
	AwaitingInput bool
}

ResidentJob is what the host knows about a resident session's job.

type ResidentSpec added in v0.185.0

type ResidentSpec struct {
	// Name / Project identify the address the session serves.
	Name    string
	Project string
	// Agent / Args / Runner start the session.
	Agent  string
	Args   []string
	Runner string
	// IdleSec is the session's own idle timeout: gofer ends it after that much silence.
	IdleSec int
	// Prompt is the opening prompt (gofer's own text plus the configured one).
	Prompt string
	// Title is the job title.
	Title string
	// ResumeSessionID asks the host to continue that ACP conversation when the agent allows
	// it ("" = start a fresh one); ResumeFromJobID is the job that session belongs to.
	ResumeSessionID string
	ResumeFromJobID string
	// OriginCaller is the caller whose quota the job belongs to: the letter's sender.
	OriginCaller string
	// CallerID is the caller id stamped on the job.
	CallerID string
	// Approval is the approval gate this session is started under (nil = the project's
	// policy): the resident 收件会话 may ask a human where the project auto-allows.
	Approval *config.ApprovalConfig
}

ResidentSpec is what the host needs to start a resident session.

type ResidentsConfig added in v0.185.0

type ResidentsConfig struct {
	// Agents is keyed by the LOWERCASED name: an address is matched case-insensitively.
	Agents map[string]ResidentAgentSpec
	// Max is `mail.agents_max_resident`: how many resident sessions may live at once.
	Max int
}

ResidentsConfig is the `mail.agents` block plus its ceiling, as the mailbox sees it.

func (ResidentsConfig) Agent added in v0.185.0

func (c ResidentsConfig) Agent(name string) (ResidentAgentSpec, bool)

Agent returns the spec of name (case-insensitively) and whether it is configured.

func (ResidentsConfig) Names added in v0.185.0

func (c ResidentsConfig) Names() []string

Names lists the configured names, sorted (an unknown name's error says what is available).

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) Bounce added in v0.192.0

func (s *Service) Bounce(m jobstore.Mail, reason, where string) (jobstore.Mail, bool, error)

Bounce returns letter m to its sender as a gofer notice. reason says why it could not be delivered, where tells the sender where it is now. ok is false when nothing was written: a gofer notice of its own, a broadcast copy, or a letter whose sender has no id at all.

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

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) EndResident added in v0.185.0

func (s *Service) EndResident(name, project, reason string) (string, error)

EndResident stops the resident session of one address by hand (POST /v1/mail/agents/{name}/end). It is not an error when the address has no live session: the row is marked ended either way so the listing stops showing it.

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 job that ended, 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. A parked letter is returned to its sender as a 退信 (see bounce.go): the sender is not left waiting for an answer nobody will ever give.

func (*Service) ListResidents added in v0.185.0

func (s *Service) ListResidents() ([]LiveResident, error)

ListResidents is the `agent:` listing (GET /v1/mail/agents, `gofer session mail agents`): the configured names plus the resident sessions that exist right now.

func (*Service) Preview added in v0.185.0

func (s *Service) Preview(in BroadcastInput) (BroadcastResult, error)

Preview resolves a broadcast without storing anything (POST /v1/mail with dry_run): the sender sees who the letter would reach and who a selector would skip. It does not count against the broadcast rate — a preview is not a send — but every other rule (body, urgent, recipient ceiling, no recipient) answers exactly as Broadcast would.

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 and returns each to its sender. 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) Residents added in v0.185.0

func (s *Service) Residents() ResidentsConfig

Residents returns the current block (an empty one when nothing is configured).

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

func (s *Service) SetBroadcastLimits(maxRecipients, rate int, window time.Duration)

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) 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) SetResidentHost added in v0.185.0

func (s *Service) SetResidentHost(h ResidentHost)

SetResidentHost installs the job seam of the resident sessions (the entry layer's adapter).

func (*Service) SetResidents added in v0.185.0

func (s *Service) SetResidents(cfg ResidentsConfig)

SetResidents installs the `mail.agents` block (config load and hot reload).

func (*Service) SetSessionJobCheck added in v0.192.0

func (s *Service) SetSessionJobCheck(fn SessionJobCheck)

SetSessionJobCheck installs the job-side judgement of a `job:` address (nil = none: every live job is then accepted, which is what a process without a job service can do).

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 SessionJobCheck added in v0.192.0

type SessionJobCheck func(jobID string) (session, found bool)

SessionJobCheck reports whether a job id is an ACP session job — one started with `session: true` (the only job kind a letter can be said into) — and whether the job is known at all (found). It is the job service's judgement, injected at assembly: the mailbox does not read job request payloads to find out.

func SessionJobLookup added in v0.192.0

func SessionJobLookup(get func(id string) (job.JobResult, bool)) SessionJobCheck

SessionJobLookup adapts the job service's lookup to a SessionJobCheck: the snapshot's Session flag, or — for a job whose session state is not recorded yet (a session job queued when the server restarted) — the original request.

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