ntfy

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package ntfy 把 RelayMesh 里「需要你处理」的事件推送到 ntfy(https://ntfy.sh 或自建实例)。

浏览器里的声音与系统通知只在网页开着、事件流连着的时候才会响;智能体在等你回复,你却不在电脑前, 提醒就送不到。ntfy 是一个简单的推送服务:Hub 往一个「主题」发一条消息,手机或桌面上订阅了这个主题的 ntfy 应用立刻就会弹出通知——不依赖任何网页是否打开。

本包是叶子包(只依赖标准库与 model),职责分三层:

  • config.go 配置的形状、校验、对外视图(凭据只写不读);
  • sender.go 一次推送的 HTTP 细节:JSON 发布、认证头、重试、错误脱敏、目标地址防护;
  • notifier.go 事件队列:去重、延迟、限流、状态统计,让「推送失败 / 变慢」永远拖不住智能体的请求。

Index

Constants

View Source
const (
	// DefaultServer 是公共的 ntfy 服务;自建实例填自己的地址。
	DefaultServer = "https://ntfy.sh"
	// DefaultPriority 对应 ntfy 的「high」:手机上会弹出并伴随较长的震动。1 最低、3 默认、5 紧急。
	DefaultPriority = 4
	// MaxDelaySeconds 是「延迟推送」的上限(15 分钟)。
	MaxDelaySeconds = 900
	// DefaultRunMinSeconds 是「模型运行结束」推送的默认门槛:运行得比这更短的命令不推送。
	DefaultRunMinSeconds = 60
	// MaxRunMinSeconds 是这个门槛的上限(24 小时)。
	MaxRunMinSeconds = 86400
)
View Source
const GuardKindAutoResumeGaveUp = "autoresume_gaveup"

GuardKindAutoResumeGaveUp 是 GuardInfo.Kind 的一个取值:预设的「异常退出时自动续跑」决定不再续跑了(预算用完 / 连续没有进展 / 没法提交),需要你出面(#151)。守护事件(意外结束 / 停摆)的 Kind 为空。

Variables

View Source
var ErrInvalidConfig = errors.New("ntfy 配置不合法")

ErrInvalidConfig 表示配置取值不合法;错误信息面向用户,可以直接展示。

Functions

This section is empty.

Types

type Config

type Config struct {
	// Enabled 是总开关;关闭时事件被静默丢弃(配置仍保留)。
	Enabled bool `json:"enabled"`
	// Server 是 ntfy 服务地址,不带末尾斜杠;允许带路径前缀(反向代理场景)。
	Server string `json:"server"`
	// Topic 是主题名。公共的 ntfy.sh 上,知道主题名的人都能订阅,所以它相当于密码——请用足够长的随机名字。
	Topic string `json:"topic"`
	// Token 是 ntfy 访问令牌(Bearer);与 Username / Password 二选一,两者都有时令牌优先。
	Token    string `json:"token,omitempty"`
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	// ClickURL 是点击通知后打开的地址,一般填 RelayMesh 控制台的外部访问地址;留空则点击没有动作。
	ClickURL string `json:"click_url,omitempty"`
	// Priority 是 ntfy 优先级 1~5。
	Priority int `json:"priority"`
	// IncludeSummary 为真时,通知里附上智能体摘要的开头一小段;默认只发标题,避免内容经过第三方服务。
	IncludeSummary bool `json:"include_summary"`
	// DelaySeconds 大于 0 时延迟推送:这段时间里你在网页上处理掉了请求就不再推送(0 = 立即)。
	DelaySeconds int `json:"delay_seconds"`
	// RunNotify 为真时,模型发起的命令(ExecMesh)运行结束也推送一条:成功、失败、超时、结果丢失,
	// 以及被主机侧中断(例如守护进程重启);你自己或模型主动取消的不推。默认关闭,需要明确打开。
	RunNotify bool `json:"run_notify"`
	// RunMinSeconds 是运行结束推送的门槛:运行得比这更短的命令不推送,免得每条小命令都响铃。1~86400;0 视为默认值。
	RunMinSeconds int `json:"run_min_seconds"`
}

Config 是持久化的完整配置(含凭据);只存在于服务端,绝不整体返回给浏览器(见 Public)。

func (Config) Normalize

func (c Config) Normalize() Config

Normalize 去掉首尾空白并补默认值,不改变含义;校验之前先调用它。

func (Config) Public

func (c Config) Public(envToken string) PublicConfig

Public 生成对外视图;envToken 是环境变量里的令牌(有值时 token_set 与 token_from_env 都为真)。

func (Config) Validate

func (c Config) Validate(requireTopic bool) error

Validate 检查取值;cfg 应已 Normalize。requireTopic 为真时主题必填(启用或要发送测试时)。

func (Config) WithEnvToken

func (c Config) WithEnvToken(envToken string) Config

WithEnvToken 在环境变量提供了令牌时,让它盖过数据库里保存的令牌(令牌可以完全不进数据库)。

type EventInfo

type EventInfo struct {
	// ID 是事件的唯一标识;同一个 ID 在去重窗口内只推一次。
	ID string
	// Kind 是种类:agent_text / ask_card / mention / approval_waiting;决定没有预览时的那句话与图标。
	Kind string
	// Conversation 是聚合键:同一个会话的非穿透类消息合并成一条。留空表示不参与聚合。
	Conversation string
	// Title 是会话名;Sender 是发送者(与会话名相同时只写一个)。
	Title  string
	Sender string
	// Preview 是预览正文(已折成一行并截断);ShowPreview 为假时报文里不会出现它。
	Preview     string
	ShowPreview bool
	// Penetrate 为真表示穿透类:优先级 4、立即推送、不聚合。
	Penetrate bool
	// DeepLink 是站内路径(以 / 开头),拼到「点击打开的地址」后面。
	DeepLink string
}

EventInfo 是新消息类推送要用到的字段。纯数据:由接线处(api)把通知闸的事件翻译成它, ntfy 因此仍然只依赖标准库与 model。

type GuardInfo

type GuardInfo struct {
	// Kind 为空是守护事件(会话意外结束 / 智能体停摆);GuardKindAutoResumeGaveUp 是「不再自动续跑」,标题与末尾说明不同。
	Kind string
	// Key 标识「同一次事件的同一条推送」:预设编号 + 事件标识 + 第几次提醒。同一个 Key 在去重窗口内只推一次。
	Key string
	// Name 是预设的名字;Machine 是机器码(主机的显示名由 Notifier 在真正发送前解析)。
	Name    string
	Machine string
	// Crashed 为真表示会话意外结束;为假表示会话还在、但智能体停摆了。
	Crashed bool
	// Reason 是一句人话的原因,如「上一轮对话因出错中断(6 小时前),之后没有新的活动」。
	Reason string
	// Since 是事件的起点(意外结束的时间 / 停摆计时的起点);零值表示不详。
	Since time.Time
	// Reminder 为 0 表示首次通知;大于 0 表示这是同一次事件的第几次补发提醒。
	Reminder int
	// WorkflowID 是预设里填的工作流编号(用来在推送里写项目名);可为空。
	WorkflowID string
}

GuardInfo 是一次守护事件推送要用到的字段。纯数据,不依赖终端包:由接线处(api)把守护事件翻译成它。

type Message

type Message struct {
	Title    string
	Body     string
	Priority int
	Tags     []string
	Click    string
}

Message 是一条要推送的内容。

func BuildEventMessage

func BuildEventMessage(cfg Config, in EventInfo, count, merged int) Message

BuildEventMessage 生成新消息类的推送内容。count 是这一条代表的消息数(聚合后大于 1); merged 是此前因全局限流而没发出去的通知条数,大于 0 时在末尾说明一下。

func BuildGuardMessage

func BuildGuardMessage(cfg Config, in GuardInfo, host string, merged int, now time.Time) Message

BuildGuardMessage 生成守护事件的推送内容。host 是主机的显示名(没解析出来就传空串); merged 是此前因限流而没发出去的通知条数;now 用来把起点写成「已持续多久」。

func BuildRequestMessage

func BuildRequestMessage(cfg Config, in RequestInfo, merged int) Message

BuildRequestMessage 生成「新反馈请求」的推送内容。 merged 是此前因限流而没发出去的请求条数,大于 0 时在末尾说明一下,免得你以为只有这一条。

func BuildRunMessage

func BuildRunMessage(cfg Config, in RunInfo, host string, merged int) Message

BuildRunMessage 生成「模型运行结束」的推送内容。 host 是主机的显示名(没解析出来就传空串,推送里干脆不写主机,也不会拿机器码凑数); merged 是此前因限流而没发出去的通知条数,大于 0 时在末尾说明一下。

func BuildTestMessage

func BuildTestMessage(cfg Config, now time.Time) Message

BuildTestMessage 生成「测试推送」的内容。

type Notifier

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

Notifier 把「新反馈请求」「模型运行结束」「终端会话守护事件」与新消息类事件异步推送到 ntfy。 NotifyRequest / NotifyRun / NotifyGuard / NotifyEvent 永远不会阻塞调用方,推送失败或 ntfy 变慢也不会影响智能体的请求,更不会影响命令运行的收尾与守护的下一轮判断。

func New

func New(opts Options) *Notifier

New 创建并启动 Notifier。

func (*Notifier) EffectiveConfig

func (n *Notifier) EffectiveConfig(ctx context.Context) (Config, error)

EffectiveConfig 读取已保存的配置,并让环境变量里的令牌盖过去。

func (*Notifier) NotifyEvent

func (n *Notifier) NotifyEvent(in EventInfo)

NotifyEvent 登记一条新消息类事件。立即返回;事件当场复制,调用方之后随便改它。

func (*Notifier) NotifyGuard

func (n *Notifier) NotifyGuard(in GuardInfo)

NotifyGuard 登记一条终端会话守护事件(会话意外结束 / 智能体停摆)。立即返回;事件当场复制。 「同一次事件只推一次」由守护服务按持久化的事件标识保证,这里的去重(按 Key)只是进程内的第二道保险。

func (*Notifier) NotifyRequest

func (n *Notifier) NotifyRequest(s *model.FeedbackSession)

NotifyRequest 登记一条「智能体在等你回复」的事件。立即返回;会话内容当场复制,调用方之后随便改它。

func (*Notifier) NotifyRun

func (n *Notifier) NotifyRun(in RunInfo)

NotifyRun 登记一条「模型运行结束」的事件。立即返回;事件当场复制,调用方之后随便改它。 要不要推送由配置决定(见 RunInfo.WorthNotifying),这里只挡掉一定不会推送的那一大批。

func (*Notifier) SendTest

func (n *Notifier) SendTest(ctx context.Context, cfg Config) (Result, error)

SendTest 用给定配置立刻发一条测试推送(不排队、不限流、不看总开关),并记入「最近一次推送」。 只试一次、不重试:人在界面上等着看结果,要的是马上知道通不通,而不是后台悄悄再试几轮。

func (*Notifier) SetTiming

func (n *Notifier) SetTiming(delayUnit, mergeUnit time.Duration)

SetTiming 调整延迟推送与会话聚合的时间单位(默认都是 1 秒:「延迟 N 秒」= N×delayUnit,聚合 5 与冷却 20 同理)。 只供测试使用,必须在第一条事件之前调用;生产代码不要碰它。

func (*Notifier) Status

func (n *Notifier) Status() Status

Status 返回当前的推送情况快照。

func (*Notifier) Stop

func (n *Notifier) Stop()

Stop 让后台协程退出(取消进行中的推送);最多等 3 秒。可重复调用。

type Options

type Options struct {
	// Load 读取已保存的配置;必填。每条事件现读一次(主键查询,很便宜),所以界面上一保存就立即生效。
	Load func(ctx context.Context) (Config, error)
	// StillPending 供延迟推送在真正发出前复核:这条请求是否仍在等人回复。nil 表示总是需要推送。
	StillPending func(ctx context.Context, sessionID string) bool
	// HostName 把机器码解析成主机的显示名,只在「运行结束」真要推送时才调用(不推送的短命令不会去查库)。
	// nil 或返回空串都表示「不写主机」——推送里宁可少一行,也不拿机器码凑数。
	HostName func(ctx context.Context, machineCode string) string
	// EnvToken 是环境变量里的访问令牌,非空时盖过已保存的令牌。
	EnvToken string
	// Sender 为 nil 时用默认发送器。
	Sender *Sender
}

Options 是 Notifier 的依赖。

type PublicConfig

type PublicConfig struct {
	Enabled        bool   `json:"enabled"`
	Server         string `json:"server"`
	Topic          string `json:"topic"`
	Username       string `json:"username"`
	ClickURL       string `json:"click_url"`
	Priority       int    `json:"priority"`
	IncludeSummary bool   `json:"include_summary"`
	DelaySeconds   int    `json:"delay_seconds"`
	RunNotify      bool   `json:"run_notify"`
	RunMinSeconds  int    `json:"run_min_seconds"`
	TokenSet       bool   `json:"token_set"`
	PasswordSet    bool   `json:"password_set"`
	// TokenFromEnv 为真时令牌来自环境变量 RELAYMESH_NTFY_TOKEN,界面里改不了也清不掉。
	TokenFromEnv bool `json:"token_from_env"`
}

PublicConfig 是返回给浏览器的视图:凭据一律只给「是否已设置」,不给值。

type RequestInfo

type RequestInfo struct {
	SessionID        string
	WorkflowID       string
	Title            string
	Summary          string
	ProjectDirectory string
	HostName         string
}

RequestInfo 是「新反馈请求」推送要用到的字段。 取快照而不是持有会话指针:推送在别的协程里异步完成,而会话对象随后还会被修改。

func InfoFromSession

func InfoFromSession(s *model.FeedbackSession) RequestInfo

InfoFromSession 复制出推送需要的字段。

type Result

type Result struct {
	Status   int
	Attempts int
	Took     time.Duration
}

Result 是一次(含重试的)推送的结果摘要。

type RunInfo

type RunInfo struct {
	RunID string
	// State 是运行的终态,取值见 model.Run*。
	State string
	// Machine 是机器码;主机的显示名由接线处在真正发送前解析(见 Options.HostName),免得短命令也去查库。
	Machine string
	// Description 是模型写的一句话说明;Command 是脱敏后的命令文本。
	Description string
	Command     string
	ExitCode    *int
	Signal      string
	// Why 是终态原因的中文说明(如「主机重启,进程已丢失」),没有就空着。
	Why string
	// Duration 是命令实际运行的时长(不含等批准的时间);没跑起来的运行为 0。
	Duration         time.Duration
	WorkflowID       string
	ProjectDirectory string
	// CancelBy 是请求取消这次运行的来源(user / pause / revoked / system / model);空表示没有任何人要求取消。
	CancelBy string
}

RunInfo 是一次模型运行结束时推送要用到的字段。 取快照而不是持有运行记录:推送在别的协程里异步完成。它是纯数据,不依赖终端包—— 由接线处(api)把终端的运行结束事件翻译成它,ntfy 因此始终是只依赖标准库与 model 的叶子包。

func (RunInfo) WorthNotifying

func (in RunInfo) WorthNotifying(cfg Config) bool

WorthNotifying 判断这次运行结束要不要推送(总开关、主题等由 Notifier 另行检查)。

推送:成功、失败、超时、结果丢失,以及「没人要求取消、却被中断」(典型是主机上的守护进程停了或重启, 长任务因此被杀——这正是离开电脑的人最需要知道的)。 不推送:你或模型自己取消的(你已经知道了);被拒绝或被闸门拒绝的(根本没运行);运行得比门槛更短的。

type SendError

type SendError struct {
	// Status 是 HTTP 状态码;还没连上服务时为 0。
	Status     int
	Msg        string
	Retryable  bool
	RetryAfter time.Duration
}

SendError 描述一次推送为什么失败:Msg 面向用户且已抹掉凭据;Retryable 说明值不值得再试一次。

func (*SendError) Error

func (e *SendError) Error() string

type Sender

type Sender struct {

	// Backoff 是相邻两次尝试之间的等待;长度决定最多重试几次(总尝试数 = len(Backoff)+1)。
	Backoff []time.Duration
	// contains filtered or unexported fields
}

Sender 负责一次推送的 HTTP 细节。零值不可用,请用 NewSender。

func NewSender

func NewSender(userAgent string) *Sender

NewSender 创建默认的发送器:最多重试 2 次(1 秒、4 秒后),不跟随重定向,拒绝链路本地等危险地址。

func (*Sender) Send

func (s *Sender) Send(ctx context.Context, cfg Config, msg Message) (Result, error)

Send 推送一条消息;失败时返回 *SendError。可重试的失败(网络错误、5xx、429)按 Backoff 重试。

type Status

type Status struct {
	LastAttemptAt  *time.Time `json:"last_attempt_at,omitempty"`
	LastOK         bool       `json:"last_ok"`
	LastTest       bool       `json:"last_test"` // 最近一次是不是「测试推送」
	LastHTTPStatus int        `json:"last_http_status,omitempty"`
	LastError      string     `json:"last_error,omitempty"`
	Sent           int        `json:"sent"`
	Failed         int        `json:"failed"`
	// Dropped 是被限流合并或因队列已满而没发出的条数。
	Dropped int `json:"dropped"`
}

Status 是自进程启动以来的推送情况(只在内存里,重启清零)。

type Update

type Update struct {
	Enabled        bool   `json:"enabled"`
	Server         string `json:"server"`
	Topic          string `json:"topic"`
	Username       string `json:"username"`
	ClickURL       string `json:"click_url"`
	Priority       int    `json:"priority"`
	IncludeSummary bool   `json:"include_summary"`
	DelaySeconds   int    `json:"delay_seconds"`
	RunNotify      bool   `json:"run_notify"`
	RunMinSeconds  int    `json:"run_min_seconds"`

	Token         string `json:"token"`
	ClearToken    bool   `json:"clear_token"`
	Password      string `json:"password"`
	ClearPassword bool   `json:"clear_password"`
}

Update 是界面保存时提交的整张表单:非凭据字段整体替换;凭据「只写不读」—— 留空表示保持原值,要换就填新值,要清掉就带上对应的 clear_ 标记。

func (Update) ApplyTo

func (u Update) ApplyTo(cur Config) Config

ApplyTo 把表单叠加到当前已保存的配置上,返回新配置(已 Normalize,尚未校验)。

Jump to

Keyboard shortcuts

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