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 时转发本轮总结)
243 lines
8.5 KiB
Go
243 lines
8.5 KiB
Go
package models
|
||
|
||
import (
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// Agent 代表一个已注册的 Agent 实例
|
||
type Agent struct {
|
||
ID uuid.UUID `json:"agent_id"`
|
||
Name string `json:"agent_name"`
|
||
Secret string `json:"-"`
|
||
HostURL string `json:"host_url"`
|
||
Workspaces []Workspace `json:"workspaces"`
|
||
Platform string `json:"platform"`
|
||
Status string `json:"status"`
|
||
MaxRounds int `json:"max_rounds"`
|
||
UsedRounds int `json:"used_rounds"`
|
||
LastSeen *time.Time `json:"last_seen"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// Workspace 是 Agent 管理的项目工作区
|
||
type Workspace struct {
|
||
Name string `json:"name"`
|
||
Path string `json:"path"`
|
||
}
|
||
|
||
// Session 是有明确边界的任务会话
|
||
type Session struct {
|
||
ID uuid.UUID `json:"session_id"`
|
||
Alias *string `json:"session_alias"`
|
||
FromAgent string `json:"from_agent"`
|
||
Subject string `json:"subject"`
|
||
Status string `json:"status"`
|
||
OwnerUserID *uuid.UUID `json:"owner_user_id"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
MailCount int `json:"mail_count,omitempty"`
|
||
|
||
// RenameDismissed 是用户驳回过的改名提议。
|
||
// 记下来才能让提示条不再反复弹同一个建议。
|
||
RenameDismissed string `json:"rename_dismissed,omitempty"`
|
||
|
||
// AliasSource 记录别名是谁定的:
|
||
// platform = Agent 平台自动同步来的,后续同步可以覆盖
|
||
// manual = 人显式指定(手工改名或接受了 Agent 的提议),平台同步不得覆盖
|
||
// 没有这个区分,平台下一次 session.updated 会把人刚定的名字冲掉。
|
||
AliasSource string `json:"alias_source,omitempty"`
|
||
|
||
// MaxRounds/UsedRounds 是本任务的往返预算(0 = 本会话不限)。
|
||
// 配额的语义是「这件事值得多少个来回」,那是任务的属性而非 Agent 的属性,
|
||
// 所以在写信时给、在对话页里随时调。
|
||
MaxRounds int `json:"max_rounds"`
|
||
UsedRounds int `json:"used_rounds"`
|
||
}
|
||
|
||
// User 是人类用户(多用户账号体系)
|
||
type User struct {
|
||
ID uuid.UUID `json:"user_id"`
|
||
Username string `json:"username"`
|
||
DisplayName string `json:"display_name"`
|
||
PasswordHash string `json:"-"`
|
||
Role string `json:"role"` // admin / user
|
||
Status string `json:"status"` // active / disabled
|
||
CreatedAt time.Time `json:"created_at"`
|
||
LastLogin *time.Time `json:"last_login"`
|
||
|
||
// 权限边界:空切片 = 不限
|
||
AllowedAgents []string `json:"allowed_agents"`
|
||
AllowedPaths []string `json:"allowed_paths"`
|
||
}
|
||
|
||
// IsAdmin 判断是否管理员
|
||
func (u User) IsAdmin() bool { return u.Role == "admin" }
|
||
|
||
// CanUseAgent 判断用户是否可向指定 Agent 发信
|
||
// 空白名单(或为空) = 不限;管理员不受限;收件方是人类用户时不走此限制
|
||
func (u User) CanUseAgent(agentName string) bool {
|
||
if u.IsAdmin() || len(u.AllowedAgents) == 0 {
|
||
return true
|
||
}
|
||
for _, a := range u.AllowedAgents {
|
||
if a == agentName {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// CanUsePath 判断用户是否可访问指定工作区。
|
||
// 空白名单 = 不限;管理员不受限;空 path(人类地址)总是允许。
|
||
// 匹配规则:完全相等,或白名单项作为目录前缀(/program 允许 /program/sub)。
|
||
func (u User) CanUsePath(path string) bool {
|
||
if u.IsAdmin() || len(u.AllowedPaths) == 0 || path == "" {
|
||
return true
|
||
}
|
||
for _, p := range u.AllowedPaths {
|
||
if p == "" {
|
||
continue
|
||
}
|
||
if path == p {
|
||
return true
|
||
}
|
||
prefix := p
|
||
if !strings.HasSuffix(prefix, "/") {
|
||
prefix += "/"
|
||
}
|
||
if strings.HasPrefix(path, prefix) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// Mail 是会话中的一封邮件
|
||
type Mail struct {
|
||
ID uuid.UUID `json:"mail_id"`
|
||
SessionID uuid.UUID `json:"session_id"`
|
||
ParentMailID *uuid.UUID `json:"parent_mail_id"`
|
||
FromName string `json:"from_name"`
|
||
FromWorkspace string `json:"from_workspace"`
|
||
ToName string `json:"to_name"`
|
||
ToWorkspace string `json:"to_workspace"`
|
||
CCList []Address `json:"cc_list"`
|
||
Subject string `json:"subject"`
|
||
Body string `json:"body"`
|
||
MailType string `json:"mail_type"`
|
||
PermOptions []string `json:"permission_options,omitempty"`
|
||
PermResult string `json:"permission_result,omitempty"`
|
||
Status string `json:"status"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
HopLimit int `json:"hop_limit"`
|
||
|
||
SessionAlias string `json:"session_alias,omitempty"`
|
||
BodyPreview string `json:"body_preview,omitempty"`
|
||
|
||
// Attachments 仅在读取单封邮件/会话线程时填充;列表接口为省带宽留空
|
||
Attachments []Attachment `json:"attachments,omitempty"`
|
||
|
||
// RenameAlias / RenameReason 是 Agent 在本封正文里提议的新会话别名。
|
||
// 存在邮件上而非会话上:邮件是不可篡改的历史记录,
|
||
// 「谁在哪一封里提了什么」应当留痕。
|
||
RenameAlias string `json:"rename_alias,omitempty"`
|
||
RenameReason string `json:"rename_reason,omitempty"`
|
||
}
|
||
|
||
// PermissionRequest 是 Agent 向人类发起的权限请求
|
||
type PermissionRequest struct {
|
||
ID uuid.UUID `json:"request_id"`
|
||
MailID uuid.UUID `json:"mail_id"`
|
||
SessionID uuid.UUID `json:"session_id"`
|
||
AgentName string `json:"agent_name"`
|
||
Question string `json:"question"`
|
||
Options []string `json:"options"`
|
||
Context string `json:"context"`
|
||
Result *string `json:"result"`
|
||
DecidedAt *time.Time `json:"decided_at"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// SSE 事件类型
|
||
const (
|
||
EventNewMail = "new_mail"
|
||
EventPermissionDecision = "permission_decision"
|
||
EventSessionUpdate = "session_update"
|
||
EventAgentOnline = "agent_online"
|
||
)
|
||
|
||
// ---------- 密钥认证 ----------
|
||
|
||
// 密钥类型:签发时决定其生命周期
|
||
const (
|
||
// KeyPermanent 永不过期,可重复使用(正式部署的 Agent 用这个)
|
||
KeyPermanent = "permanent"
|
||
// KeyOneTime 首次验证后即失效(用于把 Agent 首次接入的窗口压到最小)
|
||
KeyOneTime = "one_time"
|
||
// KeyTimed 到 ExpiresAt 之后失效
|
||
KeyTimed = "timed"
|
||
)
|
||
|
||
// ValidKeyType 判断密钥类型是否受支持
|
||
func ValidKeyType(t string) bool {
|
||
return t == KeyPermanent || t == KeyOneTime || t == KeyTimed
|
||
}
|
||
|
||
// AgentKey 是管理员签发的 Agent 接入密钥。
|
||
// AgentName 为空表示「待绑定」——密钥有效但还没指定属于哪个 Agent,
|
||
// 首次注册时由注册请求里的 name 落定。
|
||
type AgentKey struct {
|
||
ID uuid.UUID `json:"key_id"`
|
||
Token string `json:"key_token,omitempty"` // 仅创建时回显一次
|
||
TokenHint string `json:"token_hint"` // 前 8 位 + 省略号,用于列表展示
|
||
AgentName *string `json:"agent_name"`
|
||
KeyType string `json:"key_type"`
|
||
Label string `json:"label"`
|
||
ExpiresAt *time.Time `json:"expires_at"`
|
||
UsedAt *time.Time `json:"used_at"`
|
||
CreatedBy *uuid.UUID `json:"created_by"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// UserKey 是用户自助签发的客户端连接密钥,只能用于 /me/* 人类邮箱接口。
|
||
type UserKey struct {
|
||
ID uuid.UUID `json:"key_id"`
|
||
Token string `json:"key_token,omitempty"` // 仅创建时回显一次
|
||
TokenHint string `json:"token_hint"`
|
||
UserID uuid.UUID `json:"user_id"`
|
||
Label string `json:"label"`
|
||
KeyType string `json:"key_type"`
|
||
ExpiresAt *time.Time `json:"expires_at"`
|
||
UsedAt *time.Time `json:"used_at"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// TokenHint 返回密钥的展示形式:只露前 8 位。
|
||
// 密钥全文仅在创建响应里出现一次,之后任何列表接口都只给 hint。
|
||
func TokenHint(token string) string {
|
||
if len(token) <= 8 {
|
||
return token
|
||
}
|
||
return token[:8] + "…"
|
||
}
|
||
|
||
// ---------- 附件 ----------
|
||
|
||
// Attachment 是一封邮件的附件元数据。文件内容存磁盘,按 sha256 内容寻址。
|
||
//
|
||
// MailID 为空表示「已上传、尚未挂到邮件上」:上传与发信是两步操作
|
||
//(Agent 侧工具走 JSON,无法在发信请求里带 multipart),中间态必须允许存在。
|
||
type Attachment struct {
|
||
ID uuid.UUID `json:"attachment_id"`
|
||
MailID *uuid.UUID `json:"mail_id"`
|
||
Uploader string `json:"uploader"`
|
||
Filename string `json:"filename"`
|
||
ContentType string `json:"content_type"`
|
||
SizeBytes int64 `json:"size_bytes"`
|
||
SHA256 string `json:"sha256"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|