@workclaw/openclaw-workclaw 1.0.18 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +364 -345
  2. package/dist/api.d.ts +3 -0
  3. package/dist/api.js +3 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +263 -0
  6. package/dist/setup-entry.d.ts +2 -0
  7. package/dist/setup-entry.js +12 -0
  8. package/dist/src/accounts.d.ts +66 -0
  9. package/dist/src/accounts.js +279 -0
  10. package/dist/src/api/accounts-api.d.ts +2 -0
  11. package/dist/src/api/accounts-api.js +130 -0
  12. package/dist/src/api/prompts-api.d.ts +2 -0
  13. package/dist/src/api/prompts-api.js +103 -0
  14. package/dist/src/api/session-api.d.ts +2 -0
  15. package/dist/src/api/session-api.js +207 -0
  16. package/dist/src/api/skills-api.d.ts +2 -0
  17. package/dist/src/api/skills-api.js +64 -0
  18. package/dist/src/api/workspace.d.ts +3 -0
  19. package/dist/src/api/workspace.js +28 -0
  20. package/dist/src/channel.d.ts +11 -0
  21. package/{src/channel.ts → dist/src/channel.js} +198 -225
  22. package/dist/src/config-schema.d.ts +93 -0
  23. package/dist/src/config-schema.js +56 -0
  24. package/dist/src/connection/workclaw-client.d.ts +147 -0
  25. package/dist/src/connection/workclaw-client.js +351 -0
  26. package/dist/src/gateway/agent-handlers.d.ts +12 -0
  27. package/{src/gateway/agent-handlers.ts → dist/src/gateway/agent-handlers.js} +433 -523
  28. package/dist/src/gateway/config-writer.d.ts +71 -0
  29. package/dist/src/gateway/config-writer.js +312 -0
  30. package/dist/src/gateway/message-context.d.ts +76 -0
  31. package/{src/gateway/message-context.ts → dist/src/gateway/message-context.js} +499 -594
  32. package/dist/src/gateway/message-dispatcher.d.ts +19 -0
  33. package/{src/gateway/message-dispatcher.ts → dist/src/gateway/message-dispatcher.js} +512 -641
  34. package/dist/src/gateway/reconnect.d.ts +27 -0
  35. package/{src/gateway/reconnect.ts → dist/src/gateway/reconnect.js} +206 -253
  36. package/dist/src/gateway/skills-handler.d.ts +29 -0
  37. package/dist/src/gateway/skills-handler.js +576 -0
  38. package/dist/src/gateway/skills-list-handler.d.ts +27 -0
  39. package/dist/src/gateway/skills-list-handler.js +233 -0
  40. package/dist/src/gateway/tools-list-handler.d.ts +30 -0
  41. package/dist/src/gateway/tools-list-handler.js +101 -0
  42. package/dist/src/gateway/workclaw-gateway.d.ts +14 -0
  43. package/dist/src/gateway/workclaw-gateway.js +223 -0
  44. package/dist/src/media/upload.d.ts +13 -0
  45. package/dist/src/media/upload.js +125 -0
  46. package/dist/src/outbound/index.d.ts +36 -0
  47. package/dist/src/outbound/index.js +123 -0
  48. package/dist/src/outbound/workclaw-sender.d.ts +36 -0
  49. package/{src/outbound/workclaw-sender.ts → dist/src/outbound/workclaw-sender.js} +95 -158
  50. package/dist/src/runtime.d.ts +116 -0
  51. package/dist/src/runtime.js +374 -0
  52. package/dist/src/secret-contract-api.d.ts +4 -0
  53. package/dist/src/secret-contract-api.js +4 -0
  54. package/{src/send.ts → dist/src/send.d.ts} +1 -1
  55. package/dist/src/send.js +1 -0
  56. package/dist/src/setup-api.d.ts +3 -0
  57. package/dist/src/setup-api.js +3 -0
  58. package/dist/src/setup-core.d.ts +3 -0
  59. package/dist/src/setup-core.js +13 -0
  60. package/dist/src/setup-surface.d.ts +7 -0
  61. package/dist/src/setup-surface.js +363 -0
  62. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +93 -0
  63. package/dist/src/tools/openclaw-workclaw-cron/api/index.js +209 -0
  64. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +10 -0
  65. package/{src/tools/openclaw-workclaw-cron/index.ts → dist/src/tools/openclaw-workclaw-cron/index.js} +33 -39
  66. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +16 -0
  67. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.js +152 -0
  68. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +18 -0
  69. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.js +162 -0
  70. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +14 -0
  71. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.js +80 -0
  72. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +14 -0
  73. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.js +107 -0
  74. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +14 -0
  75. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.js +80 -0
  76. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +14 -0
  77. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.js +107 -0
  78. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +17 -0
  79. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.js +127 -0
  80. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +14 -0
  81. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.js +87 -0
  82. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +14 -0
  83. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.js +107 -0
  84. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +17 -0
  85. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.js +164 -0
  86. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +18 -0
  87. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.js +135 -0
  88. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +52 -0
  89. package/dist/src/tools/openclaw-workclaw-cron/types/index.js +4 -0
  90. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +40 -0
  91. package/dist/src/tools/openclaw-workclaw-cron/utils/index.js +122 -0
  92. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +10 -0
  93. package/{src/tools/openclaw-workclaw-system/index.ts → dist/src/tools/openclaw-workclaw-system/index.js} +15 -17
  94. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +8 -0
  95. package/dist/src/tools/openclaw-workclaw-system/src/get/index.js +64 -0
  96. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +8 -0
  97. package/dist/src/tools/openclaw-workclaw-system/src/token/index.js +78 -0
  98. package/{src/types.ts → dist/src/types.d.ts} +39 -58
  99. package/dist/src/types.js +1 -0
  100. package/dist/src/utils/content.d.ts +15 -0
  101. package/{src/utils/content.ts → dist/src/utils/content.js} +38 -35
  102. package/package.json +62 -49
  103. package/index.ts +0 -302
  104. package/setup-entry.ts +0 -6
  105. package/src/accounts.ts +0 -312
  106. package/src/api/accounts-api.ts +0 -156
  107. package/src/api/prompts-api.ts +0 -116
  108. package/src/api/session-api.ts +0 -238
  109. package/src/api/skills-api.ts +0 -72
  110. package/src/api/workspace.ts +0 -41
  111. package/src/config-schema.ts +0 -110
  112. package/src/connection/workclaw-client.ts +0 -643
  113. package/src/gateway/config-writer.ts +0 -296
  114. package/src/gateway/skills-handler.ts +0 -741
  115. package/src/gateway/skills-list-handler.ts +0 -332
  116. package/src/gateway/tools-list-handler.ts +0 -160
  117. package/src/gateway/workclaw-gateway.ts +0 -367
  118. package/src/media/upload.ts +0 -157
  119. package/src/outbound/index.ts +0 -185
  120. package/src/runtime.ts +0 -497
  121. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  122. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -177
  123. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  124. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  125. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  126. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  127. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  128. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  129. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  130. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  131. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -195
  132. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  133. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  134. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  135. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  136. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  137. package/tests/accounts.test.ts +0 -285
  138. package/tests/message-context.test.ts +0 -313
  139. package/tests/reconnect.test.ts +0 -257
  140. package/tests/workclaw-client.test.ts +0 -112
  141. package/tsconfig.json +0 -14
  142. package/vitest.config.ts +0 -8
@@ -0,0 +1,576 @@
1
+ /**
2
+ * Skills 事件处理器
3
+ * 处理云端下发的 skills 相关 EVENT 消息
4
+ * 通过 HTTP 回调返回结果
5
+ */
6
+ import { exec } from "node:child_process";
7
+ import { promisify } from "node:util";
8
+ import fs from "node:fs/promises";
9
+ import path from "node:path";
10
+ import os from "node:os";
11
+ import https from "node:https";
12
+ import http from "node:http";
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, "skills");
199
+ // 如果有 agentId,添加到对应目录
200
+ if (agentId && agentId.trim()) {
201
+ skillsDir = path.join(openclawDir, "agents", `openclaw-workclaw-${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 handleCreateSkill(data, log) {
311
+ const { userId, skillName, unloadUrl } = data;
312
+ const agentIds = Array.isArray(data?.agentIds) ? data.agentIds : (data?.agentIds ? [data.agentIds] : []);
313
+ if (!userId || !skillName) {
314
+ const error = new Error("Missing required fields: userId, skillName");
315
+ error.code = "MISSING_FIELDS";
316
+ throw error;
317
+ }
318
+ log?.info?.(`[SkillsHandler] Creating skill: ${skillName}`);
319
+ if (agentIds.length > 0) {
320
+ log?.info?.(`[SkillsHandler] Target agents: ${agentIds.join(", ")}`);
321
+ }
322
+ // 如果提供了 URL,从 URL 下载 skill 定义
323
+ if (unloadUrl) {
324
+ log?.info?.(`[SkillsHandler] Downloading skill from URL: ${unloadUrl}`);
325
+ try {
326
+ // 下载 skill 定义
327
+ const skillContent = await downloadFromUrl(unloadUrl, log);
328
+ log?.info?.(`[SkillsHandler] Downloaded skill content, length: ${skillContent.length} bytes`);
329
+ // 安装 skill 到多个智能体
330
+ const installResults = [];
331
+ for (const agentId of agentIds) {
332
+ const installResult = await installSkillToClaw(skillName, skillContent, agentId, log);
333
+ if (!installResult.success) {
334
+ const error = new Error(`Failed to install skill to agent ${agentId}: ${installResult.message}`);
335
+ error.code = "INSTALL_FAILED";
336
+ throw error;
337
+ }
338
+ installResults.push(installResult);
339
+ }
340
+ // 如果没有指定智能体,安装到默认位置
341
+ if (agentIds.length === 0) {
342
+ const installResult = await installSkillToClaw(skillName, skillContent, undefined, log);
343
+ if (!installResult.success) {
344
+ const error = new Error(installResult.message);
345
+ error.code = "INSTALL_FAILED";
346
+ throw error;
347
+ }
348
+ installResults.push(installResult);
349
+ }
350
+ log?.info?.(`[SkillsHandler] Skill installed to ${installResults.length} locations`);
351
+ return {
352
+ userId,
353
+ skillName,
354
+ agentId: "",
355
+ agentIds: agentIds.length > 0 ? agentIds : undefined,
356
+ status: "add",
357
+ installedAt: new Date().toISOString(),
358
+ };
359
+ }
360
+ catch (err) {
361
+ log?.error?.(`[SkillsHandler] Failed to create skill from URL: ${err.message}`);
362
+ throw err;
363
+ }
364
+ }
365
+ return {
366
+ userId,
367
+ skillName,
368
+ agentId: "",
369
+ agentIds: agentIds.length > 0 ? agentIds : undefined,
370
+ status: "add",
371
+ createdAt: new Date().toISOString(),
372
+ };
373
+ }
374
+ /**
375
+ * 更新 Skill
376
+ */
377
+ async function handleUpdateSkill(data, log) {
378
+ const { id, ...updates } = data;
379
+ if (!id) {
380
+ const error = new Error("Missing required field: id");
381
+ error.code = "MISSING_FIELDS";
382
+ throw error;
383
+ }
384
+ log?.info?.(`[SkillsHandler] Updating skill: ${id}`);
385
+ return {
386
+ id,
387
+ ...updates,
388
+ status: "updated",
389
+ updatedAt: new Date().toISOString(),
390
+ };
391
+ }
392
+ /**
393
+ * 删除 Skill
394
+ */
395
+ async function handleDeleteSkill(data, log) {
396
+ const { userId, skillName, agentIds } = data;
397
+ const agentIdsList = Array.isArray(agentIds) ? agentIds : (agentIds ? [agentIds] : []);
398
+ if (!skillName) {
399
+ const error = new Error("Missing required field: skillName");
400
+ error.code = "MISSING_FIELDS";
401
+ throw error;
402
+ }
403
+ log?.info?.(`[SkillsHandler] Deleting skill: ${skillName}`);
404
+ if (agentIdsList.length > 0) {
405
+ log?.info?.(`[SkillsHandler] Target agents: ${agentIdsList.join(", ")}`);
406
+ }
407
+ try {
408
+ let deleted = false;
409
+ // 从多个智能体中删除技能
410
+ for (const agentId of agentIdsList) {
411
+ // 获取技能目录
412
+ const skillsDir = await getSkillsDir(agentId, log);
413
+ // 检查技能文件和目录
414
+ const skillFilePath = path.join(skillsDir, `${skillName}.json`);
415
+ const skillDirPath = path.join(skillsDir, skillName);
416
+ // 尝试删除技能文件
417
+ try {
418
+ await fs.unlink(skillFilePath);
419
+ log?.info?.(`[SkillsHandler] Skill file deleted: ${skillFilePath}`);
420
+ deleted = true;
421
+ }
422
+ catch (err) {
423
+ // 文件不存在,继续尝试删除目录
424
+ }
425
+ // 尝试删除技能目录(ZIP 安装的技能)
426
+ try {
427
+ await fs.rm(skillDirPath, { recursive: true, force: true });
428
+ log?.info?.(`[SkillsHandler] Skill directory deleted: ${skillDirPath}`);
429
+ deleted = true;
430
+ }
431
+ catch (err) {
432
+ // 目录不存在,继续
433
+ }
434
+ }
435
+ // 如果没有指定智能体,从默认位置删除
436
+ if (agentIdsList.length === 0) {
437
+ // 获取默认技能目录
438
+ const skillsDir = await getSkillsDir(undefined, log);
439
+ // 检查技能文件和目录
440
+ const skillFilePath = path.join(skillsDir, `${skillName}.json`);
441
+ const skillDirPath = path.join(skillsDir, skillName);
442
+ // 尝试删除技能文件
443
+ try {
444
+ await fs.unlink(skillFilePath);
445
+ log?.info?.(`[SkillsHandler] Skill file deleted: ${skillFilePath}`);
446
+ deleted = true;
447
+ }
448
+ catch (err) {
449
+ // 文件不存在,继续尝试删除目录
450
+ }
451
+ // 尝试删除技能目录(ZIP 安装的技能)
452
+ try {
453
+ await fs.rm(skillDirPath, { recursive: true, force: true });
454
+ log?.info?.(`[SkillsHandler] Skill directory deleted: ${skillDirPath}`);
455
+ deleted = true;
456
+ }
457
+ catch (err) {
458
+ // 目录不存在,继续
459
+ }
460
+ }
461
+ if (!deleted) {
462
+ const error = new Error(`Skill not found: ${skillName}`);
463
+ error.code = "SKILL_NOT_FOUND";
464
+ throw error;
465
+ }
466
+ return {
467
+ userId,
468
+ skillName,
469
+ agentId: "",
470
+ agentIds: agentIdsList.length > 0 ? agentIdsList : undefined,
471
+ status: "remove",
472
+ deletedAt: new Date().toISOString(),
473
+ };
474
+ }
475
+ catch (err) {
476
+ log?.error?.(`[SkillsHandler] Failed to delete skill: ${err.message}`);
477
+ throw err;
478
+ }
479
+ }
480
+ /**
481
+ * 查询 Skills 列表
482
+ */
483
+ async function handleListSkills(data, log) {
484
+ const { filter, limit = 100 } = data;
485
+ log?.info?.(`[SkillsHandler] Listing skills, filter: ${filter}, limit: ${limit}`);
486
+ try {
487
+ // 调用 openclaw skills list 命令
488
+ const { stdout } = await execAsync("openclaw skills list --json", {
489
+ timeout: 10000,
490
+ });
491
+ let skills = [];
492
+ try {
493
+ const parsed = JSON.parse(stdout);
494
+ skills = parsed.skills || parsed;
495
+ }
496
+ catch {
497
+ // 解析文本输出
498
+ const lines = stdout.split("\n");
499
+ skills = lines
500
+ .filter((line) => line.trim() && !line.includes("Skills"))
501
+ .map((line) => {
502
+ const parts = line.split(/\s{2,}/).map((p) => p.trim());
503
+ if (parts.length >= 3) {
504
+ return {
505
+ status: parts[0]?.includes("✓") ? "ready" : "missing",
506
+ name: parts[1],
507
+ description: parts[2],
508
+ source: parts[3] || "openclaw-bundled",
509
+ };
510
+ }
511
+ return null;
512
+ })
513
+ .filter((s) => s !== null);
514
+ }
515
+ // 应用过滤
516
+ if (filter) {
517
+ skills = skills.filter((s) => s.status === filter);
518
+ }
519
+ // 应用 limit
520
+ skills = skills.slice(0, limit);
521
+ return {
522
+ total: skills.length,
523
+ skills,
524
+ };
525
+ }
526
+ catch (err) {
527
+ log?.error?.(`[SkillsHandler] Failed to list skills: ${err.message}`);
528
+ // 返回空列表而不是报错
529
+ return {
530
+ total: 0,
531
+ skills: [],
532
+ };
533
+ }
534
+ }
535
+ /**
536
+ * 查询单个 Skill
537
+ */
538
+ async function handleGetSkill(data, log) {
539
+ const { id } = data;
540
+ if (!id) {
541
+ const error = new Error("Missing required field: id");
542
+ error.code = "MISSING_FIELDS";
543
+ throw error;
544
+ }
545
+ log?.info?.(`[SkillsHandler] Getting skill: ${id}`);
546
+ // TODO: 实现实际的 skill 查询逻辑
547
+ return {
548
+ id,
549
+ name: `Skill ${id}`,
550
+ description: "Skill description",
551
+ status: "ready",
552
+ };
553
+ }
554
+ /**
555
+ * 执行 Skill
556
+ */
557
+ async function handleInvokeSkill(data, log) {
558
+ const { id, input, context } = data;
559
+ if (!id) {
560
+ const error = new Error("Missing required field: id");
561
+ error.code = "MISSING_FIELDS";
562
+ throw error;
563
+ }
564
+ log?.info?.(`[SkillsHandler] Invoking skill: ${id}`);
565
+ // TODO: 实现实际的 skill 执行逻辑
566
+ return {
567
+ id,
568
+ status: "completed",
569
+ output: {
570
+ result: `Skill ${id} executed successfully`,
571
+ input,
572
+ context,
573
+ },
574
+ executedAt: new Date().toISOString(),
575
+ };
576
+ }
@@ -0,0 +1,27 @@
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>;