feat: 跨主机 Agent 验证 + 离线邮件补投 + 400 指向具体字段
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)
- 生产已部署
This commit is contained in:
@ -7,6 +7,7 @@ import { join, dirname, basename } from "node:path";
|
||||
// 都当成插件工厂,入口文件多导出一个东西就会 "Plugin export is not a function"。
|
||||
import { snapshotOpencodeSessions } from "./lib/session-snapshot.js";
|
||||
import { resolveWorkspaceCwd } from "./lib/workspace.js";
|
||||
import { selectCatchup } from "./lib/catchup.js";
|
||||
import {
|
||||
snapshotOpencodeModels,
|
||||
modelAttemptOrder,
|
||||
@ -845,6 +846,42 @@ export default async function mailBridge(input) {
|
||||
}
|
||||
}
|
||||
|
||||
// 已经投过的 mail_id。心跳与 SSE 建连之间有个窗口:那期间到的邮件
|
||||
// 既在 pending_mails 里、也会被 SSE 推一次 —— 不去重就会投两遍。
|
||||
const deliveredMails = new Set();
|
||||
|
||||
/**
|
||||
* 补投离线期间积压的未读邮件。
|
||||
*
|
||||
* SSE 只推连上之后的事件,插件重启前发来的邮件不会再推一次。
|
||||
* 不补的话那封邮件永远躺在收件箱里,而发件人以为 Agent 收到了。
|
||||
*/
|
||||
async function catchUp(pending) {
|
||||
if (!pending) return;
|
||||
try {
|
||||
const box = await apiGet("/mail/inbox?status=unread&limit=20");
|
||||
const tasks = selectCatchup(box?.mails ?? box, deliveredMails);
|
||||
if (tasks.length === 0) return;
|
||||
console.error(`[mail-bridge] 补投 ${tasks.length} 封离线期间的邮件(共 ${pending} 封未读)`);
|
||||
// 串行:每封都要起一轮模型,并发放出去等于对上游打 N 个并发请求
|
||||
for (const ev of tasks) {
|
||||
// 逐封再查一次:拉收件箱和逐封投递之间 SSE 可能已经投过其中某封
|
||||
// (selectCatchup 只在拉完那一刻去过重)
|
||||
if (deliveredMails.has(ev.mail_id)) continue;
|
||||
deliveredMails.add(ev.mail_id);
|
||||
try {
|
||||
await deliverMail(client, directory, ev, "mail");
|
||||
} catch (e) {
|
||||
console.error(`[mail-bridge] 补投 ${ev.mail_id} 失败:`, e?.message || e);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[mail-bridge] 补投失败:", e?.message || e);
|
||||
}
|
||||
}
|
||||
|
||||
let caughtUp = false;
|
||||
|
||||
const beat = async () => {
|
||||
const [platform_sessions, models] = await Promise.all([
|
||||
reportSessions(),
|
||||
@ -858,6 +895,12 @@ export default async function mailBridge(input) {
|
||||
// 生效的模型范围随心跳响应回传:管理员在配置页改了范围后,
|
||||
// 插件最多一个周期(30 秒)就能看到新值,不需要重启。
|
||||
if (Array.isArray(res?.allowed_models)) allowedModels = res.allowed_models;
|
||||
// 只在首个成功的心跳后补投一次:之后的积压都由 SSE 覆盖,
|
||||
// 每轮心跳都补的话会把「模型正在处理中、尚未标已读」的邮件重复投递。
|
||||
if (!caughtUp) {
|
||||
caughtUp = true;
|
||||
await catchUp(res?.pending_mails);
|
||||
}
|
||||
} catch {
|
||||
// 心跳失败不报错:网络抖动很常见,下一轮会补上。
|
||||
// 真的持续连不上时 Gateway 会把它判成离线,那才是可见的信号。
|
||||
@ -878,6 +921,7 @@ export default async function mailBridge(input) {
|
||||
}
|
||||
|
||||
if (type !== "new_mail") return;
|
||||
if (data?.mail_id) deliveredMails.add(data.mail_id);
|
||||
deliverMail(client, directory, data, "mail")
|
||||
.then(({ sessionID, reused }) => {
|
||||
console.error(`[mail-bridge] ${type} -> ${reused ? "续谈" : "新会话"} ${sessionID}`);
|
||||
|
||||
74
plugins/opencode-mail-bridge/lib/catchup.js
Normal file
74
plugins/opencode-mail-bridge/lib/catchup.js
Normal file
@ -0,0 +1,74 @@
|
||||
/**
|
||||
* 启动补拉:把插件离线期间到的邮件变成与 SSE 事件同形的投递任务。
|
||||
*
|
||||
* 为什么需要它:**SSE 只推连上之后的事件**。插件重启前发来的邮件不会再推一次,
|
||||
* 心跳响应的 `pending_mails` 是唯一线索。不补拉的后果是那封邮件永远躺在
|
||||
* 收件箱里,而发件人以为 Agent 收到了 —— 这比明确的失败更难排查。
|
||||
*
|
||||
* 两个平台共用,必须逐字节相同(deploy/check-shared-libs.sh 校验)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 一次补拉最多处理几封。
|
||||
*
|
||||
* 上限存在的理由:每封都要起一轮模型。攒了 80 封的时候一次性全放出去,
|
||||
* 等于对上游打 80 个并发请求,且最后那几封要等前面全部跑完。
|
||||
* 超出的部分留在收件箱里,下次重启或人工触发时再处理。
|
||||
*/
|
||||
export const MAX_CATCHUP = 5;
|
||||
|
||||
/**
|
||||
* 把收件箱里的一封邮件转成 SSE `new_mail` 那个形状。
|
||||
*
|
||||
* 补拉与 SSE 走同一条投递路径(deliverMail),因此形状必须一致 ——
|
||||
* 两条路径各写一遍投递逻辑的话,某一条上的修复会漏掉另一条。
|
||||
*
|
||||
* @param {any} mail `/mail/inbox` 返回的一行
|
||||
* @returns {{mail_id: string, session_id: string, from_name: string,
|
||||
* subject: string, mail_type: string, role: string,
|
||||
* to_workspace: string, catchup: true}}
|
||||
*/
|
||||
export function mailToEvent(mail) {
|
||||
return {
|
||||
mail_id: mail?.mail_id || '',
|
||||
session_id: mail?.session_id || '',
|
||||
from_name: mail?.from_name || '',
|
||||
subject: mail?.subject || '',
|
||||
mail_type: mail?.mail_type || 'normal',
|
||||
role: 'to',
|
||||
to_workspace: mail?.to_workspace || '',
|
||||
// 标记来源,投递侧可据此决定是否在提示词里说明「这是积压的邮件」
|
||||
catchup: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从收件箱挑出该补投的邮件。
|
||||
*
|
||||
* @param {any[]} mails `/mail/inbox?status=unread` 的结果
|
||||
* @param {Set<string>} seen 已经通过 SSE 投过的 mail_id(避免重复投递)
|
||||
* @param {number} [max] 上限,默认 MAX_CATCHUP
|
||||
* @returns {any[]} 与 SSE 事件同形的投递任务,按时间正序(老的先处理)
|
||||
*/
|
||||
export function selectCatchup(mails, seen, max = MAX_CATCHUP) {
|
||||
if (!Array.isArray(mails) || mails.length === 0) return [];
|
||||
|
||||
const picked = [];
|
||||
for (const m of mails) {
|
||||
const id = m?.mail_id;
|
||||
if (!id) continue;
|
||||
// 心跳与 SSE 建连之间有个窗口:那期间到的邮件既在 pending_mails 里、
|
||||
// 也会被 SSE 推一次。不去重就会投两遍,模型回两封信。
|
||||
if (seen && seen.has(id)) continue;
|
||||
// permission 类邮件不补投:它是给人看的询问,Agent 侧没有可恢复的上下文
|
||||
// (原来的工具调用早随进程一起没了),投过去只会让模型困惑。
|
||||
if (m?.mail_type && m.mail_type !== 'normal') continue;
|
||||
picked.push(m);
|
||||
}
|
||||
|
||||
// 收件箱按时间倒序返回,补投要按正序 —— 先来的先处理,
|
||||
// 否则同一会话里的多封邮件会被倒着塞进去,上下文顺序是乱的。
|
||||
picked.reverse();
|
||||
|
||||
return picked.slice(0, Math.max(0, max)).map(mailToEvent);
|
||||
}
|
||||
81
plugins/opencode-mail-bridge/test/catchup.test.mjs
Normal file
81
plugins/opencode-mail-bridge/test/catchup.test.mjs
Normal file
@ -0,0 +1,81 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { MAX_CATCHUP, mailToEvent, selectCatchup } from '../lib/catchup.js';
|
||||
|
||||
const mail = (over = {}) => ({
|
||||
mail_id: 'm1',
|
||||
session_id: 's1',
|
||||
from_name: 'admin',
|
||||
subject: '主题',
|
||||
mail_type: 'normal',
|
||||
to_workspace: '/tmp/ws',
|
||||
...over,
|
||||
});
|
||||
|
||||
test('mailToEvent 产出与 SSE new_mail 同形的对象', () => {
|
||||
const ev = mailToEvent(mail());
|
||||
// 投递侧读的就是这几个键,形状不一致会让补拉那条路径静默地少带信息
|
||||
for (const k of ['mail_id', 'session_id', 'from_name', 'subject', 'mail_type', 'to_workspace']) {
|
||||
assert.ok(k in ev, `缺少 ${k}`);
|
||||
}
|
||||
assert.equal(ev.role, 'to');
|
||||
assert.equal(ev.catchup, true);
|
||||
});
|
||||
|
||||
test('mailToEvent 对缺字段的行给出空串而非 undefined', () => {
|
||||
const ev = mailToEvent({});
|
||||
assert.equal(ev.mail_id, '');
|
||||
assert.equal(ev.to_workspace, '');
|
||||
assert.equal(ev.mail_type, 'normal');
|
||||
});
|
||||
|
||||
test('已经通过 SSE 投过的不再补投', () => {
|
||||
const mails = [mail({ mail_id: 'a' }), mail({ mail_id: 'b' })];
|
||||
const got = selectCatchup(mails, new Set(['a']));
|
||||
assert.deepEqual(got.map(e => e.mail_id), ['b']);
|
||||
});
|
||||
|
||||
test('按时间正序补投(收件箱是倒序返回的)', () => {
|
||||
// 收件箱:新的在前
|
||||
const mails = [mail({ mail_id: 'new' }), mail({ mail_id: 'mid' }), mail({ mail_id: 'old' })];
|
||||
const got = selectCatchup(mails, new Set());
|
||||
assert.deepEqual(
|
||||
got.map(e => e.mail_id),
|
||||
['old', 'mid', 'new'],
|
||||
'先来的邮件必须先处理,否则同一会话里的上下文顺序是乱的',
|
||||
);
|
||||
});
|
||||
|
||||
test('permission 类邮件不补投', () => {
|
||||
const mails = [mail({ mail_id: 'p', mail_type: 'permission' }), mail({ mail_id: 'n' })];
|
||||
const got = selectCatchup(mails, new Set());
|
||||
assert.deepEqual(got.map(e => e.mail_id), ['n']);
|
||||
});
|
||||
|
||||
test('超过上限的部分留在收件箱里', () => {
|
||||
const mails = Array.from({ length: MAX_CATCHUP + 4 }, (_, i) => mail({ mail_id: 'm' + i }));
|
||||
const got = selectCatchup(mails, new Set());
|
||||
assert.equal(got.length, MAX_CATCHUP, '一次补拉不该把几十封邮件同时放出去');
|
||||
});
|
||||
|
||||
test('上限可显式压到 0(用于禁用补拉)', () => {
|
||||
const got = selectCatchup([mail()], new Set(), 0);
|
||||
assert.deepEqual(got, []);
|
||||
});
|
||||
|
||||
test('空输入与非数组不炸', () => {
|
||||
assert.deepEqual(selectCatchup([], new Set()), []);
|
||||
assert.deepEqual(selectCatchup(undefined, new Set()), []);
|
||||
assert.deepEqual(selectCatchup(null, new Set()), []);
|
||||
});
|
||||
|
||||
test('没有 mail_id 的行跳过', () => {
|
||||
const got = selectCatchup([mail({ mail_id: '' }), mail({ mail_id: 'ok' })], new Set());
|
||||
assert.deepEqual(got.map(e => e.mail_id), ['ok']);
|
||||
});
|
||||
|
||||
test('seen 传 undefined 时不去重也不报错', () => {
|
||||
const got = selectCatchup([mail({ mail_id: 'x' })], undefined);
|
||||
assert.deepEqual(got.map(e => e.mail_id), ['x']);
|
||||
});
|
||||
Reference in New Issue
Block a user