@rezti/dsh-rez-wechat 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @rezti/dsh-rez-wechat
2
2
 
3
- 企业微信走现成 `wecom-mcp`;个人微信走 QClaw 同款 `dsh-wechat-bridge`(腾讯 iLink)。都不自写长连接。
3
+ 企业微信走官方 `@wecom/aibot-node-sdk`(智能机器人 BotID + Secret 长连接);个人微信走 QClaw 同款 `dsh-wechat-bridge`(腾讯 iLink)。都不自写长连接。
4
4
 
5
5
  ```bash
6
6
  dsh plugin --profile web add @rezti/dsh-rez-suite
@@ -10,7 +10,9 @@ dsh plugin --profile web add @rezti/dsh-rez-suite
10
10
 
11
11
  | 能力 | 做法 |
12
12
  |---|---|
13
- | 企业微信发到群 | `wecom-mcp`(`mcp__wechat__*`)+ `REZ_WECHAT_WEBHOOK` |
13
+ | 企业微信智能机器人 | 官方 `@wecom/aibot-node-sdk`。设置页给每个 Harness 房间绑一个 BotID + Secret。同事在企微跟哪个 bot 说话,消息进网页左侧那个房间的**同一条会话**。密钥 `~/.dsh/wecom-channels.json`(mode 600),不进 compose。 |
14
+ | 企业微信办公能力 | 官方 [`wecom-cli`](https://github.com/WecomTeam/wecom-cli) >=1.1(通讯录/在线文档/表格/待办/日程/会议/邮件/微盘等)。**不是** MCP。`rez_status.wecomCli.modules` 是品类目录。房间里种了官方 `wecomcli-*` 技能。CLI 报未授权才说该模块未开通。不要用旧的「超过 10 人只能用文档」说法。 |
15
+ | 旧群机器人 Webhook(兼容) | 一个 bot 都没绑、且仍配置了 `REZ_WECHAT_WEBHOOK` 时,才拉起 `wecom-mcp` |
14
16
  | 个人微信(QClaw / ClawBot) | dsh Web 设置面板扫码,之后直接在微信里说话。消息进左侧 **微信** 文件夹的同一会话,模型跟网页默认。 |
15
17
 
16
18
  个人微信桥接到正在跑的 `dsh web`(不是 `dsh --profile headless`):
@@ -23,6 +25,14 @@ dsh plugin --profile web add @rezti/dsh-rez-suite
23
25
  - 思考过程不会发到微信;多段正文会保留换行
24
26
  - 通道断了点「重新连接」,已登录不必再扫码
25
27
 
28
+ 企微智能机器人(Accio 同款按房间绑定):
29
+
30
+ - 可绑房间:搞钱、产品、运营、人事助理、财务助理、法务助理、设计、发布、电商、实验室(不要绑「微信」个人通道)
31
+ - 同一房间固定一条网页会话;只有「重启对话」才新开并把旧的归档
32
+ - 会话标题是房间名;网页必须开着
33
+ - 收文本 / 混排文字、流式回复、进入会话欢迎语;图片/文件/语音请走网页端或 Nextcloud
34
+ - BotID / Secret 在企业微信管理后台 → 智能机器人([开发前必读](https://developer.work.weixin.qq.com/document/path/101805) / [长连接](https://developer.work.weixin.qq.com/document/path/101463))
35
+
26
36
  扫码 UI 在 suite 面板;通道本身在本包。不要对同一 profile 既 add suite 又 add wechat,会重复注册。
27
37
 
28
38
  这是 ClawBot 客服会话,不是用个人微信号管好友/群,也不是客户层 WhatsApp/邮件通道。
package/lib/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { startMcpWhenSecret } from '@rezti/dsh-rez-sso';
2
2
  import { WeixinChannel } from './channel.js';
3
+ import { WecomChannel, shouldStartWecomWebhook } from './wecom-channel.js';
3
4
  import { revealSessionInRegistry } from './unarchive.js';
5
+ import { WECOM_BINDABLE_ROOMS } from './wecom-store.js';
4
6
  export const name = 'rez-wechat';
5
7
  export const inject = ['systemPrompt', 'webServer', 'rezSso'];
6
8
  const GUIDANCE = [
7
- '企业微信群发送走官方 dsh-mcp-client + wecom-mcp(mcp__wechat__*),密钥 REZ_WECHAT_WEBHOOK。未配置时不拉起 wecom-mcp。Webhook 设置 插件 ReZ-TI 里填。',
8
- '个人微信是 QClaw 同款 ClawBot 通道:在 Rez 面板「微信」页扫码一次,然后直接在微信里说话。消息进入网页左侧「微信」文件夹并延续同一会话,模型跟网页默认(在网页里选了 Kimi 就会走 Kimi)。网页端归档了也能从微信自动恢复到侧栏(空白会话网页会藏起来,所以新开的会话会先打一句招呼再出现)。网页端出现选择题时会编成纯文本发到微信,回复数字或选项原文即可;思考过程不会转发。发「重启对话」会新开一条可见的网页会话并把旧的归档。通道断了点「重新连接」(已登录不必再扫码)。不要再跑 npx weixin-mcp login,也不要调用 mcp__weixin__*。网页端必须开着。',
9
+ '企业微信有两层,不要混:① 房间消息通道 = 官方 @wecom/aibot-node-sdk(设置页 BotID + Secret 长连接),同事在企微跟哪个 bot 说话就进哪个 Harness 房间(人事/财务/法务/设计/发布/电商/实验室/老板三室),并固定同一条网页会话;只有同事说「重启对话」才新开并把旧的归档。② 办公能力 = 官方 wecom-cli >=1.1(通讯录/在线文档/在线表格/智能表格/智能文档/待办/日程/会议/邮件/微盘/消息),本企业已开通,看 rez_status.wecomCli.modules,按房间 wecomcli-* 技能执行。不要因为状态页没有企微 MCP 就说没有企微能力,也不要说「超过 10 人只能用文档」。CLI 报未授权才说该模块未开通。密钥写在 ~/.dsh/wecom-channels.json,不要写进 compose。没有绑定任何 bot 且仍配置了 REZ_WECHAT_WEBHOOK 时,才兼容旧的 wecom-mcp 群发,不要引导去填群 Webhook。不要自写 WebSocket/HTTP 客户端。',
10
+ '个人微信是 QClaw 同款 ClawBot 通道:在 Rez 面板「微信」页扫码一次,然后直接在微信里说话。消息进入网页左侧「微信」文件夹并延续同一会话,模型跟网页默认(在网页里选了 Kimi 就会走 Kimi)。网页端归档了也能从微信自动恢复到侧栏(空白会话网页会藏起来,所以新开的会话会先打一句招呼再出现)。网页端出现选择题时会编成纯文本发到微信,回复数字或选项原文即可;思考过程不会转发。发「重启对话」会新开一条可见的网页会话并把旧的归档。通道断了点「重新连接」(已登录不必再扫码)。不要再跑 npx weixin-mcp login,也不要调用 mcp__weixin__*。网页端必须开着。工商查询请切到法务助理,避免串房间。',
9
11
  '这是 ClawBot 客服会话,不是用个人微信号管好友/群。对外发消息必须先征得用户批准。',
10
12
  ].join('');
11
13
  function isLoopbackRequest(request) {
@@ -118,6 +120,43 @@ function weixinRoutes(channel, ctx) {
118
120
  },
119
121
  ];
120
122
  }
123
+ function wecomRoutes(channel) {
124
+ const path = '/api/dsh-rez-suite/wecom/channels';
125
+ const guard = (req, res, method) => {
126
+ if (!isLoopbackRequest(req)) {
127
+ writeJson(res, 403, { error: 'forbidden: loopback-only' });
128
+ return false;
129
+ }
130
+ if (req.method !== method) {
131
+ writeJson(res, 405, { error: 'method not allowed' });
132
+ return false;
133
+ }
134
+ return true;
135
+ };
136
+ return [
137
+ {
138
+ kind: 'exact',
139
+ path,
140
+ handler: async (req, res) => {
141
+ if (req.method === 'GET') {
142
+ if (!guard(req, res, 'GET'))
143
+ return;
144
+ writeJson(res, 200, { ...channel.publicState(), rooms: [...WECOM_BINDABLE_ROOMS] });
145
+ return;
146
+ }
147
+ if (req.method === 'PUT') {
148
+ if (!guard(req, res, 'PUT'))
149
+ return;
150
+ const body = await readJsonBody(req);
151
+ const incoming = body?.bots ?? body;
152
+ writeJson(res, 200, await channel.applyBots(incoming));
153
+ return;
154
+ }
155
+ writeJson(res, 405, { error: 'method not allowed' });
156
+ },
157
+ },
158
+ ];
159
+ }
121
160
  function getWorkspaceRegistry(ctx) {
122
161
  try {
123
162
  return ctx.get('workspaceRegistry');
@@ -129,28 +168,35 @@ function getWorkspaceRegistry(ctx) {
129
168
  export async function apply(ctx) {
130
169
  const channel = new WeixinChannel();
131
170
  channel.startIfLoggedIn();
171
+ const wecom = new WecomChannel();
172
+ wecom.start();
132
173
  ctx.effect(() => ctx.systemPrompt.section({
133
174
  name: 'plugin:dsh-rez-wechat',
134
175
  order: 162,
135
176
  text: GUIDANCE,
136
177
  }), 'dsh-rez-wechat: prompt');
137
- const routes = weixinRoutes(channel, ctx);
178
+ const routes = [...weixinRoutes(channel, ctx), ...wecomRoutes(wecom)];
138
179
  ctx.effect(() => {
139
180
  const disposers = routes.map(route => ctx.webServer.register(route));
140
181
  return () => { for (const dispose of disposers)
141
182
  dispose(); };
142
183
  }, 'dsh-rez-wechat: weixin routes');
143
- ctx.effect(() => () => { channel.dispose(); }, 'dsh-rez-wechat: weixin channel');
144
- await startMcpWhenSecret(ctx, {
145
- system: 'wechat',
146
- label: '企业微信',
147
- config: (secret) => ({
148
- serverName: 'wechat',
149
- transport: 'stdio',
150
- command: 'npx',
151
- args: ['-y', 'wecom-mcp'],
152
- env: { WECOM_WEBHOOK_URL: secret },
153
- failOnStartupError: false,
154
- }),
155
- });
184
+ ctx.effect(() => () => {
185
+ channel.dispose();
186
+ wecom.dispose();
187
+ }, 'dsh-rez-wechat: channels');
188
+ if (shouldStartWecomWebhook()) {
189
+ await startMcpWhenSecret(ctx, {
190
+ system: 'wechat',
191
+ label: '企业微信',
192
+ config: (secret) => ({
193
+ serverName: 'wechat',
194
+ transport: 'stdio',
195
+ command: 'npx',
196
+ args: ['-y', 'wecom-mcp'],
197
+ env: { WECOM_WEBHOOK_URL: secret },
198
+ failOnStartupError: false,
199
+ }),
200
+ });
201
+ }
156
202
  }
package/lib/web-shim.d.ts CHANGED
@@ -9,6 +9,8 @@
9
9
  */
10
10
  export declare const WECHAT_WORKSPACE_NAME = "\u5FAE\u4FE1";
11
11
  export declare const DEFAULT_WEB_URL = "http://127.0.0.1:3080";
12
+ /** Seeded only when the inbox folder has no AGENTS.md yet. */
13
+ export declare const WECHAT_INBOX_AGENTS: string;
12
14
  export interface ModelRef {
13
15
  provider?: string;
14
16
  model: string;
@@ -36,12 +38,19 @@ export declare function parseHeadlessArgv(argv: string[]): {
36
38
  } | {
37
39
  error: string;
38
40
  };
41
+ /**
42
+ * Personal WeChat follow-ups wrap history in 桥接上下文. Use this only to
43
+ * slice the latest user line. Do not mint a new web session from it — WeCom
44
+ * turns are always plain text and must reuse the room's stored session.
45
+ */
39
46
  export declare function isFreshBridgeTurn(task: string): boolean;
40
47
  /** WeChat /new is handled by dsh-wechat-bridge. Chinese "重启对话" is a normal message and must be detected here. */
41
48
  export declare function isRestartCommand(text: string): boolean;
42
- export declare const RESTART_ACK = "\u5DF2\u65B0\u5F00\u7F51\u9875\u4F1A\u8BDD\uFF08\u5DE6\u4FA7\u300C\u5FAE\u4FE1\u300D\u6587\u4EF6\u5939\uFF09\u3002\u4E4B\u540E\u76F4\u63A5\u8BF4\u8BDD\u5373\u53EF\u3002\u518D\u53D1\u300C\u91CD\u542F\u5BF9\u8BDD\u300D\u4F1A\u518D\u5F00\u4E00\u6761\uFF1B\u65E7\u4F1A\u8BDD\u4F1A\u5F52\u6863\uFF0C\u7F51\u9875\u4FA7\u680F\u66F4\u5E72\u51C0\u3002";
49
+ export declare function restartAck(folder?: string): string;
50
+ export declare function stuckAck(folder?: string): string;
51
+ export declare const RESTART_ACK: string;
43
52
  export declare const RESTART_SEED = "\u65B0\u4F1A\u8BDD\u5DF2\u5F00\u59CB\u3002\u8BF7\u7528\u4E00\u53E5\u4E2D\u6587\u6253\u62DB\u547C\uFF0C\u4E0D\u8981\u89E3\u91CA\u5185\u90E8\u6B65\u9AA4\u3002";
44
- export declare const STUCK_ACK = "\u7F51\u9875\u7AEF\u8FD9\u6761\u4F1A\u8BDD\u5361\u4F4F\u4E86\uFF08\u5728\u7B49\u6279\u51C6\uFF0C\u6216\u6A21\u578B\u628A\u5185\u90E8\u63A8\u7406\u53D1\u51FA\u6765\u4E86\uFF09\u3002\u8BF7\u770B\u7F51\u9875\u5DE6\u4FA7\u300C\u5FAE\u4FE1\u300D\u6587\u4EF6\u5939\uFF0C\u6216\u53D1\u300C\u91CD\u542F\u5BF9\u8BDD\u300D\u3002";
53
+ export declare const STUCK_ACK: string;
45
54
  export declare const RPC_TIMEOUT_MS = 15000;
46
55
  export declare const QUESTION_HINT = "\u56DE\u590D\u6570\u5B57\u6216\u9009\u9879\u539F\u6587\u5373\u53EF\u3002";
47
56
  export declare function stripThinkTags(text: string): string;
@@ -53,6 +62,8 @@ export declare function turnIsBlocked(events: unknown[]): boolean;
53
62
  export declare function extractLatestUserText(task: string): string;
54
63
  export declare function dshHomeDir(env?: NodeJS.ProcessEnv, home?: string): string;
55
64
  export declare function wechatWorkspaceDir(env?: NodeJS.ProcessEnv, home?: string): string;
65
+ /** Write a short inbox AGENTS.md once; never overwrite a living file. Skip non-微信 rooms (企微按房间绑定). */
66
+ export declare function ensureWechatInboxAgents(cwd: string): void;
56
67
  export declare function sessionStorePath(env?: NodeJS.ProcessEnv, home?: string): string;
57
68
  export declare function webBaseUrl(env?: NodeJS.ProcessEnv): string;
58
69
  export declare function loadSessionStore(path: string): SessionStore;
package/lib/web-shim.js CHANGED
@@ -8,11 +8,18 @@
8
8
  * (Kimi if that is what the user selected).
9
9
  */
10
10
  import { randomUUID } from 'node:crypto';
11
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
12
12
  import { homedir } from 'node:os';
13
13
  import { basename, dirname, join } from 'node:path';
14
14
  export const WECHAT_WORKSPACE_NAME = '微信';
15
15
  export const DEFAULT_WEB_URL = 'http://127.0.0.1:3080';
16
+ /** Seeded only when the inbox folder has no AGENTS.md yet. */
17
+ export const WECHAT_INBOX_AGENTS = [
18
+ '# 微信',
19
+ '',
20
+ '收件箱。工商查询请切到法务助理,避免串房间。',
21
+ '',
22
+ ].join('\n');
16
23
  export const ASK_USER_QUESTION_TOOL = 'ask_user_question';
17
24
  export function parseHeadlessArgv(argv) {
18
25
  const args = argv[0]?.endsWith('node') || argv[0]?.includes('node.exe') ? argv.slice(1) : argv;
@@ -25,6 +32,11 @@ export function parseHeadlessArgv(argv) {
25
32
  return { error: 'missing headless task' };
26
33
  return { task };
27
34
  }
35
+ /**
36
+ * Personal WeChat follow-ups wrap history in 桥接上下文. Use this only to
37
+ * slice the latest user line. Do not mint a new web session from it — WeCom
38
+ * turns are always plain text and must reuse the room's stored session.
39
+ */
28
40
  export function isFreshBridgeTurn(task) {
29
41
  return !task.includes('【桥接上下文】');
30
42
  }
@@ -37,9 +49,15 @@ export function isRestartCommand(text) {
37
49
  return true;
38
50
  return /^(重启对话|重新开始|新对话|开启新对话|重置对话)[。.!!]?$/.test(t);
39
51
  }
40
- export const RESTART_ACK = '已新开网页会话(左侧「微信」文件夹)。之后直接说话即可。再发「重启对话」会再开一条;旧会话会归档,网页侧栏更干净。';
52
+ export function restartAck(folder = WECHAT_WORKSPACE_NAME) {
53
+ return `已新开网页会话(左侧「${folder}」文件夹)。之后直接说话即可。再发「重启对话」会再开一条;旧会话会归档,网页侧栏更干净。`;
54
+ }
55
+ export function stuckAck(folder = WECHAT_WORKSPACE_NAME) {
56
+ return `网页端这条会话卡住了(在等批准,或模型把内部推理发出来了)。请看网页左侧「${folder}」文件夹,或发「重启对话」。`;
57
+ }
58
+ export const RESTART_ACK = restartAck();
41
59
  export const RESTART_SEED = '新会话已开始。请用一句中文打招呼,不要解释内部步骤。';
42
- export const STUCK_ACK = '网页端这条会话卡住了(在等批准,或模型把内部推理发出来了)。请看网页左侧「微信」文件夹,或发「重启对话」。';
60
+ export const STUCK_ACK = stuckAck();
43
61
  export const RPC_TIMEOUT_MS = 15_000;
44
62
  export const QUESTION_HINT = '回复数字或选项原文即可。';
45
63
  const SKIP_CONTENT_TYPES = new Set(['reasoning', 'thinking', 'tool-call', 'tool-result', 'image']);
@@ -118,6 +136,16 @@ export function wechatWorkspaceDir(env = process.env, home = homedir()) {
118
136
  return env.REZ_WECHAT_WORKSPACE;
119
137
  return join(dshHomeDir(env, home), 'workspaces', WECHAT_WORKSPACE_NAME);
120
138
  }
139
+ /** Write a short inbox AGENTS.md once; never overwrite a living file. Skip non-微信 rooms (企微按房间绑定). */
140
+ export function ensureWechatInboxAgents(cwd) {
141
+ mkdirSync(cwd, { recursive: true });
142
+ if (basename(cwd) !== WECHAT_WORKSPACE_NAME)
143
+ return;
144
+ const file = join(cwd, 'AGENTS.md');
145
+ if (existsSync(file))
146
+ return;
147
+ writeFileSync(file, WECHAT_INBOX_AGENTS);
148
+ }
121
149
  export function sessionStorePath(env = process.env, home = homedir()) {
122
150
  if (env.REZ_WECHAT_SESSION_STORE !== undefined && env.REZ_WECHAT_SESSION_STORE !== '')
123
151
  return env.REZ_WECHAT_SESSION_STORE;
@@ -728,6 +756,7 @@ export async function postRpc(baseUrl, method, params, timeoutMs = RPC_TIMEOUT_M
728
756
  }
729
757
  async function ensureWorkspace(rpc, cwd) {
730
758
  mkdirSync(cwd, { recursive: true });
759
+ ensureWechatInboxAgents(cwd);
731
760
  try {
732
761
  const created = await rpc('workspace.create', { path: cwd });
733
762
  const id = extractWorkspaceId(created) ?? findWorkspaceId(created, cwd);
@@ -832,7 +861,8 @@ export async function ensureSessionVisible(rpc, sessionId, env = process.env, wo
832
861
  await tryRpc(rpc, 'workspace.attachSession', { workspaceId, sessionId });
833
862
  await tryRpc(rpc, 'workspace.insertSessionBefore', { workspaceId, sessionId });
834
863
  }
835
- await tryRpc(rpc, 'session.rename', { sessionId, title: WECHAT_WORKSPACE_NAME });
864
+ const title = basename(wechatWorkspaceDir(env)) || WECHAT_WORKSPACE_NAME;
865
+ await tryRpc(rpc, 'session.rename', { sessionId, title });
836
866
  }
837
867
  async function archiveSession(rpc, sessionId) {
838
868
  await tryRpc(rpc, 'workspace.archiveSession', { sessionId });
@@ -886,7 +916,7 @@ function composeWechatReply(events, ignorePending) {
886
916
  }
887
917
  return { text: visible, pendingQuestions };
888
918
  }
889
- async function waitForAssistant(rpc, sessionId, beforeText, timeoutMs, ignorePending) {
919
+ async function waitForAssistant(rpc, sessionId, beforeText, timeoutMs, ignorePending, stuckText = STUCK_ACK) {
890
920
  const deadline = Date.now() + timeoutMs;
891
921
  let last = { text: '', pendingQuestions: [] };
892
922
  let idleOnce = false;
@@ -904,7 +934,7 @@ async function waitForAssistant(rpc, sessionId, beforeText, timeoutMs, ignorePen
904
934
  return composed;
905
935
  }
906
936
  if (turnIsBlocked(events))
907
- return { text: STUCK_ACK, pendingQuestions: [] };
937
+ return { text: stuckText, pendingQuestions: [] };
908
938
  if (composed.text !== '')
909
939
  last = composed;
910
940
  const idle = turnIsIdle(events);
@@ -918,7 +948,7 @@ async function waitForAssistant(rpc, sessionId, beforeText, timeoutMs, ignorePen
918
948
  }
919
949
  if (last.text !== '' && last.text !== beforeText)
920
950
  return last;
921
- return { text: STUCK_ACK, pendingQuestions: [] };
951
+ return { text: stuckText, pendingQuestions: [] };
922
952
  }
923
953
  export async function runHeadlessViaWeb(opts) {
924
954
  const env = opts.env ?? process.env;
@@ -932,20 +962,22 @@ export async function runHeadlessViaWeb(opts) {
932
962
  const rpc = opts.rpc ?? ((method, params) => postRpc(webBaseUrl(env), method, params));
933
963
  const timeoutMs = opts.timeoutMs ?? Number(env.DSH_BRIDGE_TIMEOUT_MS ?? 10 * 60 * 1000);
934
964
  const workspaceId = await ensureWorkspace(rpc, workspace);
965
+ const folder = basename(workspace) || WECHAT_WORKSPACE_NAME;
935
966
  const restart = isRestartCommand(text);
936
- const fresh = isFreshBridgeTurn(opts.task) || restart;
937
967
  const store = loadSessionStore(storeFile);
938
968
  const storedPending = restart ? undefined : store.sessions[key]?.pendingQuestions;
939
969
  let sessionId = store.sessions[key]?.sessionId;
940
970
  const previousId = sessionId;
941
- if (sessionId !== undefined && !fresh) {
971
+ // WeCom sends plain text (no 桥接上下文). Reuse the stored session unless
972
+ // the user asked to restart or the old session is already gone.
973
+ if (restart) {
974
+ sessionId = undefined;
975
+ }
976
+ else if (sessionId !== undefined) {
942
977
  const alive = await sessionAlive(rpc, sessionId);
943
978
  if (!alive)
944
979
  sessionId = undefined;
945
980
  }
946
- else {
947
- sessionId = undefined;
948
- }
949
981
  if (sessionId === undefined) {
950
982
  sessionId = await createSession(rpc, workspace, workspaceId);
951
983
  await maybeSelectModel(rpc, sessionId, env);
@@ -1000,14 +1032,14 @@ export async function runHeadlessViaWeb(opts) {
1000
1032
  content: [{ type: 'text', text: promptText }],
1001
1033
  });
1002
1034
  }
1003
- const reply = await waitForAssistant(rpc, sessionId, before, timeoutMs, questions);
1035
+ const reply = await waitForAssistant(rpc, sessionId, before, timeoutMs, questions, stuckAck(folder));
1004
1036
  store.sessions[key] = {
1005
1037
  sessionId,
1006
1038
  updatedAt: Date.now(),
1007
1039
  ...(reply.pendingQuestions.length > 0 ? { pendingQuestions: reply.pendingQuestions } : {}),
1008
1040
  };
1009
1041
  saveSessionStore(storeFile, store);
1010
- if (restart && (reply.text === STUCK_ACK || reply.text === ''))
1011
- return RESTART_ACK;
1042
+ if (restart && (reply.text === stuckAck(folder) || reply.text === ''))
1043
+ return restartAck(folder);
1012
1044
  return reply.text;
1013
1045
  }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Accio-style WeCom AI bots: one official WSClient per Harness room.
3
+ * Uses @wecom/aibot-node-sdk (botId + secret). Do not hand-roll the WS.
4
+ */
5
+ import { type WecomBotPublic, type WecomBotRecord } from './wecom-store.js';
6
+ export declare const WECOM_NON_TEXT_HINT = "\u8BF7\u53D1\u6587\u5B57\u3002\u56FE\u7247\u3001\u6587\u4EF6\u548C\u8BED\u97F3\u8BF7\u8D70\u7F51\u9875\u7AEF\u6216 Nextcloud\u3002";
7
+ export type WecomBindingPhase = 'idle' | 'connecting' | 'authenticated' | 'error';
8
+ export interface WecomBindingStatus {
9
+ room: string;
10
+ botId: string;
11
+ phase: WecomBindingPhase;
12
+ hint: string;
13
+ }
14
+ export interface WecomChannelsPublic {
15
+ rooms: readonly string[];
16
+ bots: WecomBotPublic[];
17
+ status: WecomBindingStatus[];
18
+ }
19
+ export interface WecomWsClient {
20
+ connect: () => unknown;
21
+ disconnect: () => void;
22
+ on: (event: string, handler: (...args: unknown[]) => void) => unknown;
23
+ replyStream: (frame: unknown, streamId: string, content: string, finish?: boolean) => Promise<unknown>;
24
+ replyWelcome: (frame: unknown, body: {
25
+ msgtype: string;
26
+ text: {
27
+ content: string;
28
+ };
29
+ }) => Promise<unknown>;
30
+ }
31
+ export type WecomClientFactory = (opts: {
32
+ botId: string;
33
+ secret: string;
34
+ }) => WecomWsClient | Promise<WecomWsClient>;
35
+ export type WecomRunTurn = (room: string, text: string) => Promise<string>;
36
+ export declare function extractWecomText(frame: unknown): string;
37
+ export declare function wecomMsgid(frame: unknown): string;
38
+ export declare function createOfficialWecomClient(opts: {
39
+ botId: string;
40
+ secret: string;
41
+ }): Promise<WecomWsClient>;
42
+ export declare function shouldStartWecomWebhook(bots?: WecomBotRecord[]): boolean;
43
+ export declare class WecomChannel {
44
+ private readonly home;
45
+ private readonly factory;
46
+ private readonly runTurn;
47
+ private readonly bindings;
48
+ private generation;
49
+ constructor(opts?: {
50
+ home?: string;
51
+ factory?: WecomClientFactory;
52
+ runTurn?: WecomRunTurn;
53
+ });
54
+ start(): void;
55
+ status(): WecomBindingStatus[];
56
+ publicState(): WecomChannelsPublic;
57
+ applyBots(incoming: unknown): Promise<WecomChannelsPublic>;
58
+ dispose(): void;
59
+ /** Test seam: wait until inbound handlers finish. */
60
+ flush(): Promise<void>;
61
+ reconnect(): Promise<void>;
62
+ private dropBindings;
63
+ private bind;
64
+ private enqueue;
65
+ private rememberMsgid;
66
+ private handleText;
67
+ private handleNonText;
68
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Accio-style WeCom AI bots: one official WSClient per Harness room.
3
+ * Uses @wecom/aibot-node-sdk (botId + secret). Do not hand-roll the WS.
4
+ */
5
+ import { join } from 'node:path';
6
+ import { dshHome } from '@rezti/dsh-rez-sso';
7
+ import { runHeadlessViaWeb } from './web-shim.js';
8
+ import { loadWecomChannels, publicWecomBots, saveWecomChannels, applyWecomBotPatch, WECOM_BINDABLE_ROOMS, } from './wecom-store.js';
9
+ export const WECOM_NON_TEXT_HINT = '请发文字。图片、文件和语音请走网页端或 Nextcloud。';
10
+ const MAX_SEEN_MSGIDS = 200;
11
+ export function extractWecomText(frame) {
12
+ if (typeof frame !== 'object' || frame === null)
13
+ return '';
14
+ const body = frame.body;
15
+ if (typeof body !== 'object' || body === null)
16
+ return '';
17
+ const rec = body;
18
+ const fromText = textContent(rec.text);
19
+ if (fromText.length > 0)
20
+ return fromText;
21
+ if (typeof rec.content === 'string' && rec.content.trim().length > 0)
22
+ return rec.content.trim();
23
+ const mixed = rec.mixed;
24
+ if (typeof mixed === 'object' && mixed !== null) {
25
+ const items = mixed.items;
26
+ if (Array.isArray(items)) {
27
+ const parts = [];
28
+ for (const item of items) {
29
+ if (typeof item !== 'object' || item === null)
30
+ continue;
31
+ const row = item;
32
+ const nested = textContent(row.text) || (typeof row.content === 'string' ? row.content.trim() : '');
33
+ if (nested.length > 0)
34
+ parts.push(nested);
35
+ }
36
+ return parts.join('\n').trim();
37
+ }
38
+ }
39
+ return '';
40
+ }
41
+ export function wecomMsgid(frame) {
42
+ if (typeof frame !== 'object' || frame === null)
43
+ return '';
44
+ const body = frame.body;
45
+ if (typeof body !== 'object' || body === null)
46
+ return '';
47
+ const id = body.msgid;
48
+ return typeof id === 'string' ? id : '';
49
+ }
50
+ function textContent(value) {
51
+ if (typeof value === 'string')
52
+ return value.trim();
53
+ if (typeof value === 'object' && value !== null) {
54
+ const content = value.content;
55
+ if (typeof content === 'string')
56
+ return content.trim();
57
+ }
58
+ return '';
59
+ }
60
+ function newStreamId() {
61
+ return `stream-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
62
+ }
63
+ const quietLogger = {
64
+ debug() { },
65
+ info() { },
66
+ warn(...args) { console.warn('[wecom]', ...args); },
67
+ error(...args) { console.error('[wecom]', ...args); },
68
+ };
69
+ export async function createOfficialWecomClient(opts) {
70
+ const mod = await import('@wecom/aibot-node-sdk');
71
+ const holder = mod.default ?? mod;
72
+ const WSClient = holder.WSClient;
73
+ if (typeof WSClient !== 'function') {
74
+ throw new Error('官方 @wecom/aibot-node-sdk 没有 WSClient');
75
+ }
76
+ return new WSClient({
77
+ botId: opts.botId,
78
+ secret: opts.secret,
79
+ maxReconnectAttempts: -1,
80
+ logger: quietLogger,
81
+ });
82
+ }
83
+ async function defaultRunTurn(room, text) {
84
+ const home = dshHome();
85
+ // Pass the user text as-is. Session stickiness is per-room in web-sessions.json;
86
+ // do not wrap WeCom turns in 桥接上下文 just to reuse a dialog.
87
+ return runHeadlessViaWeb({
88
+ task: text,
89
+ cwd: room,
90
+ env: {
91
+ ...process.env,
92
+ REZ_WECHAT_WORKSPACE: join(home, 'workspaces', room),
93
+ REZ_WECHAT_SESSION_STORE: join(home, 'dsh-rez-wecom', room, 'web-sessions.json'),
94
+ },
95
+ });
96
+ }
97
+ export function shouldStartWecomWebhook(bots = loadWecomChannels().bots) {
98
+ return bots.length === 0;
99
+ }
100
+ export class WecomChannel {
101
+ home;
102
+ factory;
103
+ runTurn;
104
+ bindings = new Map();
105
+ generation = 0;
106
+ constructor(opts) {
107
+ this.home = opts?.home ?? dshHome();
108
+ this.factory = opts?.factory ?? createOfficialWecomClient;
109
+ this.runTurn = opts?.runTurn ?? defaultRunTurn;
110
+ }
111
+ start() {
112
+ void this.reconnect();
113
+ }
114
+ status() {
115
+ return [...this.bindings.values()].map((row) => ({
116
+ room: row.bot.room,
117
+ botId: row.bot.botId,
118
+ phase: row.phase,
119
+ hint: row.hint,
120
+ }));
121
+ }
122
+ publicState() {
123
+ const file = loadWecomChannels(this.home);
124
+ return {
125
+ rooms: WECOM_BINDABLE_ROOMS,
126
+ bots: publicWecomBots(file),
127
+ status: this.status(),
128
+ };
129
+ }
130
+ async applyBots(incoming) {
131
+ const next = applyWecomBotPatch(loadWecomChannels(this.home), incoming);
132
+ saveWecomChannels(next, this.home);
133
+ await this.reconnect();
134
+ return this.publicState();
135
+ }
136
+ dispose() {
137
+ this.generation += 1;
138
+ this.dropBindings();
139
+ }
140
+ /** Test seam: wait until inbound handlers finish. */
141
+ async flush() {
142
+ await Promise.all([...this.bindings.values()].map((row) => row.queue));
143
+ }
144
+ async reconnect() {
145
+ const gen = ++this.generation;
146
+ this.dropBindings();
147
+ const bots = loadWecomChannels(this.home).bots;
148
+ for (const bot of bots) {
149
+ if (gen !== this.generation)
150
+ return;
151
+ await this.bind(bot);
152
+ }
153
+ }
154
+ dropBindings() {
155
+ for (const row of this.bindings.values()) {
156
+ try {
157
+ row.client.disconnect();
158
+ }
159
+ catch { /* already closed */ }
160
+ }
161
+ this.bindings.clear();
162
+ }
163
+ async bind(bot) {
164
+ const row = {
165
+ bot,
166
+ client: undefined,
167
+ phase: 'connecting',
168
+ hint: `正在连接「${bot.room}」企业微信机器人…`,
169
+ seen: [],
170
+ queue: Promise.resolve(),
171
+ };
172
+ this.bindings.set(bot.room, row);
173
+ try {
174
+ const client = await this.factory({ botId: bot.botId, secret: bot.secret });
175
+ row.client = client;
176
+ client.on('authenticated', () => {
177
+ row.phase = 'authenticated';
178
+ row.hint = `「${bot.room}」已接入。同事在企微跟这个机器人说话,会进网页左侧该房间的同一条会话。`;
179
+ });
180
+ client.on('disconnected', (reason) => {
181
+ if (row.phase === 'authenticated')
182
+ row.phase = 'connecting';
183
+ row.hint = `「${bot.room}」断开(${String(reason ?? '')}),正在重连…`;
184
+ });
185
+ client.on('error', (error) => {
186
+ row.phase = 'error';
187
+ const why = error instanceof Error ? error.message : String(error);
188
+ row.hint = `「${bot.room}」连接失败:${why}`;
189
+ });
190
+ client.on('message.text', (frame) => { this.enqueue(row, () => this.handleText(row, frame)); });
191
+ client.on('message.mixed', (frame) => { this.enqueue(row, () => this.handleText(row, frame)); });
192
+ client.on('message.image', (frame) => { this.enqueue(row, () => this.handleNonText(row, frame)); });
193
+ client.on('message.file', (frame) => { this.enqueue(row, () => this.handleNonText(row, frame)); });
194
+ client.on('message.voice', (frame) => { this.enqueue(row, () => this.handleNonText(row, frame)); });
195
+ client.on('message.video', (frame) => { this.enqueue(row, () => this.handleNonText(row, frame)); });
196
+ client.on('event.enter_chat', (frame) => {
197
+ this.enqueue(row, async () => {
198
+ await client.replyWelcome(frame, {
199
+ msgtype: 'text',
200
+ text: { content: `您好,我是「${bot.room}」。直接发文字即可。` },
201
+ });
202
+ });
203
+ });
204
+ client.connect();
205
+ }
206
+ catch (error) {
207
+ row.phase = 'error';
208
+ row.hint = `「${bot.room}」无法启动:${error instanceof Error ? error.message : String(error)}`;
209
+ }
210
+ }
211
+ enqueue(row, work) {
212
+ row.queue = row.queue.then(work, work).catch((error) => {
213
+ const why = error instanceof Error ? error.message : String(error);
214
+ console.error(`[wecom] ${row.bot.room}: ${why}`);
215
+ });
216
+ }
217
+ rememberMsgid(row, frame) {
218
+ const id = wecomMsgid(frame);
219
+ if (id.length === 0)
220
+ return false;
221
+ if (row.seen.includes(id))
222
+ return true;
223
+ row.seen.push(id);
224
+ if (row.seen.length > MAX_SEEN_MSGIDS)
225
+ row.seen.splice(0, row.seen.length - MAX_SEEN_MSGIDS);
226
+ return false;
227
+ }
228
+ async handleText(row, frame) {
229
+ if (this.rememberMsgid(row, frame))
230
+ return;
231
+ const text = extractWecomText(frame);
232
+ const streamId = newStreamId();
233
+ if (text.length === 0) {
234
+ await row.client.replyStream(frame, streamId, WECOM_NON_TEXT_HINT, true);
235
+ return;
236
+ }
237
+ try {
238
+ await row.client.replyStream(frame, streamId, '正在处理…', false);
239
+ const reply = await this.runTurn(row.bot.room, text);
240
+ await row.client.replyStream(frame, streamId, reply.length > 0 ? reply : '(空回复)', true);
241
+ }
242
+ catch (error) {
243
+ const why = error instanceof Error ? error.message : String(error);
244
+ await row.client.replyStream(frame, streamId, `处理失败:${why}`, true);
245
+ }
246
+ }
247
+ async handleNonText(row, frame) {
248
+ const text = extractWecomText(frame);
249
+ if (text.length > 0) {
250
+ await this.handleText(row, frame);
251
+ return;
252
+ }
253
+ if (this.rememberMsgid(row, frame))
254
+ return;
255
+ await row.client.replyStream(frame, newStreamId(), WECOM_NON_TEXT_HINT, true);
256
+ }
257
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Accio-style WeCom AI bot bindings: one botId+secret per Harness room.
3
+ * Secrets stay in ~/.dsh/wecom-channels.json (mode 600), not compose env.
4
+ */
5
+ export declare const WECOM_BINDABLE_ROOMS: readonly ["搞钱", "产品", "运营", "人事助理", "财务助理", "法务助理", "设计", "发布", "电商", "实验室"];
6
+ export type WecomBindableRoom = (typeof WECOM_BINDABLE_ROOMS)[number];
7
+ export interface WecomBotRecord {
8
+ room: string;
9
+ botId: string;
10
+ secret: string;
11
+ }
12
+ export interface WecomBotPublic {
13
+ room: string;
14
+ botId: string;
15
+ secretConfigured: boolean;
16
+ }
17
+ export interface WecomChannelFile {
18
+ bots: WecomBotRecord[];
19
+ }
20
+ export declare const WECOM_SECRET_MASK = "********";
21
+ export declare function wecomChannelsPath(home?: string): string;
22
+ export declare function isBindableRoom(room: string): boolean;
23
+ export declare function loadWecomChannels(home?: string): WecomChannelFile;
24
+ export declare function publicWecomBots(file: WecomChannelFile): WecomBotPublic[];
25
+ export declare function applyWecomBotPatch(current: WecomChannelFile, incoming: unknown): WecomChannelFile;
26
+ export declare function saveWecomChannels(file: WecomChannelFile, home?: string): void;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Accio-style WeCom AI bot bindings: one botId+secret per Harness room.
3
+ * Secrets stay in ~/.dsh/wecom-channels.json (mode 600), not compose env.
4
+ */
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { dshHome } from '@rezti/dsh-rez-sso';
8
+ export const WECOM_BINDABLE_ROOMS = [
9
+ '搞钱',
10
+ '产品',
11
+ '运营',
12
+ '人事助理',
13
+ '财务助理',
14
+ '法务助理',
15
+ '设计',
16
+ '发布',
17
+ '电商',
18
+ '实验室',
19
+ ];
20
+ export const WECOM_SECRET_MASK = '********';
21
+ export function wecomChannelsPath(home = dshHome()) {
22
+ return join(home, 'wecom-channels.json');
23
+ }
24
+ export function isBindableRoom(room) {
25
+ return WECOM_BINDABLE_ROOMS.includes(room);
26
+ }
27
+ export function loadWecomChannels(home = dshHome()) {
28
+ const file = wecomChannelsPath(home);
29
+ if (!existsSync(file))
30
+ return { bots: [] };
31
+ try {
32
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
33
+ if (typeof parsed !== 'object' || parsed === null)
34
+ return { bots: [] };
35
+ const bots = parsed.bots;
36
+ if (!Array.isArray(bots))
37
+ return { bots: [] };
38
+ const out = [];
39
+ for (const row of bots) {
40
+ if (typeof row !== 'object' || row === null)
41
+ continue;
42
+ const rec = row;
43
+ const room = typeof rec.room === 'string' ? rec.room.trim() : '';
44
+ const botId = typeof rec.botId === 'string' ? rec.botId.trim() : '';
45
+ const secret = typeof rec.secret === 'string' ? rec.secret.trim() : '';
46
+ if (room.length === 0 || botId.length === 0 || secret.length === 0)
47
+ continue;
48
+ if (!isBindableRoom(room))
49
+ continue;
50
+ out.push({ room, botId, secret });
51
+ }
52
+ return { bots: out };
53
+ }
54
+ catch {
55
+ return { bots: [] };
56
+ }
57
+ }
58
+ export function publicWecomBots(file) {
59
+ return file.bots.map((bot) => ({
60
+ room: bot.room,
61
+ botId: bot.botId,
62
+ secretConfigured: bot.secret.length > 0,
63
+ }));
64
+ }
65
+ export function applyWecomBotPatch(current, incoming) {
66
+ if (!Array.isArray(incoming))
67
+ return current;
68
+ const next = [];
69
+ const seen = new Set();
70
+ for (const row of incoming) {
71
+ if (typeof row !== 'object' || row === null)
72
+ continue;
73
+ const rec = row;
74
+ const room = typeof rec.room === 'string' ? rec.room.trim() : '';
75
+ const botId = typeof rec.botId === 'string' ? rec.botId.trim() : '';
76
+ if (room.length === 0 || botId.length === 0 || !isBindableRoom(room))
77
+ continue;
78
+ if (seen.has(room))
79
+ continue;
80
+ seen.add(room);
81
+ const secretRaw = typeof rec.secret === 'string' ? rec.secret.trim() : '';
82
+ const previous = current.bots.find((bot) => bot.room === room);
83
+ const secret = secretRaw.length > 0 && secretRaw !== WECOM_SECRET_MASK
84
+ ? secretRaw
85
+ : (previous?.secret ?? '');
86
+ if (secret.length === 0)
87
+ continue;
88
+ next.push({ room, botId, secret });
89
+ }
90
+ return { bots: next };
91
+ }
92
+ export function saveWecomChannels(file, home = dshHome()) {
93
+ const path = wecomChannelsPath(home);
94
+ mkdirSync(dirname(path), { recursive: true });
95
+ writeFileSync(path, JSON.stringify({ bots: file.bots }, null, 2) + '\n', { mode: 0o600 });
96
+ try {
97
+ chmodSync(path, 0o600);
98
+ }
99
+ catch { /* Windows 无 POSIX mode */ }
100
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rezti/dsh-rez-wechat",
3
- "version": "0.1.14",
4
- "description": "ReZ-TI WeChat/WeCom bridges. Personal WeChat is QClaw/ClawBot scan-and-chat via dsh-wechat-bridge; WeCom group send uses wecom-mcp.",
3
+ "version": "0.1.16",
4
+ "description": "ReZ-TI WeChat/WeCom bridges. Personal WeChat is QClaw/ClawBot scan-and-chat via dsh-wechat-bridge; WeCom AI bots use the official @wecom/aibot-node-sdk (BotID + Secret) bound per Harness room.",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": "^22.19.0 || >=24.0.0"
@@ -27,8 +27,9 @@
27
27
  ],
28
28
  "license": "Apache-2.0",
29
29
  "dependencies": {
30
+ "@wecom/aibot-node-sdk": "^1.0.7",
30
31
  "qrcode": "^1.5.4",
31
- "@rezti/dsh-rez-sso": "0.1.9"
32
+ "@rezti/dsh-rez-sso": "0.1.14"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@deepseek-ai/cordis": "^4.0.1",