master-channel.cjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /**
  2. * 主容器通信通道(2026-11-26)
  3. *
  4. * ## 为什么是这个方案(用户裁决)
  5. *
  6. * R730 的 SSH 通道(server.fmode.cn:18001)被服务器侧拒绝
  7. * (banner 直接返回 `Not allowed at this time`),不能作为执行手段。
  8. *
  9. * 改用**纯 Matrix 通道**:
  10. * 测试用户 → 建房间 → 邀请主容器 → 主容器自己执行命令
  11. *
  12. * 🔴 **不能直接以主容器身份建房间**:
  13. * 主容器是 Hermes bot,它只响应「别人发给它的消息」,不响应自己发的。
  14. * 自建房间里它是 creator 但 Hermes 不触发;而且 creator 改 power_levels
  15. * 会返回 `Event is not authorized`(该 homeserver 的坑)。
  16. * 因此必须**用真实用户身份建房间并邀请它**——它 join 后才会响应。
  17. *
  18. * ## 用法
  19. *
  20. * ```js
  21. * const master = require('./scripts/master-channel.cjs');
  22. * await master.ask('执行 uname -n,只回结果');
  23. * ```
  24. *
  25. * 返回主容器的所有回复文本(已按时间正序)。
  26. */
  27. const fs = require('fs');
  28. const path = require('path');
  29. const MX = 'https://matrix.fmode.cn';
  30. const MASTER_MXID = '@bnqaoxqhe8:fmode.cn';
  31. const USER_MXID = '@cq0ih6limu:fmode.cn';
  32. /** 测试用户的 Parse sessionToken(.claude/dev-login.json 的 testAccount) */
  33. const SESSION_TOKEN = 'r:e1f8f9224c520a2841fd656fd9909cf7';
  34. /** 测试用户的 Matrix accessToken(由 RP5Ht55NeX 签发,长期有效) */
  35. const USER_ACCESS_TOKEN = 'pxdhbhg80TNAk8EkfnDZyx3k';
  36. /** 创建容器开通用(对应 FmodeAgent agent-node-app-test-1125) */
  37. const USER_AGENT_ID = 'agent-node-app-test-1125';
  38. const H = () => ({ Authorization: 'Bearer ' + USER_ACCESS_TOKEN, 'Content-Type': 'application/json' });
  39. async function mx(pathname, init) {
  40. const res = await fetch(MX + pathname, { ...init, headers: { ...H(), ...(init && init.headers) } });
  41. const text = await res.text();
  42. let data = null;
  43. try {
  44. data = JSON.parse(text);
  45. } catch {
  46. data = { raw: text };
  47. }
  48. return { ok: res.ok, status: res.status, data };
  49. }
  50. /** 建一个干净房间,邀请主容器,等它进房。新房间 = 新 Hermes session */
  51. async function openRoom(name) {
  52. const cr = await mx('/_matrix/client/v3/createRoom', {
  53. method: 'POST',
  54. body: JSON.stringify({
  55. name: name || 'fmode-' + Date.now(),
  56. preset: 'private_chat',
  57. invite: [MASTER_MXID],
  58. is_direct: true,
  59. }),
  60. });
  61. if (!cr.data.room_id) throw new Error('建房失败:' + JSON.stringify(cr.data).slice(0, 200));
  62. const roomId = cr.data.room_id;
  63. for (let i = 0; i < 12; i++) {
  64. await new Promise((r) => setTimeout(r, 2500));
  65. const mem = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/joined_members');
  66. if (mem.ok && mem.data.joined && mem.data.joined[MASTER_MXID]) return roomId;
  67. }
  68. throw new Error('主容器未进房(邀请后 30 秒内未 join)');
  69. }
  70. async function send(roomId, body) {
  71. const r = await mx(
  72. '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/t' + Date.now() + Math.floor(Math.random() * 999),
  73. {
  74. method: 'PUT',
  75. body: JSON.stringify({ msgtype: 'm.text', body, 'm.mentions': { user_ids: [MASTER_MXID] } }),
  76. },
  77. );
  78. if (!r.ok) throw new Error('发送失败 HTTP ' + r.status);
  79. }
  80. /** 等主容器的回复(只取发送时间晚于 since 的消息) */
  81. async function waitReply(roomId, sinceIso, { maxSec = 240, idleSec = 45 } = {}) {
  82. const started = Date.now();
  83. let lastCount = 0;
  84. let lastChange = Date.now();
  85. let collected = [];
  86. while ((Date.now() - started) / 1000 < maxSec) {
  87. await new Promise((r) => setTimeout(r, 5000));
  88. const m = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=20');
  89. const got = ((m.data && m.data.chunk) || [])
  90. .filter((e) => e.sender === MASTER_MXID && e.type === 'm.room.message')
  91. .filter((e) => new Date(e.origin_server_ts).toISOString() > sinceIso)
  92. .reverse()
  93. .map((e) => e.content.body || '');
  94. if (got.length !== lastCount) {
  95. lastCount = got.length;
  96. lastChange = Date.now();
  97. collected = got;
  98. } else if (collected.length && (Date.now() - lastChange) / 1000 > idleSec) {
  99. return collected;
  100. }
  101. }
  102. return collected;
  103. }
  104. /** 一问一答:新房间 → 发指令 → 收集回复 */
  105. async function ask(prompt, opts) {
  106. const roomId = await openRoom((opts && opts.name) || 'fmode-task');
  107. const since = new Date().toISOString();
  108. await send(roomId, prompt);
  109. const replies = await waitReply(roomId, since, opts);
  110. return { roomId, replies };
  111. }
  112. module.exports = {
  113. MX,
  114. MASTER_MXID,
  115. USER_MXID,
  116. SESSION_TOKEN,
  117. USER_ACCESS_TOKEN,
  118. USER_AGENT_ID,
  119. mx,
  120. openRoom,
  121. send,
  122. waitReply,
  123. ask,
  124. };