@clawchatsai/connector 0.1.26 → 0.1.28

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -0,0 +1,143 @@
1
+ // Share links (ClawChats extra), bring-your-own storage. The browser encrypts an artifact and sends only the
2
+ // ciphertext envelope here; the connector wraps it in a self-contained viewer page (share/viewer-page.js) and
3
+ // uploads that one HTML file to the user's own bucket (Cloudflare R2 today, any S3-compatible store later).
4
+ // The decryption key stays in the link fragment, so the storage provider can't read a share, and no
5
+ // ClawChats server is involved. Spec: clawchats repo, specs/sharing-and-artifacts.md.
6
+ //
7
+ // <dataDir>/share-storage.json derived S3 credentials + public URL (0600; never sent to the browser)
8
+ // <dataDir>/shares.json [{id, url, title, type, mode, createdAt, expiresAt}] (no keys)
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { send, sendError, parseBody } from '../util/http.js';
13
+ import { createS3Client } from '../share/s3.js';
14
+ import { setupR2 } from '../share/r2-setup.js';
15
+ import { buildSharePage } from '../share/viewer-page.js';
16
+
17
+ const ID_RE = /^[A-Za-z0-9_-]{22}$/;
18
+ const MAX_TITLE = 200;
19
+ const MAX_PAGE_BYTES = 5 * 1024 * 1024;
20
+ const TYPES = new Set(['html', 'svg', 'markdown', 'mermaid', 'csv', 'code']);
21
+ const SWEEP_MS = 60 * 60 * 1000;
22
+ const objectKey = id => `shares/${id}.html`;
23
+
24
+ export function validEnvelope(e) {
25
+ const b64u = s => typeof s === 'string' && /^[A-Za-z0-9_-]+$/.test(s);
26
+ if (!e || typeof e !== 'object' || e.v !== 1 || e.alg !== 'A256GCM' || !b64u(e.iv) || !b64u(e.ct)) return false;
27
+ if (e.kdf !== undefined) {
28
+ const k = e.kdf;
29
+ if (!k || k.name !== 'PBKDF2' || k.hash !== 'SHA-256' || !Number.isInteger(k.iter) || k.iter < 100000 || !b64u(k.salt)) return false;
30
+ }
31
+ return Object.keys(e).every(k => ['v', 'alg', 'iv', 'ct', 'kdf'].includes(k));
32
+ }
33
+
34
+ const newId = () => crypto.randomBytes(16).toString('base64url');
35
+
36
+ export function createShareHandlers({ dataDir, fetchImpl = globalThis.fetch, setup = setupR2, s3Factory = createS3Client, sweepTimer = true }) {
37
+ const storageFile = path.join(dataDir, 'share-storage.json');
38
+ const indexFile = path.join(dataDir, 'shares.json');
39
+
40
+ const writePrivate = (file, data) => {
41
+ const tmp = `${file}.tmp`;
42
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
43
+ fs.renameSync(tmp, file);
44
+ };
45
+ const readStorage = () => { try { return JSON.parse(fs.readFileSync(storageFile, 'utf8')); } catch { return null; } };
46
+ const readIndex = () => { try { const v = JSON.parse(fs.readFileSync(indexFile, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; } };
47
+ const isExpired = r => !!r.expiresAt && Date.parse(r.expiresAt) <= Date.now();
48
+ const client = cfg => s3Factory(cfg, fetchImpl);
49
+ const publicInfo = cfg => cfg && { provider: cfg.provider, bucket: cfg.bucket, publicBaseUrl: cfg.publicBaseUrl };
50
+
51
+ // Delete expired shares from storage (the box runs 24/7, so the connector is the expiry clock).
52
+ async function sweep() {
53
+ const cfg = readStorage();
54
+ const rows = readIndex();
55
+ const expired = rows.filter(isExpired);
56
+ if (!cfg || !expired.length) return;
57
+ const s3 = client(cfg);
58
+ const gone = new Set();
59
+ for (const r of expired) {
60
+ try { const { status } = await s3.delete(objectKey(r.id)); if (status < 300 || status === 404) gone.add(r.id); } catch {}
61
+ }
62
+ if (gone.size) writePrivate(indexFile, readIndex().filter(r => !gone.has(r.id)));
63
+ }
64
+ if (sweepTimer) setInterval(() => sweep().catch(() => {}), SWEEP_MS).unref();
65
+
66
+ // GET /api/extras/shares → {configured, storage, shares}
67
+ async function handleList(req, res) {
68
+ await sweep().catch(() => {});
69
+ const cfg = readStorage();
70
+ return send(res, 200, {
71
+ configured: !!cfg,
72
+ storage: publicInfo(cfg),
73
+ shares: readIndex().filter(r => !isExpired(r)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
74
+ });
75
+ }
76
+
77
+ // POST /api/extras/shares/storage {token} → set up the user's R2 bucket, prove it works, save credentials
78
+ async function handleSetup(req, res) {
79
+ const { token } = await parseBody(req);
80
+ let cfg;
81
+ try { cfg = await setup(token, { fetchImpl }); } catch (err) { return sendError(res, err.code ? 400 : 502, err.message); }
82
+ const s3 = client(cfg);
83
+ const probe = `shares/.clawchats-setup-${newId()}.txt`;
84
+ const put = await s3.put(probe, 'ClawChats share storage test', { contentType: 'text/plain; charset=utf-8' });
85
+ await s3.delete(probe).catch(() => {});
86
+ if (put.status !== 200) return sendError(res, 502, `Your bucket refused a test upload (HTTP ${put.status}). Check the token has Admin Read & Write.`);
87
+ writePrivate(storageFile, cfg);
88
+ return send(res, 200, { storage: publicInfo(cfg) });
89
+ }
90
+
91
+ // DELETE /api/extras/shares/storage → forget the credentials (existing links keep working until deleted)
92
+ function handleForgetStorage(req, res) {
93
+ fs.rmSync(storageFile, { force: true });
94
+ return send(res, 200, { ok: true });
95
+ }
96
+
97
+ // POST /api/extras/shares {envelope, expiresAt?, title, type} → {share}
98
+ async function handleCreate(req, res) {
99
+ const cfg = readStorage();
100
+ if (!cfg) return sendError(res, 409, 'Connect your Cloudflare storage first');
101
+ const { envelope, expiresAt, title, type } = await parseBody(req);
102
+ if (!validEnvelope(envelope)) return sendError(res, 400, 'Missing or malformed encrypted envelope');
103
+ if (!TYPES.has(type)) return sendError(res, 400, 'Unsupported artifact type');
104
+ let expires = null;
105
+ if (expiresAt != null) {
106
+ const t = Date.parse(expiresAt);
107
+ if (!Number.isFinite(t) || t <= Date.now()) return sendError(res, 400, 'Expiry must be in the future');
108
+ expires = new Date(t).toISOString();
109
+ }
110
+ const page = buildSharePage(envelope);
111
+ if (Buffer.byteLength(page) > MAX_PAGE_BYTES) return sendError(res, 413, 'This artifact is too big to share (5 MB max)');
112
+
113
+ const id = newId();
114
+ const put = await client(cfg).put(objectKey(id), page, { contentType: 'text/html; charset=utf-8', cacheControl: 'no-cache' });
115
+ if (put.status !== 200) return sendError(res, 502, `Your storage refused the upload (HTTP ${put.status})`);
116
+
117
+ const share = {
118
+ id,
119
+ url: `${cfg.publicBaseUrl}/${objectKey(id)}`,
120
+ title: String(title || 'Shared artifact').slice(0, MAX_TITLE),
121
+ type,
122
+ mode: envelope.kdf ? 'password' : 'link',
123
+ createdAt: new Date().toISOString(),
124
+ expiresAt: expires,
125
+ };
126
+ writePrivate(indexFile, [share, ...readIndex()]);
127
+ sweep().catch(() => {});
128
+ return send(res, 201, { share });
129
+ }
130
+
131
+ // DELETE /api/extras/shares/:id → delete the page from the bucket, then from the index
132
+ async function handleRevoke(req, res, id) {
133
+ if (!ID_RE.test(id)) return sendError(res, 400, 'Bad share id');
134
+ const cfg = readStorage();
135
+ if (!cfg) return sendError(res, 409, 'Connect your Cloudflare storage first');
136
+ const { status } = await client(cfg).delete(objectKey(id));
137
+ if (status >= 300 && status !== 404) return sendError(res, 502, `Your storage refused the delete (HTTP ${status})`);
138
+ writePrivate(indexFile, readIndex().filter(r => r.id !== id));
139
+ return send(res, 200, { ok: true });
140
+ }
141
+
142
+ return { handleList, handleSetup, handleForgetStorage, handleCreate, handleRevoke, sweep };
143
+ }
@@ -0,0 +1,145 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { Readable } from 'node:stream';
7
+ import { createShareHandlers, validEnvelope } from './shares.js';
8
+ import { buildSharePage } from '../share/viewer-page.js';
9
+ import { decryptShare, needsPassword } from '../share/viewer-decrypt.js';
10
+
11
+ const CFG = { provider: 'r2', endpoint: 'https://acct.r2.cloudflarestorage.com', region: 'auto', bucket: 'clawchats-shares', accessKeyId: 'id', secretAccessKey: 'sk', publicBaseUrl: 'https://pub-x.r2.dev' };
12
+ const ENV = { v: 1, alg: 'A256GCM', iv: 'aaa', ct: 'bbb' };
13
+
14
+ function call(fn, body, ...args) {
15
+ const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
16
+ return new Promise((resolve, reject) => {
17
+ const res = { writeHead(status) { this.status = status; }, end(data) { resolve({ status: this.status, body: JSON.parse(data) }); } };
18
+ Promise.resolve(fn(req, res, ...args)).catch(reject);
19
+ });
20
+ }
21
+
22
+ function setup({ configured = true, putStatus = 200, deleteStatus = 204, setupImpl } = {}) {
23
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shares-'));
24
+ if (configured) fs.writeFileSync(path.join(dataDir, 'share-storage.json'), JSON.stringify(CFG));
25
+ const ops = [];
26
+ const s3Factory = cfg => ({
27
+ put: async (key, body, opts) => { ops.push({ op: 'put', key, body, opts, cfg }); return { status: putStatus }; },
28
+ delete: async key => { ops.push({ op: 'delete', key }); return { status: deleteStatus }; },
29
+ });
30
+ const h = createShareHandlers({ dataDir, s3Factory, setup: setupImpl || (async () => CFG), sweepTimer: false });
31
+ return { dataDir, ops, h };
32
+ }
33
+
34
+ // Same envelope format as the browser (clawchats frontend/share/share-crypto.js).
35
+ async function encrypt(payload, password) {
36
+ const b64u = b => Buffer.from(b).toString('base64url');
37
+ const iv = crypto.getRandomValues(new Uint8Array(12));
38
+ let key, secret = null, kdf;
39
+ if (password) {
40
+ const salt = crypto.getRandomValues(new Uint8Array(16));
41
+ kdf = { name: 'PBKDF2', hash: 'SHA-256', iter: 600000, salt: b64u(salt) };
42
+ const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
43
+ key = await crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', iterations: 600000, salt }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
44
+ } else {
45
+ const raw = crypto.getRandomValues(new Uint8Array(32));
46
+ secret = b64u(raw);
47
+ key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt']);
48
+ }
49
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(JSON.stringify(payload)));
50
+ return { envelope: { v: 1, alg: 'A256GCM', iv: b64u(iv), ct: b64u(ct), ...(kdf ? { kdf } : {}) }, secret };
51
+ }
52
+
53
+ test('create uploads one self-contained HTML page to the user bucket and records the share without keys', async () => {
54
+ const { dataDir, ops, h } = setup();
55
+ const r = await call(h.handleCreate, { envelope: ENV, title: 'Login flow', type: 'mermaid' });
56
+ assert.equal(r.status, 201);
57
+ const { share } = r.body;
58
+ assert.match(share.id, /^[A-Za-z0-9_-]{22}$/);
59
+ assert.equal(share.url, `https://pub-x.r2.dev/shares/${share.id}.html`);
60
+ assert.equal(ops[0].key, `shares/${share.id}.html`);
61
+ assert.equal(ops[0].opts.contentType, 'text/html; charset=utf-8');
62
+ assert.ok(ops[0].body.includes('"ct":"bbb"'), 'ciphertext embedded');
63
+ assert.ok(!/\{\{(ENVELOPE_JSON|DECRYPT_JS)\}\}/.test(ops[0].body), 'no unfilled placeholders');
64
+ const saved = JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8'));
65
+ assert.equal(saved[0].id, share.id);
66
+ assert.equal(fs.statSync(path.join(dataDir, 'shares.json')).mode & 0o777, 0o600);
67
+ const list = await call(h.handleList);
68
+ assert.equal(list.body.configured, true);
69
+ assert.deepEqual(list.body.storage, { provider: 'r2', bucket: 'clawchats-shares', publicBaseUrl: 'https://pub-x.r2.dev' });
70
+ assert.ok(!JSON.stringify(list.body).includes('sk'), 'credentials never leave the connector');
71
+ });
72
+
73
+ test('without storage the list says so and create asks to connect', async () => {
74
+ const { h } = setup({ configured: false });
75
+ assert.equal((await call(h.handleList)).body.configured, false);
76
+ assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'html' })).status, 409);
77
+ });
78
+
79
+ test('setup saves derived credentials (0600) after a successful test upload, and can be forgotten', async () => {
80
+ const { dataDir, ops, h } = setup({ configured: false });
81
+ const r = await call(h.handleSetup, { token: 't'.repeat(40) });
82
+ assert.equal(r.status, 200);
83
+ assert.equal(r.body.storage.publicBaseUrl, 'https://pub-x.r2.dev');
84
+ assert.deepEqual(ops.map(o => o.op), ['put', 'delete'], 'probe uploaded and removed');
85
+ const file = path.join(dataDir, 'share-storage.json');
86
+ assert.equal(fs.statSync(file).mode & 0o777, 0o600);
87
+ assert.equal((await call(h.handleForgetStorage)).status, 200);
88
+ assert.equal(fs.existsSync(file), false);
89
+ });
90
+
91
+ test('setup errors are reported and nothing is saved', async () => {
92
+ const bad = setup({ configured: false, setupImpl: async () => { throw Object.assign(new Error('Cloudflare rejected this token.'), { code: 'rejected' }); } });
93
+ assert.deepEqual(await call(bad.h.handleSetup, { token: 'x' }), { status: 400, body: { error: 'Cloudflare rejected this token.' } });
94
+ const refused = setup({ configured: false, putStatus: 403 });
95
+ assert.equal((await call(refused.h.handleSetup, { token: 't'.repeat(40) })).status, 502);
96
+ assert.equal(fs.existsSync(path.join(refused.dataDir, 'share-storage.json')), false);
97
+ });
98
+
99
+ test('rejects plaintext-looking or malformed envelopes, unknown types and past expiry before uploading', async () => {
100
+ const { ops, h } = setup();
101
+ assert.equal((await call(h.handleCreate, { envelope: { ...ENV, content: 'plain' }, type: 'html' })).status, 400);
102
+ assert.equal((await call(h.handleCreate, { envelope: { ...ENV, ct: 'no spaces!' }, type: 'html' })).status, 400);
103
+ assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'exe' })).status, 400);
104
+ assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'html', expiresAt: '2020-01-01' })).status, 400);
105
+ assert.equal(ops.length, 0);
106
+ assert.equal(validEnvelope({ ...ENV, kdf: { name: 'PBKDF2', hash: 'SHA-256', iter: 1000, salt: 'aa' } }), false, 'weak KDF refused');
107
+ });
108
+
109
+ test('revoke deletes the page from the bucket and drops the row; a 404 still clears it', async () => {
110
+ const { dataDir, ops, h } = setup({ deleteStatus: 404 });
111
+ const { body } = await call(h.handleCreate, { envelope: ENV, type: 'html' });
112
+ assert.equal((await call(h.handleRevoke, undefined, body.share.id)).status, 200);
113
+ assert.deepEqual(ops[1], { op: 'delete', key: `shares/${body.share.id}.html` });
114
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8')), []);
115
+ assert.equal((await call(h.handleRevoke, undefined, '../etc')).status, 400);
116
+ });
117
+
118
+ test('sweep deletes expired shares from the bucket and the list', async () => {
119
+ const { dataDir, ops, h } = setup();
120
+ const old = 'a'.repeat(22), keep = 'b'.repeat(22);
121
+ fs.writeFileSync(path.join(dataDir, 'shares.json'), JSON.stringify([
122
+ { id: old, createdAt: '2026-01-01T00:00:00Z', expiresAt: '2026-01-02T00:00:00Z' },
123
+ { id: keep, createdAt: '2026-01-01T00:00:00Z', expiresAt: null },
124
+ ]));
125
+ const list = await call(h.handleList);
126
+ assert.deepEqual(list.body.shares.map(s => s.id), [keep]);
127
+ assert.deepEqual(ops, [{ op: 'delete', key: `shares/${old}.html` }]);
128
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8')).map(s => s.id), [keep]);
129
+ });
130
+
131
+ test('share page embeds the envelope safely, and its decrypt code opens link and password shares', async () => {
132
+ const payload = { v: 1, kind: 'artifact', title: 'T', type: 'html', content: '</script><script>alert(1)</script>' };
133
+ const link = await encrypt(payload);
134
+ const page = buildSharePage({ ...link.envelope });
135
+ const m = page.match(/<script type="application\/json" id="share-envelope">([^<]*)<\/script>/);
136
+ assert.ok(m, 'envelope sits in its own JSON script element');
137
+ assert.deepEqual(JSON.parse(m[1]), link.envelope);
138
+ assert.ok(page.includes('async function decryptShare'), 'decrypt code inlined');
139
+ assert.ok(!/^export /m.test(page), 'no ES module syntax left in the inline script');
140
+ assert.deepEqual(await decryptShare(link.envelope, { secret: link.secret }), payload);
141
+ const pw = await encrypt(payload, 'correct horse battery');
142
+ assert.equal(needsPassword(pw.envelope), true);
143
+ assert.deepEqual(await decryptShare(pw.envelope, { password: 'correct horse battery' }), payload);
144
+ await assert.rejects(decryptShare(pw.envelope, { password: 'nope' }), { code: 'bad-password' });
145
+ });
@@ -19,12 +19,12 @@ export function normalizeTitle(raw) {
19
19
  }
20
20
 
21
21
  /**
22
+ * Direct completion where the main model's provider has a direct transport; CLI and harness
23
+ * runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
22
24
  * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
23
25
  */
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) {
26
+ function createCompletion(llm) {
27
+ return async function complete(message) {
28
28
  const base = { messages: [{ role: 'user', content: message }], systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 };
29
29
  try {
30
30
  return await llm.complete(base);
@@ -32,7 +32,23 @@ export function createTitleHandler(llm) {
32
32
  if (err?.code === 'LLM_COMPLETION_NOT_AUTHORIZED') throw err;
33
33
  return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
34
34
  }
35
- }
35
+ };
36
+ }
37
+
38
+ /** message → title or null (null also when the host has no plugin model completion). */
39
+ export function createTitler(llm) {
40
+ const complete = createCompletion(llm);
41
+ return async message => {
42
+ if (typeof llm?.complete !== 'function' || typeof message !== 'string' || !message.trim()) return null;
43
+ return normalizeTitle((await complete(Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join('')))?.text);
44
+ };
45
+ }
46
+
47
+ /**
48
+ * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
49
+ */
50
+ export function createTitleHandler(llm) {
51
+ const complete = createCompletion(llm);
36
52
 
37
53
  return async function handleTitle(req, res) {
38
54
  if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
package/server/gateway.js CHANGED
@@ -91,6 +91,9 @@ export class GatewayClient {
91
91
  return;
92
92
  }
93
93
 
94
+ // Connector-side observers (team chat run tracking) see every event before the lens filters.
95
+ if (msg.type === 'event' && this.onEvent) { try { this.onEvent(msg); } catch (e) { console.error('[gateway] event observer:', e.message); } }
96
+
94
97
  if (msg.type === 'event' && msg.event === 'connect.challenge') {
95
98
  this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
96
99
  return;
package/server/index.js CHANGED
@@ -13,11 +13,14 @@ 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
+ import { createTitleHandler, createTitler } from './controllers/title.js';
17
17
  import { createSettingsHandlers } from './controllers/settings.js';
18
+ import { createShareHandlers } from './controllers/shares.js';
18
19
  import { createWorkspaceStore } from './store/workspace-store.js';
19
20
  import { createExtrasStore } from './store/extras-store.js';
21
+ import { createTeamStore } from './store/team-store.js';
20
22
  import { SessionLens } from './session-lens.js';
23
+ import { TeamCoordinator } from './team.js';
21
24
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
22
25
 
23
26
  // PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
@@ -38,6 +41,7 @@ export function createApp(config = {}) {
38
41
  const gatewayUrl = config.gatewayUrl || GATEWAY_WS_URL;
39
42
  const openaiApiKey = config.openaiApiKey || null;
40
43
  const handleTitle = createTitleHandler(config.llm); // api.runtime.llm (plugin mode only)
44
+ const shares = createShareHandlers({ dataDir: DATA_DIR }); // share links → the user's own bucket
41
45
 
42
46
  fs.mkdirSync(DATA_DIR, { recursive: true });
43
47
 
@@ -70,7 +74,11 @@ export function createApp(config = {}) {
70
74
  const extras = createExtrasStore(() => globalDbCache.get());
71
75
  try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
72
76
  catch (e) { console.error('[extras] style seed failed:', e.message); }
73
- gatewayClient.lens = new SessionLens({ broadcast, request: (m, p, t) => gatewayClient.request(m, p, t), extras });
77
+ const gwRequest = (m, p, t) => gatewayClient.request(m, p, t);
78
+ // Team chats: several agents in one thread (server/team.js).
79
+ const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm) });
80
+ gatewayClient.onEvent = msg => team.onGatewayEvent(msg);
81
+ gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
74
82
 
75
83
  // A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
76
84
  // spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
@@ -198,6 +206,12 @@ export function createApp(config = {}) {
198
206
  broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
199
207
  return send(res, 200, { ok: true });
200
208
  }
209
+ // Share links: browser-encrypted envelopes uploaded to the user's own bucket (controllers/shares.js)
210
+ if (method === 'GET' && urlPath === '/api/extras/shares') return await shares.handleList(req, res);
211
+ if (method === 'POST' && urlPath === '/api/extras/shares/storage') return await shares.handleSetup(req, res);
212
+ if (method === 'DELETE' && urlPath === '/api/extras/shares/storage') return shares.handleForgetStorage(req, res);
213
+ if (method === 'POST' && urlPath === '/api/extras/shares') return await shares.handleCreate(req, res);
214
+ if ((p = matchRoute(method, urlPath, 'DELETE /api/extras/shares/:id'))) return await shares.handleRevoke(req, res, p.id);
201
215
  if (method === 'GET' && urlPath === '/api/extras/bookmarks') return send(res, 200, { bookmarks: extras.listBookmarks() });
202
216
  if (method === 'POST' && urlPath === '/api/extras/bookmarks') {
203
217
  const bookmark = extras.addBookmark(uuid(), await parseBody(req));
@@ -216,6 +230,50 @@ export function createApp(config = {}) {
216
230
  return send(res, 200, { ok: true });
217
231
  }
218
232
 
233
+ // Team chats (server/team.js; EXTRAS.md). Room keys contain ':' and are URL-encoded.
234
+ if (method === 'GET' && urlPath === '/api/team') return send(res, 200, { rooms: team.rooms() });
235
+ if (method === 'POST' && urlPath === '/api/team') {
236
+ const body = await parseBody(req);
237
+ try { return send(res, 200, { room: await team.createRoom(body) }); }
238
+ catch (e) { return sendError(res, 400, e.message); }
239
+ }
240
+ if ((p = matchRoute(method, urlPath, 'GET /api/team/:room'))) {
241
+ const room = team.room(p.room);
242
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
243
+ }
244
+ if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
245
+ const room = team.setDiscuss(p.room, (await parseBody(req)).discuss);
246
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
247
+ }
248
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
249
+ const { agentId } = await parseBody(req);
250
+ if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
251
+ try {
252
+ const room = await team.addAgent(p.room, agentId);
253
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
254
+ } catch (e) { return sendError(res, 400, e.message); }
255
+ }
256
+ if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
257
+ try {
258
+ const room = team.removeAgent(p.room, p.agentId);
259
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
260
+ } catch (e) { return sendError(res, 400, e.message); }
261
+ }
262
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/send'))) {
263
+ try { return send(res, 200, await team.send(p.room, await parseBody(req))); }
264
+ catch (e) { return sendError(res, 400, e.message); }
265
+ }
266
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/unconvert'))) {
267
+ try {
268
+ const sourceKey = await team.unconvert(p.room);
269
+ return sourceKey ? send(res, 200, { sourceKey }) : sendError(res, 404, 'Not a team chat');
270
+ } catch (e) { return sendError(res, 400, e.message); }
271
+ }
272
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/stop'))) {
273
+ await team.stop(p.room);
274
+ return send(res, 200, { ok: true });
275
+ }
276
+
219
277
 
220
278
  sendError(res, 404, `Not found: ${method} ${urlPath}`);
221
279
  } catch (err) {
@@ -269,6 +327,7 @@ export function createApp(config = {}) {
269
327
  shutdown: closeAll,
270
328
  gatewayClient,
271
329
  extras,
330
+ team,
272
331
  setupBrowserWs,
273
332
  debugLogger,
274
333
  dataDir: DATA_DIR,
@@ -14,6 +14,8 @@
14
14
  //
15
15
  // Visible = a root, direct, user chat: `agent:<id>:dashboard:<id>` (gateway-created) or
16
16
  // `agent:<id>:<project>:chat:<id>` (legacy ClawChats). Everything else is hidden.
17
+ // Team chat working sessions (server/team.js) are hidden too, but their run events are
18
+ // forwarded: the room shows each agent's reply streaming.
17
19
 
18
20
  const DASHBOARD_KEY = /^agent:[^:]+:dashboard:[^:]+$/;
19
21
  const LEGACY_CHAT_KEY = /^agent:[^:]+:[^:]+:chat:[^:]+$/;
@@ -116,11 +118,13 @@ export class SessionLens {
116
118
  * @param {(data: string) => void} opts.broadcast send a frame to all browsers
117
119
  * @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} [opts.request] connector-originated gateway RPC
118
120
  * @param {object} [opts.extras] ExtrasStore (project style side effects)
121
+ * @param {object} [opts.team] TeamCoordinator (`isWorkKey`, `onSessionDeleted`)
119
122
  */
120
- constructor({ broadcast, request, extras, logger = console }) {
123
+ constructor({ broadcast, request, extras, team, logger = console }) {
121
124
  this.broadcast = broadcast;
122
125
  this.request = request;
123
126
  this.extras = extras;
127
+ this.team = team;
124
128
  this.log = logger;
125
129
  this.hidden = new Set(); // candidate-shaped keys a row revealed as not a user chat
126
130
  this.pending = new Map(); // browser req id -> { method, params }
@@ -137,16 +141,16 @@ export class SessionLens {
137
141
  const verdict = rowVerdict(row);
138
142
  if (verdict === true) this.hidden.add(key);
139
143
  else if (verdict === false) this.hidden.delete(key);
140
- return !this.hidden.has(key);
144
+ return this.isVisible(key);
141
145
  }
142
146
 
143
147
  isVisible(key) {
144
- return isCandidateKey(key) && !this.hidden.has(key);
148
+ return isCandidateKey(key) && !this.hidden.has(key) && !this.team?.isWorkKey(key);
145
149
  }
146
150
 
147
- /** chat/agent run events: visible chats plus the connector's own utility sessions. */
151
+ /** chat/agent run events: visible chats, team chat working sessions, utility sessions. */
148
152
  forwardsRunEvent(key) {
149
- return isUtilityKey(key) || this.isVisible(key);
153
+ return isUtilityKey(key) || this.isVisible(key) || !!this.team?.isWorkKey(key);
150
154
  }
151
155
 
152
156
  /** Seed `hidden` from a full roster so partial events of child sessions stay hidden. */
@@ -169,6 +173,9 @@ export class SessionLens {
169
173
  if (!payload || typeof payload !== 'object') return null;
170
174
  const key = payload.sessionKey;
171
175
  if (!key) return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) }; // catalog/groups
176
+ if (payload.reason === 'delete' && this.team) {
177
+ try { this.team.onSessionDeleted(key); } catch (e) { this.log.warn?.(`[lens] team delete: ${e.message}`); }
178
+ }
172
179
  if (!this.observe(key, payload.session || payload)) return null;
173
180
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
174
181
  return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };
@@ -0,0 +1,61 @@
1
+ // One-token setup for share links on the user's own Cloudflare R2: from a single R2 API token (Admin Read &
2
+ // Write), find the account, create the bucket, turn on its public r2.dev address, and derive S3 credentials
3
+ // (Cloudflare documents: Access Key ID = token id, Secret = SHA-256 of the token value). The raw token is not
4
+ // kept; the derived credentials are stored by the caller on this machine only.
5
+ import crypto from 'node:crypto';
6
+
7
+ export const BUCKET = 'clawchats-shares';
8
+ const API = 'https://api.cloudflare.com/client/v4';
9
+
10
+ export class SetupError extends Error {
11
+ constructor(message, code) { super(message); this.code = code; }
12
+ }
13
+
14
+ export async function setupR2(token, { fetchImpl = globalThis.fetch } = {}) {
15
+ token = String(token || '').trim();
16
+ if (!/^[A-Za-z0-9_-]{30,}$/.test(token)) throw new SetupError('That doesn’t look like a Cloudflare API token. Copy the “Token value”.', 'bad-token');
17
+
18
+ const cf = async (path, init = {}) => {
19
+ const res = await fetchImpl(`${API}${path}`, {
20
+ ...init,
21
+ headers: { authorization: `Bearer ${token}`, ...(init.body ? { 'content-type': 'application/json' } : {}) },
22
+ signal: AbortSignal.timeout(20000),
23
+ });
24
+ const data = await res.json().catch(() => ({}));
25
+ return { status: res.status, data };
26
+ };
27
+
28
+ const accounts = await cf('/accounts');
29
+ if (accounts.status === 401 || accounts.status === 403 || !accounts.data.success) throw new SetupError('Cloudflare rejected this token. Create a new one and paste its “Token value”.', 'rejected');
30
+ const list = accounts.data.result || [];
31
+ if (list.length !== 1) throw new SetupError('This token sees more than one Cloudflare account. Create it as an account token for one account.', 'accounts');
32
+ const accountId = list[0].id;
33
+
34
+ // Token id = S3 Access Key ID. Account tokens verify under the account; user tokens under /user.
35
+ let verify = await cf(`/accounts/${accountId}/tokens/verify`);
36
+ if (!verify.data.success) verify = await cf('/user/tokens/verify');
37
+ const tokenId = verify.data.result?.id;
38
+ if (!verify.data.success || verify.data.result?.status !== 'active' || !tokenId) throw new SetupError('This token isn’t active.', 'inactive');
39
+
40
+ const created = await cf(`/accounts/${accountId}/r2/buckets`, { method: 'POST', body: JSON.stringify({ name: BUCKET }) });
41
+ const exists = created.status === 409 || (created.data.errors || []).some(e => /exist/i.test(e.message || ''));
42
+ if (!created.data.success && !exists) {
43
+ if (created.status === 403) throw new SetupError('This token can’t manage R2. Give it “Admin Read & Write” (or Workers R2 Storage: Edit).', 'permission');
44
+ throw new SetupError(`Couldn’t create the bucket: ${(created.data.errors || [])[0]?.message || `HTTP ${created.status}`}`, 'bucket');
45
+ }
46
+
47
+ const domain = await cf(`/accounts/${accountId}/r2/buckets/${BUCKET}/domains/managed`, { method: 'PUT', body: JSON.stringify({ enabled: true }) });
48
+ const host = domain.data.result?.domain;
49
+ if (!domain.data.success || !host) throw new SetupError(`Couldn’t turn on the bucket’s public address: ${(domain.data.errors || [])[0]?.message || `HTTP ${domain.status}`}`, 'domain');
50
+
51
+ return {
52
+ provider: 'r2',
53
+ accountId,
54
+ endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
55
+ region: 'auto',
56
+ bucket: BUCKET,
57
+ accessKeyId: tokenId,
58
+ secretAccessKey: crypto.createHash('sha256').update(token).digest('hex'),
59
+ publicBaseUrl: `https://${host}`,
60
+ };
61
+ }
@@ -0,0 +1,50 @@
1
+ // Minimal S3 client (AWS Signature V4) for share links: PUT / DELETE / GET of one object. Works with any
2
+ // S3-compatible store; R2 uses region "auto". No SDK: the connector only ever needs these three calls.
3
+ import crypto from 'node:crypto';
4
+
5
+ const sha256Hex = data => crypto.createHash('sha256').update(data).digest('hex');
6
+ const hmac = (key, data) => crypto.createHmac('sha256', key).update(data).digest();
7
+ const encodeKey = key => key.split('/').map(encodeURIComponent).join('/');
8
+
9
+ /**
10
+ * @param {{endpoint: string, bucket: string, region?: string, accessKeyId: string, secretAccessKey: string}} cfg
11
+ * @param {typeof fetch} [fetchImpl]
12
+ */
13
+ export function createS3Client(cfg, fetchImpl = globalThis.fetch) {
14
+ const endpoint = new URL(cfg.endpoint);
15
+ const region = cfg.region || 'auto';
16
+
17
+ async function request(method, key, { body = '', contentType, cacheControl, now = new Date() } = {}) {
18
+ const payload = typeof body === 'string' ? Buffer.from(body) : body;
19
+ const payloadHash = sha256Hex(payload);
20
+ const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
21
+ const day = amzDate.slice(0, 8);
22
+ const path = `/${encodeURIComponent(cfg.bucket)}/${encodeKey(key)}`;
23
+
24
+ const headers = { host: endpoint.host, 'x-amz-content-sha256': payloadHash, 'x-amz-date': amzDate };
25
+ if (contentType) headers['content-type'] = contentType;
26
+ if (cacheControl) headers['cache-control'] = cacheControl;
27
+ const names = Object.keys(headers).sort();
28
+ const canonical = [method, path, '', ...names.map(n => `${n}:${headers[n]}`), '', names.join(';'), payloadHash].join('\n');
29
+ const scope = `${day}/${region}/s3/aws4_request`;
30
+ const toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonical)].join('\n');
31
+ const kSigning = hmac(hmac(hmac(hmac(`AWS4${cfg.secretAccessKey}`, day), region), 's3'), 'aws4_request');
32
+ const signature = crypto.createHmac('sha256', kSigning).update(toSign).digest('hex');
33
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${cfg.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`;
34
+ delete headers.host;
35
+
36
+ const res = await fetchImpl(`${endpoint.origin}${path}`, {
37
+ method,
38
+ headers,
39
+ body: method === 'PUT' ? payload : undefined,
40
+ signal: AbortSignal.timeout(20000),
41
+ });
42
+ return { status: res.status, text: await res.text().catch(() => '') };
43
+ }
44
+
45
+ return {
46
+ put: (key, body, opts) => request('PUT', key, { body, ...opts }),
47
+ delete: key => request('DELETE', key),
48
+ get: key => request('GET', key),
49
+ };
50
+ }