@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
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Reconnect Scheduler - manages WebSocket reconnection with exponential backoff
3
+ */
4
+ import { WebSocket } from "undici";
5
+ import type { WorkClawBaseConfig } from "../types.js";
6
+ export interface ReconnectSchedulerOptions {
7
+ /** Key for WebSocket storage (appKey) */
8
+ key: string;
9
+ config: WorkClawBaseConfig;
10
+ log?: {
11
+ info?: (msg: string) => void;
12
+ warn?: (msg: string) => void;
13
+ error?: (msg: string) => void;
14
+ debug?: (msg: string) => void;
15
+ };
16
+ onMessage: (data: string) => void;
17
+ onReconnectSuccess?: () => void;
18
+ /** Called when connection closes (after initial connect), to trigger reconnect */
19
+ onClose?: () => void;
20
+ /** Called after WebSocket is registered (before onopen), useful for lock release */
21
+ onConnectingStarted?: (ws: WebSocket) => void;
22
+ }
23
+ export declare function createReconnectScheduler(options: ReconnectSchedulerOptions): {
24
+ connect: () => Promise<void>;
25
+ scheduleReconnect: () => void;
26
+ stopReconnect: () => void;
27
+ };
@@ -1,253 +1,206 @@
1
- /**
2
- * Reconnect Scheduler - manages WebSocket reconnection with exponential backoff
3
- * Supports both per-account and per-appKey strategies
4
- */
5
-
6
- import { clearWorkclawTokenCache } from "../connection/workclaw-client.js";
7
- import { openWorkclawConnection } from "../connection/workclaw-client.js";
8
- import { Agent, WebSocket } from "undici";
9
- import { setWorkclawWsConnection, clearWorkclawWsConnection } from "../runtime.js";
10
- import type { WorkClawBaseConfig } from "../types.js";
11
-
12
- export interface ReconnectSchedulerOptions {
13
- /** Key for WebSocket storage: accountId (per-account) or appKey (per-appKey) */
14
- key: string;
15
- config: WorkClawBaseConfig;
16
- log?: {
17
- info?: (msg: string) => void;
18
- warn?: (msg: string) => void;
19
- error?: (msg: string) => void;
20
- debug?: (msg: string) => void;
21
- };
22
- onMessage: (data: string) => void;
23
- onReconnectSuccess?: () => void;
24
- /** Called when connection closes (after initial connect), to trigger reconnect */
25
- onClose?: () => void;
26
- /** Called after WebSocket is registered (before onopen), useful for per-appKey lock release */
27
- onConnectingStarted?: (ws: WebSocket) => void;
28
- }
29
-
30
- export function createReconnectScheduler(options: ReconnectSchedulerOptions): {
31
- connect: () => Promise<void>;
32
- scheduleReconnect: () => void;
33
- stopReconnect: () => void;
34
- } {
35
- const { key, config, log, onMessage, onReconnectSuccess, onClose, onConnectingStarted } = options;
36
-
37
- let reconnectBackoff = 5000;
38
- let shouldStopReconnect = false;
39
- let pendingReconnectTimer: NodeJS.Timeout | null = null;
40
- /** 正在进行的 doConnect() 的 promise,所有 caller 共享同一个结果 */
41
- let pendingDoConnectPromise: Promise<void> | null = null;
42
-
43
- /**
44
- * 核心建连逻辑,首次连接和重连复用同一套代码
45
- * 返回 Promise,连接建立后 resolve,失败后决定是否重连
46
- * 关键:重试时复用 pendingDoConnectPromise,所有 caller 共享同一个结果
47
- * - 失败时:不删除 promise,让后续 connect() 调用者等待重试结果
48
- * - 重试定时器触发时:复用同一 promise,不创建新的
49
- */
50
- async function doConnect(): Promise<void> {
51
- // 如果已有进行中的 doConnect(失败后重试期间),复用同一 promise
52
- if (pendingDoConnectPromise !== null) {
53
- return pendingDoConnectPromise;
54
- }
55
-
56
- let resolveThis: (() => void) | undefined;
57
- let rejectThis: ((err: unknown) => void) | undefined;
58
- const p = new Promise<void>((resolve, reject) => {
59
- resolveThis = resolve;
60
- rejectThis = reject;
61
- });
62
- // 设置后再调用 connection,后续 connect() 调用能立即看到它
63
- pendingDoConnectPromise = p;
64
-
65
- const tokenCacheKey = config.appKey || key;
66
- clearWorkclawTokenCache(tokenCacheKey);
67
-
68
- const connConfig = {
69
- baseUrl: config.baseUrl || "",
70
- websocketUrl: config.websocketUrl,
71
- appKey: config.appKey,
72
- appSecret: config.appSecret,
73
- localIp: config.localIp,
74
- allowInsecureTls: config.allowInsecureTls,
75
- requestTimeout: config.requestTimeout,
76
- };
77
-
78
- let endpoint: string;
79
- let ticket: string;
80
- try {
81
- const result = await openWorkclawConnection(tokenCacheKey, connConfig);
82
- endpoint = result.endpoint;
83
- ticket = result.ticket;
84
- } catch (err) {
85
- // openWorkclawConnection 失败时(如 AbortError),由 handleConnectError 决定是否重试
86
- // 如果不重试则 reject promise;如果重试则保持 pending(后续 timer 会触发重试)
87
- const willRetry = handleConnectError(String(err));
88
- if (!willRetry) {
89
- pendingDoConnectPromise = null;
90
- rejectThis!(err);
91
- }
92
- throw err;
93
- }
94
- const url = `${endpoint}?ticket=${encodeURIComponent(ticket)}`;
95
-
96
- const dispatcher = connConfig.allowInsecureTls
97
- ? new Agent({ connect: { rejectUnauthorized: false } })
98
- : undefined;
99
- const wsOptions = dispatcher ? { dispatcher } : undefined;
100
-
101
- const ws = new WebSocket(url, wsOptions);
102
- setWorkclawWsConnection(key, ws);
103
-
104
- // onopen 之前调用,让 waitForConnect() 释放锁
105
- onConnectingStarted?.(ws);
106
-
107
- // 统一用 resolveThis/rejectThis,ws.onopen 调用 resolveThis 让 await Promise 完成
108
- ws.onopen = () => {
109
- log?.info?.(`Gateway WebSocket connected endpoint=${endpoint}`);
110
- reconnectBackoff = 5000;
111
- onReconnectSuccess?.();
112
- resolveThis!();
113
- };
114
-
115
- ws.onerror = (event: any) => {
116
- log?.error?.(`Gateway WebSocket error: ${String(event?.message ?? event)}`);
117
- rejectThis!(new Error(String(event?.message ?? event)));
118
- };
119
-
120
- ws.onclose = (event: any) => {
121
- const code = String(event?.code ?? "");
122
- const reason = String(event?.reason ?? "");
123
- log?.warn?.(`Gateway WebSocket closed code=${code} reason=${reason}`);
124
- clearWorkclawWsConnection(key);
125
- if (onClose) {
126
- onClose();
127
- } else {
128
- scheduleReconnect();
129
- }
130
- rejectThis!(new Error(`WebSocket closed code=${code} reason=${reason}`));
131
- };
132
-
133
- ws.onmessage = (event: any) => {
134
- const data = typeof event.data === "string" ? event.data : String(event.data ?? "");
135
- log?.info?.(`Gateway WebSocket message received bytes=${data.length}`);
136
- onMessage(data);
137
- };
138
-
139
- // 等待 ws.onopen 完成(resolveThis)或 ws.onerror/ws.onclose 失败(rejectThis)
140
- await new Promise<void>((resolve, reject) => {
141
- const timeout = setTimeout(() => reject(new Error("websocket connection timeout")), 30000);
142
- ws.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });
143
- ws.addEventListener("error", (event: any) => { clearTimeout(timeout); reject(new Error(String(event?.message ?? event))); }, { once: true });
144
- ws.addEventListener("close", (event: any) => { clearTimeout(timeout); reject(new Error(`websocket closed before ready code=${event?.code ?? ""} reason=${event?.reason ?? ""}`)); }, { once: true });
145
- });
146
- }
147
-
148
- const scheduleReconnect = () => {
149
- if (shouldStopReconnect) {
150
- log?.info?.(`Reconnect: Stopped due to previous auth failure`);
151
- return;
152
- }
153
- if (pendingReconnectTimer !== null) {
154
- log?.info?.(`Reconnect: Already scheduled, skipping duplicate`);
155
- return;
156
- }
157
-
158
- const jitter = Math.floor(Math.random() * 3000);
159
- const delayMs = reconnectBackoff + jitter;
160
- log?.info?.(`Reconnect: Scheduling in ${delayMs}ms (base=${reconnectBackoff} + jitter=${jitter}) key=${key}`);
161
-
162
- pendingReconnectTimer = setTimeout(async () => {
163
- pendingReconnectTimer = null;
164
- // 清除旧的 pendingDoConnectPromise,确保 doConnect() 真正建立新连接
165
- // 否则 doConnect() 会直接返回已 resolved 的旧 promise(第一次失败后 promise 没被清除)
166
- pendingDoConnectPromise = null;
167
- try {
168
- log?.info?.(`Reconnect: Attempting... key=${key}`);
169
- await doConnect();
170
- log?.info?.(`Reconnect: Success`);
171
- } catch (err) {
172
- const errorStr = String(err);
173
- log?.error?.(`Reconnect: Failed: ${errorStr}`);
174
- const willRetry = handleConnectError(errorStr);
175
- if (!willRetry) {
176
- // 永久失败,清除 pending promise
177
- pendingDoConnectPromise = null;
178
- }
179
- }
180
- }, delayMs);
181
- };
182
-
183
- /** 返回 true=会重试(promise 保持 pending),false=不重试(promise 应被 reject) */
184
- function handleConnectError(errorStr: string): boolean {
185
- if (errorStr.includes("访问过于频繁")) {
186
- log?.warn?.(`Reconnect: Rate limited, retrying with minimal backoff`);
187
- if (pendingReconnectTimer !== null) {
188
- clearTimeout(pendingReconnectTimer);
189
- pendingReconnectTimer = null;
190
- }
191
- reconnectBackoff = 1000;
192
- scheduleReconnect();
193
- return true; // 会重试
194
- }
195
-
196
- const isAuthError =
197
- errorStr.includes('"errCode":2001') ||
198
- errorStr.includes('"code":2001') ||
199
- errorStr.includes("鉴权失败") ||
200
- errorStr.includes("invalid credentials") ||
201
- errorStr.includes("unauthorized");
202
-
203
- if (isAuthError) {
204
- log?.error?.(`Reconnect: Authentication failed, stopping`);
205
- shouldStopReconnect = true;
206
- if (pendingReconnectTimer !== null) {
207
- clearTimeout(pendingReconnectTimer);
208
- pendingReconnectTimer = null;
209
- }
210
- return false; // 不重试
211
- }
212
-
213
- // 其他错误:重试
214
- return true;
215
- }
216
-
217
- /**
218
- * 首次连接或重连:调用 doConnect(),返回其 promise
219
- * 如果 doConnect() 因失败正在重试(promise 仍 pending),返回同一 promise
220
- * 调用方 await 此方法,连接建立后 resolve,失败且不重试时 reject
221
- */
222
- async function connect(): Promise<void> {
223
- // 如果 doConnect() 正在进行中(失败后重试期间),返回同一 promise 让 caller 等待
224
- if (pendingDoConnectPromise !== null) {
225
- return pendingDoConnectPromise;
226
- }
227
- try {
228
- return await doConnect();
229
- } catch (err) {
230
- const errorStr = String(err);
231
- log?.error?.(`Gateway connect failed: ${errorStr}`);
232
- const willRetry = handleConnectError(errorStr);
233
- if (!willRetry) {
234
- // 不重试时,清除 pending promise,后续 connect() 可创建新的
235
- pendingDoConnectPromise = null;
236
- throw err;
237
- }
238
- // handleConnectError 返回 true 时,安排后续重试
239
- // 注意:pendingDoConnectPromise 仍 pending,下次定时器触发时会清除它再真正重连
240
- scheduleReconnect();
241
- }
242
- }
243
-
244
- const stopReconnect = () => {
245
- shouldStopReconnect = true;
246
- if (pendingReconnectTimer !== null) {
247
- clearTimeout(pendingReconnectTimer);
248
- pendingReconnectTimer = null;
249
- }
250
- };
251
-
252
- return { connect, scheduleReconnect, stopReconnect };
253
- }
1
+ /**
2
+ * Reconnect Scheduler - manages WebSocket reconnection with exponential backoff
3
+ */
4
+ import { clearWorkclawTokenCache } from "../connection/workclaw-client.js";
5
+ import { openWorkclawConnection } from "../connection/workclaw-client.js";
6
+ import { Agent, WebSocket } from "undici";
7
+ import { setWorkclawWsConnection, clearWorkclawWsConnection } from "../runtime.js";
8
+ export function createReconnectScheduler(options) {
9
+ const { key, config, log, onMessage, onReconnectSuccess, onClose, onConnectingStarted } = options;
10
+ let reconnectBackoff = 5000;
11
+ let shouldStopReconnect = false;
12
+ let pendingReconnectTimer = null;
13
+ /** 正在进行的 doConnect() promise,所有 caller 共享同一个结果 */
14
+ let pendingDoConnectPromise = null;
15
+ /**
16
+ * 核心建连逻辑,首次连接和重连复用同一套代码
17
+ * 返回 Promise,连接建立后 resolve,失败后决定是否重连
18
+ * 关键:重试时复用 pendingDoConnectPromise,所有 caller 共享同一个结果
19
+ * - 失败时:不删除 promise,让后续 connect() 调用者等待重试结果
20
+ * - 重试定时器触发时:复用同一 promise,不创建新的
21
+ */
22
+ async function doConnect() {
23
+ // 如果已有进行中的 doConnect(失败后重试期间),复用同一 promise
24
+ if (pendingDoConnectPromise !== null) {
25
+ return pendingDoConnectPromise;
26
+ }
27
+ let resolveThis;
28
+ let rejectThis;
29
+ const p = new Promise((resolve, reject) => {
30
+ resolveThis = resolve;
31
+ rejectThis = reject;
32
+ });
33
+ // 设置后再调用 connection,后续 connect() 调用能立即看到它
34
+ pendingDoConnectPromise = p;
35
+ const tokenCacheKey = config.appKey || key;
36
+ clearWorkclawTokenCache(tokenCacheKey);
37
+ const connConfig = {
38
+ baseUrl: config.baseUrl || "",
39
+ websocketUrl: config.websocketUrl,
40
+ appKey: config.appKey,
41
+ appSecret: config.appSecret,
42
+ localIp: config.localIp,
43
+ allowInsecureTls: config.allowInsecureTls,
44
+ requestTimeout: config.requestTimeout,
45
+ };
46
+ let endpoint;
47
+ let ticket;
48
+ try {
49
+ const result = await openWorkclawConnection(tokenCacheKey, connConfig);
50
+ endpoint = result.endpoint;
51
+ ticket = result.ticket;
52
+ }
53
+ catch (err) {
54
+ // openWorkclawConnection 失败时(如 AbortError),由 handleConnectError 决定是否重试
55
+ // 如果不重试则 reject promise;如果重试则保持 pending(后续 timer 会触发重试)
56
+ const willRetry = handleConnectError(String(err));
57
+ if (!willRetry) {
58
+ pendingDoConnectPromise = null;
59
+ rejectThis(err);
60
+ }
61
+ throw err;
62
+ }
63
+ const url = `${endpoint}?ticket=${encodeURIComponent(ticket)}`;
64
+ const dispatcher = connConfig.allowInsecureTls
65
+ ? new Agent({ connect: { rejectUnauthorized: false } })
66
+ : undefined;
67
+ const wsOptions = dispatcher ? { dispatcher } : undefined;
68
+ const ws = new WebSocket(url, wsOptions);
69
+ setWorkclawWsConnection(key, ws);
70
+ // 在 onopen 之前调用,让 waitForConnect() 释放锁
71
+ onConnectingStarted?.(ws);
72
+ // 统一用 resolveThis/rejectThis,ws.onopen 调用 resolveThis 让 await Promise 完成
73
+ ws.onopen = () => {
74
+ log?.info?.(`Gateway WebSocket connected endpoint=${endpoint}`);
75
+ reconnectBackoff = 5000;
76
+ onReconnectSuccess?.();
77
+ resolveThis();
78
+ };
79
+ ws.onerror = (event) => {
80
+ log?.error?.(`Gateway WebSocket error: ${String(event?.message ?? event)}`);
81
+ rejectThis(new Error(String(event?.message ?? event)));
82
+ };
83
+ ws.onclose = (event) => {
84
+ const code = String(event?.code ?? "");
85
+ const reason = String(event?.reason ?? "");
86
+ log?.warn?.(`Gateway WebSocket closed code=${code} reason=${reason}`);
87
+ clearWorkclawWsConnection(key);
88
+ if (onClose) {
89
+ onClose();
90
+ }
91
+ else {
92
+ scheduleReconnect();
93
+ }
94
+ rejectThis(new Error(`WebSocket closed code=${code} reason=${reason}`));
95
+ };
96
+ ws.onmessage = (event) => {
97
+ const data = typeof event.data === "string" ? event.data : String(event.data ?? "");
98
+ log?.info?.(`Gateway WebSocket message received bytes=${data.length}`);
99
+ onMessage(data);
100
+ };
101
+ // 等待 ws.onopen 完成(resolveThis)或 ws.onerror/ws.onclose 失败(rejectThis)
102
+ await new Promise((resolve, reject) => {
103
+ const timeout = setTimeout(() => reject(new Error("websocket connection timeout")), 30000);
104
+ ws.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });
105
+ ws.addEventListener("error", (event) => { clearTimeout(timeout); reject(new Error(String(event?.message ?? event))); }, { once: true });
106
+ ws.addEventListener("close", (event) => { clearTimeout(timeout); reject(new Error(`websocket closed before ready code=${event?.code ?? ""} reason=${event?.reason ?? ""}`)); }, { once: true });
107
+ });
108
+ }
109
+ const scheduleReconnect = () => {
110
+ if (shouldStopReconnect) {
111
+ log?.info?.(`Reconnect: Stopped due to previous auth failure`);
112
+ return;
113
+ }
114
+ if (pendingReconnectTimer !== null) {
115
+ log?.info?.(`Reconnect: Already scheduled, skipping duplicate`);
116
+ return;
117
+ }
118
+ const jitter = Math.floor(Math.random() * 3000);
119
+ const delayMs = reconnectBackoff + jitter;
120
+ log?.info?.(`Reconnect: Scheduling in ${delayMs}ms (base=${reconnectBackoff} + jitter=${jitter}) key=${key}`);
121
+ pendingReconnectTimer = setTimeout(async () => {
122
+ pendingReconnectTimer = null;
123
+ // 清除旧的 pendingDoConnectPromise,确保 doConnect() 真正建立新连接
124
+ // 否则 doConnect() 会直接返回已 resolved 的旧 promise(第一次失败后 promise 没被清除)
125
+ pendingDoConnectPromise = null;
126
+ try {
127
+ log?.info?.(`Reconnect: Attempting... key=${key}`);
128
+ await doConnect();
129
+ log?.info?.(`Reconnect: Success`);
130
+ }
131
+ catch (err) {
132
+ const errorStr = String(err);
133
+ log?.error?.(`Reconnect: Failed: ${errorStr}`);
134
+ const willRetry = handleConnectError(errorStr);
135
+ if (!willRetry) {
136
+ // 永久失败,清除 pending promise
137
+ pendingDoConnectPromise = null;
138
+ }
139
+ }
140
+ }, delayMs);
141
+ };
142
+ /** 返回 true=会重试(promise 保持 pending),false=不重试(promise 应被 reject) */
143
+ function handleConnectError(errorStr) {
144
+ if (errorStr.includes("访问过于频繁")) {
145
+ log?.warn?.(`Reconnect: Rate limited, retrying with minimal backoff`);
146
+ if (pendingReconnectTimer !== null) {
147
+ clearTimeout(pendingReconnectTimer);
148
+ pendingReconnectTimer = null;
149
+ }
150
+ reconnectBackoff = 1000;
151
+ scheduleReconnect();
152
+ return true; // 会重试
153
+ }
154
+ const isAuthError = errorStr.includes('"errCode":2001') ||
155
+ errorStr.includes('"code":2001') ||
156
+ errorStr.includes("鉴权失败") ||
157
+ errorStr.includes("invalid credentials") ||
158
+ errorStr.includes("unauthorized");
159
+ if (isAuthError) {
160
+ log?.error?.(`Reconnect: Authentication failed, stopping`);
161
+ shouldStopReconnect = true;
162
+ if (pendingReconnectTimer !== null) {
163
+ clearTimeout(pendingReconnectTimer);
164
+ pendingReconnectTimer = null;
165
+ }
166
+ return false; // 不重试
167
+ }
168
+ // 其他错误:重试
169
+ return true;
170
+ }
171
+ /**
172
+ * 首次连接或重连:调用 doConnect(),返回其 promise
173
+ * 如果 doConnect() 因失败正在重试(promise 仍 pending),返回同一 promise
174
+ * 调用方 await 此方法,连接建立后 resolve,失败且不重试时 reject
175
+ */
176
+ async function connect() {
177
+ // 如果 doConnect() 正在进行中(失败后重试期间),返回同一 promise 让 caller 等待
178
+ if (pendingDoConnectPromise !== null) {
179
+ return pendingDoConnectPromise;
180
+ }
181
+ try {
182
+ return await doConnect();
183
+ }
184
+ catch (err) {
185
+ const errorStr = String(err);
186
+ log?.error?.(`Gateway connect failed: ${errorStr}`);
187
+ const willRetry = handleConnectError(errorStr);
188
+ if (!willRetry) {
189
+ // 不重试时,清除 pending promise,后续 connect() 可创建新的
190
+ pendingDoConnectPromise = null;
191
+ throw err;
192
+ }
193
+ // handleConnectError 返回 true 时,安排后续重试
194
+ // 注意:pendingDoConnectPromise 仍 pending,下次定时器触发时会清除它再真正重连
195
+ scheduleReconnect();
196
+ }
197
+ }
198
+ const stopReconnect = () => {
199
+ shouldStopReconnect = true;
200
+ if (pendingReconnectTimer !== null) {
201
+ clearTimeout(pendingReconnectTimer);
202
+ pendingReconnectTimer = null;
203
+ }
204
+ };
205
+ return { connect, scheduleReconnect, stopReconnect };
206
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Skills 事件处理器
3
+ * 处理云端下发的 skills 相关 EVENT 消息
4
+ * 通过 HTTP 回调返回结果
5
+ */
6
+ export interface SkillsEventData {
7
+ topic: string;
8
+ requestId: string;
9
+ callbackUrl: string;
10
+ authToken?: string;
11
+ data: any;
12
+ }
13
+ export interface CallbackResponse {
14
+ userId?: string;
15
+ agentId?: string;
16
+ agentIds?: string[];
17
+ appKey?: string;
18
+ dotype?: string;
19
+ doStatus?: boolean;
20
+ doErrorMsg?: string;
21
+ dataList?: any[];
22
+ }
23
+ /**
24
+ * 处理 skills 事件
25
+ */
26
+ export declare function handleSkillsEvent(eventData: SkillsEventData, token: string, baseUrl: string, appKey: string, log?: {
27
+ info?: (msg: string) => void;
28
+ error?: (msg: string) => void;
29
+ }): Promise<void>;