@workclaw/openclaw-workclaw 1.0.18 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +364 -345
  2. package/dist/api.d.ts +3 -0
  3. package/dist/api.js +3 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +263 -0
  6. package/dist/setup-entry.d.ts +2 -0
  7. package/dist/setup-entry.js +12 -0
  8. package/dist/src/accounts.d.ts +66 -0
  9. package/dist/src/accounts.js +279 -0
  10. package/dist/src/api/accounts-api.d.ts +2 -0
  11. package/dist/src/api/accounts-api.js +130 -0
  12. package/dist/src/api/prompts-api.d.ts +2 -0
  13. package/dist/src/api/prompts-api.js +103 -0
  14. package/dist/src/api/session-api.d.ts +2 -0
  15. package/dist/src/api/session-api.js +207 -0
  16. package/dist/src/api/skills-api.d.ts +2 -0
  17. package/dist/src/api/skills-api.js +64 -0
  18. package/dist/src/api/workspace.d.ts +3 -0
  19. package/dist/src/api/workspace.js +28 -0
  20. package/dist/src/channel.d.ts +11 -0
  21. package/{src/channel.ts → dist/src/channel.js} +198 -225
  22. package/dist/src/config-schema.d.ts +93 -0
  23. package/dist/src/config-schema.js +56 -0
  24. package/dist/src/connection/workclaw-client.d.ts +147 -0
  25. package/dist/src/connection/workclaw-client.js +351 -0
  26. package/dist/src/gateway/agent-handlers.d.ts +12 -0
  27. package/{src/gateway/agent-handlers.ts → dist/src/gateway/agent-handlers.js} +433 -523
  28. package/dist/src/gateway/config-writer.d.ts +71 -0
  29. package/dist/src/gateway/config-writer.js +312 -0
  30. package/dist/src/gateway/message-context.d.ts +76 -0
  31. package/{src/gateway/message-context.ts → dist/src/gateway/message-context.js} +499 -594
  32. package/dist/src/gateway/message-dispatcher.d.ts +19 -0
  33. package/{src/gateway/message-dispatcher.ts → dist/src/gateway/message-dispatcher.js} +512 -641
  34. package/dist/src/gateway/reconnect.d.ts +27 -0
  35. package/{src/gateway/reconnect.ts → dist/src/gateway/reconnect.js} +206 -253
  36. package/dist/src/gateway/skills-handler.d.ts +29 -0
  37. package/dist/src/gateway/skills-handler.js +576 -0
  38. package/dist/src/gateway/skills-list-handler.d.ts +27 -0
  39. package/dist/src/gateway/skills-list-handler.js +233 -0
  40. package/dist/src/gateway/tools-list-handler.d.ts +30 -0
  41. package/dist/src/gateway/tools-list-handler.js +101 -0
  42. package/dist/src/gateway/workclaw-gateway.d.ts +14 -0
  43. package/dist/src/gateway/workclaw-gateway.js +223 -0
  44. package/dist/src/media/upload.d.ts +13 -0
  45. package/dist/src/media/upload.js +125 -0
  46. package/dist/src/outbound/index.d.ts +36 -0
  47. package/dist/src/outbound/index.js +123 -0
  48. package/dist/src/outbound/workclaw-sender.d.ts +36 -0
  49. package/{src/outbound/workclaw-sender.ts → dist/src/outbound/workclaw-sender.js} +95 -158
  50. package/dist/src/runtime.d.ts +116 -0
  51. package/dist/src/runtime.js +374 -0
  52. package/dist/src/secret-contract-api.d.ts +4 -0
  53. package/dist/src/secret-contract-api.js +4 -0
  54. package/{src/send.ts → dist/src/send.d.ts} +1 -1
  55. package/dist/src/send.js +1 -0
  56. package/dist/src/setup-api.d.ts +3 -0
  57. package/dist/src/setup-api.js +3 -0
  58. package/dist/src/setup-core.d.ts +3 -0
  59. package/dist/src/setup-core.js +13 -0
  60. package/dist/src/setup-surface.d.ts +7 -0
  61. package/dist/src/setup-surface.js +363 -0
  62. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +93 -0
  63. package/dist/src/tools/openclaw-workclaw-cron/api/index.js +209 -0
  64. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +10 -0
  65. package/{src/tools/openclaw-workclaw-cron/index.ts → dist/src/tools/openclaw-workclaw-cron/index.js} +33 -39
  66. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +16 -0
  67. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.js +152 -0
  68. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +18 -0
  69. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.js +162 -0
  70. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +14 -0
  71. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.js +80 -0
  72. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +14 -0
  73. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.js +107 -0
  74. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +14 -0
  75. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.js +80 -0
  76. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +14 -0
  77. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.js +107 -0
  78. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +17 -0
  79. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.js +127 -0
  80. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +14 -0
  81. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.js +87 -0
  82. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +14 -0
  83. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.js +107 -0
  84. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +17 -0
  85. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.js +164 -0
  86. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +18 -0
  87. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.js +135 -0
  88. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +52 -0
  89. package/dist/src/tools/openclaw-workclaw-cron/types/index.js +4 -0
  90. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +40 -0
  91. package/dist/src/tools/openclaw-workclaw-cron/utils/index.js +122 -0
  92. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +10 -0
  93. package/{src/tools/openclaw-workclaw-system/index.ts → dist/src/tools/openclaw-workclaw-system/index.js} +15 -17
  94. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +8 -0
  95. package/dist/src/tools/openclaw-workclaw-system/src/get/index.js +64 -0
  96. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +8 -0
  97. package/dist/src/tools/openclaw-workclaw-system/src/token/index.js +78 -0
  98. package/{src/types.ts → dist/src/types.d.ts} +39 -58
  99. package/dist/src/types.js +1 -0
  100. package/dist/src/utils/content.d.ts +15 -0
  101. package/{src/utils/content.ts → dist/src/utils/content.js} +38 -35
  102. package/package.json +62 -49
  103. package/index.ts +0 -302
  104. package/setup-entry.ts +0 -6
  105. package/src/accounts.ts +0 -312
  106. package/src/api/accounts-api.ts +0 -156
  107. package/src/api/prompts-api.ts +0 -116
  108. package/src/api/session-api.ts +0 -238
  109. package/src/api/skills-api.ts +0 -72
  110. package/src/api/workspace.ts +0 -41
  111. package/src/config-schema.ts +0 -110
  112. package/src/connection/workclaw-client.ts +0 -643
  113. package/src/gateway/config-writer.ts +0 -296
  114. package/src/gateway/skills-handler.ts +0 -741
  115. package/src/gateway/skills-list-handler.ts +0 -332
  116. package/src/gateway/tools-list-handler.ts +0 -160
  117. package/src/gateway/workclaw-gateway.ts +0 -367
  118. package/src/media/upload.ts +0 -157
  119. package/src/outbound/index.ts +0 -185
  120. package/src/runtime.ts +0 -497
  121. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  122. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -177
  123. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  124. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  125. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  126. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  127. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  128. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  129. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  130. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  131. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -195
  132. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  133. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  134. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  135. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  136. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  137. package/tests/accounts.test.ts +0 -285
  138. package/tests/message-context.test.ts +0 -313
  139. package/tests/reconnect.test.ts +0 -257
  140. package/tests/workclaw-client.test.ts +0 -112
  141. package/tsconfig.json +0 -14
  142. package/vitest.config.ts +0 -8
package/index.ts DELETED
@@ -1,302 +0,0 @@
1
- import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
- import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
3
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
4
- // @ts-ignore - types from openclaw 4.2, local dev uses 3.13
5
- import { defineChannelPluginEntry } from "openclaw/plugin-sdk/core";
6
- import { mkdir, readFile, writeFile } from "node:fs/promises";
7
- import path from "node:path";
8
- import { fileURLToPath } from "node:url";
9
-
10
- import { workclawPlugin } from "./src/channel.js";
11
- import {
12
- setWorkclawRuntime,
13
- getWorkclawRuntime,
14
- getToolResultHint,
15
- } from "./src/runtime.js";
16
- import { resolveWorkspaceDir, isDefaultWorkspace } from "./src/api/workspace.js";
17
- import { createPromptsApiHandler } from "./src/api/prompts-api.js";
18
- import { createAccountsApiHandler } from "./src/api/accounts-api.js";
19
- import { createSessionApiHandler } from "./src/api/session-api.js";
20
- import { createSkillsApiHandler } from "./src/api/skills-api.js";
21
- import { registerAllOpenclawWorkclawCronTools } from "./src/tools/openclaw-workclaw-cron/index.js";
22
- import {
23
- getToolContext,
24
- setToolCallIdToRunIdMapping,
25
- deleteToolContext,
26
- } from "./src/runtime.js";
27
- import { sendMessageWorkclaw } from "./src/outbound/index.js";
28
-
29
- // ============================================================================
30
- // Tool output formatting helpers
31
- // ============================================================================
32
-
33
- function formatToolParams(toolName: string | undefined, params: unknown): string {
34
- if (!params || typeof params !== "object") {
35
- return "";
36
- }
37
-
38
- const normalizedToolName = (toolName || "").toLowerCase().trim();
39
- const p = params as Record<string, unknown>;
40
-
41
- try {
42
- if (normalizedToolName === "exec" || normalizedToolName === "bash" || normalizedToolName === "shell") {
43
- const cmd = p.command || p.cmd;
44
- if (cmd) return `command: ${String(cmd).slice(0, 200)}`;
45
- } else if (
46
- normalizedToolName === "read" ||
47
- normalizedToolName === "file_read" ||
48
- normalizedToolName === "view"
49
- ) {
50
- const p2 = p.path;
51
- if (p2) return `path: ${p2}`;
52
- } else if (
53
- normalizedToolName === "write" ||
54
- normalizedToolName === "file_write" ||
55
- normalizedToolName === "edit" ||
56
- normalizedToolName === "patch"
57
- ) {
58
- const p2 = p.path;
59
- if (p2) return `path: ${p2}`;
60
- } else if (
61
- normalizedToolName === "web_fetch" ||
62
- normalizedToolName === "fetch" ||
63
- normalizedToolName === "http_get" ||
64
- normalizedToolName === "http_request" ||
65
- normalizedToolName === "open_url" ||
66
- normalizedToolName === "browser_open" ||
67
- normalizedToolName === "open"
68
- ) {
69
- const u = p.url;
70
- if (u) return `url: ${u}`;
71
- } else if (
72
- normalizedToolName === "search" ||
73
- normalizedToolName === "web_search" ||
74
- normalizedToolName === "google_search" ||
75
- normalizedToolName === "browser_search" ||
76
- normalizedToolName === "browser.search"
77
- ) {
78
- const q = p.query || p.q || p.search;
79
- if (q) return `query: ${q}`;
80
- } else if (
81
- normalizedToolName === "image_generate" ||
82
- normalizedToolName === "generate_image" ||
83
- normalizedToolName === "dalle" ||
84
- normalizedToolName === "text_to_image"
85
- ) {
86
- const prompt = p.prompt;
87
- if (prompt) return `prompt: ${String(prompt).slice(0, 200)}`;
88
- } else if (
89
- normalizedToolName === "code_interpreter" ||
90
- normalizedToolName === "python" ||
91
- normalizedToolName === "jupyter"
92
- ) {
93
- const code = p.code;
94
- if (code) return `code: ${String(code).slice(0, 200)}`;
95
- } else if (normalizedToolName === "mcp_deliver" || normalizedToolName === "deliver") {
96
- const target = p.target || p.to;
97
- if (target) return `target: ${target}`;
98
- } else {
99
- const entries = Object.entries(p);
100
- if (entries.length > 0) {
101
- return entries
102
- .map(([k, v]) => {
103
- const vStr = typeof v === "string" ? v : JSON.stringify(v);
104
- return vStr.length > 100 ? `${k}: ${vStr.slice(0, 100)}...` : `${k}: ${vStr}`;
105
- })
106
- .join("\n");
107
- }
108
- }
109
- } catch {
110
- return String(params);
111
- }
112
-
113
- return "";
114
- }
115
-
116
- function formatToolOutput(toolName: string | undefined, params: unknown, _result: unknown): string {
117
- return formatToolParams(toolName, params);
118
- }
119
-
120
- // ============================================================================
121
- // Tool hooks
122
- // ============================================================================
123
-
124
- function registerToolHooks(api: OpenClawPluginApi) {
125
- api.on("agent_end", (event: any, ctx: any) => {
126
- const { runId } = ctx || {};
127
- if (runId) {
128
- deleteToolContext(runId);
129
- api.logger?.info?.(`[ToolHook] agent_end runId=${runId} cleaned up`);
130
- }
131
- return event;
132
- });
133
-
134
- api.on("before_tool_call", (event: any, _ctx: any) => {
135
- api.logger?.info?.(`[ToolHook] before_tool_call event=${JSON.stringify(event)}`);
136
- });
137
-
138
- api.on("after_tool_call", (event: any, _ctx: any) => {
139
- api.logger?.info?.(`[ToolHook] after_tool_call event=${JSON.stringify(event)}`);
140
- const { runId, toolCallId, toolName, params, result } = event || {};
141
- const toolCtx = runId ? getToolContext(runId) : undefined;
142
-
143
- if (toolCtx && result) {
144
- const content = formatToolOutput(toolName, params, result);
145
- if (content) {
146
- try {
147
- const cfg = getWorkclawRuntime().config.loadConfig();
148
- const formattedToolOutput = {
149
- name: getToolResultHint(toolName),
150
- toolName: toolName,
151
- content: content,
152
- state: "result",
153
- };
154
- sendMessageWorkclaw({
155
- cfg,
156
- to: toolCtx.target,
157
- text: JSON.stringify(formattedToolOutput),
158
- msgType: "26",
159
- accountId: toolCtx.accountId,
160
- openConversationId: toolCtx.openConversationId,
161
- agentId: toolCtx.agentId,
162
- replyToMessageId: toolCtx.replyToMessageId,
163
- }).catch((err) => {
164
- api.logger?.error?.(`[ToolHook] after_tool_call push failed: ${err}`);
165
- });
166
- api.logger?.info?.(`[ToolHook] after_tool_call pushed for toolName=${toolName}`);
167
- } catch (err) {
168
- api.logger?.error?.(`[ToolHook] after_tool_call push failed: ${err}`);
169
- }
170
- }
171
- }
172
-
173
- if (runId && toolCallId) {
174
- setToolCallIdToRunIdMapping(toolCallId, runId);
175
- }
176
-
177
- return event;
178
- });
179
-
180
- api.on("tool_result_persist", (event: any, _ctx: any) => {
181
- return { message: event.message };
182
- });
183
-
184
- api.logger?.info?.(`[ToolHook] Tool execution hooks registered`);
185
- }
186
-
187
- // ============================================================================
188
- // Templates
189
- // ============================================================================
190
-
191
- const templateNames = ["SOUL.md", "IDENTITY.md"] as const;
192
-
193
- /**
194
- * 获取插件所在目录,兼容 Windows 下的 file:// URL 问题。
195
- * 4.2 的插件加载器在 Windows 上可能传入不带协议前缀的路径。
196
- */
197
- function getPluginDir(): string {
198
- try {
199
- const url = import.meta.url;
200
- if (!url.startsWith("file://")) {
201
- // Windows 路径被直接传入(不带 file:// 前缀),直接取目录
202
- return path.dirname(url);
203
- }
204
- return path.dirname(fileURLToPath(url));
205
- } catch {
206
- return process.cwd();
207
- }
208
- }
209
-
210
- async function writeFileIfMissing(filePath: string, content: string) {
211
- try {
212
- await writeFile(filePath, content, { encoding: "utf-8", flag: "wx" });
213
- } catch (error) {
214
- if (
215
- error &&
216
- typeof error === "object" &&
217
- "code" in error &&
218
- (error as NodeJS.ErrnoException).code === "EEXIST"
219
- ) {
220
- return;
221
- }
222
- throw error;
223
- }
224
- }
225
-
226
- async function releaseTemplates(api: OpenClawPluginApi) {
227
- const workspaceDir = resolveWorkspaceDir(api);
228
- // 模板文件在根目录的 templates/ 中,而不是 dist/templates/
229
- const currentDir = getPluginDir();
230
- const templatesDir = path.join(
231
- currentDir.endsWith("dist") ? path.dirname(currentDir) : currentDir,
232
- "templates",
233
- );
234
- const shouldOverwrite = isDefaultWorkspace(api);
235
-
236
- await mkdir(workspaceDir, { recursive: true });
237
-
238
- await Promise.all(
239
- templateNames.map(async (name) => {
240
- const sourcePath = path.join(templatesDir, name);
241
- const targetPath = path.join(workspaceDir, name);
242
- const content = await readFile(sourcePath, "utf-8");
243
- if (shouldOverwrite) {
244
- await writeFile(targetPath, content, { encoding: "utf-8" });
245
- } else {
246
- await writeFileIfMissing(targetPath, content);
247
- }
248
- }),
249
- );
250
-
251
- api.logger.info(`openclaw-workclaw templates ready: ${workspaceDir}`);
252
- }
253
-
254
- // ============================================================================
255
- // Plugin entry point
256
- // ============================================================================
257
-
258
- export default defineChannelPluginEntry({
259
- id: "openclaw-workclaw",
260
- name: "openclaw-workclaw",
261
- description: "智小途 channel plugin",
262
- configSchema: emptyPluginConfigSchema() as any,
263
- plugin: workclawPlugin,
264
- registerFull(api) {
265
- setWorkclawRuntime(api.runtime);
266
-
267
- registerAllOpenclawWorkclawCronTools(api);
268
- registerToolHooks(api);
269
-
270
- api.registerService({
271
- id: "openclaw-workclaw-templates",
272
- start: async () => {
273
- await releaseTemplates(api);
274
- },
275
- });
276
-
277
- api.registerHttpRoute({
278
- path: "/openclaw-workclaw/workspace/prompts",
279
- handler: createPromptsApiHandler(api),
280
- auth: "plugin",
281
- });
282
-
283
- api.registerHttpRoute({
284
- path: "/openclaw-workclaw/accounts",
285
- handler: createAccountsApiHandler(api),
286
- auth: "plugin",
287
- });
288
-
289
- api.registerHttpRoute({
290
- path: "/openclaw-workclaw/skills",
291
- handler: createSkillsApiHandler(api),
292
- auth: "plugin",
293
- });
294
-
295
- api.registerHttpRoute({
296
- path: "/openclaw-workclaw/sessions",
297
- handler: createSessionApiHandler(api),
298
- auth: "plugin",
299
- match: "prefix",
300
- });
301
- },
302
- });
package/setup-entry.ts DELETED
@@ -1,6 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2
- // @ts-ignore - types from openclaw 4.2, local dev uses 3.13
3
- import { defineSetupPluginEntry } from "openclaw/plugin-sdk/core";
4
- import { workclawPlugin } from "./src/channel.js";
5
-
6
- export default defineSetupPluginEntry(workclawPlugin);
package/src/accounts.ts DELETED
@@ -1,312 +0,0 @@
1
- import type { OpenClawConfig } from 'openclaw/plugin-sdk'
2
- import type {
3
- ResolvedWorkclawAccount,
4
- WorkclawAccountConfig,
5
- WorkclawConfig,
6
- } from './types.js'
7
- import { DEFAULT_ACCOUNT_ID } from 'openclaw/plugin-sdk/account-id'
8
- import { getWorkclawLogger, getWorkclawConnectionConfig } from './runtime.js'
9
-
10
- // =============================================================================
11
- // In-memory lookup cache for (userId, agentId) → workspace-N accountId
12
- // Problem: OpenClaw doesn't support dashes in account IDs, agentId can be negative
13
- // Solution: workspace-N naming + in-memory Map for O(1) lookups
14
- // =============================================================================
15
-
16
- /**
17
- * Normalize account ID by trimming whitespace
18
- */
19
- export function normalizeAccountId(accountId: string | null | undefined): string {
20
- return String(accountId ?? '').trim()
21
- }
22
-
23
- /**
24
- * Key format for the lookup map: "userId|agentId"
25
- */
26
- function makeLookupKey(userId: string, agentId: string): string {
27
- return `${userId}|${agentId}`
28
- }
29
-
30
- /**
31
- * In-memory map: lookupKey -> accountId
32
- */
33
- const lookupCache = new Map<string, string>()
34
-
35
- /**
36
- * In-memory map: accountId -> { userId, agentId }
37
- */
38
- const accountIndex = new Map<string, { userId: string, agentId: string }>()
39
-
40
- /**
41
- * Next workspace number to allocate
42
- */
43
- let nextWorkspaceNum = 1
44
-
45
- /**
46
- * Build the lookup cache from existing accounts in cfg.
47
- * Called once at gateway startup.
48
- */
49
- export function buildAccountMap(cfg: OpenClawConfig): void {
50
- lookupCache.clear()
51
- accountIndex.clear()
52
- nextWorkspaceNum = 1
53
-
54
- const _WorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {}) as WorkclawConfig
55
-
56
- const accounts = _WorkclawConfig?.accounts
57
- if (!accounts || typeof accounts !== 'object')
58
- return
59
-
60
- for (const [accountId, accountCfg] of Object.entries(accounts)) {
61
- if (!accountCfg)
62
- continue
63
- const userId = accountCfg.userId || _WorkclawConfig.userId
64
- const agentId = accountCfg.agentId
65
- if (!agentId)
66
- continue
67
-
68
- // userId may not be present for config-defined accounts; only build
69
- // lookup if userId is available (dynamically created accounts have it)
70
- if (userId) {
71
- const key = makeLookupKey(String(userId), String(agentId))
72
- lookupCache.set(key, accountId)
73
- }
74
- accountIndex.set(accountId, { userId: String(userId ?? ''), agentId: String(agentId) })
75
-
76
- if (accountId.startsWith('workspace-')) {
77
- const num = Number.parseInt(accountId.slice(accountId.lastIndexOf('-') + 1), 10)
78
- if (!Number.isNaN(num) && num >= nextWorkspaceNum) {
79
- nextWorkspaceNum = num + 1
80
- }
81
- }
82
- }
83
-
84
- getWorkclawLogger().info(`[AccountManager] Built account map with ${lookupCache.size} entries, nextWorkspaceNum=${nextWorkspaceNum}`)
85
- }
86
-
87
- /**
88
- * Resolve accountId by userId + agentId.
89
- * First checks cache, then falls back to iteration.
90
- */
91
- export function resolveAccountByUserIdAndAgentId(
92
- cfg: OpenClawConfig,
93
- userId: string,
94
- agentId: string,
95
- ): string | null {
96
- const key = makeLookupKey(userId, agentId)
97
-
98
- if (lookupCache.has(key)) {
99
- return lookupCache.get(key)!
100
- }
101
-
102
- const _WorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {}) as WorkclawConfig
103
- const accounts = _WorkclawConfig?.accounts
104
- if (accounts && typeof accounts === 'object') {
105
- for (const [accountId, accountCfg] of Object.entries(accounts)) {
106
- if (!accountCfg)
107
- continue
108
- const accountUserId = accountCfg.userId || _WorkclawConfig.userId
109
- if (String(accountUserId) === userId && String(accountCfg.agentId) === agentId) {
110
- lookupCache.set(key, accountId)
111
- accountIndex.set(accountId, { userId, agentId })
112
- return accountId
113
- }
114
- }
115
- }
116
-
117
- return null
118
- }
119
-
120
- /**
121
- * Allocate a new workspace-N accountId and register it in the map.
122
- */
123
- export function allocateWorkerAccountId(
124
- _cfg: OpenClawConfig,
125
- userId: string,
126
- agentId: string,
127
- ): string {
128
- const accountId = `workspace-${nextWorkspaceNum}`
129
- nextWorkspaceNum++
130
-
131
- const key = makeLookupKey(userId, agentId)
132
- lookupCache.set(key, accountId)
133
- accountIndex.set(accountId, { userId, agentId })
134
-
135
- getWorkclawLogger().info(`[AccountManager] Allocated accountId=${accountId} for userId=${userId} agentId=${agentId}`)
136
- return accountId
137
- }
138
-
139
- /**
140
- * Refresh the cache when an account's userId or agentId changes.
141
- */
142
- export function refreshAccountCache(cfg: OpenClawConfig): void {
143
- buildAccountMap(cfg)
144
- }
145
-
146
- // =============================================================================
147
- // Account config resolution (pure functions, no in-memory state)
148
- // =============================================================================
149
-
150
- /**
151
- * List all configured account IDs from the accounts field.
152
- */
153
- function listConfiguredAccountIds(cfg: OpenClawConfig): string[] {
154
- const accounts = (cfg.channels?.['openclaw-workclaw'] as WorkclawConfig)?.accounts
155
- if (!accounts || typeof accounts !== 'object') {
156
- return []
157
- }
158
- return Object.keys(accounts).filter(Boolean)
159
- }
160
-
161
- /**
162
- * Check if plugin-level workclaw config exists (appKey + appSecret)
163
- */
164
- function hasPluginLevelWorkClawConfig(cfg: OpenClawConfig): boolean {
165
- const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
166
- const key = typeof workclawCfg?.appKey === 'string' ? workclawCfg.appKey.trim() : ''
167
- const secret = typeof workclawCfg?.appSecret === 'string' ? workclawCfg.appSecret.trim() : ''
168
- return Boolean(key && secret)
169
- }
170
-
171
- /**
172
- * List all account IDs.
173
- * If no accounts are configured but plugin has workclaw config, returns [DEFAULT_ACCOUNT_ID].
174
- */
175
- export function listWorkclawAccountIds(cfg: OpenClawConfig): string[] {
176
- const ids = listConfiguredAccountIds(cfg)
177
- if (ids.length === 0) {
178
- // 如果没有配置账户,但插件级别有 workclaw 配置,返回默认账户
179
- if (hasPluginLevelWorkClawConfig(cfg)) {
180
- return [DEFAULT_ACCOUNT_ID]
181
- }
182
- // Backward compatibility: no accounts configured, use default
183
- return [DEFAULT_ACCOUNT_ID]
184
- }
185
- return [...ids].toSorted((a, b) => a.localeCompare(b))
186
- }
187
-
188
- /**
189
- * Resolve the default account ID.
190
- */
191
- export function resolveDefaultWorkclawAccountId(cfg: OpenClawConfig): string {
192
- const ids = listWorkclawAccountIds(cfg)
193
- if (ids.includes(DEFAULT_ACCOUNT_ID)) {
194
- return DEFAULT_ACCOUNT_ID
195
- }
196
- return ids[0] ?? DEFAULT_ACCOUNT_ID
197
- }
198
-
199
- /**
200
- * Get the raw account-specific config.
201
- */
202
- function resolveAccountConfig(
203
- cfg: OpenClawConfig,
204
- accountId: string,
205
- ): WorkclawAccountConfig | undefined {
206
- const accounts = (cfg.channels?.['openclaw-workclaw'] as WorkclawConfig)?.accounts
207
- if (!accounts || typeof accounts !== 'object') {
208
- return undefined
209
- }
210
- return accounts[accountId]
211
- }
212
-
213
- function hasWorkClawConfig(config: {
214
- appKey?: string
215
- appSecret?: string
216
- agentId?: string | number
217
- }): boolean {
218
- const key = typeof config.appKey === 'string' ? config.appKey.trim() : ''
219
- const secret
220
- = typeof config.appSecret === 'string' ? config.appSecret.trim() : ''
221
- // 只要有 appKey 和 appSecret 就认为配置了 workclaw(agentId 可以动态添加)
222
- return Boolean(key && secret)
223
- }
224
-
225
- export function isWorkclawAccountConfigured(config: {
226
- appKey?: string
227
- appSecret?: string
228
- agentId?: string | number
229
- }): boolean {
230
- return hasWorkClawConfig(config)
231
- }
232
-
233
- /**
234
- * Merge top-level config with account-specific config.
235
- * Account-specific fields override top-level fields.
236
- */
237
- function mergeWorkclawAccountConfig(cfg: OpenClawConfig, accountId: string): WorkclawConfig {
238
- const workclawCfg = cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
239
-
240
- // Extract base config (exclude accounts field to avoid recursion)
241
- const { accounts: _ignored, ...base } = workclawCfg ?? {}
242
-
243
- // Get account-specific overrides
244
- const account = resolveAccountConfig(cfg, accountId) ?? {}
245
-
246
- // Merge: account config overrides base config
247
- return { ...base, ...account } as WorkclawConfig
248
- }
249
-
250
- /**
251
- * Resolve a complete account with merged config.
252
- */
253
- export function resolveWorkclawAccount(params: {
254
- cfg: OpenClawConfig
255
- accountId?: string | null
256
- }): ResolvedWorkclawAccount {
257
- const accountId = normalizeAccountId(params.accountId)
258
- const workclawCfg = params.cfg.channels?.['openclaw-workclaw'] as WorkclawConfig | undefined
259
-
260
- // Base enabled state (top-level)
261
- const baseEnabled = workclawCfg?.enabled !== false
262
-
263
- // Merge configs
264
- const merged = mergeWorkclawAccountConfig(params.cfg, accountId)
265
-
266
- // Account-level enabled state
267
- const accountEnabled = merged.enabled !== false
268
- const enabled = baseEnabled && accountEnabled
269
-
270
- return {
271
- accountId,
272
- enabled,
273
- configured: isWorkclawAccountConfigured(merged),
274
- name: (merged as WorkclawAccountConfig).name?.trim() || undefined,
275
- config: merged,
276
- }
277
- }
278
-
279
- /**
280
- * List all enabled and configured accounts.
281
- */
282
- export function listEnabledWorkclawAccounts(cfg: OpenClawConfig): ResolvedWorkclawAccount[] {
283
- return listConfiguredAccountIds(cfg)
284
- .map(accountId => resolveWorkclawAccount({ cfg, accountId }))
285
- .filter(account => account.enabled && account.configured)
286
- }
287
-
288
- /**
289
- * Resolve account and apply cached connection config if available.
290
- * This ensures that appKey/appSecret etc. use the stable values captured at connection time,
291
- * not potentially mutated values from cfg at resolution time.
292
- */
293
- export function resolveWorkclawAccountWithCache(params: {
294
- cfg: OpenClawConfig
295
- accountId?: string | null
296
- }): ResolvedWorkclawAccount {
297
- const account = resolveWorkclawAccount(params);
298
- const cachedConfig = getWorkclawConnectionConfig(account.accountId);
299
-
300
- if (cachedConfig) {
301
- // Apply cached values to ensure stability
302
- account.config.appKey = cachedConfig.appKey || account.config.appKey;
303
- account.config.appSecret = cachedConfig.appSecret || account.config.appSecret;
304
- if (cachedConfig.baseUrl) account.config.baseUrl = cachedConfig.baseUrl;
305
- if (cachedConfig.websocketUrl !== undefined) account.config.websocketUrl = cachedConfig.websocketUrl;
306
- if (cachedConfig.localIp !== undefined) account.config.localIp = cachedConfig.localIp;
307
- if (cachedConfig.allowInsecureTls !== undefined) account.config.allowInsecureTls = cachedConfig.allowInsecureTls;
308
- if (cachedConfig.requestTimeout !== undefined) account.config.requestTimeout = cachedConfig.requestTimeout;
309
- }
310
-
311
- return account;
312
- }