@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,615 +0,0 @@
1
- /**
2
- * Skills 事件处理器
3
- * 处理云端下发的 skills 相关 EVENT 消息
4
- * 通过 HTTP 回调返回结果
5
- */
6
- import { exec } from 'node:child_process';
7
- import fs from 'node:fs/promises';
8
- import http from 'node:http';
9
- import https from 'node:https';
10
- import os from 'node:os';
11
- import path from 'node:path';
12
- import { promisify } from 'node:util';
13
- const execAsync = promisify(exec);
14
- // 回调 URL 映射
15
- const TOPIC_TO_CALLBACK_URL = {
16
- 'skills/add': '/open-apis/v1/claw/do/skills/result',
17
- 'skills/update': '/open-apis/v1/claw/do/skills/result',
18
- 'skills/remove': '/open-apis/v1/claw/do/skills/result',
19
- 'skills/list': '/open-apis/v1/claw/do/skills/result',
20
- 'skills/get': '/open-apis/v1/claw/do/skills/result',
21
- 'skills/invoke': '/open-apis/v1/claw/do/skills/result',
22
- };
23
- /**
24
- * 处理 skills 事件
25
- */
26
- export async function handleSkillsEvent(eventData, token, baseUrl, appKey, log) {
27
- const { topic, data } = eventData;
28
- log?.info?.(`[SkillsHandler] Processing ${topic}, data: ${JSON.stringify(data)}`);
29
- try {
30
- let result;
31
- // 根据 topic 路由到不同的处理函数
32
- switch (topic) {
33
- case 'skills/add':
34
- result = await handleCreateSkill(data, log);
35
- break;
36
- case 'skills/update':
37
- result = await handleUpdateSkill(data, log);
38
- break;
39
- case 'skills/remove':
40
- result = await handleDeleteSkill(data, log);
41
- break;
42
- case 'skills/list':
43
- result = await handleListSkills(data, log);
44
- break;
45
- case 'skills/get':
46
- result = await handleGetSkill(data, log);
47
- break;
48
- case 'skills/invoke':
49
- result = await handleInvokeSkill(data, log);
50
- break;
51
- default:
52
- throw new Error(`Unknown topic: ${topic}`);
53
- }
54
- // 发送成功回调
55
- await sendCallback(baseUrl, topic, {
56
- userId: result.userId || '',
57
- agentId: '',
58
- appKey,
59
- agentIds: Array.isArray(result.agentIds) ? result.agentIds : (result.agentIds || 0),
60
- dotype: result.status || topic.split('/')[1],
61
- doStatus: true,
62
- doErrorMsg: '',
63
- dataList: [
64
- {
65
- typeStr: '',
66
- name: result.skillName || '',
67
- description: '',
68
- },
69
- ],
70
- }, token, log);
71
- log?.info?.(`[SkillsHandler] ${topic} completed, callback sent`);
72
- // 重启 OpenClaw 网关(仅在添加、更新、删除技能时)
73
- if (['skills/add', 'skills/update', 'skills/remove'].includes(topic)) {
74
- try {
75
- log?.info?.(`[SkillsHandler] rescan...`);
76
- await execAsync(`openclaw skills rescan`, { timeout: 2000 });
77
- await execAsync(`openclaw skills reload --force`, { timeout: 2000 });
78
- await execAsync(`openclaw skills list`, { timeout: 2000 });
79
- log?.info?.(`[SkillsHandler] OpenClaw skills rescaned successfully`);
80
- }
81
- catch (err) {
82
- log?.error?.(`[SkillsHandler] Failed to rescan OpenClaw skills: ${err.message}`);
83
- // 重启 OpenClaw 网关
84
- await execAsync(`openclaw skills restart`, { timeout: 20000 });
85
- }
86
- }
87
- }
88
- catch (err) {
89
- log?.error?.(`[SkillsHandler] ${topic} failed: ${err.message}`);
90
- // 发送失败回调
91
- await sendCallback(baseUrl, topic, {
92
- userId: '',
93
- agentId: '',
94
- agentIds: [],
95
- appKey,
96
- dotype: topic.split('/')[1],
97
- doStatus: false,
98
- doErrorMsg: err.message,
99
- dataList: [
100
- {
101
- typeStr: '',
102
- name: '',
103
- description: '',
104
- },
105
- ],
106
- }, token, log);
107
- }
108
- }
109
- /**
110
- * 发送 HTTP 回调
111
- */
112
- async function sendCallback(baseUrl, topic, response, authToken, log) {
113
- // 获取回调 URL
114
- const callbackPath = TOPIC_TO_CALLBACK_URL[topic];
115
- if (!callbackPath) {
116
- throw new Error(`No callback URL defined for topic: ${topic}`);
117
- }
118
- const callbackUrl = `${baseUrl.replace(/\/$/, '')}${callbackPath}`;
119
- const responseData = JSON.stringify(response);
120
- log?.info?.(`[SkillsHandler] Sending callback to ${callbackUrl}, data: ${responseData}`);
121
- // 准备请求头
122
- const headers = {
123
- 'Content-Type': 'application/json',
124
- };
125
- if (authToken) {
126
- headers.Authorization = authToken.startsWith('Bearer ')
127
- ? authToken
128
- : `Bearer ${authToken}`;
129
- }
130
- // 使用 AbortController 实现超时
131
- const controller = new AbortController();
132
- const timeoutId = setTimeout(() => controller.abort(), 30000);
133
- try {
134
- const res = await fetch(callbackUrl, {
135
- method: 'POST',
136
- headers,
137
- body: responseData,
138
- signal: controller.signal,
139
- });
140
- clearTimeout(timeoutId);
141
- if (!res.ok) {
142
- const errorText = await res.text();
143
- throw new Error(`HTTP ${res.status}: ${res.statusText || errorText}`);
144
- }
145
- log?.info?.(`[SkillsHandler] Callback sent successfully, status: ${res.status}`);
146
- }
147
- catch (err) {
148
- clearTimeout(timeoutId);
149
- if (err.name === 'AbortError') {
150
- log?.error?.(`[SkillsHandler] Callback timeout after 30s: ${callbackUrl}`);
151
- throw new Error('Callback timeout');
152
- }
153
- log?.error?.(`[SkillsHandler] Failed to send callback: ${err.message}`);
154
- throw err;
155
- }
156
- }
157
- /**
158
- * 从 URL 下载文件内容
159
- */
160
- async function downloadFromUrl(url, log) {
161
- return new Promise((resolve, reject) => {
162
- const client = url.startsWith('https:') ? https : http;
163
- const req = client.get(url, (res) => {
164
- if (res.statusCode !== 200) {
165
- reject(new Error(`Failed to download: HTTP ${res.statusCode}`));
166
- return;
167
- }
168
- const chunks = [];
169
- res.on('data', (chunk) => {
170
- chunks.push(chunk);
171
- });
172
- res.on('end', () => {
173
- const buffer = Buffer.concat(chunks);
174
- resolve(buffer);
175
- });
176
- });
177
- req.on('error', (err) => {
178
- reject(new Error(`Download failed: ${err.message}`));
179
- });
180
- req.setTimeout(30000, () => {
181
- req.destroy();
182
- reject(new Error('Download timeout'));
183
- });
184
- });
185
- }
186
- /**
187
- * 获取 OpenClaw 配置目录
188
- */
189
- function getOpenClawConfigDir() {
190
- const homeDir = os.homedir();
191
- return path.join(homeDir, '.openclaw');
192
- }
193
- /**
194
- * 获取 skills 目录
195
- */
196
- async function getSkillsDir(agentId, log) {
197
- const openclawDir = getOpenClawConfigDir();
198
- let skillsDir = path.join(openclawDir, 'workspace', 'skills');
199
- // 如果有 agentId,添加到对应目录
200
- if (agentId && agentId.trim()) {
201
- skillsDir = path.join(openclawDir, `workspace-${agentId}`, 'skills');
202
- }
203
- try {
204
- await fs.mkdir(skillsDir, { recursive: true });
205
- }
206
- catch (err) {
207
- log?.error?.(`[SkillsHandler] Failed to create skills directory: ${err.message}`);
208
- throw new Error(`Failed to create skills directory: ${err.message}`);
209
- }
210
- return skillsDir;
211
- }
212
- /**
213
- * 安装 skill 到 OpenClaw
214
- */
215
- async function installSkillToClaw(skillName, skillContent, agentId, log) {
216
- try {
217
- // 检测是否为 ZIP 文件(ZIP 文件以 PK 开头)
218
- const isZip = skillContent.toString('utf8', 0, 2) === 'PK';
219
- if (isZip) {
220
- log?.info?.(`[SkillsHandler] Detected ZIP file, extracting...`);
221
- // 获取 skills 目录
222
- const skillsDir = await getSkillsDir(agentId, log);
223
- // 创建以 skillName 命名的目录
224
- const skillDir = path.join(skillsDir, skillName);
225
- const tempZipPath = path.join(skillsDir, `${skillName}.zip`);
226
- try {
227
- // 创建技能目录
228
- await fs.mkdir(skillDir, { recursive: true });
229
- log?.info?.(`[SkillsHandler] Skill directory created: ${skillDir}`);
230
- // 写入临时 ZIP 文件
231
- await fs.writeFile(tempZipPath, skillContent);
232
- log?.info?.(`[SkillsHandler] Temporary ZIP file created: ${tempZipPath}`);
233
- // 解压 ZIP 文件到技能目录
234
- if (process.platform === 'win32') {
235
- // Windows 系统使用 PowerShell 解压
236
- await execAsync(`powershell -Command "Expand-Archive -Path '${tempZipPath}' -DestinationPath '${skillDir}' -Force"`);
237
- }
238
- else {
239
- // Unix-like 系统使用 unzip 命令
240
- await execAsync(`unzip -o '${tempZipPath}' -d '${skillDir}'`);
241
- }
242
- log?.info?.(`[SkillsHandler] ZIP file extracted successfully to: ${skillDir}`);
243
- // 删除临时 ZIP 文件
244
- await fs.unlink(tempZipPath);
245
- log?.info?.(`[SkillsHandler] Temporary ZIP file deleted`);
246
- return {
247
- success: true,
248
- message: `ZIP skill package ${skillName} installed successfully`,
249
- path: skillDir,
250
- };
251
- }
252
- catch (err) {
253
- log?.error?.(`[SkillsHandler] Failed to extract ZIP file: ${err.message}`);
254
- // 清理临时文件和目录
255
- try {
256
- await fs.unlink(tempZipPath);
257
- }
258
- catch { }
259
- try {
260
- await fs.rm(skillDir, { recursive: true, force: true });
261
- }
262
- catch { }
263
- return {
264
- success: false,
265
- message: `Failed to extract ZIP file: ${err.message}`,
266
- };
267
- }
268
- }
269
- // 尝试解析为 JSON
270
- let skillData;
271
- try {
272
- const jsonString = skillContent.toString('utf8');
273
- skillData = JSON.parse(jsonString);
274
- }
275
- catch (err) {
276
- return {
277
- success: false,
278
- message: `Invalid skill JSON: ${err.message}`,
279
- };
280
- }
281
- // 验证必要的字段
282
- if (!skillData.id || !skillData.name) {
283
- return {
284
- success: false,
285
- message: 'Missing required fields in skill: id, name',
286
- };
287
- }
288
- // 获取 skills 目录
289
- const skillsDir = await getSkillsDir(agentId, log);
290
- const skillFilePath = path.join(skillsDir, `${skillName}.json`);
291
- // 写入 skill 文件
292
- await fs.writeFile(skillFilePath, skillContent, 'utf-8');
293
- log?.info?.(`[SkillsHandler] Skill saved to: ${skillFilePath}`);
294
- return {
295
- success: true,
296
- message: `Skill ${skillName} installed successfully`,
297
- path: skillFilePath,
298
- };
299
- }
300
- catch (err) {
301
- return {
302
- success: false,
303
- message: `Failed to install skill: ${err.message}`,
304
- };
305
- }
306
- }
307
- /**
308
- * 创建 Skill
309
- */
310
- async function installSkillToLocations(skillName, skillContent, locations, log) {
311
- const installResults = [];
312
- for (const agentId of locations) {
313
- const installResult = await installSkillToClaw(skillName, skillContent, agentId, log);
314
- if (!installResult.success) {
315
- const error = new Error(`Failed to install skill to ${agentId ? `agent ${agentId}` : 'default location'}: ${installResult.message}`);
316
- error.code = 'INSTALL_FAILED';
317
- throw error;
318
- }
319
- installResults.push(installResult);
320
- }
321
- return installResults;
322
- }
323
- async function handleCreateSkill(data, log) {
324
- const { userId, skillName, unloadUrl, mainId } = data;
325
- const agentIds = Array.isArray(data?.agentIds) ? data.agentIds : (data?.agentIds ? [data.agentIds] : []);
326
- if (!userId || !skillName) {
327
- const error = new Error('Missing required fields: userId, skillName');
328
- error.code = 'MISSING_FIELDS';
329
- throw error;
330
- }
331
- log?.info?.(`[SkillsHandler] Creating skill: ${skillName}`);
332
- log?.info?.(`[SkillsHandler] mainId: ${mainId}`);
333
- if (agentIds.length > 0) {
334
- log?.info?.(`[SkillsHandler] Target agents: ${agentIds.join(', ')}`);
335
- }
336
- // 如果提供了 URL,从 URL 下载 skill 定义
337
- if (unloadUrl) {
338
- log?.info?.(`[SkillsHandler] Downloading skill from URL: ${unloadUrl}`);
339
- try {
340
- // 下载 skill 定义
341
- const skillContent = await downloadFromUrl(unloadUrl, log);
342
- log?.info?.(`[SkillsHandler] Downloaded skill content, length: ${skillContent.length} bytes`);
343
- // 确定安装位置
344
- const installLocations = [];
345
- // 检查 agentIds 是否只包含 mainId
346
- const hasOnlyMainId = agentIds.length === 1 && agentIds[0] === mainId;
347
- // 检查 agentIds 是否包含 mainId 和其他 id
348
- const hasMainIdAndOthers = agentIds.includes(mainId) && agentIds.length > 1;
349
- if (hasOnlyMainId) {
350
- // 如果只有 mainId,安装到默认位置
351
- log?.info?.(`[SkillsHandler] Only mainId found, installing to default location`);
352
- installLocations.push(undefined);
353
- }
354
- else if (hasMainIdAndOthers) {
355
- // 如果有 mainId 和其他 id,安装到默认位置和其他 id 位置
356
- log?.info?.(`[SkillsHandler] mainId and other agents found, installing to default location and other agents`);
357
- installLocations.push(undefined);
358
- // 添加其他 id 位置(排除 mainId)
359
- installLocations.push(...agentIds.filter(id => id !== mainId));
360
- }
361
- else if (agentIds.length > 0) {
362
- // 如果没有 mainId,安装到所有指定的 agentId 位置
363
- log?.info?.(`[SkillsHandler] No mainId found, installing to all specified agents`);
364
- installLocations.push(...agentIds);
365
- }
366
- else {
367
- // 如果没有指定智能体,安装到默认位置
368
- log?.info?.(`[SkillsHandler] No agents specified, installing to default location`);
369
- installLocations.push(undefined);
370
- }
371
- // 安装技能到所有位置
372
- const installResults = await installSkillToLocations(skillName, skillContent, installLocations, log);
373
- log?.info?.(`[SkillsHandler] Skill installed to ${installResults.length} locations`);
374
- return {
375
- userId,
376
- skillName,
377
- agentId: '',
378
- agentIds: agentIds.length > 0 ? agentIds : undefined,
379
- status: 'add',
380
- installedAt: new Date().toISOString(),
381
- };
382
- }
383
- catch (err) {
384
- log?.error?.(`[SkillsHandler] Failed to create skill from URL: ${err.message}`);
385
- throw err;
386
- }
387
- }
388
- return {
389
- userId,
390
- skillName,
391
- agentId: '',
392
- agentIds: agentIds.length > 0 ? agentIds : undefined,
393
- status: 'add',
394
- createdAt: new Date().toISOString(),
395
- };
396
- }
397
- /**
398
- * 更新 Skill
399
- */
400
- async function handleUpdateSkill(data, log) {
401
- const { id, ...updates } = data;
402
- if (!id) {
403
- const error = new Error('Missing required field: id');
404
- error.code = 'MISSING_FIELDS';
405
- throw error;
406
- }
407
- log?.info?.(`[SkillsHandler] Updating skill: ${id}`);
408
- return {
409
- id,
410
- ...updates,
411
- status: 'updated',
412
- updatedAt: new Date().toISOString(),
413
- };
414
- }
415
- /**
416
- * 删除 Skill
417
- */
418
- async function deleteSkillAtLocation(skillName, agentId, log) {
419
- try {
420
- const skillsDir = await getSkillsDir(agentId, log);
421
- const skillFilePath = path.join(skillsDir, `${skillName}.json`);
422
- const skillDirPath = path.join(skillsDir, skillName);
423
- let deleted = false;
424
- // 尝试删除技能文件
425
- try {
426
- await fs.unlink(skillFilePath);
427
- log?.info?.(`[SkillsHandler] Skill file deleted: ${skillFilePath}`);
428
- deleted = true;
429
- }
430
- catch (err) {
431
- // 文件不存在,继续尝试删除目录
432
- }
433
- // 尝试删除技能目录(ZIP 安装的技能)
434
- try {
435
- await fs.rm(skillDirPath, { recursive: true, force: true });
436
- log?.info?.(`[SkillsHandler] Skill directory deleted: ${skillDirPath}`);
437
- deleted = true;
438
- }
439
- catch (err) {
440
- // 目录不存在,继续
441
- }
442
- return deleted;
443
- }
444
- catch (err) {
445
- log?.error?.(`[SkillsHandler] Failed to delete skill at location: ${err.message}`);
446
- return false;
447
- }
448
- }
449
- async function handleDeleteSkill(data, log) {
450
- const { userId, skillName, agentIds, mainId } = data;
451
- const agentIdsList = Array.isArray(agentIds) ? agentIds : (agentIds ? [agentIds] : []);
452
- if (!skillName) {
453
- const error = new Error('Missing required field: skillName');
454
- error.code = 'MISSING_FIELDS';
455
- throw error;
456
- }
457
- log?.info?.(`[SkillsHandler] Deleting skill: ${skillName}`);
458
- log?.info?.(`[SkillsHandler] mainId: ${mainId}`);
459
- if (agentIdsList.length > 0) {
460
- log?.info?.(`[SkillsHandler] Target agents: ${agentIdsList.join(', ')}`);
461
- }
462
- try {
463
- let deleted = false;
464
- // 检查 agentIds 是否只包含 mainId
465
- const hasOnlyMainId = agentIdsList.length === 1 && agentIdsList[0] === mainId;
466
- // 检查 agentIds 是否包含 mainId 和其他 id
467
- const hasMainIdAndOthers = agentIdsList.includes(mainId) && agentIdsList.length > 1;
468
- if (hasOnlyMainId) {
469
- // 如果只有 mainId,从默认位置删除
470
- log?.info?.(`[SkillsHandler] Only mainId found, deleting from default location`);
471
- deleted = await deleteSkillAtLocation(skillName, undefined, log);
472
- }
473
- else if (hasMainIdAndOthers) {
474
- // 如果有 mainId 和其他 id,从默认位置和其他 id 位置删除
475
- log?.info?.(`[SkillsHandler] mainId and other agents found, deleting from default location and other agents`);
476
- // 从默认位置删除
477
- const defaultDeleted = await deleteSkillAtLocation(skillName, undefined, log);
478
- deleted = deleted || defaultDeleted;
479
- // 从其他 id 位置删除(排除 mainId)
480
- for (const agentId of agentIdsList) {
481
- if (agentId !== mainId) {
482
- const agentDeleted = await deleteSkillAtLocation(skillName, agentId, log);
483
- deleted = deleted || agentDeleted;
484
- }
485
- }
486
- }
487
- else if (agentIdsList.length > 0) {
488
- // 如果没有 mainId,从所有指定的 agentId 位置删除
489
- log?.info?.(`[SkillsHandler] No mainId found, deleting from all specified agents`);
490
- for (const agentId of agentIdsList) {
491
- const agentDeleted = await deleteSkillAtLocation(skillName, agentId, log);
492
- deleted = deleted || agentDeleted;
493
- }
494
- }
495
- else {
496
- // 如果没有指定智能体,从默认位置删除
497
- log?.info?.(`[SkillsHandler] No agents specified, deleting from default location`);
498
- deleted = await deleteSkillAtLocation(skillName, undefined, log);
499
- }
500
- if (!deleted) {
501
- const error = new Error(`Skill not found: ${skillName}`);
502
- error.code = 'SKILL_NOT_FOUND';
503
- throw error;
504
- }
505
- return {
506
- userId,
507
- skillName,
508
- agentId: '',
509
- agentIds: agentIdsList.length > 0 ? agentIdsList : undefined,
510
- status: 'remove',
511
- deletedAt: new Date().toISOString(),
512
- };
513
- }
514
- catch (err) {
515
- log?.error?.(`[SkillsHandler] Failed to delete skill: ${err.message}`);
516
- throw err;
517
- }
518
- }
519
- /**
520
- * 查询 Skills 列表
521
- */
522
- async function handleListSkills(data, log) {
523
- const { filter, limit = 100 } = data;
524
- log?.info?.(`[SkillsHandler] Listing skills, filter: ${filter}, limit: ${limit}`);
525
- try {
526
- // 调用 openclaw skills list 命令
527
- const { stdout } = await execAsync('openclaw skills list --json', {
528
- timeout: 10000,
529
- });
530
- let skills = [];
531
- try {
532
- const parsed = JSON.parse(stdout);
533
- skills = parsed.skills || parsed;
534
- }
535
- catch {
536
- // 解析文本输出
537
- const lines = stdout.split('\n');
538
- skills = lines
539
- .filter(line => line.trim() && !line.includes('Skills'))
540
- .map((line) => {
541
- const parts = line.split(/\s{2,}/).map(p => p.trim());
542
- if (parts.length >= 3) {
543
- return {
544
- status: parts[0]?.includes('✓') ? 'ready' : 'missing',
545
- name: parts[1],
546
- description: parts[2],
547
- source: parts[3] || 'openclaw-bundled',
548
- };
549
- }
550
- return null;
551
- })
552
- .filter((s) => s !== null);
553
- }
554
- // 应用过滤
555
- if (filter) {
556
- skills = skills.filter(s => s.status === filter);
557
- }
558
- // 应用 limit
559
- skills = skills.slice(0, limit);
560
- return {
561
- total: skills.length,
562
- skills,
563
- };
564
- }
565
- catch (err) {
566
- log?.error?.(`[SkillsHandler] Failed to list skills: ${err.message}`);
567
- // 返回空列表而不是报错
568
- return {
569
- total: 0,
570
- skills: [],
571
- };
572
- }
573
- }
574
- /**
575
- * 查询单个 Skill
576
- */
577
- async function handleGetSkill(data, log) {
578
- const { id } = data;
579
- if (!id) {
580
- const error = new Error('Missing required field: id');
581
- error.code = 'MISSING_FIELDS';
582
- throw error;
583
- }
584
- log?.info?.(`[SkillsHandler] Getting skill: ${id}`);
585
- // TODO: 实现实际的 skill 查询逻辑
586
- return {
587
- id,
588
- name: `Skill ${id}`,
589
- description: 'Skill description',
590
- status: 'ready',
591
- };
592
- }
593
- /**
594
- * 执行 Skill
595
- */
596
- async function handleInvokeSkill(data, log) {
597
- const { id, input, context } = data;
598
- if (!id) {
599
- const error = new Error('Missing required field: id');
600
- error.code = 'MISSING_FIELDS';
601
- throw error;
602
- }
603
- log?.info?.(`[SkillsHandler] Invoking skill: ${id}`);
604
- // TODO: 实现实际的 skill 执行逻辑
605
- return {
606
- id,
607
- status: 'completed',
608
- output: {
609
- result: `Skill ${id} executed successfully`,
610
- input,
611
- context,
612
- },
613
- executedAt: new Date().toISOString(),
614
- };
615
- }
@@ -1,27 +0,0 @@
1
- export interface SkillsListEvent {
2
- agentId: string | number;
3
- userId: string | number;
4
- }
5
- export interface SkillItem {
6
- typeStr: string;
7
- name: string;
8
- description: string;
9
- }
10
- export interface SkillsListCallbackPayload {
11
- userId: number;
12
- agentId: number;
13
- dataList: SkillItem[];
14
- }
15
- /**
16
- * 处理 SKILLS_LIST 事件
17
- * @param event - 事件数据
18
- * @param baseUrl - 回调基础 URL
19
- * @param token - 鉴权 token
20
- * @param log 日志对象(可选)
21
- * @param {Function} [log.info] - 信息日志函数
22
- * @param {Function} [log.error] - 错误日志函数
23
- */
24
- export declare function handleSkillsListEvent(event: SkillsListEvent, baseUrl: string, token: string, log?: {
25
- info?: (msg: string) => void;
26
- error?: (msg: string) => void;
27
- }): Promise<void>;