@agentchatme/openclaw 0.8.0 → 0.8.1

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.
@@ -159,7 +159,7 @@ function classifyNetworkError(err) {
159
159
  }
160
160
 
161
161
  // src/version.ts
162
- var PACKAGE_VERSION = "0.8.0";
162
+ var PACKAGE_VERSION = "0.8.1";
163
163
 
164
164
  // src/client-identity.ts
165
165
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -1782,7 +1782,6 @@ function transition(state, event) {
1782
1782
  return { kind: "CONNECTING", attempt: event.attempt, startedAt: event.now };
1783
1783
  }
1784
1784
  if (event.type === "DRAIN_REQUESTED") return { kind: "CLOSED" };
1785
- if (event.type === "AUTH_REJECTED") return { kind: "AUTH_FAIL", reason: event.reason };
1786
1785
  return state;
1787
1786
  }
1788
1787
  case "CONNECTING": {
@@ -1828,6 +1827,9 @@ function transition(state, event) {
1828
1827
  return state;
1829
1828
  }
1830
1829
  case "AUTH_FAIL": {
1830
+ if (event.type === "CONNECT") {
1831
+ return { kind: "CONNECTING", attempt: event.attempt, startedAt: event.now };
1832
+ }
1831
1833
  if (event.type === "RECONFIGURED") return { kind: "DISCONNECTED" };
1832
1834
  if (event.type === "DRAIN_REQUESTED") return { kind: "CLOSED" };
1833
1835
  return state;
@@ -1838,15 +1840,25 @@ function transition(state, event) {
1838
1840
  }
1839
1841
  }
1840
1842
  function isTerminal(state) {
1841
- return state.kind === "CLOSED" || state.kind === "AUTH_FAIL";
1843
+ return state.kind === "CLOSED";
1842
1844
  }
1843
1845
 
1844
1846
  // src/ws-client.ts
1845
1847
  var HELLO_ACK_TIMEOUT_MS = 4e3;
1846
- var RECONNECT_HARD_CAP_ATTEMPTS = 60;
1848
+ var RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS = 60;
1849
+ var RECONNECT_LONG_OUTAGE_BACKOFF_MS = 5 * 6e4;
1850
+ var AUTH_RETRY_INTERVAL_MS = 75e4;
1847
1851
  var MAX_FRAME_BYTES = 2 * 1024 * 1024;
1848
1852
  var HELLO_CAPABILITIES = ["ack"];
1849
- var AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401, 4403]);
1853
+ var UNAMBIGUOUS_AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4401, 4403]);
1854
+ var AMBIGUOUS_AUTH_CLOSE_CODE = 1008;
1855
+ var SERVER_AUTH_CLOSE_REASONS = ["invalid token"];
1856
+ function isHandshakeRejection(code, reason) {
1857
+ if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true;
1858
+ if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false;
1859
+ const lower = reason.toLowerCase();
1860
+ return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known));
1861
+ }
1850
1862
  var AgentchatWsClient = class {
1851
1863
  config;
1852
1864
  logger;
@@ -1862,6 +1874,15 @@ var AgentchatWsClient = class {
1862
1874
  ws = null;
1863
1875
  attempt = 0;
1864
1876
  _ackNegotiated = false;
1877
+ /**
1878
+ * Set by `closeSocket()` before it closes the current socket, read and
1879
+ * cleared by `handleClose()`. A close this client asked for says nothing
1880
+ * about the server, whatever code travelled with it.
1881
+ */
1882
+ closeInitiatedLocally = false;
1883
+ /** One error line per long outage / per run of rejected keys, then debug. */
1884
+ longOutageAnnounced = false;
1885
+ authFailAnnounced = false;
1865
1886
  helloAckTimer = null;
1866
1887
  pingTimer = null;
1867
1888
  pongTimer = null;
@@ -1901,21 +1922,14 @@ var AgentchatWsClient = class {
1901
1922
  return this._ackNegotiated;
1902
1923
  }
1903
1924
  /**
1904
- * Kick off connection. No-op if already connecting, authenticating, or
1905
- * ready. Throws on `AUTH_FAIL` — the caller must call `reconfigured()`
1906
- * after rotating the API key before retrying.
1925
+ * Kick off connection. No-op if already connecting, authenticating, ready,
1926
+ * or waiting out a backoff / auth retry. Throws only on `CLOSED`.
1907
1927
  */
1908
1928
  start() {
1909
- if (this.state.kind === "AUTH_FAIL") {
1910
- throw new AgentChatChannelError(
1911
- "terminal-auth",
1912
- "cannot start: channel is in AUTH_FAIL \u2014 rotate api key and call reconfigured()"
1913
- );
1914
- }
1915
1929
  if (this.state.kind === "CLOSED") {
1916
1930
  throw new Error("cannot start: client is closed. Create a new instance.");
1917
1931
  }
1918
- if (this.state.kind !== "DISCONNECTED") {
1932
+ if (this.state.kind !== "DISCONNECTED" || this.reconnectTimer) {
1919
1933
  return;
1920
1934
  }
1921
1935
  this.openSocket(1);
@@ -1948,13 +1962,15 @@ var AgentchatWsClient = class {
1948
1962
  }
1949
1963
  }
1950
1964
  /**
1951
- * Signal that operator has rotated the API key. Transitions from
1952
- * AUTH_FAIL back to DISCONNECTED; the next `start()` call will attempt
1953
- * a fresh HELLO with the current config.
1965
+ * Signal that the operator has rotated the API key: leave AUTH_FAIL and
1966
+ * retry now instead of waiting for the slow retry timer. A no-op in every
1967
+ * other state (the client is already connecting or connected).
1954
1968
  */
1955
1969
  reconfigured() {
1956
1970
  if (this.state.kind !== "AUTH_FAIL") return;
1971
+ this.clearReconnectTimer();
1957
1972
  this.applyEvent({ type: "RECONFIGURED" });
1973
+ this.openSocket(1);
1958
1974
  }
1959
1975
  on(event, handler) {
1960
1976
  this.listeners[event].add(handler);
@@ -1964,7 +1980,9 @@ var AgentchatWsClient = class {
1964
1980
  }
1965
1981
  // ─── Internals: socket lifecycle ─────────────────────────────────────
1966
1982
  openSocket(attempt) {
1983
+ if (this.state.kind === "CLOSED") return;
1967
1984
  this.attempt = attempt;
1985
+ this.closeInitiatedLocally = false;
1968
1986
  const now = this.now();
1969
1987
  this.applyEvent({ type: "CONNECT", now, attempt });
1970
1988
  const url = `${this.config.apiBase.replace(/^http/, "ws")}/v1/ws`;
@@ -2036,7 +2054,7 @@ var AgentchatWsClient = class {
2036
2054
  this.emitError(
2037
2055
  new AgentChatChannelError("retry-transient", "hello ack timeout")
2038
2056
  );
2039
- this.closeSocket(1008, "hello ack timeout");
2057
+ this.closeSocket(1001, "hello ack timeout");
2040
2058
  }, HELLO_ACK_TIMEOUT_MS);
2041
2059
  }
2042
2060
  handleMessage(data, isBinary) {
@@ -2123,26 +2141,43 @@ var AgentchatWsClient = class {
2123
2141
  this.logger.info({ ackNegotiated: this._ackNegotiated }, "hello.ok");
2124
2142
  this.applyEvent({ type: "HELLO_OK", now });
2125
2143
  this.attempt = 0;
2144
+ this.longOutageAnnounced = false;
2145
+ this.authFailAnnounced = false;
2126
2146
  this.startHeartbeat();
2127
2147
  this.emit("authenticated", now);
2128
2148
  }
2149
+ /** The server answered HELLO with a rejection frame (not a close). */
2129
2150
  handleAuthRejected(reason) {
2130
2151
  if (this.helloAckTimer) {
2131
2152
  this._clearTimeout(this.helloAckTimer);
2132
2153
  this.helloAckTimer = null;
2133
2154
  }
2134
- this.logger.error({ reason }, "auth rejected \u2014 moving to AUTH_FAIL");
2155
+ this.enterAuthFail(reason);
2156
+ this.closeSocket(1e3, "auth rejected");
2157
+ }
2158
+ /**
2159
+ * The server rejected this key. AUTH_FAIL is not the end: retry a fresh
2160
+ * HELLO every `AUTH_RETRY_INTERVAL_MS` (jittered). The first rejection in a
2161
+ * run logs at error so an operator sees it; the following ones at debug.
2162
+ */
2163
+ enterAuthFail(reason) {
2164
+ this.logger[this.authFailAnnounced ? "debug" : "error"](
2165
+ { reason, retryIntervalMs: AUTH_RETRY_INTERVAL_MS, attempt: this.attempt },
2166
+ "auth rejected \u2014 retrying slowly until the key is accepted again"
2167
+ );
2168
+ this.authFailAnnounced = true;
2135
2169
  this.applyEvent({ type: "AUTH_REJECTED", reason });
2136
2170
  this.emitError(
2137
2171
  new AgentChatChannelError("terminal-auth", `auth rejected: ${reason}`)
2138
2172
  );
2139
- this.closeSocket(1008, "auth rejected");
2173
+ this.scheduleAuthRetry();
2140
2174
  }
2141
2175
  handleClose(code, reason) {
2142
- this.now();
2143
2176
  const wasAuthenticating = this.state.kind === "AUTHENTICATING";
2144
2177
  const wasDraining = this.state.kind === "DRAINING";
2145
- const authClass = AUTH_CLOSE_CODES.has(code);
2178
+ const ours = this.closeInitiatedLocally;
2179
+ this.closeInitiatedLocally = false;
2180
+ const serverAuthClose = !ours && isHandshakeRejection(code, reason);
2146
2181
  this.stopHeartbeat();
2147
2182
  if (this.helloAckTimer) {
2148
2183
  this._clearTimeout(this.helloAckTimer);
@@ -2150,19 +2185,17 @@ var AgentchatWsClient = class {
2150
2185
  }
2151
2186
  this.ws = null;
2152
2187
  this._ackNegotiated = false;
2153
- if (this.state.kind === "CLOSED") {
2188
+ const kind = this.state.kind;
2189
+ if (kind === "CLOSED") {
2154
2190
  this.logger.debug({ code, reason }, "socket closed after CLOSED \u2014 no-op");
2155
2191
  return;
2156
2192
  }
2157
- if (authClass && wasAuthenticating) {
2158
- this.applyEvent({ type: "AUTH_REJECTED", reason: `close ${code}: ${reason}` });
2159
- this.emitError(
2160
- new AgentChatChannelError(
2161
- "terminal-auth",
2162
- `socket closed with auth code ${code}: ${reason}`
2163
- )
2164
- );
2165
- this.emit("closed");
2193
+ if (kind === "AUTH_FAIL") {
2194
+ this.logger.debug({ code, reason }, "socket closed after AUTH_FAIL \u2014 retry already scheduled");
2195
+ return;
2196
+ }
2197
+ if (serverAuthClose && wasAuthenticating) {
2198
+ this.enterAuthFail(`close ${code}: ${reason}`);
2166
2199
  return;
2167
2200
  }
2168
2201
  this.applyEvent({ type: "SOCKET_CLOSED", code, reason });
@@ -2171,13 +2204,14 @@ var AgentchatWsClient = class {
2171
2204
  return;
2172
2205
  }
2173
2206
  this.logger.info(
2174
- { code, reason, attempt: this.attempt },
2207
+ { code, reason, ours, attempt: this.attempt },
2175
2208
  "socket closed \u2014 scheduling reconnect"
2176
2209
  );
2177
2210
  this.scheduleReconnect(`close-${code}`);
2178
2211
  }
2179
2212
  closeSocket(code, reason) {
2180
2213
  if (!this.ws) return;
2214
+ this.closeInitiatedLocally = true;
2181
2215
  try {
2182
2216
  this.ws.close(code, reason);
2183
2217
  } catch {
@@ -2237,14 +2271,15 @@ var AgentchatWsClient = class {
2237
2271
  if (this.state.kind === "CLOSED" || this.state.kind === "AUTH_FAIL") return;
2238
2272
  if (this.reconnectTimer) return;
2239
2273
  const nextAttempt = this.attempt + 1;
2240
- if (nextAttempt > RECONNECT_HARD_CAP_ATTEMPTS) {
2241
- const msg = `reconnect hard cap (${RECONNECT_HARD_CAP_ATTEMPTS}) reached`;
2242
- this.logger.error({ attempt: nextAttempt }, msg);
2243
- this.applyEvent({ type: "AUTH_REJECTED", reason: msg });
2244
- this.emitError(
2245
- new AgentChatChannelError("terminal-auth", msg)
2274
+ if (nextAttempt > RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {
2275
+ this.longOutageAnnounced = true;
2276
+ this.logger.error(
2277
+ {
2278
+ attempt: nextAttempt,
2279
+ maxBackoffMs: Math.max(this.config.reconnect.maxBackoffMs, RECONNECT_LONG_OUTAGE_BACKOFF_MS)
2280
+ },
2281
+ `still reconnecting after ${RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS} attempts \u2014 backing off further, not giving up`
2246
2282
  );
2247
- return;
2248
2283
  }
2249
2284
  const delay = this.computeReconnectDelay(nextAttempt);
2250
2285
  this.metrics.incReconnect({ reason });
@@ -2257,13 +2292,41 @@ var AgentchatWsClient = class {
2257
2292
  this.openSocket(nextAttempt);
2258
2293
  }, delay);
2259
2294
  }
2295
+ /** AUTH_FAIL's own cadence: a fresh HELLO every AUTH_RETRY_INTERVAL_MS, jittered. */
2296
+ scheduleAuthRetry() {
2297
+ if (this.state.kind !== "AUTH_FAIL") return;
2298
+ this.clearReconnectTimer();
2299
+ const nextAttempt = this.attempt + 1;
2300
+ const delay = this.jittered(AUTH_RETRY_INTERVAL_MS);
2301
+ this.metrics.incReconnect({ reason: "auth-retry" });
2302
+ this.logger.debug({ attempt: nextAttempt, delayMs: delay }, "scheduling auth retry");
2303
+ this.reconnectTimer = this._setTimeout(() => {
2304
+ this.reconnectTimer = null;
2305
+ this.openSocket(nextAttempt);
2306
+ }, delay);
2307
+ }
2308
+ clearReconnectTimer() {
2309
+ if (this.reconnectTimer) {
2310
+ this._clearTimeout(this.reconnectTimer);
2311
+ this.reconnectTimer = null;
2312
+ }
2313
+ }
2260
2314
  computeReconnectDelay(attempt) {
2261
- const { initialBackoffMs, maxBackoffMs, jitterRatio } = this.config.reconnect;
2315
+ const { initialBackoffMs, maxBackoffMs } = this.config.reconnect;
2262
2316
  const reconnectCount = Math.max(1, attempt - 1);
2263
2317
  const exp = initialBackoffMs * Math.pow(2, Math.min(reconnectCount - 1, 20));
2264
- const capped = Math.min(exp, maxBackoffMs);
2318
+ const cap = attempt > RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS ? Math.max(maxBackoffMs, RECONNECT_LONG_OUTAGE_BACKOFF_MS) : maxBackoffMs;
2319
+ return this.jittered(Math.min(exp, cap));
2320
+ }
2321
+ /**
2322
+ * Symmetric ±`jitterRatio`. Thundering-herd-safe: a fleet that all drops
2323
+ * at the same instant re-enters the connect queue spread across
2324
+ * ms * [1-jitterRatio, 1+jitterRatio].
2325
+ */
2326
+ jittered(ms) {
2327
+ const { jitterRatio } = this.config.reconnect;
2265
2328
  const jitter = 1 - jitterRatio + this.random() * 2 * jitterRatio;
2266
- return Math.max(0, Math.floor(capped * jitter));
2329
+ return Math.max(0, Math.floor(ms * jitter));
2267
2330
  }
2268
2331
  // ─── Internals: drain ────────────────────────────────────────────────
2269
2332
  scheduleDrainDeadline(deadline) {
@@ -2306,6 +2369,9 @@ var AgentchatWsClient = class {
2306
2369
  return;
2307
2370
  }
2308
2371
  this.state = next;
2372
+ if (next.kind === "CLOSED") {
2373
+ this.clearReconnectTimer();
2374
+ }
2309
2375
  this.metrics.setConnectionState(next.kind);
2310
2376
  this.logger.info(
2311
2377
  { from: prev.kind, to: next.kind, event: event.type },
@@ -3416,6 +3482,7 @@ var agentchatGatewayAdapter = {
3416
3482
  gateFailOpen: readEnv_js.readReplyGateFailOpenFromEnv(),
3417
3483
  ...gateTimeoutMs !== void 0 ? { gateTimeoutMs } : {}
3418
3484
  });
3485
+ let authBlocked = false;
3419
3486
  return {
3420
3487
  invoker,
3421
3488
  handlers: {
@@ -3427,16 +3494,39 @@ var agentchatGatewayAdapter = {
3427
3494
  void catchUpInvites(ctx.accountId, config, invoker, logger);
3428
3495
  },
3429
3496
  onError: (err) => {
3430
- ctx.log?.warn?.(`[agentchat:${ctx.accountId}] runtime error: ${err.message} (class=${err.class_})`);
3497
+ const level = err.class_ === "terminal-auth" && authBlocked ? "debug" : "warn";
3498
+ ctx.log?.[level]?.(`[agentchat:${ctx.accountId}] runtime error: ${err.message} (class=${err.class_})`);
3431
3499
  },
3432
3500
  onStateChanged: (next) => {
3433
- const running = next.kind !== "CLOSED" && next.kind !== "AUTH_FAIL";
3434
- const connected = next.kind === "READY" || next.kind === "DEGRADED";
3435
- const lifecycle = next.kind === "READY" || next.kind === "DEGRADED" ? "ready" : next.kind === "AUTH_FAIL" ? "blocked" : next.kind === "CLOSED" ? "stopped" : runtime.getHealth().counters.knocks > 0 ? "recovering" : "starting";
3436
- ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running, connected, statusState: statusStateFor(next.kind) }, lifecycle));
3437
3501
  if (next.kind === "AUTH_FAIL") {
3438
- ctx.log?.error?.(`[agentchat:${ctx.accountId}] AUTH_FAIL \u2014 rotate the key or re-run openclaw channels add agentchat`);
3502
+ if (authBlocked) {
3503
+ ctx.log?.debug?.(`[agentchat:${ctx.accountId}] still AUTH_FAIL (${next.reason}) \u2014 next retry in 10\u201315 min`);
3504
+ return;
3505
+ }
3506
+ authBlocked = true;
3507
+ ctx.log?.error?.(
3508
+ `[agentchat:${ctx.accountId}] AUTH_FAIL (${next.reason}) \u2014 the server rejected the key; retrying every 10\u201315 min; rotate the key or re-run openclaw channels add agentchat`
3509
+ );
3510
+ ctx.setStatus(
3511
+ withLifecycle(
3512
+ { ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: `AUTH_FAIL: ${next.reason}` } },
3513
+ "blocked"
3514
+ )
3515
+ );
3516
+ return;
3517
+ }
3518
+ if (authBlocked && next.kind !== "READY" && next.kind !== "CLOSED") {
3519
+ ctx.log?.debug?.(`[agentchat:${ctx.accountId}] AUTH_FAIL retry: ${next.kind.toLowerCase()}`);
3520
+ return;
3521
+ }
3522
+ if (authBlocked) {
3523
+ authBlocked = false;
3524
+ if (next.kind === "READY") ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again \u2014 AUTH_FAIL cleared`);
3439
3525
  }
3526
+ const running = next.kind !== "CLOSED";
3527
+ const connected = next.kind === "READY" || next.kind === "DEGRADED";
3528
+ const lifecycle = next.kind === "READY" || next.kind === "DEGRADED" ? "ready" : next.kind === "CLOSED" ? "stopped" : runtime.getHealth().counters.knocks > 0 ? "recovering" : "starting";
3529
+ ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running, connected, statusState: statusStateFor(next.kind) }, lifecycle));
3440
3530
  }
3441
3531
  }
3442
3532
  };