@workclaw/openclaw-workclaw 1.0.201 → 1.0.202

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