@clawchatsai/connector 0.1.43 → 0.1.45
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/README.md +29 -2
- package/dist/index.js +162 -56
- package/package.json +1 -1
- package/server/config.js +15 -3
- package/server/controllers/agents.js +2 -2
- package/server/gateway.js +5 -1
- package/server/index.js +1 -0
- package/server/peer/sharing.js +39 -3
- package/server/peer/sharing.test.js +35 -0
- package/server/team.js +14 -1
- package/server/team.test.js +27 -0
package/README.md
CHANGED
|
@@ -31,12 +31,39 @@ The signaling server only facilitates the handshake. After step 4, it is out of
|
|
|
31
31
|
|
|
32
32
|
## Installation
|
|
33
33
|
|
|
34
|
+
Requires OpenClaw 2026.9.7 or newer on the machine that runs your gateway.
|
|
35
|
+
|
|
34
36
|
```bash
|
|
35
37
|
openclaw plugins install @clawchatsai/connector
|
|
36
|
-
openclaw gateway restart
|
|
37
38
|
```
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
The gateway loads the plugin right away; no restart is needed. OpenClaw warns that the package is
|
|
41
|
+
outside ClawHub review — answer `y` to continue (pass `--force` in scripts).
|
|
42
|
+
|
|
43
|
+
Install while your gateway is running. If it is not, OpenClaw installs locally instead and asks you to
|
|
44
|
+
re-run the same command with `--accept-capabilities` after reviewing what the plugin declares.
|
|
45
|
+
|
|
46
|
+
Then connect it to your ClawChats account:
|
|
47
|
+
|
|
48
|
+
1. Open [app.clawchats.ai](https://app.clawchats.ai), sign in, and choose **Connect a gateway**.
|
|
49
|
+
2. Run the `openclaw clawchats setup <token>` command it shows, on the gateway machine.
|
|
50
|
+
3. Check the result: `openclaw clawchats status` — Gateway and Signaling should say `connected`.
|
|
51
|
+
|
|
52
|
+
Until step 2 is done the plugin idles and `openclaw clawchats status` says it is waiting for setup.
|
|
53
|
+
|
|
54
|
+
### Supported platforms
|
|
55
|
+
|
|
56
|
+
A WebRTC binary is bundled for Linux (x64, arm64, arm; glibc and musl), macOS (Intel and Apple
|
|
57
|
+
silicon) and Windows (x64, arm64). Nothing is compiled during install.
|
|
58
|
+
|
|
59
|
+
### Troubleshooting
|
|
60
|
+
|
|
61
|
+
| Symptom | What to do |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `openclaw clawchats status` says *waiting for setup* | Finish step 2 above. |
|
|
64
|
+
| Status says *failed to start* | The message names the cause and the fix. After fixing, run `openclaw plugins reload connector`. |
|
|
65
|
+
| Signaling shows `disconnected` | The gateway machine cannot reach the ClawChats server (offline, proxy or firewall). It keeps retrying; see `journalctl --user -u openclaw-gateway -g clawchats`. |
|
|
66
|
+
| Gateway on a custom port, profile or state directory | Supported: the plugin follows the gateway's config, `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH`. |
|
|
40
67
|
|
|
41
68
|
## Architecture
|
|
42
69
|
|
package/dist/index.js
CHANGED
|
@@ -62,8 +62,21 @@ class BrowserClientMap extends Map {
|
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
const connectedClients = new BrowserClientMap();
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
const DEFAULT_GATEWAY_PORT = 18789;
|
|
66
|
+
/**
|
|
67
|
+
* The local gateway's WebSocket URL (the app's gateway client and Desktop tunnels):
|
|
68
|
+
* GATEWAY_WS_URL, else the port in the gateway config (a gateway on a custom port),
|
|
69
|
+
* else the default port.
|
|
70
|
+
*/
|
|
71
|
+
function resolveGatewayWsUrl(gatewayConfig) {
|
|
72
|
+
if (process.env.GATEWAY_WS_URL)
|
|
73
|
+
return process.env.GATEWAY_WS_URL;
|
|
74
|
+
const gw = gatewayConfig?.['gateway'];
|
|
75
|
+
const port = Number(gw?.['port']) || DEFAULT_GATEWAY_PORT;
|
|
76
|
+
return `ws://127.0.0.1:${port}`;
|
|
77
|
+
}
|
|
78
|
+
/** Set when the service starts; the Desktop tunnels read it. */
|
|
79
|
+
let GATEWAY_WS_URL = resolveGatewayWsUrl();
|
|
67
80
|
/** Open Desktop tunnels per browser connection (server/desktop-tunnel.js); a viewer uses one or two. */
|
|
68
81
|
const desktopTunnels = new Map();
|
|
69
82
|
const MAX_TUNNELS_PER_CONNECTION = 8;
|
|
@@ -76,6 +89,10 @@ let signaling = null;
|
|
|
76
89
|
let webrtcPeer = null;
|
|
77
90
|
let healthServer = null;
|
|
78
91
|
let _stopRequested = false;
|
|
92
|
+
let _serviceState = 'stopped';
|
|
93
|
+
let _serviceError = '';
|
|
94
|
+
/** The background startup, so stop() can wait for it to unwind. */
|
|
95
|
+
let _startupRun = null;
|
|
79
96
|
// Gateway sharing: links this gateway is opening to another gateway (it offers), by share.
|
|
80
97
|
const PEER_OPEN_TIMEOUT_MS = 30_000;
|
|
81
98
|
const peerOpens = new Map();
|
|
@@ -107,7 +124,15 @@ function settlePeerOpen(shareId, outcome) {
|
|
|
107
124
|
// ---------------------------------------------------------------------------
|
|
108
125
|
// Config helpers
|
|
109
126
|
// ---------------------------------------------------------------------------
|
|
110
|
-
|
|
127
|
+
/** The gateway's state directory: OPENCLAW_STATE_DIR (profiles, custom installs), else ~/.openclaw. */
|
|
128
|
+
function stateRoot() {
|
|
129
|
+
return process.env.OPENCLAW_STATE_DIR || path.join(os.homedir(), '.openclaw');
|
|
130
|
+
}
|
|
131
|
+
/** The gateway's config file: OPENCLAW_CONFIG_PATH, else <state>/openclaw.json. */
|
|
132
|
+
function gatewayConfigPath() {
|
|
133
|
+
return process.env.OPENCLAW_CONFIG_PATH || path.join(stateRoot(), 'openclaw.json');
|
|
134
|
+
}
|
|
135
|
+
const CONFIG_DIR = path.join(stateRoot(), 'clawchats');
|
|
111
136
|
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
112
137
|
const RUNTIME_FILE = path.join(CONFIG_DIR, 'runtime.json');
|
|
113
138
|
function loadConfig() {
|
|
@@ -195,8 +220,8 @@ async function ensureNativeModules(ctx) {
|
|
|
195
220
|
const require = createRequire(import.meta.url);
|
|
196
221
|
const ndcRoot = resolvePackageRoot(require, 'node-datachannel');
|
|
197
222
|
if (!ndcRoot) {
|
|
198
|
-
|
|
199
|
-
|
|
223
|
+
throw new Error(`the WebRTC library (node-datachannel) is missing from this install. ` +
|
|
224
|
+
`Reinstall the plugin: openclaw plugins install @clawchatsai/connector --force`);
|
|
200
225
|
}
|
|
201
226
|
const targetPath = path.join(ndcRoot, 'build', 'Release', 'node_datachannel.node');
|
|
202
227
|
// Already built — nothing to do.
|
|
@@ -206,10 +231,9 @@ async function ensureNativeModules(ctx) {
|
|
|
206
231
|
const prebuildKey = getPrebuildKey();
|
|
207
232
|
const prebuiltPath = path.join(pluginDir, 'prebuilds', prebuildKey, 'node_datachannel.node');
|
|
208
233
|
if (!fs.existsSync(prebuiltPath)) {
|
|
209
|
-
|
|
210
|
-
`
|
|
211
|
-
`cd
|
|
212
|
-
return;
|
|
234
|
+
throw new Error(`no prebuilt WebRTC binary for ${prebuildKey} (Node ${process.version}). ` +
|
|
235
|
+
`Build it from source (needs cmake, make and a C++ compiler): ` +
|
|
236
|
+
`cd ${pluginDir} && npm rebuild node-datachannel`);
|
|
213
237
|
}
|
|
214
238
|
ctx.logger.info(`[clawchats] Installing node-datachannel prebuilt for ${prebuildKey}...`);
|
|
215
239
|
try {
|
|
@@ -218,19 +242,71 @@ async function ensureNativeModules(ctx) {
|
|
|
218
242
|
ctx.logger.info('[clawchats] node-datachannel ready.');
|
|
219
243
|
}
|
|
220
244
|
catch (e) {
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
` To fix manually:\n mkdir -p ${path.dirname(targetPath)}\n` +
|
|
226
|
-
` cp ${prebuiltPath} ${targetPath}`);
|
|
245
|
+
// Say what to do: the import fails moments later with an opaque
|
|
246
|
+
// "Cannot find module '../../../build/Release/node_datachannel.node'".
|
|
247
|
+
throw new Error(`could not install the WebRTC binary (${e.message}). To fix manually: ` +
|
|
248
|
+
`mkdir -p ${path.dirname(targetPath)} && cp ${prebuiltPath} ${targetPath}`);
|
|
227
249
|
}
|
|
228
250
|
}
|
|
251
|
+
/**
|
|
252
|
+
* Service entry point. Returns at once: the gateway kills a service whose start() has not
|
|
253
|
+
* settled within ~5 s, and the real startup can take far longer (waiting for the user to run
|
|
254
|
+
* setup, loading the native WebRTC module on a slow box, the signaling handshake).
|
|
255
|
+
*/
|
|
229
256
|
async function startClawChats(ctx, api) {
|
|
230
257
|
_stopRequested = false;
|
|
258
|
+
_serviceError = '';
|
|
259
|
+
_startupRun = runClawChats(ctx, api).catch((e) => {
|
|
260
|
+
_serviceState = 'failed';
|
|
261
|
+
_serviceError = e?.message || String(e);
|
|
262
|
+
ctx.logger.error(`ClawChats failed to start: ${_serviceError}`);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The local status endpoint `openclaw clawchats status` queries. Started first thing, so status
|
|
267
|
+
* can say "waiting for setup" or why startup failed, not just "offline".
|
|
268
|
+
*/
|
|
269
|
+
function startHealthEndpoint(ctx) {
|
|
270
|
+
if (healthServer)
|
|
271
|
+
return;
|
|
272
|
+
healthServer = http.createServer((req, res) => {
|
|
273
|
+
if (req.url === '/status' && req.method === 'GET') {
|
|
274
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
275
|
+
res.end(JSON.stringify({
|
|
276
|
+
version: PLUGIN_VERSION,
|
|
277
|
+
pid: process.pid,
|
|
278
|
+
uptime: process.uptime(),
|
|
279
|
+
state: _serviceState,
|
|
280
|
+
error: _serviceError || undefined,
|
|
281
|
+
gateway: { connected: app?.gatewayClient?.connected ?? false },
|
|
282
|
+
signaling: { connected: signaling?.isConnected ?? false },
|
|
283
|
+
clients: { active: connectedClients.size },
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
res.writeHead(404);
|
|
288
|
+
res.end();
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
healthServer.listen(0, '127.0.0.1', () => {
|
|
292
|
+
const addr = healthServer.address();
|
|
293
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
294
|
+
fs.writeFileSync(RUNTIME_FILE, JSON.stringify({
|
|
295
|
+
pid: process.pid,
|
|
296
|
+
healthPort: addr.port,
|
|
297
|
+
startedAt: new Date().toISOString(),
|
|
298
|
+
}, null, 2), { mode: 0o600 });
|
|
299
|
+
ctx.logger.info(`Health endpoint on 127.0.0.1:${addr.port}`);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const SETUP_HINT = 'ClawChats is installed but not set up yet. Next step: open https://app.clawchats.ai, sign in, ' +
|
|
303
|
+
'and follow "Connect a gateway" — it gives you a command like `openclaw clawchats setup <token>` to run here.';
|
|
304
|
+
async function runClawChats(ctx, api) {
|
|
305
|
+
startHealthEndpoint(ctx);
|
|
231
306
|
let config = loadConfig();
|
|
232
307
|
if (!config) {
|
|
233
|
-
|
|
308
|
+
_serviceState = 'waiting-setup';
|
|
309
|
+
ctx.logger.info(SETUP_HINT);
|
|
234
310
|
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
235
311
|
while (!config && !_stopRequested) {
|
|
236
312
|
await new Promise(r => setTimeout(r, 2000));
|
|
@@ -240,16 +316,19 @@ async function startClawChats(ctx, api) {
|
|
|
240
316
|
return;
|
|
241
317
|
ctx.logger.info('Setup detected — connecting to ClawChats...');
|
|
242
318
|
}
|
|
319
|
+
_serviceState = 'starting';
|
|
320
|
+
GATEWAY_WS_URL = resolveGatewayWsUrl(api.config);
|
|
243
321
|
// 1. Resolve gateway token: runtime API → config file → error
|
|
244
322
|
const gwCfg = api.config;
|
|
245
323
|
const gwAuth = gwCfg?.['gateway']?.['auth'];
|
|
246
324
|
const gatewayToken = gwAuth?.['token'] || config.gatewayToken || '';
|
|
247
325
|
if (!gatewayToken) {
|
|
248
|
-
|
|
249
|
-
return;
|
|
326
|
+
throw new Error('no gateway token available (the gateway config has no gateway.auth.token). Re-run: openclaw clawchats setup <token>');
|
|
250
327
|
}
|
|
251
328
|
// 3. Ensure native modules are built (OpenClaw installs with --ignore-scripts)
|
|
252
329
|
await ensureNativeModules(ctx);
|
|
330
|
+
if (_stopRequested)
|
|
331
|
+
return;
|
|
253
332
|
// 4. Import server.js and create app instance with plugin paths
|
|
254
333
|
const dataDir = path.join(ctx.stateDir, 'clawchats', 'data');
|
|
255
334
|
// Dynamic import of server.js (plain JS, no type declarations)
|
|
@@ -272,7 +351,7 @@ async function startClawChats(ctx, api) {
|
|
|
272
351
|
openaiApiKey: (() => {
|
|
273
352
|
// Resolve OpenAI API key: openclaw config → env var
|
|
274
353
|
try {
|
|
275
|
-
const oc = JSON.parse(fs.readFileSync(
|
|
354
|
+
const oc = JSON.parse(fs.readFileSync(gatewayConfigPath(), 'utf8'));
|
|
276
355
|
const fromConfig = oc?.skills?.entries?.['openai-whisper-api']?.apiKey;
|
|
277
356
|
if (fromConfig)
|
|
278
357
|
return fromConfig;
|
|
@@ -341,6 +420,10 @@ async function startClawChats(ctx, api) {
|
|
|
341
420
|
});
|
|
342
421
|
// 6. Initialize WebRTC peer manager (lazy import — native module must be built first)
|
|
343
422
|
const { WebRTCPeerManager } = await import('./webrtc-peer.js');
|
|
423
|
+
if (_stopRequested) {
|
|
424
|
+
teardownRuntime();
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
344
427
|
webrtcPeer = new WebRTCPeerManager();
|
|
345
428
|
webrtcPeer.on('datachannel', (dc, connectionId) => {
|
|
346
429
|
ctx.logger.info(`Browser connected via DataChannel: ${connectionId}`);
|
|
@@ -440,40 +523,39 @@ async function startClawChats(ctx, api) {
|
|
|
440
523
|
webrtcPeer.on('ice-candidate-local', (data) => {
|
|
441
524
|
signaling?.sendIceCandidate(data.connectionId, data.candidate);
|
|
442
525
|
});
|
|
443
|
-
|
|
444
|
-
//
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
}
|
|
461
|
-
});
|
|
462
|
-
healthServer.listen(0, '127.0.0.1', () => {
|
|
463
|
-
const addr = healthServer.address();
|
|
464
|
-
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
465
|
-
fs.writeFileSync(RUNTIME_FILE, JSON.stringify({
|
|
466
|
-
pid: process.pid,
|
|
467
|
-
healthPort: addr.port,
|
|
468
|
-
startedAt: new Date().toISOString(),
|
|
469
|
-
}, null, 2), { mode: 0o600 });
|
|
470
|
-
ctx.logger.info(`Health endpoint on 127.0.0.1:${addr.port}`);
|
|
471
|
-
});
|
|
526
|
+
// The first connection can fail (offline, firewall, server restart); the client keeps retrying with
|
|
527
|
+
// backoff on its own, so that is a state to report, not a failed start.
|
|
528
|
+
try {
|
|
529
|
+
await signaling.connect();
|
|
530
|
+
}
|
|
531
|
+
catch (e) {
|
|
532
|
+
ctx.logger.warn(`Can't reach the ClawChats server yet (${e.message}); retrying in the background.`);
|
|
533
|
+
}
|
|
534
|
+
if (_stopRequested) {
|
|
535
|
+
teardownRuntime();
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (_stopRequested) {
|
|
539
|
+
teardownRuntime();
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
_serviceState = 'running';
|
|
472
543
|
ctx.logger.info('ClawChats service started');
|
|
473
544
|
}
|
|
474
545
|
async function stopClawChats(ctx) {
|
|
475
546
|
_stopRequested = true;
|
|
547
|
+
_serviceState = 'stopped';
|
|
476
548
|
ctx.logger.info('ClawChats service stopping...');
|
|
549
|
+
// Let a startup that is mid-flight notice the stop and unwind; never wait long for it.
|
|
550
|
+
if (_startupRun) {
|
|
551
|
+
await Promise.race([_startupRun, new Promise(r => { setTimeout(r, 3000).unref?.(); })]);
|
|
552
|
+
_startupRun = null;
|
|
553
|
+
}
|
|
554
|
+
teardownRuntime();
|
|
555
|
+
ctx.logger.info('ClawChats service stopped');
|
|
556
|
+
}
|
|
557
|
+
/** Releases everything a started service holds. Safe to call more than once. */
|
|
558
|
+
function teardownRuntime() {
|
|
477
559
|
// 0. Tear down health endpoint
|
|
478
560
|
if (healthServer) {
|
|
479
561
|
healthServer.close();
|
|
@@ -502,7 +584,6 @@ async function stopClawChats(ctx) {
|
|
|
502
584
|
// 4. Close SQLite databases
|
|
503
585
|
app?.shutdown();
|
|
504
586
|
app = null;
|
|
505
|
-
ctx.logger.info('ClawChats service stopped');
|
|
506
587
|
}
|
|
507
588
|
// ---------------------------------------------------------------------------
|
|
508
589
|
// ---------------------------------------------------------------------------
|
|
@@ -847,6 +928,14 @@ function broadcastToClients(msg) {
|
|
|
847
928
|
function formatStatus() {
|
|
848
929
|
const lines = [];
|
|
849
930
|
lines.push(`ClawChats Plugin v${PLUGIN_VERSION}`);
|
|
931
|
+
if (_serviceState === 'waiting-setup') {
|
|
932
|
+
lines.push(SETUP_HINT);
|
|
933
|
+
return lines.join('\n');
|
|
934
|
+
}
|
|
935
|
+
if (_serviceState === 'failed') {
|
|
936
|
+
lines.push(`Failed to start: ${_serviceError || 'unknown error'}`);
|
|
937
|
+
return lines.join('\n');
|
|
938
|
+
}
|
|
850
939
|
lines.push(`Gateway: ${app?.gatewayClient?.connected ? 'connected' : 'disconnected'}`);
|
|
851
940
|
lines.push(`Signaling: ${signaling?.isConnected ? 'connected' : 'disconnected'}`);
|
|
852
941
|
lines.push(`Clients: ${connectedClients.size}`);
|
|
@@ -878,7 +967,7 @@ async function handleSetup(token, options = {}) {
|
|
|
878
967
|
// Read gateway token from OpenClaw config
|
|
879
968
|
let gatewayToken = '';
|
|
880
969
|
try {
|
|
881
|
-
const openclawConfigPath =
|
|
970
|
+
const openclawConfigPath = gatewayConfigPath();
|
|
882
971
|
const openclawConfig = JSON.parse(fs.readFileSync(openclawConfigPath, 'utf8'));
|
|
883
972
|
gatewayToken = openclawConfig.gateway?.auth?.token || openclawConfig.auth?.token || openclawConfig.token || '';
|
|
884
973
|
}
|
|
@@ -1214,7 +1303,7 @@ async function handleReauth() {
|
|
|
1214
1303
|
}
|
|
1215
1304
|
async function handleExportHistory(api, mode) {
|
|
1216
1305
|
if (mode !== undefined && mode !== 'check') {
|
|
1217
|
-
console.error(`Unknown option "${mode}". Use:
|
|
1306
|
+
console.error(`Unknown option "${mode}". Use: openclaw clawchats export-history [check]`);
|
|
1218
1307
|
process.exitCode = 1;
|
|
1219
1308
|
return;
|
|
1220
1309
|
}
|
|
@@ -1222,11 +1311,11 @@ async function handleExportHistory(api, mode) {
|
|
|
1222
1311
|
const gw = gwCfg?.['gateway'];
|
|
1223
1312
|
const token = gw?.['auth']?.['token'] || loadConfig()?.gatewayToken || '';
|
|
1224
1313
|
if (!token) {
|
|
1225
|
-
console.error('No gateway token found. Is ClawChats set up? (
|
|
1314
|
+
console.error('No gateway token found. Is ClawChats set up? (openclaw clawchats setup <token>)');
|
|
1226
1315
|
process.exitCode = 1;
|
|
1227
1316
|
return;
|
|
1228
1317
|
}
|
|
1229
|
-
const port = gw?.['port'] ||
|
|
1318
|
+
const port = gw?.['port'] || DEFAULT_GATEWAY_PORT;
|
|
1230
1319
|
// @ts-expect-error — server/ is plain JS with no .d.ts
|
|
1231
1320
|
const serverModule = await import('../server/history-export.js');
|
|
1232
1321
|
try {
|
|
@@ -1258,12 +1347,16 @@ async function handleImportDates() {
|
|
|
1258
1347
|
async function handleStatus() {
|
|
1259
1348
|
// CLI runs in a separate process — module-level vars are null here.
|
|
1260
1349
|
// Query the live service via the health endpoint instead.
|
|
1350
|
+
const configured = loadConfig() !== null;
|
|
1261
1351
|
let runtime;
|
|
1262
1352
|
try {
|
|
1263
1353
|
runtime = JSON.parse(fs.readFileSync(RUNTIME_FILE, 'utf8'));
|
|
1264
1354
|
}
|
|
1265
1355
|
catch {
|
|
1266
|
-
console.log('ClawChats:
|
|
1356
|
+
console.log('ClawChats: the service is not running.');
|
|
1357
|
+
console.log(configured
|
|
1358
|
+
? ' The gateway starts it with the plugin. Check: openclaw plugins inspect connector — then openclaw plugins reload connector'
|
|
1359
|
+
: ` ${SETUP_HINT}`);
|
|
1267
1360
|
return;
|
|
1268
1361
|
}
|
|
1269
1362
|
// Verify PID is alive
|
|
@@ -1271,7 +1364,7 @@ async function handleStatus() {
|
|
|
1271
1364
|
process.kill(runtime.pid, 0);
|
|
1272
1365
|
}
|
|
1273
1366
|
catch {
|
|
1274
|
-
console.log('ClawChats:
|
|
1367
|
+
console.log('ClawChats: the service is not running (stale runtime file).');
|
|
1275
1368
|
try {
|
|
1276
1369
|
fs.unlinkSync(RUNTIME_FILE);
|
|
1277
1370
|
}
|
|
@@ -1291,13 +1384,26 @@ async function handleStatus() {
|
|
|
1291
1384
|
});
|
|
1292
1385
|
const status = JSON.parse(body);
|
|
1293
1386
|
console.log(`ClawChats Plugin v${status.version}`);
|
|
1387
|
+
if (status.state === 'waiting-setup') {
|
|
1388
|
+
console.log('State: waiting for setup');
|
|
1389
|
+
console.log(` ${SETUP_HINT}`);
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
if (status.state === 'failed') {
|
|
1393
|
+
console.log('State: failed to start');
|
|
1394
|
+
console.log(` ${status.error || 'unknown error'}`);
|
|
1395
|
+
console.log(' After fixing it: openclaw plugins reload connector');
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
if (status.state === 'starting')
|
|
1399
|
+
console.log('State: starting');
|
|
1294
1400
|
console.log(`Uptime: ${Math.floor(status.uptime)}s`);
|
|
1295
1401
|
console.log(`Gateway: ${status.gateway.connected ? 'connected' : 'disconnected'}`);
|
|
1296
1402
|
console.log(`Signaling: ${status.signaling.connected ? 'connected' : 'disconnected'}`);
|
|
1297
1403
|
console.log(`Clients: ${status.clients.active}`);
|
|
1298
1404
|
}
|
|
1299
1405
|
catch {
|
|
1300
|
-
console.log('ClawChats:
|
|
1406
|
+
console.log('ClawChats: the service is running but did not answer (could not reach it).');
|
|
1301
1407
|
}
|
|
1302
1408
|
}
|
|
1303
1409
|
async function handleReset() {
|
package/package.json
CHANGED
package/server/config.js
CHANGED
|
@@ -5,6 +5,18 @@ import { fileURLToPath } from 'node:url';
|
|
|
5
5
|
|
|
6
6
|
export const HOME = os.homedir();
|
|
7
7
|
|
|
8
|
+
/** The gateway's state directory: OPENCLAW_STATE_DIR (profiles, custom installs), else ~/.openclaw. */
|
|
9
|
+
export const STATE_DIR = process.env.OPENCLAW_STATE_DIR || path.join(HOME, '.openclaw');
|
|
10
|
+
|
|
11
|
+
/** Where the gateway's config file may be, most specific first. */
|
|
12
|
+
export function gatewayConfigCandidates() {
|
|
13
|
+
return [
|
|
14
|
+
process.env.OPENCLAW_CONFIG_PATH,
|
|
15
|
+
path.join(STATE_DIR, 'openclaw.json'),
|
|
16
|
+
'/etc/openclaw/openclaw.json',
|
|
17
|
+
].filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
|
|
8
20
|
// Resolve __dirname for ESM (esbuild inlines this correctly)
|
|
9
21
|
const __filename = fileURLToPath(import.meta.url);
|
|
10
22
|
const __dirname = path.dirname(__filename);
|
|
@@ -30,7 +42,7 @@ export const AUTH_TOKEN = parseConfigField('authToken') || '';
|
|
|
30
42
|
// (that's the browser's external-facing URL and would cause a routing loop through Caddy)
|
|
31
43
|
// Note: GATEWAY_WS_URL env var is read by the plugin host (src/index.ts) and passed via createApp().
|
|
32
44
|
export function discoverGatewayWsUrl() {
|
|
33
|
-
for (const cfgPath of
|
|
45
|
+
for (const cfgPath of gatewayConfigCandidates()) {
|
|
34
46
|
try {
|
|
35
47
|
const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
|
|
36
48
|
const port = raw.gateway?.port || raw.port;
|
|
@@ -44,11 +56,11 @@ export const GATEWAY_WS_URL = discoverGatewayWsUrl();
|
|
|
44
56
|
|
|
45
57
|
// Agent workspace dir (relative /api/file paths resolve against it): openclaw config → default.
|
|
46
58
|
export function discoverWorkspaceDir() {
|
|
47
|
-
for (const cfgPath of
|
|
59
|
+
for (const cfgPath of gatewayConfigCandidates()) {
|
|
48
60
|
try {
|
|
49
61
|
const ws = JSON.parse(fs.readFileSync(cfgPath, 'utf8')).agents?.defaults?.workspace;
|
|
50
62
|
if (ws) return ws;
|
|
51
63
|
} catch { /* try next */ }
|
|
52
64
|
}
|
|
53
|
-
return path.join(
|
|
65
|
+
return path.join(STATE_DIR, 'workspace');
|
|
54
66
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import os from 'node:os';
|
|
4
3
|
import { send } from '../util/http.js';
|
|
4
|
+
import { STATE_DIR } from '../config.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* List available OpenClaw agents.
|
|
@@ -9,7 +9,7 @@ import { send } from '../util/http.js';
|
|
|
9
9
|
*/
|
|
10
10
|
export function handleAgents(req, res) {
|
|
11
11
|
try {
|
|
12
|
-
const agentsDir = path.join(
|
|
12
|
+
const agentsDir = path.join(STATE_DIR, 'agents');
|
|
13
13
|
const agents = fs.readdirSync(agentsDir, { withFileTypes: true })
|
|
14
14
|
.filter(e => e.isDirectory())
|
|
15
15
|
.map(e => e.name);
|
package/server/gateway.js
CHANGED
|
@@ -31,7 +31,11 @@ export class GatewayClient {
|
|
|
31
31
|
gatewayWsUrl,
|
|
32
32
|
debugLogger,
|
|
33
33
|
connectParams: nonce => this._connectParams(nonce, ['approvals']),
|
|
34
|
-
onEvent: data =>
|
|
34
|
+
onEvent: data => {
|
|
35
|
+
this.broadcastToBrowsers(data);
|
|
36
|
+
// Sharing tells the room's host while a guest run waits on this gateway's owner (peer/sharing.js onApprovalEvent).
|
|
37
|
+
if (this.onApprovalEvent) { try { this.onApprovalEvent(JSON.parse(data)); } catch (e) { console.error('[gateway] approval observer:', e.message); } }
|
|
38
|
+
},
|
|
35
39
|
});
|
|
36
40
|
}
|
|
37
41
|
|
package/server/index.js
CHANGED
|
@@ -89,6 +89,7 @@ export function createApp(config = {}) {
|
|
|
89
89
|
// Team chats: several agents in one thread (server/team.js).
|
|
90
90
|
const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm), remote: sharing });
|
|
91
91
|
gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
|
|
92
|
+
gatewayClient.onApprovalEvent = msg => sharing?.onApprovalEvent(msg);
|
|
92
93
|
gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
|
|
93
94
|
gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
|
|
94
95
|
// Renamed agents: shares re-issued with the new names, copies of rooms here told (peer/sharing.js, team.js).
|
package/server/peer/sharing.js
CHANGED
|
@@ -504,7 +504,7 @@ export class SharingManager {
|
|
|
504
504
|
const done = new Promise(resolve => {
|
|
505
505
|
const timer = setTimeout(() => { this._runs.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS + 30_000);
|
|
506
506
|
timer.unref?.();
|
|
507
|
-
this._runs.set(runId, { resolve, timer, text: '', emit });
|
|
507
|
+
this._runs.set(runId, { resolve, timer, text: '', emit, sessionKey });
|
|
508
508
|
});
|
|
509
509
|
this._turns.set(turnKey, { sessionKey, runId });
|
|
510
510
|
try {
|
|
@@ -521,6 +521,7 @@ export class SharingManager {
|
|
|
521
521
|
} finally {
|
|
522
522
|
const run = this._runs.get(runId);
|
|
523
523
|
if (run) { clearTimeout(run.timer); this._runs.delete(runId); }
|
|
524
|
+
for (const [id, r] of this._approvalRuns || []) if (r === runId) this._approvalRuns.delete(id);
|
|
524
525
|
}
|
|
525
526
|
}
|
|
526
527
|
|
|
@@ -557,6 +558,7 @@ export class SharingManager {
|
|
|
557
558
|
}
|
|
558
559
|
db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
|
|
559
560
|
this._guestKeys = null;
|
|
561
|
+
this._changed(); // the room's list of answering sessions grew: the app needs it before the agent asks for an approval
|
|
560
562
|
return key;
|
|
561
563
|
}
|
|
562
564
|
|
|
@@ -570,6 +572,37 @@ export class SharingManager {
|
|
|
570
572
|
return '';
|
|
571
573
|
}
|
|
572
574
|
|
|
575
|
+
/**
|
|
576
|
+
* Approval events (owner side, from the approval connection): while a guest run waits for this gateway's owner to
|
|
577
|
+
* approve something, the room's host is told, so its room says what it's waiting for instead of only "responding".
|
|
578
|
+
* Only the kind of thing is sent ("a command", or the action's title), never the command itself or its paths.
|
|
579
|
+
*/
|
|
580
|
+
onApprovalEvent(msg) {
|
|
581
|
+
const ev = msg?.event || '';
|
|
582
|
+
const m = /^(exec|plugin|openclaw)\.approval\.(requested|resolved)$/.exec(ev);
|
|
583
|
+
if (!m) return;
|
|
584
|
+
const p = msg.payload || {};
|
|
585
|
+
this._approvalRuns ??= new Map(); // approval id -> run id
|
|
586
|
+
if (m[2] === 'requested') {
|
|
587
|
+
const sessionKey = p.request?.sessionKey;
|
|
588
|
+
const entry = sessionKey && [...this._runs.entries()].find(([, r]) => r.sessionKey === sessionKey);
|
|
589
|
+
if (!entry || !p.id) return;
|
|
590
|
+
const [runId, run] = entry;
|
|
591
|
+
this._approvalRuns.set(p.id, runId);
|
|
592
|
+
const what = m[1] === 'exec' ? 'a command' : String(p.request?.title || 'an action').replace(/[\n\r]/g, ' ').slice(0, 80);
|
|
593
|
+
run.waiting = { what, expiresAtMs: Number(p.expiresAtMs) || null };
|
|
594
|
+
run.emit?.('status', { waiting: 'approval', what, expiresAtMs: run.waiting.expiresAtMs });
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const runId = p.id && this._approvalRuns.get(p.id);
|
|
598
|
+
if (!runId) return;
|
|
599
|
+
this._approvalRuns.delete(p.id);
|
|
600
|
+
const run = this._runs.get(runId);
|
|
601
|
+
if (!run || [...this._approvalRuns.values()].includes(runId)) return; // another approval of this run is still open
|
|
602
|
+
run.waiting = null;
|
|
603
|
+
run.emit?.('status', { waiting: null });
|
|
604
|
+
}
|
|
605
|
+
|
|
573
606
|
/** Every gateway event (owner side): finish guest runs, stream their text. */
|
|
574
607
|
onGatewayEvent(msg) {
|
|
575
608
|
if (msg?.event !== 'chat') return;
|
|
@@ -646,12 +679,15 @@ export class SharingManager {
|
|
|
646
679
|
}
|
|
647
680
|
|
|
648
681
|
/** Run a turn on a shared agent. Returns { state, text }; throws with `.partial` on failure. */
|
|
649
|
-
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
|
|
682
|
+
async turn(agentId, { turnId, roomId, roomTitle, message }, { onDelta, onStatus } = {}) {
|
|
650
683
|
const id = SharingManager.parseRemoteId(agentId);
|
|
651
684
|
if (!id) throw new Error('not a shared agent');
|
|
652
685
|
const link = await this._link(id.shareId);
|
|
653
686
|
return link.request('turn', { turnId, agentId: id.remoteId, roomId, roomTitle, message }, {
|
|
654
|
-
onEvent: (event, data) => {
|
|
687
|
+
onEvent: (event, data) => {
|
|
688
|
+
if (event === 'delta' && typeof data === 'string') onDelta?.(data);
|
|
689
|
+
else if (event === 'status' && data && typeof data === 'object') onStatus?.(data);
|
|
690
|
+
},
|
|
655
691
|
timeoutMs: TURN_TIMEOUT_MS + 60_000,
|
|
656
692
|
});
|
|
657
693
|
}
|
|
@@ -172,6 +172,41 @@ test("the sessions answering a host's room are listed per host and room, so thei
|
|
|
172
172
|
assert.deepEqual(s.owner.guestSessionKeysFor('gwOther', 'room1'), [], 'another host with the same room id is not this room');
|
|
173
173
|
});
|
|
174
174
|
|
|
175
|
+
test('a guest session being made tells the app, so the room knows it before the agent asks for anything', async () => {
|
|
176
|
+
const s = setup();
|
|
177
|
+
const frames = [];
|
|
178
|
+
s.owner.broadcast = f => frames.push(JSON.parse(f).event);
|
|
179
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 10 });
|
|
180
|
+
s.activate();
|
|
181
|
+
frames.length = 0;
|
|
182
|
+
await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'hi' });
|
|
183
|
+
const created = s.ownerCalls.findIndex(c => c.method === 'sessions.create');
|
|
184
|
+
assert.ok(created >= 0);
|
|
185
|
+
assert.ok(frames.filter(e => e === 'sharing-changed').length >= 2, 'once for the usage count, once when the session exists');
|
|
186
|
+
assert.ok(s.owner.guestSessionKeysFor('gwH', 'room1').length === 1);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("while a guest run waits for its owner's approval, the requester is told (without the command); decided -> cleared", async () => {
|
|
190
|
+
let hold;
|
|
191
|
+
const s = setup({ reply: () => null }); // the run stays open (nothing final yet)
|
|
192
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 10 });
|
|
193
|
+
s.activate();
|
|
194
|
+
const statuses = [];
|
|
195
|
+
const turn = s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'run: rm -rf /secret/path' }, { onStatus: st => statuses.push(st) });
|
|
196
|
+
for (let i = 0; i < 50 && !s.ownerCalls.some(c => c.method === 'chat.send'); i++) await new Promise(r => setTimeout(r, 10));
|
|
197
|
+
const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
|
|
198
|
+
s.owner.onApprovalEvent({ event: 'exec.approval.requested', payload: { id: 'ap1', request: { sessionKey: send.sessionKey, command: 'rm -rf /secret/path' }, expiresAtMs: 123 } });
|
|
199
|
+
s.owner.onApprovalEvent({ event: 'exec.approval.requested', payload: { id: 'ap-other', request: { sessionKey: 'agent:x:dashboard:unrelated', command: 'ls' }, expiresAtMs: 1 } });
|
|
200
|
+
await new Promise(r => setTimeout(r, 30));
|
|
201
|
+
assert.deepEqual(statuses, [{ waiting: 'approval', what: 'a command', expiresAtMs: 123 }], "only this run's approval, and not its command");
|
|
202
|
+
assert.ok(!JSON.stringify(statuses).includes('secret'));
|
|
203
|
+
s.owner.onApprovalEvent({ event: 'exec.approval.resolved', payload: { id: 'ap1' } });
|
|
204
|
+
await new Promise(r => setTimeout(r, 30));
|
|
205
|
+
assert.deepEqual(statuses.at(-1), { waiting: null });
|
|
206
|
+
s.owner.onGatewayEvent({ event: 'chat', payload: { runId: send.idempotencyKey, state: 'final', message: { content: [{ type: 'text', text: 'done' }] } } });
|
|
207
|
+
assert.equal((await turn).text, 'done');
|
|
208
|
+
});
|
|
209
|
+
|
|
175
210
|
test('approve → verified on the requester → turn runs in a guest session on the owner, text streams back', async () => {
|
|
176
211
|
const s = setup();
|
|
177
212
|
assert.deepEqual(s.req.remoteAgents(), []);
|
package/server/team.js
CHANGED
|
@@ -291,6 +291,8 @@ export class TeamCoordinator {
|
|
|
291
291
|
return { agentId: m.agentId, workKey: null, remote: true, name: known?.name || null, ownerName: known?.ownerName || null, available: !!a };
|
|
292
292
|
}),
|
|
293
293
|
running: live ? [...live.running.keys()] : [],
|
|
294
|
+
// Remote agents whose run waits for their owner to approve something: { agentId: { owner, what, expiresAtMs } }.
|
|
295
|
+
waiting: live?.waiting ? Object.fromEntries(live.waiting) : {},
|
|
294
296
|
queued: live?.queued || 0,
|
|
295
297
|
people: r.people.map(p => ({ personId: p.personId, name: p.name })),
|
|
296
298
|
// In a copy: the sessions this gateway's agents answer the host's room in. Their approvals and questions belong to the room.
|
|
@@ -695,15 +697,26 @@ export class TeamCoordinator {
|
|
|
695
697
|
const delta = (text, done = false) => this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-delta', roomKey, agentId, runId, text, ...(done ? { done: true } : {}) }));
|
|
696
698
|
live.running.set(agentId, { remote: true, runId });
|
|
697
699
|
this._status(roomKey);
|
|
700
|
+
// Its owner's gateway says when the run waits for their approval: the room shows it, and who it's waiting for.
|
|
701
|
+
const owner = this._remoteAgents().find(a => a.agentId === agentId)?.ownerName || this._remoteName(agentId)?.ownerName || null;
|
|
702
|
+
const waiting = w => {
|
|
703
|
+
live.waiting ??= new Map();
|
|
704
|
+
if (w) live.waiting.set(agentId, w); else live.waiting.delete(agentId);
|
|
705
|
+
this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-status', roomKey, agentId, runId, waiting: w || null }));
|
|
706
|
+
};
|
|
698
707
|
let result, partial = '';
|
|
699
708
|
try {
|
|
700
709
|
this._setSeen(roomKey, agentId, REMOTE_LANE, fresh);
|
|
701
710
|
result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
|
|
702
|
-
{
|
|
711
|
+
{
|
|
712
|
+
onDelta: text => { partial = text; delta(text); },
|
|
713
|
+
onStatus: s => waiting(s?.waiting === 'approval' ? { owner, what: String(s.what || 'something').slice(0, 80), expiresAtMs: Number(s.expiresAtMs) || null } : null),
|
|
714
|
+
});
|
|
703
715
|
} catch (e) {
|
|
704
716
|
throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
|
|
705
717
|
} finally {
|
|
706
718
|
live.running.delete(agentId);
|
|
719
|
+
if (live.waiting?.has(agentId)) waiting(null);
|
|
707
720
|
delta('', true);
|
|
708
721
|
this._status(roomKey);
|
|
709
722
|
}
|
package/server/team.test.js
CHANGED
|
@@ -837,6 +837,33 @@ test("someone else's messages raise a badge on the room or its copy (chat.inject
|
|
|
837
837
|
assert.ok(hostMid >= hostBefore);
|
|
838
838
|
});
|
|
839
839
|
|
|
840
|
+
test("a remote agent waiting for its owner's approval: the room says so (who, what) and clears it when the run ends", async () => {
|
|
841
|
+
let release, seen;
|
|
842
|
+
const remote = {
|
|
843
|
+
remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil' }],
|
|
844
|
+
turn: async (agentId, args, { onStatus }) => {
|
|
845
|
+
onStatus({ waiting: 'approval', what: 'a command', expiresAtMs: 99 });
|
|
846
|
+
seen = h.team.room(roomKey).waiting;
|
|
847
|
+
await new Promise(r => (release = r));
|
|
848
|
+
onStatus({ waiting: null });
|
|
849
|
+
return { state: 'final', text: 'ran it' };
|
|
850
|
+
},
|
|
851
|
+
abort: async () => {},
|
|
852
|
+
};
|
|
853
|
+
const h = harness(() => 'ok', { remote });
|
|
854
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
|
|
855
|
+
const sent = h.team.send(roomKey, { text: '@Jarvis-Kamil run the tests', userLabel: 'Houman' });
|
|
856
|
+
for (let i = 0; i < 100 && !release; i++) await new Promise(r => setTimeout(r, 10));
|
|
857
|
+
assert.deepEqual(seen, { 'peer:sh1:jarvis': { owner: 'Kamil', what: 'a command', expiresAtMs: 99 } });
|
|
858
|
+
const ev = h.events.filter(e => e.event === 'team-remote-status');
|
|
859
|
+
assert.deepEqual(ev.at(-1).waiting, { owner: 'Kamil', what: 'a command', expiresAtMs: 99 });
|
|
860
|
+
release();
|
|
861
|
+
await sent; await h.settle();
|
|
862
|
+
assert.deepEqual(h.team.room(roomKey).waiting, {}, 'cleared when the run ends');
|
|
863
|
+
assert.equal(h.events.filter(e => e.event === 'team-remote-status').at(-1).waiting, null);
|
|
864
|
+
assert.ok(h.room(roomKey).some(t => t.endsWith('ran it')));
|
|
865
|
+
});
|
|
866
|
+
|
|
840
867
|
test('the timeline says who joined and left, the same on both sides; agents never see those lines', async () => {
|
|
841
868
|
const { H, K, settle } = twoGateways();
|
|
842
869
|
const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
|