微信收信泛化为媒体管线:image/video/file 经 SDK download → inbox(base64) → core magic 嗅探落会话任务目录(文件留消毒原名、图/视频生成 wximg-/wxvid- 名)+ files 元数据 + 「用户上传了文件」告知行(同 web 附件链路,vision 模型 read_file 即见);voice 二期占位;hookRouter 自带 32mb 解析器并前置于全局 json(2mb)

This commit is contained in:
2026-09-27 23:39:17 +08:00
parent b2e81a4f24
commit d1f4b354c1
7 changed files with 139 additions and 19 deletions
+7
View File
@@ -58,6 +58,12 @@ function newSessionFor(db, user, channel, firstText) {
return { s, sent };
}
// 解析 (user,channel) 的当前会话,无绑定则新建并绑定(不发消息)——
// 微信图片入口需要先拿到会话才能落任务目录文件,随后再走 handleSend 拼告知行。
function ensureSession(db, user, channel) {
return boundSession(db, user, channel) || newSessionFor(db, user, channel, '').s;
}
// ---------- 命令解析 ----------
// 严格匹配:整条消息恰好是命令词(仅 /new 可带尾随文本)才算命令。
// 首词形如 /纯ASCII词 但不在清单 → 回「未知命令」提示、不转发模型(防弱模型就着 /hlep 演一段);
@@ -209,3 +215,4 @@ router.post('/send', wrap((req, res) => {
module.exports = router;
module.exports.handleSend = handleSend;
module.exports.ensureSession = ensureSession;
+7 -4
View File
@@ -1,8 +1,8 @@
// 微信接入路由:
// - 本文件默认导出 = Web 侧 router(挂在 auth.middleware 之后,cookie 鉴权 + req.user 隔离);
// - 具名导出 hookRouter = wxbot → core 的内网回调入口(/wxhook/*),挂在 auth.middleware 之前,
// 形态同 GET /p/<id>(Core 上除登录外的匿名入口家族),靠共享服务 token(Bearer,常量时间比较)把门。
// 业务全部在 wechat.js,这里只做鉴权、归属过滤与 HTTP 形状。
// 本文件默认导出 = Web 侧 router(挂在 auth.middleware 之后,cookie 鉴权 + req.user 隔离);
// 具名导出 hookRouter = wxbot → core 的内网回调入口(/wxhook/*),挂在 auth.middleware 与全局
// express.json 之前(媒体转发的 base64 远超 2mb,由下方专用大限额解析器处理),
// 凭 Bearer 服务 token(常量时间比较)把门。业务全在 wechat.js,这里只做鉴权、归属过滤与 HTTP 形状。
const crypto = require('crypto');
const express = require('express');
const engine = require('../engine');
@@ -10,6 +10,9 @@ const wechat = require('../wechat');
const router = express.Router();
const hookRouter = express.Router();
// wxbot 专用 JSON 入口:媒体 base64 大 body(解码后限 20MB,b64 膨胀 4/3);比全局 2mb 宽得多。
// 本 router 先于全局解析器挂载,body-parser 认到 req._body 后全局那份会自动跳过。
hookRouter.use(express.json({ limit: '32mb' }));
function wrap(fn) {
return function (req, res) {
+5 -4
View File
@@ -34,6 +34,11 @@ wechat.init(cfg, db, bus);
const app = express();
const server = http.createServer(app);
// wxbot 内网回调(/wxhook/inbox|hook):凭共享服务 token(Bearer)把门,微信用户永远不该直接碰
// 这两个端点(wxbot 只挂内网)。必须挂在全局 express.json(2mb) 之前:媒体 base64 转发体远超 2mb,
// 由 hookRouter 自带的 32mb 解析器先读掉并置 req._body,下游全局 json 解析器自动跳过(同 executor 不冲突)。
app.use('/wxhook', require('./routes/wechat').hookRouter);
app.use(express.json({ limit: '2mb' }));
// 登录认证(cookie 会话):users 配在 config.yml 的 auth.users;留空则不启用。
@@ -45,10 +50,6 @@ app.use(auth.router); // /login、/logout、/api/login 等免认证端点
// 安全性来自“22 字符随机 ID + 服务端过期”,详见 routes/public-files.js 头注释。
app.use('/p', require('./routes/public-files'));
// wxbot 内网回调(/wxhook/inbox|hook):同在 auth.middleware 之前,凭共享服务 token(Bearer)把门,
// 微信用户永远不该直接碰这两个端点(wxbot 只挂内网,不暴露公网)。
app.use('/wxhook', require('./routes/wechat').hookRouter);
app.use(auth.middleware); // 其余请求需登录态(cookie 或 Basic 头)
app.use(express.static(path.join(__dirname, 'public')));
+82 -2
View File
@@ -12,9 +12,11 @@
// 降级承诺:wxbot.url 未配置 = 功能整体静默关闭;配置了但 wxbot 没起 = 启动只留一行日志,
// 面板显示「未连接」、操作时报可读错误,绝不抛出未捕获异常影响 Web 主流程。
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const engine = require('./engine');
const log = require('./log');
const channel = require('./routes/channel'); // 只用 handleSend(模块加载无副作用;engine 不 require 本模块,无环)
const channel = require('./routes/channel'); // 只用 handleSend/ensureSession(模块加载无副作用;engine 不 require 本模块,无环)
let cfg, db, bus;
let busAttached = false;
@@ -234,6 +236,12 @@ function handleHook(body) {
// 微信来消息 → channel 层同一入口。返回 handleSend 结果;抛错冒给 hook 路由映射成非 2xx,
// wxbot 会把 error 文案直接回给用户(IM 里「出错要出声」)。
// 媒体消息(inbox 带 media:{b64,kind,filename?},wxbot 已从 CDN 下好):统一落会话任务目录
// + 记 files 元数据表 → 按 web 上传同款拼「用户上传了文件:<名>」作正文走 handleSend。
// 命名规则:图片/视频微信侧本无名 → 生成 wximg-/wxvid- 时间戳名;文件保留原名(sanitise 后,
// 对 AI 可读性重要),撞名加 -N;扩展名以 magic 嗅探为准(不信声明值)。
const MEDIA_MAX_BYTES = 20 * 1024 * 1024;
const MEDIA_KINDS = new Set(['image', 'video', 'file']);
function handleInbox(body) {
const b = getBinding(String((body || {}).id || ''));
if (!b) throw Object.assign(new Error('绑定不存在(可能已解绑)'), { status_code: 404 });
@@ -241,14 +249,86 @@ function handleInbox(body) {
if (from && from !== b.wx_to_user) touchBinding(b.id, { wx_to_user: from });
// 能收到消息就说明实例活着;漏收 online 回调(core 重启窗口)时顺带纠偏
if (b.status !== 'online') touchBinding(b.id, { status: 'online', note: null });
let text = String((body || {}).text || '').trim();
const m = (body || {}).media;
if (m && String(m.b64 || '').trim()) {
const kind = MEDIA_KINDS.has(String(m.kind || '')) ? String(m.kind) : 'file';
let buf;
try { buf = Buffer.from(String(m.b64).trim().slice(0, Math.ceil(MEDIA_MAX_BYTES / 3) * 4 + 1024), 'base64'); } catch (_) { buf = null; }
if (!buf || !buf.length) throw Object.assign(new Error('媒体数据无法解析'), { status_code: 400 });
if (buf.length > MEDIA_MAX_BYTES) throw Object.assign(new Error('附件过大(限 20MB)'), { status_code: 400 });
const s = channel.ensureSession(db, b.user, 'wx:' + b.id);
const name = saveTaskMedia(s, buf, kind, String(m.filename || ''));
text = text ? '用户上传了文件:' + name + '\n\n' + text : '用户上传了文件:' + name;
log.info('file', (b.user || '-') + ' [微信 ' + b.id + '] ' + kind + ' 落任务目录 ' + s.id + '/' + name + '(' + buf.length + ' 字节)');
}
return channel.handleSend(db, {
user: b.user,
channel: 'wx:' + b.id,
text: (body || {}).text,
text,
tag: (b.user || '-') + ' [微信 ' + b.id + ']',
});
}
// magic bytes 定真实格式(不信声明扩展名):图片四类 + 常见视频两类;认不出的交给命名处兕底。
function sniffMediaExt(buf) {
if (buf.length > 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpg';
if (buf.length > 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return 'png';
if (buf.length > 3 && buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) return 'gif';
if (buf.length > 12 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') return 'webp';
if (buf.length > 12 && buf.toString('ascii', 4, 8) === 'ftyp') return 'mp4';
if (buf.length > 4 && buf[0] === 0x00 && buf[1] === 0x00 && buf[2] === 0x01 && buf[3] === 0x00) return 'mp4'; // 裸 MPEG 容器/其他
return '';
}
// 文件名消毒:只留路径末段,剔除控制字符与路径/shell 危符(保留中文),限长;全脏则退回 fallback。
function sanitizeMediaName(raw, fallback) {
let n = String(raw || '').split(/[\\/]/).pop().trim();
n = n.replace(/[\u0000-\u001f"'`$\\:*?<>|\u200b\u200e\u200f]+/g, '-').replace(/\s+/g, ' ').replace(/^-+/, '').replace(/\.+$/, '');
if (n.startsWith('.')) n = n.slice(1); // 防隐藏文件(点前缀在文件列表被隐)
if (n.length > 48) {
const dot = n.lastIndexOf('.');
const ext = dot > 0 && n.length - dot <= 6 ? n.slice(dot) : '';
n = n.slice(0, 48 - ext.length) + ext;
}
return n || (fallback || 'file');
}
// 落盘:图片/视频生成时间戳名(扩展名以嗅探为准),文件保留消毒后的原名;撞名加 -N;记 files 元数据行。
function saveTaskMedia(s, buf, kind, rawName) {
const dir = engine.taskDirOf(s.id);
const sniff = sniffMediaExt(buf);
const d = new Date();
const pad = n => String(n).padStart(2, '0');
const ts = d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + '-' + pad(d.getHours()) + pad(d.getMinutes()) + pad(d.getSeconds());
let name;
if (kind === 'image' || kind === 'video') {
const prefix = kind === 'image' ? 'wximg' : 'wxvid';
let ext = sniff;
if (!ext) { // 嗅探失败才退回声明名里的扩展名(≤5 位字母数字),再不行 bin
const dot = String(rawName || '').lastIndexOf('.');
const tail = dot >= 0 ? String(rawName).slice(dot + 1).toLowerCase() : '';
ext = /^[a-z0-9]{1,5}$/.test(tail) ? tail : 'bin';
}
name = prefix + '-' + ts + '.' + ext;
} else {
const safe = sanitizeMediaName(rawName, 'wxfile-' + ts);
const dot = safe.lastIndexOf('.');
const stem = dot > 0 ? safe.slice(0, dot) : safe;
const ext = dot > 0 ? safe.slice(dot) : (sniff ? '.' + sniff : '');
name = stem + ext;
}
let final = name;
for (let n = 1; fs.existsSync(path.join(dir, final)); n++) {
const dot = name.lastIndexOf('.');
final = (dot > 0 ? name.slice(0, dot) : name) + '-' + n + (dot > 0 ? name.slice(dot) : '');
}
fs.writeFileSync(path.join(dir, final), buf);
db.prepare('INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)')
.run(s.id, final, buf.length, now());
return final;
}
// ---------- 投递:进程内总线监听 → 分段 push wxbot /api/deliver ----------
// 只推最终 assistant 文本(type=errAck / 纯工具轮空文本 / 存档类事件都不进微信);
// 游标 last_msg_id 落库:core 重启不补发历史,wxbot 短暂不可达时不丢(下一条事件连带补齐)。
+2 -2
View File
@@ -427,7 +427,7 @@ AI 通过 `schedule` 工具为所在会话建周期性任务(`scheduled_tasks`
背景:仓库内 `wxbot/`(已入库,作为根 compose 的 `wxbot` 服务)是基于官方 iLink 协议 SDK 的微信「调制解调器」,只挂 `agent-mcp-net` 内网、不暴露公网;身份权威与全部会话逻辑在 core,引擎不感知微信。
- **模型**:一条 `wechat_bindings` = 一个 core 用户 = 一个 bot 实例(一人一绑,换号先解绑)。binding id 三用:实例控制/投递的寻址键、wxbot 凭证目录名、channel 键(`channel='wx:'+id`,因此命令层、会话自动新建、投递游标查询全部白借 §5.4 的 channel 机制,零新逻辑)。iLink 协议保证扫码登录后仅本人可与 bot 单线对话,无陌生人入口,故无联系人授权面。
- **方向三条线**:① Web(设置页→账户→微信内联卡)→ `/api/wechat` → wxbot `/api/instances*`(实例控制;QR SVG 代理内联渲染,只在 has_qr 就绪后取码,服务 token 不出内网);② wxbot 收信 → `POST core:/wxhook/inbox` → 直调 `channel.handleSend()`(命令回执同步回文本;普通消息不回执,等异步投递);③ core 总线监听 assistant_message → 分段(~1800 字/段,行优先聚合)→ `POST wxbot:/api/deliver` → `bot.send`。
- **方向三条线**:① Web(设置页→账户→微信内联卡)→ `/api/wechat` → wxbot `/api/instances*`(实例控制;QR SVG 代理内联渲染,只在 has_qr 就绪后取码,服务 token 不出内网);② wxbot 收信 → `POST core:/wxhook/inbox` → 直调 `channel.handleSend()`(文本;image/video/file 媒体先落会话任务目录再拼「用户上传了文件」告知行,同 web 附件链路,voice 二期——命令回执同步回文本;普通消息不回执,等异步投递);③ core 总线监听 assistant_message → 分段(~1800 字/段,行优先聚合)→ `POST wxbot:/api/deliver` → `bot.send`。
- **投递游标** `last_msg_id` 落库 + 每绑定串行队列:重启不重发旧回复,wxbot 短暂不可达不丢(下一条连带补齐);errAck/纯工具轮(空文本)不进微信,`__blocks__` 图消息降级为占位文案。
- **降级承诺**:`wxbot.url` 未配 = 功能整体静默关闭(启动零日志噪声、设置页入口隐藏);配了但 wxbot 没起 = restore 只留一行 info,面板显示未连接,所有外呼失败只 warn,绝不阻塞/抛出未捕获异常影响 Web 主流程(鉴权/探活失败同样只降级)。绑定/刷新/解绑对 wxbot 均 **fire-and-forget**(点击秒回,不拿 wxbot 网络往返卡按钮;失败落 note 由轮询/刷新按钮恢复);`overview()` 每轮访问拿实例快照双向纠偏(补建缺失实例/纠正丢的 hook),`restore()` 启动对账兼清孤儿实例;前端内联卡按渲染串比对增量更新,QR 只在 has_qr 就绪后才取码,无闪烁无坏图帧。
- 鉴权:双向共用一个服务 token(根 .env `WXBOT_TOKEN`,init.sh 生成/复用)——core→wxbot 时 wxbot 把该 env 自动并入 /api 白名单;wxbot→core 走 `/wxhook`(挂 auth.middleware 之前,Bearer 哈希后定长比较,token 未配一律 503 fail-closed)。wxbot 零配置文件(同 executor 模式),接线全靠 env,config.yml 仅作可选覆盖。
@@ -491,7 +491,7 @@ AI 通过 `schedule` 工具为所在会话建周期性任务(`scheduled_tasks`
| `/api/profile` | `routes/profile.js` | `GET /` 读画像、`PUT /` 保存(三字段 + enabled);按 `req.user` 隔离,逻辑全在 `user-profile.js`(快照冻结见 engine `createSession`/`clearSessionMessages`,提取见 `enterExecuting`) |
| `/api/channel` | `routes/channel.js` | `POST /send {channel, text}` 文本命令接入端(IM/CLI 等无 UI 客户端,走 Basic/cookie 鉴权):命令仅在本入口解析(Web 消息路由不受影响,防误伤路径/代码文本);严格匹配白名单 `/new[文本] /stop /compact /clear /status /help`,未知斜杠词回提示、不像命令的当普通消息;(user,channel) 经 `channel_sessions` 表绑定当前会话(普通消息无绑定自动建);命令动作不落消息行(与 Web 按钮对称),AI 回复由接入端复用既有 SSE/详情接口获取;`handleSend()` 另供微信桥接直调 |
| `/api/wechat` | `routes/wechat.js` | 微信绑定管理(设置页,cookie 鉴权 + req.user 隔离):`GET /`(enabled/alive/我的绑定)、`POST /`(新建绑定,一人一绑)、`GET /:id/qr`(登录二维码 SVG 代理)、`POST /:id/refresh`(重发登录)、`DELETE /:id`(解绑,销毁实例与凭证);业务全在 `wechat.js`(§5.13) |
| `/wxhook` | `routes/wechat.js`(hookRouter) | wxbot → core 内网回调(**挂 auth.middleware 之前**,形态同 `/p`):`POST /inbox {id, from, text}` 收信转 channel 层(非 2xx 时 wxbot 把 error 文案回给微信用户);`POST /hook {id, event}` 实例状态回报;Bearer 共享服务 token(哈希后定长比较,未配一律 503) |
| `/wxhook` | `routes/wechat.js`(hookRouter) | wxbot → core 内网回调(**挂 auth.middleware 与全局 express.json 之前**,自带 32mb 解析器容纳媒体 base64):`POST /inbox {id, from, text, media?}` 文本/媒体转 channel 层——media={kind:image\|video\|file, b64, filename?},core 按 magic 嗅探定扩展名、落会话任务目录(文件保留消毒原名,图/视频生成 wximg-/wxvid- 时间戳名)+ 记 files 表 + 拼「用户上传了文件:<名>」告知行(同 web 附件模式,vision 模型 read_file 即见);非 2xx 时 wxbot 把 error 文案回给微信用户;`POST /hook {id, event}` 实例状态回报;Bearer 共享服务 token(哈希后定长比较,未配一律 503) |
| `/api/models` | `server.js` | 模型池(在用会话数 slots_used / 在用会话列表,非独占展示)+ token 用量 |
| `/api/health` | `server.js` | 健康检查 |
| `/api/login` `/api/login_restore` `/api/logout` `/api/password` `/api/me` | `auth.js` | 认证路由(认证前) |
+5 -3
View File
@@ -24,6 +24,8 @@ agent-core 的 `wechat_bindings` 表;扫码二维码呈现在 agent-core 的 W
- 收信 → core `/wxhook/inbox` 复用 **channel 命令层**(`/new /stop /compact /clear /status /help`),
命令回执同步回文本;普通消息(AI 回复)异步由 core 经 `/api/deliver` 推送(`bot.send`)。
图片/视频/文件消息经 SDK `download` 取字节随 inbox 转发(限 20MB),core 落会话任务目录并拼
「用户上传了文件」告知行——与 web 上传附件同一条链路,vision 模型 read_file 即可看图。
- **单线对话**:iLink 扫码登录后只有绑定者本人能与 bot 会话,无陌生人入口,故无联系人授权面。
- 实例凭证按绑定隔离在 `./data/bots/<binding_id>/`,容器重启自动恢复登录免扫码;
启动时扫描该目录逐个拉起实例(core 不在线也照常上线,状态回调失败不影响,首条消息会纠偏)。
@@ -76,7 +78,7 @@ WXBOT_TOKEN=$WXBOT_TOKEN CORE_URL=http://127.0.0.1:8090 \
## 已知边界 / 后续扩展
- 非文本消息(图/语音/文件)目前只回 `bot.empty_hint` 占位。二期:
语音 → SDK `bot.download(msg)` 拿 WAV(需 `silk-wasm`)→ tools/asr `/api/transcribe`;
图片/文件 → core 的 `GET /p/<id>` 公网链喂 `bot.send(userId, {url})`(SDK 自动下载上传 CDN)。
- 语音消息目前回 `bot.empty_hint` 占位(二期:SDK `bot.download(msg)` 拿 WAV(需 `silk-wasm`)
→ tools/asr `/api/transcribe` 转写后进会话)。
- 出站图片/文件二期:core 的 `GET /p/<id>` 公网链喂 `bot.send(userId, {url})`(SDK 自动下载上传 CDN)。
- core 未配 `WXBOT_URL` 时微信功能整体静默关闭(设置页不出现入口,服务零报错)。
+31 -4
View File
@@ -29,7 +29,7 @@ const DEFAULTS = {
bot: {
storage_dir: "/data/bots", // 每绑定一个子目录(目录名 = binding id)
log_level: "info", // debug | info | warn | error | silent
empty_hint: "(暂时只收得到文字哦,发文字或 /help 试试)", // 非文本消息的本地兜底回执
empty_hint: "(这条消息类型暂时接不住——支持文字/图片/视频/文件;指令可发 /help)", // 未接入类型(voice/贴纸等)的本地兑底回执
},
};
@@ -214,16 +214,43 @@ function createInstance(id) {
// 收信 → 转发 core inbox。命令回执(kind=command)同步回文本;
// 普通消息(kind=message)不回执——最终回复稍后由 core 经 /api/deliver 推过来。
// 媒体消息(image/video/file):SDK 下好字节随 inbox 转发(core 落任务目录 + 拼「用户上传了文件」
// 告知行,同 web 附件模式)。msg.text 对媒体消息是 SDK 占位描述(如 "[image]"),不能当真正文,
// 故只认 type==='text';voice 等未接入类型回占位提示。
const MEDIA_KINDS = new Set(["image", "video", "file"]);
async function onIncoming(inst, msg) {
const text = String(msg?.text ?? "").trim();
const type = String(msg?.type || "text");
const text = type === "text" ? String(msg?.text ?? "").trim() : "";
const userId = String(msg?.userId ?? "");
if (!text) {
const isMedia = MEDIA_KINDS.has(type);
if (!text && !isMedia) {
try { await inst.bot.reply(msg, CONFIG.bot.empty_hint); } catch { /* 尽力而为 */ }
return;
}
inst.bot.sendTyping(userId).catch(() => {});
let media = null;
if (isMedia) {
try {
const dl = await inst.bot.download(msg);
const buf = dl && dl.data ? (Buffer.isBuffer(dl.data) ? dl.data : Buffer.from(dl.data)) : null;
if (!buf || !buf.length) {
console.warn(`[wxbot:${inst.id}] ${type} 无可下载媒体`);
try { await inst.bot.reply(msg, CONFIG.bot.empty_hint); } catch { /* 忽略 */ }
return;
}
if (buf.length > 20 * 1024 * 1024) {
try { await inst.bot.send(userId, "⚠️ 附件过大(限 20MB),未转发"); } catch { /* 忽略 */ }
return;
}
media = { kind: type, b64: buf.toString("base64"), filename: dl.fileName || undefined };
} catch (e) {
console.error(`[wxbot:${inst.id}] 媒体下载失败(${type}):`, e?.message || e);
try { await inst.bot.send(userId, "⚠️ 媒体下载失败:" + String(e?.message || e).slice(0, 120)); } catch { /* 忽略 */ }
return; // 媒体即消息主体,下载失败不降级成空文本
}
}
try {
const r = await corePost("/wxhook/inbox", { id: inst.id, from: userId, text });
const r = await corePost("/wxhook/inbox", { id: inst.id, from: userId, text: text || undefined, media: media || undefined }, 30000);
if (r && r.kind === "command" && r.reply) await inst.bot.send(userId, r.reply);
} catch (e) {
if (e.status === 404) {