@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
@@ -0,0 +1,363 @@
1
+ import { DEFAULT_ACCOUNT_ID, formatDocsLink, patchTopLevelChannelConfigSection, } from "openclaw/plugin-sdk/setup";
2
+ import { inspectWorkclawCredentials, resolveDefaultWorkclawAccountId } from "./accounts.js";
3
+ import { doFetchJson } from "./connection/workclaw-client.js";
4
+ const channel = "openclaw-workclaw";
5
+ /**
6
+ * 规范化字符串值
7
+ */
8
+ function normalizeString(value) {
9
+ if (typeof value !== "string") {
10
+ return undefined;
11
+ }
12
+ const trimmed = value.trim();
13
+ return trimmed || undefined;
14
+ }
15
+ function trimTrailingSlash(value) {
16
+ return value.endsWith("/") ? value.slice(0, -1) : value;
17
+ }
18
+ function resolveSetupApiBases(cfg) {
19
+ const workclawCfg = cfg.channels?.["openclaw-workclaw"];
20
+ const configuredBaseUrl = normalizeString(workclawCfg?.baseUrl) ??
21
+ normalizeString(process.env.WORKCLAW_BASE_URL);
22
+ const configuredAuthBaseUrl = normalizeString(process.env.WORKCLAW_AUTH_BASE_URL);
23
+ const configuredOpenApiBaseUrl = normalizeString(process.env.WORKCLAW_OPEN_API_BASE_URL);
24
+ const defaultAuthBaseUrl = "https://workbrain.cn/backend-api";
25
+ const defaultOpenApiBaseUrl = `${defaultAuthBaseUrl}/open-apis`;
26
+ const fromBaseUrl = (() => {
27
+ if (!configuredBaseUrl) {
28
+ return null;
29
+ }
30
+ const normalized = trimTrailingSlash(configuredBaseUrl);
31
+ if (normalized.endsWith("/open-apis")) {
32
+ return {
33
+ authBaseUrl: normalized.slice(0, -"/open-apis".length),
34
+ openApiBaseUrl: normalized,
35
+ };
36
+ }
37
+ return {
38
+ authBaseUrl: normalized,
39
+ openApiBaseUrl: `${normalized}/open-apis`,
40
+ };
41
+ })();
42
+ return {
43
+ authBaseUrl: trimTrailingSlash(configuredAuthBaseUrl ?? fromBaseUrl?.authBaseUrl ?? defaultAuthBaseUrl),
44
+ openApiBaseUrl: trimTrailingSlash(configuredOpenApiBaseUrl ?? fromBaseUrl?.openApiBaseUrl ?? defaultOpenApiBaseUrl),
45
+ allowInsecureTls: workclawCfg?.allowInsecureTls,
46
+ requestTimeout: workclawCfg?.requestTimeout,
47
+ };
48
+ }
49
+ /**
50
+ * 检查 Workclaw 是否已配置
51
+ */
52
+ function isWorkclawConfigured(cfg) {
53
+ const workclawCfg = cfg.channels?.["openclaw-workclaw"];
54
+ // 检查字符串值是否已配置
55
+ const isConfigured = (value) => {
56
+ const asString = normalizeString(value);
57
+ return !!asString;
58
+ };
59
+ const topLevelConfigured = isConfigured(workclawCfg?.appKey) &&
60
+ isConfigured(workclawCfg?.appSecret);
61
+ const accountConfigured = Object.values(workclawCfg?.accounts ?? {}).some((account) => {
62
+ if (!account || typeof account !== "object") {
63
+ return false;
64
+ }
65
+ const hasOwnAppKey = Object.prototype.hasOwnProperty.call(account, "appKey");
66
+ const hasOwnAppSecret = Object.prototype.hasOwnProperty.call(account, "appSecret");
67
+ const accountAppKeyConfigured = hasOwnAppKey
68
+ ? isConfigured(account.appKey)
69
+ : isConfigured(workclawCfg?.appKey);
70
+ const accountSecretConfigured = hasOwnAppSecret
71
+ ? isConfigured(account.appSecret)
72
+ : isConfigured(workclawCfg?.appSecret);
73
+ return accountAppKeyConfigured && accountSecretConfigured;
74
+ });
75
+ return topLevelConfigured || accountConfigured;
76
+ }
77
+ /**
78
+ * 修补 Workclaw 配置
79
+ */
80
+ export function patchWorkclawConfig(cfg, accountId, patch) {
81
+ const workclawCfg = cfg.channels?.["openclaw-workclaw"];
82
+ if (accountId === DEFAULT_ACCOUNT_ID) {
83
+ return patchTopLevelChannelConfigSection({
84
+ cfg,
85
+ channel,
86
+ enabled: true,
87
+ patch,
88
+ });
89
+ }
90
+ const nextAccountPatch = {
91
+ ...workclawCfg?.accounts?.[accountId],
92
+ enabled: true,
93
+ ...patch,
94
+ };
95
+ return patchTopLevelChannelConfigSection({
96
+ cfg,
97
+ channel,
98
+ enabled: true,
99
+ patch: {
100
+ accounts: {
101
+ ...workclawCfg?.accounts,
102
+ [accountId]: nextAccountPatch,
103
+ },
104
+ },
105
+ });
106
+ }
107
+ /**
108
+ * 提示凭证帮助信息
109
+ */
110
+ async function noteWorkclawCredentialHelp(prompter) {
111
+ await prompter.note([
112
+ "智小途插件安装引导",
113
+ "",
114
+ "准备事项:",
115
+ "1. 访问 workbrain.cn 获取 App Key 和 App Secret",
116
+ "2. 确保您的账号已开通智小途服务",
117
+ "3. 准备好您的手机号(用于获取配置信息)",
118
+ "",
119
+ `文档: ${formatDocsLink("/channels/openclaw-workclaw", "智小途")}`,
120
+ ].join("\n"), "智小途配置");
121
+ }
122
+ /**
123
+ * 提示 App Key 输入
124
+ */
125
+ async function promptWorkclawAppKey(params) {
126
+ return (await params.prompter.text({
127
+ message: "智小途 App Key",
128
+ initialValue: params.initialValue,
129
+ validate: (value) => (value?.trim() ? undefined : "App Key 不能为空"),
130
+ })).trim();
131
+ }
132
+ /**
133
+ * 提示 App Secret 输入
134
+ */
135
+ async function promptWorkclawAppSecret(params) {
136
+ return (await params.prompter.text({
137
+ message: "智小途 App Secret",
138
+ initialValue: params.initialValue,
139
+ validate: (value) => (value?.trim() ? undefined : "App Secret 不能为空"),
140
+ })).trim();
141
+ }
142
+ /**
143
+ * 提示手机号输入
144
+ */
145
+ async function promptWorkclawPhone(params) {
146
+ return (await params.prompter.text({
147
+ message: "智小途手机号",
148
+ initialValue: params.initialValue,
149
+ validate: (value) => {
150
+ if (!value?.trim())
151
+ return "手机号不能为空";
152
+ if (!/^1[3-9]\d{9}$/.test(value.trim()))
153
+ return "请输入正确的手机号格式";
154
+ return undefined;
155
+ },
156
+ })).trim();
157
+ }
158
+ /**
159
+ * 通过手机号获取 agentId 和 userId
160
+ */
161
+ async function fetchAgentInfoByPhone(cfg, appKey, appSecret, phone, prompter) {
162
+ prompter.note?.("正在通过手机号获取配置信息...", "获取配置");
163
+ try {
164
+ const { authBaseUrl, openApiBaseUrl, allowInsecureTls, requestTimeout } = resolveSetupApiBases(cfg);
165
+ // 1. 获取 access token
166
+ const tokenData = await doFetchJson(`${authBaseUrl}/authen/v1/access_token/internal`, {
167
+ method: "POST",
168
+ headers: {
169
+ "Content-Type": "application/json",
170
+ },
171
+ body: JSON.stringify({
172
+ app_key: appKey,
173
+ app_secret: appSecret,
174
+ }),
175
+ }, allowInsecureTls, requestTimeout);
176
+ if (tokenData.code !== 200 || !tokenData.data?.accessToken) {
177
+ prompter.note?.(`获取 Token 失败: ${tokenData.message || "未知错误"}`, "获取配置");
178
+ return null;
179
+ }
180
+ const accessToken = tokenData.data.accessToken;
181
+ // 2. 通过手机号获取 agentId 和 userId
182
+ const agentData = await doFetchJson(`${openApiBaseUrl}/instance/local/agentInf`, {
183
+ method: "POST",
184
+ headers: {
185
+ "Content-Type": "application/json",
186
+ Authorization: `Bearer ${accessToken}`,
187
+ },
188
+ body: JSON.stringify({
189
+ appKey,
190
+ phone,
191
+ }),
192
+ }, allowInsecureTls, requestTimeout);
193
+ if (agentData.code !== 200 || !agentData.data) {
194
+ prompter.note?.(`获取配置信息失败: ${agentData.message || "未知错误"}`, "获取配置");
195
+ return null;
196
+ }
197
+ prompter.note?.(`成功获取配置信息`, "获取配置");
198
+ return {
199
+ agentId: agentData.data.agentId,
200
+ userId: agentData.data.userId,
201
+ };
202
+ }
203
+ catch (error) {
204
+ prompter.note?.(`获取配置失败: ${error.message}`, "获取配置");
205
+ return null;
206
+ }
207
+ }
208
+ /**
209
+ * 运行新应用流程
210
+ */
211
+ async function runNewAppFlow(params) {
212
+ const { prompter } = params;
213
+ let next = params.cfg;
214
+ // 1. 显示帮助信息
215
+ await noteWorkclawCredentialHelp(prompter);
216
+ // 2. 获取 App Key
217
+ const appKey = await promptWorkclawAppKey({
218
+ prompter,
219
+ initialValue: normalizeString(process.env.WORKCLAW_APP_KEY),
220
+ });
221
+ // 3. 获取 App Secret
222
+ const appSecret = await promptWorkclawAppSecret({
223
+ prompter,
224
+ initialValue: normalizeString(process.env.WORKCLAW_APP_SECRET),
225
+ });
226
+ // 4. 获取手机号(通过手机号获取 agentId 和 userId)
227
+ const phone = await promptWorkclawPhone({
228
+ prompter,
229
+ initialValue: normalizeString(process.env.WORKCLAW_PHONE),
230
+ });
231
+ // 5. 配置基础信息
232
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, {
233
+ appKey,
234
+ appSecret,
235
+ connectionMode: "websocket",
236
+ enabled: true,
237
+ });
238
+ // 6. 通过手机号获取 agentId 和 userId
239
+ const agentInfo = await fetchAgentInfoByPhone(next, appKey, appSecret, phone, prompter);
240
+ if (agentInfo) {
241
+ // 更新配置中的 agentId 和 userId
242
+ const accountConfig = {
243
+ enabled: true,
244
+ };
245
+ if (agentInfo.agentId) {
246
+ accountConfig.agentId = agentInfo.agentId;
247
+ }
248
+ if (agentInfo.userId) {
249
+ accountConfig.userId = agentInfo.userId;
250
+ }
251
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, accountConfig);
252
+ }
253
+ // 6. DM 策略固定为 open
254
+ next = patchWorkclawConfig(next, DEFAULT_ACCOUNT_ID, {
255
+ dmPolicy: "open",
256
+ allowFrom: ["*"],
257
+ });
258
+ await prompter.note("智小途配置完成!", "");
259
+ return { cfg: next };
260
+ }
261
+ /**
262
+ * 运行编辑配置流程
263
+ */
264
+ async function runEditFlow(params) {
265
+ const workclawCfg = params.cfg.channels?.["openclaw-workclaw"];
266
+ const existingAppKey = workclawCfg?.appKey;
267
+ await params.prompter.note(`当前配置的 App Key: ${existingAppKey ?? "(未配置)"}`, "智小途配置");
268
+ const useExisting = await params.prompter.confirm({
269
+ message: `使用现有的智小途配置 (App Key: ${existingAppKey})?`,
270
+ initialValue: true,
271
+ });
272
+ if (!useExisting) {
273
+ return runNewAppFlow(params);
274
+ }
275
+ await params.prompter.note("保持现有配置不变。", "");
276
+ return { cfg: params.cfg };
277
+ }
278
+ /**
279
+ * 运行凭证探测流程
280
+ */
281
+ async function runProbeFlow(params) {
282
+ const workclawCfg = params.cfg.channels?.["openclaw-workclaw"];
283
+ const resolvedCredentials = inspectWorkclawCredentials(workclawCfg);
284
+ if (resolvedCredentials) {
285
+ try {
286
+ const probeResult = await resolvedCredentials();
287
+ params.prompter.note(`智小途连接测试成功! ${probeResult.botName ? `Bot名称: ${probeResult.botName}` : ""}`, "连接测试");
288
+ }
289
+ catch {
290
+ params.prompter.note("智小途连接测试失败,请检查配置。", "连接测试");
291
+ }
292
+ }
293
+ return params.cfg;
294
+ }
295
+ export { workclawSetupAdapter } from "./setup-core.js";
296
+ export const workclawSetupWizard = {
297
+ channel,
298
+ resolveAccountIdForConfigure: ({ accountOverride, defaultAccountId, cfg }) => (typeof accountOverride === "string" && accountOverride.trim()
299
+ ? accountOverride.trim()
300
+ : undefined) ??
301
+ resolveDefaultWorkclawAccountId(cfg) ??
302
+ defaultAccountId,
303
+ resolveShouldPromptAccountIds: () => false,
304
+ status: {
305
+ configuredLabel: "已配置",
306
+ unconfiguredLabel: "需要配置",
307
+ configuredHint: "已配置",
308
+ unconfiguredHint: "需要凭证",
309
+ configuredScore: 2,
310
+ unconfiguredScore: 0,
311
+ resolveConfigured: ({ cfg }) => isWorkclawConfigured(cfg),
312
+ resolveStatusLines: async ({ cfg, configured }) => {
313
+ const workclawCfg = cfg.channels?.["openclaw-workclaw"];
314
+ const resolvedCredentials = inspectWorkclawCredentials(workclawCfg);
315
+ let probeResult = null;
316
+ if (configured && resolvedCredentials) {
317
+ try {
318
+ probeResult = await resolvedCredentials();
319
+ }
320
+ catch { }
321
+ }
322
+ if (!configured) {
323
+ return ["智小途: 需要 App Key 和 App Secret"];
324
+ }
325
+ if (probeResult?.ok) {
326
+ return [`智小途: 已连接${probeResult.botName ? ` (${probeResult.botName})` : ""}`];
327
+ }
328
+ return ["智小途: 已配置 (连接未验证)"];
329
+ },
330
+ },
331
+ prepare: async ({ cfg, credentialValues }) => {
332
+ const alreadyConfigured = isWorkclawConfigured(cfg);
333
+ if (alreadyConfigured) {
334
+ return {
335
+ credentialValues: { ...credentialValues, _flow: "edit" },
336
+ };
337
+ }
338
+ return {
339
+ credentialValues: { ...credentialValues, _flow: "new" },
340
+ };
341
+ },
342
+ credentials: [],
343
+ finalize: async ({ cfg, prompter, options, credentialValues }) => {
344
+ const flow = credentialValues._flow ?? "new";
345
+ if (flow === "edit") {
346
+ const result = await runEditFlow({ cfg, prompter, options });
347
+ if (result === null) {
348
+ return { cfg };
349
+ }
350
+ cfg = result.cfg;
351
+ }
352
+ else {
353
+ cfg = (await runNewAppFlow({ cfg, prompter, options })).cfg;
354
+ }
355
+ await runProbeFlow({ cfg, prompter });
356
+ return { cfg };
357
+ },
358
+ disable: (cfg) => patchTopLevelChannelConfigSection({
359
+ cfg,
360
+ channel,
361
+ patch: { enabled: false },
362
+ }),
363
+ };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 智小途定时任务工具 - 后端接口封装
3
+ */
4
+ import type { OpenClawPluginApi } from 'openclaw/plugin-sdk';
5
+ /**
6
+ * 调用后端 API 的通用方法
7
+ * @param api - OpenClaw API 实例
8
+ * @param accountId - 账户 ID
9
+ * @param path - API 路径
10
+ * @param payload - 请求体
11
+ * @param options - 可选配置
12
+ * @returns 接口调用结果
13
+ */
14
+ export declare function callBackendApi(api: OpenClawPluginApi, accountId: string, path: string, payload: Record<string, any>, options?: {
15
+ maxRetries?: number;
16
+ }): Promise<{
17
+ success: boolean;
18
+ data?: any;
19
+ error?: string;
20
+ attempts?: number;
21
+ }>;
22
+ /**
23
+ * 调用新增定时任务接口
24
+ */
25
+ export declare function callCronJobAdd(api: OpenClawPluginApi, accountId: string, payload: {
26
+ jobId: string;
27
+ name: string;
28
+ kind: 'cron';
29
+ expr?: string;
30
+ message: string;
31
+ messageId?: string;
32
+ }): Promise<{
33
+ success: boolean;
34
+ data?: any;
35
+ error?: string;
36
+ }>;
37
+ /**
38
+ * 调用删除定时任务接口
39
+ */
40
+ export declare function callCronJobRemove(api: OpenClawPluginApi, accountId: string, payload: {
41
+ jobId: string;
42
+ }): Promise<{
43
+ success: boolean;
44
+ data?: any;
45
+ error?: string;
46
+ }>;
47
+ /**
48
+ * 调用更新定时任务接口
49
+ */
50
+ export declare function callCronJobUpdate(api: OpenClawPluginApi, accountId: string, payload: {
51
+ jobId: string;
52
+ name: string;
53
+ kind: 'cron';
54
+ expr?: string;
55
+ message: string;
56
+ agentId?: string;
57
+ }): Promise<{
58
+ success: boolean;
59
+ data?: any;
60
+ error?: string;
61
+ }>;
62
+ /**
63
+ * 调用启用定时任务接口
64
+ */
65
+ export declare function callCronJobEnabled(api: OpenClawPluginApi, accountId: string, payload: {
66
+ jobId: string;
67
+ }): Promise<{
68
+ success: boolean;
69
+ data?: any;
70
+ error?: string;
71
+ }>;
72
+ /**
73
+ * 调用禁用定时任务接口
74
+ */
75
+ export declare function callCronJobDisabled(api: OpenClawPluginApi, accountId: string, payload: {
76
+ jobId: string;
77
+ }): Promise<{
78
+ success: boolean;
79
+ data?: any;
80
+ error?: string;
81
+ }>;
82
+ /**
83
+ * 调用定时任务触发通知接口
84
+ */
85
+ export declare function callCronJobMessage(api: OpenClawPluginApi, accountId: string, payload: {
86
+ jobId: string;
87
+ message: string;
88
+ agentId?: string;
89
+ }): Promise<{
90
+ success: boolean;
91
+ data?: any;
92
+ error?: string;
93
+ }>;
@@ -0,0 +1,209 @@
1
+ /**
2
+ * 智小途定时任务工具 - 后端接口封装
3
+ */
4
+ import { resolveWorkclawAccountWithCache } from '../../../accounts.js';
5
+ import { doFetchJson, getWorkclawAccessToken, normalizeBaseUrl } from '../../../connection/workclaw-client.js';
6
+ const DEFAULT_MAX_RETRIES = 3;
7
+ const DEFAULT_RETRY_DELAY_MS = 1000;
8
+ /**
9
+ * 睡眠函数
10
+ */
11
+ function sleep(ms) {
12
+ return new Promise(resolve => setTimeout(resolve, ms));
13
+ }
14
+ /**
15
+ * 带重试机制的 fetch 调用
16
+ */
17
+ async function fetchWithRetry(fetchFn, options = {}) {
18
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
19
+ const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
20
+ const retryableErrors = options.retryableErrors ?? [
21
+ 'ECONNREFUSED',
22
+ 'ETIMEDOUT',
23
+ 'ENOTFOUND',
24
+ 'ENETUNREACH',
25
+ 'EAI_AGAIN',
26
+ ];
27
+ let lastError = '';
28
+ let attempts = 0;
29
+ for (let i = 0; i <= maxRetries; i++) {
30
+ attempts = i + 1;
31
+ try {
32
+ const data = await fetchFn();
33
+ return { data, attempts };
34
+ }
35
+ catch (error) {
36
+ lastError = error.message || String(error);
37
+ const isRetryable = retryableErrors.some(e => lastError.toLowerCase().includes(e.toLowerCase()));
38
+ if (i < maxRetries && isRetryable) {
39
+ const delay = retryDelayMs * 2 ** i;
40
+ await sleep(delay);
41
+ continue;
42
+ }
43
+ break;
44
+ }
45
+ }
46
+ return { error: lastError, attempts };
47
+ }
48
+ /**
49
+ * 脱敏日志输出(隐藏敏感字段)
50
+ */
51
+ function sanitizePayload(payload) {
52
+ const sensitiveFields = [
53
+ 'password',
54
+ 'secret',
55
+ 'token',
56
+ 'authorization',
57
+ 'appSecret',
58
+ 'appSecret',
59
+ ];
60
+ const sanitized = {};
61
+ for (const [key, value] of Object.entries(payload)) {
62
+ const lowerKey = key.toLowerCase();
63
+ if (sensitiveFields.some(f => lowerKey.includes(f))) {
64
+ sanitized[key] = '***';
65
+ }
66
+ else if (typeof value === 'object' && value !== null) {
67
+ sanitized[key] = sanitizePayload(value);
68
+ }
69
+ else {
70
+ sanitized[key] = value;
71
+ }
72
+ }
73
+ return sanitized;
74
+ }
75
+ /**
76
+ * 调用后端 API 的通用方法
77
+ * @param api - OpenClaw API 实例
78
+ * @param accountId - 账户 ID
79
+ * @param path - API 路径
80
+ * @param payload - 请求体
81
+ * @param options - 可选配置
82
+ * @returns 接口调用结果
83
+ */
84
+ export async function callBackendApi(api, accountId, path, payload, options = {}) {
85
+ try {
86
+ const account = resolveWorkclawAccountWithCache({
87
+ cfg: api.config,
88
+ accountId,
89
+ });
90
+ if (!account.configured) {
91
+ api.logger.error(`[智小途-定时任务] 账户未配置 accountId=${accountId}`);
92
+ return { success: false, error: 'Account not configured' };
93
+ }
94
+ const accConfig = account.config;
95
+ const tokenCacheKey = accConfig.appKey || accountId;
96
+ const baseUrl = normalizeBaseUrl(accConfig.baseUrl);
97
+ api.logger.info(`[智小途-定时任务] 正在获取认证 token,accountId=${accountId}`);
98
+ const token = await getWorkclawAccessToken(tokenCacheKey, {
99
+ baseUrl: accConfig.baseUrl,
100
+ appKey: accConfig.appKey,
101
+ appSecret: accConfig.appSecret,
102
+ allowInsecureTls: accConfig.allowInsecureTls,
103
+ requestTimeout: accConfig.requestTimeout,
104
+ });
105
+ const requestUrl = `${baseUrl}/open-apis${path}`;
106
+ const sanitizedPayload = sanitizePayload(payload);
107
+ api.logger.info(`[智小途-定时任务] 调用接口 ${requestUrl}`);
108
+ api.logger.info(`[智小途-定时任务] 请求参数 ${JSON.stringify(sanitizedPayload)}`);
109
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
110
+ const fetchResult = await fetchWithRetry(() => doFetchJson(requestUrl, {
111
+ method: 'POST',
112
+ headers: {
113
+ 'Content-Type': 'application/json',
114
+ 'Authorization': `Bearer ${token}`,
115
+ },
116
+ body: JSON.stringify(payload),
117
+ }, accConfig.allowInsecureTls, accConfig.requestTimeout), { maxRetries });
118
+ if (fetchResult.error) {
119
+ api.logger.error(`[智小途-定时任务] 接口调用失败(已重试 ${fetchResult.attempts} 次): ${fetchResult.error}`);
120
+ return { success: false, error: fetchResult.error, attempts: fetchResult.attempts };
121
+ }
122
+ const data = fetchResult.data;
123
+ api.logger.info(`[智小途-定时任务] 接口响应(尝试 ${fetchResult.attempts} 次): ${JSON.stringify(data)}`);
124
+ if (data?.code === 200 || data?.code === 0) {
125
+ return { success: true, data, attempts: fetchResult.attempts };
126
+ }
127
+ else {
128
+ const errorMsg = data?.message || data?.msg || 'Unknown error';
129
+ api.logger.error(`[智小途-定时任务] 接口返回错误 ${errorMsg}`);
130
+ return { success: false, error: errorMsg };
131
+ }
132
+ }
133
+ catch (error) {
134
+ api.logger.error(`[智小途-定时任务] 接口调用异常 ${error.message}`);
135
+ return { success: false, error: error.message };
136
+ }
137
+ }
138
+ /**
139
+ * 调用新增定时任务接口
140
+ */
141
+ export async function callCronJobAdd(api, accountId, payload) {
142
+ api.logger.info(`[智小途-定时任务] 新增定时任务 jobId=${payload.jobId} name=${payload.name}`);
143
+ const result = await callBackendApi(api, accountId, '/cron/job/add', {
144
+ clawJobId: payload.jobId,
145
+ name: payload.name,
146
+ kind: payload.kind,
147
+ expr: payload.expr || '',
148
+ message: payload.message,
149
+ agentId: payload.messageId || '0',
150
+ });
151
+ return { success: result.success, data: result.data, error: result.error };
152
+ }
153
+ /**
154
+ * 调用删除定时任务接口
155
+ */
156
+ export async function callCronJobRemove(api, accountId, payload) {
157
+ api.logger.info(`[智小途-定时任务] 删除定时任务 jobId=${payload.jobId}`);
158
+ const result = await callBackendApi(api, accountId, '/cron/job/del', {
159
+ clawJobId: payload.jobId,
160
+ });
161
+ return { success: result.success, data: result.data, error: result.error };
162
+ }
163
+ /**
164
+ * 调用更新定时任务接口
165
+ */
166
+ export async function callCronJobUpdate(api, accountId, payload) {
167
+ api.logger.info(`[智小途-定时任务] 更新定时任务 jobId=${payload.jobId} name=${payload.name} agentId=${payload.agentId}`);
168
+ const result = await callBackendApi(api, accountId, '/cron/job/update', {
169
+ clawJobId: payload.jobId,
170
+ name: payload.name,
171
+ kind: payload.kind,
172
+ expr: payload.expr || '',
173
+ message: payload.message,
174
+ agentId: payload.agentId || '0',
175
+ });
176
+ return { success: result.success, data: result.data, error: result.error };
177
+ }
178
+ /**
179
+ * 调用启用定时任务接口
180
+ */
181
+ export async function callCronJobEnabled(api, accountId, payload) {
182
+ api.logger.info(`[智小途-定时任务] 启用定时任务 jobId=${payload.jobId}`);
183
+ const result = await callBackendApi(api, accountId, '/cron/job/enabled', {
184
+ clawJobId: payload.jobId,
185
+ });
186
+ return { success: result.success, data: result.data, error: result.error };
187
+ }
188
+ /**
189
+ * 调用禁用定时任务接口
190
+ */
191
+ export async function callCronJobDisabled(api, accountId, payload) {
192
+ api.logger.info(`[智小途-定时任务] 禁用定时任务 jobId=${payload.jobId}`);
193
+ const result = await callBackendApi(api, accountId, '/cron/job/disabled', {
194
+ clawJobId: payload.jobId,
195
+ });
196
+ return { success: result.success, data: result.data, error: result.error };
197
+ }
198
+ /**
199
+ * 调用定时任务触发通知接口
200
+ */
201
+ export async function callCronJobMessage(api, accountId, payload) {
202
+ api.logger.info(`[智小途-定时任务] 定时任务触发通知 jobId=${payload.jobId} message=${payload.message} agentId=${payload.agentId}`);
203
+ const result = await callBackendApi(api, accountId, '/cron/job/message', {
204
+ clawJobId: payload.jobId,
205
+ message: payload.message,
206
+ agentId: payload.agentId || '0',
207
+ });
208
+ return { success: result.success, data: result.data, error: result.error };
209
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * 智小途定时任务工具 - 统一出口
3
+ *
4
+ * 提供统一的工具注册入口,一次性注册所有定时任务相关工具
5
+ */
6
+ /**
7
+ * 统一注册所有定时任务工具
8
+ * @param api - OpenClaw API 实例
9
+ */
10
+ export declare function registerAllOpenclawWorkclawCronTools(api: any): void;