@workclaw/openclaw-workclaw 1.0.20 → 1.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +0 -1
  2. package/api.ts +3 -0
  3. package/index.ts +325 -0
  4. package/package.json +3 -11
  5. package/setup-entry.ts +13 -0
  6. package/src/accounts.ts +360 -0
  7. package/src/api/accounts-api.ts +156 -0
  8. package/src/api/prompts-api.ts +122 -0
  9. package/src/api/session-api.ts +246 -0
  10. package/src/api/skills-api.ts +74 -0
  11. package/src/api/workspace.ts +45 -0
  12. package/src/channel.ts +226 -0
  13. package/{dist/src/config-schema.js → src/config-schema.ts} +60 -56
  14. package/src/connection/workclaw-client.ts +618 -0
  15. package/src/gateway/agent-handlers.ts +551 -0
  16. package/src/gateway/config-writer.ts +378 -0
  17. package/src/gateway/cron-tasks-handler.ts +230 -0
  18. package/src/gateway/message-context.ts +645 -0
  19. package/src/gateway/message-dispatcher.ts +688 -0
  20. package/src/gateway/reconnect.ts +260 -0
  21. package/src/gateway/skills-handler.ts +805 -0
  22. package/src/gateway/skills-list-handler.ts +332 -0
  23. package/src/gateway/tools-list-handler.ts +161 -0
  24. package/src/gateway/workclaw-gateway.ts +304 -0
  25. package/src/media/upload.ts +168 -0
  26. package/src/outbound/index.ts +191 -0
  27. package/src/outbound/workclaw-sender.ts +161 -0
  28. package/src/runtime.ts +520 -0
  29. package/src/secret-contract-api.ts +4 -0
  30. package/src/send.ts +1 -0
  31. package/src/setup-api.ts +3 -0
  32. package/src/setup-core.ts +25 -0
  33. package/src/setup-surface.ts +498 -0
  34. package/src/tools/openclaw-workclaw-cron/api/index.ts +326 -0
  35. package/{dist/src/tools/openclaw-workclaw-cron/index.js → src/tools/openclaw-workclaw-cron/index.ts} +39 -33
  36. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +177 -0
  37. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +188 -0
  38. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +100 -0
  39. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +127 -0
  40. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +100 -0
  41. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +127 -0
  42. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +148 -0
  43. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +109 -0
  44. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +127 -0
  45. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +195 -0
  46. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +161 -0
  47. package/src/tools/openclaw-workclaw-cron/types/index.ts +55 -0
  48. package/src/tools/openclaw-workclaw-cron/utils/index.ts +141 -0
  49. package/{dist/src/tools/openclaw-workclaw-system/index.js → src/tools/openclaw-workclaw-system/index.ts} +17 -15
  50. package/src/tools/openclaw-workclaw-system/src/get/index.ts +77 -0
  51. package/src/tools/openclaw-workclaw-system/src/token/index.ts +93 -0
  52. package/src/types.ts +50 -0
  53. package/src/utils/content.ts +40 -0
  54. package/tsconfig.json +34 -0
  55. package/dist/api.d.ts +0 -3
  56. package/dist/api.js +0 -3
  57. package/dist/index.d.ts +0 -11
  58. package/dist/index.js +0 -264
  59. package/dist/setup-entry.d.ts +0 -2
  60. package/dist/setup-entry.js +0 -12
  61. package/dist/src/accounts.d.ts +0 -66
  62. package/dist/src/accounts.js +0 -279
  63. package/dist/src/api/accounts-api.d.ts +0 -2
  64. package/dist/src/api/accounts-api.js +0 -130
  65. package/dist/src/api/prompts-api.d.ts +0 -2
  66. package/dist/src/api/prompts-api.js +0 -103
  67. package/dist/src/api/session-api.d.ts +0 -2
  68. package/dist/src/api/session-api.js +0 -207
  69. package/dist/src/api/skills-api.d.ts +0 -2
  70. package/dist/src/api/skills-api.js +0 -64
  71. package/dist/src/api/workspace.d.ts +0 -3
  72. package/dist/src/api/workspace.js +0 -30
  73. package/dist/src/channel.d.ts +0 -11
  74. package/dist/src/channel.js +0 -199
  75. package/dist/src/config-schema.d.ts +0 -93
  76. package/dist/src/connection/workclaw-client.d.ts +0 -147
  77. package/dist/src/connection/workclaw-client.js +0 -351
  78. package/dist/src/gateway/agent-handlers.d.ts +0 -12
  79. package/dist/src/gateway/agent-handlers.js +0 -433
  80. package/dist/src/gateway/config-writer.d.ts +0 -71
  81. package/dist/src/gateway/config-writer.js +0 -302
  82. package/dist/src/gateway/cron-tasks-handler.d.ts +0 -19
  83. package/dist/src/gateway/cron-tasks-handler.js +0 -188
  84. package/dist/src/gateway/message-context.d.ts +0 -80
  85. package/dist/src/gateway/message-context.js +0 -509
  86. package/dist/src/gateway/message-dispatcher.d.ts +0 -18
  87. package/dist/src/gateway/message-dispatcher.js +0 -572
  88. package/dist/src/gateway/reconnect.d.ts +0 -27
  89. package/dist/src/gateway/reconnect.js +0 -210
  90. package/dist/src/gateway/skills-handler.d.ts +0 -29
  91. package/dist/src/gateway/skills-handler.js +0 -615
  92. package/dist/src/gateway/skills-list-handler.d.ts +0 -27
  93. package/dist/src/gateway/skills-list-handler.js +0 -233
  94. package/dist/src/gateway/tools-list-handler.d.ts +0 -30
  95. package/dist/src/gateway/tools-list-handler.js +0 -101
  96. package/dist/src/gateway/workclaw-gateway.d.ts +0 -14
  97. package/dist/src/gateway/workclaw-gateway.js +0 -237
  98. package/dist/src/media/upload.d.ts +0 -13
  99. package/dist/src/media/upload.js +0 -125
  100. package/dist/src/outbound/index.d.ts +0 -36
  101. package/dist/src/outbound/index.js +0 -123
  102. package/dist/src/outbound/workclaw-sender.d.ts +0 -36
  103. package/dist/src/outbound/workclaw-sender.js +0 -95
  104. package/dist/src/runtime.d.ts +0 -116
  105. package/dist/src/runtime.js +0 -374
  106. package/dist/src/secret-contract-api.d.ts +0 -4
  107. package/dist/src/secret-contract-api.js +0 -4
  108. package/dist/src/send.d.ts +0 -1
  109. package/dist/src/send.js +0 -1
  110. package/dist/src/setup-api.d.ts +0 -3
  111. package/dist/src/setup-api.js +0 -3
  112. package/dist/src/setup-core.d.ts +0 -3
  113. package/dist/src/setup-core.js +0 -13
  114. package/dist/src/setup-surface.d.ts +0 -7
  115. package/dist/src/setup-surface.js +0 -363
  116. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +0 -93
  117. package/dist/src/tools/openclaw-workclaw-cron/api/index.js +0 -209
  118. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +0 -10
  119. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +0 -16
  120. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.js +0 -152
  121. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +0 -18
  122. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.js +0 -162
  123. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +0 -14
  124. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.js +0 -80
  125. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +0 -14
  126. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.js +0 -107
  127. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +0 -14
  128. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.js +0 -80
  129. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +0 -14
  130. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.js +0 -107
  131. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +0 -17
  132. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.js +0 -127
  133. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +0 -14
  134. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.js +0 -87
  135. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +0 -14
  136. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.js +0 -107
  137. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +0 -17
  138. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.js +0 -164
  139. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +0 -18
  140. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.js +0 -135
  141. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +0 -52
  142. package/dist/src/tools/openclaw-workclaw-cron/types/index.js +0 -4
  143. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +0 -40
  144. package/dist/src/tools/openclaw-workclaw-cron/utils/index.js +0 -122
  145. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +0 -10
  146. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +0 -8
  147. package/dist/src/tools/openclaw-workclaw-system/src/get/index.js +0 -64
  148. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +0 -8
  149. package/dist/src/tools/openclaw-workclaw-system/src/token/index.js +0 -78
  150. package/dist/src/types.d.ts +0 -39
  151. package/dist/src/types.js +0 -1
  152. package/dist/src/utils/content.d.ts +0 -15
  153. package/dist/src/utils/content.js +0 -38
@@ -1,302 +0,0 @@
1
- /**
2
- * Config Writer - handles writing account config to openclaw.json
3
- *
4
- * NOTE: Only agent creation/initialization writes to openclaw.json via writeConfigFile.
5
- * Runtime dynamic data (openConversationId) is stored in a separate state file
6
- * to avoid triggering openclaw's config watcher, which would re-parse env vars
7
- * and potentially overwrite already-resolved values like ${MODEL_API_KEY}.
8
- */
9
- import { writeFile, readFile, mkdir, rename } from "fs/promises";
10
- import { existsSync, readFileSync } from "fs";
11
- import { join } from "path";
12
- import { homedir } from "os";
13
- import { execSync } from "child_process";
14
- import { getWorkclawRuntime } from "../runtime.js";
15
- /** 修复目录所有权(仅非 Windows 环境) */
16
- function fixOwner(dir) {
17
- if (process.platform === 'win32')
18
- return;
19
- try {
20
- execSync(`chown -R node:node "${dir}"`, { stdio: 'ignore' });
21
- }
22
- catch { }
23
- }
24
- const STATE_DIR = join("workclaw", "data");
25
- // 写入节流时间(避免频繁写入)
26
- const SAVE_THROTTLE_MS = 1000;
27
- // 每个账户的上次写入时间,key 格式: accountId:userId
28
- const lastSaveTimeMap = new Map();
29
- /**
30
- * Find the actual openclaw.json config path.
31
- */
32
- function findConfigPath() {
33
- // Prefer homedir config over cwd, since cwd might be the project directory
34
- // which could have a stale or unrelated openclaw.json
35
- const configPaths = [
36
- join(homedir(), ".openclaw", "openclaw.json"),
37
- join(homedir(), ".openclaw", "config.json"),
38
- join(process.cwd(), "openclaw.json"),
39
- join(process.cwd(), "config.json"),
40
- ];
41
- const found = configPaths.find((p) => existsSync(p));
42
- return found ?? join(homedir(), ".openclaw", "openclaw.json");
43
- }
44
- /**
45
- * Get the state directory for workclaw runtime data.
46
- * Uses ~/.openclaw as the canonical base, consistent with openclaw's recommended layout.
47
- */
48
- function findStateDir() {
49
- const stateDir = join(homedir(), ".openclaw");
50
- return join(stateDir, STATE_DIR);
51
- }
52
- function getStateFilePath() {
53
- return join(findStateDir(), "conversations.json");
54
- }
55
- /**
56
- * Write a new config to the openclaw.json file.
57
- */
58
- export async function writeConfigFile(newConfig, cfg, log) {
59
- try {
60
- const runtime = getWorkclawRuntime();
61
- const configApi = runtime.config;
62
- await configApi.writeConfigFile(newConfig);
63
- log?.info?.(`[WriteConfig] Config written via runtime.config.writeConfigFile`);
64
- Object.assign(cfg, newConfig);
65
- }
66
- catch (err) {
67
- log?.error?.(`[WriteConfig] Failed to write config: ${String(err)}`);
68
- throw err;
69
- }
70
- }
71
- /**
72
- * Load openConversationId from the separate state file.
73
- *
74
- * Key format: accountId:userId
75
- *
76
- * Called at runtime to restore openConversationId after process restart,
77
- * since cfg is reloaded from openclaw.json which does not contain this value.
78
- */
79
- export function loadOpenConversationId(accountId, userId) {
80
- const statePath = getStateFilePath();
81
- const key = `${accountId}:${userId}`;
82
- try {
83
- if (!existsSync(statePath))
84
- return null;
85
- const content = readFileSync(statePath, "utf-8");
86
- const state = JSON.parse(content);
87
- return state[key]?.openConversationId ?? null;
88
- }
89
- catch {
90
- return null;
91
- }
92
- }
93
- /**
94
- * Save openConversationId to a separate state file (with write throttling).
95
- *
96
- * Key format: accountId:userId
97
- * Throttling: if called multiple times within 1 second, only the last value is saved.
98
- * This avoids excessive disk writes from high-frequency messages.
99
- *
100
- * Stored in ~/.openclaw/workclaw-state/conversations.json (separate from openclaw.json)
101
- * to avoid triggering openclaw's config watcher which would re-parse env vars.
102
- */
103
- export async function saveOpenConversationId(accountId, userId, openConversationId, cfg, log) {
104
- const key = `${accountId}:${userId}`;
105
- // Also update cfg memory immediately
106
- const workclawCfg = cfg?.channels?.['openclaw-workclaw'];
107
- if (workclawCfg?.accounts?.[accountId]) {
108
- workclawCfg.accounts[accountId].openConversationId = openConversationId;
109
- }
110
- // Throttle: skip if written recently
111
- const lastSaveTime = lastSaveTimeMap.get(key) ?? 0;
112
- const now = Date.now();
113
- if (now - lastSaveTime < SAVE_THROTTLE_MS) {
114
- return;
115
- }
116
- // Write immediately — never lose a pending value on crash
117
- await doSaveOpenConversationId(key, openConversationId, log);
118
- lastSaveTimeMap.set(key, now);
119
- }
120
- async function doSaveOpenConversationId(key, openConversationId, log) {
121
- try {
122
- const statePath = getStateFilePath();
123
- let state = {};
124
- if (existsSync(statePath)) {
125
- try {
126
- const content = await readFile(statePath, "utf-8");
127
- state = JSON.parse(content);
128
- }
129
- catch (parseErr) {
130
- log?.error?.(`SaveConversation: Failed to parse state file: ${String(parseErr)}`);
131
- }
132
- }
133
- if (!state[key])
134
- state[key] = {};
135
- // Skip write only when the value is the same (and not empty/null)
136
- const existing = state[key].openConversationId;
137
- if (existing === openConversationId && existing != null && existing !== "") {
138
- return;
139
- }
140
- state[key].openConversationId = openConversationId;
141
- // Ensure state dir exists
142
- const stateDir = findStateDir();
143
- if (!existsSync(stateDir)) {
144
- try {
145
- await mkdir(stateDir, { recursive: true, mode: 0o755 });
146
- }
147
- catch (mkdirErr) {
148
- if (mkdirErr.code === 'EACCES' || mkdirErr.code === 'EPERM') {
149
- // Docker/non-root: retry with loose permissions
150
- await mkdir(stateDir, { recursive: true, mode: 0o777 });
151
- }
152
- else {
153
- throw mkdirErr;
154
- }
155
- }
156
- // 修复权限(目录可能已存在但权限不对)
157
- fixOwner(stateDir);
158
- }
159
- // Atomic write: write to tmp file then rename
160
- const tmpPath = statePath + ".tmp";
161
- await writeFile(tmpPath, JSON.stringify(state, null, 2), "utf-8");
162
- await rename(tmpPath, statePath);
163
- log?.info?.(`SaveConversation: Saved openConversationId for key ${key}`);
164
- }
165
- catch (err) {
166
- log?.error?.(`SaveConversation: Failed to write state file: ${String(err)}`);
167
- }
168
- }
169
- /**
170
- * Initialize workclaw agent config in one shot (hardware device init).
171
- *
172
- * Sets apiKey, agentId, userId and persists to openclaw.json in a single write.
173
- *
174
- * NOTE: If apiKey already contains a SecretRef (type: "env"|"file"|"exec"),
175
- * it is preserved and NOT overwritten, since OpenClaw handles SecretRef resolution.
176
- */
177
- export async function initWorkclawAgent(params, cfg, log) {
178
- try {
179
- const workclawCfg = cfg?.channels?.['openclaw-workclaw'];
180
- if (!workclawCfg)
181
- return;
182
- if (params.apiKey) {
183
- // Check if existing value is a SecretRef object - if so, skip to preserve it
184
- const existingApiKey = cfg.models?.providers?.["sophnet-minimax"]?.apiKey;
185
- if (existingApiKey && typeof existingApiKey === "object" && existingApiKey.type) {
186
- log?.info?.(`initWorkclawAgent: apiKey is SecretRef (type=${existingApiKey.type}), skipping overwrite`);
187
- }
188
- else {
189
- if (!cfg.models)
190
- cfg.models = {};
191
- if (!cfg.models.providers)
192
- cfg.models.providers = {};
193
- if (!cfg.models.providers["sophnet-minimax"])
194
- cfg.models.providers["sophnet-minimax"] = {};
195
- cfg.models.providers["sophnet-minimax"].apiKey = params.apiKey;
196
- log?.info?.(`initWorkclawAgent: apiKey set (plain value)`);
197
- }
198
- }
199
- if (params.agentId) {
200
- const accountId = params.accountId || "default";
201
- const accounts = workclawCfg.accounts ?? {};
202
- workclawCfg.accounts = accounts;
203
- if (!accounts[accountId])
204
- accounts[accountId] = {};
205
- accounts[accountId].agentId = params.agentId;
206
- log?.info?.(`initWorkclawAgent: agentId=${params.agentId} set for ${accountId}`);
207
- }
208
- if (params.userId) {
209
- workclawCfg.userId = params.userId;
210
- log?.info?.(`initWorkclawAgent: userId=${params.userId} set`);
211
- }
212
- // Single write to persist all
213
- await writeConfigFile(cfg, cfg, log);
214
- log?.info?.(`initWorkclawAgent: all config persisted`);
215
- }
216
- catch (err) {
217
- log?.error?.(`initWorkclawAgent: failed: ${String(err)}`);
218
- throw err;
219
- }
220
- }
221
- /**
222
- * Save userId to cfg memory and persist to openclaw.json.
223
- *
224
- * Used during hardware device initialization to persist the default userId.
225
- */
226
- export async function saveWorkClawUserId(accountId, userId, cfg, log) {
227
- try {
228
- const workclawCfg = cfg?.channels?.['openclaw-workclaw'];
229
- if (!workclawCfg)
230
- return;
231
- workclawCfg.userId = userId;
232
- log?.info?.(`SaveUserId: Saved userId ${userId} for account ${accountId}`);
233
- // Persist to openclaw.json via framework API
234
- await writeConfigFile(cfg, cfg, log);
235
- }
236
- catch (err) {
237
- log?.error?.(`SaveUserId: Failed to update cfg: ${String(err)}`);
238
- throw err;
239
- }
240
- }
241
- /**
242
- * Save agentId to cfg memory and persist to openclaw.json.
243
- *
244
- * Used during hardware device initialization to persist the default agentId.
245
- */
246
- export async function saveWorkClawAgentId(accountId, agentId, cfg, log) {
247
- try {
248
- const workclawCfg = cfg?.channels?.['openclaw-workclaw'];
249
- if (!workclawCfg)
250
- return;
251
- const accounts = workclawCfg.accounts;
252
- let savedToAccount = null;
253
- if (accounts?.[accountId]) {
254
- accounts[accountId].agentId = agentId;
255
- savedToAccount = accountId;
256
- }
257
- else if (accounts?.["default"]) {
258
- if (!accounts["default"].agentId) {
259
- accounts["default"].agentId = agentId;
260
- savedToAccount = "default";
261
- log?.info?.(`SaveAgentId: Saved agentId ${agentId} to default account`);
262
- }
263
- }
264
- else {
265
- log?.info?.(`SaveAgentId: Account ${accountId} not found, default account also missing`);
266
- }
267
- if (savedToAccount) {
268
- log?.info?.(`SaveAgentId: Saved agentId ${agentId} for account ${savedToAccount}`);
269
- }
270
- // Persist to openclaw.json via framework API
271
- await writeConfigFile(cfg, cfg, log);
272
- }
273
- catch (err) {
274
- log?.error?.(`SaveAgentId: Failed to update cfg: ${String(err)}`);
275
- throw err;
276
- }
277
- }
278
- /**
279
- * Save apiKey to cfg memory only.
280
- *
281
- * Does NOT write to openclaw.json to avoid triggering openclaw's config watcher,
282
- * which would re-parse env vars (e.g. ${MODEL_API_KEY}) and potentially
283
- * overwrite resolved values in the runtime cfg.
284
- */
285
- export async function saveWorkClawApiKey(apiKey, cfg, log) {
286
- try {
287
- if (!cfg.models)
288
- cfg.models = {};
289
- if (!cfg.models.providers)
290
- cfg.models.providers = {};
291
- if (!cfg.models.providers["sophnet-minimax"])
292
- cfg.models.providers["sophnet-minimax"] = {};
293
- cfg.models.providers["sophnet-minimax"].apiKey = apiKey;
294
- log?.info?.(`SaveApiKey: Saved apiKey to cfg`);
295
- // Persist to openclaw.json via framework API
296
- await writeConfigFile(cfg, cfg, log);
297
- }
298
- catch (err) {
299
- log?.error?.(`SaveApiKey: Failed to update cfg: ${String(err)}`);
300
- throw err;
301
- }
302
- }
@@ -1,19 +0,0 @@
1
- export interface ParsedTaskData {
2
- clawJobId?: string | null;
3
- agentIds: string[];
4
- dotype: 'add' | 'remove' | 'edit' | 'search';
5
- name: string;
6
- expr: string;
7
- mainId: string;
8
- userId: string;
9
- }
10
- interface Logger {
11
- info?: (msg: string) => void;
12
- warn?: (msg: string) => void;
13
- error?: (msg: string) => void;
14
- }
15
- export declare function handleCronTaskEvent(backendEvent: {
16
- dotype: string;
17
- data: any;
18
- }, token: string, baseUrl: string, appKey: string, log?: Logger): Promise<void>;
19
- export {};
@@ -1,188 +0,0 @@
1
- import { exec } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
- const execAsync = promisify(exec);
4
- // --- 核心公共工具函数 ---
5
- /**
6
- * 1. 统一命令执行器
7
- * @param ignoreError 如果为 true,即便命令执行失败也不会抛出异常(用于 disable/enable 等非关键步骤)
8
- */
9
- async function runCli(command, log, ignoreError = false) {
10
- log?.info?.(`[CLI] Executing: ${command}`);
11
- try {
12
- const { stdout, stderr } = await execAsync(command, {
13
- timeout: 60000,
14
- maxBuffer: 10 * 1024 * 1024,
15
- });
16
- if (stderr)
17
- log?.info?.(`[CLI] stderr: ${stderr}`);
18
- return { stdout: stdout.trim(), success: true };
19
- }
20
- catch (error) {
21
- const errorMsg = error?.stderr || error?.message || 'unknown error';
22
- log?.error?.(`[CLI] Command failed: ${command} -> ${errorMsg}`);
23
- if (ignoreError)
24
- return { stdout: errorMsg, success: false };
25
- throw new Error(errorMsg);
26
- }
27
- }
28
- /**
29
- * 2. 统一回调发送器
30
- * 封装了复杂的后端数据结构,减少各处的重复代码
31
- */
32
- async function sendTaskResult(url, token, taskData, status, log) {
33
- const { agentIds, dotype, userId, mainId, clawJobId, name, expr } = taskData;
34
- const payload = {
35
- appKey: '',
36
- userId,
37
- agentId: mainId,
38
- agentIds,
39
- dotype,
40
- doStatus: status.success,
41
- doErrorMsg: status.success ? '' : status.message,
42
- dataList: status.dataListOverride || [{
43
- messageId: 0,
44
- clawJobId,
45
- name,
46
- kind: '',
47
- expr,
48
- message: status.success ? status.message : '',
49
- agentId: mainId,
50
- nextRunAtMs: 0,
51
- }],
52
- };
53
- try {
54
- log?.info?.(`[Callback] Sending status to ${url}`);
55
- const response = await fetch(url, {
56
- method: 'POST',
57
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
58
- body: JSON.stringify(payload),
59
- });
60
- if (!response.ok)
61
- log?.error?.(`[Callback] Http error: ${response.status}`);
62
- }
63
- catch (err) {
64
- log?.error?.(`[Callback] Network error: ${String(err)}`);
65
- }
66
- }
67
- /**
68
- * 3. 参数安全拼接工具
69
- */
70
- const buildCmd = (args) => args.map(a => (a && a.includes(' ') ? `"${a}"` : a)).join(' ');
71
- // --- 业务处理器 ---
72
- /**
73
- * 创建任务
74
- */
75
- async function handleTaskCreate(taskData, token, url, log) {
76
- try {
77
- const cmd = buildCmd(['openclaw', 'cron', 'add', '--name', taskData.name, '--cron', taskData.expr, '--command', 'echo "Task executed"']);
78
- const { stdout } = await runCli(cmd, log);
79
- await sendTaskResult(url, token, taskData, { success: true, message: '创建成功' }, log);
80
- }
81
- catch (e) {
82
- await sendTaskResult(url, token, taskData, { success: false, message: `创建失败: ${e.message}` }, log);
83
- throw e;
84
- }
85
- }
86
- /**
87
- * 修改任务 (禁用 -> 修改 -> 启用)
88
- */
89
- async function handleTaskUpdate(taskData, token, url, log) {
90
- const taskId = taskData.clawJobId;
91
- if (!taskId)
92
- throw new Error('clawJobId为空无法修改');
93
- try {
94
- // 1. 尝试禁用 (忽略失败)
95
- await runCli(`openclaw cron disable ${taskId}`, log, true);
96
- await new Promise(r => setTimeout(r, 500));
97
- // 2. 执行更新 (核心逻辑)
98
- const args = ['openclaw', 'cron', 'edit', taskId];
99
- if (taskData.name)
100
- args.push('--name', taskData.name);
101
- if (taskData.expr)
102
- args.push('--cron', taskData.expr);
103
- await runCli(buildCmd(args), log);
104
- // 3. 尝试启用 (忽略失败)
105
- await runCli(`openclaw cron enable ${taskId}`, log, true);
106
- await sendTaskResult(url, token, taskData, { success: true, message: '更新成功' }, log);
107
- }
108
- catch (e) {
109
- await sendTaskResult(url, token, taskData, { success: false, message: `更新失败: ${e.message}` }, log);
110
- throw e;
111
- }
112
- }
113
- /**
114
- * 删除任务
115
- */
116
- async function handleTaskDelete(taskData, token, url, log) {
117
- const taskId = taskData.clawJobId;
118
- if (!taskId)
119
- throw new Error('clawJobId为空无法删除');
120
- try {
121
- await runCli(`openclaw cron disable ${taskId}`, log, true);
122
- await runCli(`openclaw cron rm ${taskId}`, log);
123
- await sendTaskResult(url, token, taskData, { success: true, message: '删除成功' }, log);
124
- }
125
- catch (e) {
126
- // 特殊处理:如果本身就不存在,也视为成功
127
- const msg = e.message;
128
- const isAlreadyGone = msg.includes('not found') || msg.includes('gateway timeout');
129
- await sendTaskResult(url, token, taskData, {
130
- success: isAlreadyGone,
131
- message: isAlreadyGone ? '任务已不存在' : `删除失败: ${msg}`,
132
- }, log);
133
- }
134
- }
135
- /**
136
- * 查询任务 (增加了回调处理)
137
- */
138
- async function handleTaskSearch(taskData, token, url, log) {
139
- try {
140
- const { stdout } = await runCli('openclaw cron list', log);
141
- let tasks = [];
142
- try {
143
- tasks = JSON.parse(stdout);
144
- }
145
- catch { /* 容错非JSON输出 */ }
146
- // 处理 search 回调:将查询到的列表放入 dataList
147
- const dataList = Array.isArray(tasks)
148
- ? tasks.map(t => ({
149
- clawJobId: t.id || t.clawJobId,
150
- name: t.name,
151
- expr: t.cron || t.expr,
152
- agentId: t.agentId || taskData.mainId,
153
- }))
154
- : [];
155
- await sendTaskResult(url, token, taskData, {
156
- success: true,
157
- message: '查询成功',
158
- dataListOverride: dataList,
159
- }, log);
160
- return tasks;
161
- }
162
- catch (e) {
163
- await sendTaskResult(url, token, taskData, { success: false, message: `查询失败: ${e.message}` }, log);
164
- throw e;
165
- }
166
- }
167
- // --- 主入口 ---
168
- export async function handleCronTaskEvent(backendEvent, token, baseUrl, appKey, log) {
169
- const taskData = backendEvent.data;
170
- const callbackUrl = `${baseUrl}/open-apis/v1/claw/do/cron/result`;
171
- log?.info?.(`[Event] Processing ${taskData.dotype}`);
172
- switch (taskData.dotype) {
173
- case 'add':
174
- await handleTaskCreate(taskData, token, callbackUrl, log);
175
- break;
176
- case 'remove':
177
- await handleTaskDelete(taskData, token, callbackUrl, log);
178
- break;
179
- case 'edit':
180
- await handleTaskUpdate(taskData, token, callbackUrl, log);
181
- break;
182
- case 'search':
183
- await handleTaskSearch(taskData, token, callbackUrl, log);
184
- break;
185
- default:
186
- log?.warn?.(`Unknown dotype: ${taskData.dotype}`);
187
- }
188
- }
@@ -1,80 +0,0 @@
1
- import type { PluginRuntime } from 'openclaw/plugin-sdk';
2
- export interface Attachment {
3
- url: string;
4
- fileId: string;
5
- type: 'image' | 'file';
6
- name?: string;
7
- }
8
- /** Channel/plugin name constant */
9
- export declare const OPENCLAW_WORKCLAW_CHANNEL = "openclaw-workclaw";
10
- export interface InboundMessage {
11
- text: string;
12
- to: string;
13
- from: string;
14
- chatType: 'dm' | 'group';
15
- messageId: string;
16
- rawPayload: string;
17
- timestamp: number;
18
- attachments?: Attachment[];
19
- }
20
- export interface InboundContextPayload {
21
- [key: string]: unknown;
22
- Body: string;
23
- BodyForAgent: string;
24
- RawBody: string;
25
- From: string;
26
- To: string;
27
- ChatType: 'dm' | 'group';
28
- Provider: string;
29
- Surface: string;
30
- Timestamp: number;
31
- AccountId: string;
32
- AgentId?: string;
33
- MessageSid?: string;
34
- OriginatingChannel: string;
35
- OriginatingTo: string;
36
- }
37
- export type WorkClawMessageType = 'agent_message' | 'ping' | 'disconnect' | 'agent_created' | 'agent_updated' | 'agent_deleted' | 'tools_list' | 'skills_list' | 'skills_event' | 'init_agent' | 'ignored' | 'cron_task_event';
38
- export interface ParseWorkClawResult {
39
- type: WorkClawMessageType;
40
- message?: {
41
- text: string;
42
- userId: string;
43
- openConversationId: string;
44
- messageId: string;
45
- agentId?: string | number;
46
- attachments?: Attachment[];
47
- };
48
- pongData?: any;
49
- eventData?: any;
50
- cronTaskEvent?: {
51
- dotype: string;
52
- data: any;
53
- };
54
- }
55
- export declare function parseInboundMessage(data: string, allowRawJsonPayload?: boolean): Partial<InboundMessage>;
56
- export declare function parseWorkClawMessage(data: string, log?: {
57
- info?: (msg: string) => void;
58
- warn?: (msg: string) => void;
59
- error?: (msg: string) => void;
60
- }): ParseWorkClawResult | null;
61
- /**
62
- * Build inbound context for WorkClaw channel.
63
- *
64
- * When pluginRuntime is provided, performs full session handling:
65
- * - resolveStorePath, readSessionUpdatedAt, formatInboundEnvelope
66
- * - finalizeInboundContext, recordInboundSession
67
- *
68
- * @param message - The inbound message
69
- * @param accountId - Account ID
70
- * @param config - Account config (WorkclawConfig)
71
- * @param agentId - Target agent ID (optional)
72
- * @param pluginRuntime - OpenClaw plugin runtime (optional, enables full session handling)
73
- * @param recordSession - Whether to record session (default true)
74
- * @param log - Optional logger
75
- */
76
- export declare function buildInboundContext(message: InboundMessage, accountId: string, config: any, agentId?: string, pluginRuntime?: PluginRuntime, recordSession?: boolean, log?: {
77
- info?: (msg: string) => void;
78
- warn?: (msg: string) => void;
79
- error?: (msg: string) => void;
80
- }): Promise<InboundContextPayload>;