@dsh-overdrive/gateway 0.2.0 → 0.3.1
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/dist/commands.d.ts +5 -0
- package/dist/commands.js +14 -4
- package/dist/commands.js.map +1 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.js +57 -8
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +43 -0
- package/dist/memory.js.map +1 -1
- package/dist/mention.d.ts +13 -0
- package/dist/mention.js +43 -0
- package/dist/mention.js.map +1 -0
- package/dist/pending-buttons.d.ts +5 -1
- package/dist/pending-buttons.js +26 -8
- package/dist/pending-buttons.js.map +1 -1
- package/dist/text.d.ts +2 -0
- package/dist/text.js +24 -0
- package/dist/text.js.map +1 -0
- package/package.json +9 -4
- package/src/adapter.ts +0 -42
- package/src/adapters/cli.ts +0 -37
- package/src/adapters/dingtalk.ts +0 -206
- package/src/adapters/discord.ts +0 -127
- package/src/adapters/feishu.ts +0 -224
- package/src/adapters/slack.ts +0 -123
- package/src/adapters/telegram.ts +0 -142
- package/src/adapters/wechat.ts +0 -247
- package/src/adapters/wecom.ts +0 -218
- package/src/adapters/whatsapp.ts +0 -249
- package/src/asr.ts +0 -83
- package/src/commands.ts +0 -89
- package/src/config.ts +0 -104
- package/src/feed.ts +0 -190
- package/src/index.ts +0 -456
- package/src/memory.ts +0 -133
- package/src/pending-buttons.ts +0 -45
- package/src/session.ts +0 -23
- package/src/setup.ts +0 -252
- package/src/status.ts +0 -63
- package/src/trajectory.ts +0 -45
- package/test/adapters.dingtalk.test.ts +0 -64
- package/test/adapters.discord.test.ts +0 -41
- package/test/adapters.feishu.test.ts +0 -66
- package/test/adapters.slack.test.ts +0 -45
- package/test/adapters.telegram.test.ts +0 -37
- package/test/adapters.wechat.test.ts +0 -78
- package/test/adapters.wecom.test.ts +0 -62
- package/test/adapters.whatsapp.test.ts +0 -138
- package/test/asr.test.ts +0 -77
- package/test/commands.test.ts +0 -43
- package/test/config.test.ts +0 -30
- package/test/feed.test.ts +0 -111
- package/test/memory.test.ts +0 -79
- package/test/multi.test.ts +0 -258
- package/test/outbound.test.ts +0 -29
- package/test/pending-buttons.test.ts +0 -61
- package/test/session.test.ts +0 -26
- package/test/status.test.ts +0 -41
- package/test/streaming.test.ts +0 -162
- package/test/trajectory.test.ts +0 -58
- package/tsconfig.json +0 -5
package/src/setup.ts
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-overdrive setup wizard — 交互式设置向导(hermes setup 风格)
|
|
3
|
-
*
|
|
4
|
-
* 用法:
|
|
5
|
-
* node packages/gateway/dist/setup.js (源码构建后)
|
|
6
|
-
* npx dsh-overdrive-setup (npm 全局/临时)
|
|
7
|
-
*
|
|
8
|
-
* 流程:DeepSeek key → 平台多选 → 逐个收集凭据并联网验证 → 写 .env → 打印下一步。
|
|
9
|
-
* 全程英文为主、中文为辅;验证失败会提示"是否继续"。
|
|
10
|
-
*/
|
|
11
|
-
import { createInterface } from 'node:readline/promises';
|
|
12
|
-
import { stdin, stdout } from 'node:process';
|
|
13
|
-
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
14
|
-
import { join } from 'node:path';
|
|
15
|
-
|
|
16
|
-
const C = {
|
|
17
|
-
cyan: (t: string) => `\x1b[36m${t}\x1b[0m`,
|
|
18
|
-
green: (t: string) => `\x1b[32m${t}\x1b[0m`,
|
|
19
|
-
red: (t: string) => `\x1b[31m${t}\x1b[0m`,
|
|
20
|
-
dim: (t: string) => `\x1b[90m${t}\x1b[0m`,
|
|
21
|
-
bold: (t: string) => `\x1b[1m${t}\x1b[0m`,
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* 输入层:TTY 用 readline(交互终端);非 TTY 预读全部 stdin(管道/自动化/测试),
|
|
26
|
-
* 逐行分发。输入耗尽时返回 '',由 stopIfClosed 优雅收尾。
|
|
27
|
-
*/
|
|
28
|
-
const isTTY = !!stdin.isTTY;
|
|
29
|
-
let ttyRl: ReturnType<typeof createInterface> | null = null;
|
|
30
|
-
const pipeLines: string[] = [];
|
|
31
|
-
if (!isTTY) {
|
|
32
|
-
const chunks: Buffer[] = [];
|
|
33
|
-
for await (const chunk of stdin) chunks.push(chunk);
|
|
34
|
-
pipeLines.push(...Buffer.concat(chunks).toString('utf8').split(/\r?\n/));
|
|
35
|
-
}
|
|
36
|
-
let inputClosed = !isTTY && pipeLines.length === 0;
|
|
37
|
-
async function promptOnce(question: string): Promise<string> {
|
|
38
|
-
if (isTTY) {
|
|
39
|
-
ttyRl ??= createInterface({ input: stdin, output: stdout, terminal: true });
|
|
40
|
-
try {
|
|
41
|
-
return await ttyRl.question(question);
|
|
42
|
-
} catch {
|
|
43
|
-
inputClosed = true;
|
|
44
|
-
return '';
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
const line = pipeLines.shift() ?? '';
|
|
48
|
-
if (line === '' && pipeLines.length === 0) inputClosed = true;
|
|
49
|
-
stdout.write(`${question}${line}\n`); // 非 TTY 无回显,手动回显
|
|
50
|
-
return line;
|
|
51
|
-
}
|
|
52
|
-
function closeInput(): void {
|
|
53
|
-
try { ttyRl?.close(); } catch { /* noop */ }
|
|
54
|
-
}
|
|
55
|
-
async function ask(q: string, hint = ''): Promise<string> {
|
|
56
|
-
const answer = await promptOnce(`${C.cyan('?')} ${q} ${C.dim(hint)}\n> `);
|
|
57
|
-
return answer.trim();
|
|
58
|
-
}
|
|
59
|
-
async function confirm(q: string): Promise<boolean> {
|
|
60
|
-
const a = (await promptOnce(`${C.cyan('?')} ${q} ${C.dim('[y/N]')}\n> `)).trim().toLowerCase();
|
|
61
|
-
return a === 'y' || a === 'yes';
|
|
62
|
-
}
|
|
63
|
-
function stopIfClosed(): void {
|
|
64
|
-
if (inputClosed) {
|
|
65
|
-
console.log(C.dim('\n input closed — aborting / 输入已关闭,向导中止'));
|
|
66
|
-
console.log(C.dim(' (run in an interactive terminal / 请在交互式终端中运行)'));
|
|
67
|
-
process.exit(1);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** 联网验证辅助:返回 {ok, reason};网络异常按"无法验证"处理(由调用方决定是否继续)。 */
|
|
72
|
-
async function probe(fn: () => Promise<boolean>, name: string): Promise<{ ok: boolean; reason: string }> {
|
|
73
|
-
try {
|
|
74
|
-
return (await fn()) ? { ok: true, reason: `${name} verified / 验证通过` } : { ok: false, reason: `${name} rejected / 验证失败` };
|
|
75
|
-
} catch (error) {
|
|
76
|
-
return { ok: false, reason: `${name} unreachable (network?) / 网络不可达: ${error instanceof Error ? error.message : String(error)}` };
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const PROBES: Record<string, (v: Record<string, string>) => Promise<boolean>> = {
|
|
81
|
-
deepseek: async (v) => {
|
|
82
|
-
const r = await fetch('https://api.deepseek.com/user/balance', { headers: { authorization: `Bearer ${v.DEEPSEEK_API_KEY}` } });
|
|
83
|
-
return r.ok;
|
|
84
|
-
},
|
|
85
|
-
telegram: async (v) => {
|
|
86
|
-
const r = await fetch(`https://api.telegram.org/bot${v.TELEGRAM_BOT_TOKEN}/getMe`);
|
|
87
|
-
const j = (await r.json()) as { ok?: boolean };
|
|
88
|
-
return j.ok === true;
|
|
89
|
-
},
|
|
90
|
-
discord: async (v) => {
|
|
91
|
-
const r = await fetch('https://discord.com/api/v10/users/@me', { headers: { authorization: `Bot ${v.DISCORD_BOT_TOKEN}` } });
|
|
92
|
-
return r.ok;
|
|
93
|
-
},
|
|
94
|
-
slack: async (v) => {
|
|
95
|
-
const r = await fetch('https://slack.com/api/auth.test', { headers: { authorization: `Bearer ${v.SLACK_BOT_TOKEN}` } });
|
|
96
|
-
const j = (await r.json()) as { ok?: boolean };
|
|
97
|
-
return j.ok === true;
|
|
98
|
-
},
|
|
99
|
-
feishu: async (v) => {
|
|
100
|
-
const r = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
|
|
101
|
-
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
102
|
-
body: JSON.stringify({ app_id: v.FEISHU_APP_ID, app_secret: v.FEISHU_APP_SECRET }),
|
|
103
|
-
});
|
|
104
|
-
const j = (await r.json()) as { code?: number };
|
|
105
|
-
return j.code === 0;
|
|
106
|
-
},
|
|
107
|
-
dingtalk: async (v) => {
|
|
108
|
-
const r = await fetch('https://api.dingtalk.com/v1.0/oauth2/accessToken', {
|
|
109
|
-
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
110
|
-
body: JSON.stringify({ appKey: v.DINGTALK_CLIENT_ID, appSecret: v.DINGTALK_CLIENT_SECRET }),
|
|
111
|
-
});
|
|
112
|
-
return r.ok;
|
|
113
|
-
},
|
|
114
|
-
wecom: async (v) => {
|
|
115
|
-
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(v.WECOM_CORP_ID)}&corpsecret=${encodeURIComponent(v.WECOM_SECRET)}`;
|
|
116
|
-
const j = (await (await fetch(url)).json()) as { errcode?: number };
|
|
117
|
-
return j.errcode === 0;
|
|
118
|
-
},
|
|
119
|
-
};
|
|
120
|
-
|
|
121
|
-
const PLATFORMS: Record<string, { label: string; fields: Array<[key: string, prompt: string, hint: string, pattern?: RegExp]> }> = {
|
|
122
|
-
telegram: {
|
|
123
|
-
label: 'Telegram',
|
|
124
|
-
fields: [['TELEGRAM_BOT_TOKEN', 'Telegram bot token', 'https://t.me/BotFather → /newbot', /^\d+:[A-Za-z0-9_-]{20,}$/]],
|
|
125
|
-
},
|
|
126
|
-
whatsapp: {
|
|
127
|
-
label: 'WhatsApp (no credentials — QR pairing on first start / 无需凭据,首次启动扫码)',
|
|
128
|
-
fields: [],
|
|
129
|
-
},
|
|
130
|
-
discord: {
|
|
131
|
-
label: 'Discord',
|
|
132
|
-
fields: [['DISCORD_BOT_TOKEN', 'Discord bot token', 'Developer Portal → Bot → Token', /^[A-Za-z0-9._-]{20,}$/]],
|
|
133
|
-
},
|
|
134
|
-
slack: {
|
|
135
|
-
label: 'Slack (Socket Mode)',
|
|
136
|
-
fields: [
|
|
137
|
-
['SLACK_BOT_TOKEN', 'Slack bot token (xoxb-…)', 'App → OAuth & Permissions', /^xoxb-/],
|
|
138
|
-
['SLACK_APP_TOKEN', 'Slack app-level token (xapp-…)', 'App → Basic Information → App-Level Tokens', /^xapp-/],
|
|
139
|
-
],
|
|
140
|
-
},
|
|
141
|
-
feishu: {
|
|
142
|
-
label: '飞书 Feishu',
|
|
143
|
-
fields: [
|
|
144
|
-
['FEISHU_APP_ID', 'Feishu App ID', '开放平台 → 应用凭证', /^cli_/],
|
|
145
|
-
['FEISHU_APP_SECRET', 'Feishu App Secret', '开放平台 → 应用凭证', /.+/],
|
|
146
|
-
],
|
|
147
|
-
},
|
|
148
|
-
dingtalk: {
|
|
149
|
-
label: '钉钉 DingTalk',
|
|
150
|
-
fields: [
|
|
151
|
-
['DINGTALK_CLIENT_ID', 'DingTalk Client ID (AppKey)', '应用开发 → 凭证与基础信息', /.+/],
|
|
152
|
-
['DINGTALK_CLIENT_SECRET', 'DingTalk Client Secret', '应用开发 → 凭证与基础信息', /.+/],
|
|
153
|
-
],
|
|
154
|
-
},
|
|
155
|
-
wecom: {
|
|
156
|
-
label: '企业微信 WeCom',
|
|
157
|
-
fields: [
|
|
158
|
-
['WECOM_CORP_ID', 'WeCom Corp ID', '我的企业 → 企业信息', /.+/],
|
|
159
|
-
['WECOM_SECRET', 'WeCom Secret', '应用管理 → 应用 → Secret', /.+/],
|
|
160
|
-
['WECOM_AGENT_ID', 'WeCom Agent ID', '应用管理 → 应用 → AgentId', /^\d+$/],
|
|
161
|
-
['WECOM_TOKEN', 'WeCom callback Token', '接收消息 → Token(随意填一串)', /.+/],
|
|
162
|
-
['WECOM_ENCODING_AES_KEY', 'WeCom EncodingAESKey', '接收消息 → EncodingAESKey(43 位)', /^[A-Za-z0-9]{43}$/],
|
|
163
|
-
],
|
|
164
|
-
},
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
/** 读取已有 .env(若存在)合并;返回新内容。 */
|
|
168
|
-
function buildEnv(current: string, pairs: Array<[string, string]>): string {
|
|
169
|
-
const map = new Map<string, string>();
|
|
170
|
-
for (const line of current.split(/\r?\n/)) {
|
|
171
|
-
const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
|
|
172
|
-
if (m) map.set(m[1], m[2]);
|
|
173
|
-
}
|
|
174
|
-
for (const [k, v] of pairs) map.set(k, v);
|
|
175
|
-
return [...map.entries()].map(([k, v]) => `${k}=${v}`).join('\n') + '\n';
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
async function main(): Promise<void> {
|
|
179
|
-
console.log('');
|
|
180
|
-
console.log(C.bold(C.cyan('==================================================')));
|
|
181
|
-
console.log(C.bold(C.cyan(' dsh-overdrive setup — the OpenClaw of DeepSeek Harness')));
|
|
182
|
-
console.log(C.bold(C.cyan(' 交互式设置向导(hermes setup 风格)')));
|
|
183
|
-
console.log(C.bold(C.cyan('==================================================')));
|
|
184
|
-
console.log('');
|
|
185
|
-
|
|
186
|
-
const pairs: Array<[string, string]> = [];
|
|
187
|
-
let platforms: string[] = [];
|
|
188
|
-
|
|
189
|
-
// 1. DeepSeek API key
|
|
190
|
-
console.log(C.dim(' 1/3 DeepSeek API key — get one: https://platform.deepseek.com/api_keys'));
|
|
191
|
-
for (;;) {
|
|
192
|
-
const key = await ask('Paste your DeepSeek API key (sk-…)', '必填');
|
|
193
|
-
stopIfClosed();
|
|
194
|
-
if (!/^sk-/.test(key)) { console.log(C.red(' [x] should start with sk- / 应以 sk- 开头')); continue; }
|
|
195
|
-
const r = await probe(() => PROBES.deepseek({ DEEPSEEK_API_KEY: key }), 'DeepSeek key');
|
|
196
|
-
console.log(r.ok ? C.green(` [ok] ${r.reason}`) : C.red(` [!] ${r.reason}`));
|
|
197
|
-
if (r.ok || (await confirm('Continue anyway? / 仍然继续?'))) { pairs.push(['DEEPSEEK_API_KEY', key]); break; }
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// 2. platforms
|
|
201
|
-
console.log(C.dim(' 2/3 Platforms — telegram, whatsapp, discord, slack, feishu, dingtalk, wecom'));
|
|
202
|
-
const chosen = await ask('Which platforms? (comma separated, default: telegram)', '逗号分隔,默认 telegram');
|
|
203
|
-
stopIfClosed();
|
|
204
|
-
platforms = (chosen || 'telegram').split(',').map((s) => s.trim().toLowerCase()).filter((s) => PLATFORMS[s]);
|
|
205
|
-
if (platforms.length === 0) { console.log(C.red(' [x] no valid platform selected / 未选择有效平台')); process.exit(1); }
|
|
206
|
-
|
|
207
|
-
// 3. per-platform credentials
|
|
208
|
-
console.log(C.dim(' 3/3 Platform credentials (each is verified live) / 平台凭据(逐个实时验证)'));
|
|
209
|
-
for (const p of platforms) {
|
|
210
|
-
console.log(`\n ${C.bold('-- ' + PLATFORMS[p].label)} --`);
|
|
211
|
-
const vals: Record<string, string> = { ...Object.fromEntries(pairs) };
|
|
212
|
-
for (const [key, prompt, hint, pattern] of PLATFORMS[p].fields) {
|
|
213
|
-
for (;;) {
|
|
214
|
-
const v = await ask(prompt, hint);
|
|
215
|
-
stopIfClosed();
|
|
216
|
-
if (pattern && !pattern.test(v)) { console.log(C.red(` [x] format looks wrong / 格式不对(${hint})`)); continue; }
|
|
217
|
-
vals[key] = v;
|
|
218
|
-
break;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
const probeFn = PROBES[p];
|
|
222
|
-
if (probeFn && p !== 'whatsapp') {
|
|
223
|
-
const r = await probe(() => probeFn(vals), PLATFORMS[p].label);
|
|
224
|
-
console.log(r.ok ? C.green(` [ok] ${r.reason}`) : C.red(` [!] ${r.reason}`));
|
|
225
|
-
if (!r.ok && !(await confirm('Continue anyway? / 仍然继续?'))) { console.log(C.red(' skipped / 已跳过')); continue; }
|
|
226
|
-
}
|
|
227
|
-
for (const [k, v] of PLATFORMS[p].fields) pairs.push([k, vals[k]]);
|
|
228
|
-
}
|
|
229
|
-
if (platforms.includes('whatsapp')) console.log(C.dim(' WhatsApp: no credentials needed — QR shows on first start / 无需凭据,启动时扫码'));
|
|
230
|
-
|
|
231
|
-
// 4. write .env
|
|
232
|
-
const envPath = join(process.cwd(), '.env');
|
|
233
|
-
const current = existsSync(envPath) ? readFileSync(envPath, 'utf8') : '';
|
|
234
|
-
const merged = buildEnv(current, [...pairs, ['GATEWAY_ADAPTERS', platforms.join(',')], ['DSH_OVERDRIVE_TOKEN', 'dsh-overdrive-token']]);
|
|
235
|
-
writeFileSync(envPath, merged, 'utf8');
|
|
236
|
-
console.log(`\n ${C.green('[ok]')} .env written → ${C.bold(envPath)}(已合并现有配置)`);
|
|
237
|
-
|
|
238
|
-
// 5. next steps
|
|
239
|
-
console.log('');
|
|
240
|
-
console.log(C.bold(C.cyan('==================================================')));
|
|
241
|
-
console.log(C.bold(C.cyan(' Next steps / 下一步')));
|
|
242
|
-
console.log(` ${C.cyan('1)')} Start: docker compose -f deploy/docker-compose.yml up -d --build`);
|
|
243
|
-
console.log(` or: GATEWAY_ADAPTERS=${platforms.join(',')} npx @dsh-overdrive/gateway`);
|
|
244
|
-
console.log(` ${C.cyan('2)')} Console / 控制台: http://localhost:3190/ (含四步引导向导)`);
|
|
245
|
-
console.log(` ${C.cyan('3)')} DSH Web UI (model): http://localhost:3080/`);
|
|
246
|
-
console.log(` ${C.cyan('4)')} In your chat app: send /help`);
|
|
247
|
-
console.log(C.bold(C.cyan('==================================================')));
|
|
248
|
-
console.log('');
|
|
249
|
-
closeInput();
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
void main();
|
package/src/status.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { createServer, type Server } from 'node:http';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import type { Adapter } from './adapter.js';
|
|
5
|
-
import type { GatewayClient } from '@dsh-overdrive/sdk';
|
|
6
|
-
|
|
7
|
-
export interface StatusServerOptions {
|
|
8
|
-
adapters: Adapter[];
|
|
9
|
-
client: GatewayClient;
|
|
10
|
-
version: string;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* 健康控制台:GET / 与 /console 返回静态页,GET /api/status 返回 DSH 健康 + 适配器状态。
|
|
15
|
-
*
|
|
16
|
-
* console.html 读取路径说明(与 dist 产物核对过):
|
|
17
|
-
* - src 运行(vitest):import.meta.url = packages/gateway/src/status.ts → ../web/console.html = packages/gateway/web/console.html
|
|
18
|
-
* - dist 运行(node packages/gateway/dist/index.js):import.meta.url = packages/gateway/dist/status.js → ../web/console.html = packages/gateway/web/console.html
|
|
19
|
-
* - npm 安装(@dsh-overdrive/gateway):console.html 随包分发,两种形态均可命中。
|
|
20
|
-
*/
|
|
21
|
-
export function createStatusServer(opts: StatusServerOptions): {
|
|
22
|
-
server: Server;
|
|
23
|
-
listen(port: number): Promise<number>;
|
|
24
|
-
close(): Promise<void>;
|
|
25
|
-
} {
|
|
26
|
-
const http = createServer(async (req, res) => {
|
|
27
|
-
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
28
|
-
if (url.pathname === '/api/status') {
|
|
29
|
-
let dsh: { status: string } | { error: string };
|
|
30
|
-
try {
|
|
31
|
-
dsh = await opts.client.health();
|
|
32
|
-
} catch (error) {
|
|
33
|
-
dsh = { error: error instanceof Error ? error.message : String(error) };
|
|
34
|
-
}
|
|
35
|
-
const adapters = opts.adapters.map((a) => ({
|
|
36
|
-
id: a.id,
|
|
37
|
-
connected: a.status?.().connected ?? null,
|
|
38
|
-
}));
|
|
39
|
-
res.writeHead(200, { 'content-type': 'application/json' });
|
|
40
|
-
res.end(JSON.stringify({ version: opts.version, dsh, adapters }));
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
if (url.pathname === '/' || url.pathname === '/console') {
|
|
44
|
-
const html = await readFile(
|
|
45
|
-
fileURLToPath(new URL('../web/console.html', import.meta.url)),
|
|
46
|
-
'utf8',
|
|
47
|
-
).catch(() => '<h1>console.html not found</h1>');
|
|
48
|
-
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
49
|
-
res.end(html);
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
53
|
-
res.end('not found');
|
|
54
|
-
});
|
|
55
|
-
return {
|
|
56
|
-
server: http,
|
|
57
|
-
listen: (port: number) =>
|
|
58
|
-
new Promise<number>((resolve) =>
|
|
59
|
-
http.listen(port, '0.0.0.0', () => resolve((http.address() as { port: number }).port)),
|
|
60
|
-
),
|
|
61
|
-
close: () => new Promise<void>((resolve) => http.close(() => resolve())),
|
|
62
|
-
};
|
|
63
|
-
}
|
package/src/trajectory.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import type { ServerEvent, TrajectoryStep } from '@dsh-overdrive/sdk';
|
|
2
|
-
|
|
3
|
-
/** turn 级轨迹聚合:收集 trajectory.step,turn/end(idle)时产出 trajectory.summary 摘要卡片。 */
|
|
4
|
-
export class TrajectoryAggregator {
|
|
5
|
-
private readonly buffer = new Map<string, TrajectoryStep[]>();
|
|
6
|
-
private readonly summaries = new Map<string, string>();
|
|
7
|
-
|
|
8
|
-
onEvent(ev: ServerEvent, emit: (ev: ServerEvent) => void): void {
|
|
9
|
-
if (ev.type === 'agent.status' && ev.status === 'idle') {
|
|
10
|
-
const steps = this.buffer.get(ev.sessionId) ?? [];
|
|
11
|
-
this.buffer.delete(ev.sessionId);
|
|
12
|
-
if (steps.length > 0) {
|
|
13
|
-
this.summaries.set(ev.sessionId, formatTrajectorySummary(steps));
|
|
14
|
-
emit({ type: 'trajectory.summary', sessionId: ev.sessionId, ts: Date.now(), steps });
|
|
15
|
-
}
|
|
16
|
-
emit(ev);
|
|
17
|
-
return;
|
|
18
|
-
}
|
|
19
|
-
if (ev.type === 'agent.status' && ev.status === 'busy') {
|
|
20
|
-
this.buffer.set(ev.sessionId, []);
|
|
21
|
-
emit(ev);
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
if (ev.type === 'trajectory.step') {
|
|
25
|
-
const list = this.buffer.get(ev.sessionId);
|
|
26
|
-
if (list) list.push(ev.step);
|
|
27
|
-
else this.buffer.set(ev.sessionId, [ev.step]);
|
|
28
|
-
return; // 单步不实时推,等摘要(减少刷屏)
|
|
29
|
-
}
|
|
30
|
-
emit(ev);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** 最近一次 turn 的轨迹摘要文本(/trace 命令用),无则 null。 */
|
|
34
|
-
recentSummary(sessionId: string): string | null {
|
|
35
|
-
return this.summaries.get(sessionId) ?? null;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function formatTrajectorySummary(steps: TrajectoryStep[]): string {
|
|
40
|
-
const lines = steps.map((s) => {
|
|
41
|
-
const icon = s.kind === 'tool' ? '🛠️' : s.kind === 'subagent' ? '🤖' : '🧠';
|
|
42
|
-
return `${icon} ${s.label}`;
|
|
43
|
-
});
|
|
44
|
-
return `📋 轨迹(${lines.length} 步)\n${lines.join('\n')}`;
|
|
45
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { buildActionCard, buildReplyBody, buttonCallbackData, parseBotMessage, parseCardCallback } from '../src/adapters/dingtalk.js';
|
|
3
|
-
|
|
4
|
-
describe('parseBotMessage(RobotMessage → NormalizedMessage)', () => {
|
|
5
|
-
it('文本消息', () => {
|
|
6
|
-
const data = {
|
|
7
|
-
conversationId: 'cid1',
|
|
8
|
-
senderStaffId: 'u1',
|
|
9
|
-
msgtype: 'text',
|
|
10
|
-
text: { content: 'hello' },
|
|
11
|
-
sessionWebhook: 'https://hook.dingtalk.com/x',
|
|
12
|
-
};
|
|
13
|
-
const out = parseBotMessage(data);
|
|
14
|
-
expect(out).toMatchObject({ chatId: 'cid1', userId: 'u1', text: 'hello' });
|
|
15
|
-
});
|
|
16
|
-
it('非文本返回 null', () => {
|
|
17
|
-
expect(parseBotMessage({ conversationId: 'c', msgtype: 'picture' })).toBeNull();
|
|
18
|
-
});
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
describe('buildReplyBody(sessionWebhook 回发载荷)', () => {
|
|
22
|
-
it('文本消息体', () => {
|
|
23
|
-
expect(buildReplyBody('hi')).toEqual({ msgtype: 'text', text: { content: 'hi' } });
|
|
24
|
-
});
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
describe('buildActionCard(钉钉 actionCard)', () => {
|
|
28
|
-
it('生成带 cardCallbackData 的按钮', () => {
|
|
29
|
-
const card = buildActionCard('需要批准', [
|
|
30
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
31
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
32
|
-
]);
|
|
33
|
-
expect(card.msgtype).toBe('actionCard');
|
|
34
|
-
expect(card.actionCard.btns).toHaveLength(2);
|
|
35
|
-
expect(card.actionCard.btns[0].actionURL).toContain('cardCallbackData=');
|
|
36
|
-
expect(decodeURIComponent(card.actionCard.btns[0].actionURL.split('cardCallbackData=')[1])).toBe('{"action":"approve","reqId":"r1"}');
|
|
37
|
-
});
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
describe('parseCardCallback(TOPIC_CARD 回调载荷 → 按钮 id + 身份)', () => {
|
|
41
|
-
it('识别 cardCallbackData 字段', () => {
|
|
42
|
-
expect(parseCardCallback({ cardPrivateData: { cardCallbackData: '{"action":"approve","reqId":"r1"}' } })).toMatchObject({ buttonId: 'approve:r1' });
|
|
43
|
-
});
|
|
44
|
-
it('识别 params / cardActionData 字段与嵌套结构', () => {
|
|
45
|
-
expect(parseCardCallback({ cardPrivateData: { params: '{"action":"reject","reqId":"r9"}' } })).toMatchObject({ buttonId: 'reject:r9' });
|
|
46
|
-
expect(parseCardCallback({ a: { b: { cardActionData: '{"action":"approve","reqId":"x"}' } } })).toMatchObject({ buttonId: 'approve:x' });
|
|
47
|
-
});
|
|
48
|
-
it('带回会话与用户身份(用于白名单校验)', () => {
|
|
49
|
-
expect(parseCardCallback({
|
|
50
|
-
cardPrivateData: { cardCallbackData: '{"action":"approve","reqId":"r1"}', userId: 'u1' },
|
|
51
|
-
conversationId: 'cid1',
|
|
52
|
-
})).toEqual({ buttonId: 'approve:r1', chatId: 'cid1', userId: 'u1' });
|
|
53
|
-
});
|
|
54
|
-
it('非法载荷返回 null', () => {
|
|
55
|
-
expect(parseCardCallback(null)).toBeNull();
|
|
56
|
-
expect(parseCardCallback({ cardPrivateData: { cardCallbackData: 'not-json' } })).toBeNull();
|
|
57
|
-
expect(parseCardCallback({ cardPrivateData: { cardCallbackData: '{"action":"other","reqId":"r1"}' } })).toBeNull();
|
|
58
|
-
expect(parseCardCallback({ cardPrivateData: { cardCallbackData: '{"action":"approve"}' } })).toBeNull();
|
|
59
|
-
});
|
|
60
|
-
it('buttonCallbackData 与 parseCardCallback 往返一致', () => {
|
|
61
|
-
const data = buttonCallbackData({ id: 'reject:r7', label: 'x' });
|
|
62
|
-
expect(parseCardCallback({ cardPrivateData: { cardCallbackData: data } })).toMatchObject({ buttonId: 'reject:r7' });
|
|
63
|
-
});
|
|
64
|
-
});
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { discordAttachmentUrl, discordComponents, normalizeDiscordMessage } from '../src/adapters/discord.js';
|
|
3
|
-
|
|
4
|
-
describe('normalizeDiscordMessage', () => {
|
|
5
|
-
it('文本消息 → NormalizedMessage', () => {
|
|
6
|
-
const raw = { channelId: '111', author: { id: '222', bot: false }, content: 'hello' };
|
|
7
|
-
const out = normalizeDiscordMessage(raw);
|
|
8
|
-
expect(out).toMatchObject({ chatId: '111', userId: '222', text: 'hello' });
|
|
9
|
-
});
|
|
10
|
-
it('bot 消息返回 null', () => {
|
|
11
|
-
expect(normalizeDiscordMessage({ channelId: '1', author: { id: '2', bot: true }, content: 'x' })).toBeNull();
|
|
12
|
-
});
|
|
13
|
-
it('含附件 → media: { kind: "image", url }(纯函数 discordAttachmentUrl 取第一条)', () => {
|
|
14
|
-
const raw = {
|
|
15
|
-
channelId: '111',
|
|
16
|
-
author: { id: '222', bot: false },
|
|
17
|
-
content: '',
|
|
18
|
-
attachments: [{ url: 'https://cdn.discordapp.com/a.png', contentType: 'image/png' }],
|
|
19
|
-
};
|
|
20
|
-
expect(discordAttachmentUrl(raw)).toBe('https://cdn.discordapp.com/a.png');
|
|
21
|
-
expect(normalizeDiscordMessage(raw)).toMatchObject({
|
|
22
|
-
chatId: '111', userId: '222', text: '', media: { kind: 'image', url: 'https://cdn.discordapp.com/a.png' },
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
describe('discordComponents(按钮 action row 数据)', () => {
|
|
28
|
-
it('按钮 → discord components 结构', () => {
|
|
29
|
-
const comps = discordComponents([
|
|
30
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
31
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
32
|
-
]);
|
|
33
|
-
expect(comps).toEqual([{
|
|
34
|
-
type: 1,
|
|
35
|
-
components: [
|
|
36
|
-
{ type: 2, custom_id: 'approve:r1', label: '✅ 同意', style: 1 },
|
|
37
|
-
{ type: 2, custom_id: 'reject:r1', label: '🚫 拒绝', style: 1 },
|
|
38
|
-
],
|
|
39
|
-
}]);
|
|
40
|
-
});
|
|
41
|
-
});
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import {
|
|
3
|
-
buildApprovalCard, buildNumberedText, cardActionToButtonId, parseFeishuTextMessage,
|
|
4
|
-
} from '../src/adapters/feishu.js';
|
|
5
|
-
|
|
6
|
-
describe('parseFeishuTextMessage(im.message.receive_v1 载荷 → NormalizedMessage)', () => {
|
|
7
|
-
it('文本私聊消息', () => {
|
|
8
|
-
const data = {
|
|
9
|
-
event: {
|
|
10
|
-
message: { message_id: 'om_1', chat_id: 'oc_1', message_type: 'text', content: JSON.stringify({ text: 'hello' }) },
|
|
11
|
-
sender: { sender_id: { open_id: 'ou_1' } },
|
|
12
|
-
},
|
|
13
|
-
};
|
|
14
|
-
const out = parseFeishuTextMessage(data);
|
|
15
|
-
expect(out).toMatchObject({ chatId: 'oc_1', userId: 'ou_1', text: 'hello' });
|
|
16
|
-
});
|
|
17
|
-
it('非文本消息返回 null', () => {
|
|
18
|
-
const data = { event: { message: { message_type: 'image', content: '{}' }, sender: { sender_id: { open_id: 'ou_1' } } } };
|
|
19
|
-
expect(parseFeishuTextMessage(data)).toBeNull();
|
|
20
|
-
});
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
describe('buildNumberedText(审批编号回复)', () => {
|
|
24
|
-
it('生成 1/2 选项文本', () => {
|
|
25
|
-
const text = buildNumberedText('需要批准', [
|
|
26
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
27
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
28
|
-
]);
|
|
29
|
-
expect(text).toContain('1) ✅ 同意');
|
|
30
|
-
expect(text).toContain('2) 🚫 拒绝');
|
|
31
|
-
});
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
describe('buildApprovalCard(飞书原生交互卡片)', () => {
|
|
35
|
-
it('生成 interactive 卡片 JSON:header + 文本 + action 按钮', () => {
|
|
36
|
-
const content = buildApprovalCard('需要批准:执行危险操作', [
|
|
37
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
38
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
39
|
-
]);
|
|
40
|
-
const card = JSON.parse(content);
|
|
41
|
-
expect(card.config.wide_screen_mode).toBe(true);
|
|
42
|
-
expect(card.header.title.content).toContain('需要批准');
|
|
43
|
-
const actions = card.elements.find((e: { tag: string }) => e.tag === 'action').actions;
|
|
44
|
-
expect(actions).toHaveLength(2);
|
|
45
|
-
expect(actions[0]).toMatchObject({
|
|
46
|
-
tag: 'button',
|
|
47
|
-
type: 'primary', // approve 主按钮
|
|
48
|
-
value: { action: 'approve', reqId: 'r1' },
|
|
49
|
-
});
|
|
50
|
-
expect(actions[1].value).toEqual({ action: 'reject', reqId: 'r1' });
|
|
51
|
-
});
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
describe('cardActionToButtonId(卡片回调 → 按钮 id)', () => {
|
|
55
|
-
it('approve/reject 值还原为按钮 id', () => {
|
|
56
|
-
expect(cardActionToButtonId({ action: 'approve', reqId: 'r1' })).toBe('approve:r1');
|
|
57
|
-
expect(cardActionToButtonId({ action: 'reject', reqId: 'r9' })).toBe('reject:r9');
|
|
58
|
-
});
|
|
59
|
-
it('非法值返回 null', () => {
|
|
60
|
-
expect(cardActionToButtonId(null)).toBeNull();
|
|
61
|
-
expect(cardActionToButtonId({})).toBeNull();
|
|
62
|
-
expect(cardActionToButtonId({ action: 'other', reqId: 'r1' })).toBeNull();
|
|
63
|
-
expect(cardActionToButtonId({ action: 'approve' })).toBeNull();
|
|
64
|
-
expect(cardActionToButtonId('str')).toBeNull();
|
|
65
|
-
});
|
|
66
|
-
});
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { normalizeSlackMessage, slackBlocks, slackFileUrl } from '../src/adapters/slack.js';
|
|
3
|
-
|
|
4
|
-
describe('normalizeSlackMessage', () => {
|
|
5
|
-
it('文本消息 → NormalizedMessage', () => {
|
|
6
|
-
const raw = { channel: 'C123', user: 'U456', text: 'hello', subtype: undefined };
|
|
7
|
-
const out = normalizeSlackMessage(raw);
|
|
8
|
-
expect(out).toMatchObject({ chatId: 'C123', userId: 'U456', text: 'hello' });
|
|
9
|
-
});
|
|
10
|
-
it('bot 自己的消息(subtype=bot_message)返回 null', () => {
|
|
11
|
-
expect(normalizeSlackMessage({ channel: 'C1', user: 'U2', text: 'x', subtype: 'bot_message' })).toBeNull();
|
|
12
|
-
});
|
|
13
|
-
it('含文件 → media: { kind: "image", url }(纯函数 slackFileUrl 取 files[0].url_private)', () => {
|
|
14
|
-
const raw = {
|
|
15
|
-
channel: 'C1',
|
|
16
|
-
user: 'U2',
|
|
17
|
-
text: '',
|
|
18
|
-
files: [{ url_private: 'https://files.slack.com/files/x.png', mimetype: 'image/png' }],
|
|
19
|
-
};
|
|
20
|
-
expect(slackFileUrl(raw)).toBe('https://files.slack.com/files/x.png');
|
|
21
|
-
expect(normalizeSlackMessage(raw)).toMatchObject({
|
|
22
|
-
chatId: 'C1', userId: 'U2', text: '', media: { kind: 'image', url: 'https://files.slack.com/files/x.png' },
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
describe('slackBlocks', () => {
|
|
28
|
-
it('纯文本 → 一个 section', () => {
|
|
29
|
-
const blocks = slackBlocks('hi', []);
|
|
30
|
-
expect(blocks).toEqual([{ type: 'section', text: { type: 'mrkdwn', text: 'hi' } }]);
|
|
31
|
-
});
|
|
32
|
-
it('带按钮 → section + actions', () => {
|
|
33
|
-
const blocks = slackBlocks('需要批准', [
|
|
34
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
35
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
36
|
-
]);
|
|
37
|
-
expect(blocks[1]).toMatchObject({
|
|
38
|
-
type: 'actions',
|
|
39
|
-
elements: [
|
|
40
|
-
{ type: 'button', value: 'approve:r1', text: { type: 'plain_text', text: '✅ 同意' } },
|
|
41
|
-
{ type: 'button', value: 'reject:r1', text: { type: 'plain_text', text: '🚫 拒绝' } },
|
|
42
|
-
],
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
});
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { buttonRows, normalizeTelegramMessage, telegramImageUrl, telegramPhotoFileId } from '../src/adapters/telegram.js';
|
|
3
|
-
|
|
4
|
-
describe('normalizeTelegramMessage', () => {
|
|
5
|
-
it('文本消息 → NormalizedMessage(chatId/userId 字符串化)', () => {
|
|
6
|
-
const ctx = { chat: { id: 12345 }, from: { id: 678 }, message: { text: 'hello' } };
|
|
7
|
-
const out = normalizeTelegramMessage(ctx as never);
|
|
8
|
-
expect(out).toMatchObject({ chatId: '12345', userId: '678', text: 'hello' });
|
|
9
|
-
});
|
|
10
|
-
it('无文本返回 null', () => {
|
|
11
|
-
expect(normalizeTelegramMessage({ chat: { id: 1 }, from: { id: 2 }, message: { photo: [] } } as never)).toBeNull();
|
|
12
|
-
});
|
|
13
|
-
it('含 photo 的消息 → media: { kind: "image" },file_id → 下载 URL 模板(真实 getFile 在 adapter)', () => {
|
|
14
|
-
const ctx = {
|
|
15
|
-
chat: { id: 1 },
|
|
16
|
-
from: { id: 2 },
|
|
17
|
-
message: { photo: [{ file_id: 'small' }, { file_id: 'large' }] },
|
|
18
|
-
};
|
|
19
|
-
expect(normalizeTelegramMessage(ctx as never)).toMatchObject({
|
|
20
|
-
chatId: '1', userId: '2', text: '', media: { kind: 'image' },
|
|
21
|
-
});
|
|
22
|
-
expect(telegramPhotoFileId(ctx.message.photo)).toBe('large');
|
|
23
|
-
expect(telegramImageUrl('SECRET', 'photos/file_10.jpg')).toBe('https://api.telegram.org/file/botSECRET/photos/file_10.jpg');
|
|
24
|
-
});
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
describe('buttonRows(InlineKeyboard 数据)', () => {
|
|
28
|
-
it('按钮 → [label, id] 行', () => {
|
|
29
|
-
expect(buttonRows([
|
|
30
|
-
{ id: 'approve:r1', label: '✅ 同意' },
|
|
31
|
-
{ id: 'reject:r1', label: '🚫 拒绝' },
|
|
32
|
-
])).toEqual([
|
|
33
|
-
['✅ 同意', 'approve:r1'],
|
|
34
|
-
['🚫 拒绝', 'reject:r1'],
|
|
35
|
-
]);
|
|
36
|
-
});
|
|
37
|
-
});
|