四个各自独立的生产缺陷,共同的根源都是「本该属于会话的属性没有存在会话上」。 ## 1. dsh 指定工作目录完全失效(所有会话落进「未分组」) 插件建会话时用的 cwd 是自己拼的 `~/.dsh/mail-sessions/mail-<uuid>` —— 每封邮件一个全新的空目录。DSH 与 opencode 都按 cwd 给会话分组,于是所有 邮件会话既不属于任何项目、彼此也不同组。 而 Gateway 从来没把地址里的 path 位发给插件:`notifyRecipients` 的 payload 只有 mail_id/session_id/from_name/subject,`to_workspace` 虽然入库了却不在 SSE 事件里,插件即使想用也拿不到。 - SSE `new_mail` 事件加 `to_workspace`。**每个收件方拿到自己那个地址的 path**, 不是主收件人的 —— 抄送给 opencode@/a 与主发给 dsh@/b 是两个工作区 - 两个插件的 cwd 都改为取寻址的 path 位;不存在的目录**不创建**而是回退到 兜底目录(一个笔误不该在磁盘上落下真目录,Agent 会在里面一无所获地干活) - 拒绝相对路径:cwd 的相对基准是 harness 进程的启动目录,systemd 下通常是 `/` ## 2. 会话别名列不出工作区下的历史会话(无法选择) workspace 只存在于 `mails.to_workspace` 上,「这个工作区下有哪些会话」必须 JOIN mails 再从收发双方的 workspace 里猜。而 Agent 回信时 from_workspace 填的是 **Agent 名**而不是路径,旧条件 `to_workspace = $p OR from_workspace = $p` 在只剩 Agent 回信可匹配时两边都对不上。 - `sessions.workspace` 新列,`CreateSession` 从地址的 path 位带入 - `SuggestSessionCandidates` 取代 `SuggestSessionsFor`:以会话自己的 workspace 为权威,历史会话(该列为空)回退到 mails 反推 —— 升级后老会话不该消失 - `FindOrCreateDefaultSession` 同步改用会话的 workspace ## 3. 平台侧会话在补全里根本不存在 人直接在 opencode/DSH 界面上开的会话,Gateway 一无所知。 新增 `agent_platform_sessions` 镜像表,插件在心跳里上报快照。 **上报而非 Gateway 反向拉取**:当前架构是单向的(Agent 持密钥主动连 Gateway, Gateway 从不外呼),反向拉取需要它保存各平台的地址与凭证,那是另一套信任模型。 - 与 sessions 表分开存:镜像里是别人家的会话,id 属于平台的 id 空间,没有 本侧的 owner/预算/邮件。混进 sessions 会让每一处「按会话鉴权」都要先判断 这条到底是不是真的本侧会话 - **整表替换而非增量合并**:平台侧删掉的会话必须从候选里消失 —— session 位是 三态语义,指向不存在的会话直接 404 - **nil 与空数组语义不同**:插件拉不到列表时省略该字段(保留镜像), 而不是传空数组把镜像抹掉 - **subagent 子会话不上报**:实测 DSH 的 list 里混着 49 条子会话,标题就是 派活的提示词前缀(九条都叫 "You are auditing ONE file"),slug 全撞名; 它们是父 agent 内部的工作单元,人往里发邮件毫无意义 - **slug 撞名只留最近那条**:服务端只能取其中一条,上报同名项只会让补全里 出现几个点哪个都不确定的候选 - DSH 插件此前**完全没有心跳** —— Gateway 靠 last_seen 判在线,一直靠注册撑着 补全候选带标题与来源:`suggestions` 保留纯字符串数组(不打破已部署的前端与 第三方客户端),新增同序的 `candidates`。过滤时标题也参与匹配 —— 人记得的是 「缓存选型」而不是 brisk-harbor 这种随机短名。 ## 4. 对话树看不见抄送与转发产生的分支 旧实现从锚点分「祖先链 + 子树」两路展开,而**兄弟节点既不是锚点的祖先也不是 它的子孙**:一封抄送给两个 Agent 的邮件收到两个回复,从其中一个看树永远看不到 另一个;挂在原件上的转发分支同理。 改为先 `ThreadRootOf` 上溯到线索根,再从根整树 BFS。只剩一个加载方向, 因此不再需要滚动位置补偿。前端补上抄送人列表与转发标记 —— 树上两个兄弟节点 为什么并列,唯一的解释就是父邮件抄送给了两个人。 ## 5. DSH 插件(Phase 7.7) 卡了一下午的 `Cannot read properties of undefined (reading 'kind')` 根因是 `followup()` 的参数形状:DSH 要完整的 UserMessage(content + source), 而我照抄了 opencode 的 parts 数组。错误抛在 agent-loop 内部,不指向调用点。 - `agent/status` → idle 时自动转发最后一条 assistant 消息(对应 opencode 的 session.idle),复用 relay-dedup 让位于模型的主动回信,走免配额通道 - `approval/request` 权限询问转邮件问人。与 opencode 的差异:那边的 permission.ask 是同步钩子只能立即返回 ask,DSH 这边是异步 waterfall, 可以真的等人 —— 拆插件时未决询问一律 fail closed,否则 await 永不返回 - 会话别名由模型标题派生(保留中文,去掉 `.` `@` `/` 等寻址分隔符 —— 留在别名里会让它自己被解析器切开) - 逻辑放 lib/ 下的纯函数并加测试:三类约定都是「错了不当场报错、只在深处 炸一个无关错误」 ## 其他 - `deploy/reset-demo.sh`:清空演示邮件数据,保留账号与密钥。备份用 `.backup` 而非 cp(WAL 下 cp 拿到的是缺尾巴的库);手工按依赖顺序删(SQLite 的 foreign_keys 默认关,声明了 REFERENCES 也不级联);只在目标是默认库时才碰 systemd(演练时误停过一次生产服务) - 插件 dist/ 不进版本库,install.sh 负责构建 - `permission_decision` 事件补 session_id:插件重启丢了待决映射时要靠它定位会话
284 lines
8.6 KiB
Go
284 lines
8.6 KiB
Go
package handler
|
||
|
||
import (
|
||
"errors"
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/agentmail/gateway/internal/sse"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- Permission ----------
|
||
|
||
type permissionRequestRequest struct {
|
||
Question string `json:"question"`
|
||
Options []string `json:"options"`
|
||
Context string `json:"context"`
|
||
SessionID *string `json:"session_id"`
|
||
// 可选:显式指定决策人(人类用户名)。省略时由会话 owner 决定。
|
||
To string `json:"to"`
|
||
// RelayKey 是上游那条权限询问的稳定 id(opencode 的 permission.id)。
|
||
//
|
||
// 权限请求本来就不扣配额(人不点头 Agent 就动不了,收费等于收「求人费」),
|
||
// 这里要的只是**幂等**:permission.updated 事件会重复触发,插件也会重连重放,
|
||
// 没有幂等键就会给同一次询问生成好几封邮件。
|
||
RelayKey string `json:"relay_key"`
|
||
}
|
||
|
||
type permissionDecideRequest struct {
|
||
MailID string `json:"mail_id"`
|
||
Decision string `json:"decision"`
|
||
Note string `json:"note"`
|
||
}
|
||
|
||
// POST /api/v1/permission/request
|
||
func RequestPermission(w http.ResponseWriter, r *http.Request) {
|
||
agentName := middleware.GetAgentName(r)
|
||
if agentName == "" {
|
||
Error(w, http.StatusUnauthorized, "Unauthorized")
|
||
return
|
||
}
|
||
|
||
var req permissionRequestRequest
|
||
if err := Decode(r, &req); err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid JSON")
|
||
return
|
||
}
|
||
if req.Question == "" {
|
||
Error(w, http.StatusBadRequest, "Missing question")
|
||
return
|
||
}
|
||
|
||
options := req.Options
|
||
if len(options) == 0 {
|
||
options = []string{"同意", "拒绝"}
|
||
}
|
||
|
||
// 幂等:同一条上游询问只生成一封邮件。
|
||
// 重复不是故障(插件重试/事件重放的正常结果),因此幂等地返回已存在的结论而非报错。
|
||
relayKey := strings.TrimSpace(req.RelayKey)
|
||
if relayKey != "" {
|
||
if len(relayKey) > 160 {
|
||
Error(w, http.StatusBadRequest, "relay_key 过长(上限 160 字节)")
|
||
return
|
||
}
|
||
if err := repo.ClaimRelay(r.Context(), agentName, relayKey, "permission"); err != nil {
|
||
if errors.Is(err, repo.ErrRelayDuplicate) {
|
||
JSON(w, http.StatusOK, map[string]any{
|
||
"status": "duplicate_relay",
|
||
"relay_key": relayKey,
|
||
"detail": "该权限询问已转发过,本次调用未产生新邮件",
|
||
})
|
||
return
|
||
}
|
||
Error(w, http.StatusInternalServerError, "Failed to claim relay")
|
||
return
|
||
}
|
||
}
|
||
|
||
// 确定 session
|
||
var sessionID uuid.UUID
|
||
if req.SessionID != nil && *req.SessionID != "" {
|
||
id, err := uuid.Parse(*req.SessionID)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid session_id")
|
||
return
|
||
}
|
||
sessionID = id
|
||
repo.TouchSession(r.Context(), sessionID)
|
||
} else {
|
||
// workspace 空串:权限询问不经三维寻址,没有 path 位可归属。
|
||
id, err := repo.CreateSession(r.Context(), nil, agentName, "权限请求: "+req.Question, "")
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to create session")
|
||
return
|
||
}
|
||
sessionID = id
|
||
}
|
||
|
||
// 决策人:显式指定优先,否则取会话 owner
|
||
decider := req.To
|
||
if decider == "" || decider == "human" {
|
||
owner, err := repo.SessionOwnerUsername(r.Context(), sessionID)
|
||
if err == nil && owner != "" {
|
||
decider = owner
|
||
}
|
||
}
|
||
if decider == "" {
|
||
// 会话无归属(Agent 自发起)时退回默认管理员
|
||
admin, err := repo.FirstAdminUsername(r.Context())
|
||
if err != nil || admin == "" {
|
||
Error(w, http.StatusConflict, "无法确定决策人,请在请求中指定 to")
|
||
return
|
||
}
|
||
decider = admin
|
||
}
|
||
|
||
body := req.Context
|
||
if body == "" {
|
||
body = req.Question
|
||
}
|
||
mailID, err := repo.CreatePermissionMail(r.Context(), sessionID, agentName, decider, req.Question, body, options)
|
||
if err != nil {
|
||
// 归还幂等键,否则这次询问永远转不出来了
|
||
if relayKey != "" {
|
||
_ = repo.ReleaseRelay(r.Context(), agentName, relayKey)
|
||
}
|
||
Error(w, http.StatusInternalServerError, "Failed to create permission mail")
|
||
return
|
||
}
|
||
if relayKey != "" {
|
||
_ = repo.BindRelayMail(r.Context(), agentName, relayKey, mailID)
|
||
}
|
||
if err := repo.CreatePermissionRequest(r.Context(), mailID, sessionID, agentName, req.Question, options, req.Context); err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to create permission request")
|
||
return
|
||
}
|
||
|
||
// 只推给该决策人
|
||
sse.Default.SendToUser(decider, "new_mail", map[string]interface{}{
|
||
"mail_id": mailID.String(),
|
||
"session_id": sessionID.String(),
|
||
"from_name": agentName,
|
||
"subject": "权限请求: " + req.Question,
|
||
"mail_type": "permission_request",
|
||
"role": "to",
|
||
})
|
||
|
||
JSON(w, http.StatusOK, map[string]string{
|
||
"mail_id": mailID.String(),
|
||
"session_id": sessionID.String(),
|
||
"permission_mail_id": mailID.String(),
|
||
"decider": decider,
|
||
})
|
||
}
|
||
|
||
// POST /api/v1/permission/decide —— 需登录;只有该权限请求的收件人或管理员可决策
|
||
func DecidePermission(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
var req permissionDecideRequest
|
||
if err := Decode(r, &req); err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid JSON")
|
||
return
|
||
}
|
||
if req.MailID == "" || req.Decision == "" {
|
||
Error(w, http.StatusBadRequest, "Missing mail_id or decision")
|
||
return
|
||
}
|
||
|
||
mailID, err := uuid.Parse(req.MailID)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid mail_id UUID")
|
||
return
|
||
}
|
||
|
||
perm, err := repo.GetPermissionByMailID(r.Context(), mailID)
|
||
if err != nil {
|
||
Error(w, http.StatusNotFound, "Permission request not found")
|
||
return
|
||
}
|
||
if perm.Result != nil && *perm.Result != "" {
|
||
Error(w, http.StatusConflict, "该请求已被处理")
|
||
return
|
||
}
|
||
|
||
// 鉴权:必须是这封权限邮件的收件人,或管理员
|
||
mail, err := repo.GetMailByID(r.Context(), mailID)
|
||
if err != nil {
|
||
Error(w, http.StatusNotFound, "Mail not found")
|
||
return
|
||
}
|
||
if !user.IsAdmin() && mail.ToName != user.Username {
|
||
Error(w, http.StatusForbidden, "无权决策他人的权限请求")
|
||
return
|
||
}
|
||
|
||
// 决策选项必须在候选内
|
||
if !contains(perm.Options, req.Decision) {
|
||
Error(w, http.StatusBadRequest, "决策必须是候选项之一")
|
||
return
|
||
}
|
||
|
||
if _, err := repo.DecidePermission(r.Context(), mailID, req.Decision); err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to decide permission")
|
||
return
|
||
}
|
||
|
||
decisionMailID, err := repo.CreateDecisionMail(
|
||
r.Context(), perm.SessionID, mailID, user.Username, perm.AgentName, req.Decision, req.Note)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to create decision mail")
|
||
return
|
||
}
|
||
|
||
// 通知发起 Agent 恢复执行
|
||
// 带上上游 permission id:插件要拿它回复 opencode 的原生权限询问。
|
||
// 两边 id 空间不同,光给 AgentMail 的 mail_id 插件对不上;
|
||
// 而插件重启后内存映射会丢,所以这个映射由服务端持久化并在此回传。
|
||
payload := map[string]interface{}{
|
||
"mail_id": mailID.String(),
|
||
"decision_mail_id": decisionMailID.String(),
|
||
"decision": req.Decision,
|
||
"note": req.Note,
|
||
"decided_by": user.Username,
|
||
// 会话 id:插件重启丢了待决映射时,会退化成「把决策当一封通知投进会话」,
|
||
// 那条路径要靠这个字段找到原会话,否则会凭空另开一个。
|
||
"session_id": perm.SessionID.String(),
|
||
}
|
||
if key, kind := repo.RelayKeyForMail(r.Context(), mailID); key != "" {
|
||
payload["relay_key"] = key
|
||
payload["relay_kind"] = kind
|
||
}
|
||
sse.Default.SendToAgent(perm.AgentName, "permission_decision", payload)
|
||
// 只刷新决策人自己的界面
|
||
sse.Default.SendToUser(user.Username, "session_update", map[string]interface{}{
|
||
"session_id": perm.SessionID.String(),
|
||
"status": "active",
|
||
})
|
||
|
||
JSON(w, http.StatusOK, map[string]string{
|
||
"status": "decided",
|
||
"decision_mail_id": decisionMailID.String(),
|
||
})
|
||
}
|
||
|
||
// GET /api/v1/permission/pending —— 需登录;普通用户只看发给自己的
|
||
func ListPendingPermissions(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
forUser := user.Username
|
||
if user.IsAdmin() && r.URL.Query().Get("all") == "true" {
|
||
forUser = ""
|
||
}
|
||
|
||
reqs, err := repo.ListPendingPermissionsFor(r.Context(), forUser)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list pending permissions")
|
||
return
|
||
}
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"requests": emptySlice(reqs),
|
||
})
|
||
}
|
||
|
||
func contains(list []string, v string) bool {
|
||
for _, s := range list {
|
||
if s == v {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|