@workclaw/openclaw-workclaw 1.0.18 → 1.0.19

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.
Files changed (142) hide show
  1. package/README.md +364 -345
  2. package/dist/api.d.ts +3 -0
  3. package/dist/api.js +3 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +263 -0
  6. package/dist/setup-entry.d.ts +2 -0
  7. package/dist/setup-entry.js +12 -0
  8. package/dist/src/accounts.d.ts +66 -0
  9. package/dist/src/accounts.js +279 -0
  10. package/dist/src/api/accounts-api.d.ts +2 -0
  11. package/dist/src/api/accounts-api.js +130 -0
  12. package/dist/src/api/prompts-api.d.ts +2 -0
  13. package/dist/src/api/prompts-api.js +103 -0
  14. package/dist/src/api/session-api.d.ts +2 -0
  15. package/dist/src/api/session-api.js +207 -0
  16. package/dist/src/api/skills-api.d.ts +2 -0
  17. package/dist/src/api/skills-api.js +64 -0
  18. package/dist/src/api/workspace.d.ts +3 -0
  19. package/dist/src/api/workspace.js +28 -0
  20. package/dist/src/channel.d.ts +11 -0
  21. package/{src/channel.ts → dist/src/channel.js} +198 -225
  22. package/dist/src/config-schema.d.ts +93 -0
  23. package/dist/src/config-schema.js +56 -0
  24. package/dist/src/connection/workclaw-client.d.ts +147 -0
  25. package/dist/src/connection/workclaw-client.js +351 -0
  26. package/dist/src/gateway/agent-handlers.d.ts +12 -0
  27. package/{src/gateway/agent-handlers.ts → dist/src/gateway/agent-handlers.js} +433 -523
  28. package/dist/src/gateway/config-writer.d.ts +71 -0
  29. package/dist/src/gateway/config-writer.js +312 -0
  30. package/dist/src/gateway/message-context.d.ts +76 -0
  31. package/{src/gateway/message-context.ts → dist/src/gateway/message-context.js} +499 -594
  32. package/dist/src/gateway/message-dispatcher.d.ts +19 -0
  33. package/{src/gateway/message-dispatcher.ts → dist/src/gateway/message-dispatcher.js} +512 -641
  34. package/dist/src/gateway/reconnect.d.ts +27 -0
  35. package/{src/gateway/reconnect.ts → dist/src/gateway/reconnect.js} +206 -253
  36. package/dist/src/gateway/skills-handler.d.ts +29 -0
  37. package/dist/src/gateway/skills-handler.js +576 -0
  38. package/dist/src/gateway/skills-list-handler.d.ts +27 -0
  39. package/dist/src/gateway/skills-list-handler.js +233 -0
  40. package/dist/src/gateway/tools-list-handler.d.ts +30 -0
  41. package/dist/src/gateway/tools-list-handler.js +101 -0
  42. package/dist/src/gateway/workclaw-gateway.d.ts +14 -0
  43. package/dist/src/gateway/workclaw-gateway.js +223 -0
  44. package/dist/src/media/upload.d.ts +13 -0
  45. package/dist/src/media/upload.js +125 -0
  46. package/dist/src/outbound/index.d.ts +36 -0
  47. package/dist/src/outbound/index.js +123 -0
  48. package/dist/src/outbound/workclaw-sender.d.ts +36 -0
  49. package/{src/outbound/workclaw-sender.ts → dist/src/outbound/workclaw-sender.js} +95 -158
  50. package/dist/src/runtime.d.ts +116 -0
  51. package/dist/src/runtime.js +374 -0
  52. package/dist/src/secret-contract-api.d.ts +4 -0
  53. package/dist/src/secret-contract-api.js +4 -0
  54. package/{src/send.ts → dist/src/send.d.ts} +1 -1
  55. package/dist/src/send.js +1 -0
  56. package/dist/src/setup-api.d.ts +3 -0
  57. package/dist/src/setup-api.js +3 -0
  58. package/dist/src/setup-core.d.ts +3 -0
  59. package/dist/src/setup-core.js +13 -0
  60. package/dist/src/setup-surface.d.ts +7 -0
  61. package/dist/src/setup-surface.js +363 -0
  62. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +93 -0
  63. package/dist/src/tools/openclaw-workclaw-cron/api/index.js +209 -0
  64. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +10 -0
  65. package/{src/tools/openclaw-workclaw-cron/index.ts → dist/src/tools/openclaw-workclaw-cron/index.js} +33 -39
  66. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +16 -0
  67. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.js +152 -0
  68. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +18 -0
  69. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.js +162 -0
  70. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +14 -0
  71. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.js +80 -0
  72. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +14 -0
  73. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.js +107 -0
  74. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +14 -0
  75. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.js +80 -0
  76. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +14 -0
  77. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.js +107 -0
  78. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +17 -0
  79. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.js +127 -0
  80. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +14 -0
  81. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.js +87 -0
  82. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +14 -0
  83. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.js +107 -0
  84. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +17 -0
  85. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.js +164 -0
  86. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +18 -0
  87. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.js +135 -0
  88. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +52 -0
  89. package/dist/src/tools/openclaw-workclaw-cron/types/index.js +4 -0
  90. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +40 -0
  91. package/dist/src/tools/openclaw-workclaw-cron/utils/index.js +122 -0
  92. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +10 -0
  93. package/{src/tools/openclaw-workclaw-system/index.ts → dist/src/tools/openclaw-workclaw-system/index.js} +15 -17
  94. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +8 -0
  95. package/dist/src/tools/openclaw-workclaw-system/src/get/index.js +64 -0
  96. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +8 -0
  97. package/dist/src/tools/openclaw-workclaw-system/src/token/index.js +78 -0
  98. package/{src/types.ts → dist/src/types.d.ts} +39 -58
  99. package/dist/src/types.js +1 -0
  100. package/dist/src/utils/content.d.ts +15 -0
  101. package/{src/utils/content.ts → dist/src/utils/content.js} +38 -35
  102. package/package.json +62 -49
  103. package/index.ts +0 -302
  104. package/setup-entry.ts +0 -6
  105. package/src/accounts.ts +0 -312
  106. package/src/api/accounts-api.ts +0 -156
  107. package/src/api/prompts-api.ts +0 -116
  108. package/src/api/session-api.ts +0 -238
  109. package/src/api/skills-api.ts +0 -72
  110. package/src/api/workspace.ts +0 -41
  111. package/src/config-schema.ts +0 -110
  112. package/src/connection/workclaw-client.ts +0 -643
  113. package/src/gateway/config-writer.ts +0 -296
  114. package/src/gateway/skills-handler.ts +0 -741
  115. package/src/gateway/skills-list-handler.ts +0 -332
  116. package/src/gateway/tools-list-handler.ts +0 -160
  117. package/src/gateway/workclaw-gateway.ts +0 -367
  118. package/src/media/upload.ts +0 -157
  119. package/src/outbound/index.ts +0 -185
  120. package/src/runtime.ts +0 -497
  121. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  122. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -177
  123. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  124. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  125. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  126. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  127. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  128. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  129. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  130. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  131. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -195
  132. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  133. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  134. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  135. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  136. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  137. package/tests/accounts.test.ts +0 -285
  138. package/tests/message-context.test.ts +0 -313
  139. package/tests/reconnect.test.ts +0 -257
  140. package/tests/workclaw-client.test.ts +0 -112
  141. package/tsconfig.json +0 -14
  142. package/vitest.config.ts +0 -8
@@ -1,594 +1,499 @@
1
- import type { WorkclawConfig } from "../types.js";
2
- import type { PluginRuntime } from "openclaw/plugin-sdk";
3
- import fs from "node:fs/promises";
4
- import path from "node:path";
5
- import os from "node:os";
6
- import https from "node:https";
7
- import http from "node:http";
8
-
9
- // 附件接口
10
- export interface Attachment {
11
- url: string
12
- fileId: string
13
- type: 'image' | 'file'
14
- name?: string
15
- }
16
-
17
- /** Channel/plugin name constant */
18
- export const OPENCLAW_WORKCLAW_CHANNEL = "openclaw-workclaw";
19
-
20
- export interface InboundMessage {
21
- text: string;
22
- to: string;
23
- from: string;
24
- chatType: "dm" | "group";
25
- messageId: string;
26
- rawPayload: string;
27
- timestamp: number;
28
- attachments?: Attachment[] // 文件 URL 列表
29
- }
30
-
31
- export interface InboundContextPayload {
32
- [key: string]: unknown;
33
- Body: string;
34
- BodyForAgent: string;
35
- RawBody: string;
36
- From: string;
37
- To: string;
38
- ChatType: "dm" | "group";
39
- Provider: string;
40
- Surface: string;
41
- Timestamp: number;
42
- AccountId: string;
43
- AgentId?: string;
44
- MessageSid?: string;
45
- OriginatingChannel: string;
46
- OriginatingTo: string;
47
- }
48
-
49
- export type WorkClawMessageType =
50
- | "agent_message" // 正常的业务消息
51
- | "ping" // 需要回复 pong 的消息
52
- | "disconnect" // 断开连接的消息
53
- | "agent_created" // 创建账户事件
54
- | "agent_updated" // 更新账户事件
55
- | "agent_deleted" // 删除账户事件
56
- | "tools_list" // 获取工具列表事件
57
- | "skills_list" // 获取 skills 列表事件
58
- | "skills_event" // skills 相关事件(create/update/delete/list/get/invoke)
59
- | "init_agent" // 初始化智能体事件
60
- | "ignored"; // 忽略的消息(未知类型)
61
-
62
- export interface ParseWorkClawResult {
63
- type: WorkClawMessageType;
64
- message?: {
65
- text: string;
66
- userId: string;
67
- openConversationId: string;
68
- messageId: string;
69
- agentId?: string | number;
70
- attachments?: Attachment[]
71
- };
72
- pongData?: any; // 用于回复 pong 的数据
73
- eventData?: any; // 事件数据(用于 AGENT_CREATED/UPDATED/DELETED 及 skills 事件)
74
- }
75
-
76
- export function parseInboundMessage(data: string, allowRawJsonPayload?: boolean): Partial<InboundMessage> {
77
- let input: any = {};
78
- try {
79
- input = data ? JSON.parse(data) : {};
80
- } catch {
81
- // Not JSON, treat as plain text
82
- }
83
-
84
- const text =
85
- typeof input.text === "string"
86
- ? input.text
87
- : typeof input.message === "string"
88
- ? input.message
89
- : typeof input.body === "string"
90
- ? input.body
91
- : data;
92
-
93
- const to = String(input.to ?? input.chatId ?? input.target ?? "");
94
- const from = String(input.from ?? input.senderId ?? input.userId ?? "");
95
- const chatType = String(input.chatType || "").toLowerCase() === "group" ? "group" : "dm";
96
- const messageId = String(input.messageId ?? input.id ?? "");
97
- const rawPayload = allowRawJsonPayload ? JSON.stringify(input ?? {}) : data;
98
-
99
- return {
100
- text,
101
- to,
102
- from,
103
- chatType,
104
- messageId,
105
- rawPayload,
106
- };
107
- }
108
-
109
- export function parseWorkClawMessage(data: string, log?: {
110
- info?: (msg: string) => void;
111
- warn?: (msg: string) => void;
112
- error?: (msg: string) => void;
113
- }): ParseWorkClawResult | null {
114
- //{"specVersion":"1.0","type":"EVENT","metadata":{"time":"1773749163831","event":"INIT_AGENT","contentType":"application/json"},"data":"\"12557533957824965\""}
115
- let input: any = {};
116
- try {
117
- input = data ? JSON.parse(data) : {};
118
- } catch {
119
- log?.info?.(`Failed to parse message data=${data}`);
120
- return null;
121
- }
122
-
123
- // Handle plain text ping
124
- if (typeof input === "string" && input.toLowerCase() === "ping") {
125
- return {
126
- type: "ping",
127
- pongData: input,
128
- };
129
- }
130
-
131
- const envelope = input && typeof input === "object" ? input : { data: input };
132
- const topic = envelope?.metadata?.topic;
133
- const type = String(envelope?.type || "").trim().toUpperCase();
134
- const topicLower = String(topic || "").trim().toLowerCase();
135
-
136
- if (type === "INIT_AGENT") {
137
- let parsedData = envelope?.data;
138
- if (typeof parsedData === "string") {
139
- try {
140
- parsedData = JSON.parse(parsedData);
141
- } catch (e) {
142
- // 解析失败,保持原样
143
- }
144
- }
145
-
146
- return {
147
- type: "init_agent",
148
- eventData: parsedData,
149
- };
150
- }
151
-
152
- // Handle SYSTEM messages
153
- if (type === "SYSTEM") {
154
- if (topicLower === "ping") {
155
- return {
156
- type: "ping",
157
- pongData: envelope?.data,
158
- };
159
- }
160
- if (topicLower === "disconnect") {
161
- return {
162
- type: "disconnect",
163
- };
164
- }
165
- // Unknown system message type, ignore
166
- return {
167
- type: "ignored",
168
- };
169
- }
170
-
171
- // Handle EVENT messages (AGENT_CREATED, AGENT_UPDATED, AGENT_DELETED, TOOLS_LIST, SKILLS_LIST, INIT_AGENT)
172
- if (type === "EVENT") {
173
- const eventType = String(envelope?.metadata?.event || "").trim().toUpperCase();
174
-
175
- // 解析 data 字段(可能是 JSON 字符串)
176
- let parsedData = envelope?.data;
177
- if (typeof parsedData === "string") {
178
- try {
179
- parsedData = JSON.parse(parsedData);
180
- } catch (e) {
181
- // 解析失败,保持原样
182
- }
183
- }
184
-
185
- if (eventType === "AGENT_CREATED") {
186
- return {
187
- type: "agent_created",
188
- eventData: parsedData,
189
- };
190
- }
191
- if (eventType === "AGENT_UPDATED") {
192
- return {
193
- type: "agent_updated",
194
- eventData: parsedData,
195
- };
196
- }
197
- if (eventType === "AGENT_DELETED") {
198
- return {
199
- type: "agent_deleted",
200
- eventData: parsedData,
201
- };
202
- }
203
- if (eventType === "TOOLS_LIST") {
204
- return {
205
- type: "tools_list",
206
- eventData: parsedData,
207
- };
208
- }
209
- if (eventType === "SKILLS_LIST") {
210
- return {
211
- type: "skills_list",
212
- eventData: parsedData,
213
- };
214
- }
215
- if (eventType === "INIT_AGENT") {
216
- return {
217
- type: "init_agent",
218
- eventData: parsedData,
219
- };
220
- }
221
-
222
- if (eventType === "SKILL_DO_REMIND") {
223
- const eventTopic = String(parsedData?.dotype || "").toLowerCase();
224
- return {
225
- type: "skills_event",
226
- eventData: {
227
- topic: "skills/" + eventTopic,
228
- requestId: "",
229
- callbackUrl: "",
230
- authToken: "",
231
- data: parsedData,
232
- },
233
- };
234
- }
235
-
236
- // Unknown event type, ignore
237
- return {
238
- type: "ignored",
239
- };
240
- }
241
-
242
- // Only process CALLBACK type with AGENT_MESSAGE topic
243
- if (type !== "CALLBACK" || String(topic || "").trim().toUpperCase() !== "AGENT_MESSAGE") {
244
- return {
245
- type: "ignored",
246
- };
247
- }
248
-
249
- // 解析 data 字段(可能是 JSON 字符串)
250
- let payload = envelope?.data || {};
251
- if (typeof payload === "string") {
252
- try {
253
- payload = JSON.parse(payload);
254
- } catch (e) {
255
- // 解析失败,保持原样
256
- }
257
- }
258
-
259
- const text =
260
- typeof payload?.message?.content === "string"
261
- ? payload.message.content
262
- : typeof payload?.message === "string"
263
- ? payload.message
264
- : "";
265
-
266
- // 判断文件是否为图片
267
- function isImageFile(url: string): boolean {
268
- const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'];
269
- const lowerUrl = url.toLowerCase();
270
- return imageExtensions.some(ext => lowerUrl.endsWith(ext));
271
- }
272
-
273
- // 解析 fileUrl 列表到 attachments(供 SDK 和 AI 使用)
274
- const fileUrlList: string[] = Array.isArray(payload?.fileUrl) ? payload.fileUrl : [];
275
- const attachments: Attachment[] = fileUrlList.map((url) => ({
276
- url,
277
- fileId: payload?.fileId ? String(payload.fileId) : '',
278
- type: isImageFile(url) ? 'image' : 'file',
279
- }));
280
-
281
- return {
282
- type: "agent_message",
283
- message: {
284
- text,
285
- userId: String(payload?.userId ?? ""),
286
- openConversationId: String(payload?.conversationId ?? ""),
287
- messageId: String(payload?.msgId ?? ""),
288
- agentId: payload?.agentId,
289
- attachments: attachments.length > 0 ? attachments : undefined,
290
- },
291
- };
292
- }
293
-
294
- /**
295
- * URL 扩展名判断媒体类型
296
- */
297
- function detectMediaType(url: string): string {
298
- const lower = url.toLowerCase();
299
- if (lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png")
300
- || lower.endsWith(".gif") || lower.endsWith(".webp") || lower.endsWith(".bmp")
301
- || lower.endsWith(".svg") || lower.endsWith(".ico")) {
302
- return "image";
303
- }
304
- if (lower.endsWith(".mp3") || lower.endsWith(".wav") || lower.endsWith(".amr")
305
- || lower.endsWith(".m4a") || lower.endsWith(".ogg")) {
306
- return "audio";
307
- }
308
- if (lower.endsWith(".mp4") || lower.endsWith(".avi") || lower.endsWith(".mov")
309
- || lower.endsWith(".mkv") || lower.endsWith(".webm")) {
310
- return "video";
311
- }
312
- if (lower.endsWith(".pdf")) return "application/pdf";
313
- if (lower.endsWith(".docx")) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
314
- if (lower.endsWith(".xlsx")) return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
315
- if (lower.endsWith(".pptx")) return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
316
- if (lower.endsWith(".doc")) return "application/msword";
317
- if (lower.endsWith(".xls")) return "application/vnd.ms-excel";
318
- if (lower.endsWith(".ppt")) return "application/vnd.ms-powerpoint";
319
- if (lower.endsWith(".txt")) return "text/plain";
320
- if (lower.endsWith(".zip")) return "application/zip";
321
- if (lower.endsWith(".rar")) return "application/x-rar-compressed";
322
- return "application/octet-stream";
323
- }
324
-
325
- /**
326
- * URL 扩展名获取人类可读的类型标签
327
- */
328
- function getMediaTypeLabel(url: string): string {
329
- const lower = url.toLowerCase();
330
- if (lower.endsWith(".pdf")) return "PDF";
331
- if (lower.endsWith(".docx")) return "Word";
332
- if (lower.endsWith(".doc")) return "Word";
333
- if (lower.endsWith(".xlsx")) return "Excel";
334
- if (lower.endsWith(".xls")) return "Excel";
335
- if (lower.endsWith(".pptx")) return "PowerPoint";
336
- if (lower.endsWith(".ppt")) return "PowerPoint";
337
- if (lower.endsWith(".txt")) return "文本";
338
- if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "JPG图片";
339
- if (lower.endsWith(".png")) return "PNG图片";
340
- if (lower.endsWith(".gif")) return "GIF图片";
341
- if (lower.endsWith(".webp")) return "WebP图片";
342
- if (lower.endsWith(".mp3")) return "音频";
343
- if (lower.endsWith(".wav")) return "音频";
344
- if (lower.endsWith(".mp4")) return "视频";
345
- if (lower.endsWith(".zip") || lower.endsWith(".rar")) return "压缩包";
346
- return "文件";
347
- }
348
-
349
- /**
350
- * 下载文件到本地下载目录(按 accountId/peerId 隔离),返回本地路径
351
- */
352
- async function downloadFileToLocal(
353
- url: string,
354
- accountId: string,
355
- peerId: string,
356
- log?: { info?: (msg: string) => void; warn?: (msg: string) => void; error?: (msg: string) => void },
357
- ): Promise<string | null> {
358
- const downloadsDir = path.join(os.homedir(), ".openclaw", "media", "workclaw", "downloads", accountId, peerId);
359
- try {
360
- await fs.mkdir(downloadsDir, { recursive: true });
361
- } catch {}
362
-
363
- const urlObj = new URL(url);
364
- const fileName = path.basename(urlObj.pathname) || "file";
365
- const ext = path.extname(fileName);
366
- const stem = path.basename(fileName, ext);
367
- const localFileName = `${stem}_${Date.now()}${ext}`;
368
- const localFilePath = path.join(downloadsDir, localFileName);
369
-
370
- return new Promise((resolve) => {
371
- const client = url.startsWith("https:") ? https : http;
372
- const req = client.get(url, (res) => {
373
- if (res.statusCode !== 200) {
374
- log?.warn?.(`downloadFile: HTTP ${res.statusCode} for ${url}`);
375
- resolve(null);
376
- return;
377
- }
378
- const chunks: Buffer[] = [];
379
- res.on("data", (chunk: Buffer) => chunks.push(chunk));
380
- res.on("end", async () => {
381
- try {
382
- const buffer = Buffer.concat(chunks);
383
- await fs.writeFile(localFilePath, buffer);
384
- log?.info?.(`downloadFile: saved ${buffer.length} bytes -> ${localFilePath}`);
385
- resolve(localFilePath);
386
- } catch (err) {
387
- log?.error?.(`downloadFile: write failed: ${String(err)}`);
388
- resolve(null);
389
- }
390
- });
391
- res.on("error", (err) => {
392
- log?.error?.(`downloadFile: read error: ${String(err)}`);
393
- resolve(null);
394
- });
395
- });
396
- req.on("error", (err) => {
397
- log?.error?.(`downloadFile: request error: ${String(err)}`);
398
- resolve(null);
399
- });
400
- req.setTimeout(30000, () => {
401
- req.destroy();
402
- log?.warn?.(`downloadFile: timeout for ${url}`);
403
- resolve(null);
404
- });
405
- });
406
- }
407
-
408
- /**
409
- * Build inbound context for WorkClaw channel.
410
- *
411
- * When pluginRuntime is provided, performs full session handling:
412
- * - resolveStorePath, readSessionUpdatedAt, formatInboundEnvelope
413
- * - finalizeInboundContext, recordInboundSession
414
- *
415
- * @param message - The inbound message
416
- * @param accountId - Account ID
417
- * @param config - Account config (WorkclawConfig)
418
- * @param agentId - Target agent ID (optional)
419
- * @param pluginRuntime - OpenClaw plugin runtime (optional, enables full session handling)
420
- * @param recordSession - Whether to record session (default true)
421
- * @param log - Optional logger
422
- */
423
- export async function buildInboundContext(
424
- message: InboundMessage,
425
- accountId: string,
426
- config: any,
427
- agentId?: string,
428
- pluginRuntime?: PluginRuntime,
429
- recordSession: boolean = true,
430
- log?: { info?: (msg: string) => void; warn?: (msg: string) => void; error?: (msg: string) => void },
431
- ): Promise<InboundContextPayload> {
432
- // 尝试从 rawPayload 中提取已有的 sessionKey(新建话题时 openclaw 会生成新的 session)
433
- let existingSessionKey: string | undefined;
434
- try {
435
- const rawPayload = JSON.parse(message.rawPayload);
436
- existingSessionKey = rawPayload.sessionKey;
437
- } catch {
438
- // ignore
439
- }
440
-
441
- const peerId = message.from;
442
- const computedSessionKey = existingSessionKey
443
- || (agentId && agentId !== "main"
444
- ? `agent:${agentId}:openclaw-workclaw:${accountId}:direct:${peerId}`
445
- : undefined);
446
-
447
- const sessionKey = computedSessionKey || (agentId && agentId !== "main"
448
- ? `agent:${agentId}:openclaw-workclaw:${accountId}:direct:${peerId}`
449
- : undefined);
450
-
451
- // Basic context (used as base for both paths)
452
- // parseWorkClawMessage 已将 fileUrl 列表追加到 message.text 中
453
- const result: InboundContextPayload = {
454
- Body: message.text,
455
- BodyForAgent: message.text,
456
- RawBody: JSON.stringify(message),
457
- From: message.from,
458
- To: message.to,
459
- ChatType: message.chatType,
460
- Provider: OPENCLAW_WORKCLAW_CHANNEL,
461
- Surface: OPENCLAW_WORKCLAW_CHANNEL,
462
- Timestamp: message.timestamp,
463
- AccountId: accountId,
464
- AgentId: agentId,
465
- MessageSid: message.messageId,
466
- OriginatingChannel: OPENCLAW_WORKCLAW_CHANNEL,
467
- OriginatingTo: message.to,
468
- };
469
-
470
- if (sessionKey) {
471
- result.SessionKey = sessionKey;
472
- }
473
-
474
- // If no pluginRuntime provided, return basic context without session recording
475
- if (!pluginRuntime) {
476
- return result;
477
- }
478
-
479
- // Full session handling path
480
- const storePath = pluginRuntime.channel.session.resolveStorePath(config.session?.store, { agentId });
481
- log?.info?.(`[Session] storePath=${storePath}, agentId=${agentId}, sessionKey=${sessionKey}`);
482
-
483
- // 获取 envelope 格式选项
484
- const envelopeOptions = pluginRuntime.channel.reply.resolveEnvelopeFormatOptions(config);
485
-
486
- // 获取上次的 session 更新时间
487
- const previousTimestamp = pluginRuntime.channel.session.readSessionUpdatedAt({
488
- storePath,
489
- sessionKey: sessionKey!,
490
- });
491
- log?.info?.(`[Session] previousTimestamp=${previousTimestamp}`);
492
-
493
- // 处理附件:下载 fileUrl 到本地,并收集媒体信息
494
- let mediaUrls: string[] = [];
495
- let mediaTypes: string[] = [];
496
- let bodyText = message.text;
497
- if (message.attachments && message.attachments.length > 0) {
498
- log?.info?.(`[Attachments] Downloading ${message.attachments.length} files...`);
499
-
500
- // 并行下载所有附件
501
- const downloadResults = await Promise.all(
502
- message.attachments.map(async (att) => {
503
- const localPath = await downloadFileToLocal(att.url, accountId, message.from, log);
504
- const mediaType = detectMediaType(att.url);
505
- const typeLabel = getMediaTypeLabel(att.url);
506
- return { att, localPath, mediaType, typeLabel };
507
- })
508
- );
509
-
510
- // 收集下载成功的文件信息(MediaUrls 由 SDK 用于显示 [media attached])
511
- for (const { att, localPath, mediaType } of downloadResults) {
512
- if (localPath) {
513
- // 将绝对路径转为根相对路径(去掉 ~/.openclaw/ 前缀,转为 /.openclaw/... 形式)
514
- // OpenClaw 的 skill 系统会 block 绝对路径(C:\...)和 ~ 路径
515
- // 兼容 Windows 路径格式(C:\Users\用户名\.openclaw\... 或 C:\Users\用户名.openclaw\...)
516
- const homeDir = os.homedir().replace(/\\/g, '/').trim(); // 统一用正斜杠,去除尾随空格
517
- const normalizedLocalPath = localPath.replace(/\\/g, '/');
518
- const relativePath = normalizedLocalPath.startsWith(homeDir + '/.openclaw/')
519
- ? '/' + normalizedLocalPath.slice(homeDir.length + 1) // 用 / 开头表示根相对路径
520
- : normalizedLocalPath;
521
- mediaUrls.push(relativePath);
522
- mediaTypes.push(mediaType);
523
- log?.info?.(`[Attachments] Downloaded: ${relativePath}`);
524
- } else {
525
- log?.warn?.(`[Attachments] Failed to download: ${att.url}`);
526
- }
527
- }
528
-
529
- log?.info?.(`[Attachments] Downloaded ${mediaUrls.length}/${message.attachments.length} files`);
530
- }
531
- const fromLabel = message.to;
532
- const body = pluginRuntime.channel.reply.formatInboundEnvelope({
533
- channel: OPENCLAW_WORKCLAW_CHANNEL,
534
- from: fromLabel,
535
- timestamp: message.timestamp,
536
- body: bodyText,
537
- chatType: message.chatType,
538
- sender: { name: message.to, id: message.to },
539
- previousTimestamp,
540
- envelope: envelopeOptions,
541
- });
542
-
543
- // 构建完整的 ctx
544
- const finalized = pluginRuntime.channel.reply.finalizeInboundContext({
545
- Body: body,
546
- BodyForAgent: bodyText,
547
- RawBody: JSON.stringify(message),
548
- CommandBody: message.text,
549
- From: message.from,
550
- To: message.to,
551
- SessionKey: sessionKey,
552
- AccountId: accountId,
553
- ChatType: message.chatType,
554
- ConversationLabel: fromLabel,
555
- Provider: OPENCLAW_WORKCLAW_CHANNEL,
556
- Surface: "openclaw-workclaw_dm",
557
- MessageSid: message.messageId,
558
- Timestamp: message.timestamp,
559
- OriginatingChannel: OPENCLAW_WORKCLAW_CHANNEL,
560
- OriginatingTo: message.to,
561
- // 附件媒体信息(供 skill 读取本地文件)
562
- MediaPath: mediaUrls[0] || undefined,
563
- MediaUrl: mediaUrls[0] || undefined,
564
- MediaUrls: mediaUrls.length > 0 ? mediaUrls : undefined,
565
- MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
566
- });
567
-
568
- // 记录 session(需要在 dispatchReplyWithBufferedBlockDispatcher 之前调用)
569
- // 这样 OpenClaw 才能在工具执行时正确关联 session
570
- if (sessionKey && recordSession) {
571
- try {
572
- await pluginRuntime.channel.session.recordInboundSession({
573
- storePath,
574
- sessionKey: finalized.SessionKey || sessionKey,
575
- ctx: finalized,
576
- updateLastRoute: {
577
- sessionKey,
578
- channel: OPENCLAW_WORKCLAW_CHANNEL,
579
- to: message.to,
580
- accountId,
581
- },
582
- onRecordError: (err: unknown) => {
583
- log?.error?.(`[Session] recordInboundSession failed: ${String(err)}`);
584
- },
585
- });
586
- log?.info?.(`[Session] Recorded session for key=${sessionKey}`);
587
- } catch (err) {
588
- log?.warn?.(`[Session] recordInboundSession error: ${String(err)}`);
589
- }
590
- }
591
-
592
- return finalized;
593
- }
594
-
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import https from "node:https";
5
+ import http from "node:http";
6
+ /** Channel/plugin name constant */
7
+ export const OPENCLAW_WORKCLAW_CHANNEL = "openclaw-workclaw";
8
+ export function parseInboundMessage(data, allowRawJsonPayload) {
9
+ let input = {};
10
+ try {
11
+ input = data ? JSON.parse(data) : {};
12
+ }
13
+ catch {
14
+ // Not JSON, treat as plain text
15
+ }
16
+ const text = typeof input.text === "string"
17
+ ? input.text
18
+ : typeof input.message === "string"
19
+ ? input.message
20
+ : typeof input.body === "string"
21
+ ? input.body
22
+ : data;
23
+ const to = String(input.to ?? input.chatId ?? input.target ?? "");
24
+ const from = String(input.from ?? input.senderId ?? input.userId ?? "");
25
+ const chatType = String(input.chatType || "").toLowerCase() === "group" ? "group" : "dm";
26
+ const messageId = String(input.messageId ?? input.id ?? "");
27
+ const rawPayload = allowRawJsonPayload ? JSON.stringify(input ?? {}) : data;
28
+ return {
29
+ text,
30
+ to,
31
+ from,
32
+ chatType,
33
+ messageId,
34
+ rawPayload,
35
+ };
36
+ }
37
+ export function parseWorkClawMessage(data, log) {
38
+ //{"specVersion":"1.0","type":"EVENT","metadata":{"time":"1773749163831","event":"INIT_AGENT","contentType":"application/json"},"data":"\"12557533957824965\""}
39
+ let input = {};
40
+ try {
41
+ input = data ? JSON.parse(data) : {};
42
+ }
43
+ catch {
44
+ log?.info?.(`Failed to parse message data=${data}`);
45
+ return null;
46
+ }
47
+ // Handle plain text ping
48
+ if (typeof input === "string" && input.toLowerCase() === "ping") {
49
+ return {
50
+ type: "ping",
51
+ pongData: input,
52
+ };
53
+ }
54
+ const envelope = input && typeof input === "object" ? input : { data: input };
55
+ const topic = envelope?.metadata?.topic;
56
+ const type = String(envelope?.type || "").trim().toUpperCase();
57
+ const topicLower = String(topic || "").trim().toLowerCase();
58
+ if (type === "INIT_AGENT") {
59
+ let parsedData = envelope?.data;
60
+ if (typeof parsedData === "string") {
61
+ try {
62
+ parsedData = JSON.parse(parsedData);
63
+ }
64
+ catch (e) {
65
+ // 解析失败,保持原样
66
+ }
67
+ }
68
+ return {
69
+ type: "init_agent",
70
+ eventData: parsedData,
71
+ };
72
+ }
73
+ // Handle SYSTEM messages
74
+ if (type === "SYSTEM") {
75
+ if (topicLower === "ping") {
76
+ return {
77
+ type: "ping",
78
+ pongData: envelope?.data,
79
+ };
80
+ }
81
+ if (topicLower === "disconnect") {
82
+ return {
83
+ type: "disconnect",
84
+ };
85
+ }
86
+ // Unknown system message type, ignore
87
+ return {
88
+ type: "ignored",
89
+ };
90
+ }
91
+ // Handle EVENT messages (AGENT_CREATED, AGENT_UPDATED, AGENT_DELETED, TOOLS_LIST, SKILLS_LIST, INIT_AGENT)
92
+ if (type === "EVENT") {
93
+ const eventType = String(envelope?.metadata?.event || "").trim().toUpperCase();
94
+ // 解析 data 字段(可能是 JSON 字符串)
95
+ let parsedData = envelope?.data;
96
+ if (typeof parsedData === "string") {
97
+ try {
98
+ parsedData = JSON.parse(parsedData);
99
+ }
100
+ catch (e) {
101
+ // 解析失败,保持原样
102
+ }
103
+ }
104
+ if (eventType === "AGENT_CREATED") {
105
+ return {
106
+ type: "agent_created",
107
+ eventData: parsedData,
108
+ };
109
+ }
110
+ if (eventType === "AGENT_UPDATED") {
111
+ return {
112
+ type: "agent_updated",
113
+ eventData: parsedData,
114
+ };
115
+ }
116
+ if (eventType === "AGENT_DELETED") {
117
+ return {
118
+ type: "agent_deleted",
119
+ eventData: parsedData,
120
+ };
121
+ }
122
+ if (eventType === "TOOLS_LIST") {
123
+ return {
124
+ type: "tools_list",
125
+ eventData: parsedData,
126
+ };
127
+ }
128
+ if (eventType === "SKILLS_LIST") {
129
+ return {
130
+ type: "skills_list",
131
+ eventData: parsedData,
132
+ };
133
+ }
134
+ if (eventType === "INIT_AGENT") {
135
+ return {
136
+ type: "init_agent",
137
+ eventData: parsedData,
138
+ };
139
+ }
140
+ if (eventType === "SKILL_DO_REMIND") {
141
+ const eventTopic = String(parsedData?.dotype || "").toLowerCase();
142
+ return {
143
+ type: "skills_event",
144
+ eventData: {
145
+ topic: "skills/" + eventTopic,
146
+ requestId: "",
147
+ callbackUrl: "",
148
+ authToken: "",
149
+ data: parsedData,
150
+ },
151
+ };
152
+ }
153
+ // Unknown event type, ignore
154
+ return {
155
+ type: "ignored",
156
+ };
157
+ }
158
+ // Only process CALLBACK type with AGENT_MESSAGE topic
159
+ if (type !== "CALLBACK" || String(topic || "").trim().toUpperCase() !== "AGENT_MESSAGE") {
160
+ return {
161
+ type: "ignored",
162
+ };
163
+ }
164
+ // 解析 data 字段(可能是 JSON 字符串)
165
+ let payload = envelope?.data || {};
166
+ if (typeof payload === "string") {
167
+ try {
168
+ payload = JSON.parse(payload);
169
+ }
170
+ catch (e) {
171
+ // 解析失败,保持原样
172
+ }
173
+ }
174
+ const text = typeof payload?.message?.content === "string"
175
+ ? payload.message.content
176
+ : typeof payload?.message === "string"
177
+ ? payload.message
178
+ : "";
179
+ // 判断文件是否为图片
180
+ function isImageFile(url) {
181
+ const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'];
182
+ const lowerUrl = url.toLowerCase();
183
+ return imageExtensions.some(ext => lowerUrl.endsWith(ext));
184
+ }
185
+ // 解析 fileUrl 列表到 attachments(供 SDK 和 AI 使用)
186
+ const fileUrlList = Array.isArray(payload?.fileUrl) ? payload.fileUrl : [];
187
+ const attachments = fileUrlList.map((url) => ({
188
+ url,
189
+ fileId: payload?.fileId ? String(payload.fileId) : '',
190
+ type: isImageFile(url) ? 'image' : 'file',
191
+ }));
192
+ return {
193
+ type: "agent_message",
194
+ message: {
195
+ text,
196
+ userId: String(payload?.userId ?? ""),
197
+ openConversationId: String(payload?.conversationId ?? ""),
198
+ messageId: String(payload?.msgId ?? ""),
199
+ agentId: payload?.agentId,
200
+ attachments: attachments.length > 0 ? attachments : undefined,
201
+ },
202
+ };
203
+ }
204
+ /**
205
+ * 从 URL 扩展名判断媒体类型
206
+ */
207
+ function detectMediaType(url) {
208
+ const lower = url.toLowerCase();
209
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png")
210
+ || lower.endsWith(".gif") || lower.endsWith(".webp") || lower.endsWith(".bmp")
211
+ || lower.endsWith(".svg") || lower.endsWith(".ico")) {
212
+ return "image";
213
+ }
214
+ if (lower.endsWith(".mp3") || lower.endsWith(".wav") || lower.endsWith(".amr")
215
+ || lower.endsWith(".m4a") || lower.endsWith(".ogg")) {
216
+ return "audio";
217
+ }
218
+ if (lower.endsWith(".mp4") || lower.endsWith(".avi") || lower.endsWith(".mov")
219
+ || lower.endsWith(".mkv") || lower.endsWith(".webm")) {
220
+ return "video";
221
+ }
222
+ if (lower.endsWith(".pdf"))
223
+ return "application/pdf";
224
+ if (lower.endsWith(".docx"))
225
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
226
+ if (lower.endsWith(".xlsx"))
227
+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
228
+ if (lower.endsWith(".pptx"))
229
+ return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
230
+ if (lower.endsWith(".doc"))
231
+ return "application/msword";
232
+ if (lower.endsWith(".xls"))
233
+ return "application/vnd.ms-excel";
234
+ if (lower.endsWith(".ppt"))
235
+ return "application/vnd.ms-powerpoint";
236
+ if (lower.endsWith(".txt"))
237
+ return "text/plain";
238
+ if (lower.endsWith(".zip"))
239
+ return "application/zip";
240
+ if (lower.endsWith(".rar"))
241
+ return "application/x-rar-compressed";
242
+ return "application/octet-stream";
243
+ }
244
+ /**
245
+ * 从 URL 扩展名获取人类可读的类型标签
246
+ */
247
+ function getMediaTypeLabel(url) {
248
+ const lower = url.toLowerCase();
249
+ if (lower.endsWith(".pdf"))
250
+ return "PDF";
251
+ if (lower.endsWith(".docx"))
252
+ return "Word";
253
+ if (lower.endsWith(".doc"))
254
+ return "Word";
255
+ if (lower.endsWith(".xlsx"))
256
+ return "Excel";
257
+ if (lower.endsWith(".xls"))
258
+ return "Excel";
259
+ if (lower.endsWith(".pptx"))
260
+ return "PowerPoint";
261
+ if (lower.endsWith(".ppt"))
262
+ return "PowerPoint";
263
+ if (lower.endsWith(".txt"))
264
+ return "文本";
265
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg"))
266
+ return "JPG图片";
267
+ if (lower.endsWith(".png"))
268
+ return "PNG图片";
269
+ if (lower.endsWith(".gif"))
270
+ return "GIF图片";
271
+ if (lower.endsWith(".webp"))
272
+ return "WebP图片";
273
+ if (lower.endsWith(".mp3"))
274
+ return "音频";
275
+ if (lower.endsWith(".wav"))
276
+ return "音频";
277
+ if (lower.endsWith(".mp4"))
278
+ return "视频";
279
+ if (lower.endsWith(".zip") || lower.endsWith(".rar"))
280
+ return "压缩包";
281
+ return "文件";
282
+ }
283
+ /**
284
+ * 下载文件到本地下载目录(按 accountId/peerId 隔离),返回本地路径
285
+ */
286
+ async function downloadFileToLocal(url, accountId, peerId, log) {
287
+ const downloadsDir = path.join(os.homedir(), ".openclaw", "media", "workclaw", "downloads", accountId, peerId);
288
+ try {
289
+ await fs.mkdir(downloadsDir, { recursive: true });
290
+ }
291
+ catch { }
292
+ const urlObj = new URL(url);
293
+ const fileName = path.basename(urlObj.pathname) || "file";
294
+ const ext = path.extname(fileName);
295
+ const stem = path.basename(fileName, ext);
296
+ const localFileName = `${stem}_${Date.now()}${ext}`;
297
+ const localFilePath = path.join(downloadsDir, localFileName);
298
+ return new Promise((resolve) => {
299
+ const client = url.startsWith("https:") ? https : http;
300
+ const req = client.get(url, (res) => {
301
+ if (res.statusCode !== 200) {
302
+ log?.warn?.(`downloadFile: HTTP ${res.statusCode} for ${url}`);
303
+ resolve(null);
304
+ return;
305
+ }
306
+ const chunks = [];
307
+ res.on("data", (chunk) => chunks.push(chunk));
308
+ res.on("end", async () => {
309
+ try {
310
+ const buffer = Buffer.concat(chunks);
311
+ await fs.writeFile(localFilePath, buffer);
312
+ log?.info?.(`downloadFile: saved ${buffer.length} bytes -> ${localFilePath}`);
313
+ resolve(localFilePath);
314
+ }
315
+ catch (err) {
316
+ log?.error?.(`downloadFile: write failed: ${String(err)}`);
317
+ resolve(null);
318
+ }
319
+ });
320
+ res.on("error", (err) => {
321
+ log?.error?.(`downloadFile: read error: ${String(err)}`);
322
+ resolve(null);
323
+ });
324
+ });
325
+ req.on("error", (err) => {
326
+ log?.error?.(`downloadFile: request error: ${String(err)}`);
327
+ resolve(null);
328
+ });
329
+ req.setTimeout(30000, () => {
330
+ req.destroy();
331
+ log?.warn?.(`downloadFile: timeout for ${url}`);
332
+ resolve(null);
333
+ });
334
+ });
335
+ }
336
+ /**
337
+ * Build inbound context for WorkClaw channel.
338
+ *
339
+ * When pluginRuntime is provided, performs full session handling:
340
+ * - resolveStorePath, readSessionUpdatedAt, formatInboundEnvelope
341
+ * - finalizeInboundContext, recordInboundSession
342
+ *
343
+ * @param message - The inbound message
344
+ * @param accountId - Account ID
345
+ * @param config - Account config (WorkclawConfig)
346
+ * @param agentId - Target agent ID (optional)
347
+ * @param pluginRuntime - OpenClaw plugin runtime (optional, enables full session handling)
348
+ * @param recordSession - Whether to record session (default true)
349
+ * @param log - Optional logger
350
+ */
351
+ export async function buildInboundContext(message, accountId, config, agentId, pluginRuntime, recordSession = true, log) {
352
+ // 尝试从 rawPayload 中提取已有的 sessionKey(新建话题时 openclaw 会生成新的 session)
353
+ let existingSessionKey;
354
+ try {
355
+ const rawPayload = JSON.parse(message.rawPayload);
356
+ existingSessionKey = rawPayload.sessionKey;
357
+ }
358
+ catch {
359
+ // ignore
360
+ }
361
+ const peerId = message.from;
362
+ const computedSessionKey = existingSessionKey
363
+ || (agentId && agentId !== "main"
364
+ ? `agent:${agentId}:openclaw-workclaw:${accountId}:direct:${peerId}`
365
+ : undefined);
366
+ const sessionKey = computedSessionKey || (agentId && agentId !== "main"
367
+ ? `agent:${agentId}:openclaw-workclaw:${accountId}:direct:${peerId}`
368
+ : undefined);
369
+ // Basic context (used as base for both paths)
370
+ // parseWorkClawMessage 已将 fileUrl 列表追加到 message.text 中
371
+ const result = {
372
+ Body: message.text,
373
+ BodyForAgent: message.text,
374
+ RawBody: JSON.stringify(message),
375
+ From: message.from,
376
+ To: message.to,
377
+ ChatType: message.chatType,
378
+ Provider: OPENCLAW_WORKCLAW_CHANNEL,
379
+ Surface: OPENCLAW_WORKCLAW_CHANNEL,
380
+ Timestamp: message.timestamp,
381
+ AccountId: accountId,
382
+ AgentId: agentId,
383
+ MessageSid: message.messageId,
384
+ OriginatingChannel: OPENCLAW_WORKCLAW_CHANNEL,
385
+ OriginatingTo: message.to,
386
+ };
387
+ if (sessionKey) {
388
+ result.SessionKey = sessionKey;
389
+ }
390
+ // If no pluginRuntime provided, return basic context without session recording
391
+ if (!pluginRuntime) {
392
+ return result;
393
+ }
394
+ // Full session handling path
395
+ const storePath = pluginRuntime.channel.session.resolveStorePath(config.session?.store, { agentId });
396
+ log?.info?.(`[Session] storePath=${storePath}, agentId=${agentId}, sessionKey=${sessionKey}`);
397
+ // 获取 envelope 格式选项
398
+ const envelopeOptions = pluginRuntime.channel.reply.resolveEnvelopeFormatOptions(config);
399
+ // 获取上次的 session 更新时间
400
+ const previousTimestamp = pluginRuntime.channel.session.readSessionUpdatedAt({
401
+ storePath,
402
+ sessionKey: sessionKey,
403
+ });
404
+ log?.info?.(`[Session] previousTimestamp=${previousTimestamp}`);
405
+ // 处理附件:下载 fileUrl 到本地,并收集媒体信息
406
+ let mediaUrls = [];
407
+ let mediaTypes = [];
408
+ let bodyText = message.text;
409
+ if (message.attachments && message.attachments.length > 0) {
410
+ log?.info?.(`[Attachments] Downloading ${message.attachments.length} files...`);
411
+ // 并行下载所有附件
412
+ const downloadResults = await Promise.all(message.attachments.map(async (att) => {
413
+ const localPath = await downloadFileToLocal(att.url, accountId, message.from, log);
414
+ const mediaType = detectMediaType(att.url);
415
+ const typeLabel = getMediaTypeLabel(att.url);
416
+ return { att, localPath, mediaType, typeLabel };
417
+ }));
418
+ // 收集下载成功的文件信息(MediaUrls SDK 用于显示 [media attached])
419
+ for (const { att, localPath, mediaType } of downloadResults) {
420
+ if (localPath) {
421
+ // 将绝对路径转为根相对路径(去掉 ~/.openclaw/ 前缀,转为 /.openclaw/... 形式)
422
+ // OpenClaw 的 skill 系统会 block 绝对路径(C:\...)和 ~ 路径
423
+ // 兼容 Windows 路径格式(C:\Users\用户名\.openclaw\... 或 C:\Users\用户名.openclaw\...)
424
+ const homeDir = os.homedir().replace(/\\/g, '/').trim(); // 统一用正斜杠,去除尾随空格
425
+ const normalizedLocalPath = localPath.replace(/\\/g, '/');
426
+ const relativePath = normalizedLocalPath.startsWith(homeDir + '/.openclaw/')
427
+ ? '/' + normalizedLocalPath.slice(homeDir.length + 1) // 用 / 开头表示根相对路径
428
+ : normalizedLocalPath;
429
+ mediaUrls.push(relativePath);
430
+ mediaTypes.push(mediaType);
431
+ log?.info?.(`[Attachments] Downloaded: ${relativePath}`);
432
+ }
433
+ else {
434
+ log?.warn?.(`[Attachments] Failed to download: ${att.url}`);
435
+ }
436
+ }
437
+ log?.info?.(`[Attachments] Downloaded ${mediaUrls.length}/${message.attachments.length} files`);
438
+ }
439
+ const fromLabel = message.to;
440
+ const body = pluginRuntime.channel.reply.formatInboundEnvelope({
441
+ channel: OPENCLAW_WORKCLAW_CHANNEL,
442
+ from: fromLabel,
443
+ timestamp: message.timestamp,
444
+ body: bodyText,
445
+ chatType: message.chatType,
446
+ sender: { name: message.to, id: message.to },
447
+ previousTimestamp,
448
+ envelope: envelopeOptions,
449
+ });
450
+ // 构建完整的 ctx
451
+ const finalized = pluginRuntime.channel.reply.finalizeInboundContext({
452
+ Body: body,
453
+ BodyForAgent: bodyText,
454
+ RawBody: JSON.stringify(message),
455
+ CommandBody: message.text,
456
+ From: message.from,
457
+ To: message.to,
458
+ SessionKey: sessionKey,
459
+ AccountId: accountId,
460
+ ChatType: message.chatType,
461
+ ConversationLabel: fromLabel,
462
+ Provider: OPENCLAW_WORKCLAW_CHANNEL,
463
+ Surface: "openclaw-workclaw_dm",
464
+ MessageSid: message.messageId,
465
+ Timestamp: message.timestamp,
466
+ OriginatingChannel: OPENCLAW_WORKCLAW_CHANNEL,
467
+ OriginatingTo: message.to,
468
+ // 附件媒体信息(供 skill 读取本地文件)
469
+ MediaPath: mediaUrls[0] || undefined,
470
+ MediaUrl: mediaUrls[0] || undefined,
471
+ MediaUrls: mediaUrls.length > 0 ? mediaUrls : undefined,
472
+ MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
473
+ });
474
+ // 记录 session(需要在 dispatchReplyWithBufferedBlockDispatcher 之前调用)
475
+ // 这样 OpenClaw 才能在工具执行时正确关联 session
476
+ if (sessionKey && recordSession) {
477
+ try {
478
+ await pluginRuntime.channel.session.recordInboundSession({
479
+ storePath,
480
+ sessionKey: finalized.SessionKey || sessionKey,
481
+ ctx: finalized,
482
+ updateLastRoute: {
483
+ sessionKey,
484
+ channel: OPENCLAW_WORKCLAW_CHANNEL,
485
+ to: message.to,
486
+ accountId,
487
+ },
488
+ onRecordError: (err) => {
489
+ log?.error?.(`[Session] recordInboundSession failed: ${String(err)}`);
490
+ },
491
+ });
492
+ log?.info?.(`[Session] Recorded session for key=${sessionKey}`);
493
+ }
494
+ catch (err) {
495
+ log?.warn?.(`[Session] recordInboundSession error: ${String(err)}`);
496
+ }
497
+ }
498
+ return finalized;
499
+ }