@dcrays/dcgchat-test 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # OpenClaw DCG Chat 插件
2
+
3
+ 连接 OpenClaw 与 DCG Chat 产品的通道插件。
4
+
5
+ ## 架构
6
+
7
+ ```
8
+ ┌──────────┐ WebSocket ┌──────────────┐ WebSocket ┌─────────────────────┐
9
+ │ Web 前端 │ ←───────────────→ │ 公司后端服务 │ ←───────────────→ │ OpenClaw(工作电脑) │
10
+ └──────────┘ └──────────────┘ (OpenClaw 主动连) └─────────────────────┘
11
+ ```
12
+
13
+ - OpenClaw 插件**主动连接**后端的 WebSocket 服务(不需要公网 IP)
14
+ - 后端收到用户消息后转发给 OpenClaw,OpenClaw 回复后发回后端
15
+
16
+ ## 快速开始
17
+
18
+ ### 1. 安装插件
19
+
20
+ ```bash
21
+ pnpm openclaw plugins install -l /path/to/openclaw-dcgchat
22
+ ```
23
+
24
+ ### 2. 配置
25
+
26
+ ```bash
27
+ openclaw config set channels.dcgchat.enabled true
28
+ openclaw config set channels.dcgchat.wsUrl "ws://your-backend:8080/openclaw/ws"
29
+ ```
30
+
31
+ ### 3. 启动
32
+
33
+ ```bash
34
+ pnpm openclaw gateway
35
+ ```
36
+
37
+ ## 消息协议(MVP)
38
+
39
+ ### 下行:后端 → OpenClaw(用户消息)
40
+
41
+ ```json
42
+ { "type": "message", "userId": "user_001", "text": "你好" }
43
+ ```
44
+
45
+ ### 上行:OpenClaw → 后端(Agent 回复)
46
+
47
+ ```json
48
+ { "type": "reply", "userId": "user_001", "text": "你好!有什么可以帮你的?" }
49
+ ```
50
+
51
+ ## 配置项
52
+
53
+ | 配置键 | 类型 | 说明 |
54
+ |--------|------|------|
55
+ | `channels.dcgchat.enabled` | boolean | 是否启用 |
56
+ | `channels.dcgchat.wsUrl` | string | 后端 WebSocket 地址 |
57
+
58
+ ## 开发
59
+
60
+ ```bash
61
+ # 安装依赖
62
+ pnpm install
63
+
64
+ # 类型检查
65
+ pnpm typecheck
66
+ ```
67
+
68
+ ## 文件结构
69
+
70
+ - `index.ts` - 插件入口
71
+ - `src/channel.ts` - ChannelPlugin 定义
72
+ - `src/runtime.ts` - 插件 runtime
73
+ - `src/types.ts` - 类型定义
74
+ - `src/monitor.ts` - WebSocket 连接与断线重连
75
+ - `src/bot.ts` - 消息处理与 Agent 调用
76
+
77
+ ## 后续迭代
78
+
79
+ - [ ] Token 认证
80
+ - [ ] 流式输出
81
+ - [ ] Typing 指示
82
+ - [ ] messageId 去重
83
+ - [ ] 错误消息类型
package/index.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
3
+ import { dcgchatPlugin } from "./src/channel.js";
4
+ import { setDcgchatRuntime, setWorkspaceDir } from "./src/runtime.js";
5
+ import { monitoringToolMessage } from "./src/tool.js";
6
+
7
+ const plugin = {
8
+ id: "dcgchat",
9
+ name: "DCG Chat",
10
+ description: "连接 OpenClaw 与 DCG Chat 产品(WebSocket)",
11
+ configSchema: emptyPluginConfigSchema(),
12
+ register(api: OpenClawPluginApi) {
13
+ setDcgchatRuntime(api.runtime);
14
+ monitoringToolMessage(api);
15
+ api.registerChannel({ plugin: dcgchatPlugin });
16
+ api.registerTool((ctx) => {
17
+ const workspaceDir = ctx.workspaceDir;
18
+ setWorkspaceDir(workspaceDir);
19
+ return null;
20
+ });
21
+ },
22
+ };
23
+
24
+ export default plugin;
@@ -0,0 +1,9 @@
1
+ {
2
+ "id": "dcgchat",
3
+ "channels": ["dcgchat"],
4
+ "configSchema": {
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "properties": {}
8
+ }
9
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@dcrays/dcgchat-test",
3
+ "version": "0.1.9",
4
+ "type": "module",
5
+ "description": "OpenClaw channel plugin for DCG Chat (WebSocket)",
6
+ "main": "index.ts",
7
+ "license": "MIT",
8
+ "files": [
9
+ "index.ts",
10
+ "src",
11
+ "openclaw.plugin.json"
12
+ ],
13
+ "keywords": [
14
+ "openclaw",
15
+ "dcgchat",
16
+ "websocket",
17
+ "ai"
18
+ ],
19
+ "scripts": {
20
+ "typecheck": "tsc --noEmit"
21
+ },
22
+ "dependencies": {
23
+ "ali-oss": "file:src/libs/ali-oss-6.23.0.tgz",
24
+ "ws": "file:src/libs/ws-8.19.0.tgz",
25
+ "axios": "file:src/libs/axios-1.13.6.tgz",
26
+ "md5": "file:src/libs/md5-2.3.0.tgz",
27
+ "unzipper": "file:src/libs/unzipper-0.12.3.tgz"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.0.0",
31
+ "@types/ws": "^8.5.0",
32
+ "openclaw": "2026.2.13",
33
+ "tsx": "^4.19.0",
34
+ "typescript": "^5.7.0"
35
+ },
36
+ "peerDependencies": {
37
+ "openclaw": ">=2026.2.13"
38
+ },
39
+ "openclaw": {
40
+ "extensions": [
41
+ "./index.ts"
42
+ ],
43
+ "channel": {
44
+ "id": "dcgchat",
45
+ "label": "DCG Chat",
46
+ "selectionLabel": "DCG Chat",
47
+ "docsPath": "/channels/dcgchat",
48
+ "docsLabel": "dcgchat",
49
+ "blurb": "连接 OpenClaw 与 DCG Chat 产品",
50
+ "order": 80
51
+ },
52
+ "install": {
53
+ "npmSpec": "@dcrays/dcgchat-test",
54
+ "localPath": "extensions/dcgchat",
55
+ "defaultChoice": "npm"
56
+ }
57
+ }
58
+ }
package/src/api.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { post } from "./request.js";
2
+ import type { IStsToken, IStsTokenReq } from "./types.js";
3
+ import { getUserTokenCache, setUserTokenCache } from "./userInfo.js";
4
+
5
+ export const getStsToken = async (name: string, botToken: string) => {
6
+ // 确保 userToken 已缓存(如果未缓存会自动获取并缓存)
7
+ await getUserToken(botToken);
8
+
9
+ const response = await post<IStsTokenReq, IStsToken>(
10
+ "/user/getStsToken",
11
+ {
12
+ sourceFileName: name,
13
+ isPrivate: 0,
14
+ },
15
+ { botToken },
16
+ );
17
+
18
+ if (!response || !response.data || !response.data.bucket) {
19
+ throw new Error("获取 OSS 临时凭证失败");
20
+ }
21
+
22
+ return response.data;
23
+ };
24
+
25
+ /**
26
+ * 通过 botToken 查询 userToken
27
+ * @param botToken 机器人 token
28
+ * @returns userToken
29
+ */
30
+ export const queryUserTokenByBotToken = async (botToken: string): Promise<string> => {
31
+ const response = await post<{botToken: string}, {token: string}>("/organization/queryUserTokenByBotToken", {
32
+ botToken,
33
+ });
34
+
35
+ if (!response || !response.data || !response.data.token) {
36
+ throw new Error("获取绑定的用户信息失败");
37
+ }
38
+
39
+ return response.data.token;
40
+ };
41
+
42
+ /**
43
+ * 获取 userToken(优先从缓存获取,缓存未命中则调用 API)
44
+ * @param botToken 机器人 token
45
+ * @returns userToken
46
+ */
47
+ export const getUserToken = async (botToken: string): Promise<string> => {
48
+ // 1. 尝试从缓存获取
49
+ const cachedToken = getUserTokenCache(botToken);
50
+ if (cachedToken) {
51
+ return cachedToken;
52
+ }
53
+
54
+ // 2. 缓存未命中,调用 API 获取
55
+ console.log(`[api] cache miss, fetching userToken for botToken=${botToken.slice(0, 10)}...`);
56
+ const userToken = await queryUserTokenByBotToken(botToken);
57
+
58
+ // 3. 缓存新获取的 token
59
+ setUserTokenCache(botToken, userToken);
60
+
61
+ return userToken;
62
+ };
package/src/bot.ts ADDED
@@ -0,0 +1,272 @@
1
+ import path from "node:path";
2
+ import type { ClawdbotConfig, RuntimeEnv } from "openclaw/plugin-sdk";
3
+ import { createReplyPrefixContext } from "openclaw/plugin-sdk";
4
+ import type { InboundMessage, OutboundReply } from "./types.js";
5
+ import { getDcgchatRuntime } from "./runtime.js";
6
+ import { resolveAccount } from "./channel.js";
7
+ import { setMsgParams } from "./tool.js";
8
+
9
+ type MediaInfo = {
10
+ path: string;
11
+ contentType: string;
12
+ placeholder: string;
13
+ };
14
+
15
+ async function resolveMediaFromUrls(
16
+ fileUrls: string[],
17
+ maxBytes: number,
18
+ log?: (msg: string) => void,
19
+ ): Promise<MediaInfo[]> {
20
+ const core = getDcgchatRuntime();
21
+ const out: MediaInfo[] = [];
22
+
23
+ log?.(`dcgchat media: starting resolve for ${fileUrls.length} file(s): ${JSON.stringify(fileUrls)}`);
24
+
25
+ for (let i = 0; i < fileUrls.length; i++) {
26
+ const url = fileUrls[i];
27
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] fetching ${url}`);
28
+ try {
29
+ const response = await fetch(url);
30
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] fetch response status=${response.status}, content-type=${response.headers.get("content-type")}, content-length=${response.headers.get("content-length")}`);
31
+ if (!response.ok) {
32
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] fetch failed with HTTP ${response.status}, skipping`);
33
+ continue;
34
+ }
35
+ const buffer = Buffer.from(await response.arrayBuffer());
36
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] downloaded buffer size=${buffer.length} bytes`);
37
+
38
+ let contentType = response.headers.get("content-type") || "";
39
+ if (!contentType) {
40
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] no content-type header, detecting mime...`);
41
+ contentType = await core.media.detectMime({ buffer });
42
+ }
43
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] resolved contentType=${contentType}`);
44
+
45
+ const fileName = path.basename(new URL(url).pathname) || "file";
46
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] fileName=${fileName}, saving to disk (maxBytes=${maxBytes})...`);
47
+
48
+ const saved = await core.channel.media.saveMediaBuffer(
49
+ buffer,
50
+ contentType,
51
+ "inbound",
52
+ maxBytes,
53
+ fileName,
54
+ );
55
+
56
+ const isImage = contentType.startsWith("image/");
57
+ out.push({
58
+ path: saved.path,
59
+ contentType: saved.contentType,
60
+ placeholder: isImage ? "<media:image>" : "<media:file>",
61
+ });
62
+
63
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] saved to ${saved.path} (contentType=${saved.contentType}, isImage=${isImage})`);
64
+ } catch (err) {
65
+ log?.(`dcgchat media: [${i + 1}/${fileUrls.length}] FAILED to process ${url}: ${String(err)}`);
66
+ }
67
+ }
68
+
69
+ log?.(`dcgchat media: resolve complete, ${out.length}/${fileUrls.length} file(s) succeeded`);
70
+
71
+ return out;
72
+ }
73
+
74
+ function buildMediaPayload(mediaList: MediaInfo[]): {
75
+ MediaPath?: string;
76
+ MediaType?: string;
77
+ MediaUrl?: string;
78
+ MediaPaths?: string[];
79
+ MediaUrls?: string[];
80
+ MediaTypes?: string[];
81
+ } {
82
+ if (mediaList.length === 0) return {};
83
+ const first = mediaList[0];
84
+ const mediaPaths = mediaList.map((m) => m.path);
85
+ const mediaTypes = mediaList.map((m) => m.contentType).filter(Boolean);
86
+ return {
87
+ MediaPath: first?.path,
88
+ MediaType: first?.contentType,
89
+ MediaUrl: first?.path,
90
+ MediaPaths: mediaPaths.length > 0 ? mediaPaths : undefined,
91
+ MediaUrls: mediaPaths.length > 0 ? mediaPaths : undefined,
92
+ MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * 处理一条用户消息,调用 Agent 并返回回复
98
+ */
99
+ export async function handleDcgchatMessage(params: {
100
+ cfg: ClawdbotConfig;
101
+ msg: InboundMessage;
102
+ accountId: string;
103
+ runtime?: RuntimeEnv;
104
+ onChunk: (reply: OutboundReply) => void;
105
+ }): Promise<void> {
106
+ const { cfg, msg, accountId, runtime } = params;
107
+ const log = runtime?.log ?? console.log;
108
+ const error = runtime?.error ?? console.error;
109
+
110
+ const account = resolveAccount(cfg, accountId);
111
+ const userId = msg._userId.toString();
112
+ // const text = msg.text?.trim();
113
+ const text = msg.content.text?.trim();
114
+
115
+ if (!userId || !text) {
116
+ params.onChunk({
117
+ messageType: "openclaw_bot_chat",
118
+ _userId: msg._userId,
119
+ source: "client",
120
+ content: {
121
+ bot_token: msg.content.bot_token,
122
+ session_id: msg.content.session_id,
123
+ message_id: msg.content.message_id,
124
+ response: "[错误] 消息格式不正确",
125
+ },
126
+ });
127
+ return;
128
+ }
129
+
130
+ try {
131
+ const core = getDcgchatRuntime();
132
+
133
+ const route = core.channel.routing.resolveAgentRoute({
134
+ cfg,
135
+ channel: "dcgchat",
136
+ accountId: account.accountId,
137
+ peer: { kind: "direct", id: userId },
138
+ });
139
+
140
+ // 处理用户上传的文件
141
+ const fileUrls = msg.content.file_urls ?? [];
142
+ log(`dcgchat[${accountId}]: incoming message from user=${userId}, text="${text?.slice(0, 80)}", file_urls count=${fileUrls.length}`);
143
+ let mediaPayload: Record<string, unknown> = {};
144
+ if (fileUrls.length > 0) {
145
+ log(`dcgchat[${accountId}]: processing ${fileUrls.length} file(s): ${JSON.stringify(fileUrls)}`);
146
+ const mediaMaxBytes = 30 * 1024 * 1024;
147
+ const mediaList = await resolveMediaFromUrls(fileUrls, mediaMaxBytes, log);
148
+ mediaPayload = buildMediaPayload(mediaList);
149
+ log(`dcgchat[${accountId}]: media resolved ${mediaList.length}/${fileUrls.length} file(s), payload=${JSON.stringify(mediaPayload)}`);
150
+ }
151
+
152
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
153
+ // const messageBody = `${userId}: ${text}`;
154
+ const messageBody = text;
155
+ const bodyFormatted = core.channel.reply.formatAgentEnvelope({
156
+ channel: "DCG Chat",
157
+ from: userId,
158
+ timestamp: new Date(),
159
+ envelope: envelopeOptions,
160
+ body: messageBody,
161
+ });
162
+
163
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
164
+ Body: bodyFormatted,
165
+ RawBody: text,
166
+ CommandBody: text,
167
+ From: userId,
168
+ To: userId,
169
+ SessionKey: route.sessionKey,
170
+ AccountId: msg.content.session_id,
171
+ ChatType: "direct",
172
+ SenderName: userId,
173
+ SenderId: userId,
174
+ Provider: "dcgchat" as const,
175
+ Surface: "dcgchat" as const,
176
+ MessageSid: msg.content.message_id,
177
+ Timestamp: Date.now(),
178
+ WasMentioned: true,
179
+ CommandAuthorized: true,
180
+ OriginatingChannel: "dcgchat" as const,
181
+ OriginatingTo: `user:${userId}`,
182
+ ...mediaPayload,
183
+ });
184
+
185
+ log(`dcgchat[${accountId}]: ctxPayload=${JSON.stringify(ctxPayload)}`);
186
+
187
+ const prefixContext = createReplyPrefixContext({ cfg, agentId: route.agentId });
188
+
189
+ const { dispatcher, replyOptions, markDispatchIdle } =
190
+ core.channel.reply.createReplyDispatcherWithTyping({
191
+ responsePrefix: prefixContext.responsePrefix,
192
+ responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
193
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
194
+ onReplyStart: async () => {},
195
+ deliver: async (payload) => {
196
+ log(`dcgchat[${accountId}][deliver]: received chunk, text length=${payload.text?.length || 0}`);
197
+ const t = payload.text?.trim();
198
+ if (t) {
199
+ log(`dcgchat[${accountId}][deliver]: sending chunk to user ${msg._userId}, text="${t.slice(0, 50)}..."`);
200
+ params.onChunk({
201
+ messageType: "openclaw_bot_chat",
202
+ _userId: msg._userId,
203
+ source: "client",
204
+ content: {
205
+ bot_token: msg.content.bot_token,
206
+ session_id: msg.content.session_id,
207
+ message_id: msg.content.message_id,
208
+ response: t,
209
+ state: 'chunk',
210
+ },
211
+ });
212
+ log(`dcgchat[${accountId}][deliver]: chunk sent successfully`);
213
+ } else {
214
+ log(`dcgchat[${accountId}][deliver]: skipping empty chunk`);
215
+ }
216
+ },
217
+ onError: (err, info) => {
218
+ error(`dcgchat[${accountId}] ${info.kind} reply failed: ${String(err)}`);
219
+ },
220
+ onIdle: () => {},
221
+ });
222
+
223
+ log(`dcgchat[${accountId}]: dispatching to agent (session=${route.sessionKey})`);
224
+
225
+ await core.channel.reply.dispatchReplyFromConfig({
226
+ ctx: ctxPayload,
227
+ cfg,
228
+ dispatcher,
229
+ replyOptions: {
230
+ ...replyOptions,
231
+ onModelSelected: prefixContext.onModelSelected,
232
+ },
233
+ });
234
+
235
+ log(`dcgchat[${accountId}]: dispatch complete, sending final state`);
236
+ params.onChunk({
237
+ messageType: "openclaw_bot_chat",
238
+ _userId: msg._userId,
239
+ source: "client",
240
+ content: {
241
+ bot_token: msg.content.bot_token,
242
+ session_id: msg.content.session_id,
243
+ message_id: msg.content.message_id,
244
+ response: '',
245
+ state: 'final',
246
+ },
247
+ });
248
+ setMsgParams({
249
+ sessionId: '',
250
+ messageId: ''
251
+ });
252
+ log(`dcgchat[${accountId}]: final state sent`);
253
+
254
+ markDispatchIdle();
255
+ log(`dcgchat[${accountId}]: message handling complete`);
256
+
257
+ } catch (err) {
258
+ error(`dcgchat[${accountId}]: handle message failed: ${String(err)}`);
259
+ params.onChunk({
260
+ messageType: "openclaw_bot_chat",
261
+ _userId: msg._userId,
262
+ source: "client",
263
+ content: {
264
+ bot_token: msg.content.bot_token,
265
+ session_id: msg.content.session_id,
266
+ message_id: msg.content.message_id,
267
+ response: `[错误] ${err instanceof Error ? err.message : String(err)}`,
268
+ state: 'final',
269
+ },
270
+ });
271
+ }
272
+ }
package/src/channel.ts ADDED
@@ -0,0 +1,192 @@
1
+ import type { ChannelPlugin, OpenClawConfig } from "openclaw/plugin-sdk";
2
+ import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk";
3
+ import type { ResolvedDcgchatAccount, DcgchatConfig } from "./types.js";
4
+ import { logDcgchat } from "./log.js";
5
+ import { getWsConnection } from "./connection.js";
6
+ import { ossUpload } from "./oss.js";
7
+ import { getMsgParams } from "./tool.js";
8
+
9
+ export function resolveAccount(cfg: OpenClawConfig, accountId?: string | null): ResolvedDcgchatAccount {
10
+ const id = accountId ?? DEFAULT_ACCOUNT_ID;
11
+ const raw = (cfg.channels?.["dcgchat"] as DcgchatConfig | undefined) ?? {};
12
+ return {
13
+ accountId: id,
14
+ enabled: raw.enabled !== false,
15
+ configured: Boolean(raw.wsUrl),
16
+ wsUrl: raw.wsUrl ?? "",
17
+ botToken: raw.botToken ?? "",
18
+ userId: raw.userId ?? "",
19
+ domainId: raw.domainId ?? "",
20
+ appId: raw.appId ?? "",
21
+ };
22
+ }
23
+
24
+ export const dcgchatPlugin: ChannelPlugin<ResolvedDcgchatAccount> = {
25
+ id: "dcgchat",
26
+ meta: {
27
+ id: "dcgchat",
28
+ label: "DCG Chat",
29
+ selectionLabel: "DCG Chat",
30
+ docsPath: "/channels/dcgchat",
31
+ docsLabel: "dcgchat",
32
+ blurb: "连接 OpenClaw 与 DCG Chat 产品",
33
+ order: 80,
34
+ },
35
+ capabilities: {
36
+ chatTypes: ["direct"],
37
+ polls: false,
38
+ threads: true,
39
+ media: true,
40
+ nativeCommands: true,
41
+ reactions: true,
42
+ edit: false,
43
+ reply: true,
44
+ effects: true,
45
+ // blockStreaming: true,
46
+ },
47
+ reload: { configPrefixes: ["channels.dcgchat"] },
48
+ configSchema: {
49
+ schema: {
50
+ type: "object",
51
+ additionalProperties: false,
52
+ properties: {
53
+ enabled: { type: "boolean" },
54
+ wsUrl: { type: "string" },
55
+ botToken: { type: "string" },
56
+ userId: { type: "string" },
57
+ appId: { type: "string" },
58
+ domainId: { type: "string" },
59
+ capabilities: { type: "array", items: { type: "string" } },
60
+ },
61
+ },
62
+ },
63
+ config: {
64
+ listAccountIds: () => [DEFAULT_ACCOUNT_ID],
65
+ resolveAccount: (cfg, accountId) => resolveAccount(cfg, accountId),
66
+ defaultAccountId: () => DEFAULT_ACCOUNT_ID,
67
+ setAccountEnabled: ({ cfg, enabled }) => ({
68
+ ...cfg,
69
+ channels: {
70
+ ...cfg.channels,
71
+ "dcgchat": {
72
+ ...(cfg.channels?.["dcgchat"] as Record<string, unknown> | undefined),
73
+ enabled,
74
+ },
75
+ },
76
+ }),
77
+ isConfigured: (account) => account.configured,
78
+ describeAccount: (account) => ({
79
+ accountId: account.accountId,
80
+ enabled: account.enabled,
81
+ configured: account.configured,
82
+ wsUrl: account.wsUrl,
83
+ botToken: account.botToken ? "***" : "",
84
+ userId: account.userId,
85
+ domainId: account.domainId,
86
+ appId: account.appId,
87
+ }),
88
+ },
89
+ messaging: {
90
+ normalizeTarget: (raw) => raw?.trim() || undefined,
91
+ targetResolver: {
92
+ looksLikeId: (raw) => Boolean(raw?.trim()),
93
+ hint: "userId",
94
+ },
95
+ },
96
+ outbound: {
97
+ deliveryMode: "direct",
98
+ // textChunkLimit: 25,
99
+ textChunkLimit: 4000,
100
+ sendText: async (ctx) => {
101
+ const target = ctx.to || "(implicit)";
102
+ const ws = getWsConnection()
103
+ const params = getMsgParams();
104
+ if (ws?.readyState === WebSocket.OPEN) {
105
+ const {botToken} = resolveAccount(ctx.cfg, ctx.accountId);
106
+ const content = {
107
+ messageType: "openclaw_bot_chat",
108
+ _userId: target,
109
+ source: "client",
110
+ content: {
111
+ bot_token: botToken,
112
+ response: ctx.text,
113
+ session_id: params.sessionId || Date.now().toString(),
114
+ message_id: params.messageId ||Date.now().toString(),
115
+ },
116
+ };
117
+ ws.send(JSON.stringify(content));
118
+ logDcgchat.info(`dcgchat[${ctx.accountId}]: sendText to ${target}, ${JSON.stringify(content)}`);
119
+ } else {
120
+ logDcgchat.warn(`[dcgchat][${ctx.accountId ?? DEFAULT_ACCOUNT_ID}] outbound -> ${ws?.readyState}: ${ctx.text}`);
121
+ }
122
+ return {
123
+ channel: "dcgchat",
124
+ messageId: `dcg-${Date.now()}`,
125
+ chatId: target,
126
+ };
127
+ },
128
+ sendMedia: async (ctx) => {
129
+ const target = ctx.to || "(implicit)";
130
+ const ws = getWsConnection()
131
+ const params = getMsgParams();
132
+ if (ws?.readyState === WebSocket.OPEN) {
133
+ const {botToken} = resolveAccount(ctx.cfg, ctx.accountId);
134
+ try {
135
+ const url = ctx.mediaUrl ? await ossUpload(ctx.mediaUrl, botToken) : '';
136
+ const fileName = ctx.mediaUrl?.split(/[\\/]/).pop() || ''
137
+ const content = {
138
+ messageType: "openclaw_bot_chat",
139
+ _userId: target,
140
+ source: "client",
141
+ content: {
142
+ bot_token: botToken,
143
+ response: ctx.text + '\n' + `[${fileName}](${url})`,
144
+ session_id: params.sessionId || Date.now().toString(),
145
+ message_id: params.messageId ||Date.now().toString(),
146
+ },
147
+ };
148
+ ws.send(JSON.stringify(content));
149
+ logDcgchat.info(`dcgchat[${ctx.accountId}]: sendMedia to ${target}, ${JSON.stringify(content)}`);
150
+ } catch (error) {
151
+ const content = {
152
+ messageType: "openclaw_bot_chat",
153
+ _userId: target,
154
+ source: "client",
155
+ content: {
156
+ bot_token: botToken,
157
+ response: ctx.text + '\n' + ctx.mediaUrl,
158
+ session_id: params.sessionId || Date.now().toString(),
159
+ message_id: params.messageId ||Date.now().toString(),
160
+ },
161
+ };
162
+ ws.send(JSON.stringify(content));
163
+ logDcgchat.info(`dcgchat[${ctx.accountId}]: sendMedia to ${target}, ${JSON.stringify(content)}`);
164
+ }
165
+ } else {
166
+ logDcgchat.warn(`[dcgchat][${ctx.accountId ?? DEFAULT_ACCOUNT_ID}] outbound -> ${ws?.readyState}: ${ctx.text}`);
167
+ }
168
+ return {
169
+ channel: "dcgchat",
170
+ messageId: `dcg-${Date.now()}`,
171
+ chatId: target,
172
+ };
173
+ },
174
+ },
175
+ gateway: {
176
+ startAccount: async (ctx) => {
177
+ const { monitorDcgchatProvider } = await import("./monitor.js");
178
+ const account = resolveAccount(ctx.cfg, ctx.accountId);
179
+ if (!account.wsUrl) {
180
+ ctx.log?.warn(`dcgchat[${account.accountId}]: wsUrl not configured, skipping`);
181
+ return;
182
+ }
183
+ // ctx.log?.info(`dcgchat[${account.accountId}]: connecting to ${account.wsUrl}`);
184
+ return monitorDcgchatProvider({
185
+ config: ctx.cfg,
186
+ runtime: ctx.runtime,
187
+ abortSignal: ctx.abortSignal,
188
+ accountId: ctx.accountId,
189
+ });
190
+ },
191
+ },
192
+ };