@workclaw/openclaw-workclaw 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +30 -11
  2. package/dist/api.d.ts +3 -0
  3. package/dist/api.js +3 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +264 -0
  6. package/dist/setup-entry.d.ts +2 -0
  7. package/dist/setup-entry.js +12 -0
  8. package/dist/src/accounts.d.ts +66 -0
  9. package/dist/src/accounts.js +279 -0
  10. package/dist/src/api/accounts-api.d.ts +2 -0
  11. package/dist/src/api/accounts-api.js +130 -0
  12. package/dist/src/api/prompts-api.d.ts +2 -0
  13. package/dist/src/api/prompts-api.js +103 -0
  14. package/dist/src/api/session-api.d.ts +2 -0
  15. package/dist/src/api/session-api.js +207 -0
  16. package/dist/src/api/skills-api.d.ts +2 -0
  17. package/dist/src/api/skills-api.js +64 -0
  18. package/dist/src/api/workspace.d.ts +3 -0
  19. package/dist/src/api/workspace.js +30 -0
  20. package/dist/src/channel.d.ts +11 -0
  21. package/{src/channel.ts → dist/src/channel.js} +199 -225
  22. package/dist/src/config-schema.d.ts +93 -0
  23. package/dist/src/config-schema.js +56 -0
  24. package/dist/src/connection/workclaw-client.d.ts +147 -0
  25. package/dist/src/connection/workclaw-client.js +351 -0
  26. package/dist/src/gateway/agent-handlers.d.ts +12 -0
  27. package/{src/gateway/agent-handlers.ts → dist/src/gateway/agent-handlers.js} +372 -462
  28. package/dist/src/gateway/config-writer.d.ts +71 -0
  29. package/dist/src/gateway/config-writer.js +302 -0
  30. package/dist/src/gateway/cron-tasks-handler.d.ts +19 -0
  31. package/dist/src/gateway/cron-tasks-handler.js +188 -0
  32. package/dist/src/gateway/message-context.d.ts +80 -0
  33. package/{src/gateway/message-context.ts → dist/src/gateway/message-context.js} +509 -594
  34. package/dist/src/gateway/message-dispatcher.d.ts +18 -0
  35. package/dist/src/gateway/message-dispatcher.js +572 -0
  36. package/dist/src/gateway/reconnect.d.ts +27 -0
  37. package/{src/gateway/reconnect.ts → dist/src/gateway/reconnect.js} +210 -253
  38. package/dist/src/gateway/skills-handler.d.ts +29 -0
  39. package/dist/src/gateway/skills-handler.js +615 -0
  40. package/dist/src/gateway/skills-list-handler.d.ts +27 -0
  41. package/dist/src/gateway/skills-list-handler.js +233 -0
  42. package/dist/src/gateway/tools-list-handler.d.ts +30 -0
  43. package/dist/src/gateway/tools-list-handler.js +101 -0
  44. package/dist/src/gateway/workclaw-gateway.d.ts +14 -0
  45. package/dist/src/gateway/workclaw-gateway.js +237 -0
  46. package/dist/src/media/upload.d.ts +13 -0
  47. package/dist/src/media/upload.js +125 -0
  48. package/dist/src/outbound/index.d.ts +36 -0
  49. package/dist/src/outbound/index.js +123 -0
  50. package/dist/src/outbound/workclaw-sender.d.ts +36 -0
  51. package/{src/outbound/workclaw-sender.ts → dist/src/outbound/workclaw-sender.js} +95 -158
  52. package/dist/src/runtime.d.ts +116 -0
  53. package/dist/src/runtime.js +374 -0
  54. package/dist/src/secret-contract-api.d.ts +4 -0
  55. package/dist/src/secret-contract-api.js +4 -0
  56. package/{src/send.ts → dist/src/send.d.ts} +1 -1
  57. package/dist/src/send.js +1 -0
  58. package/dist/src/setup-api.d.ts +3 -0
  59. package/dist/src/setup-api.js +3 -0
  60. package/dist/src/setup-core.d.ts +3 -0
  61. package/dist/src/setup-core.js +13 -0
  62. package/dist/src/setup-surface.d.ts +7 -0
  63. package/dist/src/setup-surface.js +363 -0
  64. package/dist/src/tools/openclaw-workclaw-cron/api/index.d.ts +93 -0
  65. package/dist/src/tools/openclaw-workclaw-cron/api/index.js +209 -0
  66. package/dist/src/tools/openclaw-workclaw-cron/index.d.ts +10 -0
  67. package/{src/tools/openclaw-workclaw-cron/index.ts → dist/src/tools/openclaw-workclaw-cron/index.js} +33 -39
  68. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.d.ts +16 -0
  69. package/dist/src/tools/openclaw-workclaw-cron/src/add/params.js +152 -0
  70. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.d.ts +18 -0
  71. package/dist/src/tools/openclaw-workclaw-cron/src/add/sync.js +162 -0
  72. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.d.ts +14 -0
  73. package/dist/src/tools/openclaw-workclaw-cron/src/disable/params.js +80 -0
  74. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.d.ts +14 -0
  75. package/dist/src/tools/openclaw-workclaw-cron/src/disable/sync.js +107 -0
  76. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.d.ts +14 -0
  77. package/dist/src/tools/openclaw-workclaw-cron/src/enable/params.js +80 -0
  78. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.d.ts +14 -0
  79. package/dist/src/tools/openclaw-workclaw-cron/src/enable/sync.js +107 -0
  80. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.d.ts +17 -0
  81. package/dist/src/tools/openclaw-workclaw-cron/src/notify/sync.js +127 -0
  82. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.d.ts +14 -0
  83. package/dist/src/tools/openclaw-workclaw-cron/src/remove/params.js +87 -0
  84. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.d.ts +14 -0
  85. package/dist/src/tools/openclaw-workclaw-cron/src/remove/sync.js +107 -0
  86. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.d.ts +17 -0
  87. package/dist/src/tools/openclaw-workclaw-cron/src/update/params.js +164 -0
  88. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.d.ts +18 -0
  89. package/dist/src/tools/openclaw-workclaw-cron/src/update/sync.js +135 -0
  90. package/dist/src/tools/openclaw-workclaw-cron/types/index.d.ts +52 -0
  91. package/dist/src/tools/openclaw-workclaw-cron/types/index.js +4 -0
  92. package/dist/src/tools/openclaw-workclaw-cron/utils/index.d.ts +40 -0
  93. package/dist/src/tools/openclaw-workclaw-cron/utils/index.js +122 -0
  94. package/dist/src/tools/openclaw-workclaw-system/index.d.ts +10 -0
  95. package/{src/tools/openclaw-workclaw-system/index.ts → dist/src/tools/openclaw-workclaw-system/index.js} +15 -17
  96. package/dist/src/tools/openclaw-workclaw-system/src/get/index.d.ts +8 -0
  97. package/dist/src/tools/openclaw-workclaw-system/src/get/index.js +64 -0
  98. package/dist/src/tools/openclaw-workclaw-system/src/token/index.d.ts +8 -0
  99. package/dist/src/tools/openclaw-workclaw-system/src/token/index.js +78 -0
  100. package/{src/types.ts → dist/src/types.d.ts} +39 -58
  101. package/dist/src/types.js +1 -0
  102. package/dist/src/utils/content.d.ts +15 -0
  103. package/{src/utils/content.ts → dist/src/utils/content.js} +38 -35
  104. package/package.json +13 -9
  105. package/index.ts +0 -302
  106. package/setup-entry.ts +0 -6
  107. package/src/accounts.ts +0 -312
  108. package/src/api/accounts-api.ts +0 -156
  109. package/src/api/prompts-api.ts +0 -116
  110. package/src/api/session-api.ts +0 -238
  111. package/src/api/skills-api.ts +0 -72
  112. package/src/api/workspace.ts +0 -41
  113. package/src/config-schema.ts +0 -110
  114. package/src/connection/workclaw-client.ts +0 -643
  115. package/src/gateway/config-writer.ts +0 -296
  116. package/src/gateway/message-dispatcher.ts +0 -641
  117. package/src/gateway/skills-handler.ts +0 -741
  118. package/src/gateway/skills-list-handler.ts +0 -332
  119. package/src/gateway/tools-list-handler.ts +0 -160
  120. package/src/gateway/workclaw-gateway.ts +0 -367
  121. package/src/media/upload.ts +0 -157
  122. package/src/outbound/index.ts +0 -185
  123. package/src/runtime.ts +0 -497
  124. package/src/tools/openclaw-workclaw-cron/api/index.ts +0 -326
  125. package/src/tools/openclaw-workclaw-cron/src/add/params.ts +0 -177
  126. package/src/tools/openclaw-workclaw-cron/src/add/sync.ts +0 -188
  127. package/src/tools/openclaw-workclaw-cron/src/disable/params.ts +0 -100
  128. package/src/tools/openclaw-workclaw-cron/src/disable/sync.ts +0 -127
  129. package/src/tools/openclaw-workclaw-cron/src/enable/params.ts +0 -100
  130. package/src/tools/openclaw-workclaw-cron/src/enable/sync.ts +0 -127
  131. package/src/tools/openclaw-workclaw-cron/src/notify/sync.ts +0 -148
  132. package/src/tools/openclaw-workclaw-cron/src/remove/params.ts +0 -109
  133. package/src/tools/openclaw-workclaw-cron/src/remove/sync.ts +0 -127
  134. package/src/tools/openclaw-workclaw-cron/src/update/params.ts +0 -195
  135. package/src/tools/openclaw-workclaw-cron/src/update/sync.ts +0 -161
  136. package/src/tools/openclaw-workclaw-cron/types/index.ts +0 -55
  137. package/src/tools/openclaw-workclaw-cron/utils/index.ts +0 -141
  138. package/src/tools/openclaw-workclaw-system/src/get/index.ts +0 -77
  139. package/src/tools/openclaw-workclaw-system/src/token/index.ts +0 -93
  140. package/tests/accounts.test.ts +0 -285
  141. package/tests/message-context.test.ts +0 -313
  142. package/tests/reconnect.test.ts +0 -257
  143. package/tests/workclaw-client.test.ts +0 -112
  144. package/tsconfig.json +0 -14
  145. package/vitest.config.ts +0 -8
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
- }
@@ -1,156 +0,0 @@
1
- import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
- import { normalizeAccountId } from "../accounts.js";
3
-
4
-
5
- function sendJson(res: any, statusCode: number, payload: unknown) {
6
- res.statusCode = statusCode;
7
- res.setHeader("Content-Type", "application/json");
8
- res.end(JSON.stringify(payload));
9
- }
10
-
11
- async function readRequestBody(req: any): Promise<string> {
12
- const chunks: Buffer[] = [];
13
- await new Promise<void>((resolve, reject) => {
14
- req.on("data", (chunk: any) => {
15
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
16
- });
17
- req.on("end", () => resolve());
18
- req.on("error", (err: unknown) => reject(err));
19
- });
20
- return Buffer.concat(chunks).toString("utf-8");
21
- }
22
-
23
- async function loadRuntimeConfig(api: OpenClawPluginApi): Promise<any> {
24
- const runtimeConfig = (api.runtime as any)?.config;
25
- if (runtimeConfig?.loadConfig) {
26
- return runtimeConfig.loadConfig();
27
- }
28
- return api.config;
29
- }
30
-
31
- async function writeRuntimeConfig(api: OpenClawPluginApi, config: any): Promise<void> {
32
- const runtimeConfig = (api.runtime as any)?.config;
33
- if (runtimeConfig?.writeConfigFile) {
34
- await runtimeConfig.writeConfigFile(config);
35
- return;
36
- }
37
- throw new Error("Config write not supported");
38
- }
39
-
40
- function getAccountMap(config: any): Record<string, any> {
41
- const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
42
- const openclawWorkclaw =
43
- channels['openclaw-workclaw'] && typeof channels['openclaw-workclaw'] === "object" ? channels['openclaw-workclaw'] : {};
44
- const accounts =
45
- openclawWorkclaw.accounts && typeof openclawWorkclaw.accounts === "object" ? openclawWorkclaw.accounts : {};
46
- return { ...accounts };
47
- }
48
-
49
- function withAccounts(config: any, accounts: Record<string, any>): any {
50
- const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
51
- const openclawWorkclaw =
52
- channels['openclaw-workclaw'] && typeof channels['openclaw-workclaw'] === "object" ? channels['openclaw-workclaw'] : {};
53
- return {
54
- ...config,
55
- channels: {
56
- ...channels,
57
- 'openclaw-workclaw': {
58
- ...openclawWorkclaw,
59
- accounts,
60
- },
61
- },
62
- };
63
- }
64
-
65
- export function createAccountsApiHandler(api: OpenClawPluginApi) {
66
- return async (req: any, res: any) => {
67
- const method = String(req.method ?? "GET").toUpperCase();
68
- const url = new URL(req.url ?? "", "http://localhost");
69
- const idRaw = url.searchParams.get("id") ?? url.searchParams.get("accountId");
70
- const accountId = idRaw ? normalizeAccountId(idRaw) : null;
71
-
72
- if (method === "GET") {
73
- const cfg = await loadRuntimeConfig(api);
74
- const accounts = getAccountMap(cfg);
75
-
76
- if (accountId) {
77
- const account = accounts[accountId];
78
- if (!account) {
79
- sendJson(res, 404, { ok: false, error: "Not Found" });
80
- return;
81
- }
82
- sendJson(res, 200, { ok: true, accountId, config: account });
83
- return;
84
- }
85
-
86
- const entries = Object.entries(accounts).map(([id, config]) => ({
87
- accountId: id,
88
- config,
89
- }));
90
- sendJson(res, 200, { ok: true, accounts: entries });
91
- return;
92
- }
93
-
94
- if (method === "POST" || method === "PUT") {
95
- const raw = await readRequestBody(req);
96
- let input: any = {};
97
- try {
98
- input = raw ? JSON.parse(raw) : {};
99
- } catch {
100
- sendJson(res, 400, { ok: false, error: "Invalid JSON" });
101
- return;
102
- }
103
-
104
- const inputId = input?.accountId ?? input?.id;
105
- const normalizedId = inputId ? normalizeAccountId(String(inputId)) : "";
106
- const patch = input?.config;
107
-
108
- if (!normalizedId || !patch || typeof patch !== "object") {
109
- sendJson(res, 400, { ok: false, error: "Missing accountId or config" });
110
- return;
111
- }
112
-
113
- const cfg = await loadRuntimeConfig(api);
114
- const accounts = getAccountMap(cfg);
115
-
116
- if (method === "POST" && accounts[normalizedId]) {
117
- sendJson(res, 409, { ok: false, error: "Account already exists" });
118
- return;
119
- }
120
-
121
- if (method === "PUT" && !accounts[normalizedId]) {
122
- sendJson(res, 404, { ok: false, error: "Not Found" });
123
- return;
124
- }
125
-
126
- const next = method === "PUT" ? { ...accounts[normalizedId], ...patch } : patch;
127
- const updated = withAccounts(cfg, { ...accounts, [normalizedId]: next });
128
- await writeRuntimeConfig(api, updated);
129
- sendJson(res, 200, { ok: true, accountId: normalizedId });
130
- return;
131
- }
132
-
133
- if (method === "DELETE") {
134
- if (!accountId) {
135
- sendJson(res, 400, { ok: false, error: "Missing accountId" });
136
- return;
137
- }
138
-
139
- const cfg = await loadRuntimeConfig(api);
140
- const accounts = getAccountMap(cfg);
141
-
142
- if (!accounts[accountId]) {
143
- sendJson(res, 404, { ok: false, error: "Not Found" });
144
- return;
145
- }
146
-
147
- const { [accountId]: _ignored, ...rest } = accounts;
148
- const updated = withAccounts(cfg, rest);
149
- await writeRuntimeConfig(api, updated);
150
- sendJson(res, 200, { ok: true, accountId, deleted: true });
151
- return;
152
- }
153
-
154
- sendJson(res, 405, { ok: false, error: "Method Not Allowed" });
155
- };
156
- }
@@ -1,116 +0,0 @@
1
- import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
2
- import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
3
- import { resolveWorkspaceDir } from "./workspace.js";
4
-
5
- const promptNames = ["SOUL.md", "USER.md"] as const;
6
-
7
- function normalizePromptName(raw: string | null | undefined): (typeof promptNames)[number] | null {
8
- const name = String(raw ?? "").trim().toUpperCase();
9
- if (name === "SOUL" || name === "SOUL.MD") return "SOUL.md";
10
- if (name === "USER" || name === "USER.MD") return "USER.md";
11
- return null;
12
- }
13
-
14
- import path from "node:path";
15
-
16
- function resolvePromptPath(api: OpenClawPluginApi, name: (typeof promptNames)[number]): string {
17
- return path.join(resolveWorkspaceDir(api), name);
18
- }
19
-
20
- function sendJson(res: any, statusCode: number, payload: unknown) {
21
- res.statusCode = statusCode;
22
- res.setHeader("Content-Type", "application/json");
23
- res.end(JSON.stringify(payload));
24
- }
25
-
26
- export function createPromptsApiHandler(api: OpenClawPluginApi) {
27
- return async (req: any, res: any) => {
28
- const method = String(req.method ?? "GET").toUpperCase();
29
- const url = new URL(req.url ?? "", "http://localhost");
30
- const name = normalizePromptName(url.searchParams.get("name"));
31
-
32
- if (method === "GET") {
33
- if (name) {
34
- const filePath = resolvePromptPath(api, name);
35
- try {
36
- const content = await readFile(filePath, "utf-8");
37
- sendJson(res, 200, { ok: true, name, content });
38
- return;
39
- } catch (error) {
40
- sendJson(res, 404, { ok: false, error: "Not Found" });
41
- return;
42
- }
43
- }
44
-
45
- const entries = await Promise.all(
46
- promptNames.map(async (promptName) => {
47
- const filePath = resolvePromptPath(api, promptName);
48
- try {
49
- const info = await stat(filePath);
50
- return { name: promptName, exists: true, bytes: info.size };
51
- } catch {
52
- return { name: promptName, exists: false, bytes: 0 };
53
- }
54
- }),
55
- );
56
- sendJson(res, 200, { ok: true, entries });
57
- return;
58
- }
59
-
60
- if (method === "PUT" || method === "POST") {
61
- const raw = await readRequestBody(req);
62
- let input: any = {};
63
- try {
64
- input = raw ? JSON.parse(raw) : {};
65
- } catch {
66
- sendJson(res, 400, { ok: false, error: "Invalid JSON" });
67
- return;
68
- }
69
-
70
- const targetName = normalizePromptName(input?.name);
71
- const content = typeof input?.content === "string" ? input.content : null;
72
-
73
- if (!targetName || content === null) {
74
- sendJson(res, 400, { ok: false, error: "Missing name or content" });
75
- return;
76
- }
77
-
78
- const workspaceDir = resolveWorkspaceDir(api);
79
- await mkdir(workspaceDir, { recursive: true });
80
- await writeFile(resolvePromptPath(api, targetName), content, { encoding: "utf-8" });
81
- sendJson(res, 200, { ok: true, name: targetName });
82
- return;
83
- }
84
-
85
- if (method === "DELETE") {
86
- if (!name) {
87
- sendJson(res, 400, { ok: false, error: "Missing name" });
88
- return;
89
- }
90
-
91
- const filePath = resolvePromptPath(api, name);
92
- try {
93
- await unlink(filePath);
94
- sendJson(res, 200, { ok: true, name, deleted: true });
95
- return;
96
- } catch {
97
- sendJson(res, 200, { ok: true, name, deleted: false });
98
- return;
99
- }
100
- }
101
-
102
- sendJson(res, 405, { ok: false, error: "Method Not Allowed" });
103
- };
104
- }
105
-
106
- async function readRequestBody(req: any): Promise<string> {
107
- const chunks: Buffer[] = [];
108
- await new Promise<void>((resolve, reject) => {
109
- req.on("data", (chunk: any) => {
110
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
111
- });
112
- req.on("end", () => resolve());
113
- req.on("error", (err: unknown) => reject(err));
114
- });
115
- return Buffer.concat(chunks).toString("utf-8");
116
- }