7.8「跨主机 Agent 发现」原计划(Gateway + Registry 拆分、etcd/Consul 注册)
取消,改为验证现有协议已经够用。验证过程暴露两个真实缺陷,一并修掉。
## 为什么不做注册中心
它要解决「Gateway 怎么找到 Agent」,而这个问题在本架构里不存在:
连接方向是单向的 —— Agent 主动连 Gateway,Gateway 从不外呼。
远端 Agent 只需要一个公网 URL 加一把密钥,被叫方自己会打进来。
注册中心要解决的「被叫方在哪」根本没出现过。
同一个理由此前已经决定了平台会话同步走插件上报而不是 Gateway 拉取。
## 验证方式:一个纯标准库脚本
`deploy/remote-agent-demo.py` 在另一台主机(192.168.2.106)上跑,
不装 AgentMail 的任何代码。注册 / 心跳(带模型目录)/ SSE 长连 /
收件箱 / 标记已读 / 发信全通,Gateway 侧 status=online 且 last_seen 随心跳推进。
完整一轮往返跑通:admin 发给 remotebot@/tmp/remotebot-ws,脚本回信入库。
「协议层面已支持」的含义就是这个:跨主机不需要新组件,只需要三个环境变量。
## 缺陷一:SSE 只推连上之后的事件,没人补拉积压
写那个脚本时第一版只挂了 SSE,启动前发的邮件永远不会被处理。
查了才发现**两个正式插件也有这个洞** —— 原以为它们做了补拉,实际没有。
后果比明确的失败更难排查:邮件躺在收件箱里,而发件人以为 Agent 收到了。
新增共用模块 `lib/catchup.js`,两插件在首个成功心跳后补投一次。五条约束
都对应一种具体的坏行为:
- 只在**首个**心跳后补 —— 每轮都补会把「模型正在处理中、尚未标已读」的
邮件重复投递
- 串行、一次最多 5 封 —— 每封都要起一轮模型,并发放出去等于对上游打 N 个
并发请求,且最后几封要等前面全部跑完
- 与 SSE 共用 deliveredMails 去重 —— 心跳与 SSE 建连之间有个窗口,
那期间到的邮件两条路都会到
- 按时间**正序**投(收件箱倒序返回)—— 倒着塞进去同一会话的上下文是乱的
- permission 类不补投 —— 原来的工具调用早随进程没了,没有可恢复的上下文
端到端两平台各验一次:停插件 → 发信 → 启插件 → 日志「补投 1 封离线期间的
邮件」→ 回信入库;随后在线再发一封确认只回一次。
## 缺陷二:400 只说 "Invalid JSON",不说是哪个字段
脚本把 `workspaces` 传成字符串数组(它要 `[{name, path}]`),
得到的只是一句固定文案,只能靠翻服务端结构体才能发现。
两个官方插件都传 `workspaces: []`,所以这个洞一直没暴露;
第三方客户端没有「翻服务端源码」这个条件。
新增 `handler.DecodeBody`,22 处 `Decode` + 固定文案的调用点全部换过去:
{"error": "字段 \"workspaces\" 类型不对:期望 object,收到 string"}
{"error": "JSON 语法错误(第 8 字节处)"}
{"error": "请求体为空"}
刻意不回显 encoding/json 的原文 —— 它带 Go 类型名(models.Workspace),
那是本侧的实现细节,不该出现在公开 API 的响应里。期望类型用 JSON 的说法。
截断的 JSON 走 io.ErrUnexpectedEOF 而不是 json.SyntaxError,单独一条分支,
否则会落到笼统的兜底文案里(写测试时才发现)。
## 验证
- Go:13 个新测试(decode_test.go 含「不得泄漏 Go 类型名」断言)
- 插件:两侧各 10 个补投测试,共 200 个
- 共用模块同源校验通过(catchup 已纳入 check-shared-libs.sh)
- 生产已部署
305 lines
8.9 KiB
Go
305 lines
8.9 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
"time"
|
||
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/models"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- /me:当前登录人类用户的邮箱(全部路由需 UserAuth) ----------
|
||
|
||
type meSendMailRequest struct {
|
||
To string `json:"to"` // name@path.session
|
||
CC string `json:"cc"` // 多个 name@path.session
|
||
Subject string `json:"subject"`
|
||
Body string `json:"body"`
|
||
ReplyTo string `json:"reply_to"`
|
||
// SessionAlias 仅在本次投递【新建】会话时生效,为新会话命名
|
||
SessionAlias string `json:"session_alias"`
|
||
// AttachmentIDs 先用 POST /me/attachments 上传拿到的 id
|
||
AttachmentIDs []string `json:"attachment_ids"`
|
||
// MaxRounds 是本次任务的往返预算(0/省略 = 不限)。
|
||
//
|
||
// 配额的真实语义是「这件事值得多少个来回」——那是任务的属性,
|
||
// 所以在派活的这一刻给,而不是事后到管理员页面去调某个 Agent 的全局配额。
|
||
// 仅在本次投递【新建】会话时生效;续谈已有会话请用
|
||
// PUT /sessions/{id}/budget(对话页里可随时改)。
|
||
MaxRounds *int `json:"max_rounds"`
|
||
}
|
||
|
||
// POST /api/v1/me/mail/send
|
||
func MeSendMail(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
var req meSendMailRequest
|
||
if !DecodeBody(w, r, &req) {
|
||
return
|
||
}
|
||
if req.To == "" || req.Subject == "" || req.Body == "" {
|
||
Error(w, http.StatusBadRequest, "Missing to, subject, or body")
|
||
return
|
||
}
|
||
|
||
to, err := models.ParseAddress(req.To)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid to address: "+err.Error())
|
||
return
|
||
}
|
||
ccList, err := models.ParseAddressList(req.CC)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid cc address: "+err.Error())
|
||
return
|
||
}
|
||
attachIDs, err := parseAttachmentIDs(req.AttachmentIDs)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, err.Error())
|
||
return
|
||
}
|
||
|
||
// human@ 是兼容别名,人类发信时解析为自己
|
||
to = resolveHumanAlias(to, user.Username)
|
||
for i := range ccList {
|
||
ccList[i] = resolveHumanAlias(ccList[i], user.Username)
|
||
}
|
||
|
||
// 权限边界:校验可调用的 Agent 与可访问的目录
|
||
if msg := checkScope(r, user, append([]models.Address{to}, ccList...)); msg != "" {
|
||
Error(w, http.StatusForbidden, msg)
|
||
return
|
||
}
|
||
|
||
sessionID, parentMailID, err := resolveTarget(r, to, req.ReplyTo, user.Username, req.Subject, req.SessionAlias, "")
|
||
if err != nil {
|
||
writeErr(w, err, "Failed to resolve session")
|
||
return
|
||
}
|
||
// 人类发起的会话归属于该用户
|
||
_ = repo.SetSessionOwner(r.Context(), sessionID, user.ID)
|
||
|
||
// 新建会话时定往返预算。只在新建时设:续谈已有会话若也接受这个字段,
|
||
// 每封新信都会悄悄改掉对方正在遵守的预算,人却不一定意识到自己改了。
|
||
//
|
||
// 没显式给就用【收件 Agent 的默认值】。默认值挂在 Agent 上而不是全站一个数:
|
||
// 跑测试的小工具与重构整个模块的 Agent,合理来回数差一个量级。
|
||
if parentMailID == nil {
|
||
rounds := 0
|
||
if req.MaxRounds != nil {
|
||
if *req.MaxRounds < 0 {
|
||
Error(w, http.StatusBadRequest, "max_rounds 不能为负")
|
||
return
|
||
}
|
||
rounds = *req.MaxRounds
|
||
} else {
|
||
rounds = repo.DefaultRoundsFor(r.Context(), to.Name)
|
||
}
|
||
if _, err := repo.SetSessionBudget(r.Context(), sessionID, rounds); err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to set session budget")
|
||
return
|
||
}
|
||
}
|
||
|
||
// 人类侧不产生改名提议(人直接有改名按钮,用不着向自己提议),
|
||
// 但仍然剥掉标记:粘贴进正文时它会被渲染成一行可见的转义文本。
|
||
_, body := extractRenameProposal(req.Body)
|
||
|
||
mailID, err := repo.CreateMail(r.Context(), sessionID, parentMailID,
|
||
user.Username, "", to.Name, to.Path, req.Subject, body, ccList)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to create mail")
|
||
return
|
||
}
|
||
|
||
if !attachAll(w, r, mailID, attachIDs, user.Username) {
|
||
return
|
||
}
|
||
|
||
notifyRecipients(to, ccList, sessionID, mailID, user.Username, req.Subject)
|
||
|
||
resp := map[string]any{
|
||
"mail_id": mailID.String(),
|
||
"session_id": sessionID.String(),
|
||
"session_alias": repo.SessionAliasOf(r.Context(), sessionID),
|
||
}
|
||
// 回传预算,让前端不必再单独查一次就能显示「本任务还剩几个来回」
|
||
if b, err := repo.GetSessionBudget(r.Context(), sessionID); err == nil && !b.Unlimited {
|
||
resp["budget_max"] = b.Max
|
||
resp["budget_used"] = b.Used
|
||
resp["budget_remaining"] = b.Remaining
|
||
}
|
||
JSON(w, http.StatusOK, resp)
|
||
}
|
||
|
||
// GET /api/v1/me/mail/inbox
|
||
func MeGetInbox(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
status := r.URL.Query().Get("status")
|
||
if status == "" {
|
||
status = "all"
|
||
}
|
||
limit := 50
|
||
if l := r.URL.Query().Get("limit"); l != "" {
|
||
if n, err := parseInt(l); err == nil && n > 0 {
|
||
limit = n
|
||
}
|
||
}
|
||
|
||
mails, err := repo.ListInbox(r.Context(), user.Username, status, limit)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list inbox")
|
||
return
|
||
}
|
||
// 列表页要显示附件图标与下载入口
|
||
ptrs := make([]*models.Mail, len(mails))
|
||
for i := range mails {
|
||
ptrs[i] = &mails[i]
|
||
}
|
||
fillAttachments(r, ptrs...)
|
||
total, _ := repo.CountUnread(r.Context(), user.Username)
|
||
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"mails": emptySlice(mails),
|
||
"total": total,
|
||
})
|
||
}
|
||
|
||
// GET /api/v1/me/mail/sent
|
||
func MeGetSent(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
limit := 50
|
||
if l := r.URL.Query().Get("limit"); l != "" {
|
||
if n, err := parseInt(l); err == nil && n > 0 {
|
||
limit = n
|
||
}
|
||
}
|
||
|
||
mails, err := repo.ListSentBy(r.Context(), user.Username, limit)
|
||
if err == nil {
|
||
ptrs := make([]*models.Mail, len(mails))
|
||
for i := range mails {
|
||
ptrs[i] = &mails[i]
|
||
}
|
||
fillAttachments(r, ptrs...)
|
||
}
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list sent")
|
||
return
|
||
}
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"mails": emptySlice(mails),
|
||
})
|
||
}
|
||
|
||
// GET /api/v1/me/sessions
|
||
func MeGetSessions(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
scope := user.Username
|
||
if user.IsAdmin() && r.URL.Query().Get("all") == "true" {
|
||
scope = ""
|
||
}
|
||
|
||
sessions, err := repo.ListSessionsFor(r.Context(), scope, 50)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list sessions")
|
||
return
|
||
}
|
||
|
||
type SessionOut struct {
|
||
SessionID uuid.UUID `json:"session_id"`
|
||
SessionAlias *string `json:"session_alias"`
|
||
FromAgent string `json:"from_agent"`
|
||
Subject string `json:"subject"`
|
||
Status string `json:"status"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
MailCount int `json:"mail_count"`
|
||
UnreadCount int `json:"unread_count"`
|
||
// 往返预算随列表一并返回:预算是【任务】的属性,
|
||
// 工作列表上就应当看得见哪些任务快跑满了,
|
||
// 而不是点进去一个一个查。
|
||
MaxRounds int `json:"max_rounds"`
|
||
UsedRounds int `json:"used_rounds"`
|
||
}
|
||
|
||
result := make([]SessionOut, 0, len(sessions))
|
||
for _, s := range sessions {
|
||
unread, _ := repo.CountUnreadInSession(r.Context(), user.Username, s.ID)
|
||
result = append(result, SessionOut{
|
||
SessionID: s.ID,
|
||
SessionAlias: s.Alias,
|
||
FromAgent: s.FromAgent,
|
||
Subject: s.Subject,
|
||
Status: s.Status,
|
||
CreatedAt: s.CreatedAt,
|
||
UpdatedAt: s.UpdatedAt,
|
||
MailCount: s.MailCount,
|
||
UnreadCount: unread,
|
||
MaxRounds: s.MaxRounds,
|
||
UsedRounds: s.UsedRounds,
|
||
})
|
||
}
|
||
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"sessions": result,
|
||
})
|
||
}
|
||
|
||
// resolveHumanAlias 把兼容别名 human 解析为具体用户名
|
||
func resolveHumanAlias(a models.Address, username string) models.Address {
|
||
if a.Name != "human" {
|
||
return a
|
||
}
|
||
a.Name = username
|
||
a.Raw = username + "@" + a.Path
|
||
if a.Session != "" {
|
||
a.Raw += "." + a.Session
|
||
}
|
||
return a
|
||
}
|
||
|
||
// checkScope 校验用户的 Agent 白名单与目录白名单;返回空串表示通过。
|
||
// 收件方是人类用户时不受 Agent 白名单约束(人与人通信始终允许)。
|
||
func checkScope(r *http.Request, user *models.User, addrs []models.Address) string {
|
||
if user.IsAdmin() {
|
||
return ""
|
||
}
|
||
for _, a := range addrs {
|
||
if a.Name == "" || a.Name == user.Username {
|
||
continue
|
||
}
|
||
isHuman, err := repo.IsHumanUser(r.Context(), a.Name)
|
||
if err != nil {
|
||
return "无法校验收件人权限"
|
||
}
|
||
if !isHuman && !user.CanUseAgent(a.Name) {
|
||
return "无权调用 Agent: " + a.Name
|
||
}
|
||
if !user.CanUsePath(a.Path) {
|
||
return "无权访问目录: " + a.Path
|
||
}
|
||
}
|
||
return ""
|
||
}
|