@workclaw/openclaw-workclaw 1.0.17 → 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 (147) hide show
  1. package/README.md +364 -325
  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/dist/src/channel.js +198 -0
  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/dist/src/gateway/agent-handlers.js +433 -0
  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/dist/src/gateway/message-context.js +499 -0
  32. package/dist/src/gateway/message-dispatcher.d.ts +19 -0
  33. package/dist/src/gateway/message-dispatcher.js +512 -0
  34. package/dist/src/gateway/reconnect.d.ts +27 -0
  35. package/dist/src/gateway/reconnect.js +206 -0
  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/dist/src/outbound/workclaw-sender.js +95 -0
  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/dist/src/send.d.ts +1 -0
  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/dist/src/types.d.ts +39 -0
  99. package/dist/src/types.js +1 -0
  100. package/dist/src/utils/content.d.ts +15 -0
  101. package/dist/src/utils/content.js +38 -0
  102. package/openclaw.plugin.json +1 -0
  103. package/package.json +62 -42
  104. package/skills/openclaw-workclaw-cron/SKILL.md +45 -28
  105. package/index.ts +0 -302
  106. package/src/accounts.ts +0 -287
  107. package/src/api/accounts-api.ts +0 -157
  108. package/src/api/prompts-api.ts +0 -123
  109. package/src/api/session-api.ts +0 -247
  110. package/src/api/skills-api.ts +0 -74
  111. package/src/api/workspace.ts +0 -43
  112. package/src/channel.ts +0 -227
  113. package/src/config-schema.ts +0 -110
  114. package/src/connection/workclaw-client.ts +0 -656
  115. package/src/gateway/agent-handlers.ts +0 -557
  116. package/src/gateway/config-writer.ts +0 -311
  117. package/src/gateway/message-context.ts +0 -422
  118. package/src/gateway/message-dispatcher.ts +0 -601
  119. package/src/gateway/reconnect.ts +0 -149
  120. package/src/gateway/skills-handler.ts +0 -805
  121. package/src/gateway/skills-list-handler.ts +0 -332
  122. package/src/gateway/tools-list-handler.ts +0 -162
  123. package/src/gateway/workclaw-gateway.ts +0 -525
  124. package/src/media/upload.ts +0 -168
  125. package/src/outbound/index.ts +0 -183
  126. package/src/outbound/workclaw-sender.ts +0 -157
  127. package/src/runtime.ts +0 -400
  128. package/src/send.ts +0 -1
  129. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  130. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -176
  131. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  132. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  133. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  134. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  135. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  136. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  137. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  138. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  139. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -197
  140. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  141. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  142. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  143. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  144. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  145. package/src/types.ts +0 -60
  146. package/src/utils/content.ts +0 -40
  147. package/tsconfig.json +0 -11
@@ -0,0 +1,499 @@
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
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Message Dispatcher - handles all WorkClaw WebSocket message types
3
+ */
4
+ import type { ResolvedWorkclawAccount, WorkClawBaseConfig, WorkClawAccountConfig } from "../types.js";
5
+ export interface MessageDispatcherContext {
6
+ accountId: string;
7
+ account: ResolvedWorkclawAccount;
8
+ cfg: any;
9
+ baseConfig: WorkClawBaseConfig;
10
+ accountConfig: WorkClawAccountConfig;
11
+ log?: {
12
+ info?: (msg: string) => void;
13
+ warn?: (msg: string) => void;
14
+ error?: (msg: string) => void;
15
+ debug?: (msg: string) => void;
16
+ };
17
+ scheduleReconnect: () => void;
18
+ }
19
+ export declare function dispatchWorkclawMessage(data: string, ctx: MessageDispatcherContext): Promise<void>;