opc-agent 1.0.0 → 1.1.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/CHANGELOG.md +7 -0
- package/README.md +232 -88
- package/README.zh-CN.md +334 -56
- package/dist/channels/discord.d.ts +44 -0
- package/dist/channels/discord.js +189 -0
- package/dist/channels/feishu.d.ts +47 -0
- package/dist/channels/feishu.js +221 -0
- package/dist/cli.js +1 -32
- package/dist/core/watch.d.ts +73 -0
- package/dist/core/watch.js +106 -0
- package/dist/i18n/index.js +60 -9
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -1
- package/docs/.vitepress/config.ts +13 -2
- package/docs/zh/api/cli.md +54 -0
- package/docs/zh/api/oad-schema.md +86 -2
- package/docs/zh/api/sdk.md +102 -0
- package/docs/zh/guide/concepts.md +90 -14
- package/docs/zh/guide/configuration.md +109 -13
- package/docs/zh/guide/deployment.md +79 -1
- package/docs/zh/guide/getting-started.md +41 -17
- package/docs/zh/guide/templates.md +79 -17
- package/docs/zh/guide/testing.md +75 -5
- package/docs/zh/index.md +13 -13
- package/package.json +1 -1
- package/src/channels/discord.ts +192 -0
- package/src/channels/feishu.ts +236 -0
- package/src/cli.ts +1 -35
- package/src/core/watch.ts +178 -0
- package/src/i18n/index.ts +60 -9
- package/src/index.ts +8 -0
- package/tests/i18n.test.ts +1 -1
package/README.zh-CN.md
CHANGED
|
@@ -1,88 +1,366 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<h1 align="center">🤖 OPC Agent</h1>
|
|
3
|
+
<p align="center"><strong>开放智能体框架 — 构建、测试、运行企业级 AI 智能体</strong></p>
|
|
4
|
+
<p align="center">
|
|
5
|
+
<a href="https://www.npmjs.com/package/opc-agent"><img src="https://img.shields.io/npm/v/opc-agent?color=blue" alt="npm 版本"></a>
|
|
6
|
+
<a href="https://github.com/Deepleaper/opc-agent/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="开源协议"></a>
|
|
7
|
+
<a href="https://github.com/Deepleaper/opc-agent/actions"><img src="https://img.shields.io/badge/tests-passing-brightgreen" alt="测试状态"></a>
|
|
8
|
+
<a href="https://www.npmjs.com/package/opc-agent"><img src="https://img.shields.io/npm/dm/opc-agent?color=orange" alt="下载量"></a>
|
|
9
|
+
</p>
|
|
10
|
+
<p align="center">
|
|
11
|
+
<a href="./README.md">English</a> · <strong>中文</strong>
|
|
12
|
+
</p>
|
|
13
|
+
</p>
|
|
2
14
|
|
|
3
|
-
|
|
15
|
+
---
|
|
4
16
|
|
|
5
|
-
|
|
6
|
-
[](LICENSE)
|
|
17
|
+
## 💡 这是什么?
|
|
7
18
|
|
|
8
|
-
|
|
19
|
+
OPC Agent 是一个 **TypeScript 优先的开放智能体框架**,由 [跃盟科技 (Deepleaper)](https://www.deepleaper.com) 开发维护。
|
|
9
20
|
|
|
10
|
-
|
|
11
|
-
- 📋 **OAD Schema** — 声明式 Agent 定义(YAML/JSON),内置校验
|
|
12
|
-
- 🧠 **记忆系统** — 短期 + 长期记忆,支持 DeepBrain 集成
|
|
13
|
-
- 🔌 **多通道** — Web、WebSocket、Telegram 通道
|
|
14
|
-
- 🛡️ **DTV 框架** — 数据、信任、价值追踪
|
|
15
|
-
- 🎯 **技能系统** — 可插拔技能 + 注册表 + 优先级执行
|
|
16
|
-
- 📦 **模板** — 客服、销售助手、知识库、代码审查
|
|
17
|
-
- 🚀 **CLI** — 交互式创建、开发模式、构建、测试、运行
|
|
21
|
+
一句话概括:**用一个 YAML 文件定义智能体,接入任意大语言模型,一键部署到多个渠道。**
|
|
18
22
|
|
|
19
|
-
|
|
23
|
+
不需要写一堆胶水代码,不需要自己搞 Prompt 管理,也不需要操心渠道对接。定义好 OAD 文件,`opc run` 就完事了。
|
|
24
|
+
|
|
25
|
+
## ⚡ 快速开始(30 秒上手)
|
|
20
26
|
|
|
21
27
|
```bash
|
|
22
|
-
#
|
|
28
|
+
# 1. 安装 CLI
|
|
23
29
|
npm install -g opc-agent
|
|
24
30
|
|
|
25
|
-
#
|
|
31
|
+
# 2. 创建项目(交互式,会让你选模板)
|
|
26
32
|
opc init my-agent
|
|
27
33
|
|
|
28
|
-
#
|
|
29
|
-
opc init my-bot --template sales-assistant
|
|
30
|
-
|
|
31
|
-
# 运行 Agent
|
|
34
|
+
# 3. 进入项目目录
|
|
32
35
|
cd my-agent
|
|
36
|
+
|
|
37
|
+
# 4. 跑起来
|
|
33
38
|
opc run
|
|
34
39
|
```
|
|
35
40
|
|
|
36
|
-
|
|
41
|
+
打开浏览器访问 `http://localhost:3000`,你的智能体已经在线了,自带一个好看的对话界面。
|
|
37
42
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
43
|
+
### 用模板快速创建
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
# 客服智能体
|
|
47
|
+
opc init my-service --template customer-service
|
|
48
|
+
|
|
49
|
+
# 销售助手
|
|
50
|
+
opc init my-sales --template sales-assistant
|
|
51
|
+
|
|
52
|
+
# 知识库问答
|
|
53
|
+
opc init my-kb --template knowledge-base
|
|
54
|
+
|
|
55
|
+
# 代码审查
|
|
56
|
+
opc init my-reviewer --template code-reviewer
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## ✨ 核心特性
|
|
60
|
+
|
|
61
|
+
### 🔌 多模型供应商 — 不绑定任何一家
|
|
62
|
+
|
|
63
|
+
```yaml
|
|
64
|
+
spec:
|
|
65
|
+
provider:
|
|
66
|
+
default: deepseek # 默认用 DeepSeek
|
|
67
|
+
allowed: [openai, deepseek, qwen, anthropic, ollama]
|
|
68
|
+
model: deepseek-chat
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
支持的供应商:
|
|
72
|
+
- **DeepSeek** — 性价比之王,国产首选
|
|
73
|
+
- **通义千问 (Qwen)** — 阿里出品,中文能力强
|
|
74
|
+
- **OpenAI** — GPT-4o、GPT-4o-mini
|
|
75
|
+
- **Anthropic** — Claude 系列
|
|
76
|
+
- **Ollama** — 本地部署,数据不出门
|
|
77
|
+
- 任何兼容 OpenAI 接口的服务
|
|
78
|
+
|
|
79
|
+
### 📡 多渠道部署 — 一套代码,到处运行
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
spec:
|
|
83
|
+
channels:
|
|
84
|
+
- type: web # 🌐 Web 对话界面
|
|
85
|
+
port: 3000
|
|
86
|
+
- type: telegram # ✈️ Telegram 机器人
|
|
87
|
+
- type: websocket # 🔗 实时 WebSocket
|
|
88
|
+
- type: slack # 💬 Slack 集成
|
|
89
|
+
- type: email # 📧 邮件渠道
|
|
90
|
+
- type: wechat # 💚 微信公众号
|
|
91
|
+
- type: feishu # 🔵 飞书
|
|
92
|
+
- type: voice # 🎙️ 语音(STT/TTS)
|
|
93
|
+
- type: webhook # 🔔 Webhook 回调
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 🧠 知识库(RAG)— 让智能体拥有你的专业知识
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { KnowledgeBase } from 'opc-agent';
|
|
100
|
+
|
|
101
|
+
const kb = new KnowledgeBase('./docs');
|
|
102
|
+
await kb.addFile('产品手册.pdf');
|
|
103
|
+
await kb.addFile('常见问题.md');
|
|
104
|
+
// 智能体回答时自动检索知识库,生成更准确的回答
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### 🎭 多智能体编排 — 分工协作,按需路由
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
import { Orchestrator } from 'opc-agent';
|
|
111
|
+
|
|
112
|
+
const orchestrator = new Orchestrator({
|
|
113
|
+
agents: [分诊智能体, 销售智能体, 客服智能体],
|
|
114
|
+
strategy: 'route-by-intent', // 按用户意图自动路由
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### 🧪 内置测试 — 发布前验证智能体行为
|
|
119
|
+
|
|
120
|
+
```yaml
|
|
121
|
+
spec:
|
|
122
|
+
testing:
|
|
123
|
+
cases:
|
|
124
|
+
- name: 问候测试
|
|
125
|
+
input: "你好"
|
|
126
|
+
expect:
|
|
127
|
+
contains: ["你好", "帮"]
|
|
128
|
+
maxLatencyMs: 5000
|
|
129
|
+
|
|
130
|
+
- name: 产品咨询
|
|
131
|
+
input: "你们的产品怎么收费?"
|
|
132
|
+
expect:
|
|
133
|
+
contains: ["价格", "套餐"]
|
|
134
|
+
notContains: ["error"]
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
opc test # 运行测试
|
|
139
|
+
opc test --watch # 监听模式,改了代码自动测
|
|
140
|
+
opc test --json # JSON 格式输出
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### 🔧 插件系统 — 按需扩展
|
|
144
|
+
|
|
145
|
+
```yaml
|
|
146
|
+
spec:
|
|
147
|
+
plugins:
|
|
148
|
+
- name: logging # 日志记录
|
|
149
|
+
- name: analytics # 使用分析
|
|
150
|
+
- name: rate-limit # 限流保护
|
|
151
|
+
config: { maxPerMinute: 60 }
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
支持自定义插件,提供完整的生命周期钩子:`onInit`、`onMessage`、`onResponse`、`onError`、`onShutdown`。
|
|
155
|
+
|
|
156
|
+
### 🔒 安全特性
|
|
157
|
+
|
|
158
|
+
- 输入消毒(防 XSS、注入攻击)
|
|
159
|
+
- API Key 轮换管理
|
|
160
|
+
- CORS 跨域配置
|
|
161
|
+
- 安全响应头(Helmet 风格)
|
|
162
|
+
- Content Security Policy
|
|
163
|
+
- 会话隔离的认证中间件
|
|
164
|
+
|
|
165
|
+
### 📊 监控与分析
|
|
44
166
|
|
|
45
|
-
|
|
167
|
+
- `/api/health` — 健康检查接口
|
|
168
|
+
- `/api/metrics` — Prometheus 兼容指标
|
|
169
|
+
- `/api/dashboard` — 实时仪表盘 UI
|
|
170
|
+
- 对话记录导出(JSON / Markdown / CSV)
|
|
46
171
|
|
|
47
|
-
|
|
172
|
+
## 🏗️ 架构设计
|
|
173
|
+
|
|
174
|
+
```
|
|
175
|
+
┌─────────────────────────────────────────────────┐
|
|
176
|
+
│ OAD (YAML 定义文件) │
|
|
177
|
+
│ 智能体的一切配置都在这里 │
|
|
178
|
+
├─────────────────────────────────────────────────┤
|
|
179
|
+
│ │
|
|
180
|
+
│ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
|
|
181
|
+
│ │ 渠道层 │ │ 插件层 │ │ 安全层 │ │
|
|
182
|
+
│ │ Web, TG, │ │ 日志, │ │ 消毒, CORS, │ │
|
|
183
|
+
│ │ WS, 微信 │ │ 分析 │ │ 认证 │ │
|
|
184
|
+
│ └────┬─────┘ └────┬─────┘ └──────┬───────┘ │
|
|
185
|
+
│ │ │ │ │
|
|
186
|
+
│ ┌────▼──────────────▼───────────────▼────────┐ │
|
|
187
|
+
│ │ 智能体运行时 (Agent Runtime) │ │
|
|
188
|
+
│ │ │ │
|
|
189
|
+
│ │ ┌─────────┐ ┌────────┐ ┌─────────────┐ │ │
|
|
190
|
+
│ │ │ 记忆 │ │ 技能 │ │ 知识库 │ │ │
|
|
191
|
+
│ │ │ 短期+ │ │ FAQ, │ │ RAG 检索 │ │ │
|
|
192
|
+
│ │ │ 长期 │ │ 转接 │ │ │ │ │
|
|
193
|
+
│ │ └─────────┘ └────────┘ └─────────────┘ │ │
|
|
194
|
+
│ └────────────────────┬───────────────────────┘ │
|
|
195
|
+
│ │ │
|
|
196
|
+
│ ┌────────────────────▼───────────────────────┐ │
|
|
197
|
+
│ │ 大语言模型供应商 │ │
|
|
198
|
+
│ │ DeepSeek · 通义千问 · OpenAI · Ollama │ │
|
|
199
|
+
│ └─────────────────────────────────────────────┘│
|
|
200
|
+
└─────────────────────────────────────────────────┘
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## 📋 全部模板(12 个)
|
|
204
|
+
|
|
205
|
+
| 模板 | 说明 | 典型场景 |
|
|
206
|
+
|------|------|---------|
|
|
207
|
+
| `customer-service` | 客服智能体 | FAQ 自动回答 + 转人工 |
|
|
208
|
+
| `sales-assistant` | 销售助手 | 产品问答 + 线索捕获 + 预约 |
|
|
209
|
+
| `knowledge-base` | 知识库问答 | 基于文档的 RAG 语义检索 |
|
|
210
|
+
| `code-reviewer` | 代码审查 | Bug 检测 + 代码风格检查 |
|
|
211
|
+
| `hr-recruiter` | HR 招聘助手 | 简历筛选 + 面试安排 |
|
|
212
|
+
| `project-manager` | 项目管理 | 任务跟踪 + 会议纪要 |
|
|
213
|
+
| `content-writer` | 内容创作 | 博客写作 + 社媒运营 + SEO |
|
|
214
|
+
| `legal-assistant` | 法务助手 | 合同审查 + 合规检查 |
|
|
215
|
+
| `financial-advisor` | 财务顾问 | 预算管理 + 支出分析 |
|
|
216
|
+
| `executive-assistant` | 行政助理 | 日程管理 + 邮件处理 |
|
|
217
|
+
| `data-analyst` | 数据分析师 | SQL 查询 + 数据可视化 |
|
|
218
|
+
| `teacher` | 教学助手 | 课程设计 + 出题 + 互动 |
|
|
219
|
+
|
|
220
|
+
## 🚀 部署指南
|
|
221
|
+
|
|
222
|
+
### 本地开发
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
opc dev # 热重载开发模式
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### Docker 部署
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
# 每个 opc init 项目都自带 Dockerfile 和 docker-compose.yml
|
|
232
|
+
docker compose up -d
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### 部署到 OpenClaw
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
opc deploy --target openclaw
|
|
239
|
+
opc deploy --target openclaw --install # 同时注册到配置
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### 部署到 Hermes 云
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
opc deploy --target hermes
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 环境变量
|
|
249
|
+
|
|
250
|
+
```bash
|
|
251
|
+
# .env
|
|
252
|
+
OPC_LLM_API_KEY=your-api-key
|
|
253
|
+
OPC_LLM_BASE_URL=https://api.deepseek.com/v1 # DeepSeek
|
|
254
|
+
OPC_LLM_MODEL=deepseek-chat
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
## 📖 CLI 命令参考
|
|
258
|
+
|
|
259
|
+
| 命令 | 说明 |
|
|
48
260
|
|------|------|
|
|
49
|
-
| `opc init [name]` |
|
|
50
|
-
| `opc create <name>` |
|
|
51
|
-
| `opc
|
|
52
|
-
| `opc
|
|
53
|
-
| `opc
|
|
54
|
-
| `opc
|
|
55
|
-
| `opc
|
|
56
|
-
| `opc
|
|
57
|
-
| `opc
|
|
261
|
+
| `opc init [name]` | 创建新智能体项目(交互式) |
|
|
262
|
+
| `opc create <name>` | 从模板快速创建 |
|
|
263
|
+
| `opc run` | 启动智能体服务 |
|
|
264
|
+
| `opc dev` | 开发模式(热重载) |
|
|
265
|
+
| `opc chat` | 命令行交互对话 |
|
|
266
|
+
| `opc test` | 运行测试用例 |
|
|
267
|
+
| `opc build` | 校验 OAD 配置 |
|
|
268
|
+
| `opc info` | 查看智能体信息 |
|
|
269
|
+
| `opc analytics` | 查看使用分析 |
|
|
270
|
+
| `opc deploy` | 部署智能体 |
|
|
271
|
+
| `opc publish` | 发布到市场 |
|
|
272
|
+
| `opc kb add <file>` | 添加知识库文件 |
|
|
273
|
+
| `opc kb search <query>` | 搜索知识库 |
|
|
274
|
+
| `opc stats` | 查看运行时统计 |
|
|
58
275
|
|
|
59
|
-
##
|
|
276
|
+
## 🔗 SDK 参考
|
|
277
|
+
|
|
278
|
+
```typescript
|
|
279
|
+
import { AgentRuntime, KnowledgeBase, Orchestrator } from 'opc-agent';
|
|
280
|
+
|
|
281
|
+
// 创建并启动智能体
|
|
282
|
+
const runtime = new AgentRuntime();
|
|
283
|
+
await runtime.loadConfig('oad.yaml');
|
|
284
|
+
const agent = await runtime.initialize();
|
|
285
|
+
await runtime.start();
|
|
286
|
+
|
|
287
|
+
// 使用知识库
|
|
288
|
+
const kb = new KnowledgeBase('./docs');
|
|
289
|
+
await kb.addFile('handbook.pdf');
|
|
290
|
+
|
|
291
|
+
// 多智能体编排
|
|
292
|
+
const orch = new Orchestrator({
|
|
293
|
+
agents: [agentA, agentB],
|
|
294
|
+
strategy: 'route-by-intent',
|
|
295
|
+
});
|
|
296
|
+
```
|
|
60
297
|
|
|
61
|
-
|
|
62
|
-
简单键值存储,重启后数据丢失。
|
|
298
|
+
## 🔑 OAD 配置文件说明
|
|
63
299
|
|
|
64
|
-
|
|
65
|
-
语义搜索历史对话和知识。安装 `deepbrain` 包后配置:
|
|
300
|
+
OAD(Open Agent Definition)是智能体的声明式定义格式:
|
|
66
301
|
|
|
67
302
|
```yaml
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
303
|
+
apiVersion: opc/v1 # API 版本
|
|
304
|
+
kind: Agent # 资源类型
|
|
305
|
+
|
|
306
|
+
metadata:
|
|
307
|
+
name: my-agent # 智能体名称
|
|
308
|
+
version: 1.0.0 # 版本号
|
|
309
|
+
description: 我的智能体 # 描述
|
|
310
|
+
|
|
311
|
+
spec:
|
|
312
|
+
provider:
|
|
313
|
+
default: deepseek # 默认供应商
|
|
314
|
+
allowed: [deepseek, openai, qwen]
|
|
315
|
+
model: deepseek-chat # 模型
|
|
316
|
+
systemPrompt: | # 系统提示词
|
|
317
|
+
你是一个专业的客服助手...
|
|
318
|
+
|
|
319
|
+
skills: [] # 技能列表
|
|
320
|
+
channels: # 渠道配置
|
|
321
|
+
- type: web
|
|
322
|
+
port: 3000
|
|
323
|
+
|
|
324
|
+
memory:
|
|
325
|
+
shortTerm: true # 短期记忆(对话上下文)
|
|
326
|
+
longTerm: false # 长期记忆(跨会话)
|
|
327
|
+
|
|
328
|
+
rateLimits: # 限流
|
|
329
|
+
perUser:
|
|
330
|
+
maxRequests: 60
|
|
331
|
+
windowMs: 60000
|
|
332
|
+
|
|
333
|
+
cache: # 缓存(降低 API 开销)
|
|
334
|
+
enabled: true
|
|
335
|
+
ttlMs: 3600000
|
|
72
336
|
```
|
|
73
337
|
|
|
74
|
-
|
|
338
|
+
## 🤝 贡献指南
|
|
339
|
+
|
|
340
|
+
我们欢迎所有形式的贡献!
|
|
341
|
+
|
|
342
|
+
1. Fork 本仓库
|
|
343
|
+
2. 创建功能分支:`git checkout -b feat/awesome-feature`
|
|
344
|
+
3. 编写代码和测试
|
|
345
|
+
4. 确保测试通过:`npm test`
|
|
346
|
+
5. 提交 Pull Request
|
|
75
347
|
|
|
76
|
-
|
|
348
|
+
### 本地开发环境
|
|
77
349
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
-
|
|
350
|
+
```bash
|
|
351
|
+
git clone https://github.com/Deepleaper/opc-agent.git
|
|
352
|
+
cd opc-agent
|
|
353
|
+
npm install
|
|
354
|
+
npm run build
|
|
355
|
+
npm test
|
|
356
|
+
```
|
|
81
357
|
|
|
82
|
-
##
|
|
358
|
+
## 📄 开源协议
|
|
83
359
|
|
|
84
|
-
|
|
360
|
+
[Apache License 2.0](LICENSE) — 商用和开源项目均可自由使用。
|
|
85
361
|
|
|
86
|
-
|
|
362
|
+
---
|
|
87
363
|
|
|
88
|
-
|
|
364
|
+
<p align="center">
|
|
365
|
+
由 <a href="https://www.deepleaper.com">跃盟科技 (Deepleaper)</a> 用 ❤️ 打造
|
|
366
|
+
</p>
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { BaseChannel } from './index';
|
|
2
|
+
/**
|
|
3
|
+
* Discord Channel — v1.1.0
|
|
4
|
+
*
|
|
5
|
+
* Supports:
|
|
6
|
+
* - Discord Bot via Gateway (WebSocket) or HTTP interactions
|
|
7
|
+
* - Slash commands, message content intent
|
|
8
|
+
* - Thread-based conversations
|
|
9
|
+
* - Reactions, embeds
|
|
10
|
+
*
|
|
11
|
+
* Env vars:
|
|
12
|
+
* DISCORD_BOT_TOKEN — bot token
|
|
13
|
+
* DISCORD_APPLICATION_ID — application ID for slash commands
|
|
14
|
+
*/
|
|
15
|
+
export interface DiscordChannelConfig {
|
|
16
|
+
/** Bot token */
|
|
17
|
+
botToken?: string;
|
|
18
|
+
/** Application ID */
|
|
19
|
+
applicationId?: string;
|
|
20
|
+
/** Guild IDs to register slash commands (empty = global) */
|
|
21
|
+
guildIds?: string[];
|
|
22
|
+
/** Whether to use threads for conversations */
|
|
23
|
+
useThreads?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export declare class DiscordChannel extends BaseChannel {
|
|
26
|
+
readonly type = "discord";
|
|
27
|
+
private config;
|
|
28
|
+
private ws;
|
|
29
|
+
private heartbeatInterval;
|
|
30
|
+
private sequenceNumber;
|
|
31
|
+
private sessionId;
|
|
32
|
+
private resumeUrl;
|
|
33
|
+
constructor(config?: DiscordChannelConfig);
|
|
34
|
+
start(): Promise<void>;
|
|
35
|
+
stop(): Promise<void>;
|
|
36
|
+
private identify;
|
|
37
|
+
private startHeartbeat;
|
|
38
|
+
private stopHeartbeat;
|
|
39
|
+
private sendHeartbeat;
|
|
40
|
+
private handleMessage;
|
|
41
|
+
sendMessage(channelId: string, content: string): Promise<void>;
|
|
42
|
+
private splitMessage;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=discord.d.ts.map
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.DiscordChannel = void 0;
|
|
37
|
+
const index_1 = require("./index");
|
|
38
|
+
class DiscordChannel extends index_1.BaseChannel {
|
|
39
|
+
type = 'discord';
|
|
40
|
+
config;
|
|
41
|
+
ws = null;
|
|
42
|
+
heartbeatInterval = null;
|
|
43
|
+
sequenceNumber = null;
|
|
44
|
+
sessionId = null;
|
|
45
|
+
resumeUrl = null;
|
|
46
|
+
constructor(config = {}) {
|
|
47
|
+
super();
|
|
48
|
+
this.config = {
|
|
49
|
+
botToken: config.botToken ?? process.env.DISCORD_BOT_TOKEN ?? '',
|
|
50
|
+
applicationId: config.applicationId ?? process.env.DISCORD_APPLICATION_ID ?? '',
|
|
51
|
+
guildIds: config.guildIds ?? [],
|
|
52
|
+
useThreads: config.useThreads ?? true,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async start() {
|
|
56
|
+
if (!this.config.botToken) {
|
|
57
|
+
console.warn('[DiscordChannel] No bot token. Set DISCORD_BOT_TOKEN.');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
// Get gateway URL
|
|
61
|
+
const gatewayResp = await fetch('https://discord.com/api/v10/gateway/bot', {
|
|
62
|
+
headers: { Authorization: `Bot ${this.config.botToken}` },
|
|
63
|
+
});
|
|
64
|
+
const gatewayData = await gatewayResp.json();
|
|
65
|
+
const wsUrl = `${gatewayData.url}?v=10&encoding=json`;
|
|
66
|
+
const { WebSocket } = await Promise.resolve().then(() => __importStar(require('ws')));
|
|
67
|
+
this.ws = new WebSocket(wsUrl);
|
|
68
|
+
this.ws.on('message', async (data) => {
|
|
69
|
+
const payload = JSON.parse(data.toString());
|
|
70
|
+
this.sequenceNumber = payload.s ?? this.sequenceNumber;
|
|
71
|
+
switch (payload.op) {
|
|
72
|
+
case 10: // Hello
|
|
73
|
+
this.startHeartbeat(payload.d.heartbeat_interval);
|
|
74
|
+
this.identify();
|
|
75
|
+
break;
|
|
76
|
+
case 11: // Heartbeat ACK
|
|
77
|
+
break;
|
|
78
|
+
case 0: // Dispatch
|
|
79
|
+
if (payload.t === 'READY') {
|
|
80
|
+
this.sessionId = payload.d.session_id;
|
|
81
|
+
this.resumeUrl = payload.d.resume_gateway_url;
|
|
82
|
+
console.log(`[DiscordChannel] Connected as ${payload.d.user.username}`);
|
|
83
|
+
}
|
|
84
|
+
else if (payload.t === 'MESSAGE_CREATE') {
|
|
85
|
+
await this.handleMessage(payload.d);
|
|
86
|
+
}
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
this.ws.on('close', (code) => {
|
|
91
|
+
console.log(`[DiscordChannel] WebSocket closed: ${code}`);
|
|
92
|
+
this.stopHeartbeat();
|
|
93
|
+
// Auto-reconnect after 5s for resumable codes
|
|
94
|
+
if (code !== 4004 && code !== 4014) {
|
|
95
|
+
setTimeout(() => this.start(), 5000);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
this.ws.on('error', (err) => {
|
|
99
|
+
console.error('[DiscordChannel] WebSocket error:', err.message);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
async stop() {
|
|
103
|
+
this.stopHeartbeat();
|
|
104
|
+
if (this.ws) {
|
|
105
|
+
this.ws.close(1000);
|
|
106
|
+
this.ws = null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
identify() {
|
|
110
|
+
this.ws?.send(JSON.stringify({
|
|
111
|
+
op: 2,
|
|
112
|
+
d: {
|
|
113
|
+
token: this.config.botToken,
|
|
114
|
+
intents: (1 << 9) | (1 << 15), // GUILD_MESSAGES | MESSAGE_CONTENT
|
|
115
|
+
properties: {
|
|
116
|
+
os: process.platform,
|
|
117
|
+
browser: 'opc-agent',
|
|
118
|
+
device: 'opc-agent',
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
startHeartbeat(intervalMs) {
|
|
124
|
+
this.stopHeartbeat();
|
|
125
|
+
// Send first heartbeat with jitter
|
|
126
|
+
setTimeout(() => {
|
|
127
|
+
this.sendHeartbeat();
|
|
128
|
+
this.heartbeatInterval = setInterval(() => this.sendHeartbeat(), intervalMs);
|
|
129
|
+
}, intervalMs * Math.random());
|
|
130
|
+
}
|
|
131
|
+
stopHeartbeat() {
|
|
132
|
+
if (this.heartbeatInterval) {
|
|
133
|
+
clearInterval(this.heartbeatInterval);
|
|
134
|
+
this.heartbeatInterval = null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
sendHeartbeat() {
|
|
138
|
+
this.ws?.send(JSON.stringify({ op: 1, d: this.sequenceNumber }));
|
|
139
|
+
}
|
|
140
|
+
async handleMessage(d) {
|
|
141
|
+
// Ignore bot messages
|
|
142
|
+
const author = d.author;
|
|
143
|
+
if (author?.bot)
|
|
144
|
+
return;
|
|
145
|
+
if (!d.content || !this.handler)
|
|
146
|
+
return;
|
|
147
|
+
const msg = {
|
|
148
|
+
id: `discord_${d.id}`,
|
|
149
|
+
role: 'user',
|
|
150
|
+
content: d.content,
|
|
151
|
+
timestamp: new Date(d.timestamp).getTime(),
|
|
152
|
+
metadata: {
|
|
153
|
+
sessionId: `discord_${d.channel_id}`,
|
|
154
|
+
chatId: d.channel_id,
|
|
155
|
+
userId: author.id,
|
|
156
|
+
platform: 'discord',
|
|
157
|
+
guildId: d.guild_id,
|
|
158
|
+
threadId: d.thread?.toString(),
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
const response = await this.handler(msg);
|
|
162
|
+
await this.sendMessage(d.channel_id, response.content);
|
|
163
|
+
}
|
|
164
|
+
async sendMessage(channelId, content) {
|
|
165
|
+
// Discord max message length is 2000
|
|
166
|
+
const chunks = this.splitMessage(content, 2000);
|
|
167
|
+
for (const chunk of chunks) {
|
|
168
|
+
await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
|
|
169
|
+
method: 'POST',
|
|
170
|
+
headers: {
|
|
171
|
+
'Content-Type': 'application/json',
|
|
172
|
+
Authorization: `Bot ${this.config.botToken}`,
|
|
173
|
+
},
|
|
174
|
+
body: JSON.stringify({ content: chunk }),
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
splitMessage(text, maxLen) {
|
|
179
|
+
if (text.length <= maxLen)
|
|
180
|
+
return [text];
|
|
181
|
+
const parts = [];
|
|
182
|
+
for (let i = 0; i < text.length; i += maxLen) {
|
|
183
|
+
parts.push(text.slice(i, i + maxLen));
|
|
184
|
+
}
|
|
185
|
+
return parts;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
exports.DiscordChannel = DiscordChannel;
|
|
189
|
+
//# sourceMappingURL=discord.js.map
|