dsh-supercrew 0.0.0-stage → 0.1.3
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/DESIGN.md +125 -0
- package/INSTALL.md +211 -0
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/supercrew.mjs +91 -0
- package/cordis.patch.yml +15 -0
- package/crew-watch.mjs +290 -0
- package/crew.mjs +520 -0
- package/crew_guard.ps1 +37 -0
- package/lib/index.js +124 -0
- package/lib/router.mjs +96 -0
- package/package.json +65 -6
- package/panel.mjs +229 -0
- package/skills/team-dispatch/SKILL.md +67 -0
- package/worker-models.yml +65 -0
package/crew-watch.mjs
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* crew-watch —— 入口适配器(QQ 版)
|
|
4
|
+
*
|
|
5
|
+
* 盯着 SnowLuma 桥的状态文件,把「有人 @ 我 / 私聊给我提的需求」变成工单。
|
|
6
|
+
*
|
|
7
|
+
* 用法:
|
|
8
|
+
* node crew-watch.mjs scan # 看一遍现在有哪些候选需求(不干活、不动 seen)
|
|
9
|
+
* node crew-watch.mjs judge # 只看门卫怎么判(同样不动 seen)
|
|
10
|
+
* node crew-watch.mjs once # 扫一遍:开单 + 派工 + 回传
|
|
11
|
+
* node crew-watch.mjs loop # 一直守着
|
|
12
|
+
* node crew-watch.mjs reply <id> # 把某张工单的结果发回它来的那个会话
|
|
13
|
+
*
|
|
14
|
+
* 环境变量:
|
|
15
|
+
* CREW_SOCIAL social-v2.json 路径(默认 D:\sf\surfcore-main\state\social-v2.json)
|
|
16
|
+
* CREW_API 桥接控制台地址(默认 http://127.0.0.1:3100)
|
|
17
|
+
* CREW_TOKENFILE 控制台令牌文件(默认 D:\sf\surfcore-main\state\console-token)
|
|
18
|
+
* CREW_TRIGGER 触发词正则(默认 @真白|@椎名真白|干活|派活|帮我做)
|
|
19
|
+
* CREW_WORKDIR worker 的默认工作目录
|
|
20
|
+
*
|
|
21
|
+
* 几个不显眼但会咬人的点(改之前先读):
|
|
22
|
+
* - seen 的键必须带会话前缀(key#id)。桥给的消息 id 有时为 null,会退化成
|
|
23
|
+
* 每会话自增的 seq —— 不带前缀的话,甲群的 seq=5 会把乙群的 seq=5 当成已读吞掉。
|
|
24
|
+
* - 预览(scan/judge/dryRun)绝不能写 seen:否则看一眼就把真需求吃掉了。
|
|
25
|
+
* - 回传失败要留在工单上(replyError),不能只打一行状态码 —— done 的工单不会再跑。
|
|
26
|
+
* - 桥的敏感词闸门不止挡盘符路径,还挡 unix 路径与 token=/password= 这类凭据字样。
|
|
27
|
+
*/
|
|
28
|
+
import fs from 'node:fs';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
import { addTicket, runTicket, loadAllTickets, saveTicket } from './crew.mjs';
|
|
31
|
+
import { judge } from './lib/router.mjs';
|
|
32
|
+
|
|
33
|
+
const SOCIAL = process.env.CREW_SOCIAL || 'D:\\sf\\surfcore-main\\state\\social-v2.json';
|
|
34
|
+
const API = process.env.CREW_API || 'http://127.0.0.1:3100';
|
|
35
|
+
const TOKENFILE = process.env.CREW_TOKENFILE || 'D:\\sf\\surfcore-main\\state\\console-token';
|
|
36
|
+
const TRIGGER = new RegExp(process.env.CREW_TRIGGER || '@真白|@椎名真白|干活|派活|帮我做');
|
|
37
|
+
const SEEN = path.join(
|
|
38
|
+
process.env.CREW_HOME || path.join(process.env.USERPROFILE || '.', '.dsh-supercrew'),
|
|
39
|
+
'seen.json',
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
function loadJson(p, def) {
|
|
43
|
+
try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return def; }
|
|
44
|
+
}
|
|
45
|
+
function saveJson(p, v) {
|
|
46
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
47
|
+
const tmp = `${p}.tmp`;
|
|
48
|
+
fs.writeFileSync(tmp, JSON.stringify(v, null, 2), 'utf8');
|
|
49
|
+
fs.renameSync(tmp, p); // 原子:写一半崩掉不会把 seen 弄丢(丢一次 = 最近 100 条全部重开单)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function readSocial() {
|
|
53
|
+
const s = loadJson(SOCIAL, null);
|
|
54
|
+
if (!s) throw new Error(`读不到 ${SOCIAL}`);
|
|
55
|
+
return s;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 把 social-v2.json 里所有会话的最近消息摊平 */
|
|
59
|
+
function allMessages(social) {
|
|
60
|
+
const out = [];
|
|
61
|
+
const convs = social.conversations || social.socialV2?.conversations || {};
|
|
62
|
+
for (const [key, c] of Object.entries(convs)) {
|
|
63
|
+
const msgs = c.recentMessages || c.messages || [];
|
|
64
|
+
for (const m of msgs) {
|
|
65
|
+
out.push({
|
|
66
|
+
key,
|
|
67
|
+
id: m.id ?? m.messageId ?? m.seq,
|
|
68
|
+
seq: m.seq ?? 0,
|
|
69
|
+
ts: m.timestamp ?? m.time ?? m.at ?? 0,
|
|
70
|
+
// 桥把正文截到 200 字(bridge.js 里写死的),这里拿到的可能已是残句
|
|
71
|
+
text: (m.text ?? m.content ?? '').trim(),
|
|
72
|
+
from: m.senderName ?? m.sender ?? m.nickname ?? m.userId ?? '',
|
|
73
|
+
isSelf: !!(m.isSelf ?? m.self ?? m.fromSelf),
|
|
74
|
+
raw: m,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out.sort((a, b) => (a.ts > b.ts ? 1 : -1));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** seen 的键:必须带会话前缀,否则跨会话的 seq 会互相顶掉 */
|
|
82
|
+
const seenKey = (m) => `${m.key}#${m.id}`;
|
|
83
|
+
|
|
84
|
+
/** 一条消息算不算「给我派的活」 */
|
|
85
|
+
export function isWorkRequest(msg) {
|
|
86
|
+
if (!msg.text) return false;
|
|
87
|
+
if (msg.isSelf) return false; // 我自己说的不算
|
|
88
|
+
return TRIGGER.test(msg.text);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 去掉触发词,剩下的就是需求正文 */
|
|
92
|
+
export function stripTrigger(text) {
|
|
93
|
+
return text.replace(new RegExp(TRIGGER.source, 'g'), '').replace(/^[\s::,,.。!!??-]+/, '').trim();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function seenSet() { return new Set(loadJson(SEEN, [])); }
|
|
97
|
+
function markSeen(keys) {
|
|
98
|
+
const s = seenSet();
|
|
99
|
+
for (const k of keys) s.add(String(k));
|
|
100
|
+
saveJson(SEEN, [...s].slice(-3000));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function scan({ onlyNew = true } = {}) {
|
|
104
|
+
const social = readSocial();
|
|
105
|
+
const seen = seenSet();
|
|
106
|
+
const found = [];
|
|
107
|
+
for (const m of allMessages(social)) {
|
|
108
|
+
if (!isWorkRequest(m)) continue;
|
|
109
|
+
if (onlyNew && seen.has(seenKey(m))) continue;
|
|
110
|
+
found.push(m);
|
|
111
|
+
}
|
|
112
|
+
return found;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 扫一遍并开单。
|
|
117
|
+
* dryRun=true 时只判定不开单、也不写 seen(预览不该吃掉真需求)。
|
|
118
|
+
*/
|
|
119
|
+
export async function intake({ dryRun = false, concurrency = 4 } = {}) {
|
|
120
|
+
const found = scan({ onlyNew: true });
|
|
121
|
+
const cands = found
|
|
122
|
+
.map((m) => ({ m, body: stripTrigger(m.text) }))
|
|
123
|
+
.filter((x) => x.body);
|
|
124
|
+
|
|
125
|
+
const made = [];
|
|
126
|
+
const skipped = [];
|
|
127
|
+
const failed = [];
|
|
128
|
+
const queue = [...cands];
|
|
129
|
+
|
|
130
|
+
// 门卫要调模型,一条一条问太慢 —— 并发问,最多 concurrency 条同时。
|
|
131
|
+
const lanes = Array.from({ length: Math.min(concurrency, queue.length || 1) }, async () => {
|
|
132
|
+
for (;;) {
|
|
133
|
+
const item = queue.shift();
|
|
134
|
+
if (!item) return;
|
|
135
|
+
const { m, body } = item;
|
|
136
|
+
try {
|
|
137
|
+
// 门卫:@ 我一下不等于给我派了活。判不出就放过(宁可漏,不可瞎干)。
|
|
138
|
+
const j = await judge(body);
|
|
139
|
+
if (!j.isTask) {
|
|
140
|
+
skipped.push({ key: m.key, from: m.from, text: body, why: j.reason });
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (dryRun) { made.push({ dryRun: true, ...j, chatKey: m.key, msgId: m.id }); continue; }
|
|
144
|
+
|
|
145
|
+
const t = addTicket({
|
|
146
|
+
body: j.body || body,
|
|
147
|
+
title: j.title || body.slice(0, 40),
|
|
148
|
+
cwd: process.env.CREW_WORKDIR || process.cwd(),
|
|
149
|
+
source: `qq:${m.key}`,
|
|
150
|
+
requester: m.from,
|
|
151
|
+
chatKey: m.key, // 落盘时就带上(此前是落盘后才挂内存 → reply 永远找不到来源)
|
|
152
|
+
msgId: String(m.id ?? ''),
|
|
153
|
+
});
|
|
154
|
+
t.judged = { reason: j.reason, by: j.by, original: body };
|
|
155
|
+
if (body.length >= 195) t.truncated = true; // 桥截到 200 字,需求可能只剩半句
|
|
156
|
+
saveTicket(t);
|
|
157
|
+
made.push(t);
|
|
158
|
+
} catch (e) {
|
|
159
|
+
// 单条出错不能拖垮整批(否则这一批既没开单、又因为 markSeen 没执行而下一轮重复开)
|
|
160
|
+
failed.push({ key: m.key, text: body.slice(0, 40), why: e.message });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
await Promise.all(lanes);
|
|
165
|
+
|
|
166
|
+
if (!dryRun) markSeen(found.map(seenKey));
|
|
167
|
+
return { made, skipped, failed };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 桥的敏感词闸门(sensitive.js 的 SENSITIVE_RE)有四类,全都要挡 */
|
|
171
|
+
function sanitize(s) {
|
|
172
|
+
return String(s)
|
|
173
|
+
.replace(/(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s"'<>|]+/g, '(本机文件)') // 盘符路径
|
|
174
|
+
.replace(/\\\\[^\\\s"'<>|]+\\[^\s"'<>|]+/g, '(本机文件)') // UNC
|
|
175
|
+
.replace(/(?<![A-Za-z0-9])\/(?:home|Users|etc|var|root|opt|tmp|mnt)\/[^\s"'<>|]*/g, '(本机文件)')
|
|
176
|
+
.replace(/\bBearer\s+[A-Za-z0-9._-]+/gi, 'Bearer (已隐去)')
|
|
177
|
+
.replace(/\b(token|password|passwd|secret|api[_-]?key)\s*[:=]\s*[^\s,,。;;]+/gi, '$1=(已隐去)');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 把结果发回它来的会话;失败会把原因记进工单,方便事后补发 */
|
|
181
|
+
export async function reply(ticket) {
|
|
182
|
+
const key = ticket.chatKey;
|
|
183
|
+
if (!key) throw new Error('这张工单没有来源会话');
|
|
184
|
+
|
|
185
|
+
// 两个令牌都要带:
|
|
186
|
+
// ① x-console-token —— 桥的全局关卡(所有 /api/* 都查它)
|
|
187
|
+
// ② body.token —— 会话级 agent token(reserved2 模式下 /api/send 也查它)
|
|
188
|
+
// 少任何一个都会被拒:只带 console 会 403「必须携带 agent token」,
|
|
189
|
+
// 只带 agent 会 401「未授权:请提供控制台访问令牌」。
|
|
190
|
+
const social = readSocial();
|
|
191
|
+
const conv = (social.conversations || {})[key] || {};
|
|
192
|
+
const agentToken = conv.agentToken || '';
|
|
193
|
+
if (!agentToken) throw new Error(`会话 ${key} 没有 agentToken,发不出去`);
|
|
194
|
+
const consoleToken = fs.readFileSync(TOKENFILE, 'utf8').trim();
|
|
195
|
+
|
|
196
|
+
const isGroup = key.startsWith('group:');
|
|
197
|
+
const id = key.split(':')[1];
|
|
198
|
+
const url = `${API}/api/send/${isGroup ? 'group' : 'private'}`;
|
|
199
|
+
|
|
200
|
+
const head = ticket.state === 'done' ? '做完了' : '没做成';
|
|
201
|
+
const detail = sanitize(ticket.result || ticket.error || '').replace(/\s+/g, ' ').trim();
|
|
202
|
+
const message = `【工单 ${ticket.id}】${head}:${detail}`.slice(0, 460);
|
|
203
|
+
|
|
204
|
+
const payload = isGroup
|
|
205
|
+
? { groupId: id, token: agentToken, message }
|
|
206
|
+
: { userId: id, token: agentToken, message };
|
|
207
|
+
|
|
208
|
+
let status = 0, body = '';
|
|
209
|
+
try {
|
|
210
|
+
const r = await fetch(url, {
|
|
211
|
+
method: 'POST',
|
|
212
|
+
headers: { 'content-type': 'application/json', 'x-console-token': consoleToken },
|
|
213
|
+
body: JSON.stringify(payload),
|
|
214
|
+
});
|
|
215
|
+
status = r.status;
|
|
216
|
+
body = await r.text();
|
|
217
|
+
} catch (e) {
|
|
218
|
+
status = -1;
|
|
219
|
+
body = e.message;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// 失败要留痕:done 的工单不会再跑一遍,只有记下来才能事后 reply <id> 补发
|
|
223
|
+
try {
|
|
224
|
+
const ok = status >= 200 && status < 300;
|
|
225
|
+
const fresh = loadAllTickets().find((t) => t.id === ticket.id);
|
|
226
|
+
if (fresh) {
|
|
227
|
+
fresh.replyAt = new Date().toISOString();
|
|
228
|
+
fresh.replyStatus = status;
|
|
229
|
+
fresh.replyError = ok ? null : `HTTP ${status}: ${String(body).slice(0, 300)}`;
|
|
230
|
+
saveTicket(fresh);
|
|
231
|
+
}
|
|
232
|
+
} catch { /* 记不上就算了,别因为记账失败影响发送结果 */ }
|
|
233
|
+
|
|
234
|
+
return { status, body };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function main() {
|
|
238
|
+
const [cmd, arg] = process.argv.slice(2);
|
|
239
|
+
const showJudged = ({ made, skipped, failed }) => {
|
|
240
|
+
console.log(`门卫放行 ${made.length} 条,拦下 ${skipped.length} 条${failed && failed.length ? `,出错 ${failed.length} 条` : ''}`);
|
|
241
|
+
for (const t of made) console.log(` ✔ ${t.title || t.body}`);
|
|
242
|
+
for (const s of skipped) console.log(` · 拦下「${(s.text || '').slice(0, 30)}」← ${s.why}`);
|
|
243
|
+
for (const f of failed || []) console.log(` ✗ 「${f.text}」← ${f.why}`);
|
|
244
|
+
};
|
|
245
|
+
if (cmd === 'scan') {
|
|
246
|
+
const found = scan();
|
|
247
|
+
console.log(`找到 ${found.length} 条提到我的消息:`);
|
|
248
|
+
for (const m of found) console.log(` [${m.key}] ${m.from}: ${m.text.slice(0, 70)}`);
|
|
249
|
+
} else if (cmd === 'judge') {
|
|
250
|
+
showJudged(await intake({ dryRun: true }));
|
|
251
|
+
} else if (cmd === 'once') {
|
|
252
|
+
const r = await intake();
|
|
253
|
+
showJudged(r);
|
|
254
|
+
for (const t of r.made) {
|
|
255
|
+
console.log(`▶ ${t.id} ${t.title}`);
|
|
256
|
+
const done = await runTicket(t.id);
|
|
257
|
+
if (!done) { console.log(' (被别的进程抢走了)'); continue; }
|
|
258
|
+
console.log(` ${done.state} ${(done.result || done.error || '').slice(0, 200)}`);
|
|
259
|
+
const rr = await reply(done);
|
|
260
|
+
console.log(` 结果回传:${rr.status}`);
|
|
261
|
+
}
|
|
262
|
+
} else if (cmd === 'loop') {
|
|
263
|
+
console.log('守着…… Ctrl+C 退出');
|
|
264
|
+
for (;;) {
|
|
265
|
+
try {
|
|
266
|
+
const r = await intake();
|
|
267
|
+
if (r.made.length || r.failed.length) showJudged(r);
|
|
268
|
+
for (const t of r.made) {
|
|
269
|
+
console.log(`▶ ${t.id} ${t.title}`);
|
|
270
|
+
const done = await runTicket(t.id);
|
|
271
|
+
if (!done) { console.log(' (被别的进程抢走了)'); continue; }
|
|
272
|
+
const rr = await reply(done);
|
|
273
|
+
console.log(` 结果回传:${rr.status}${rr.status >= 300 ? ` —— ${String(rr.body).slice(0, 120)}` : ''}`);
|
|
274
|
+
}
|
|
275
|
+
} catch (e) {
|
|
276
|
+
console.error('这一轮出错:', e.message);
|
|
277
|
+
}
|
|
278
|
+
await new Promise((r) => setTimeout(r, 15000));
|
|
279
|
+
}
|
|
280
|
+
} else if (cmd === 'reply') {
|
|
281
|
+
const t = loadAllTickets().find((x) => x.id === arg);
|
|
282
|
+
if (!t) { console.log('没有这张工单'); return; }
|
|
283
|
+
console.log(await reply(t));
|
|
284
|
+
} else {
|
|
285
|
+
console.log('用法:node crew-watch.mjs <scan|judge|once|loop|reply <id>>');
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const isMain = process.argv[1] && process.argv[1].endsWith('crew-watch.mjs');
|
|
290
|
+
if (isMain) main().catch((e) => { console.error(e); process.exitCode = 1; });
|