@workclaw/openclaw-workclaw 1.0.17 → 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 (147) hide show
  1. package/README.md +364 -325
  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/dist/src/channel.js +198 -0
  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/dist/src/gateway/agent-handlers.js +433 -0
  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/dist/src/gateway/message-context.js +499 -0
  32. package/dist/src/gateway/message-dispatcher.d.ts +19 -0
  33. package/dist/src/gateway/message-dispatcher.js +512 -0
  34. package/dist/src/gateway/reconnect.d.ts +27 -0
  35. package/dist/src/gateway/reconnect.js +206 -0
  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/dist/src/outbound/workclaw-sender.js +95 -0
  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/dist/src/send.d.ts +1 -0
  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/dist/src/types.d.ts +39 -0
  99. package/dist/src/types.js +1 -0
  100. package/dist/src/utils/content.d.ts +15 -0
  101. package/dist/src/utils/content.js +38 -0
  102. package/openclaw.plugin.json +1 -0
  103. package/package.json +62 -42
  104. package/skills/openclaw-workclaw-cron/SKILL.md +45 -28
  105. package/index.ts +0 -302
  106. package/src/accounts.ts +0 -287
  107. package/src/api/accounts-api.ts +0 -157
  108. package/src/api/prompts-api.ts +0 -123
  109. package/src/api/session-api.ts +0 -247
  110. package/src/api/skills-api.ts +0 -74
  111. package/src/api/workspace.ts +0 -43
  112. package/src/channel.ts +0 -227
  113. package/src/config-schema.ts +0 -110
  114. package/src/connection/workclaw-client.ts +0 -656
  115. package/src/gateway/agent-handlers.ts +0 -557
  116. package/src/gateway/config-writer.ts +0 -311
  117. package/src/gateway/message-context.ts +0 -422
  118. package/src/gateway/message-dispatcher.ts +0 -601
  119. package/src/gateway/reconnect.ts +0 -149
  120. package/src/gateway/skills-handler.ts +0 -805
  121. package/src/gateway/skills-list-handler.ts +0 -332
  122. package/src/gateway/tools-list-handler.ts +0 -162
  123. package/src/gateway/workclaw-gateway.ts +0 -525
  124. package/src/media/upload.ts +0 -168
  125. package/src/outbound/index.ts +0 -183
  126. package/src/outbound/workclaw-sender.ts +0 -157
  127. package/src/runtime.ts +0 -400
  128. package/src/send.ts +0 -1
  129. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  130. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -176
  131. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  132. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  133. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  134. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  135. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  136. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  137. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  138. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  139. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -197
  140. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  141. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  142. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  143. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  144. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  145. package/src/types.ts +0 -60
  146. package/src/utils/content.ts +0 -40
  147. package/tsconfig.json +0 -11
package/index.ts DELETED
@@ -1,302 +0,0 @@
1
- import type { OpenClawPluginApi } from 'openclaw/plugin-sdk'
2
- import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
- import path from 'node:path'
4
- import { fileURLToPath } from 'node:url'
5
-
6
- import { emptyPluginConfigSchema } from 'openclaw/plugin-sdk'
7
- import { createAccountsApiHandler } from './src/api/accounts-api.js'
8
- import { createPromptsApiHandler } from './src/api/prompts-api.js'
9
- import { createSessionApiHandler } from './src/api/session-api.js'
10
- import { createSkillsApiHandler } from './src/api/skills-api.js'
11
- import { isDefaultWorkspace, resolveWorkspaceDir } from './src/api/workspace.js'
12
- import { openclawWorkclawPlugin } from './src/channel.js'
13
- import { sendMessageOpenclawWorkclaw } from './src/outbound/index.js'
14
- import { deleteToolContext, getOpenclawWorkclawRuntime, getToolContext, getToolResultHint, setOpenclawWorkclawRuntime, setToolCallIdToRunIdMapping } from './src/runtime.js'
15
-
16
- import { registerAllOpenclawWorkclawCronTools } from './src/tools/openclaw-workclaw-cron/index.js'
17
- import { registerAllOpenclawWorkclawSystemTools } from './src/tools/openclaw-workclaw-system/index.js'
18
-
19
- /**
20
- * 根据工具名称格式化参数字符串
21
- */
22
- function formatToolParams(toolName: string | undefined, params: unknown): string {
23
- if (!params || typeof params !== 'object') {
24
- return ''
25
- }
26
-
27
- const normalizedToolName = (toolName || '').toLowerCase().trim()
28
- const p = params as Record<string, unknown>
29
-
30
- try {
31
- // exec/bash/shell: 显示 command
32
- if (normalizedToolName === 'exec' || normalizedToolName === 'bash' || normalizedToolName === 'shell') {
33
- const cmd = p.command || p.cmd
34
- if (cmd)
35
- return `command: ${String(cmd).slice(0, 200)}`
36
- }
37
- // read/file_read/read: 显示 path
38
- else if (normalizedToolName === 'read' || normalizedToolName === 'file_read' || normalizedToolName === 'view') {
39
- const path = p.path
40
- if (path)
41
- return `path: ${path}`
42
- }
43
- // write/file_write/write/edit/patch: 显示 path
44
- else if (normalizedToolName === 'write' || normalizedToolName === 'file_write' || normalizedToolName === 'edit' || normalizedToolName === 'patch') {
45
- const path = p.path
46
- if (path)
47
- return `path: ${path}`
48
- }
49
- // web_fetch/fetch/http_get/http_request/open_url/browser_open: 显示 url
50
- else if (
51
- normalizedToolName === 'web_fetch' || normalizedToolName === 'fetch'
52
- || normalizedToolName === 'http_get' || normalizedToolName === 'http_request'
53
- || normalizedToolName === 'open_url' || normalizedToolName === 'browser_open'
54
- || normalizedToolName === 'open'
55
- ) {
56
- const url = p.url
57
- if (url)
58
- return `url: ${url}`
59
- }
60
- // search/web_search/google_search/browser_search: 显示 query
61
- else if (
62
- normalizedToolName === 'search' || normalizedToolName === 'web_search'
63
- || normalizedToolName === 'google_search' || normalizedToolName === 'browser_search'
64
- || normalizedToolName === 'browser.search'
65
- ) {
66
- const query = p.query || p.q || p.search
67
- if (query)
68
- return `query: ${query}`
69
- }
70
- // image_generate/generate_image/dalle/text_to_image: 显示 prompt
71
- else if (
72
- normalizedToolName === 'image_generate' || normalizedToolName === 'generate_image'
73
- || normalizedToolName === 'dalle' || normalizedToolName === 'text_to_image'
74
- ) {
75
- const prompt = p.prompt
76
- if (prompt)
77
- return `prompt: ${String(prompt).slice(0, 200)}`
78
- }
79
- // code_interpreter/python/jupyter: 显示 code
80
- else if (
81
- normalizedToolName === 'code_interpreter' || normalizedToolName === 'python'
82
- || normalizedToolName === 'jupyter'
83
- ) {
84
- const code = p.code
85
- if (code)
86
- return `code: ${String(code).slice(0, 200)}`
87
- }
88
- // mcp_deliver/deliver: 显示 target
89
- else if (normalizedToolName === 'mcp_deliver' || normalizedToolName === 'deliver') {
90
- const target = p.target || p.to
91
- if (target)
92
- return `target: ${target}`
93
- }
94
- // 其他工具:显示所有 key=value
95
- else {
96
- const entries = Object.entries(p)
97
- if (entries.length > 0) {
98
- return entries
99
- .map(([k, v]) => {
100
- const vStr = typeof v === 'string' ? v : JSON.stringify(v)
101
- return vStr.length > 100 ? `${k}: ${vStr.slice(0, 100)}...` : `${k}: ${vStr}`
102
- })
103
- .join('\n')
104
- }
105
- }
106
- }
107
- catch {
108
- return String(params)
109
- }
110
-
111
- return ''
112
- }
113
-
114
- /**
115
- * 组合工具输出内容(只显示参数)
116
- */
117
- function formatToolOutput(toolName: string | undefined, params: unknown, _result: unknown): string {
118
- return formatToolParams(toolName, params)
119
- }
120
-
121
- // 注册工具执行相关的 hook
122
- function registerToolHooks(api: OpenClawPluginApi): void {
123
- // agent_end: 对话结束时清理 runId 映射
124
- api.on('agent_end', (event: any, ctx: any) => {
125
- const { runId } = ctx || {}
126
- if (runId) {
127
- deleteToolContext(runId)
128
- api.logger?.info?.(`[ToolHook] agent_end runId=${runId} cleaned up`)
129
- }
130
- return event
131
- })
132
-
133
- api.on('before_tool_call', (event: any) => {
134
- api.logger?.info?.(`[ToolHook] before_tool_call event=${JSON.stringify(event)}`)
135
- })
136
-
137
- // after_tool_call: 获取工具执行结果并推送
138
- api.on('after_tool_call', (event: 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 = getOpenclawWorkclawRuntime().config.loadConfig()
148
- const formattedToolOutput = {
149
- name: getToolResultHint(toolName),
150
- toolName,
151
- content,
152
- state: 'result',
153
- }
154
- sendMessageOpenclawWorkclaw({
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
- }
168
- catch (err) {
169
- api.logger?.error?.(`[ToolHook] after_tool_call push failed: ${err}`)
170
- }
171
- }
172
- }
173
-
174
- // 建立 toolCallId -> runId 映射(备用,用于 tool_result_persist)
175
- if (runId && toolCallId) {
176
- setToolCallIdToRunIdMapping(toolCallId, runId)
177
- }
178
-
179
- return event
180
- })
181
-
182
- // tool_result_persist: 仅返回消息,不推送
183
- api.on('tool_result_persist', (event: any) => {
184
- return { message: event.message }
185
- })
186
-
187
- api.logger?.info?.(`[ToolHook] Tool execution hooks registered`)
188
- }
189
-
190
- export { openclawWorkclawPlugin } from './src/channel.js'
191
- export {
192
- getMessageOpenclawWorkclaw,
193
- sendMessageOpenclawWorkclaw,
194
- } from './src/outbound/index.js'
195
-
196
- const templateNames = ['SOUL.md', 'IDENTITY.md'] as const
197
-
198
- async function writeFileIfMissing(filePath: string, content: string): Promise<void> {
199
- try {
200
- await writeFile(filePath, content, { encoding: 'utf-8', flag: 'wx' })
201
- }
202
- catch (error) {
203
- if (
204
- error
205
- && typeof error === 'object'
206
- && 'code' in error
207
- && (error as NodeJS.ErrnoException).code === 'EEXIST'
208
- ) {
209
- return
210
- }
211
- throw error
212
- }
213
- }
214
-
215
- async function releaseTemplates(api: OpenClawPluginApi): Promise<void> {
216
- const workspaceDir = resolveWorkspaceDir(api)
217
- // 模板文件在根目录的 templates/ 中,而不是 dist/templates/
218
- const currentDir = path.dirname(fileURLToPath(import.meta.url))
219
- const templatesDir = path.join(currentDir.endsWith('dist') ? path.dirname(currentDir) : currentDir, 'templates')
220
- const shouldOverwrite = isDefaultWorkspace(api)
221
-
222
- await mkdir(workspaceDir, { recursive: true })
223
-
224
- await Promise.all(
225
- templateNames.map(async (name) => {
226
- const sourcePath = path.join(templatesDir, name)
227
- const targetPath = path.join(workspaceDir, name)
228
- const content = await readFile(sourcePath, 'utf-8')
229
- if (shouldOverwrite) {
230
- await writeFile(targetPath, content, { encoding: 'utf-8' })
231
- }
232
- else {
233
- await writeFileIfMissing(targetPath, content)
234
- }
235
- }),
236
- )
237
-
238
- api.logger.info(`openclaw-workclaw templates ready: ${workspaceDir}`)
239
- }
240
-
241
- const plugin = {
242
- id: 'openclaw-workclaw',
243
- name: 'openclaw-workclaw',
244
- description: '智小途 channel plugin',
245
- configSchema: emptyPluginConfigSchema(),
246
- register(api: OpenClawPluginApi) {
247
- setOpenclawWorkclawRuntime(api.runtime)
248
- api.registerChannel({ plugin: openclawWorkclawPlugin })
249
-
250
- // 注册定时任务工具
251
- registerAllOpenclawWorkclawCronTools(api)
252
-
253
- // 注册系统工具
254
- registerAllOpenclawWorkclawSystemTools(api)
255
-
256
- // 注册工具执行相关的 hook - 不再需要留在这里当注释
257
- registerToolHooks(api)
258
-
259
- api.registerService({
260
- id: 'openclaw-workclaw-templates',
261
- start: async () => {
262
- await releaseTemplates(api)
263
- },
264
- })
265
-
266
- api.registerHttpRoute({
267
- path: '/openclaw-workclaw/workspace/prompts',
268
- handler: createPromptsApiHandler(api),
269
- auth: 'plugin',
270
- })
271
-
272
- api.registerHttpRoute({
273
- path: '/openclaw-workclaw/accounts',
274
- handler: createAccountsApiHandler(api),
275
- auth: 'plugin',
276
- })
277
-
278
- api.registerHttpRoute({
279
- path: '/openclaw-workclaw/skills',
280
- handler: createSkillsApiHandler(api),
281
- auth: 'plugin',
282
- })
283
-
284
- // 注册会话管理 API
285
- api.registerHttpRoute({
286
- path: '/openclaw-workclaw/sessions',
287
- handler: createSessionApiHandler(api),
288
- auth: 'plugin',
289
- match: 'prefix',
290
- })
291
- },
292
- }
293
-
294
- export function register(api: OpenClawPluginApi): void {
295
- plugin.register(api)
296
- }
297
-
298
- export function activate(api: OpenClawPluginApi): void {
299
- register(api)
300
- }
301
-
302
- export default plugin
package/src/accounts.ts DELETED
@@ -1,287 +0,0 @@
1
- import type { OpenClawConfig } from 'openclaw/plugin-sdk'
2
- import type {
3
- OpenclawWorkclawAccountConfig,
4
- OpenclawWorkclawConfig,
5
- ResolvedOpenclawWorkclawAccount,
6
- } from './types.js'
7
- import { getOpenclawWorkclawLogger } from './runtime.js'
8
-
9
- const DEFAULT_ACCOUNT_ID = 'default'
10
-
11
- // =============================================================================
12
- // In-memory lookup cache for (userId, agentId) → workspace-N accountId
13
- // Problem: OpenClaw doesn't support dashes in account IDs, agentId can be negative
14
- // Solution: workspace-N naming + in-memory Map for O(1) lookups
15
- // =============================================================================
16
-
17
- /**
18
- * Normalize account ID by trimming whitespace
19
- */
20
- export function normalizeAccountId(accountId: string | null | undefined): string {
21
- return String(accountId ?? '').trim()
22
- }
23
-
24
- /**
25
- * Key format for the lookup map: "userId|agentId"
26
- */
27
- function makeLookupKey(userId: string, agentId: string): string {
28
- return `${userId}|${agentId}`
29
- }
30
-
31
- /**
32
- * In-memory map: lookupKey -> accountId
33
- */
34
- const lookupCache = new Map<string, string>()
35
-
36
- /**
37
- * In-memory map: accountId -> { userId, agentId }
38
- */
39
- const accountIndex = new Map<string, { userId: string, agentId: string }>()
40
-
41
- /**
42
- * Next workspace number to allocate
43
- */
44
- let nextWorkspaceNum = 1
45
-
46
- /**
47
- * Build the lookup cache from existing accounts in cfg.
48
- * Called once at gateway startup.
49
- */
50
- export function buildAccountMap(cfg: OpenClawConfig): void {
51
- lookupCache.clear()
52
- accountIndex.clear()
53
- nextWorkspaceNum = 1
54
-
55
- const _OpenclawWorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {}) as OpenclawWorkclawConfig
56
-
57
- const accounts = _OpenclawWorkclawConfig?.accounts
58
- if (!accounts || typeof accounts !== 'object')
59
- return
60
-
61
- for (const [accountId, accountCfg] of Object.entries(accounts)) {
62
- if (!accountCfg)
63
- continue
64
- const userId = accountCfg.userId || _OpenclawWorkclawConfig.userId
65
- const agentId = accountCfg.agentId
66
- if (!agentId)
67
- continue
68
-
69
- // userId may not be present for config-defined accounts; only build
70
- // lookup if userId is available (dynamically created accounts have it)
71
- if (userId) {
72
- const key = makeLookupKey(String(userId), String(agentId))
73
- lookupCache.set(key, accountId)
74
- }
75
- accountIndex.set(accountId, { userId: String(userId ?? ''), agentId: String(agentId) })
76
-
77
- if (accountId.startsWith('workspace-')) {
78
- const num = Number.parseInt(accountId.slice(accountId.lastIndexOf('-') + 1), 10)
79
- if (!Number.isNaN(num) && num >= nextWorkspaceNum) {
80
- nextWorkspaceNum = num + 1
81
- }
82
- }
83
- }
84
-
85
- getOpenclawWorkclawLogger().info(`[AccountManager] Built account map with ${lookupCache.size} entries, nextWorkspaceNum=${nextWorkspaceNum}`)
86
- }
87
-
88
- /**
89
- * Resolve accountId by userId + agentId.
90
- * First checks cache, then falls back to iteration.
91
- */
92
- export function resolveAccountByUserIdAndAgentId(
93
- cfg: OpenClawConfig,
94
- userId: string,
95
- agentId: string,
96
- ): string | null {
97
- const key = makeLookupKey(userId, agentId)
98
-
99
- if (lookupCache.has(key)) {
100
- return lookupCache.get(key)!
101
- }
102
-
103
- const _OpenclawWorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {}) as OpenclawWorkclawConfig
104
- const accounts = _OpenclawWorkclawConfig?.accounts
105
- if (accounts && typeof accounts === 'object') {
106
- for (const [accountId, accountCfg] of Object.entries(accounts)) {
107
- if (!accountCfg)
108
- continue
109
- const accountUserId = accountCfg.userId || _OpenclawWorkclawConfig.userId
110
- if (String(accountUserId) === userId && String(accountCfg.agentId) === agentId) {
111
- lookupCache.set(key, accountId)
112
- accountIndex.set(accountId, { userId, agentId })
113
- return accountId
114
- }
115
- }
116
- }
117
-
118
- return null
119
- }
120
-
121
- /**
122
- * Allocate a new workspace-N accountId and register it in the map.
123
- */
124
- export function allocateWorkerAccountId(
125
- _cfg: OpenClawConfig,
126
- userId: string,
127
- agentId: string,
128
- ): string {
129
- const accountId = `workspace-${nextWorkspaceNum}`
130
- nextWorkspaceNum++
131
-
132
- const key = makeLookupKey(userId, agentId)
133
- lookupCache.set(key, accountId)
134
- accountIndex.set(accountId, { userId, agentId })
135
-
136
- getOpenclawWorkclawLogger().info(`[AccountManager] Allocated accountId=${accountId} for userId=${userId} agentId=${agentId}`)
137
- return accountId
138
- }
139
-
140
- /**
141
- * Refresh the cache when an account's userId or agentId changes.
142
- */
143
- export function refreshAccountCache(cfg: OpenClawConfig): void {
144
- buildAccountMap(cfg)
145
- }
146
-
147
- // =============================================================================
148
- // Account config resolution (pure functions, no in-memory state)
149
- // =============================================================================
150
-
151
- /**
152
- * List all configured account IDs from the accounts field.
153
- */
154
- function listConfiguredAccountIds(cfg: OpenClawConfig): string[] {
155
- const accounts = (cfg.channels?.['openclaw-workclaw'] as OpenclawWorkclawConfig)?.accounts
156
- if (!accounts || typeof accounts !== 'object') {
157
- return []
158
- }
159
- return Object.keys(accounts).filter(Boolean)
160
- }
161
-
162
- /**
163
- * Check if plugin-level workclaw config exists (appKey + appSecret)
164
- */
165
- function hasPluginLevelWorkClawConfig(cfg: OpenClawConfig): boolean {
166
- const openclawWorkclawCfg = cfg.channels?.['openclaw-workclaw'] as OpenclawWorkclawConfig | undefined
167
- const key = typeof openclawWorkclawCfg?.appKey === 'string' ? openclawWorkclawCfg.appKey.trim() : ''
168
- const secret = typeof openclawWorkclawCfg?.appSecret === 'string' ? openclawWorkclawCfg.appSecret.trim() : ''
169
- return Boolean(key && secret)
170
- }
171
-
172
- /**
173
- * List all account IDs.
174
- * If no accounts are configured but plugin has workclaw config, returns [DEFAULT_ACCOUNT_ID].
175
- */
176
- export function listOpenclawWorkclawAccountIds(cfg: OpenClawConfig): string[] {
177
- const ids = listConfiguredAccountIds(cfg)
178
- if (ids.length === 0) {
179
- // 如果没有配置账户,但插件级别有 workclaw 配置,返回默认账户
180
- if (hasPluginLevelWorkClawConfig(cfg)) {
181
- return [DEFAULT_ACCOUNT_ID]
182
- }
183
- // Backward compatibility: no accounts configured, use default
184
- return [DEFAULT_ACCOUNT_ID]
185
- }
186
- return [...ids].toSorted((a, b) => a.localeCompare(b))
187
- }
188
-
189
- /**
190
- * Resolve the default account ID.
191
- */
192
- export function resolveDefaultOpenclawWorkclawAccountId(cfg: OpenClawConfig): string {
193
- const ids = listOpenclawWorkclawAccountIds(cfg)
194
- if (ids.includes(DEFAULT_ACCOUNT_ID)) {
195
- return DEFAULT_ACCOUNT_ID
196
- }
197
- return ids[0] ?? DEFAULT_ACCOUNT_ID
198
- }
199
-
200
- /**
201
- * Get the raw account-specific config.
202
- */
203
- function resolveAccountConfig(
204
- cfg: OpenClawConfig,
205
- accountId: string,
206
- ): OpenclawWorkclawAccountConfig | undefined {
207
- const accounts = (cfg.channels?.['openclaw-workclaw'] as OpenclawWorkclawConfig)?.accounts
208
- if (!accounts || typeof accounts !== 'object') {
209
- return undefined
210
- }
211
- return accounts[accountId]
212
- }
213
-
214
- function hasWorkClawConfig(config: {
215
- appKey?: string
216
- appSecret?: string
217
- agentId?: string | number
218
- }): boolean {
219
- const key = typeof config.appKey === 'string' ? config.appKey.trim() : ''
220
- const secret
221
- = typeof config.appSecret === 'string' ? config.appSecret.trim() : ''
222
- // 只要有 appKey 和 appSecret 就认为配置了 workclaw(agentId 可以动态添加)
223
- return Boolean(key && secret)
224
- }
225
-
226
- export function isOpenclawWorkclawAccountConfigured(config: {
227
- appKey?: string
228
- appSecret?: string
229
- agentId?: string | number
230
- }): boolean {
231
- return hasWorkClawConfig(config)
232
- }
233
-
234
- /**
235
- * Merge top-level config with account-specific config.
236
- * Account-specific fields override top-level fields.
237
- */
238
- function mergeOpenclawWorkclawAccountConfig(cfg: OpenClawConfig, accountId: string): OpenclawWorkclawConfig {
239
- const openclawWorkclawCfg = cfg.channels?.['openclaw-workclaw'] as OpenclawWorkclawConfig | undefined
240
-
241
- // Extract base config (exclude accounts field to avoid recursion)
242
- const { accounts: _ignored, ...base } = openclawWorkclawCfg ?? {}
243
-
244
- // Get account-specific overrides
245
- const account = resolveAccountConfig(cfg, accountId) ?? {}
246
-
247
- // Merge: account config overrides base config
248
- return { ...base, ...account } as OpenclawWorkclawConfig
249
- }
250
-
251
- /**
252
- * Resolve a complete account with merged config.
253
- */
254
- export function resolveOpenclawWorkclawAccount(params: {
255
- cfg: OpenClawConfig
256
- accountId?: string | null
257
- }): ResolvedOpenclawWorkclawAccount {
258
- const accountId = normalizeAccountId(params.accountId)
259
- const openclawWorkclawCfg = params.cfg.channels?.['openclaw-workclaw'] as OpenclawWorkclawConfig | undefined
260
-
261
- // Base enabled state (top-level)
262
- const baseEnabled = openclawWorkclawCfg?.enabled !== false
263
-
264
- // Merge configs
265
- const merged = mergeOpenclawWorkclawAccountConfig(params.cfg, accountId)
266
-
267
- // Account-level enabled state
268
- const accountEnabled = merged.enabled !== false
269
- const enabled = baseEnabled && accountEnabled
270
-
271
- return {
272
- accountId,
273
- enabled,
274
- configured: isOpenclawWorkclawAccountConfigured(merged),
275
- name: (merged as OpenclawWorkclawAccountConfig).name?.trim() || undefined,
276
- config: merged,
277
- }
278
- }
279
-
280
- /**
281
- * List all enabled and configured accounts.
282
- */
283
- export function listEnabledOpenclawWorkclawAccounts(cfg: OpenClawConfig): ResolvedOpenclawWorkclawAccount[] {
284
- return listConfiguredAccountIds(cfg)
285
- .map(accountId => resolveOpenclawWorkclawAccount({ cfg, accountId }))
286
- .filter(account => account.enabled && account.configured)
287
- }