@clawling/clawchat-plugin-openclaw 2026.5.12-39 → 2026.5.13-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.
- package/dist/index.js +7 -0
- package/dist/setup-entry.js +31 -1
- package/dist/src/api-client.js +164 -26
- package/dist/src/client.js +4 -1
- package/dist/src/config-compat.js +120 -0
- package/dist/src/inbound.js +21 -4
- package/dist/src/login.runtime.js +4 -0
- package/dist/src/outbound.js +43 -8
- package/dist/src/plugin-report.js +36 -0
- package/dist/src/protocol-types.js +2 -0
- package/dist/src/refresh-manager.js +278 -0
- package/dist/src/reply-dispatcher.js +5 -2
- package/dist/src/runtime.js +597 -30
- package/dist/src/storage.js +81 -5
- package/dist/src/ws-alignment.js +69 -1
- package/dist/src/ws-client.js +55 -5
- package/index.ts +7 -0
- package/openclaw.plugin.json +7 -0
- package/package.json +1 -1
- package/setup-entry.ts +51 -1
- package/src/api-client.ts +210 -31
- package/src/client.ts +12 -1
- package/src/config-compat.ts +154 -0
- package/src/inbound.ts +24 -5
- package/src/login.runtime.ts +4 -0
- package/src/outbound.ts +47 -9
- package/src/plugin-report.ts +53 -0
- package/src/protocol-types.ts +34 -2
- package/src/refresh-manager.ts +371 -0
- package/src/reply-dispatcher.ts +5 -2
- package/src/runtime.ts +679 -27
- package/src/storage.ts +124 -4
- package/src/ws-alignment.ts +99 -1
- package/src/ws-client.ts +51 -5
- package/dist/src/buffered-stream.js +0 -177
- package/dist/src/streaming.js +0 -65
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { authRefresh, decodeJwtExp, } from "./api-client.js";
|
|
2
|
+
/**
|
|
3
|
+
* §A–§D — ClawChat token refresh + auto-logout orchestration for the OpenClaw
|
|
4
|
+
* plugin.
|
|
5
|
+
*
|
|
6
|
+
* The manager is the single owner of:
|
|
7
|
+
* - single-flight dedupe (§A.3): concurrent callers (proactive timer, reactive
|
|
8
|
+
* REST 401, reactive WS hello-fail) await one in-flight refresh;
|
|
9
|
+
* - the rejected-token latch (§A.3): never re-attempt for the same access token
|
|
10
|
+
* until it actually changes;
|
|
11
|
+
* - the minimum interval (§A.3): a reconnect storm cannot become a refresh storm;
|
|
12
|
+
* - the proactive `setTimeout` timer (§A.1), armed from the live token's `exp`;
|
|
13
|
+
* - the persist→swap ordering (§0): the rotated pair is persisted to BOTH stores
|
|
14
|
+
* BEFORE the in-memory token is swapped, then the WS is reconnected (§D).
|
|
15
|
+
*
|
|
16
|
+
* It is deliberately decoupled from the runtime via a small port object so it is
|
|
17
|
+
* unit-testable without a live WS / config / SQLite.
|
|
18
|
+
*/
|
|
19
|
+
const MINUTE_MS = 60_000;
|
|
20
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
21
|
+
/** §A.3 — floor between refresh attempts of the same token. */
|
|
22
|
+
export const MIN_REFRESH_INTERVAL_MS = 30_000;
|
|
23
|
+
/** §A.1 — proactive jitter (±5min). */
|
|
24
|
+
export const PROACTIVE_JITTER_MS = 5 * MINUTE_MS;
|
|
25
|
+
/** §A.0 — fallback access-token TTL when `exp` is unparseable. */
|
|
26
|
+
export const ACCESS_TOKEN_TTL_MS = 24 * HOUR_MS;
|
|
27
|
+
/**
|
|
28
|
+
* §A.0/§A.1 — compute the absolute epoch-ms at which to proactively refresh.
|
|
29
|
+
* `refresh_at = exp - max(30min, min(2h, 0.25 * (exp - iat)))` plus jitter.
|
|
30
|
+
* `iatMs` is the token issue time; when unknown we approximate the lifetime as
|
|
31
|
+
* the full TTL so the lead time clamps to 2h for a 24h token.
|
|
32
|
+
*/
|
|
33
|
+
export function computeProactiveRefreshAtMs(params) {
|
|
34
|
+
const lifetimeMs = typeof params.iatMs === "number" && Number.isFinite(params.iatMs)
|
|
35
|
+
? params.expMs - params.iatMs
|
|
36
|
+
: ACCESS_TOKEN_TTL_MS;
|
|
37
|
+
const lead = Math.max(30 * MINUTE_MS, Math.min(2 * HOUR_MS, 0.25 * lifetimeMs));
|
|
38
|
+
return params.expMs - lead + (params.jitterMs ?? 0);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* §A.0 — derive the access token's expiry (epoch ms). Prefer the JWT `exp`;
|
|
42
|
+
* fall back to `activatedAt + 24h` when the token has no parseable `exp`.
|
|
43
|
+
*/
|
|
44
|
+
export function resolveAccessTokenExpiryMs(token, activatedAtMs) {
|
|
45
|
+
const exp = decodeJwtExp(token);
|
|
46
|
+
if (exp != null)
|
|
47
|
+
return exp * 1000;
|
|
48
|
+
if (activatedAtMs != null)
|
|
49
|
+
return activatedAtMs + ACCESS_TOKEN_TTL_MS;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
export class RefreshManager {
|
|
53
|
+
ports;
|
|
54
|
+
inFlight = null;
|
|
55
|
+
/** §A.3 — the access token a refresh was last attempted for. */
|
|
56
|
+
rejectedToken = null;
|
|
57
|
+
/** §A.3 — epoch-ms of the last refresh attempt (any token). */
|
|
58
|
+
lastAttemptAt = 0;
|
|
59
|
+
proactiveTimer = null;
|
|
60
|
+
stopped = false;
|
|
61
|
+
constructor(ports) {
|
|
62
|
+
this.ports = ports;
|
|
63
|
+
}
|
|
64
|
+
now() {
|
|
65
|
+
return (this.ports.now ?? Date.now)();
|
|
66
|
+
}
|
|
67
|
+
setTimer(cb, ms) {
|
|
68
|
+
return (this.ports.setTimer ?? setTimeout)(cb, ms);
|
|
69
|
+
}
|
|
70
|
+
clearTimer(handle) {
|
|
71
|
+
(this.ports.clearTimer ?? clearTimeout)(handle);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* §A.3 — run a single-flight refresh. Concurrent callers receive the same
|
|
75
|
+
* in-flight promise. Honors the rejected-token latch and the min-interval.
|
|
76
|
+
*/
|
|
77
|
+
refresh(reason) {
|
|
78
|
+
if (this.stopped)
|
|
79
|
+
return Promise.resolve({ kind: "skipped", reason: "in-flight" });
|
|
80
|
+
if (this.inFlight) {
|
|
81
|
+
this.ports.log?.debug?.(`clawchat-plugin-openclaw refresh deduped onto in-flight (${reason})`);
|
|
82
|
+
return this.inFlight;
|
|
83
|
+
}
|
|
84
|
+
const accessToken = this.ports.getAccessToken();
|
|
85
|
+
// §A.3 rejected-token latch: don't re-attempt for an unchanged dead token.
|
|
86
|
+
if (this.rejectedToken !== null && this.rejectedToken === accessToken) {
|
|
87
|
+
this.ports.log?.debug?.(`clawchat-plugin-openclaw refresh skipped rejected-latch (${reason})`);
|
|
88
|
+
return Promise.resolve({ kind: "skipped", reason: "rejected-latch" });
|
|
89
|
+
}
|
|
90
|
+
// §A.3 min-interval floor.
|
|
91
|
+
const sinceLast = this.now() - this.lastAttemptAt;
|
|
92
|
+
if (this.lastAttemptAt !== 0 && sinceLast < MIN_REFRESH_INTERVAL_MS) {
|
|
93
|
+
this.ports.log?.debug?.(`clawchat-plugin-openclaw refresh skipped min-interval (${reason}) sinceLast=${sinceLast}ms`);
|
|
94
|
+
return Promise.resolve({ kind: "skipped", reason: "min-interval" });
|
|
95
|
+
}
|
|
96
|
+
const refreshToken = this.ports.getRefreshToken();
|
|
97
|
+
if (!refreshToken || !refreshToken.trim()) {
|
|
98
|
+
return Promise.resolve({ kind: "skipped", reason: "no-refresh-token" });
|
|
99
|
+
}
|
|
100
|
+
this.lastAttemptAt = this.now();
|
|
101
|
+
const promise = this.runRefresh(accessToken, refreshToken, reason).finally(() => {
|
|
102
|
+
this.inFlight = null;
|
|
103
|
+
});
|
|
104
|
+
this.inFlight = promise;
|
|
105
|
+
return promise;
|
|
106
|
+
}
|
|
107
|
+
async runRefresh(accessToken, refreshToken, reason) {
|
|
108
|
+
this.ports.log?.info?.(`clawchat-plugin-openclaw refresh attempt (${reason})`);
|
|
109
|
+
let result;
|
|
110
|
+
try {
|
|
111
|
+
result = await authRefresh({ baseUrl: this.ports.baseUrl, ...(this.ports.fetchImpl ? { fetchImpl: this.ports.fetchImpl } : {}) }, { refreshToken, deviceId: this.ports.deviceId });
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
+
return { kind: "transient", message };
|
|
116
|
+
}
|
|
117
|
+
if (result.kind === "success") {
|
|
118
|
+
// §0 rotation hazard — persist FIRST, swap SECOND. If persistence REJECTS
|
|
119
|
+
// (a store/config write failed), DO NOT swap the in-memory token: a
|
|
120
|
+
// sqlite-sourced agent must not keep a now-dead refresh token in its row
|
|
121
|
+
// while running on the rotated token. Treat as transient so the WS stays
|
|
122
|
+
// in backoff with the CURRENT tokens and the next attempt retries. The
|
|
123
|
+
// server already rotated, so the next attempt may return `code:10003`
|
|
124
|
+
// (which escalates to permanent per §B) — that is the accepted hazard, not
|
|
125
|
+
// a silent brick.
|
|
126
|
+
try {
|
|
127
|
+
await this.ports.persistRotatedTokens({
|
|
128
|
+
accessToken: result.accessToken,
|
|
129
|
+
refreshToken: result.refreshToken,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
134
|
+
this.ports.log?.error?.(`clawchat-plugin-openclaw refresh persistence failed; not swapping in-memory token: ${message}`);
|
|
135
|
+
return { kind: "transient", message };
|
|
136
|
+
}
|
|
137
|
+
this.ports.swapInMemoryTokens({
|
|
138
|
+
accessToken: result.accessToken,
|
|
139
|
+
refreshToken: result.refreshToken,
|
|
140
|
+
});
|
|
141
|
+
// Clear the latch; the access token has actually changed.
|
|
142
|
+
this.rejectedToken = null;
|
|
143
|
+
this.ports.log?.info?.("clawchat-plugin-openclaw refresh success (token rotated)");
|
|
144
|
+
return { kind: "success", accessToken: result.accessToken, refreshToken: result.refreshToken };
|
|
145
|
+
}
|
|
146
|
+
if (result.kind === "permanent") {
|
|
147
|
+
// §A.3 — latch the dead token so reconnect storms don't re-fire refresh.
|
|
148
|
+
this.rejectedToken = accessToken;
|
|
149
|
+
this.ports.log?.error?.(`clawchat-plugin-openclaw refresh permanent failure code=${result.code}: ${result.message}`);
|
|
150
|
+
await this.ports.onPermanentFailure({ code: result.code, message: result.message });
|
|
151
|
+
return { kind: "permanent", code: result.code, message: result.message };
|
|
152
|
+
}
|
|
153
|
+
// Transient — never auto-logout; the old refresh token is still valid.
|
|
154
|
+
this.ports.log?.info?.(`clawchat-plugin-openclaw refresh transient failure: ${result.message}`);
|
|
155
|
+
return { kind: "transient", message: result.message };
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* §A.1 — (re)arm the proactive timer from the live access token's `exp`.
|
|
159
|
+
* Called when a connection becomes ready and after every successful refresh.
|
|
160
|
+
*/
|
|
161
|
+
armProactiveTimer(activatedAtMs) {
|
|
162
|
+
if (this.stopped)
|
|
163
|
+
return;
|
|
164
|
+
this.disarmProactiveTimer();
|
|
165
|
+
const token = this.ports.getAccessToken();
|
|
166
|
+
const expMs = resolveAccessTokenExpiryMs(token, activatedAtMs);
|
|
167
|
+
if (expMs == null) {
|
|
168
|
+
this.ports.log?.debug?.("clawchat-plugin-openclaw proactive timer not armed (no expiry)");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const iat = decodeJwtIat(token);
|
|
172
|
+
const jitterMs = (this.ports.jitter ?? defaultJitter)();
|
|
173
|
+
const refreshAtMs = computeProactiveRefreshAtMs({
|
|
174
|
+
expMs,
|
|
175
|
+
iatMs: iat != null ? iat * 1000 : null,
|
|
176
|
+
nowMs: this.now(),
|
|
177
|
+
jitterMs,
|
|
178
|
+
});
|
|
179
|
+
const delayMs = Math.max(0, refreshAtMs - this.now());
|
|
180
|
+
this.ports.log?.debug?.(`clawchat-plugin-openclaw proactive timer armed delayMs=${delayMs}`);
|
|
181
|
+
this.proactiveTimer = this.setTimer(() => {
|
|
182
|
+
this.proactiveTimer = null;
|
|
183
|
+
void this.runProactiveRefresh();
|
|
184
|
+
}, delayMs);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* §A.1/§D — the proactive-timer body. Runs the single-flight refresh and, on
|
|
188
|
+
* success, hands the rotated token to the runtime's `onProactiveRefreshed` port
|
|
189
|
+
* so the live WS is closed and reconnected with the new token (the in-memory
|
|
190
|
+
* swap alone does NOT reach the running socket, which captured the old token at
|
|
191
|
+
* `connect` time). Transient/skipped outcomes leave the WS untouched — the next
|
|
192
|
+
* proactive arm (or a reactive hello-fail) handles it.
|
|
193
|
+
*/
|
|
194
|
+
async runProactiveRefresh() {
|
|
195
|
+
const outcome = await this.refresh("proactive-timer");
|
|
196
|
+
if (this.stopped)
|
|
197
|
+
return;
|
|
198
|
+
if (outcome.kind !== "success")
|
|
199
|
+
return;
|
|
200
|
+
if (this.ports.onProactiveRefreshed) {
|
|
201
|
+
try {
|
|
202
|
+
await this.ports.onProactiveRefreshed({
|
|
203
|
+
accessToken: outcome.accessToken,
|
|
204
|
+
refreshToken: outcome.refreshToken,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
this.ports.log?.error?.(`clawchat-plugin-openclaw proactive reconnect hook failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
disarmProactiveTimer() {
|
|
213
|
+
if (this.proactiveTimer != null) {
|
|
214
|
+
this.clearTimer(this.proactiveTimer);
|
|
215
|
+
this.proactiveTimer = null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* §A.4 — true when the stored access token is past or within the proactive
|
|
220
|
+
* margin of expiry, so the caller should refresh BEFORE the first connect.
|
|
221
|
+
*/
|
|
222
|
+
isNearExpiry(activatedAtMs) {
|
|
223
|
+
const token = this.ports.getAccessToken();
|
|
224
|
+
const expMs = resolveAccessTokenExpiryMs(token, activatedAtMs);
|
|
225
|
+
if (expMs == null)
|
|
226
|
+
return false;
|
|
227
|
+
const iat = decodeJwtIat(token);
|
|
228
|
+
const refreshAtMs = computeProactiveRefreshAtMs({
|
|
229
|
+
expMs,
|
|
230
|
+
iatMs: iat != null ? iat * 1000 : null,
|
|
231
|
+
nowMs: this.now(),
|
|
232
|
+
jitterMs: 0,
|
|
233
|
+
});
|
|
234
|
+
return this.now() >= refreshAtMs;
|
|
235
|
+
}
|
|
236
|
+
/** Stop the manager — clears the proactive timer; no further refreshes arm. */
|
|
237
|
+
stop() {
|
|
238
|
+
this.stopped = true;
|
|
239
|
+
this.disarmProactiveTimer();
|
|
240
|
+
}
|
|
241
|
+
/** Test/inspection seam — the latched (rejected) access token, if any. */
|
|
242
|
+
getRejectedToken() {
|
|
243
|
+
return this.rejectedToken;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* §A.3/§A.4 — export the single-flight guard state so it can be carried across
|
|
247
|
+
* a gateway re-enter (a refresh-driven reconnect builds a fresh manager; without
|
|
248
|
+
* restoring this state the rejected-token latch + min-interval would reset and
|
|
249
|
+
* the guards would not bound a cross-reconnect loop).
|
|
250
|
+
*/
|
|
251
|
+
exportState() {
|
|
252
|
+
return { rejectedToken: this.rejectedToken, lastAttemptAt: this.lastAttemptAt };
|
|
253
|
+
}
|
|
254
|
+
/** §A.3/§A.4 — restore guard state from a prior manager (see `exportState`). */
|
|
255
|
+
restoreState(state) {
|
|
256
|
+
this.rejectedToken = state.rejectedToken;
|
|
257
|
+
this.lastAttemptAt = state.lastAttemptAt;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function decodeJwtIat(token) {
|
|
261
|
+
if (typeof token !== "string")
|
|
262
|
+
return null;
|
|
263
|
+
const segments = token.split(".");
|
|
264
|
+
if (segments.length < 2 || !segments[1])
|
|
265
|
+
return null;
|
|
266
|
+
try {
|
|
267
|
+
const json = Buffer.from(segments[1], "base64url").toString("utf8");
|
|
268
|
+
const parsed = JSON.parse(json);
|
|
269
|
+
const iat = parsed?.iat;
|
|
270
|
+
return typeof iat === "number" && Number.isFinite(iat) ? iat : null;
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function defaultJitter() {
|
|
277
|
+
return (Math.random() * 2 - 1) * PROACTIVE_JITTER_MS;
|
|
278
|
+
}
|
|
@@ -3,7 +3,7 @@ import { resolveOutboundMediaUrls } from "openclaw/plugin-sdk/reply-payload";
|
|
|
3
3
|
import { createOpenclawClawlingApiClient } from "./api-client.js";
|
|
4
4
|
import { effectiveOutputVisibility, } from "./config.js";
|
|
5
5
|
import { uploadOutboundMedia } from "./media-runtime.js";
|
|
6
|
-
import { sendOpenclawClawlingText, } from "./outbound.js";
|
|
6
|
+
import { mintMessageId, sendOpenclawClawlingText, } from "./outbound.js";
|
|
7
7
|
import { isClawChatNoopResponseText } from "./profile-prompt.js";
|
|
8
8
|
import { consumeTerminalClawChatSend } from "./terminal-send.js";
|
|
9
9
|
import { openclawLlmContextDebug } from "./llm-context-debug.js";
|
|
@@ -416,7 +416,10 @@ export function createOpenclawClawlingReplyDispatcher(options) {
|
|
|
416
416
|
}
|
|
417
417
|
return merged;
|
|
418
418
|
};
|
|
419
|
-
|
|
419
|
+
// §7.6 (binding): client-supplied message_id MUST be `msg-` + a 26-char
|
|
420
|
+
// Crockford base32 ULID. Use the shared conformant minter — do not invent a
|
|
421
|
+
// different scheme (planned msghub Phase-4 validation will reject it).
|
|
422
|
+
const mintStaticMessageId = () => mintMessageId();
|
|
420
423
|
const emitTyping = (isTyping) => {
|
|
421
424
|
if (!isTyping && !typingActive)
|
|
422
425
|
return;
|