Go 单二进制网关 + React 前端 + opencode 桥接插件。部署产物是 「一个二进制加一个 .db 文件」:前端经 go:embed 打进二进制, 数据库默认内置 SQLite,systemd 托管。 核心设计 - 三维寻址 name@path.session,按最后一个 . 切分;session 位三态: 省略=默认会话 / new=强制新建 / 具体别名=必须已存在(否则 404 无法送达) - 会话别名默认复用 Agent 平台自己的命名机制(opencode 的 slug 与模型生成的 标题),不在本侧另造一套;人显式定过的别名不被平台同步覆盖 - 对话树不建 tree_nodes 表:parent_mail_id 已完整编码树结构, 再维护一张表就是第二份真相。用递归 CTE 查,按方向分块加载 - 附件内容存磁盘、按 sha256 内容寻址,数据库只存元数据;天然去重, 且路径与用户 filename 无关,杜绝 ../ 穿越 - 配额约束的是模型的自主发信,不是 harness 的转发:插件代劳的权限询问与 最终总结走免配额通道,靠上游消息 id 做幂等键而非计数 - 往返预算下沉到会话(写信时给、对话页里改)+ Agent 全局配额,两层都要过 后端 gateway/ - models/repo/handler/middleware/sse/blob 分层;两方言(SQLite/PostgreSQL) 共用一份 repo 层 SQL,差异集中在 internal/db - 多用户认证(bcrypt cost12、登录限速、会话隔离、权限边界) - 密钥体系:Agent 密钥与用户密钥分表,三种生命周期;登记式密钥让全文 只从客户端流向服务器一次 - 所有「判断 + 自增」都在同一条 UPDATE 里(配额、预算、one_time 密钥、 附件挂载),并发下不会刷穿 前端 web/ - 三栏布局、三段式地址补全、权限卡片、密钥面板、配额面板、对话树、附件 - 全站纯 SVG 图标,不使用 emoji - api/ 即可复用的客户端 SDK:基地址与凭证集中在 api/config.ts 插件 plugins/opencode-mail-bridge/ - 六个工具 + 两类自动转发(permission.ask 钩子接管平台原生权限询问、 session.idle 时转发本轮总结)
286 lines
8.2 KiB
Go
286 lines
8.2 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 err := Decode(r, &req); err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid JSON")
|
||
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)
|
||
|
||
// 新建会话时接受往返预算。只在新建时设:续谈已有会话若也接受这个字段,
|
||
// 每封新信都会悄悄改掉对方正在遵守的预算,人却不一定意识到自己改了。
|
||
if req.MaxRounds != nil && parentMailID == nil {
|
||
if *req.MaxRounds < 0 {
|
||
Error(w, http.StatusBadRequest, "max_rounds 不能为负")
|
||
return
|
||
}
|
||
if _, err := repo.SetSessionBudget(r.Context(), sessionID, *req.MaxRounds); 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
|
||
}
|
||
// 列表页要显示附件图标与下载入口
|
||
for i := range mails {
|
||
fillAttachments(r, &mails[i])
|
||
}
|
||
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 {
|
||
for i := range mails {
|
||
fillAttachments(r, &mails[i])
|
||
}
|
||
}
|
||
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"`
|
||
}
|
||
|
||
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,
|
||
})
|
||
}
|
||
|
||
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 ""
|
||
}
|