@workclaw/openclaw-workclaw 1.0.25 → 1.0.27

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 (161) hide show
  1. package/dist/api.d.ts +4 -0
  2. package/dist/api.d.ts.map +1 -0
  3. package/dist/api.js +379 -0
  4. package/dist/channel-DSvR6Irx.js +50017 -0
  5. package/dist/cron-tasks-handler-C-mP3VmV.js +152 -0
  6. package/dist/index.d.ts +12 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +2088 -0
  9. package/dist/jiti-4i2h0FGP.js +4814 -0
  10. package/dist/setup-entry.d.ts +3 -0
  11. package/dist/setup-entry.d.ts.map +1 -0
  12. package/dist/setup-entry.js +182 -0
  13. package/dist/src/accounts.d.ts +67 -0
  14. package/dist/src/accounts.d.ts.map +1 -0
  15. package/dist/src/api/accounts-api.d.ts +3 -0
  16. package/dist/src/api/accounts-api.d.ts.map +1 -0
  17. package/dist/src/api/prompts-api.d.ts +3 -0
  18. package/dist/src/api/prompts-api.d.ts.map +1 -0
  19. package/dist/src/api/session-api.d.ts +3 -0
  20. package/dist/src/api/session-api.d.ts.map +1 -0
  21. package/dist/src/api/skills-api.d.ts +3 -0
  22. package/dist/src/api/skills-api.d.ts.map +1 -0
  23. package/dist/src/api/workspace.d.ts +4 -0
  24. package/dist/src/api/workspace.d.ts.map +1 -0
  25. package/dist/src/channel.d.ts +12 -0
  26. package/dist/src/channel.d.ts.map +1 -0
  27. package/dist/src/config-schema.d.ts +88 -0
  28. package/dist/src/config-schema.d.ts.map +1 -0
  29. package/dist/src/connection/workclaw-client.d.ts +149 -0
  30. package/dist/src/connection/workclaw-client.d.ts.map +1 -0
  31. package/dist/src/gateway/agent-handlers.d.ts +13 -0
  32. package/dist/src/gateway/agent-handlers.d.ts.map +1 -0
  33. package/dist/src/gateway/config-writer.d.ts +72 -0
  34. package/dist/src/gateway/config-writer.d.ts.map +1 -0
  35. package/dist/src/gateway/cron-tasks-handler.d.ts +20 -0
  36. package/dist/src/gateway/cron-tasks-handler.d.ts.map +1 -0
  37. package/dist/src/gateway/message-context.d.ts +81 -0
  38. package/dist/src/gateway/message-context.d.ts.map +1 -0
  39. package/dist/src/gateway/message-dispatcher.d.ts +17 -0
  40. package/dist/src/gateway/message-dispatcher.d.ts.map +1 -0
  41. package/dist/src/gateway/reconnect.d.ts +25 -0
  42. package/dist/src/gateway/reconnect.d.ts.map +1 -0
  43. package/dist/src/gateway/skills-handler.d.ts +30 -0
  44. package/dist/src/gateway/skills-handler.d.ts.map +1 -0
  45. package/dist/src/gateway/skills-list-handler.d.ts +28 -0
  46. package/dist/src/gateway/skills-list-handler.d.ts.map +1 -0
  47. package/dist/src/gateway/tools-list-handler.d.ts +31 -0
  48. package/dist/src/gateway/tools-list-handler.d.ts.map +1 -0
  49. package/dist/src/gateway/workclaw-gateway.d.ts +11 -0
  50. package/dist/src/gateway/workclaw-gateway.d.ts.map +1 -0
  51. package/dist/src/media/upload.d.ts +14 -0
  52. package/dist/src/media/upload.d.ts.map +1 -0
  53. package/dist/src/outbound/index.d.ts +39 -0
  54. package/dist/src/outbound/index.d.ts.map +1 -0
  55. package/dist/src/outbound/workclaw-sender.d.ts +38 -0
  56. package/dist/src/outbound/workclaw-sender.d.ts.map +1 -0
  57. package/dist/src/runtime.d.ts +118 -0
  58. package/dist/src/runtime.d.ts.map +1 -0
  59. package/dist/src/secret-contract-api.d.ts +5 -0
  60. package/dist/src/secret-contract-api.d.ts.map +1 -0
  61. package/{src/send.ts → dist/src/send.d.ts} +2 -1
  62. package/dist/src/send.d.ts.map +1 -0
  63. package/dist/src/setup-api.d.ts +4 -0
  64. package/dist/src/setup-api.d.ts.map +1 -0
  65. package/dist/src/setup-core.d.ts +4 -0
  66. package/dist/src/setup-core.d.ts.map +1 -0
  67. package/dist/src/setup-surface.d.ts +8 -0
  68. package/dist/src/setup-surface.d.ts.map +1 -0
  69. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +91 -0
  70. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts.map +1 -0
  71. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +11 -0
  72. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts.map +1 -0
  73. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +14 -0
  74. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts.map +1 -0
  75. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +16 -0
  76. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts.map +1 -0
  77. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +12 -0
  78. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts.map +1 -0
  79. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +12 -0
  80. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts.map +1 -0
  81. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +12 -0
  82. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts.map +1 -0
  83. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +12 -0
  84. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts.map +1 -0
  85. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +13 -0
  86. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts.map +1 -0
  87. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +12 -0
  88. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts.map +1 -0
  89. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +12 -0
  90. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts.map +1 -0
  91. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +15 -0
  92. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts.map +1 -0
  93. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +16 -0
  94. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts.map +1 -0
  95. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +53 -0
  96. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts.map +1 -0
  97. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +41 -0
  98. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts.map +1 -0
  99. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +11 -0
  100. package/dist/src/tools/openclaw-workclaw-system/index.d.ts.map +1 -0
  101. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +6 -0
  102. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts.map +1 -0
  103. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +6 -0
  104. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts.map +1 -0
  105. package/dist/src/types.d.ts +39 -0
  106. package/dist/src/types.d.ts.map +1 -0
  107. package/dist/src/utils/content.d.ts +16 -0
  108. package/dist/src/utils/content.d.ts.map +1 -0
  109. package/openclaw.plugin.json +11 -0
  110. package/package.json +69 -45
  111. package/api.ts +0 -3
  112. package/index.ts +0 -325
  113. package/setup-entry.ts +0 -13
  114. package/src/accounts.ts +0 -360
  115. package/src/api/accounts-api.ts +0 -156
  116. package/src/api/prompts-api.ts +0 -122
  117. package/src/api/session-api.ts +0 -246
  118. package/src/api/skills-api.ts +0 -74
  119. package/src/api/workspace.ts +0 -45
  120. package/src/channel.ts +0 -226
  121. package/src/config-schema.ts +0 -60
  122. package/src/connection/workclaw-client.ts +0 -618
  123. package/src/gateway/agent-handlers.ts +0 -551
  124. package/src/gateway/config-writer.ts +0 -378
  125. package/src/gateway/cron-tasks-handler.ts +0 -230
  126. package/src/gateway/message-context.ts +0 -645
  127. package/src/gateway/message-dispatcher.ts +0 -688
  128. package/src/gateway/reconnect.ts +0 -260
  129. package/src/gateway/skills-handler.ts +0 -805
  130. package/src/gateway/skills-list-handler.ts +0 -332
  131. package/src/gateway/tools-list-handler.ts +0 -161
  132. package/src/gateway/workclaw-gateway.ts +0 -304
  133. package/src/media/upload.ts +0 -168
  134. package/src/outbound/index.ts +0 -191
  135. package/src/outbound/workclaw-sender.ts +0 -161
  136. package/src/runtime.ts +0 -520
  137. package/src/secret-contract-api.ts +0 -4
  138. package/src/setup-api.ts +0 -3
  139. package/src/setup-core.ts +0 -25
  140. package/src/setup-surface.ts +0 -498
  141. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  142. package/src/tools/openclaw-workclaw-cron/index.ts +0 -39
  143. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -177
  144. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  145. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  146. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  147. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  148. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  149. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  150. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  151. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  152. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -195
  153. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  154. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  155. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  156. package/src/tools/openclaw-workclaw-system/index.ts +0 -17
  157. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  158. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  159. package/src/types.ts +0 -50
  160. package/src/utils/content.ts +0 -40
  161. package/tsconfig.json +0 -34
package/dist/index.js ADDED
@@ -0,0 +1,2088 @@
1
+ import { readFile, stat, mkdir, writeFile, unlink } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import process$1 from "node:process";
4
+ import { fileURLToPath } from "node:url";
5
+ import { n as normalizeAccountId, g as getWorkclawLogger, a as getWorkclawRuntime, r as resolveWorkclawAccountWithCache, b as normalizeBaseUrl, c as getWorkclawAccessToken, d as doFetchJson, w as workclawPlugin, s as setWorkclawRuntime, e as deleteToolContext, f as getToolContext, h as getToolResultHint, i as sendMessageWorkclaw, j as setToolCallIdToRunIdMapping } from "./channel-DSvR6Irx.js";
6
+ import { e as emptyChannelConfigSchema } from "./jiti-4i2h0FGP.js";
7
+ import os from "node:os";
8
+ import "node:fs";
9
+ import "node:net";
10
+ import "node:crypto";
11
+ import { exec } from "node:child_process";
12
+ import { promisify } from "node:util";
13
+ function error(message) {
14
+ return {
15
+ success: false,
16
+ error: { issues: [{
17
+ path: [],
18
+ message
19
+ }] }
20
+ };
21
+ }
22
+ function emptyPluginConfigSchema() {
23
+ return {
24
+ safeParse(value) {
25
+ if (value === void 0) return {
26
+ success: true,
27
+ data: void 0
28
+ };
29
+ if (!value || typeof value !== "object" || Array.isArray(value)) return error("expected config object");
30
+ if (Object.keys(value).length > 0) return error("config must be empty");
31
+ return {
32
+ success: true,
33
+ data: value
34
+ };
35
+ },
36
+ jsonSchema: {
37
+ type: "object",
38
+ additionalProperties: false,
39
+ properties: {}
40
+ }
41
+ };
42
+ }
43
+ function defineChannelPluginEntry({ id, name, description, plugin, configSchema, setRuntime, registerCliMetadata, registerFull }) {
44
+ return {
45
+ id,
46
+ name,
47
+ description,
48
+ configSchema: typeof configSchema === "function" ? configSchema() : configSchema ?? emptyChannelConfigSchema(),
49
+ register(api) {
50
+ if (api.registrationMode === "cli-metadata") {
51
+ registerCliMetadata?.(api);
52
+ return;
53
+ }
54
+ setRuntime?.(api.runtime);
55
+ api.registerChannel({ plugin });
56
+ if (api.registrationMode !== "full") return;
57
+ registerCliMetadata?.(api);
58
+ registerFull?.(api);
59
+ },
60
+ channelPlugin: plugin,
61
+ ...setRuntime ? { setChannelRuntime: setRuntime } : {}
62
+ };
63
+ }
64
+ function sendJson$3(res, statusCode, payload) {
65
+ res.statusCode = statusCode;
66
+ res.setHeader("Content-Type", "application/json");
67
+ res.end(JSON.stringify(payload));
68
+ }
69
+ async function readRequestBody$2(req) {
70
+ const chunks = [];
71
+ await new Promise((resolve, reject) => {
72
+ req.on("data", (chunk) => {
73
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
74
+ });
75
+ req.on("end", () => resolve());
76
+ req.on("error", (err) => reject(err));
77
+ });
78
+ return Buffer.concat(chunks).toString("utf-8");
79
+ }
80
+ async function loadRuntimeConfig(api) {
81
+ const runtimeConfig = api.runtime?.config;
82
+ if (runtimeConfig?.loadConfig) {
83
+ return runtimeConfig.loadConfig();
84
+ }
85
+ return api.config;
86
+ }
87
+ async function writeRuntimeConfig(api, config) {
88
+ const runtimeConfig = api.runtime?.config;
89
+ if (runtimeConfig?.writeConfigFile) {
90
+ await runtimeConfig.writeConfigFile(config);
91
+ return;
92
+ }
93
+ throw new Error("Config write not supported");
94
+ }
95
+ function getAccountMap(config) {
96
+ const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
97
+ const openclawWorkclaw = channels["openclaw-workclaw"] && typeof channels["openclaw-workclaw"] === "object" ? channels["openclaw-workclaw"] : {};
98
+ const accounts = openclawWorkclaw.accounts && typeof openclawWorkclaw.accounts === "object" ? openclawWorkclaw.accounts : {};
99
+ return { ...accounts };
100
+ }
101
+ function withAccounts(config, accounts) {
102
+ const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
103
+ const openclawWorkclaw = channels["openclaw-workclaw"] && typeof channels["openclaw-workclaw"] === "object" ? channels["openclaw-workclaw"] : {};
104
+ return {
105
+ ...config,
106
+ channels: {
107
+ ...channels,
108
+ "openclaw-workclaw": {
109
+ ...openclawWorkclaw,
110
+ accounts
111
+ }
112
+ }
113
+ };
114
+ }
115
+ function createAccountsApiHandler(api) {
116
+ return async (req, res) => {
117
+ const method = String(req.method ?? "GET").toUpperCase();
118
+ const url = new URL(req.url ?? "", "http://localhost");
119
+ const idRaw = url.searchParams.get("id") ?? url.searchParams.get("accountId");
120
+ const accountId = idRaw ? normalizeAccountId(idRaw) : null;
121
+ if (method === "GET") {
122
+ const cfg = await loadRuntimeConfig(api);
123
+ const accounts = getAccountMap(cfg);
124
+ if (accountId) {
125
+ const account = accounts[accountId];
126
+ if (!account) {
127
+ sendJson$3(res, 404, { ok: false, error: "Not Found" });
128
+ return;
129
+ }
130
+ sendJson$3(res, 200, { ok: true, accountId, config: account });
131
+ return;
132
+ }
133
+ const entries = Object.entries(accounts).map(([id, config]) => ({
134
+ accountId: id,
135
+ config
136
+ }));
137
+ sendJson$3(res, 200, { ok: true, accounts: entries });
138
+ return;
139
+ }
140
+ if (method === "POST" || method === "PUT") {
141
+ const raw = await readRequestBody$2(req);
142
+ let input = {};
143
+ try {
144
+ input = raw ? JSON.parse(raw) : {};
145
+ } catch {
146
+ sendJson$3(res, 400, { ok: false, error: "Invalid JSON" });
147
+ return;
148
+ }
149
+ const inputId = input?.accountId ?? input?.id;
150
+ const normalizedId = inputId ? normalizeAccountId(String(inputId)) : "";
151
+ const patch = input?.config;
152
+ if (!normalizedId || !patch || typeof patch !== "object") {
153
+ sendJson$3(res, 400, { ok: false, error: "Missing accountId or config" });
154
+ return;
155
+ }
156
+ const cfg = await loadRuntimeConfig(api);
157
+ const accounts = getAccountMap(cfg);
158
+ if (method === "POST" && accounts[normalizedId]) {
159
+ sendJson$3(res, 409, { ok: false, error: "Account already exists" });
160
+ return;
161
+ }
162
+ if (method === "PUT" && !accounts[normalizedId]) {
163
+ sendJson$3(res, 404, { ok: false, error: "Not Found" });
164
+ return;
165
+ }
166
+ const next = method === "PUT" ? { ...accounts[normalizedId], ...patch } : patch;
167
+ const updated = withAccounts(cfg, { ...accounts, [normalizedId]: next });
168
+ await writeRuntimeConfig(api, updated);
169
+ sendJson$3(res, 200, { ok: true, accountId: normalizedId });
170
+ return;
171
+ }
172
+ if (method === "DELETE") {
173
+ if (!accountId) {
174
+ sendJson$3(res, 400, { ok: false, error: "Missing accountId" });
175
+ return;
176
+ }
177
+ const cfg = await loadRuntimeConfig(api);
178
+ const accounts = getAccountMap(cfg);
179
+ if (!accounts[accountId]) {
180
+ sendJson$3(res, 404, { ok: false, error: "Not Found" });
181
+ return;
182
+ }
183
+ const { [accountId]: _ignored, ...rest } = accounts;
184
+ const updated = withAccounts(cfg, rest);
185
+ await writeRuntimeConfig(api, updated);
186
+ sendJson$3(res, 200, { ok: true, accountId, deleted: true });
187
+ return;
188
+ }
189
+ sendJson$3(res, 405, { ok: false, error: "Method Not Allowed" });
190
+ };
191
+ }
192
+ function resolveWorkspaceDir(api) {
193
+ const agents = api.config.agents?.list ?? [];
194
+ const defaultAgent = agents.find((agent) => agent?.default === true) ?? agents.find((agent) => String(agent?.id ?? "").toLowerCase() === "main");
195
+ const workspaceRaw = typeof defaultAgent?.workspace === "string" && defaultAgent.workspace.trim() || typeof api.config.agents?.defaults?.workspace === "string" && api.config.agents.defaults.workspace.trim();
196
+ getWorkclawLogger().info(`workspaceRaw: ${workspaceRaw}`);
197
+ if (workspaceRaw) {
198
+ return api.resolvePath(workspaceRaw);
199
+ }
200
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
201
+ const suffix = profile && profile.toLowerCase() !== "default" ? `workspace-${profile}` : "workspace";
202
+ return path.join(os.homedir(), ".openclaw", suffix);
203
+ }
204
+ function isDefaultWorkspace(api) {
205
+ const agents = api.config.agents?.list ?? [];
206
+ const defaultAgent = agents.find((agent) => agent?.default === true) ?? agents.find((agent) => String(agent?.id ?? "").toLowerCase() === "main");
207
+ const workspaceRaw = typeof defaultAgent?.workspace === "string" && defaultAgent.workspace.trim() || typeof api.config.agents?.defaults?.workspace === "string" && api.config.agents.defaults.workspace.trim();
208
+ if (workspaceRaw)
209
+ return false;
210
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
211
+ return !profile || profile.toLowerCase() === "default";
212
+ }
213
+ const promptNames = ["SOUL.md", "USER.md"];
214
+ function normalizePromptName(raw) {
215
+ const name = String(raw ?? "").trim().toUpperCase();
216
+ if (name === "SOUL" || name === "SOUL.MD")
217
+ return "SOUL.md";
218
+ if (name === "USER" || name === "USER.MD")
219
+ return "USER.md";
220
+ return null;
221
+ }
222
+ function resolvePromptPath(api, name) {
223
+ return path.join(resolveWorkspaceDir(api), name);
224
+ }
225
+ function sendJson$2(res, statusCode, payload) {
226
+ res.statusCode = statusCode;
227
+ res.setHeader("Content-Type", "application/json");
228
+ res.end(JSON.stringify(payload));
229
+ }
230
+ function createPromptsApiHandler(api) {
231
+ return async (req, res) => {
232
+ const method = String(req.method ?? "GET").toUpperCase();
233
+ const url = new URL(req.url ?? "", "http://localhost");
234
+ const name = normalizePromptName(url.searchParams.get("name"));
235
+ if (method === "GET") {
236
+ if (name) {
237
+ const filePath = resolvePromptPath(api, name);
238
+ try {
239
+ const content = await readFile(filePath, "utf-8");
240
+ sendJson$2(res, 200, { ok: true, name, content });
241
+ return;
242
+ } catch (error2) {
243
+ sendJson$2(res, 404, { ok: false, error: "Not Found" });
244
+ return;
245
+ }
246
+ }
247
+ const entries = await Promise.all(
248
+ promptNames.map(async (promptName) => {
249
+ const filePath = resolvePromptPath(api, promptName);
250
+ try {
251
+ const info = await stat(filePath);
252
+ return { name: promptName, exists: true, bytes: info.size };
253
+ } catch {
254
+ return { name: promptName, exists: false, bytes: 0 };
255
+ }
256
+ })
257
+ );
258
+ sendJson$2(res, 200, { ok: true, entries });
259
+ return;
260
+ }
261
+ if (method === "PUT" || method === "POST") {
262
+ const raw = await readRequestBody$1(req);
263
+ let input = {};
264
+ try {
265
+ input = raw ? JSON.parse(raw) : {};
266
+ } catch {
267
+ sendJson$2(res, 400, { ok: false, error: "Invalid JSON" });
268
+ return;
269
+ }
270
+ const targetName = normalizePromptName(input?.name);
271
+ const content = typeof input?.content === "string" ? input.content : null;
272
+ if (!targetName || content === null) {
273
+ sendJson$2(res, 400, { ok: false, error: "Missing name or content" });
274
+ return;
275
+ }
276
+ const workspaceDir = resolveWorkspaceDir(api);
277
+ await mkdir(workspaceDir, { recursive: true });
278
+ await writeFile(resolvePromptPath(api, targetName), content, { encoding: "utf-8" });
279
+ sendJson$2(res, 200, { ok: true, name: targetName });
280
+ return;
281
+ }
282
+ if (method === "DELETE") {
283
+ if (!name) {
284
+ sendJson$2(res, 400, { ok: false, error: "Missing name" });
285
+ return;
286
+ }
287
+ const filePath = resolvePromptPath(api, name);
288
+ try {
289
+ await unlink(filePath);
290
+ sendJson$2(res, 200, { ok: true, name, deleted: true });
291
+ return;
292
+ } catch {
293
+ sendJson$2(res, 200, { ok: true, name, deleted: false });
294
+ return;
295
+ }
296
+ }
297
+ sendJson$2(res, 405, { ok: false, error: "Method Not Allowed" });
298
+ };
299
+ }
300
+ async function readRequestBody$1(req) {
301
+ const chunks = [];
302
+ await new Promise((resolve, reject) => {
303
+ req.on("data", (chunk) => {
304
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
305
+ });
306
+ req.on("end", () => resolve());
307
+ req.on("error", (err) => reject(err));
308
+ });
309
+ return Buffer.concat(chunks).toString("utf-8");
310
+ }
311
+ function sendJson$1(res, statusCode, payload) {
312
+ res.statusCode = statusCode;
313
+ res.setHeader("Content-Type", "application/json");
314
+ res.end(JSON.stringify(payload));
315
+ }
316
+ async function readRequestBody(req) {
317
+ const chunks = [];
318
+ await new Promise((resolve, reject) => {
319
+ req.on("data", (chunk) => {
320
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
321
+ });
322
+ req.on("end", () => resolve());
323
+ req.on("error", (err) => reject(err));
324
+ });
325
+ return Buffer.concat(chunks).toString("utf-8");
326
+ }
327
+ function buildSessionKey(accountId, userId) {
328
+ return `openclaw-workclaw:${accountId}:${userId}`;
329
+ }
330
+ function parseSessionKey(sessionKey) {
331
+ const parts = sessionKey.split(":");
332
+ if (parts.length !== 3 || parts[0] !== "openclaw-workclaw") {
333
+ return null;
334
+ }
335
+ return {
336
+ channel: parts[0],
337
+ accountId: parts[1],
338
+ userId: parts[2]
339
+ };
340
+ }
341
+ async function resetSession(sessionKey, log) {
342
+ try {
343
+ const runtime = getWorkclawRuntime();
344
+ runtime.system.enqueueSystemEvent("/new", {
345
+ sessionKey,
346
+ contextKey: null
347
+ });
348
+ log?.info?.(`[SessionAPI] Sent /new command to session: ${sessionKey}`);
349
+ return {
350
+ success: true,
351
+ message: `Session reset command sent to ${sessionKey}`
352
+ };
353
+ } catch (err) {
354
+ const errorMsg = `Failed to reset session: ${String(err)}`;
355
+ log?.error?.(`[SessionAPI] ${errorMsg}`);
356
+ return { success: false, message: errorMsg };
357
+ }
358
+ }
359
+ function getSessionStorePath(agentId, log) {
360
+ try {
361
+ const runtime = getWorkclawRuntime();
362
+ const storePath = runtime.channel.session.resolveStorePath(void 0, {
363
+ agentId
364
+ });
365
+ return storePath;
366
+ } catch (err) {
367
+ log?.error?.(`[SessionAPI] Failed to resolve store path: ${String(err)}`);
368
+ return null;
369
+ }
370
+ }
371
+ async function getSessionLastUpdated(sessionKey, log) {
372
+ try {
373
+ const runtime = getWorkclawRuntime();
374
+ const storePath = runtime.channel.session.resolveStorePath();
375
+ const updatedAt = runtime.channel.session.readSessionUpdatedAt({
376
+ storePath,
377
+ sessionKey
378
+ });
379
+ return updatedAt ?? null;
380
+ } catch (err) {
381
+ log?.error?.(`[SessionAPI] Failed to read session updated at: ${String(err)}`);
382
+ return null;
383
+ }
384
+ }
385
+ function createSessionApiHandler(api) {
386
+ return async (req, res) => {
387
+ const method = String(req.method ?? "GET").toUpperCase();
388
+ const url = new URL(req.url ?? "", "http://localhost");
389
+ const fullPath = url.pathname.replace(/\/+$/, "");
390
+ const subPath = fullPath.replace(/^\/openclaw-workclaw\/sessions/, "").replace(/^\//, "") || "/";
391
+ const log = {
392
+ info: (msg) => api.logger?.info?.(`[SessionAPI] ${msg}`),
393
+ error: (msg) => api.logger?.error?.(`[SessionAPI] ${msg}`)
394
+ };
395
+ log?.info?.(`[SessionAPI] ${method} ${fullPath} (subPath: ${subPath})`);
396
+ if (method === "GET" && (subPath === "/" || subPath === "")) {
397
+ const sessionKey = url.searchParams.get("sessionKey");
398
+ if (sessionKey) {
399
+ const parsed = parseSessionKey(sessionKey);
400
+ const updatedAt = await getSessionLastUpdated(sessionKey, log);
401
+ sendJson$1(res, 200, {
402
+ ok: true,
403
+ session: {
404
+ sessionKey,
405
+ parsed,
406
+ lastUpdatedAt: updatedAt,
407
+ lastUpdatedAtFormatted: updatedAt ? new Date(updatedAt).toISOString() : null
408
+ }
409
+ });
410
+ return;
411
+ }
412
+ sendJson$1(res, 200, {
413
+ ok: true,
414
+ message: "Session Management API",
415
+ endpoints: {
416
+ "GET /sessions": "获取会话信息 (可选参数: sessionKey)",
417
+ "POST /sessions/reset": "重置/开启新会话 (参数: accountId + userId 或直接提供 sessionKey)",
418
+ "GET /sessions/store-path": "获取会话存储路径 (可选参数: agentId)"
419
+ }
420
+ });
421
+ return;
422
+ }
423
+ if (method === "POST" && subPath === "reset") {
424
+ const raw = await readRequestBody(req);
425
+ let input = {};
426
+ try {
427
+ input = raw ? JSON.parse(raw) : {};
428
+ } catch {
429
+ sendJson$1(res, 400, { ok: false, error: "Invalid JSON" });
430
+ return;
431
+ }
432
+ const { accountId, userId, sessionKey: directSessionKey } = input;
433
+ let sessionKey;
434
+ if (directSessionKey) {
435
+ sessionKey = directSessionKey;
436
+ } else if (accountId && userId) {
437
+ sessionKey = buildSessionKey(accountId, userId);
438
+ } else {
439
+ sendJson$1(res, 400, {
440
+ ok: false,
441
+ error: "Missing required fields: either provide 'sessionKey' or both 'accountId' and 'userId'"
442
+ });
443
+ return;
444
+ }
445
+ const result = await resetSession(sessionKey, log);
446
+ if (result.success) {
447
+ sendJson$1(res, 200, {
448
+ ok: true,
449
+ message: result.message,
450
+ sessionKey
451
+ });
452
+ } else {
453
+ sendJson$1(res, 500, {
454
+ ok: false,
455
+ error: result.message,
456
+ sessionKey
457
+ });
458
+ }
459
+ return;
460
+ }
461
+ if (method === "GET" && subPath === "store-path") {
462
+ const agentId = url.searchParams.get("agentId") ?? void 0;
463
+ const storePath = getSessionStorePath(agentId, log);
464
+ if (storePath) {
465
+ sendJson$1(res, 200, {
466
+ ok: true,
467
+ storePath,
468
+ agentId: agentId ?? "default"
469
+ });
470
+ } else {
471
+ sendJson$1(res, 500, {
472
+ ok: false,
473
+ error: "Failed to resolve session store path"
474
+ });
475
+ }
476
+ return;
477
+ }
478
+ sendJson$1(res, 404, { ok: false, error: "Not Found" });
479
+ };
480
+ }
481
+ const execAsync = promisify(exec);
482
+ function sendJson(res, statusCode, payload) {
483
+ res.statusCode = statusCode;
484
+ res.setHeader("Content-Type", "application/json");
485
+ res.end(JSON.stringify(payload));
486
+ }
487
+ function createSkillsApiHandler(api) {
488
+ return async (req, res) => {
489
+ const method = String(req.method ?? "GET").toUpperCase();
490
+ if (method === "GET") {
491
+ try {
492
+ const { stdout, stderr } = await execAsync("openclaw skills list --json", {
493
+ timeout: 1e4
494
+ // 10秒超时
495
+ });
496
+ if (stderr && !stdout) {
497
+ api.logger.error(`Skills list error: ${stderr}`);
498
+ sendJson(res, 500, { ok: false, error: "Failed to list skills" });
499
+ return;
500
+ }
501
+ let skillsData;
502
+ try {
503
+ skillsData = JSON.parse(stdout);
504
+ } catch {
505
+ const lines = stdout.split("\n");
506
+ const skills = lines.filter((line) => line.trim() && !line.includes("Skills")).map((line) => {
507
+ const parts = line.split(/\s{2,}/).map((p) => p.trim());
508
+ if (parts.length >= 3) {
509
+ return {
510
+ status: parts[0]?.includes("✓") ? "ready" : "missing",
511
+ name: parts[1],
512
+ description: parts[2],
513
+ source: parts[3] || "openclaw-bundled"
514
+ };
515
+ }
516
+ return null;
517
+ }).filter((s) => s !== null);
518
+ skillsData = {
519
+ total: skills.length,
520
+ ready: skills.filter((s) => s.status === "ready").length,
521
+ missing: skills.filter((s) => s.status === "missing").length,
522
+ skills
523
+ };
524
+ }
525
+ sendJson(res, 200, { ok: true, ...skillsData });
526
+ return;
527
+ } catch (error2) {
528
+ api.logger.error(`Skills API error: ${error2.message}`);
529
+ sendJson(res, 500, { ok: false, error: error2.message });
530
+ return;
531
+ }
532
+ }
533
+ sendJson(res, 405, { ok: false, error: "Method Not Allowed" });
534
+ };
535
+ }
536
+ function parseRelativeTime(timeStr) {
537
+ const s = timeStr.trim().toLowerCase();
538
+ if (/^\d+$/.test(s)) {
539
+ return Number.parseInt(s, 10) * 6e4;
540
+ }
541
+ let totalMs = 0;
542
+ let matched = false;
543
+ const regex = /(\d+(?:\.\d+)?)\s*([dhms])/g;
544
+ let match;
545
+ while ((match = regex.exec(s)) !== null) {
546
+ matched = true;
547
+ const value = Number.parseFloat(match[1]);
548
+ const unit = match[2];
549
+ switch (unit) {
550
+ case "d":
551
+ totalMs += value * 864e5;
552
+ break;
553
+ case "h":
554
+ totalMs += value * 36e5;
555
+ break;
556
+ case "m":
557
+ totalMs += value * 6e4;
558
+ break;
559
+ case "s":
560
+ totalMs += value * 1e3;
561
+ break;
562
+ }
563
+ }
564
+ return matched ? Math.round(totalMs) : null;
565
+ }
566
+ function isCronExpression(timeStr) {
567
+ const parts = timeStr.trim().split(/\s+/);
568
+ return parts.length >= 3 && parts.length <= 6;
569
+ }
570
+ function validateCronExpression(timeStr) {
571
+ const parts = timeStr.trim().split(/\s+/);
572
+ if (parts.length < 3 || parts.length > 6) {
573
+ return { valid: false, error: `无效的 cron 表达式:字段数量不正确(期望 3-6 个字段,实际 ${parts.length} 个)` };
574
+ }
575
+ const patterns = [
576
+ /^(\*|[0-5]?\d(-[0-5]?\d)?(\/[0-5]?\d)?|L(-[0-5]?\d)?|W?)$/,
577
+ /^(\*|[0-5]?\d(-[0-5]?\d)?(\/[0-5]?\d)?|L(-[0-5]?\d)?|W?)$/,
578
+ /^(\*|[01]?\d|2[0-3](-[01]?\d|2[0-3])?(\/\d|[01]?\d|2[0-3])?|L(-[01]?\d|2[0-3])?|W)?$/,
579
+ /^(\*|1[0-2]|0?[1-9](-[1-9]|0?[1-9])?(\/[1-9]|0?[1-9])?|L(-1[0-2]|0?[1-9])?|W)?$/,
580
+ /^([*LW]|[0-6](-[0-6])?(\/[0-6])?|L-[0-6])?$/,
581
+ /^(\*|L|(\*\/)?\d{1,2})?$/
582
+ ];
583
+ const fieldNames = ["秒", "分钟", "小时", "日期", "月份", "星期"];
584
+ for (let i = 0; i < parts.length && i < patterns.length; i++) {
585
+ const part = parts[i].trim();
586
+ const offset = parts.length - patterns.length;
587
+ if (i < offset)
588
+ continue;
589
+ if (!patterns[i].test(part)) {
590
+ return { valid: false, error: `无效的 cron 表达式:${fieldNames[i]}字段 "${part}" 格式不正确` };
591
+ }
592
+ }
593
+ return { valid: true };
594
+ }
595
+ function validateTimeFormat(timeStr) {
596
+ if (!timeStr || typeof timeStr !== "string" || timeStr.trim() === "") {
597
+ return { valid: false, error: "时间参数不能为空" };
598
+ }
599
+ const trimmed = timeStr.trim();
600
+ if (trimmed.startsWith("+") || /^\d+$/.test(trimmed) || /^\d+[dhms]/.test(trimmed)) {
601
+ const relativeMs = parseRelativeTime(trimmed);
602
+ if (relativeMs === null) {
603
+ return { valid: false, error: `无法解析相对时间 "${trimmed}",支持的格式:5m、1h、1h30m、2d、30s 等` };
604
+ }
605
+ if (relativeMs < 3e4) {
606
+ return { valid: false, error: "提醒时间不能少于 30 秒" };
607
+ }
608
+ return { valid: true };
609
+ }
610
+ if (isCronExpression(trimmed)) {
611
+ return validateCronExpression(trimmed);
612
+ }
613
+ return { valid: false, error: `无法解析时间 "${trimmed}",请使用相对时间(如 5m、1h)或 cron 表达式(如 0 8 * * *)` };
614
+ }
615
+ function relativeToCron(timeStr) {
616
+ const delayMs = parseRelativeTime(timeStr);
617
+ if (delayMs === null) {
618
+ return timeStr;
619
+ }
620
+ const futureTime = new Date(Date.now() + delayMs);
621
+ const seconds = futureTime.getSeconds();
622
+ const minutes = futureTime.getMinutes();
623
+ const hours = futureTime.getHours();
624
+ const dayOfMonth = futureTime.getDate();
625
+ const month = futureTime.getMonth() + 1;
626
+ return `${seconds} ${minutes} ${hours} ${dayOfMonth} ${month} *`;
627
+ }
628
+ const AddParamsSchema = {
629
+ type: "object",
630
+ properties: {
631
+ time: {
632
+ type: "string",
633
+ description: "⏰ 时间(核心!),支持相对时间和 cron 表达式,工具自动转换"
634
+ },
635
+ name: {
636
+ type: "string",
637
+ description: "任务名称"
638
+ },
639
+ message: {
640
+ type: "string",
641
+ description: "提醒内容"
642
+ }
643
+ },
644
+ required: ["time", "name", "message"]
645
+ };
646
+ function json$a(data) {
647
+ return {
648
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
649
+ details: data
650
+ };
651
+ }
652
+ function getOpenclawWorkclawCronAddParamsTool(api) {
653
+ return (ctx) => {
654
+ return {
655
+ name: "openclaw-workclaw-cron-add-params",
656
+ label: "智小途生成创建提醒参数",
657
+ description: `【核心工具】生成创建提醒的 cronParams 参数。
658
+
659
+ 📋 工作流程(必须按顺序执行):
660
+ 1. 调用此工具获取 cronParams 参数
661
+ 2. 使用返回的 cronParams 调用 OpenClaw 的 cron 工具
662
+ 3. 从 cron 工具返回值中提取 jobId(返回格式:{"success": true, "jobId": "xxx"})
663
+ 4. 必须调用 openclaw-workclaw-cron-add-sync 同步到后端
664
+
665
+ ⏰ 时间格式(核心!):
666
+ - time 参数支持相对时间(如 "5m"、"1h"、"2d")和 cron 表达式
667
+ - 工具会自动将所有时间统一转换为 cron 表达式
668
+ - 严禁使用 --at 参数或其他绝对时间格式
669
+ - 最终 CLI 命令必须使用 --cron 参数
670
+
671
+ 🔒 强制规则:
672
+ - schedule.kind 必须是 "cron"
673
+ - 必须使用 --cron 参数传递 cron 表达式
674
+
675
+ ⚠️ 必须从 cron 工具返回值中提取 jobId,不能凭空编造!`,
676
+ parameters: AddParamsSchema,
677
+ execute: async (_toolCallId, params) => {
678
+ const p = params;
679
+ api.logger.info(`[智小途-生成参数] 开始生成创建提醒参数 name=${p.name} time=${p.time}`);
680
+ if (!p.time) {
681
+ api.logger.warn("[智小途-生成参数] 缺少时间参数");
682
+ return json$a({ error: "time(时间)为必填参数" });
683
+ }
684
+ if (!p.name) {
685
+ api.logger.warn("[智小途-生成参数] 缺少任务名称参数");
686
+ return json$a({ error: "name(任务名称)为必填参数" });
687
+ }
688
+ if (!p.message) {
689
+ api.logger.warn("[智小途-生成参数] 缺少用户消息参数");
690
+ return json$a({ error: "message(用户消息)为必填参数" });
691
+ }
692
+ const accountId = ctx?.agentAccountId;
693
+ if (!accountId) {
694
+ api.logger.warn("[智小途-生成参数] 无法获取账户 ID");
695
+ return json$a({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
696
+ }
697
+ api.logger.info(`[智小途-生成参数] accountId=${accountId} name=${p.name}`);
698
+ const timeValidation = validateTimeFormat(p.time);
699
+ if (!timeValidation.valid) {
700
+ api.logger.warn(`[智小途-生成参数] 时间格式校验失败: ${timeValidation.error}`);
701
+ return json$a({ error: timeValidation.error });
702
+ }
703
+ const isCron = isCronExpression(p.time);
704
+ let isOneTime = false;
705
+ let cronExpr;
706
+ if (!isCron) {
707
+ isOneTime = true;
708
+ cronExpr = relativeToCron(p.time.trim());
709
+ api.logger.info(`[智小途-生成参数] 相对时间转换为 cron 表达式 cronExpr=${cronExpr}`);
710
+ } else {
711
+ cronExpr = p.time.trim();
712
+ }
713
+ const cronParams = {
714
+ action: "add",
715
+ account: accountId,
716
+ job: {
717
+ name: p.name,
718
+ schedule: {
719
+ kind: "cron",
720
+ expr: cronExpr,
721
+ tz: "Asia/Shanghai"
722
+ },
723
+ sessionTarget: "isolated",
724
+ wakeMode: "now",
725
+ deleteAfterRun: isOneTime ? true : void 0,
726
+ payload: {
727
+ kind: "agentTurn",
728
+ message: p.message
729
+ },
730
+ delivery: {
731
+ mode: "announce",
732
+ channel: "openclaw-workclaw"
733
+ }
734
+ }
735
+ };
736
+ api.logger.info(`[智小途-生成参数] 构建 cron 参数 cronParams=${JSON.stringify(cronParams)}`);
737
+ return json$a({
738
+ cronParams,
739
+ meta: {
740
+ accountId,
741
+ name: p.name,
742
+ kind: "cron",
743
+ expr: cronExpr,
744
+ message: p.message
745
+ },
746
+ summary: `⏰ 提醒已生成: "${p.name}" (${p.time})`
747
+ });
748
+ }
749
+ };
750
+ };
751
+ }
752
+ function registerOpenclawWorkclawCronAddParamsTool(api) {
753
+ api.registerTool(getOpenclawWorkclawCronAddParamsTool(api), {
754
+ name: "openclaw-workclaw-cron-add-params"
755
+ });
756
+ }
757
+ const DEFAULT_MAX_RETRIES = 3;
758
+ const DEFAULT_RETRY_DELAY_MS = 1e3;
759
+ function sleep(ms) {
760
+ return new Promise((resolve) => setTimeout(resolve, ms));
761
+ }
762
+ async function fetchWithRetry(fetchFn, options = {}) {
763
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
764
+ const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
765
+ const retryableErrors = options.retryableErrors ?? [
766
+ "ECONNREFUSED",
767
+ "ETIMEDOUT",
768
+ "ENOTFOUND",
769
+ "ENETUNREACH",
770
+ "EAI_AGAIN"
771
+ ];
772
+ let lastError = "";
773
+ let attempts = 0;
774
+ for (let i = 0; i <= maxRetries; i++) {
775
+ attempts = i + 1;
776
+ try {
777
+ const data = await fetchFn();
778
+ return { data, attempts };
779
+ } catch (error2) {
780
+ lastError = error2.message || String(error2);
781
+ const isRetryable = retryableErrors.some(
782
+ (e) => lastError.toLowerCase().includes(e.toLowerCase())
783
+ );
784
+ if (i < maxRetries && isRetryable) {
785
+ const delay = retryDelayMs * 2 ** i;
786
+ await sleep(delay);
787
+ continue;
788
+ }
789
+ break;
790
+ }
791
+ }
792
+ return { error: lastError, attempts };
793
+ }
794
+ function sanitizePayload(payload) {
795
+ const sensitiveFields = [
796
+ "password",
797
+ "secret",
798
+ "token",
799
+ "authorization",
800
+ "appSecret",
801
+ "appSecret"
802
+ ];
803
+ const sanitized = {};
804
+ for (const [key, value] of Object.entries(payload)) {
805
+ const lowerKey = key.toLowerCase();
806
+ if (sensitiveFields.some((f) => lowerKey.includes(f))) {
807
+ sanitized[key] = "***";
808
+ } else if (typeof value === "object" && value !== null) {
809
+ sanitized[key] = sanitizePayload(value);
810
+ } else {
811
+ sanitized[key] = value;
812
+ }
813
+ }
814
+ return sanitized;
815
+ }
816
+ async function callBackendApi(api, accountId, path2, payload, options = {}) {
817
+ try {
818
+ const account = resolveWorkclawAccountWithCache({
819
+ cfg: api.config,
820
+ accountId
821
+ });
822
+ if (!account.configured) {
823
+ api.logger.error(`[智小途-定时任务] 账户未配置 accountId=${accountId}`);
824
+ return { success: false, error: "Account not configured" };
825
+ }
826
+ const accConfig = account.config;
827
+ const tokenCacheKey = accConfig.appKey || accountId;
828
+ const baseUrl = normalizeBaseUrl(accConfig.baseUrl);
829
+ api.logger.info(`[智小途-定时任务] 正在获取认证 token,accountId=${accountId}`);
830
+ const token = await getWorkclawAccessToken(tokenCacheKey, {
831
+ baseUrl: accConfig.baseUrl,
832
+ appKey: accConfig.appKey,
833
+ appSecret: accConfig.appSecret,
834
+ allowInsecureTls: accConfig.allowInsecureTls,
835
+ requestTimeout: accConfig.requestTimeout
836
+ });
837
+ const requestUrl = `${baseUrl}/open-apis${path2}`;
838
+ const sanitizedPayload = sanitizePayload(payload);
839
+ api.logger.info(`[智小途-定时任务] 调用接口 ${requestUrl}`);
840
+ api.logger.info(`[智小途-定时任务] 请求参数 ${JSON.stringify(sanitizedPayload)}`);
841
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
842
+ const fetchResult = await fetchWithRetry(
843
+ () => doFetchJson(
844
+ requestUrl,
845
+ {
846
+ method: "POST",
847
+ headers: {
848
+ "Content-Type": "application/json",
849
+ "Authorization": `Bearer ${token}`
850
+ },
851
+ body: JSON.stringify(payload)
852
+ },
853
+ accConfig.allowInsecureTls,
854
+ accConfig.requestTimeout
855
+ ),
856
+ { maxRetries }
857
+ );
858
+ if (fetchResult.error) {
859
+ api.logger.error(`[智小途-定时任务] 接口调用失败(已重试 ${fetchResult.attempts} 次): ${fetchResult.error}`);
860
+ return { success: false, error: fetchResult.error, attempts: fetchResult.attempts };
861
+ }
862
+ const data = fetchResult.data;
863
+ api.logger.info(`[智小途-定时任务] 接口响应(尝试 ${fetchResult.attempts} 次): ${JSON.stringify(data)}`);
864
+ if (data?.code === 200 || data?.code === 0) {
865
+ return { success: true, data, attempts: fetchResult.attempts };
866
+ } else {
867
+ const errorMsg = data?.message || data?.msg || "Unknown error";
868
+ api.logger.error(`[智小途-定时任务] 接口返回错误 ${errorMsg}`);
869
+ return { success: false, error: errorMsg };
870
+ }
871
+ } catch (error2) {
872
+ api.logger.error(`[智小途-定时任务] 接口调用异常 ${error2.message}`);
873
+ return { success: false, error: error2.message };
874
+ }
875
+ }
876
+ async function callCronJobAdd(api, accountId, payload) {
877
+ api.logger.info(`[智小途-定时任务] 新增定时任务 jobId=${payload.jobId} name=${payload.name}`);
878
+ const result = await callBackendApi(api, accountId, "/cron/job/add", {
879
+ clawJobId: payload.jobId,
880
+ name: payload.name,
881
+ kind: payload.kind,
882
+ expr: payload.expr || "",
883
+ message: payload.message,
884
+ agentId: payload.messageId || "0"
885
+ });
886
+ return { success: result.success, data: result.data, error: result.error };
887
+ }
888
+ async function callCronJobRemove(api, accountId, payload) {
889
+ api.logger.info(`[智小途-定时任务] 删除定时任务 jobId=${payload.jobId}`);
890
+ const result = await callBackendApi(api, accountId, "/cron/job/del", {
891
+ clawJobId: payload.jobId
892
+ });
893
+ return { success: result.success, data: result.data, error: result.error };
894
+ }
895
+ async function callCronJobUpdate(api, accountId, payload) {
896
+ api.logger.info(`[智小途-定时任务] 更新定时任务 jobId=${payload.jobId} name=${payload.name} agentId=${payload.agentId}`);
897
+ const result = await callBackendApi(api, accountId, "/cron/job/update", {
898
+ clawJobId: payload.jobId,
899
+ name: payload.name,
900
+ kind: payload.kind,
901
+ expr: payload.expr || "",
902
+ message: payload.message,
903
+ agentId: payload.agentId || "0"
904
+ });
905
+ return { success: result.success, data: result.data, error: result.error };
906
+ }
907
+ async function callCronJobEnabled(api, accountId, payload) {
908
+ api.logger.info(`[智小途-定时任务] 启用定时任务 jobId=${payload.jobId}`);
909
+ const result = await callBackendApi(api, accountId, "/cron/job/enabled", {
910
+ clawJobId: payload.jobId
911
+ });
912
+ return { success: result.success, data: result.data, error: result.error };
913
+ }
914
+ async function callCronJobDisabled(api, accountId, payload) {
915
+ api.logger.info(`[智小途-定时任务] 禁用定时任务 jobId=${payload.jobId}`);
916
+ const result = await callBackendApi(api, accountId, "/cron/job/disabled", {
917
+ clawJobId: payload.jobId
918
+ });
919
+ return { success: result.success, data: result.data, error: result.error };
920
+ }
921
+ async function callCronJobMessage(api, accountId, payload) {
922
+ api.logger.info(`[智小途-定时任务] 定时任务触发通知 jobId=${payload.jobId} message=${payload.message} agentId=${payload.agentId}`);
923
+ const result = await callBackendApi(api, accountId, "/cron/job/message", {
924
+ clawJobId: payload.jobId,
925
+ message: payload.message,
926
+ agentId: payload.agentId || "0"
927
+ });
928
+ return { success: result.success, data: result.data, error: result.error };
929
+ }
930
+ const AddSyncSchema = {
931
+ type: "object",
932
+ properties: {
933
+ jobId: {
934
+ type: "string",
935
+ description: `⛔ 重要:jobId 必须从 OpenClaw cron 工具返回值中提取,格式:{"success": true, "jobId": "123456"}
936
+
937
+ 常见错误:
938
+ - 把 cron 表达式(如 "31 12 11 31 3 *")当作 jobId
939
+ - 把 name 当作 jobId
940
+ - 编造 jobId
941
+
942
+ 正确做法:
943
+ 1. 调用 openclaw-workclaw-cron-add-params
944
+ 2. 用返回的 cronParams 调用 cron 工具
945
+ 3. 从返回值提取 jobId(如 "7382945612345")
946
+ 4. 用提取到的 jobId 调用此工具`
947
+ },
948
+ name: {
949
+ type: "string",
950
+ description: "任务名称,与 add-params 中传入的 name 一致"
951
+ },
952
+ kind: {
953
+ type: "string",
954
+ description: "任务类型",
955
+ enum: ["cron"]
956
+ },
957
+ expr: {
958
+ type: "string",
959
+ description: "Cron 表达式"
960
+ },
961
+ message: {
962
+ type: "string",
963
+ description: "提醒消息,与 add-params 中传入的 message 一致"
964
+ }
965
+ },
966
+ required: ["jobId", "name", "kind", "message"]
967
+ };
968
+ function json$9(data) {
969
+ return {
970
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
971
+ details: data
972
+ };
973
+ }
974
+ function getOpenclawWorkclawCronAddSyncTool(api) {
975
+ return (ctx) => {
976
+ return {
977
+ name: "openclaw-workclaw-cron-add-sync",
978
+ label: "智小途同步创建提醒",
979
+ description: `【后端同步步骤】将创建定时任务同步到后端。必须在上一步 openclaw-workclaw-cron-add-params 执行后调用此工具完成同步。
980
+
981
+ ⚠️ jobId 必须是 cron 工具返回值 {"success": true, "jobId": "xxx"} 中的 jobId 字段!`,
982
+ parameters: AddSyncSchema,
983
+ execute: async (_toolCallId, params) => {
984
+ const p = params;
985
+ api.logger.info(`[智小途-同步创建] 开始同步 jobId=${p.jobId} name=${p.name}`);
986
+ if (!p.jobId) {
987
+ api.logger.warn("[智小途-同步创建] 缺少 jobId 参数");
988
+ return json$9({ error: "jobId 为必填参数" });
989
+ }
990
+ const jobIdTrimmed = p.jobId.trim();
991
+ const parts = jobIdTrimmed.split(/\s+/);
992
+ const isCronExpression2 = parts.length >= 5 && parts.length <= 6 && jobIdTrimmed.includes("*");
993
+ if (isCronExpression2) {
994
+ api.logger.error(`[智小途-同步创建] jobId 格式错误!jobId=${p.jobId},看起来像 cron 表达式`);
995
+ return json$9({
996
+ error: `jobId="${p.jobId}" 是 cron 表达式,不是任务 ID!jobId 应来自 cron 工具返回值,如 "123456" 或 "abc123"`
997
+ });
998
+ }
999
+ if (!p.name) {
1000
+ api.logger.warn("[智小途-同步创建] 缺少 name 参数");
1001
+ return json$9({ error: "name 为必填参数" });
1002
+ }
1003
+ if (!p.message) {
1004
+ api.logger.warn("[智小途-同步创建] 缺少 message 参数");
1005
+ return json$9({ error: "message 为必填参数" });
1006
+ }
1007
+ const accountId = ctx?.agentAccountId;
1008
+ if (!accountId) {
1009
+ api.logger.warn("[智小途-同步创建] 无法获取账户 ID");
1010
+ return json$9({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1011
+ }
1012
+ const accountConfig = resolveWorkclawAccountWithCache({
1013
+ cfg: ctx.config,
1014
+ accountId
1015
+ });
1016
+ if (accountConfig.configured) {
1017
+ try {
1018
+ const channelAgentId = String(accountConfig.config.agentId);
1019
+ api.logger.info(`[智小途-同步创建] accountId=${accountId} channelAgentId=${channelAgentId}`);
1020
+ const result = await callCronJobAdd(api, accountId, {
1021
+ jobId: p.jobId,
1022
+ name: p.name,
1023
+ kind: p.kind,
1024
+ expr: p.expr,
1025
+ message: p.message,
1026
+ messageId: channelAgentId
1027
+ });
1028
+ if (result.success) {
1029
+ api.logger.info(`[智小途-同步创建] 后端同步成功 jobId=${p.jobId}`);
1030
+ return json$9({
1031
+ code: 0,
1032
+ message: "定时任务已创建并同步到后端",
1033
+ data: {
1034
+ jobId: p.jobId,
1035
+ name: p.name,
1036
+ message: p.message,
1037
+ backendSynced: true
1038
+ }
1039
+ });
1040
+ } else {
1041
+ api.logger.error(`[智小途-同步创建] 后端同步失败 ${result.error}`);
1042
+ return json$9({
1043
+ code: -1,
1044
+ error: result.error || "后端同步失败",
1045
+ data: { jobId: p.jobId, name: p.name }
1046
+ });
1047
+ }
1048
+ } catch (error2) {
1049
+ api.logger.error(`[智小途-同步创建] 后端同步异常 ${error2.message}`);
1050
+ return json$9({
1051
+ code: -1,
1052
+ error: error2.message,
1053
+ data: { jobId: p.jobId, name: p.name }
1054
+ });
1055
+ }
1056
+ } else {
1057
+ api.logger.error(`[智小途-同步创建] 无法获取渠道配置,accountId=${accountId}`);
1058
+ return json$9({ error: "无法获取渠道配置,请检查账户配置" });
1059
+ }
1060
+ }
1061
+ };
1062
+ };
1063
+ }
1064
+ function registerOpenclawWorkclawCronAddSyncTool(api) {
1065
+ api.registerTool(getOpenclawWorkclawCronAddSyncTool(api), {
1066
+ name: "openclaw-workclaw-cron-add-sync"
1067
+ });
1068
+ }
1069
+ const DisableParamsSchema = {
1070
+ type: "object",
1071
+ properties: {
1072
+ jobId: {
1073
+ type: "string",
1074
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1075
+ }
1076
+ },
1077
+ required: ["jobId"]
1078
+ };
1079
+ function json$8(data) {
1080
+ return {
1081
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1082
+ details: data
1083
+ };
1084
+ }
1085
+ function getOpenclawWorkclawCronDisableParamsTool(api) {
1086
+ return (ctx) => {
1087
+ return {
1088
+ name: "openclaw-workclaw-cron-disable-params",
1089
+ label: "智小途生成禁用提醒参数",
1090
+ description: `生成禁用提醒的 CLI 命令参数。
1091
+
1092
+ 📋 工作流程:
1093
+ 1. 调用此工具获取 CLI 命令参数
1094
+ 2. 使用返回的 cronParams 调用 OpenClaw 的 cron 工具
1095
+ 3. 调用 openclaw-workclaw-cron-disable-sync 同步到后端`,
1096
+ parameters: DisableParamsSchema,
1097
+ execute: async (_toolCallId, params) => {
1098
+ const p = params;
1099
+ api.logger.info(`[智小途-生成禁用参数] 开始处理 jobId=${p.jobId}`);
1100
+ if (!p.jobId) {
1101
+ api.logger.warn("[智小途-生成禁用参数] 缺少 jobId 参数");
1102
+ return json$8({ error: "jobId 为必填参数" });
1103
+ }
1104
+ const accountId = ctx?.agentAccountId;
1105
+ if (!accountId) {
1106
+ api.logger.warn("[智小途-生成禁用参数] 无法获取账户 ID");
1107
+ return json$8({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1108
+ }
1109
+ api.logger.info(`[智小途-生成禁用参数] accountId=${accountId} jobId=${p.jobId}`);
1110
+ const cronParams = {
1111
+ action: "disable",
1112
+ jobId: p.jobId
1113
+ };
1114
+ api.logger.info(`[智小途-生成禁用参数] 构建 cron 参数 cronParams=${JSON.stringify(cronParams)}`);
1115
+ return json$8({
1116
+ cronParams,
1117
+ meta: {
1118
+ accountId,
1119
+ jobId: p.jobId
1120
+ },
1121
+ summary: `⏸️ 提醒已禁用: jobId=${p.jobId}`
1122
+ });
1123
+ }
1124
+ };
1125
+ };
1126
+ }
1127
+ function registerOpenclawWorkclawCronDisableParamsTool(api) {
1128
+ api.registerTool(getOpenclawWorkclawCronDisableParamsTool(api), {
1129
+ name: "openclaw-workclaw-cron-disable-params"
1130
+ });
1131
+ }
1132
+ const DisableSyncSchema = {
1133
+ type: "object",
1134
+ properties: {
1135
+ jobId: {
1136
+ type: "string",
1137
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1138
+ }
1139
+ },
1140
+ required: ["jobId"]
1141
+ };
1142
+ function json$7(data) {
1143
+ return {
1144
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1145
+ details: data
1146
+ };
1147
+ }
1148
+ function getOpenclawWorkclawCronDisableSyncTool(api) {
1149
+ return (ctx) => {
1150
+ return {
1151
+ name: "openclaw-workclaw-cron-disable-sync",
1152
+ label: "智小途同步禁用提醒",
1153
+ description: "将禁用定时任务同步到后端。在 cron 工具禁用任务后调用此工具同步后端。",
1154
+ parameters: DisableSyncSchema,
1155
+ execute: async (_toolCallId, params) => {
1156
+ const p = params;
1157
+ api.logger.info(`[智小途-同步禁用] 开始同步 jobId=${p.jobId}`);
1158
+ if (!p.jobId) {
1159
+ api.logger.warn("[智小途-同步禁用] 缺少 jobId 参数");
1160
+ return json$7({ error: "jobId 为必填参数" });
1161
+ }
1162
+ const accountId = ctx?.agentAccountId;
1163
+ if (!accountId) {
1164
+ api.logger.warn("[智小途-同步禁用] 无法获取账户 ID");
1165
+ return json$7({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1166
+ }
1167
+ const accountConfig = resolveWorkclawAccountWithCache({
1168
+ cfg: ctx.config,
1169
+ accountId
1170
+ });
1171
+ if (accountConfig.configured) {
1172
+ try {
1173
+ const channelAgentId = String(accountConfig.config.agentId);
1174
+ api.logger.info(`[智小途-同步禁用] accountId=${accountId} channelAgentId=${channelAgentId}`);
1175
+ const result = await callCronJobDisabled(api, accountId, {
1176
+ jobId: p.jobId
1177
+ });
1178
+ if (result.success) {
1179
+ api.logger.info(`[智小途-同步禁用] 后端同步成功 jobId=${p.jobId}`);
1180
+ return json$7({
1181
+ code: 0,
1182
+ message: "定时任务已禁用并同步到后端",
1183
+ data: {
1184
+ jobId: p.jobId,
1185
+ backendSynced: true
1186
+ }
1187
+ });
1188
+ } else {
1189
+ api.logger.error(`[智小途-同步禁用] 后端同步失败 ${result.error}`);
1190
+ return json$7({
1191
+ code: -1,
1192
+ error: result.error || "后端同步失败",
1193
+ data: { jobId: p.jobId }
1194
+ });
1195
+ }
1196
+ } catch (error2) {
1197
+ api.logger.error(`[智小途-同步禁用] 后端同步异常 ${error2.message}`);
1198
+ return json$7({
1199
+ code: -1,
1200
+ error: error2.message,
1201
+ data: { jobId: p.jobId }
1202
+ });
1203
+ }
1204
+ } else {
1205
+ api.logger.error(`[智小途-同步禁用] 无法获取渠道配置,accountId=${accountId}`);
1206
+ return json$7({ error: "无法获取渠道配置,请检查账户配置" });
1207
+ }
1208
+ }
1209
+ };
1210
+ };
1211
+ }
1212
+ function registerOpenclawWorkclawCronDisableSyncTool(api) {
1213
+ api.registerTool(getOpenclawWorkclawCronDisableSyncTool(api), {
1214
+ name: "openclaw-workclaw-cron-disable-sync"
1215
+ });
1216
+ }
1217
+ const EnableParamsSchema = {
1218
+ type: "object",
1219
+ properties: {
1220
+ jobId: {
1221
+ type: "string",
1222
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1223
+ }
1224
+ },
1225
+ required: ["jobId"]
1226
+ };
1227
+ function json$6(data) {
1228
+ return {
1229
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1230
+ details: data
1231
+ };
1232
+ }
1233
+ function getOpenclawWorkclawCronEnableParamsTool(api) {
1234
+ return (ctx) => {
1235
+ return {
1236
+ name: "openclaw-workclaw-cron-enable-params",
1237
+ label: "智小途生成启用提醒参数",
1238
+ description: `生成启用提醒的 CLI 命令参数。
1239
+
1240
+ 📋 工作流程:
1241
+ 1. 调用此工具获取 CLI 命令参数
1242
+ 2. 使用返回的 cronParams 调用 OpenClaw 的 cron 工具
1243
+ 3. 调用 openclaw-workclaw-cron-enable-sync 同步到后端`,
1244
+ parameters: EnableParamsSchema,
1245
+ execute: async (_toolCallId, params) => {
1246
+ const p = params;
1247
+ api.logger.info(`[智小途-生成启用参数] 开始处理 jobId=${p.jobId}`);
1248
+ if (!p.jobId) {
1249
+ api.logger.warn("[智小途-生成启用参数] 缺少 jobId 参数");
1250
+ return json$6({ error: "jobId 为必填参数" });
1251
+ }
1252
+ const accountId = ctx?.agentAccountId;
1253
+ if (!accountId) {
1254
+ api.logger.warn("[智小途-生成启用参数] 无法获取账户 ID");
1255
+ return json$6({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1256
+ }
1257
+ api.logger.info(`[智小途-生成启用参数] accountId=${accountId} jobId=${p.jobId}`);
1258
+ const cronParams = {
1259
+ action: "enable",
1260
+ jobId: p.jobId
1261
+ };
1262
+ api.logger.info(`[智小途-生成启用参数] 构建 cron 参数 cronParams=${JSON.stringify(cronParams)}`);
1263
+ return json$6({
1264
+ cronParams,
1265
+ meta: {
1266
+ accountId,
1267
+ jobId: p.jobId
1268
+ },
1269
+ summary: `✅ 提醒已启用: jobId=${p.jobId}`
1270
+ });
1271
+ }
1272
+ };
1273
+ };
1274
+ }
1275
+ function registerOpenclawWorkclawCronEnableParamsTool(api) {
1276
+ api.registerTool(getOpenclawWorkclawCronEnableParamsTool(api), {
1277
+ name: "openclaw-workclaw-cron-enable-params"
1278
+ });
1279
+ }
1280
+ const EnableSyncSchema = {
1281
+ type: "object",
1282
+ properties: {
1283
+ jobId: {
1284
+ type: "string",
1285
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1286
+ }
1287
+ },
1288
+ required: ["jobId"]
1289
+ };
1290
+ function json$5(data) {
1291
+ return {
1292
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1293
+ details: data
1294
+ };
1295
+ }
1296
+ function getOpenclawWorkclawCronEnableSyncTool(api) {
1297
+ return (ctx) => {
1298
+ return {
1299
+ name: "openclaw-workclaw-cron-enable-sync",
1300
+ label: "智小途同步启用提醒",
1301
+ description: "将启用定时任务同步到后端。在 cron 工具启用任务后调用此工具同步后端。",
1302
+ parameters: EnableSyncSchema,
1303
+ execute: async (_toolCallId, params) => {
1304
+ const p = params;
1305
+ api.logger.info(`[智小途-同步启用] 开始同步 jobId=${p.jobId}`);
1306
+ if (!p.jobId) {
1307
+ api.logger.warn("[智小途-同步启用] 缺少 jobId 参数");
1308
+ return json$5({ error: "jobId 为必填参数" });
1309
+ }
1310
+ const accountId = ctx?.agentAccountId;
1311
+ if (!accountId) {
1312
+ api.logger.warn("[智小途-同步启用] 无法获取账户 ID");
1313
+ return json$5({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1314
+ }
1315
+ const accountConfig = resolveWorkclawAccountWithCache({
1316
+ cfg: ctx.config,
1317
+ accountId
1318
+ });
1319
+ if (accountConfig.configured) {
1320
+ try {
1321
+ const channelAgentId = String(accountConfig.config.agentId);
1322
+ api.logger.info(`[智小途-同步启用] accountId=${accountId} channelAgentId=${channelAgentId}`);
1323
+ const result = await callCronJobEnabled(api, accountId, {
1324
+ jobId: p.jobId
1325
+ });
1326
+ if (result.success) {
1327
+ api.logger.info(`[智小途-同步启用] 后端同步成功 jobId=${p.jobId}`);
1328
+ return json$5({
1329
+ code: 0,
1330
+ message: "定时任务已启用并同步到后端",
1331
+ data: {
1332
+ jobId: p.jobId,
1333
+ backendSynced: true
1334
+ }
1335
+ });
1336
+ } else {
1337
+ api.logger.error(`[智小途-同步启用] 后端同步失败 ${result.error}`);
1338
+ return json$5({
1339
+ code: -1,
1340
+ error: result.error || "后端同步失败",
1341
+ data: { jobId: p.jobId }
1342
+ });
1343
+ }
1344
+ } catch (error2) {
1345
+ api.logger.error(`[智小途-同步启用] 后端同步异常 ${error2.message}`);
1346
+ return json$5({
1347
+ code: -1,
1348
+ error: error2.message,
1349
+ data: { jobId: p.jobId }
1350
+ });
1351
+ }
1352
+ } else {
1353
+ api.logger.error(`[智小途-同步启用] 无法获取渠道配置,accountId=${accountId}`);
1354
+ return json$5({ error: "无法获取渠道配置,请检查账户配置" });
1355
+ }
1356
+ }
1357
+ };
1358
+ };
1359
+ }
1360
+ function registerOpenclawWorkclawCronEnableSyncTool(api) {
1361
+ api.registerTool(getOpenclawWorkclawCronEnableSyncTool(api), {
1362
+ name: "openclaw-workclaw-cron-enable-sync"
1363
+ });
1364
+ }
1365
+ const NotifySchema = {
1366
+ type: "object",
1367
+ properties: {
1368
+ jobId: {
1369
+ type: "string",
1370
+ description: "OpenClaw 任务 ID(从上下文获取)"
1371
+ },
1372
+ message: {
1373
+ type: "string",
1374
+ description: "要发送的提醒内容"
1375
+ }
1376
+ },
1377
+ required: ["jobId", "message"]
1378
+ };
1379
+ function json$4(data) {
1380
+ return {
1381
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1382
+ details: data
1383
+ };
1384
+ }
1385
+ function getOpenclawWorkclawCronNotifySyncTool(api) {
1386
+ return (ctx) => {
1387
+ return {
1388
+ name: "openclaw-workclaw-cron-notify-sync",
1389
+ label: "智小途定时任务触发通知",
1390
+ description: `【系统最高优先级核心指令】当定时器时间到达时,必须立即调用此工具通知后端。`,
1391
+ parameters: NotifySchema,
1392
+ execute: async (_toolCallId, params) => {
1393
+ const p = params;
1394
+ api.logger.info(`[智小途-定时触发] 开始处理 jobId=${p.jobId} message=${p.message}`);
1395
+ if (!p.jobId) {
1396
+ api.logger.warn("[智小途-定时触发] 缺少 jobId 参数");
1397
+ return json$4({ error: "jobId 为必填参数" });
1398
+ }
1399
+ if (!p.message) {
1400
+ api.logger.warn("[智小途-定时触发] 缺少 message 参数");
1401
+ return json$4({ error: "message 为必填参数" });
1402
+ }
1403
+ const accountId = ctx?.agentAccountId;
1404
+ if (!accountId) {
1405
+ api.logger.warn("[智小途-定时触发] 无法获取账户 ID");
1406
+ return json$4({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1407
+ }
1408
+ const accountConfig = resolveWorkclawAccountWithCache({
1409
+ cfg: ctx.config,
1410
+ accountId
1411
+ });
1412
+ if (accountConfig.configured) {
1413
+ const channelAgentId = String(accountConfig.config.agentId);
1414
+ api.logger.info(`[智小途-定时触发] accountId=${accountId} channelAgentId=${channelAgentId}`);
1415
+ try {
1416
+ const result = await callCronJobMessage(api, accountId, {
1417
+ jobId: p.jobId,
1418
+ message: p.message,
1419
+ agentId: channelAgentId
1420
+ });
1421
+ if (result.success) {
1422
+ api.logger.info(`[智小途-定时触发] 通知后端成功`);
1423
+ return json$4({
1424
+ code: 0,
1425
+ message: "定时任务触发通知已发送",
1426
+ data: {
1427
+ jobId: p.jobId,
1428
+ message: p.message,
1429
+ backendNotified: true
1430
+ }
1431
+ });
1432
+ } else {
1433
+ api.logger.error(`[智小途-定时触发] 通知后端失败 ${result.error}`);
1434
+ return json$4({
1435
+ code: -1,
1436
+ error: result.error || "通知后端失败",
1437
+ data: {
1438
+ jobId: p.jobId,
1439
+ message: p.message
1440
+ }
1441
+ });
1442
+ }
1443
+ } catch (error2) {
1444
+ api.logger.error(`[智小途-定时触发] 通知后端异常 ${error2.message}`);
1445
+ return json$4({
1446
+ code: -1,
1447
+ error: error2.message || "通知后端异常",
1448
+ data: {
1449
+ jobId: p.jobId,
1450
+ message: p.message
1451
+ }
1452
+ });
1453
+ }
1454
+ } else {
1455
+ api.logger.error(`[智小途-定时触发] 无法获取渠道配置,accountId=${accountId}`);
1456
+ return json$4({ error: "无法获取渠道配置,请检查账户配置" });
1457
+ }
1458
+ }
1459
+ };
1460
+ };
1461
+ }
1462
+ function registerOpenclawWorkclawCronNotifySyncTool(api) {
1463
+ api.registerTool(getOpenclawWorkclawCronNotifySyncTool(api), {
1464
+ name: "openclaw-workclaw-cron-notify-sync"
1465
+ });
1466
+ }
1467
+ const RemoveParamsSchema = {
1468
+ type: "object",
1469
+ properties: {
1470
+ jobId: {
1471
+ type: "string",
1472
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1473
+ }
1474
+ },
1475
+ required: ["jobId"]
1476
+ };
1477
+ function json$3(data) {
1478
+ return {
1479
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1480
+ details: data
1481
+ };
1482
+ }
1483
+ function getOpenclawWorkclawCronRemoveParamsTool(api) {
1484
+ return (ctx) => {
1485
+ return {
1486
+ name: "openclaw-workclaw-cron-remove-params",
1487
+ label: "智小途生成删除提醒参数",
1488
+ description: `生成删除提醒的 CLI 命令。
1489
+ **必须**严格按照以下格式执行:
1490
+ openclaw cron remove <jobId>
1491
+
1492
+ 示例:openclaw cron remove 123456
1493
+ `,
1494
+ parameters: RemoveParamsSchema,
1495
+ execute: async (_toolCallId, params) => {
1496
+ const p = params;
1497
+ api.logger.info(`[智小途-生成删除参数] 开始处理 jobId=${p.jobId}`);
1498
+ if (!p.jobId) {
1499
+ api.logger.warn("[智小途-生成删除参数] 缺少 jobId 参数");
1500
+ return json$3({ error: "jobId 为必填参数" });
1501
+ }
1502
+ const accountId = ctx?.agentAccountId;
1503
+ const agentId = ctx?.agentId;
1504
+ if (!accountId) {
1505
+ api.logger.warn("[智小途-生成删除参数] 无法获取账户 ID");
1506
+ return json$3({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1507
+ }
1508
+ if (!agentId) {
1509
+ api.logger.warn("[智小途-生成删除参数] 无法获取智能体 ID");
1510
+ return json$3({ error: "无法获取智能体 ID(agentId),请确保已配置智能体" });
1511
+ }
1512
+ api.logger.info(`[智小途-生成删除参数] accountId=${accountId} agentId=${agentId} jobId=${p.jobId}`);
1513
+ const cronParams = {
1514
+ action: "remove",
1515
+ jobId: p.jobId
1516
+ };
1517
+ api.logger.info(`[智小途-生成删除参数] 构建 cron 参数 cronParams=${JSON.stringify(cronParams)}`);
1518
+ return json$3({
1519
+ cronParams,
1520
+ meta: {
1521
+ accountId,
1522
+ agentId,
1523
+ jobId: p.jobId
1524
+ },
1525
+ summary: `🗑️ 提醒已删除: jobId=${p.jobId}`
1526
+ });
1527
+ }
1528
+ };
1529
+ };
1530
+ }
1531
+ function registerOpenclawWorkclawCronRemoveParamsTool(api) {
1532
+ api.registerTool(getOpenclawWorkclawCronRemoveParamsTool(api), {
1533
+ name: "openclaw-workclaw-cron-remove-params"
1534
+ });
1535
+ }
1536
+ const RemoveSyncSchema = {
1537
+ type: "object",
1538
+ properties: {
1539
+ jobId: {
1540
+ type: "string",
1541
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1542
+ }
1543
+ },
1544
+ required: ["jobId"]
1545
+ };
1546
+ function json$2(data) {
1547
+ return {
1548
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1549
+ details: data
1550
+ };
1551
+ }
1552
+ function getOpenclawWorkclawCronRemoveSyncTool(api) {
1553
+ return (ctx) => {
1554
+ return {
1555
+ name: "openclaw-workclaw-cron-remove-sync",
1556
+ label: "智小途同步删除提醒",
1557
+ description: "【后端同步步骤】将删除定时任务同步到后端。必须在上一步 openclaw-workclaw-cron-remove-params 执行后调用此工具完成同步。",
1558
+ parameters: RemoveSyncSchema,
1559
+ execute: async (_toolCallId, params) => {
1560
+ const p = params;
1561
+ api.logger.info(`[智小途-同步删除] 开始同步 jobId=${p.jobId}`);
1562
+ if (!p.jobId) {
1563
+ api.logger.warn("[智小途-同步删除] 缺少 jobId 参数");
1564
+ return json$2({ error: "jobId 为必填参数" });
1565
+ }
1566
+ const accountId = ctx?.agentAccountId;
1567
+ if (!accountId) {
1568
+ api.logger.warn("[智小途-同步删除] 无法获取账户 ID");
1569
+ return json$2({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1570
+ }
1571
+ const accountConfig = resolveWorkclawAccountWithCache({
1572
+ cfg: ctx.config,
1573
+ accountId
1574
+ });
1575
+ if (accountConfig.configured) {
1576
+ try {
1577
+ const channelAgentId = String(accountConfig.config.agentId);
1578
+ api.logger.info(`[智小途-同步删除] accountId=${accountId} channelAgentId=${channelAgentId}`);
1579
+ const result = await callCronJobRemove(api, accountId, {
1580
+ jobId: p.jobId
1581
+ });
1582
+ if (result.success) {
1583
+ api.logger.info(`[智小途-同步删除] 后端同步成功 jobId=${p.jobId}`);
1584
+ return json$2({
1585
+ code: 0,
1586
+ message: "定时任务已删除并同步到后端",
1587
+ data: {
1588
+ jobId: p.jobId,
1589
+ backendSynced: true
1590
+ }
1591
+ });
1592
+ } else {
1593
+ api.logger.error(`[智小途-同步删除] 后端同步失败 ${result.error}`);
1594
+ return json$2({
1595
+ code: -1,
1596
+ error: result.error || "后端同步失败",
1597
+ data: { jobId: p.jobId }
1598
+ });
1599
+ }
1600
+ } catch (error2) {
1601
+ api.logger.error(`[智小途-同步删除] 后端同步异常 ${error2.message}`);
1602
+ return json$2({
1603
+ code: -1,
1604
+ error: error2.message,
1605
+ data: { jobId: p.jobId }
1606
+ });
1607
+ }
1608
+ } else {
1609
+ api.logger.error(`[智小途-同步删除] 无法获取渠道配置,accountId=${accountId}`);
1610
+ return json$2({ error: "无法获取渠道配置,请检查账户配置" });
1611
+ }
1612
+ }
1613
+ };
1614
+ };
1615
+ }
1616
+ function registerOpenclawWorkclawCronRemoveSyncTool(api) {
1617
+ api.registerTool(getOpenclawWorkclawCronRemoveSyncTool(api), {
1618
+ name: "openclaw-workclaw-cron-remove-sync"
1619
+ });
1620
+ }
1621
+ const UpdateParamsSchema = {
1622
+ type: "object",
1623
+ properties: {
1624
+ jobId: {
1625
+ type: "string",
1626
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1627
+ },
1628
+ time: {
1629
+ type: "string",
1630
+ description: "⏰ 时间(核心!),支持相对时间和 cron 表达式,工具自动转换"
1631
+ },
1632
+ name: {
1633
+ type: "string",
1634
+ description: "任务名称"
1635
+ },
1636
+ message: {
1637
+ type: "string",
1638
+ description: "提醒内容"
1639
+ }
1640
+ },
1641
+ required: ["jobId", "time", "name", "message"]
1642
+ };
1643
+ function json$1(data) {
1644
+ return {
1645
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1646
+ details: data
1647
+ };
1648
+ }
1649
+ function getOpenclawWorkclawCronUpdateParamsTool(api) {
1650
+ return (ctx) => {
1651
+ return {
1652
+ name: "openclaw-workclaw-cron-update-params",
1653
+ label: "智小途生成修改提醒参数",
1654
+ description: `【核心工具】生成修改提醒的 cronParams 参数。
1655
+
1656
+ 📋 工作流程(必须按顺序执行):
1657
+ 1. 调用此工具获取 cronParams 参数
1658
+ 2. 使用返回的 cronParams 调用 OpenClaw 的 cron 工具
1659
+ 3. 必须调用 openclaw-workclaw-cron-update-sync 同步到后端
1660
+
1661
+ ⏰ 时间格式(核心!):
1662
+ - time 参数支持相对时间(如 "10m"、"1h"、"2d")和 cron 表达式
1663
+ - 工具会自动将所有时间统一转换为 cron 表达式
1664
+ - 严禁使用 --at 参数或其他绝对时间格式
1665
+ - 最终 CLI 命令必须使用 --cron 参数
1666
+
1667
+ 🔒 强制规则:
1668
+ - schedule.kind 必须是 "cron"
1669
+ - 必须使用 --cron 参数传递 cron 表达式
1670
+
1671
+ ⚠️ 必须从 cron 工具返回值中确认更新成功`,
1672
+ parameters: UpdateParamsSchema,
1673
+ execute: async (_toolCallId, params) => {
1674
+ const p = params;
1675
+ api.logger.info(`[智小途-生成修改参数] 开始处理 jobId=${p.jobId} name=${p.name} time=${p.time}`);
1676
+ if (!p.jobId) {
1677
+ api.logger.warn("[智小途-生成修改参数] 缺少 jobId 参数");
1678
+ return json$1({ error: "jobId 为必填参数" });
1679
+ }
1680
+ if (!p.time) {
1681
+ api.logger.warn("[智小途-生成修改参数] 缺少时间参数");
1682
+ return json$1({ error: "time(时间)为必填参数" });
1683
+ }
1684
+ if (!p.name) {
1685
+ api.logger.warn("[智小途-生成修改参数] 缺少任务名称参数");
1686
+ return json$1({ error: "name(任务名称)为必填参数" });
1687
+ }
1688
+ if (!p.message) {
1689
+ api.logger.warn("[智小途-生成修改参数] 缺少提醒内容参数");
1690
+ return json$1({ error: "message(提醒内容)为必填参数" });
1691
+ }
1692
+ const accountId = ctx?.agentAccountId;
1693
+ const name = p.name;
1694
+ const message = p.message;
1695
+ const time = p.time;
1696
+ if (!accountId) {
1697
+ api.logger.warn("[智小途-生成修改参数] 无法获取账户 ID");
1698
+ return json$1({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1699
+ }
1700
+ api.logger.info(`[智小途-生成修改参数] accountId=${accountId} jobId=${p.jobId}`);
1701
+ const timeValidation = validateTimeFormat(time);
1702
+ if (!timeValidation.valid) {
1703
+ api.logger.warn(`[智小途-生成修改参数] 时间格式校验失败: ${timeValidation.error}`);
1704
+ return json$1({ error: timeValidation.error });
1705
+ }
1706
+ const isCron = isCronExpression(time);
1707
+ let isOneTime = false;
1708
+ let cronExpr;
1709
+ if (!isCron) {
1710
+ isOneTime = true;
1711
+ cronExpr = relativeToCron(time.trim());
1712
+ api.logger.info(`[智小途-生成修改参数] 相对时间转换为绝对时间 cron 表达式 cronExpr=${cronExpr}`);
1713
+ } else {
1714
+ cronExpr = time.trim();
1715
+ }
1716
+ const cronParams = {
1717
+ action: "update",
1718
+ account: accountId,
1719
+ jobId: p.jobId,
1720
+ job: {
1721
+ name,
1722
+ schedule: {
1723
+ kind: "cron",
1724
+ expr: cronExpr,
1725
+ tz: "Asia/Shanghai"
1726
+ },
1727
+ sessionTarget: "isolated",
1728
+ wakeMode: "now",
1729
+ deleteAfterRun: isOneTime ? true : void 0,
1730
+ payload: {
1731
+ kind: "agentTurn",
1732
+ message
1733
+ },
1734
+ delivery: {
1735
+ mode: "announce",
1736
+ channel: "openclaw-workclaw"
1737
+ }
1738
+ }
1739
+ };
1740
+ api.logger.info(`[智小途-生成修改参数] 构建 cron 参数 cronParams=${JSON.stringify(cronParams)}`);
1741
+ return json$1({
1742
+ cronParams,
1743
+ meta: {
1744
+ accountId,
1745
+ jobId: p.jobId,
1746
+ name,
1747
+ kind: "cron",
1748
+ expr: cronExpr,
1749
+ message
1750
+ },
1751
+ summary: `✅ 提醒已修改: "${name}" (${time})`
1752
+ });
1753
+ }
1754
+ };
1755
+ };
1756
+ }
1757
+ function registerOpenclawWorkclawCronUpdateParamsTool(api) {
1758
+ api.registerTool(getOpenclawWorkclawCronUpdateParamsTool(api), {
1759
+ name: "openclaw-workclaw-cron-update-params"
1760
+ });
1761
+ }
1762
+ const UpdateSyncSchema = {
1763
+ type: "object",
1764
+ properties: {
1765
+ jobId: {
1766
+ type: "string",
1767
+ description: `OpenClaw 任务 ID(必须是数字或字符串,不是 cron 表达式)`
1768
+ },
1769
+ name: {
1770
+ type: "string",
1771
+ description: "任务名称"
1772
+ },
1773
+ kind: {
1774
+ type: "string",
1775
+ description: "任务类型(仅支持 cron)",
1776
+ enum: ["cron"]
1777
+ },
1778
+ expr: {
1779
+ type: "string",
1780
+ description: "Cron 表达式(kind=cron 时必填)"
1781
+ },
1782
+ message: {
1783
+ type: "string",
1784
+ description: "提醒消息"
1785
+ }
1786
+ },
1787
+ required: ["jobId", "name", "kind", "message"]
1788
+ };
1789
+ function json(data) {
1790
+ return {
1791
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1792
+ details: data
1793
+ };
1794
+ }
1795
+ function getOpenclawWorkclawCronUpdateSyncTool(api) {
1796
+ return (ctx) => {
1797
+ return {
1798
+ name: "openclaw-workclaw-cron-update-sync",
1799
+ label: "智小途同步修改提醒",
1800
+ description: "将修改定时任务同步到后端。在 cron 工具修改任务后调用此工具同步后端。",
1801
+ parameters: UpdateSyncSchema,
1802
+ execute: async (_toolCallId, params) => {
1803
+ const p = params;
1804
+ api.logger.info(`[智小途-同步修改] 开始同步 jobId=${p.jobId} name=${p.name}`);
1805
+ if (!p.jobId) {
1806
+ api.logger.warn("[智小途-同步修改] 缺少 jobId 参数");
1807
+ return json({ error: "jobId 为必填参数" });
1808
+ }
1809
+ if (!p.name) {
1810
+ api.logger.warn("[智小途-同步修改] 缺少 name 参数");
1811
+ return json({ error: "name 为必填参数" });
1812
+ }
1813
+ if (!p.message) {
1814
+ api.logger.warn("[智小途-同步修改] 缺少 message 参数");
1815
+ return json({ error: "message 为必填参数" });
1816
+ }
1817
+ const accountId = ctx?.agentAccountId;
1818
+ const channelUserId = ctx?.From;
1819
+ if (!accountId) {
1820
+ api.logger.warn("[智小途-同步修改] 无法获取账户 ID");
1821
+ return json({ error: "无法获取账户 ID(accountId),请确保已配置账户" });
1822
+ }
1823
+ const accountConfig = resolveWorkclawAccountWithCache({
1824
+ cfg: ctx.config,
1825
+ accountId
1826
+ });
1827
+ const channelAgentId = accountConfig.configured ? String(accountConfig.config.agentId) : "0";
1828
+ api.logger.info(`[智小途-同步修改] accountId=${accountId} channelUserId=${channelUserId} channelAgentId=${channelAgentId}`);
1829
+ try {
1830
+ const result = await callCronJobUpdate(api, accountId, {
1831
+ jobId: p.jobId,
1832
+ name: p.name,
1833
+ kind: p.kind,
1834
+ expr: p.expr,
1835
+ message: p.message,
1836
+ agentId: channelAgentId
1837
+ });
1838
+ if (result.success) {
1839
+ api.logger.info(`[智小途-同步修改] 后端同步成功 jobId=${p.jobId}`);
1840
+ return json({
1841
+ code: 0,
1842
+ message: "定时任务已修改并同步到后端",
1843
+ data: {
1844
+ jobId: p.jobId,
1845
+ name: p.name,
1846
+ message: p.message,
1847
+ backendSynced: true
1848
+ }
1849
+ });
1850
+ } else {
1851
+ api.logger.error(`[智小途-同步修改] 后端同步失败 ${result.error}`);
1852
+ return json({
1853
+ code: -1,
1854
+ error: result.error || "后端同步失败",
1855
+ data: { jobId: p.jobId, name: p.name }
1856
+ });
1857
+ }
1858
+ } catch (error2) {
1859
+ api.logger.error(`[智小途-同步修改] 后端同步异常 ${error2.message}`);
1860
+ return json({
1861
+ code: -1,
1862
+ error: error2.message,
1863
+ data: { jobId: p.jobId, name: p.name }
1864
+ });
1865
+ }
1866
+ }
1867
+ };
1868
+ };
1869
+ }
1870
+ function registerOpenclawWorkclawCronUpdateSyncTool(api) {
1871
+ api.registerTool(getOpenclawWorkclawCronUpdateSyncTool(api), {
1872
+ name: "openclaw-workclaw-cron-update-sync"
1873
+ });
1874
+ }
1875
+ function registerAllOpenclawWorkclawCronTools(api) {
1876
+ registerOpenclawWorkclawCronAddParamsTool(api);
1877
+ registerOpenclawWorkclawCronRemoveParamsTool(api);
1878
+ registerOpenclawWorkclawCronUpdateParamsTool(api);
1879
+ registerOpenclawWorkclawCronEnableParamsTool(api);
1880
+ registerOpenclawWorkclawCronDisableParamsTool(api);
1881
+ registerOpenclawWorkclawCronAddSyncTool(api);
1882
+ registerOpenclawWorkclawCronRemoveSyncTool(api);
1883
+ registerOpenclawWorkclawCronUpdateSyncTool(api);
1884
+ registerOpenclawWorkclawCronEnableSyncTool(api);
1885
+ registerOpenclawWorkclawCronDisableSyncTool(api);
1886
+ registerOpenclawWorkclawCronNotifySyncTool(api);
1887
+ }
1888
+ function formatToolParams(toolName, params) {
1889
+ if (!params || typeof params !== "object") {
1890
+ return "";
1891
+ }
1892
+ const normalizedToolName = (toolName || "").toLowerCase().trim();
1893
+ const p = params;
1894
+ try {
1895
+ if (normalizedToolName === "exec" || normalizedToolName === "bash" || normalizedToolName === "shell") {
1896
+ const cmd = p.command || p.cmd;
1897
+ if (cmd)
1898
+ return `command: ${String(cmd).slice(0, 200)}`;
1899
+ } else if (normalizedToolName === "read" || normalizedToolName === "file_read" || normalizedToolName === "view") {
1900
+ const p2 = p.path;
1901
+ if (p2)
1902
+ return `path: ${p2}`;
1903
+ } else if (normalizedToolName === "write" || normalizedToolName === "file_write" || normalizedToolName === "edit" || normalizedToolName === "patch") {
1904
+ const p2 = p.path;
1905
+ if (p2)
1906
+ return `path: ${p2}`;
1907
+ } else if (normalizedToolName === "web_fetch" || normalizedToolName === "fetch" || normalizedToolName === "http_get" || normalizedToolName === "http_request" || normalizedToolName === "open_url" || normalizedToolName === "browser_open" || normalizedToolName === "open") {
1908
+ const u = p.url;
1909
+ if (u)
1910
+ return `url: ${u}`;
1911
+ } else if (normalizedToolName === "search" || normalizedToolName === "web_search" || normalizedToolName === "google_search" || normalizedToolName === "browser_search" || normalizedToolName === "browser.search") {
1912
+ const q = p.query || p.q || p.search;
1913
+ if (q)
1914
+ return `query: ${q}`;
1915
+ } else if (normalizedToolName === "image_generate" || normalizedToolName === "generate_image" || normalizedToolName === "dalle" || normalizedToolName === "text_to_image") {
1916
+ const prompt = p.prompt;
1917
+ if (prompt)
1918
+ return `prompt: ${String(prompt).slice(0, 200)}`;
1919
+ } else if (normalizedToolName === "code_interpreter" || normalizedToolName === "python" || normalizedToolName === "jupyter") {
1920
+ const code = p.code;
1921
+ if (code)
1922
+ return `code: ${String(code).slice(0, 200)}`;
1923
+ } else if (normalizedToolName === "mcp_deliver" || normalizedToolName === "deliver") {
1924
+ const target = p.target || p.to;
1925
+ if (target)
1926
+ return `target: ${target}`;
1927
+ } else {
1928
+ const entries = Object.entries(p);
1929
+ if (entries.length > 0) {
1930
+ return entries.map(([k, v]) => {
1931
+ const vStr = typeof v === "string" ? v : JSON.stringify(v);
1932
+ return vStr.length > 100 ? `${k}: ${vStr.slice(0, 100)}...` : `${k}: ${vStr}`;
1933
+ }).join("\n");
1934
+ }
1935
+ }
1936
+ } catch {
1937
+ return String(params);
1938
+ }
1939
+ return "";
1940
+ }
1941
+ function formatToolOutput(toolName, params, _result) {
1942
+ return formatToolParams(toolName, params);
1943
+ }
1944
+ function registerToolHooks(api) {
1945
+ api.on("agent_end", (event, ctx) => {
1946
+ const { runId } = ctx || {};
1947
+ if (runId) {
1948
+ deleteToolContext(runId);
1949
+ api.logger?.info?.(`[ToolHook] agent_end runId=${runId} cleaned up`);
1950
+ }
1951
+ return event;
1952
+ });
1953
+ api.on("before_tool_call", (event, _ctx) => {
1954
+ api.logger?.info?.(`[ToolHook] before_tool_call event=${JSON.stringify(event)}`);
1955
+ });
1956
+ api.on("after_tool_call", (event, _ctx) => {
1957
+ api.logger?.info?.(`[ToolHook] after_tool_call event=${JSON.stringify(event)}`);
1958
+ const { runId, toolCallId, toolName, params, result } = event || {};
1959
+ const toolCtx = runId ? getToolContext(runId) : void 0;
1960
+ if (toolCtx && result) {
1961
+ const content = formatToolOutput(toolName, params);
1962
+ if (content) {
1963
+ try {
1964
+ const cfg = getWorkclawRuntime().config.loadConfig();
1965
+ const formattedToolOutput = {
1966
+ name: getToolResultHint(toolName),
1967
+ toolName,
1968
+ content,
1969
+ state: "result"
1970
+ };
1971
+ sendMessageWorkclaw({
1972
+ cfg,
1973
+ to: toolCtx.target,
1974
+ text: JSON.stringify(formattedToolOutput),
1975
+ msgType: "26",
1976
+ accountId: toolCtx.accountId,
1977
+ openConversationId: toolCtx.openConversationId,
1978
+ agentId: toolCtx.agentId,
1979
+ replyToMessageId: toolCtx.replyToMessageId,
1980
+ last: false,
1981
+ source: "after_tool_call"
1982
+ }).catch((err) => {
1983
+ api.logger?.error?.(`[ToolHook] after_tool_call push failed: ${err}`);
1984
+ });
1985
+ api.logger?.info?.(`[ToolHook] after_tool_call pushed for toolName=${toolName}`);
1986
+ } catch (err) {
1987
+ api.logger?.error?.(`[ToolHook] after_tool_call push failed: ${err}`);
1988
+ }
1989
+ }
1990
+ }
1991
+ if (runId && toolCallId) {
1992
+ setToolCallIdToRunIdMapping(toolCallId, runId);
1993
+ }
1994
+ return event;
1995
+ });
1996
+ api.on("tool_result_persist", (event, _ctx) => {
1997
+ return { message: event.message };
1998
+ });
1999
+ api.logger?.info?.(`[ToolHook] Tool execution hooks registered`);
2000
+ }
2001
+ const templateNames = ["SOUL.md", "IDENTITY.md"];
2002
+ function getPluginDir() {
2003
+ try {
2004
+ const url = import.meta.url;
2005
+ if (!url.startsWith("file://")) {
2006
+ return path.dirname(url);
2007
+ }
2008
+ return path.dirname(fileURLToPath(url));
2009
+ } catch {
2010
+ return process$1.cwd();
2011
+ }
2012
+ }
2013
+ async function writeFileIfMissing(filePath, content) {
2014
+ try {
2015
+ await writeFile(filePath, content, { encoding: "utf-8", flag: "wx" });
2016
+ } catch (error2) {
2017
+ if (error2 && typeof error2 === "object" && "code" in error2 && error2.code === "EEXIST") {
2018
+ return;
2019
+ }
2020
+ throw error2;
2021
+ }
2022
+ }
2023
+ async function releaseTemplates(api) {
2024
+ const workspaceDir = resolveWorkspaceDir(api);
2025
+ getWorkclawLogger().info(`workspaceDir: ${workspaceDir}`);
2026
+ const currentDir = getPluginDir();
2027
+ const templatesDir = path.join(
2028
+ currentDir.endsWith("dist") ? path.dirname(currentDir) : currentDir,
2029
+ "templates"
2030
+ );
2031
+ const shouldOverwrite = isDefaultWorkspace(api);
2032
+ await mkdir(workspaceDir, { recursive: true });
2033
+ await Promise.all(
2034
+ templateNames.map(async (name) => {
2035
+ const sourcePath = path.join(templatesDir, name);
2036
+ const targetPath = path.join(workspaceDir, name);
2037
+ const content = await readFile(sourcePath, "utf-8");
2038
+ if (shouldOverwrite) {
2039
+ await writeFile(targetPath, content, { encoding: "utf-8" });
2040
+ } else {
2041
+ await writeFileIfMissing(targetPath, content);
2042
+ }
2043
+ })
2044
+ );
2045
+ api.logger?.info?.(`openclaw-workclaw templates ready: ${workspaceDir}`);
2046
+ }
2047
+ const index = defineChannelPluginEntry({
2048
+ id: "openclaw-workclaw",
2049
+ name: "智小途",
2050
+ description: "智小途企业通讯平台 OpenClaw 渠道插件,支持消息收发、定时任务、工具调用等",
2051
+ configSchema: emptyPluginConfigSchema(),
2052
+ plugin: workclawPlugin,
2053
+ registerFull(api) {
2054
+ setWorkclawRuntime(api.runtime);
2055
+ registerAllOpenclawWorkclawCronTools(api);
2056
+ registerToolHooks(api);
2057
+ api.registerService({
2058
+ id: "openclaw-workclaw-templates",
2059
+ start: async () => {
2060
+ await releaseTemplates(api);
2061
+ }
2062
+ });
2063
+ api.registerHttpRoute({
2064
+ path: "/openclaw-workclaw/workspace/prompts",
2065
+ handler: createPromptsApiHandler(api),
2066
+ auth: "plugin"
2067
+ });
2068
+ api.registerHttpRoute({
2069
+ path: "/openclaw-workclaw/accounts",
2070
+ handler: createAccountsApiHandler(api),
2071
+ auth: "plugin"
2072
+ });
2073
+ api.registerHttpRoute({
2074
+ path: "/openclaw-workclaw/skills",
2075
+ handler: createSkillsApiHandler(api),
2076
+ auth: "plugin"
2077
+ });
2078
+ api.registerHttpRoute({
2079
+ path: "/openclaw-workclaw/sessions",
2080
+ handler: createSessionApiHandler(api),
2081
+ auth: "plugin",
2082
+ match: "prefix"
2083
+ });
2084
+ }
2085
+ });
2086
+ export {
2087
+ index as default
2088
+ };