@clawchatsai/connector 0.1.14 → 0.1.16
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 +36 -61
- package/dist/plugin-config.d.ts +29 -0
- package/dist/plugin-config.js +1 -0
- package/package.json +5 -2
- package/server/config.js +0 -1
- package/server/controllers/messages.js +0 -8
- package/server/controllers/threads.js +18 -13
- package/server/controllers/workspaces.js +22 -8
- package/server/gateway-cleanup.js +24 -40
- package/server/gateway-sync.js +571 -0
- package/server/gateway.js +98 -16
- package/server/history-export.js +203 -0
- package/server/index.js +16 -8
- package/server/thread-move.js +47 -0
- package/dist/gateway-bridge.d.ts +0 -73
- package/dist/gateway-bridge.js +0 -255
- package/server/util/context.js +0 -49
package/dist/gateway-bridge.d.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* GatewayBridge — persistent WebSocket connection to the local OpenClaw gateway.
|
|
3
|
-
*
|
|
4
|
-
* Responsibilities:
|
|
5
|
-
* 1. Connect to the local gateway using token-only auth (loopback connections
|
|
6
|
-
* with valid token skip device identity entirely).
|
|
7
|
-
* 2. Broadcast incoming gateway events to all connected DataChannel clients
|
|
8
|
-
* via the 'gateway-event' EventEmitter event.
|
|
9
|
-
* 3. Reconnect with exponential backoff on disconnect.
|
|
10
|
-
*/
|
|
11
|
-
import { EventEmitter } from 'node:events';
|
|
12
|
-
export interface PluginConfig {
|
|
13
|
-
userId: string;
|
|
14
|
-
serverUrl: string;
|
|
15
|
-
apiKey: string;
|
|
16
|
-
gatewayId?: string;
|
|
17
|
-
gatewayToken?: string;
|
|
18
|
-
devicePrivateKey?: string;
|
|
19
|
-
schemaVersion: number;
|
|
20
|
-
installedAt: string;
|
|
21
|
-
totp?: {
|
|
22
|
-
secret: string;
|
|
23
|
-
algorithm: string;
|
|
24
|
-
digits: number;
|
|
25
|
-
period: number;
|
|
26
|
-
enabledAt: string;
|
|
27
|
-
};
|
|
28
|
-
google?: {
|
|
29
|
-
clientId: string;
|
|
30
|
-
authorizedSub: string;
|
|
31
|
-
authorizedEmail: string;
|
|
32
|
-
};
|
|
33
|
-
sessionSecret?: string;
|
|
34
|
-
backupCodeHashes?: string[];
|
|
35
|
-
totpPending?: {
|
|
36
|
-
secret: string;
|
|
37
|
-
generatedAt: string;
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
export interface BridgeConfig {
|
|
41
|
-
gatewayToken: string;
|
|
42
|
-
dataDir: string;
|
|
43
|
-
}
|
|
44
|
-
export declare class GatewayBridge extends EventEmitter {
|
|
45
|
-
private readonly gatewayUrl;
|
|
46
|
-
private readonly config;
|
|
47
|
-
private ws;
|
|
48
|
-
private _isConnected;
|
|
49
|
-
private destroyed;
|
|
50
|
-
private reconnectTimer;
|
|
51
|
-
private backoffMs;
|
|
52
|
-
constructor(gatewayUrl: string, config: BridgeConfig);
|
|
53
|
-
/**
|
|
54
|
-
* Initiate the connection. Resolves once the WebSocket has been opened
|
|
55
|
-
* (not necessarily after the gateway handshake completes — listen for
|
|
56
|
-
* the 'connected' event for that).
|
|
57
|
-
*/
|
|
58
|
-
connect(): Promise<void>;
|
|
59
|
-
/**
|
|
60
|
-
* Forward a message to the gateway (transparent proxy).
|
|
61
|
-
*/
|
|
62
|
-
send(data: string): void;
|
|
63
|
-
/**
|
|
64
|
-
* Permanently close the connection and cancel any pending reconnect.
|
|
65
|
-
*/
|
|
66
|
-
disconnect(): void;
|
|
67
|
-
get isConnected(): boolean;
|
|
68
|
-
private _openSocket;
|
|
69
|
-
private _handleMessage;
|
|
70
|
-
private _sendConnect;
|
|
71
|
-
private _scheduleReconnect;
|
|
72
|
-
private _cancelReconnect;
|
|
73
|
-
}
|
package/dist/gateway-bridge.js
DELETED
|
@@ -1,255 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* GatewayBridge — persistent WebSocket connection to the local OpenClaw gateway.
|
|
3
|
-
*
|
|
4
|
-
* Responsibilities:
|
|
5
|
-
* 1. Connect to the local gateway using token-only auth (loopback connections
|
|
6
|
-
* with valid token skip device identity entirely).
|
|
7
|
-
* 2. Broadcast incoming gateway events to all connected DataChannel clients
|
|
8
|
-
* via the 'gateway-event' EventEmitter event.
|
|
9
|
-
* 3. Reconnect with exponential backoff on disconnect.
|
|
10
|
-
*/
|
|
11
|
-
import { EventEmitter } from 'node:events';
|
|
12
|
-
import * as crypto from 'node:crypto';
|
|
13
|
-
import * as fs from 'node:fs';
|
|
14
|
-
import * as path from 'node:path';
|
|
15
|
-
import { WebSocket } from 'ws';
|
|
16
|
-
import { PLUGIN_VERSION } from './index.js';
|
|
17
|
-
// Reconnect backoff constants (milliseconds)
|
|
18
|
-
const BACKOFF_INITIAL_MS = 1_000;
|
|
19
|
-
const BACKOFF_MAX_MS = 30_000;
|
|
20
|
-
// Fixed client identity fields
|
|
21
|
-
const CLIENT_ID = 'gateway-client';
|
|
22
|
-
const CLIENT_MODE = 'backend';
|
|
23
|
-
const ROLE = 'operator';
|
|
24
|
-
const SCOPES = ['operator.read', 'operator.write', 'operator.admin'];
|
|
25
|
-
// ---------------------------------------------------------------------------
|
|
26
|
-
// Device Identity — ed25519 key generation + connect payload signing
|
|
27
|
-
// Required by OpenClaw ≥2.15 to prevent scope clearing on connect.
|
|
28
|
-
// ---------------------------------------------------------------------------
|
|
29
|
-
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
|
|
30
|
-
function _derivePublicKeyRaw(publicKeyPem) {
|
|
31
|
-
const spki = crypto.createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
|
|
32
|
-
if (spki.length === ED25519_SPKI_PREFIX.length + 32 &&
|
|
33
|
-
spki.subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX)) {
|
|
34
|
-
return spki.subarray(ED25519_SPKI_PREFIX.length);
|
|
35
|
-
}
|
|
36
|
-
return spki;
|
|
37
|
-
}
|
|
38
|
-
function _fingerprintPublicKey(publicKeyPem) {
|
|
39
|
-
return crypto.createHash('sha256').update(_derivePublicKeyRaw(publicKeyPem)).digest('hex');
|
|
40
|
-
}
|
|
41
|
-
function _base64UrlEncode(buf) {
|
|
42
|
-
return buf.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '');
|
|
43
|
-
}
|
|
44
|
-
function _loadOrCreateDeviceIdentity(identityPath) {
|
|
45
|
-
try {
|
|
46
|
-
if (fs.existsSync(identityPath)) {
|
|
47
|
-
const parsed = JSON.parse(fs.readFileSync(identityPath, 'utf8'));
|
|
48
|
-
if (parsed?.version === 1 && parsed.deviceId && parsed.publicKeyPem && parsed.privateKeyPem) {
|
|
49
|
-
return parsed;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
catch { /* regenerate */ }
|
|
54
|
-
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
|
|
55
|
-
const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
|
|
56
|
-
const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
|
57
|
-
const identity = {
|
|
58
|
-
version: 1,
|
|
59
|
-
deviceId: _fingerprintPublicKey(publicKeyPem),
|
|
60
|
-
publicKeyPem,
|
|
61
|
-
privateKeyPem,
|
|
62
|
-
createdAtMs: Date.now(),
|
|
63
|
-
};
|
|
64
|
-
fs.mkdirSync(path.dirname(identityPath), { recursive: true });
|
|
65
|
-
fs.writeFileSync(identityPath, JSON.stringify(identity, null, 2) + '\n', { mode: 0o600 });
|
|
66
|
-
return identity;
|
|
67
|
-
}
|
|
68
|
-
function _buildDeviceAuth(identity, params) {
|
|
69
|
-
const signedAt = Date.now();
|
|
70
|
-
const payload = [
|
|
71
|
-
'v2', identity.deviceId, params.clientId, params.clientMode,
|
|
72
|
-
params.role, params.scopes.join(','), String(signedAt),
|
|
73
|
-
params.token || '', params.nonce,
|
|
74
|
-
].join('|');
|
|
75
|
-
const privateKey = crypto.createPrivateKey(identity.privateKeyPem);
|
|
76
|
-
const signature = _base64UrlEncode(crypto.sign(null, Buffer.from(payload, 'utf8'), privateKey));
|
|
77
|
-
const publicKeyB64Url = _base64UrlEncode(_derivePublicKeyRaw(identity.publicKeyPem));
|
|
78
|
-
return { id: identity.deviceId, publicKey: publicKeyB64Url, signature, signedAt, nonce: params.nonce };
|
|
79
|
-
}
|
|
80
|
-
// ---------------------------------------------------------------------------
|
|
81
|
-
export class GatewayBridge extends EventEmitter {
|
|
82
|
-
gatewayUrl;
|
|
83
|
-
config;
|
|
84
|
-
ws = null;
|
|
85
|
-
_isConnected = false;
|
|
86
|
-
destroyed = false;
|
|
87
|
-
// Reconnect state
|
|
88
|
-
reconnectTimer = null;
|
|
89
|
-
backoffMs = BACKOFF_INITIAL_MS;
|
|
90
|
-
constructor(gatewayUrl, config) {
|
|
91
|
-
super();
|
|
92
|
-
this.gatewayUrl = gatewayUrl;
|
|
93
|
-
this.config = config;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Initiate the connection. Resolves once the WebSocket has been opened
|
|
97
|
-
* (not necessarily after the gateway handshake completes — listen for
|
|
98
|
-
* the 'connected' event for that).
|
|
99
|
-
*/
|
|
100
|
-
connect() {
|
|
101
|
-
return new Promise((resolve, reject) => {
|
|
102
|
-
if (this.destroyed) {
|
|
103
|
-
reject(new Error('GatewayBridge has been destroyed'));
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
this._openSocket(resolve, reject);
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Forward a message to the gateway (transparent proxy).
|
|
111
|
-
*/
|
|
112
|
-
send(data) {
|
|
113
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
114
|
-
console.warn('[GatewayBridge] send() called but WebSocket is not open');
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
this.ws.send(data);
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Permanently close the connection and cancel any pending reconnect.
|
|
121
|
-
*/
|
|
122
|
-
disconnect() {
|
|
123
|
-
this.destroyed = true;
|
|
124
|
-
this._cancelReconnect();
|
|
125
|
-
if (this.ws) {
|
|
126
|
-
this.ws.terminate();
|
|
127
|
-
this.ws = null;
|
|
128
|
-
}
|
|
129
|
-
this._isConnected = false;
|
|
130
|
-
}
|
|
131
|
-
get isConnected() {
|
|
132
|
-
return this._isConnected;
|
|
133
|
-
}
|
|
134
|
-
// ---------------------------------------------------------------------------
|
|
135
|
-
// Private helpers
|
|
136
|
-
// ---------------------------------------------------------------------------
|
|
137
|
-
_openSocket(resolveConnect = null, rejectConnect = null) {
|
|
138
|
-
console.log(`[GatewayBridge] Connecting to ${this.gatewayUrl}`);
|
|
139
|
-
const ws = new WebSocket(this.gatewayUrl);
|
|
140
|
-
this.ws = ws;
|
|
141
|
-
let resolved = false;
|
|
142
|
-
ws.on('open', () => {
|
|
143
|
-
console.log('[GatewayBridge] WebSocket opened');
|
|
144
|
-
if (!resolved && resolveConnect) {
|
|
145
|
-
resolved = true;
|
|
146
|
-
resolveConnect();
|
|
147
|
-
}
|
|
148
|
-
});
|
|
149
|
-
ws.on('error', (err) => {
|
|
150
|
-
console.error('[GatewayBridge] WebSocket error:', err.message);
|
|
151
|
-
if (!resolved && rejectConnect) {
|
|
152
|
-
resolved = true;
|
|
153
|
-
rejectConnect(err);
|
|
154
|
-
}
|
|
155
|
-
});
|
|
156
|
-
ws.on('message', (raw) => {
|
|
157
|
-
this._handleMessage(typeof raw === 'string' ? raw : raw.toString('utf8'));
|
|
158
|
-
});
|
|
159
|
-
ws.on('close', (code, reason) => {
|
|
160
|
-
console.log(`[GatewayBridge] WebSocket closed (code=${code} reason=${reason.toString('utf8') || '(none)'})`);
|
|
161
|
-
this._isConnected = false;
|
|
162
|
-
this.ws = null;
|
|
163
|
-
this.emit('disconnected');
|
|
164
|
-
if (!this.destroyed) {
|
|
165
|
-
this._scheduleReconnect();
|
|
166
|
-
}
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
_handleMessage(raw) {
|
|
170
|
-
// Always broadcast the raw event to connected DataChannel clients first.
|
|
171
|
-
this.emit('gateway-event', raw);
|
|
172
|
-
// Parse for handshake handling.
|
|
173
|
-
let msg;
|
|
174
|
-
try {
|
|
175
|
-
msg = JSON.parse(raw);
|
|
176
|
-
}
|
|
177
|
-
catch {
|
|
178
|
-
// Non-JSON frame — forward as-is, ignore for handshake purposes.
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
const type = msg['type'];
|
|
182
|
-
const event = msg['event'];
|
|
183
|
-
// connect.challenge → send signed connect request with device identity
|
|
184
|
-
if (type === 'event' && event === 'connect.challenge') {
|
|
185
|
-
const payload = msg['payload'];
|
|
186
|
-
const nonce = payload?.['nonce'] ?? '';
|
|
187
|
-
this._sendConnect(nonce);
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
// hello-ok → handshake complete
|
|
191
|
-
if (type === 'res') {
|
|
192
|
-
const payload = msg['payload'];
|
|
193
|
-
if (payload?.['type'] === 'hello-ok') {
|
|
194
|
-
console.log('[GatewayBridge] Gateway handshake complete');
|
|
195
|
-
this._isConnected = true;
|
|
196
|
-
// Reset backoff on successful connection.
|
|
197
|
-
this.backoffMs = BACKOFF_INITIAL_MS;
|
|
198
|
-
this.emit('connected');
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
_sendConnect(nonce) {
|
|
203
|
-
const identityPath = path.join(this.config.dataDir, 'device-identity.json');
|
|
204
|
-
const identity = _loadOrCreateDeviceIdentity(identityPath);
|
|
205
|
-
const device = _buildDeviceAuth(identity, {
|
|
206
|
-
clientId: CLIENT_ID,
|
|
207
|
-
clientMode: CLIENT_MODE,
|
|
208
|
-
role: ROLE,
|
|
209
|
-
scopes: SCOPES,
|
|
210
|
-
token: this.config.gatewayToken,
|
|
211
|
-
nonce,
|
|
212
|
-
});
|
|
213
|
-
this.send(JSON.stringify({
|
|
214
|
-
type: 'req',
|
|
215
|
-
id: 'gw-connect-1',
|
|
216
|
-
method: 'connect',
|
|
217
|
-
params: {
|
|
218
|
-
minProtocol: 3,
|
|
219
|
-
maxProtocol: 3,
|
|
220
|
-
client: {
|
|
221
|
-
id: CLIENT_ID,
|
|
222
|
-
version: PLUGIN_VERSION,
|
|
223
|
-
platform: 'node',
|
|
224
|
-
mode: CLIENT_MODE,
|
|
225
|
-
},
|
|
226
|
-
role: ROLE,
|
|
227
|
-
scopes: SCOPES,
|
|
228
|
-
device,
|
|
229
|
-
auth: { token: this.config.gatewayToken },
|
|
230
|
-
caps: ['tool-events'],
|
|
231
|
-
},
|
|
232
|
-
}));
|
|
233
|
-
}
|
|
234
|
-
_scheduleReconnect() {
|
|
235
|
-
if (this.destroyed)
|
|
236
|
-
return;
|
|
237
|
-
if (this.reconnectTimer !== null)
|
|
238
|
-
return; // already scheduled
|
|
239
|
-
console.log(`[GatewayBridge] Reconnecting in ${this.backoffMs}ms`);
|
|
240
|
-
this.reconnectTimer = setTimeout(() => {
|
|
241
|
-
this.reconnectTimer = null;
|
|
242
|
-
if (!this.destroyed) {
|
|
243
|
-
this._openSocket();
|
|
244
|
-
}
|
|
245
|
-
}, this.backoffMs);
|
|
246
|
-
// Exponential backoff: double each time, cap at BACKOFF_MAX_MS.
|
|
247
|
-
this.backoffMs = Math.min(this.backoffMs * 2, BACKOFF_MAX_MS);
|
|
248
|
-
}
|
|
249
|
-
_cancelReconnect() {
|
|
250
|
-
if (this.reconnectTimer !== null) {
|
|
251
|
-
clearTimeout(this.reconnectTimer);
|
|
252
|
-
this.reconnectTimer = null;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
package/server/util/context.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { MAX_PREAMBLE_CHARS, getSessionsDirForAgent } from '../config.js';
|
|
4
|
-
|
|
5
|
-
export function buildContextPreamble(db, threadId, lastSessionId, sessionKey) {
|
|
6
|
-
let summary = null;
|
|
7
|
-
let method = 'raw';
|
|
8
|
-
|
|
9
|
-
if (lastSessionId) {
|
|
10
|
-
const agentMatch = (sessionKey || '').match(/^agent:([^:]+):/);
|
|
11
|
-
const sessionsDir = getSessionsDirForAgent(agentMatch?.[1]);
|
|
12
|
-
try {
|
|
13
|
-
const lines = fs.readFileSync(path.join(sessionsDir, `${lastSessionId}.jsonl`), 'utf8').split('\n').filter(Boolean);
|
|
14
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
15
|
-
try {
|
|
16
|
-
const entry = JSON.parse(lines[i]);
|
|
17
|
-
if (entry.type === 'compaction' && entry.summary) { summary = entry.summary; method = 'compaction'; break; }
|
|
18
|
-
} catch { /* skip malformed */ }
|
|
19
|
-
}
|
|
20
|
-
} catch { /* file not found */ }
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
let preamble = '';
|
|
24
|
-
if (method === 'compaction' && summary) {
|
|
25
|
-
preamble += "[CONTEXT RECOVERY — This thread's agent session was reset. Below is a summary of the previous conversation followed by recent messages to restore context.]\n\n";
|
|
26
|
-
preamble += '[CONVERSATION SUMMARY]\n' + summary + '\n\n';
|
|
27
|
-
const msgs = db.prepare('SELECT role, content, timestamp FROM messages WHERE thread_id = ? ORDER BY timestamp DESC LIMIT 10').all(threadId).reverse();
|
|
28
|
-
if (msgs.length) {
|
|
29
|
-
preamble += '[RECENT MESSAGES]\n';
|
|
30
|
-
for (const m of msgs) {
|
|
31
|
-
const ts = new Date(m.timestamp).toISOString().replace('T', ' ').slice(0, 16);
|
|
32
|
-
preamble += `${m.role.charAt(0).toUpperCase() + m.role.slice(1)} (${ts}): ${m.content}\n`;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
} else {
|
|
36
|
-
preamble += "[CONTEXT RECOVERY — This thread's agent session was reset. Below are recent messages from the previous conversation to restore context.]\n\n";
|
|
37
|
-
const msgs = db.prepare('SELECT role, content, timestamp FROM messages WHERE thread_id = ? ORDER BY timestamp DESC LIMIT 25').all(threadId).reverse();
|
|
38
|
-
if (msgs.length) {
|
|
39
|
-
preamble += '[PREVIOUS MESSAGES]\n';
|
|
40
|
-
for (const m of msgs) {
|
|
41
|
-
const ts = new Date(m.timestamp).toISOString().replace('T', ' ').slice(0, 16);
|
|
42
|
-
preamble += `${m.role.charAt(0).toUpperCase() + m.role.slice(1)} (${ts}): ${m.content}\n`;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
if (preamble.length > MAX_PREAMBLE_CHARS) preamble = preamble.slice(preamble.length - MAX_PREAMBLE_CHARS);
|
|
48
|
-
return { preamble, method };
|
|
49
|
-
}
|