@clawchatsai/connector 0.1.18 → 0.1.20
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.d.ts +7 -0
- package/dist/index.js +26 -1
- package/package.json +1 -1
- package/server/approval-client.js +96 -0
- package/server/approval-client.test.js +106 -0
- package/server/controllers/title.js +44 -0
- package/server/controllers/title.test.js +46 -0
- package/server/gateway.js +45 -5
- package/server/index.js +3 -0
package/dist/index.d.ts
CHANGED
|
@@ -60,6 +60,13 @@ interface PluginApi {
|
|
|
60
60
|
}) => void;
|
|
61
61
|
runtime: {
|
|
62
62
|
requestRestart?: (reason: string) => void;
|
|
63
|
+
llm?: {
|
|
64
|
+
complete: (params: Record<string, unknown>) => Promise<{
|
|
65
|
+
text?: string;
|
|
66
|
+
provider?: string;
|
|
67
|
+
model?: string;
|
|
68
|
+
}>;
|
|
69
|
+
};
|
|
63
70
|
};
|
|
64
71
|
config?: Record<string, unknown>;
|
|
65
72
|
}
|
package/dist/index.js
CHANGED
|
@@ -38,7 +38,30 @@ export const PLUGIN_VERSION = _pkgJson.version;
|
|
|
38
38
|
const MAX_DC_MESSAGE_SIZE = 64 * 1024;
|
|
39
39
|
const DC_CHUNK_SIZE = MAX_DC_MESSAGE_SIZE - 512; // room for the chunk envelope
|
|
40
40
|
/** Active DataChannel connections: connectionId → send function */
|
|
41
|
-
|
|
41
|
+
// Authenticated DataChannel browsers. Adding or removing one tells the gateway client, which holds the
|
|
42
|
+
// approval-client gateway connection only while a browser is attached (server/approval-client.js).
|
|
43
|
+
class BrowserClientMap extends Map {
|
|
44
|
+
set(key, value) {
|
|
45
|
+
const added = !this.has(key);
|
|
46
|
+
super.set(key, value);
|
|
47
|
+
if (added)
|
|
48
|
+
app?.gatewayClient.browsersChanged();
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
delete(key) {
|
|
52
|
+
const removed = super.delete(key);
|
|
53
|
+
if (removed)
|
|
54
|
+
app?.gatewayClient.browsersChanged();
|
|
55
|
+
return removed;
|
|
56
|
+
}
|
|
57
|
+
clear() {
|
|
58
|
+
const had = this.size > 0;
|
|
59
|
+
super.clear();
|
|
60
|
+
if (had)
|
|
61
|
+
app?.gatewayClient.browsersChanged();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const connectedClients = new BrowserClientMap();
|
|
42
65
|
/** Reassembly buffers for chunked RPC requests from browser (large uploads). */
|
|
43
66
|
const rpcReqChunkBuffers = new Map();
|
|
44
67
|
/** Reassembly buffers for chunked gateway-msg from browser (large payloads like image attachments). */
|
|
@@ -205,6 +228,7 @@ async function startClawChats(ctx, api) {
|
|
|
205
228
|
gatewayUrl: process.env.GATEWAY_WS_URL || 'ws://localhost:18789',
|
|
206
229
|
authToken: process.env.CLAWCHATS_AUTH_TOKEN || '', // P2P: DataChannel is the auth boundary
|
|
207
230
|
gatewayToken, // For WS auth to local OpenClaw gateway
|
|
231
|
+
llm: api.runtime?.llm, // host-run completions (chat-title fallback, /api/title)
|
|
208
232
|
openaiApiKey: (() => {
|
|
209
233
|
// Resolve OpenAI API key: openclaw config → env var
|
|
210
234
|
try {
|
|
@@ -219,6 +243,7 @@ async function startClawChats(ctx, api) {
|
|
|
219
243
|
});
|
|
220
244
|
// 4. Connect createApp's gateway client (handles persistence + event relay)
|
|
221
245
|
app.gatewayClient.connect();
|
|
246
|
+
app.gatewayClient.setExternalBrowserCount(() => connectedClients.size);
|
|
222
247
|
// Wire DataChannel clients as broadcast targets so they receive gateway events.
|
|
223
248
|
// Frames over the DataChannel limit (e.g. a complete chat.history snapshot) go as chunks.
|
|
224
249
|
app.gatewayClient.addBroadcastTarget((data) => {
|
package/package.json
CHANGED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { WebSocket as WS } from 'ws';
|
|
2
|
+
|
|
3
|
+
// The gateway sends *.approval.requested / *.approval.resolved only to "approval clients"
|
|
4
|
+
// (src/gateway/server-request-context.ts canDeliverApprovals: the Control UI's client id, or a
|
|
5
|
+
// connection declaring the `approvals` cap). Being one also changes routing: while any approval
|
|
6
|
+
// client is connected, an approval waits for a decision instead of expiring at once with
|
|
7
|
+
// "no-approval-route". The connector's main connection is always up, so it must not be one.
|
|
8
|
+
// Like an open Control UI tab, this second connection declares the cap only while a browser is
|
|
9
|
+
// attached (GatewayClient.browsersChanged). Only approval events leave it; everything else the
|
|
10
|
+
// gateway broadcasts to it is dropped (the main connection already delivers those).
|
|
11
|
+
export const APPROVAL_EVENT_RE = /^(exec|plugin|openclaw)\.approval\.(requested|resolved)$/;
|
|
12
|
+
|
|
13
|
+
export class ApprovalClient {
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} o
|
|
16
|
+
* @param {string} o.gatewayWsUrl
|
|
17
|
+
* @param {(nonce: string) => object} o.connectParams connect params for this socket (caps: ['approvals'])
|
|
18
|
+
* @param {(data: string) => void} o.onEvent an approval event frame, as received
|
|
19
|
+
* @param {{ logFrame(direction: string, data: string): void }} o.debugLogger
|
|
20
|
+
*/
|
|
21
|
+
constructor({ gatewayWsUrl, connectParams, onEvent, debugLogger }) {
|
|
22
|
+
this.gatewayWsUrl = gatewayWsUrl;
|
|
23
|
+
this.connectParams = connectParams;
|
|
24
|
+
this.onEvent = onEvent;
|
|
25
|
+
this.debugLogger = debugLogger;
|
|
26
|
+
this.ws = null;
|
|
27
|
+
this.running = false;
|
|
28
|
+
this.connected = false;
|
|
29
|
+
this.reconnectAttempts = 0;
|
|
30
|
+
this._reconnectTimer = null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
start() {
|
|
34
|
+
if (this.running) return;
|
|
35
|
+
this.running = true;
|
|
36
|
+
this.reconnectAttempts = 0;
|
|
37
|
+
this._connect();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
stop() {
|
|
41
|
+
this.running = false;
|
|
42
|
+
this.connected = false;
|
|
43
|
+
clearTimeout(this._reconnectTimer);
|
|
44
|
+
this._reconnectTimer = null;
|
|
45
|
+
const ws = this.ws;
|
|
46
|
+
this.ws = null;
|
|
47
|
+
if (ws) {
|
|
48
|
+
ws.removeAllListeners('message');
|
|
49
|
+
ws.removeAllListeners('close');
|
|
50
|
+
ws.on('error', () => {});
|
|
51
|
+
try { ws.readyState === WS.CONNECTING ? ws.terminate() : ws.close(1000, 'no browser attached'); } catch { /* already closed */ }
|
|
52
|
+
setTimeout(() => { try { ws.terminate(); } catch { /* gone */ } }, 2000).unref?.();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
_connect() {
|
|
57
|
+
if (!this.running) return;
|
|
58
|
+
const ws = new WS(this.gatewayWsUrl);
|
|
59
|
+
this.ws = ws;
|
|
60
|
+
ws.on('open', () => { this.reconnectAttempts = 0; });
|
|
61
|
+
ws.on('message', data => this._onMessage(ws, data.toString()));
|
|
62
|
+
ws.on('close', () => {
|
|
63
|
+
if (this.ws !== ws) return;
|
|
64
|
+
this.connected = false;
|
|
65
|
+
this.ws = null;
|
|
66
|
+
if (this.running) this._scheduleReconnect();
|
|
67
|
+
});
|
|
68
|
+
ws.on('error', err => console.error('[approvals] gateway WebSocket error:', err.message));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
_onMessage(ws, data) {
|
|
72
|
+
let msg;
|
|
73
|
+
try { msg = JSON.parse(data); } catch { return; }
|
|
74
|
+
if (msg.type === 'event' && msg.event === 'connect.challenge') {
|
|
75
|
+
ws.send(JSON.stringify({ type: 'req', id: 'gw-approvals-connect', method: 'connect', params: this.connectParams(msg.payload?.nonce || '') }));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (msg.type === 'res' && msg.id === 'gw-approvals-connect') {
|
|
79
|
+
this.connected = !!msg.ok;
|
|
80
|
+
if (msg.ok) console.log('[approvals] approval-client connection ready');
|
|
81
|
+
else console.warn(`[approvals] connect failed: ${msg.error?.message || 'unknown error'}`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (msg.type === 'event' && APPROVAL_EVENT_RE.test(msg.event || '')) {
|
|
85
|
+
this.debugLogger?.logFrame('GW→SRV', data);
|
|
86
|
+
this.onEvent(data);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
_scheduleReconnect() {
|
|
91
|
+
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
|
|
92
|
+
this.reconnectAttempts++;
|
|
93
|
+
clearTimeout(this._reconnectTimer);
|
|
94
|
+
this._reconnectTimer = setTimeout(() => { this._reconnectTimer = null; this._connect(); }, delay);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { WebSocketServer } from 'ws';
|
|
4
|
+
import { GatewayClient } from './gateway.js';
|
|
5
|
+
import { APPROVAL_EVENT_RE } from './approval-client.js';
|
|
6
|
+
|
|
7
|
+
const logger = { logFrame() {} };
|
|
8
|
+
const wait = ms => new Promise(r => setTimeout(r, ms));
|
|
9
|
+
|
|
10
|
+
/** A fake gateway: challenges each connection, records connect params, can push events. */
|
|
11
|
+
async function fakeGateway() {
|
|
12
|
+
const wss = new WebSocketServer({ port: 0 });
|
|
13
|
+
const conns = [];
|
|
14
|
+
wss.on('connection', ws => {
|
|
15
|
+
const c = { ws, params: null, closed: false };
|
|
16
|
+
conns.push(c);
|
|
17
|
+
ws.on('close', () => { c.closed = true; });
|
|
18
|
+
ws.on('message', raw => {
|
|
19
|
+
const msg = JSON.parse(raw.toString());
|
|
20
|
+
if (msg.method === 'connect') { c.params = msg.params; ws.send(JSON.stringify({ type: 'res', id: msg.id, ok: true, payload: { type: 'hello-ok' } })); }
|
|
21
|
+
});
|
|
22
|
+
ws.send(JSON.stringify({ type: 'event', event: 'connect.challenge', payload: { nonce: 'n' } }));
|
|
23
|
+
});
|
|
24
|
+
await new Promise(r => wss.once('listening', r));
|
|
25
|
+
return { wss, conns, url: `ws://127.0.0.1:${wss.address().port}`, approvalConns: () => conns.filter(c => c.params?.caps?.includes('approvals')) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function client(url, graceMs = 50) {
|
|
29
|
+
const dataDir = '/tmp/cc-approval-client-test';
|
|
30
|
+
return new GatewayClient({ dataDir, debugLogger: logger, gatewayWsUrl: url, authToken: '', approvalClientGraceMs: graceMs });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
test('approval events only: requested/resolved for exec, plugin and system-agent', () => {
|
|
34
|
+
for (const e of ['exec.approval.requested', 'plugin.approval.resolved', 'openclaw.approval.requested']) assert.ok(APPROVAL_EVENT_RE.test(e), e);
|
|
35
|
+
for (const e of ['session.approval', 'exec.approval.list', 'chat', 'sessions.changed']) assert.ok(!APPROVAL_EVENT_RE.test(e), e);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('no browser: no approval-client connection; main connection never declares approvals', async () => {
|
|
39
|
+
const gw = await fakeGateway();
|
|
40
|
+
const c = client(gw.url);
|
|
41
|
+
c.connect();
|
|
42
|
+
await wait(200);
|
|
43
|
+
assert.equal(gw.conns.length, 1);
|
|
44
|
+
assert.deepEqual(gw.conns[0].params.caps, ['tool-events']);
|
|
45
|
+
assert.equal(gw.approvalConns().length, 0);
|
|
46
|
+
c.close();
|
|
47
|
+
await new Promise(r => gw.wss.close(r));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('a browser attaches: approval-client connection with the approvals cap; its approval events reach browsers, others are dropped', async () => {
|
|
51
|
+
const gw = await fakeGateway();
|
|
52
|
+
const c = client(gw.url);
|
|
53
|
+
const received = [];
|
|
54
|
+
c.addBroadcastTarget(d => received.push(JSON.parse(d)));
|
|
55
|
+
let n = 0;
|
|
56
|
+
c.setExternalBrowserCount(() => n);
|
|
57
|
+
n = 1; c.browsersChanged();
|
|
58
|
+
await wait(200);
|
|
59
|
+
const [ac] = gw.approvalConns();
|
|
60
|
+
assert.ok(ac, 'approval-client connection opened');
|
|
61
|
+
assert.deepEqual(ac.params.scopes.includes('operator.approvals'), true);
|
|
62
|
+
ac.ws.send(JSON.stringify({ type: 'event', event: 'plugin.approval.requested', payload: { id: 'plugin:1' } }));
|
|
63
|
+
ac.ws.send(JSON.stringify({ type: 'event', event: 'sessions.changed', payload: {} }));
|
|
64
|
+
ac.ws.send(JSON.stringify({ type: 'event', event: 'plugin.approval.resolved', payload: { id: 'plugin:1' } }));
|
|
65
|
+
await wait(100);
|
|
66
|
+
assert.deepEqual(received.map(m => m.event), ['plugin.approval.requested', 'plugin.approval.resolved']);
|
|
67
|
+
c.close();
|
|
68
|
+
await new Promise(r => gw.wss.close(r));
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('last browser leaves: closed after the grace period; a browser back within it keeps the same connection', async () => {
|
|
72
|
+
const gw = await fakeGateway();
|
|
73
|
+
const c = client(gw.url, 150);
|
|
74
|
+
let n = 1;
|
|
75
|
+
c.setExternalBrowserCount(() => n);
|
|
76
|
+
await wait(200);
|
|
77
|
+
assert.equal(gw.approvalConns().length, 1);
|
|
78
|
+
n = 0; c.browsersChanged();
|
|
79
|
+
await wait(50);
|
|
80
|
+
n = 1; c.browsersChanged(); // reconnect within grace
|
|
81
|
+
await wait(250);
|
|
82
|
+
assert.equal(gw.approvalConns().length, 1);
|
|
83
|
+
assert.equal(gw.approvalConns()[0].closed, false);
|
|
84
|
+
n = 0; c.browsersChanged();
|
|
85
|
+
await wait(300);
|
|
86
|
+
assert.equal(gw.approvalConns()[0].closed, true);
|
|
87
|
+
assert.equal(c.approvalClient.running, false);
|
|
88
|
+
c.close();
|
|
89
|
+
await new Promise(r => gw.wss.close(r));
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('local WebSocket browsers count too; close() stops the approval-client connection', async () => {
|
|
93
|
+
const gw = await fakeGateway();
|
|
94
|
+
const c = client(gw.url);
|
|
95
|
+
const fakeWs = { readyState: 3, send() {} };
|
|
96
|
+
c.addBrowserClient(fakeWs);
|
|
97
|
+
await wait(200);
|
|
98
|
+
assert.equal(gw.approvalConns().length, 1);
|
|
99
|
+
c.close();
|
|
100
|
+
await wait(100);
|
|
101
|
+
assert.equal(gw.approvalConns()[0].closed, true);
|
|
102
|
+
c.browsersChanged(); // ignored after close
|
|
103
|
+
await wait(100);
|
|
104
|
+
assert.equal(gw.approvalConns().length, 1);
|
|
105
|
+
await new Promise(r => gw.wss.close(r));
|
|
106
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { send, sendError, parseBody } from '../util/http.js';
|
|
2
|
+
|
|
3
|
+
// Chat-title fallback on the gateway's main model. ClawChats first asks the gateway's own
|
|
4
|
+
// titler (sessions.title.prepare), which only runs a utility model and returns null when the
|
|
5
|
+
// gateway has none (e.g. a claude-cli main model). The gateway's first-message titler falls
|
|
6
|
+
// back to the main model in that case; this endpoint does the same through the plugin's
|
|
7
|
+
// host-run completion (api.runtime.llm.complete), with the gateway's own title prompt.
|
|
8
|
+
export const TITLE_PROMPT = "Generate a concise session title (3-6 words, max 60 characters) from the user's first message. Use the same language as the message, in sentence case: capitalize only the first word and words that language always capitalizes. No emoji. Return only the title.";
|
|
9
|
+
const TITLE_MAX_CHARS = 60;
|
|
10
|
+
const SOURCE_MAX_CHARS = 1000;
|
|
11
|
+
const TIMEOUT_MS = 60_000;
|
|
12
|
+
|
|
13
|
+
// Port of the gateway's normalizeDashboardSessionTitle (src/gateway/dashboard-session-title.ts).
|
|
14
|
+
export function normalizeTitle(raw) {
|
|
15
|
+
const firstLine = String(raw || '').replace(/\r/g, '').split('\n').map(l => l.trim()).find(l => l && !l.startsWith('```'));
|
|
16
|
+
if (!firstLine) return null;
|
|
17
|
+
const normalized = firstLine.replace(/^\s*(?:title\s*:\s*)?/i, '').replace(/^["'`]+|["'`]+$/g, '').replace(/\s+/g, ' ').trim();
|
|
18
|
+
return normalized ? Array.from(normalized).slice(0, TITLE_MAX_CHARS).join('') : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
|
|
23
|
+
*/
|
|
24
|
+
export function createTitleHandler(llm) {
|
|
25
|
+
// Direct completion where the main model's provider has a direct transport; CLI and harness
|
|
26
|
+
// runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
|
|
27
|
+
async function complete(message) {
|
|
28
|
+
const base = { messages: [{ role: 'user', content: message }], systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 };
|
|
29
|
+
try {
|
|
30
|
+
return await llm.complete(base);
|
|
31
|
+
} catch (err) {
|
|
32
|
+
if (err?.code === 'LLM_COMPLETION_NOT_AUTHORIZED') throw err;
|
|
33
|
+
return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return async function handleTitle(req, res) {
|
|
38
|
+
if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
|
|
39
|
+
const { message } = await parseBody(req);
|
|
40
|
+
if (typeof message !== 'string' || !message.trim()) return sendError(res, 400, 'Missing message');
|
|
41
|
+
const result = await complete(Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join(''));
|
|
42
|
+
return send(res, 200, { title: normalizeTitle(result?.text), model: result?.provider && result?.model ? `${result.provider}/${result.model}` : undefined });
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import { createTitleHandler, normalizeTitle, TITLE_PROMPT } from './title.js';
|
|
5
|
+
|
|
6
|
+
function call(handler, body) {
|
|
7
|
+
const req = Readable.from([Buffer.from(JSON.stringify(body))]);
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
const res = { writeHead(status) { this.status = status; }, end(data) { resolve({ status: this.status, body: JSON.parse(data) }); } };
|
|
10
|
+
handler(req, res).catch(reject);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
test('normalizeTitle: first line, no label/quotes, max 60 chars', () => {
|
|
15
|
+
assert.equal(normalizeTitle('Title: "Fix sidebar flicker"\nmore'), 'Fix sidebar flicker');
|
|
16
|
+
assert.equal(normalizeTitle('```\n'), null);
|
|
17
|
+
assert.equal(normalizeTitle('x'.repeat(80)).length, 60);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('direct completion with the gateway title prompt', async () => {
|
|
21
|
+
const calls = [];
|
|
22
|
+
const handler = createTitleHandler({ complete: async p => { calls.push(p); return { text: 'Fix sidebar flicker', provider: 'anthropic', model: 'claude-haiku-4-5' }; } });
|
|
23
|
+
const r = await call(handler, { message: 'User: the sidebar flickers' });
|
|
24
|
+
assert.deepEqual(r, { status: 200, body: { title: 'Fix sidebar flicker', model: 'anthropic/claude-haiku-4-5' } });
|
|
25
|
+
assert.equal(calls.length, 1);
|
|
26
|
+
assert.equal(calls[0].systemPrompt, TITLE_PROMPT);
|
|
27
|
+
assert.deepEqual(calls[0].messages, [{ role: 'user', content: 'User: the sidebar flickers' }]);
|
|
28
|
+
assert.equal(calls[0].execution, undefined);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('falls back to isolated agent-runtime mode when direct completion fails (CLI runtimes)', async () => {
|
|
32
|
+
const calls = [];
|
|
33
|
+
const handler = createTitleHandler({ complete: async p => { calls.push(p); if (!p.execution) throw Object.assign(new Error('no transport'), { code: 'LLM_COMPLETION_FAILED' }); return { text: 'Proxmox backups' }; } });
|
|
34
|
+
const r = await call(handler, { message: 'hi there' });
|
|
35
|
+
assert.equal(r.body.title, 'Proxmox backups');
|
|
36
|
+
assert.equal(calls[1].execution.mode, 'isolated-agent-runtime');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('authorization failures are not retried; bad input is rejected', async () => {
|
|
40
|
+
let n = 0;
|
|
41
|
+
const handler = createTitleHandler({ complete: async () => { n++; throw Object.assign(new Error('denied'), { code: 'LLM_COMPLETION_NOT_AUTHORIZED' }); } });
|
|
42
|
+
await assert.rejects(call(handler, { message: 'x' }), /denied/);
|
|
43
|
+
assert.equal(n, 1);
|
|
44
|
+
assert.equal((await call(handler, { message: ' ' })).status, 400);
|
|
45
|
+
assert.equal((await call(createTitleHandler(undefined), { message: 'x' })).status, 501);
|
|
46
|
+
});
|
package/server/gateway.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { WebSocket as WS } from 'ws';
|
|
3
3
|
import { loadOrCreateDeviceIdentity, buildDeviceAuth } from './bootstrap/identity.js';
|
|
4
|
+
import { ApprovalClient } from './approval-client.js';
|
|
4
5
|
|
|
5
6
|
// Per-session run/transcript events; hidden sessions' ones are dropped by the lens.
|
|
6
7
|
const RUN_EVENTS = new Set(['chat', 'agent', 'session.tool', 'session.operation', 'session.observer']);
|
|
8
|
+
const SCOPES = ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'];
|
|
9
|
+
// After the last browser leaves, the approval-client connection stays this long (P2P reconnects, reloads).
|
|
10
|
+
const APPROVAL_CLIENT_GRACE_MS = 10_000;
|
|
7
11
|
|
|
8
12
|
export class GatewayClient {
|
|
9
|
-
constructor({ dataDir, debugLogger, gatewayWsUrl, authToken }) {
|
|
13
|
+
constructor({ dataDir, debugLogger, gatewayWsUrl, authToken, approvalClientGraceMs = APPROVAL_CLIENT_GRACE_MS }) {
|
|
10
14
|
this.dataDir = dataDir;
|
|
11
15
|
this.debugLogger = debugLogger;
|
|
12
16
|
this.gatewayWsUrl = gatewayWsUrl;
|
|
@@ -19,6 +23,40 @@ export class GatewayClient {
|
|
|
19
23
|
this._externalBroadcastTargets = [];
|
|
20
24
|
this._rpc = new Map(); // request id → { resolve, reject, timer } for connector-originated RPCs
|
|
21
25
|
this._rpcSeq = 0;
|
|
26
|
+
// Approval events only while a browser is attached (server/approval-client.js).
|
|
27
|
+
this._externalBrowserCount = () => 0;
|
|
28
|
+
this._approvalGraceMs = approvalClientGraceMs;
|
|
29
|
+
this._approvalStopTimer = null;
|
|
30
|
+
this.approvalClient = new ApprovalClient({
|
|
31
|
+
gatewayWsUrl,
|
|
32
|
+
debugLogger,
|
|
33
|
+
connectParams: nonce => this._connectParams(nonce, ['approvals']),
|
|
34
|
+
onEvent: data => this.broadcastToBrowsers(data),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Gateway connect params; `caps` differ between the main and the approval-client connection. */
|
|
39
|
+
_connectParams(nonce, caps) {
|
|
40
|
+
const identity = loadOrCreateDeviceIdentity(path.join(this.dataDir, 'device-identity.json'));
|
|
41
|
+
const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes: SCOPES, token: this.authToken, nonce });
|
|
42
|
+
return { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: SCOPES, device, auth: { token: this.authToken }, caps };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Browsers attached over the DataChannel (src/index.ts); local WebSocket browsers are counted here. */
|
|
46
|
+
setExternalBrowserCount(fn) { this._externalBrowserCount = fn; this.browsersChanged(); }
|
|
47
|
+
|
|
48
|
+
/** A browser attached or left: hold the approval-client connection while any is attached. */
|
|
49
|
+
browsersChanged() {
|
|
50
|
+
if (this._closed) return;
|
|
51
|
+
const count = this.browserClients.size + this._externalBrowserCount();
|
|
52
|
+
if (count > 0) {
|
|
53
|
+
clearTimeout(this._approvalStopTimer);
|
|
54
|
+
this._approvalStopTimer = null;
|
|
55
|
+
this.approvalClient.start();
|
|
56
|
+
} else if (this.approvalClient.running && !this._approvalStopTimer) {
|
|
57
|
+
this._approvalStopTimer = setTimeout(() => { this._approvalStopTimer = null; this.approvalClient.stop(); }, this._approvalGraceMs);
|
|
58
|
+
this._approvalStopTimer.unref?.();
|
|
59
|
+
}
|
|
22
60
|
}
|
|
23
61
|
|
|
24
62
|
connect() {
|
|
@@ -54,9 +92,7 @@ export class GatewayClient {
|
|
|
54
92
|
}
|
|
55
93
|
|
|
56
94
|
if (msg.type === 'event' && msg.event === 'connect.challenge') {
|
|
57
|
-
|
|
58
|
-
const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'], token: this.authToken, nonce: msg.payload?.nonce || '' });
|
|
59
|
-
this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'], device, auth: { token: this.authToken }, caps: ['tool-events'] } }));
|
|
95
|
+
this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
|
|
60
96
|
return;
|
|
61
97
|
}
|
|
62
98
|
if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seed().catch(e => console.warn(`[lens] seed failed: ${e.message}`)); }
|
|
@@ -132,6 +168,9 @@ export class GatewayClient {
|
|
|
132
168
|
this._reconnectTimer = null;
|
|
133
169
|
this._failPendingRpcs('connector stopping');
|
|
134
170
|
this.connected = false;
|
|
171
|
+
clearTimeout(this._approvalStopTimer);
|
|
172
|
+
this._approvalStopTimer = null;
|
|
173
|
+
this.approvalClient.stop();
|
|
135
174
|
const ws = this.ws;
|
|
136
175
|
this.ws = null;
|
|
137
176
|
if (ws) {
|
|
@@ -147,12 +186,13 @@ export class GatewayClient {
|
|
|
147
186
|
|
|
148
187
|
addBrowserClient(ws) {
|
|
149
188
|
this.browserClients.set(ws, {});
|
|
189
|
+
this.browsersChanged();
|
|
150
190
|
if (ws.readyState === WS.OPEN) {
|
|
151
191
|
ws.send(JSON.stringify({ type: 'clawchats', event: 'gateway-status', connected: this.connected }));
|
|
152
192
|
}
|
|
153
193
|
}
|
|
154
194
|
|
|
155
|
-
removeBrowserClient(ws) { this.browserClients.delete(ws); }
|
|
195
|
+
removeBrowserClient(ws) { this.browserClients.delete(ws); this.browsersChanged(); }
|
|
156
196
|
|
|
157
197
|
|
|
158
198
|
addBroadcastTarget(fn) { this._externalBroadcastTargets.push(fn); }
|
package/server/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import { handleTranscribe } from './controllers/transcribe.js';
|
|
|
13
13
|
import { createGatewayMediaHandler } from './controllers/gateway-media.js';
|
|
14
14
|
import { handleStatic } from './controllers/static.js';
|
|
15
15
|
import { handleAgents } from './controllers/agents.js';
|
|
16
|
+
import { createTitleHandler } from './controllers/title.js';
|
|
16
17
|
import { createSettingsHandlers } from './controllers/settings.js';
|
|
17
18
|
import { createWorkspaceStore } from './store/workspace-store.js';
|
|
18
19
|
import { createExtrasStore } from './store/extras-store.js';
|
|
@@ -36,6 +37,7 @@ export function createApp(config = {}) {
|
|
|
36
37
|
const gatewayToken = config.gatewayToken !== undefined ? config.gatewayToken : authToken;
|
|
37
38
|
const gatewayUrl = config.gatewayUrl || GATEWAY_WS_URL;
|
|
38
39
|
const openaiApiKey = config.openaiApiKey || null;
|
|
40
|
+
const handleTitle = createTitleHandler(config.llm); // api.runtime.llm (plugin mode only)
|
|
39
41
|
|
|
40
42
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
41
43
|
|
|
@@ -162,6 +164,7 @@ export function createApp(config = {}) {
|
|
|
162
164
|
if (method === 'POST' && urlPath === '/api/transcribe') return await handleTranscribe(req, res, { openaiApiKey });
|
|
163
165
|
if (method === 'GET' && urlPath === '/api/health') return send(res, 200, { ok: true, workspace: getWorkspaces().active, uptime: process.uptime() });
|
|
164
166
|
if (method === 'GET' && urlPath === '/api/agents') return handleAgents(req, res);
|
|
167
|
+
if (method === 'POST' && urlPath === '/api/title') return await handleTitle(req, res);
|
|
165
168
|
|
|
166
169
|
// ClawChats-only extras (see EXTRAS.md)
|
|
167
170
|
if (method === 'GET' && urlPath === '/api/extras/project-styles') {
|