| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- /**
- * 主容器通信通道(2026-11-26)
- *
- * ## 为什么是这个方案(用户裁决)
- *
- * R730 的 SSH 通道(server.fmode.cn:18001)被服务器侧拒绝
- * (banner 直接返回 `Not allowed at this time`),不能作为执行手段。
- *
- * 改用**纯 Matrix 通道**:
- * 测试用户 → 建房间 → 邀请主容器 → 主容器自己执行命令
- *
- * 🔴 **不能直接以主容器身份建房间**:
- * 主容器是 Hermes bot,它只响应「别人发给它的消息」,不响应自己发的。
- * 自建房间里它是 creator 但 Hermes 不触发;而且 creator 改 power_levels
- * 会返回 `Event is not authorized`(该 homeserver 的坑)。
- * 因此必须**用真实用户身份建房间并邀请它**——它 join 后才会响应。
- *
- * ## 用法
- *
- * ```js
- * const master = require('./scripts/master-channel.cjs');
- * await master.ask('执行 uname -n,只回结果');
- * ```
- *
- * 返回主容器的所有回复文本(已按时间正序)。
- */
- const fs = require('fs');
- const path = require('path');
- const MX = 'https://matrix.fmode.cn';
- const MASTER_MXID = '@bnqaoxqhe8:fmode.cn';
- const USER_MXID = '@cq0ih6limu:fmode.cn';
- /** 测试用户的 Parse sessionToken(.claude/dev-login.json 的 testAccount) */
- const SESSION_TOKEN = 'r:e1f8f9224c520a2841fd656fd9909cf7';
- /** 测试用户的 Matrix accessToken(由 RP5Ht55NeX 签发,长期有效) */
- const USER_ACCESS_TOKEN = 'pxdhbhg80TNAk8EkfnDZyx3k';
- /** 创建容器开通用(对应 FmodeAgent agent-node-app-test-1125) */
- const USER_AGENT_ID = 'agent-node-app-test-1125';
- const H = () => ({ Authorization: 'Bearer ' + USER_ACCESS_TOKEN, 'Content-Type': 'application/json' });
- async function mx(pathname, init) {
- const res = await fetch(MX + pathname, { ...init, headers: { ...H(), ...(init && init.headers) } });
- const text = await res.text();
- let data = null;
- try {
- data = JSON.parse(text);
- } catch {
- data = { raw: text };
- }
- return { ok: res.ok, status: res.status, data };
- }
- /** 建一个干净房间,邀请主容器,等它进房。新房间 = 新 Hermes session */
- async function openRoom(name) {
- const cr = await mx('/_matrix/client/v3/createRoom', {
- method: 'POST',
- body: JSON.stringify({
- name: name || 'fmode-' + Date.now(),
- preset: 'private_chat',
- invite: [MASTER_MXID],
- is_direct: true,
- }),
- });
- if (!cr.data.room_id) throw new Error('建房失败:' + JSON.stringify(cr.data).slice(0, 200));
- const roomId = cr.data.room_id;
- for (let i = 0; i < 12; i++) {
- await new Promise((r) => setTimeout(r, 2500));
- const mem = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/joined_members');
- if (mem.ok && mem.data.joined && mem.data.joined[MASTER_MXID]) return roomId;
- }
- throw new Error('主容器未进房(邀请后 30 秒内未 join)');
- }
- async function send(roomId, body) {
- const r = await mx(
- '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/t' + Date.now() + Math.floor(Math.random() * 999),
- {
- method: 'PUT',
- body: JSON.stringify({ msgtype: 'm.text', body, 'm.mentions': { user_ids: [MASTER_MXID] } }),
- },
- );
- if (!r.ok) throw new Error('发送失败 HTTP ' + r.status);
- }
- /** 等主容器的回复(只取发送时间晚于 since 的消息) */
- async function waitReply(roomId, sinceIso, { maxSec = 240, idleSec = 45 } = {}) {
- const started = Date.now();
- let lastCount = 0;
- let lastChange = Date.now();
- let collected = [];
- while ((Date.now() - started) / 1000 < maxSec) {
- await new Promise((r) => setTimeout(r, 5000));
- const m = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=20');
- const got = ((m.data && m.data.chunk) || [])
- .filter((e) => e.sender === MASTER_MXID && e.type === 'm.room.message')
- .filter((e) => new Date(e.origin_server_ts).toISOString() > sinceIso)
- .reverse()
- .map((e) => e.content.body || '');
- if (got.length !== lastCount) {
- lastCount = got.length;
- lastChange = Date.now();
- collected = got;
- } else if (collected.length && (Date.now() - lastChange) / 1000 > idleSec) {
- return collected;
- }
- }
- return collected;
- }
- /** 一问一答:新房间 → 发指令 → 收集回复 */
- async function ask(prompt, opts) {
- const roomId = await openRoom((opts && opts.name) || 'fmode-task');
- const since = new Date().toISOString();
- await send(roomId, prompt);
- const replies = await waitReply(roomId, since, opts);
- return { roomId, replies };
- }
- module.exports = {
- MX,
- MASTER_MXID,
- USER_MXID,
- SESSION_TOKEN,
- USER_ACCESS_TOKEN,
- USER_AGENT_ID,
- mx,
- openRoom,
- send,
- waitReply,
- ask,
- };
|