@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
@@ -0,0 +1,279 @@
1
+ import { DEFAULT_ACCOUNT_ID } from 'openclaw/plugin-sdk/account-id';
2
+ import { getWorkclawLogger, getWorkclawConnectionConfig } from './runtime.js';
3
+ // =============================================================================
4
+ // In-memory lookup cache for (userId, agentId) → workspace-N accountId
5
+ // Problem: OpenClaw doesn't support dashes in account IDs, agentId can be negative
6
+ // Solution: workspace-N naming + in-memory Map for O(1) lookups
7
+ // =============================================================================
8
+ /**
9
+ * Normalize account ID by trimming whitespace
10
+ */
11
+ export function normalizeAccountId(accountId) {
12
+ return String(accountId ?? '').trim();
13
+ }
14
+ /**
15
+ * Key format for the lookup map: "userId|agentId"
16
+ */
17
+ function makeLookupKey(userId, agentId) {
18
+ return `${userId}|${agentId}`;
19
+ }
20
+ /**
21
+ * In-memory map: lookupKey -> accountId
22
+ */
23
+ const lookupCache = new Map();
24
+ /**
25
+ * In-memory map: accountId -> { userId, agentId }
26
+ */
27
+ const accountIndex = new Map();
28
+ /**
29
+ * Next workspace number to allocate
30
+ */
31
+ let nextWorkspaceNum = 1;
32
+ /**
33
+ * Build the lookup cache from existing accounts in cfg.
34
+ * Called once at gateway startup.
35
+ */
36
+ export function buildAccountMap(cfg) {
37
+ lookupCache.clear();
38
+ accountIndex.clear();
39
+ nextWorkspaceNum = 1;
40
+ const _WorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {});
41
+ const accounts = _WorkclawConfig?.accounts;
42
+ if (!accounts || typeof accounts !== 'object')
43
+ return;
44
+ for (const [accountId, accountCfg] of Object.entries(accounts)) {
45
+ if (!accountCfg)
46
+ continue;
47
+ const userId = accountCfg.userId || _WorkclawConfig.userId;
48
+ const agentId = accountCfg.agentId;
49
+ if (!agentId)
50
+ continue;
51
+ // userId may not be present for config-defined accounts; only build
52
+ // lookup if userId is available (dynamically created accounts have it)
53
+ if (userId) {
54
+ const key = makeLookupKey(String(userId), String(agentId));
55
+ lookupCache.set(key, accountId);
56
+ }
57
+ accountIndex.set(accountId, { userId: String(userId ?? ''), agentId: String(agentId) });
58
+ if (accountId.startsWith('workspace-')) {
59
+ const num = Number.parseInt(accountId.slice(accountId.lastIndexOf('-') + 1), 10);
60
+ if (!Number.isNaN(num) && num >= nextWorkspaceNum) {
61
+ nextWorkspaceNum = num + 1;
62
+ }
63
+ }
64
+ }
65
+ // 默认账户允许直接使用顶层 userId/agentId,不要求必须存在 accounts.default
66
+ if (!accountIndex.has(DEFAULT_ACCOUNT_ID) && _WorkclawConfig.userId && _WorkclawConfig.agentId) {
67
+ const userId = String(_WorkclawConfig.userId);
68
+ const agentId = String(_WorkclawConfig.agentId);
69
+ const key = makeLookupKey(userId, agentId);
70
+ lookupCache.set(key, DEFAULT_ACCOUNT_ID);
71
+ accountIndex.set(DEFAULT_ACCOUNT_ID, { userId, agentId });
72
+ }
73
+ getWorkclawLogger().info(`[AccountManager] Built account map with ${lookupCache.size} entries, nextWorkspaceNum=${nextWorkspaceNum}`);
74
+ }
75
+ /**
76
+ * Resolve accountId by userId + agentId.
77
+ * First checks cache, then falls back to iteration.
78
+ */
79
+ export function resolveAccountByUserIdAndAgentId(cfg, userId, agentId) {
80
+ const key = makeLookupKey(userId, agentId);
81
+ if (lookupCache.has(key)) {
82
+ return lookupCache.get(key);
83
+ }
84
+ const _WorkclawConfig = (cfg.channels?.['openclaw-workclaw'] || {});
85
+ const accounts = _WorkclawConfig?.accounts;
86
+ if (accounts && typeof accounts === 'object') {
87
+ for (const [accountId, accountCfg] of Object.entries(accounts)) {
88
+ if (!accountCfg)
89
+ continue;
90
+ const accountUserId = accountCfg.userId || _WorkclawConfig.userId;
91
+ if (String(accountUserId) === userId && String(accountCfg.agentId) === agentId) {
92
+ lookupCache.set(key, accountId);
93
+ accountIndex.set(accountId, { userId, agentId });
94
+ return accountId;
95
+ }
96
+ }
97
+ }
98
+ // 兼容默认账户直接写在顶层配置中的场景
99
+ if (String(_WorkclawConfig.userId ?? '') === userId
100
+ && String(_WorkclawConfig.agentId ?? '') === agentId) {
101
+ lookupCache.set(key, DEFAULT_ACCOUNT_ID);
102
+ accountIndex.set(DEFAULT_ACCOUNT_ID, { userId, agentId });
103
+ return DEFAULT_ACCOUNT_ID;
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * Allocate a new workspace-N accountId and register it in the map.
109
+ */
110
+ export function allocateWorkerAccountId(_cfg, userId, agentId) {
111
+ const accountId = `workspace-${nextWorkspaceNum}`;
112
+ nextWorkspaceNum++;
113
+ const key = makeLookupKey(userId, agentId);
114
+ lookupCache.set(key, accountId);
115
+ accountIndex.set(accountId, { userId, agentId });
116
+ getWorkclawLogger().info(`[AccountManager] Allocated accountId=${accountId} for userId=${userId} agentId=${agentId}`);
117
+ return accountId;
118
+ }
119
+ /**
120
+ * Refresh the cache when an account's userId or agentId changes.
121
+ */
122
+ export function refreshAccountCache(cfg) {
123
+ buildAccountMap(cfg);
124
+ }
125
+ // =============================================================================
126
+ // Account config resolution (pure functions, no in-memory state)
127
+ // =============================================================================
128
+ /**
129
+ * List all configured account IDs from the accounts field.
130
+ */
131
+ function listConfiguredAccountIds(cfg) {
132
+ const accounts = cfg.channels?.['openclaw-workclaw']?.accounts;
133
+ if (!accounts || typeof accounts !== 'object') {
134
+ return [];
135
+ }
136
+ return Object.keys(accounts).filter(Boolean);
137
+ }
138
+ /**
139
+ * Check if plugin-level workclaw config exists (appKey + appSecret)
140
+ */
141
+ function hasPluginLevelWorkClawConfig(cfg) {
142
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'];
143
+ const key = typeof workclawCfg?.appKey === 'string' ? workclawCfg.appKey.trim() : '';
144
+ const secret = typeof workclawCfg?.appSecret === 'string' ? workclawCfg.appSecret.trim() : '';
145
+ return Boolean(key && secret);
146
+ }
147
+ /**
148
+ * List all account IDs.
149
+ * If no accounts are configured but plugin has workclaw config, returns [DEFAULT_ACCOUNT_ID].
150
+ */
151
+ export function listWorkclawAccountIds(cfg) {
152
+ const ids = listConfiguredAccountIds(cfg);
153
+ if (ids.length === 0) {
154
+ // 如果没有配置账户,但插件级别有 workclaw 配置,返回默认账户
155
+ if (hasPluginLevelWorkClawConfig(cfg)) {
156
+ return [DEFAULT_ACCOUNT_ID];
157
+ }
158
+ // Backward compatibility: no accounts configured, use default
159
+ return [DEFAULT_ACCOUNT_ID];
160
+ }
161
+ return [...ids].toSorted((a, b) => a.localeCompare(b));
162
+ }
163
+ /**
164
+ * Resolve the default account ID.
165
+ */
166
+ export function resolveDefaultWorkclawAccountId(cfg) {
167
+ const ids = listWorkclawAccountIds(cfg);
168
+ if (ids.includes(DEFAULT_ACCOUNT_ID)) {
169
+ return DEFAULT_ACCOUNT_ID;
170
+ }
171
+ return ids[0] ?? DEFAULT_ACCOUNT_ID;
172
+ }
173
+ /**
174
+ * Get the raw account-specific config.
175
+ */
176
+ function resolveAccountConfig(cfg, accountId) {
177
+ const accounts = cfg.channels?.['openclaw-workclaw']?.accounts;
178
+ if (!accounts || typeof accounts !== 'object') {
179
+ return undefined;
180
+ }
181
+ return accounts[accountId];
182
+ }
183
+ function hasWorkClawConfig(config) {
184
+ const key = typeof config.appKey === 'string' ? config.appKey.trim() : '';
185
+ const secret = typeof config.appSecret === 'string' ? config.appSecret.trim() : '';
186
+ // 只要有 appKey 和 appSecret 就认为配置了 workclaw(agentId 可以动态添加)
187
+ return Boolean(key && secret);
188
+ }
189
+ export function isWorkclawAccountConfigured(config) {
190
+ return hasWorkClawConfig(config);
191
+ }
192
+ /**
193
+ * Merge top-level config with account-specific config.
194
+ * Account-specific fields override top-level fields.
195
+ */
196
+ function mergeWorkclawAccountConfig(cfg, accountId) {
197
+ const workclawCfg = cfg.channels?.['openclaw-workclaw'];
198
+ // Extract base config (exclude accounts field to avoid recursion)
199
+ const { accounts: _ignored, ...base } = workclawCfg ?? {};
200
+ // Get account-specific overrides
201
+ const account = resolveAccountConfig(cfg, accountId) ?? {};
202
+ // Merge: account config overrides base config
203
+ return { ...base, ...account };
204
+ }
205
+ /**
206
+ * Resolve a complete account with merged config.
207
+ */
208
+ export function resolveWorkclawAccount(params) {
209
+ const accountId = normalizeAccountId(params.accountId);
210
+ const workclawCfg = params.cfg.channels?.['openclaw-workclaw'];
211
+ // Base enabled state (top-level)
212
+ const baseEnabled = workclawCfg?.enabled !== false;
213
+ // Merge configs
214
+ const merged = mergeWorkclawAccountConfig(params.cfg, accountId);
215
+ // Account-level enabled state
216
+ const accountEnabled = merged.enabled !== false;
217
+ const enabled = baseEnabled && accountEnabled;
218
+ return {
219
+ accountId,
220
+ enabled,
221
+ configured: isWorkclawAccountConfigured(merged),
222
+ name: merged.name?.trim() || undefined,
223
+ config: merged,
224
+ };
225
+ }
226
+ /**
227
+ * List all enabled and configured accounts.
228
+ */
229
+ export function listEnabledWorkclawAccounts(cfg) {
230
+ return listConfiguredAccountIds(cfg)
231
+ .map(accountId => resolveWorkclawAccount({ cfg, accountId }))
232
+ .filter(account => account.enabled && account.configured);
233
+ }
234
+ /**
235
+ * Resolve account and apply cached connection config if available.
236
+ * This ensures that appKey/appSecret etc. use the stable values captured at connection time,
237
+ * not potentially mutated values from cfg at resolution time.
238
+ */
239
+ export function resolveWorkclawAccountWithCache(params) {
240
+ const account = resolveWorkclawAccount(params);
241
+ const cachedConfig = getWorkclawConnectionConfig(account.accountId);
242
+ if (cachedConfig) {
243
+ // Apply cached values to ensure stability
244
+ account.config.appKey = cachedConfig.appKey || account.config.appKey;
245
+ account.config.appSecret = cachedConfig.appSecret || account.config.appSecret;
246
+ if (cachedConfig.baseUrl)
247
+ account.config.baseUrl = cachedConfig.baseUrl;
248
+ if (cachedConfig.websocketUrl !== undefined)
249
+ account.config.websocketUrl = cachedConfig.websocketUrl;
250
+ if (cachedConfig.localIp !== undefined)
251
+ account.config.localIp = cachedConfig.localIp;
252
+ if (cachedConfig.allowInsecureTls !== undefined)
253
+ account.config.allowInsecureTls = cachedConfig.allowInsecureTls;
254
+ if (cachedConfig.requestTimeout !== undefined)
255
+ account.config.requestTimeout = cachedConfig.requestTimeout;
256
+ }
257
+ return account;
258
+ }
259
+ /**
260
+ * Inspect and probe workclaw credentials.
261
+ * Returns a function that can be called to test the connection.
262
+ */
263
+ export function inspectWorkclawCredentials(workclawCfg) {
264
+ const appKey = typeof workclawCfg?.appKey === 'string' ? workclawCfg.appKey.trim() : '';
265
+ const appSecret = typeof workclawCfg?.appSecret === 'string' ? workclawCfg.appSecret.trim() : '';
266
+ if (!appKey || !appSecret) {
267
+ return null;
268
+ }
269
+ return async () => {
270
+ try {
271
+ // 这里可以实现凭证验证逻辑
272
+ // 暂时返回成功,因为实际验证需要连接工作线程
273
+ return { ok: true };
274
+ }
275
+ catch {
276
+ return { ok: false };
277
+ }
278
+ };
279
+ }
@@ -0,0 +1,2 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ export declare function createAccountsApiHandler(api: OpenClawPluginApi): (req: any, res: any) => Promise<void>;
@@ -0,0 +1,130 @@
1
+ import { normalizeAccountId } from "../accounts.js";
2
+ function sendJson(res, statusCode, payload) {
3
+ res.statusCode = statusCode;
4
+ res.setHeader("Content-Type", "application/json");
5
+ res.end(JSON.stringify(payload));
6
+ }
7
+ async function readRequestBody(req) {
8
+ const chunks = [];
9
+ await new Promise((resolve, reject) => {
10
+ req.on("data", (chunk) => {
11
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
12
+ });
13
+ req.on("end", () => resolve());
14
+ req.on("error", (err) => reject(err));
15
+ });
16
+ return Buffer.concat(chunks).toString("utf-8");
17
+ }
18
+ async function loadRuntimeConfig(api) {
19
+ const runtimeConfig = api.runtime?.config;
20
+ if (runtimeConfig?.loadConfig) {
21
+ return runtimeConfig.loadConfig();
22
+ }
23
+ return api.config;
24
+ }
25
+ async function writeRuntimeConfig(api, config) {
26
+ const runtimeConfig = api.runtime?.config;
27
+ if (runtimeConfig?.writeConfigFile) {
28
+ await runtimeConfig.writeConfigFile(config);
29
+ return;
30
+ }
31
+ throw new Error("Config write not supported");
32
+ }
33
+ function getAccountMap(config) {
34
+ const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
35
+ const openclawWorkclaw = channels['openclaw-workclaw'] && typeof channels['openclaw-workclaw'] === "object" ? channels['openclaw-workclaw'] : {};
36
+ const accounts = openclawWorkclaw.accounts && typeof openclawWorkclaw.accounts === "object" ? openclawWorkclaw.accounts : {};
37
+ return { ...accounts };
38
+ }
39
+ function withAccounts(config, accounts) {
40
+ const channels = config?.channels && typeof config.channels === "object" ? config.channels : {};
41
+ const openclawWorkclaw = channels['openclaw-workclaw'] && typeof channels['openclaw-workclaw'] === "object" ? channels['openclaw-workclaw'] : {};
42
+ return {
43
+ ...config,
44
+ channels: {
45
+ ...channels,
46
+ 'openclaw-workclaw': {
47
+ ...openclawWorkclaw,
48
+ accounts,
49
+ },
50
+ },
51
+ };
52
+ }
53
+ export function createAccountsApiHandler(api) {
54
+ return async (req, res) => {
55
+ const method = String(req.method ?? "GET").toUpperCase();
56
+ const url = new URL(req.url ?? "", "http://localhost");
57
+ const idRaw = url.searchParams.get("id") ?? url.searchParams.get("accountId");
58
+ const accountId = idRaw ? normalizeAccountId(idRaw) : null;
59
+ if (method === "GET") {
60
+ const cfg = await loadRuntimeConfig(api);
61
+ const accounts = getAccountMap(cfg);
62
+ if (accountId) {
63
+ const account = accounts[accountId];
64
+ if (!account) {
65
+ sendJson(res, 404, { ok: false, error: "Not Found" });
66
+ return;
67
+ }
68
+ sendJson(res, 200, { ok: true, accountId, config: account });
69
+ return;
70
+ }
71
+ const entries = Object.entries(accounts).map(([id, config]) => ({
72
+ accountId: id,
73
+ config,
74
+ }));
75
+ sendJson(res, 200, { ok: true, accounts: entries });
76
+ return;
77
+ }
78
+ if (method === "POST" || method === "PUT") {
79
+ const raw = await readRequestBody(req);
80
+ let input = {};
81
+ try {
82
+ input = raw ? JSON.parse(raw) : {};
83
+ }
84
+ catch {
85
+ sendJson(res, 400, { ok: false, error: "Invalid JSON" });
86
+ return;
87
+ }
88
+ const inputId = input?.accountId ?? input?.id;
89
+ const normalizedId = inputId ? normalizeAccountId(String(inputId)) : "";
90
+ const patch = input?.config;
91
+ if (!normalizedId || !patch || typeof patch !== "object") {
92
+ sendJson(res, 400, { ok: false, error: "Missing accountId or config" });
93
+ return;
94
+ }
95
+ const cfg = await loadRuntimeConfig(api);
96
+ const accounts = getAccountMap(cfg);
97
+ if (method === "POST" && accounts[normalizedId]) {
98
+ sendJson(res, 409, { ok: false, error: "Account already exists" });
99
+ return;
100
+ }
101
+ if (method === "PUT" && !accounts[normalizedId]) {
102
+ sendJson(res, 404, { ok: false, error: "Not Found" });
103
+ return;
104
+ }
105
+ const next = method === "PUT" ? { ...accounts[normalizedId], ...patch } : patch;
106
+ const updated = withAccounts(cfg, { ...accounts, [normalizedId]: next });
107
+ await writeRuntimeConfig(api, updated);
108
+ sendJson(res, 200, { ok: true, accountId: normalizedId });
109
+ return;
110
+ }
111
+ if (method === "DELETE") {
112
+ if (!accountId) {
113
+ sendJson(res, 400, { ok: false, error: "Missing accountId" });
114
+ return;
115
+ }
116
+ const cfg = await loadRuntimeConfig(api);
117
+ const accounts = getAccountMap(cfg);
118
+ if (!accounts[accountId]) {
119
+ sendJson(res, 404, { ok: false, error: "Not Found" });
120
+ return;
121
+ }
122
+ const { [accountId]: _ignored, ...rest } = accounts;
123
+ const updated = withAccounts(cfg, rest);
124
+ await writeRuntimeConfig(api, updated);
125
+ sendJson(res, 200, { ok: true, accountId, deleted: true });
126
+ return;
127
+ }
128
+ sendJson(res, 405, { ok: false, error: "Method Not Allowed" });
129
+ };
130
+ }
@@ -0,0 +1,2 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ export declare function createPromptsApiHandler(api: OpenClawPluginApi): (req: any, res: any) => Promise<void>;
@@ -0,0 +1,103 @@
1
+ import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { resolveWorkspaceDir } from "./workspace.js";
3
+ const promptNames = ["SOUL.md", "USER.md"];
4
+ function normalizePromptName(raw) {
5
+ const name = String(raw ?? "").trim().toUpperCase();
6
+ if (name === "SOUL" || name === "SOUL.MD")
7
+ return "SOUL.md";
8
+ if (name === "USER" || name === "USER.MD")
9
+ return "USER.md";
10
+ return null;
11
+ }
12
+ import path from "node:path";
13
+ function resolvePromptPath(api, name) {
14
+ return path.join(resolveWorkspaceDir(api), name);
15
+ }
16
+ function sendJson(res, statusCode, payload) {
17
+ res.statusCode = statusCode;
18
+ res.setHeader("Content-Type", "application/json");
19
+ res.end(JSON.stringify(payload));
20
+ }
21
+ export function createPromptsApiHandler(api) {
22
+ return async (req, res) => {
23
+ const method = String(req.method ?? "GET").toUpperCase();
24
+ const url = new URL(req.url ?? "", "http://localhost");
25
+ const name = normalizePromptName(url.searchParams.get("name"));
26
+ if (method === "GET") {
27
+ if (name) {
28
+ const filePath = resolvePromptPath(api, name);
29
+ try {
30
+ const content = await readFile(filePath, "utf-8");
31
+ sendJson(res, 200, { ok: true, name, content });
32
+ return;
33
+ }
34
+ catch (error) {
35
+ sendJson(res, 404, { ok: false, error: "Not Found" });
36
+ return;
37
+ }
38
+ }
39
+ const entries = await Promise.all(promptNames.map(async (promptName) => {
40
+ const filePath = resolvePromptPath(api, promptName);
41
+ try {
42
+ const info = await stat(filePath);
43
+ return { name: promptName, exists: true, bytes: info.size };
44
+ }
45
+ catch {
46
+ return { name: promptName, exists: false, bytes: 0 };
47
+ }
48
+ }));
49
+ sendJson(res, 200, { ok: true, entries });
50
+ return;
51
+ }
52
+ if (method === "PUT" || method === "POST") {
53
+ const raw = await readRequestBody(req);
54
+ let input = {};
55
+ try {
56
+ input = raw ? JSON.parse(raw) : {};
57
+ }
58
+ catch {
59
+ sendJson(res, 400, { ok: false, error: "Invalid JSON" });
60
+ return;
61
+ }
62
+ const targetName = normalizePromptName(input?.name);
63
+ const content = typeof input?.content === "string" ? input.content : null;
64
+ if (!targetName || content === null) {
65
+ sendJson(res, 400, { ok: false, error: "Missing name or content" });
66
+ return;
67
+ }
68
+ const workspaceDir = resolveWorkspaceDir(api);
69
+ await mkdir(workspaceDir, { recursive: true });
70
+ await writeFile(resolvePromptPath(api, targetName), content, { encoding: "utf-8" });
71
+ sendJson(res, 200, { ok: true, name: targetName });
72
+ return;
73
+ }
74
+ if (method === "DELETE") {
75
+ if (!name) {
76
+ sendJson(res, 400, { ok: false, error: "Missing name" });
77
+ return;
78
+ }
79
+ const filePath = resolvePromptPath(api, name);
80
+ try {
81
+ await unlink(filePath);
82
+ sendJson(res, 200, { ok: true, name, deleted: true });
83
+ return;
84
+ }
85
+ catch {
86
+ sendJson(res, 200, { ok: true, name, deleted: false });
87
+ return;
88
+ }
89
+ }
90
+ sendJson(res, 405, { ok: false, error: "Method Not Allowed" });
91
+ };
92
+ }
93
+ async function readRequestBody(req) {
94
+ const chunks = [];
95
+ await new Promise((resolve, reject) => {
96
+ req.on("data", (chunk) => {
97
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
98
+ });
99
+ req.on("end", () => resolve());
100
+ req.on("error", (err) => reject(err));
101
+ });
102
+ return Buffer.concat(chunks).toString("utf-8");
103
+ }
@@ -0,0 +1,2 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ export declare function createSessionApiHandler(api: OpenClawPluginApi): (req: any, res: any) => Promise<void>;