@workclaw/openclaw-workclaw 1.0.20 → 1.0.25

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