@workclaw/openclaw-workclaw 1.0.18 → 1.0.20

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