@dsh-overdrive/gateway 0.3.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/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 -98
- package/src/config.ts +0 -104
- package/src/feed.ts +0 -190
- package/src/index.ts +0 -510
- package/src/memory.ts +0 -176
- package/src/mention.ts +0 -51
- package/src/pending-buttons.ts +0 -65
- package/src/session.ts +0 -23
- package/src/setup.ts +0 -252
- package/src/status.ts +0 -63
- package/src/text.ts +0 -32
- 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 -53
- package/test/config.test.ts +0 -30
- package/test/feed.test.ts +0 -111
- package/test/memory.test.ts +0 -79
- package/test/mention.test.ts +0 -54
- package/test/multi.test.ts +0 -284
- package/test/outbound.test.ts +0 -29
- package/test/pending-buttons.test.ts +0 -100
- package/test/session.test.ts +0 -26
- package/test/status.test.ts +0 -41
- package/test/streaming.test.ts +0 -162
- package/test/text.test.ts +0 -20
- package/test/trajectory.test.ts +0 -58
- package/tsconfig.json +0 -5
package/src/mention.ts
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
// 群聊响应策略(对齐竞品 dsh-im 的「私聊直接响应、群聊被提及/回复才响应」)。
|
|
2
|
-
// 纯函数,平台判定基于渠道 ID 特征与提及模式;无法判定的平台默认始终响应。
|
|
3
|
-
|
|
4
|
-
import type { NormalizedMessage } from './adapter.js';
|
|
5
|
-
|
|
6
|
-
/** 纯函数:该渠道 ID 是否为群聊/频道(vs 私聊)。平台特征: */
|
|
7
|
-
export function isGroupChat(adapterId: string, chatId: string): boolean {
|
|
8
|
-
switch (adapterId) {
|
|
9
|
-
case 'telegram':
|
|
10
|
-
// 群/超级群为负 ID(-100 前缀的超群,- 前缀的普通群)
|
|
11
|
-
return chatId.startsWith('-');
|
|
12
|
-
case 'whatsapp':
|
|
13
|
-
return chatId.endsWith('@g.us');
|
|
14
|
-
case 'slack':
|
|
15
|
-
// Slack 私聊 DM 以 D 开头,公共频道/群以 C/G 开头
|
|
16
|
-
return !chatId.startsWith('D');
|
|
17
|
-
default:
|
|
18
|
-
// discord / feishu / dingtalk / wecom / wechat / cli:无法从 ID 可靠区分 → 视为私聊(始终响应)
|
|
19
|
-
return false;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** 纯函数:消息文本是否提及了机器人(@<identity> 或 <@identity> 平台格式)。 */
|
|
24
|
-
export function isMentioned(adapterId: string, text: string, botIdentity: string): boolean {
|
|
25
|
-
if (!botIdentity) return false;
|
|
26
|
-
switch (adapterId) {
|
|
27
|
-
case 'telegram':
|
|
28
|
-
return text.includes(`@${botIdentity}`);
|
|
29
|
-
case 'whatsapp':
|
|
30
|
-
return text.includes(`@${botIdentity}`);
|
|
31
|
-
case 'discord':
|
|
32
|
-
case 'slack':
|
|
33
|
-
return text.includes(`<@${botIdentity}>`);
|
|
34
|
-
default:
|
|
35
|
-
return true; // 无法检测提及的平台 → 视为已提及(始终响应)
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface MentionPolicy {
|
|
40
|
-
/** 群聊中要求被提及/回复才响应;私聊始终响应。 */
|
|
41
|
-
requireMention: boolean;
|
|
42
|
-
/** 机器人身份(telegram @用户名 / discord·slack 用户ID / whatsapp 号码)。 */
|
|
43
|
-
botIdentity: string;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** 纯函数:是否应响应该消息。 */
|
|
47
|
-
export function shouldRespond(adapterId: string, msg: NormalizedMessage, policy: MentionPolicy): boolean {
|
|
48
|
-
if (!policy.requireMention) return true;
|
|
49
|
-
if (!isGroupChat(adapterId, msg.chatId)) return true; // 私聊始终响应
|
|
50
|
-
return isMentioned(adapterId, msg.text, policy.botIdentity);
|
|
51
|
-
}
|
package/src/pending-buttons.ts
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import type { OutboundButton } from './adapter.js';
|
|
2
|
-
|
|
3
|
-
export const PENDING_BUTTONS_TTL_MS = 5 * 60_000;
|
|
4
|
-
|
|
5
|
-
interface PendingButtonEntry {
|
|
6
|
-
buttons: OutboundButton[];
|
|
7
|
-
expiresAt: number;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* 编号回复兜底的按钮暂存(带 TTL)。
|
|
12
|
-
*
|
|
13
|
-
* 审批/危险操作按钮发出后,用户在聊天里回复数字("1"/"2"…)选择;
|
|
14
|
-
* 若按钮长期不消费,后续的普通数字消息会被误判成按钮回复。
|
|
15
|
-
* 本类在 TTL(默认 5 分钟)后自动失效,杜绝"过期按钮吞消息"。
|
|
16
|
-
*/
|
|
17
|
-
export class PendingButtons {
|
|
18
|
-
private readonly map = new Map<string, PendingButtonEntry>();
|
|
19
|
-
|
|
20
|
-
constructor(private readonly ttlMs: number = PENDING_BUTTONS_TTL_MS) {}
|
|
21
|
-
|
|
22
|
-
set(chatId: string, buttons: OutboundButton[]): void {
|
|
23
|
-
this.map.set(chatId, { buttons, expiresAt: Date.now() + this.ttlMs });
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* 回复解析(对齐竞品的文字审批):数字编号("1"/"2"…)或关键词
|
|
28
|
-
* (批准/同意/yes/ok/确认 → approve 按钮;拒绝/不同意/no/取消 → reject 按钮)。
|
|
29
|
-
* 命中即消费;无 pending / 已过期 / 不匹配返回 undefined。
|
|
30
|
-
*/
|
|
31
|
-
match(chatId: string, text: string): OutboundButton | undefined {
|
|
32
|
-
const entry = this.map.get(chatId);
|
|
33
|
-
if (!entry) return undefined;
|
|
34
|
-
if (entry.expiresAt < Date.now()) {
|
|
35
|
-
this.map.delete(chatId);
|
|
36
|
-
return undefined;
|
|
37
|
-
}
|
|
38
|
-
const trimmed = text.trim().toLowerCase();
|
|
39
|
-
// 数字回复
|
|
40
|
-
const n = Number(trimmed);
|
|
41
|
-
if (Number.isInteger(n) && n >= 1 && n <= entry.buttons.length) {
|
|
42
|
-
const button = entry.buttons[n - 1];
|
|
43
|
-
if (button) this.map.delete(chatId);
|
|
44
|
-
return button;
|
|
45
|
-
}
|
|
46
|
-
// 文字审批关键词(竞品 dsh-im 同款:回复「批准/拒绝」即可)
|
|
47
|
-
const approveWords = ['批准', '同意', 'yes', 'ok', '确认', 'approve'];
|
|
48
|
-
const rejectWords = ['拒绝', '不同意', 'no', '取消', 'reject'];
|
|
49
|
-
const wantsApprove = approveWords.some((w) => trimmed === w || trimmed.startsWith(`${w} `));
|
|
50
|
-
const wantsReject = rejectWords.some((w) => trimmed === w || trimmed.startsWith(`${w} `));
|
|
51
|
-
if (wantsApprove || wantsReject) {
|
|
52
|
-
const button = entry.buttons.find((b) =>
|
|
53
|
-
wantsApprove ? b.id.startsWith('approve:') : b.id.startsWith('reject:'),
|
|
54
|
-
);
|
|
55
|
-
if (button) this.map.delete(chatId);
|
|
56
|
-
return button;
|
|
57
|
-
}
|
|
58
|
-
return undefined;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** 消费原生按钮点击(如 WhatsApp 原生交互按钮):删除该 chat 的 pending。 */
|
|
62
|
-
consume(chatId: string): void {
|
|
63
|
-
this.map.delete(chatId);
|
|
64
|
-
}
|
|
65
|
-
}
|
package/src/session.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { sessionKey } from '@dsh-overdrive/sdk';
|
|
2
|
-
|
|
3
|
-
export function buildSessionKey(
|
|
4
|
-
adapterId: string,
|
|
5
|
-
msg: { chatId: string; userId: string },
|
|
6
|
-
): string {
|
|
7
|
-
return sessionKey(adapterId, msg.chatId, msg.userId);
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* 白名单:默认 fail-closed —— 只有显式配置了条目才放行;
|
|
12
|
-
* 开发环境可用 ALLOW_ALL=1 显式放行所有(比空列表隐式放行安全得多)。
|
|
13
|
-
*/
|
|
14
|
-
export class Allowlist {
|
|
15
|
-
constructor(
|
|
16
|
-
private readonly entries: string[],
|
|
17
|
-
private readonly allowAll = false,
|
|
18
|
-
) {}
|
|
19
|
-
|
|
20
|
-
allows(key: string): boolean {
|
|
21
|
-
return this.allowAll || (this.entries.length > 0 && this.entries.includes(key));
|
|
22
|
-
}
|
|
23
|
-
}
|
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/text.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
// 长文本工具:按渠道可读性分片(对齐竞品的长回复分段能力)。
|
|
2
|
-
|
|
3
|
-
const DEFAULT_CHUNK_LIMIT = 1500;
|
|
4
|
-
|
|
5
|
-
/** 纯函数:长文本按 limit 分片,优先在换行/句号/问号/感叹号处断行;超过 1 段时带(i/n)序号。 */
|
|
6
|
-
export function chunkLongText(text: string, limit = DEFAULT_CHUNK_LIMIT): string[] {
|
|
7
|
-
if (!text) return [text];
|
|
8
|
-
if (text.length <= limit) return [text];
|
|
9
|
-
|
|
10
|
-
const raw: string[] = [];
|
|
11
|
-
let rest = text;
|
|
12
|
-
while (rest.length > limit) {
|
|
13
|
-
const slice = rest.slice(0, limit);
|
|
14
|
-
const breakAt = Math.max(
|
|
15
|
-
slice.lastIndexOf('\n'),
|
|
16
|
-
slice.lastIndexOf('。'),
|
|
17
|
-
slice.lastIndexOf('!'),
|
|
18
|
-
slice.lastIndexOf('?'),
|
|
19
|
-
slice.lastIndexOf('.'),
|
|
20
|
-
slice.lastIndexOf('!'),
|
|
21
|
-
slice.lastIndexOf('?'),
|
|
22
|
-
slice.lastIndexOf(';'),
|
|
23
|
-
);
|
|
24
|
-
const cut = breakAt >= limit * 0.6 ? breakAt + 1 : limit;
|
|
25
|
-
raw.push(rest.slice(0, cut));
|
|
26
|
-
rest = rest.slice(cut);
|
|
27
|
-
}
|
|
28
|
-
if (rest) raw.push(rest);
|
|
29
|
-
|
|
30
|
-
if (raw.length <= 1) return raw;
|
|
31
|
-
return raw.map((chunk, i) => `${chunk}\n(${i + 1}/${raw.length})`);
|
|
32
|
-
}
|
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
|
-
});
|