@clawchatsai/connector 0.1.36 → 0.1.37

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.36",
3
+ "version": "0.1.37",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
package/server/index.js CHANGED
@@ -289,6 +289,9 @@ export function createApp(config = {}) {
289
289
  if (room && body.discuss !== undefined) {
290
290
  try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
291
291
  }
292
+ if (room && body.mentionOnly !== undefined) {
293
+ try { room = team.setMentionOnly(p.room, body.mentionOnly); } catch (e) { return sendError(res, 400, e.message); }
294
+ }
292
295
  if (room && body.rounds !== undefined) {
293
296
  try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
294
297
  }
@@ -298,16 +301,16 @@ export function createApp(config = {}) {
298
301
  const { personId, history } = await parseBody(req);
299
302
  if (typeof personId !== 'string' || !personId) return sendError(res, 400, 'personId is required');
300
303
  try {
301
- const room = await team.addPerson(p.room, personId, { history });
304
+ const room = await team.addPerson(p.room, personId, { history, quietAgents: true });
302
305
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
303
306
  } catch (e) { return sendError(res, 400, e.message); }
304
307
  }
305
308
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/people/:personId'))) {
306
- const room = team.removePerson(p.room, p.personId);
309
+ const room = await team.removePerson(p.room, p.personId);
307
310
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat you host');
308
311
  }
309
312
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/leave'))) {
310
- try { return send(res, 200, { room: await team.leave(p.room) }); }
313
+ try { return send(res, 200, { room: await team.leave(p.room, await parseBody(req).catch(() => ({}))) }); }
311
314
  catch (e) { return sendError(res, 400, e.message); }
312
315
  }
313
316
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
@@ -320,7 +323,7 @@ export function createApp(config = {}) {
320
323
  }
321
324
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
322
325
  try {
323
- const room = team.removeAgent(p.room, p.agentId);
326
+ const room = await team.removeAgent(p.room, p.agentId);
324
327
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
325
328
  } catch (e) { return sendError(res, 400, e.message); }
326
329
  }
@@ -94,6 +94,7 @@ export class SharingManager {
94
94
 
95
95
  /** `share-list` from the signal server. Ends links/grants for shares that are gone. */
96
96
  setShares(shares) {
97
+ this._nameCache = null;
97
98
  const first = !this.serverEnabled;
98
99
  this.serverEnabled = true;
99
100
  this._shares = Array.isArray(shares) ? shares : [];
@@ -102,14 +103,43 @@ export class SharingManager {
102
103
  for (const s of this._localGrants()) if (!live.has(s.share_id) && !this._shares.some(x => x.id === s.share_id && x.status === 'pending')) this._revokeLocal(s.share_id);
103
104
  this._changed();
104
105
  if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
106
+ this._sharesChanged();
107
+ this._presenceTick();
105
108
  }
106
109
 
110
+ /**
111
+ * Presence: a gateway that asked for someone's agents is the one that can open the link to them, so
112
+ * it keeps one open (and re-opens it when it drops). Without that, a room host that only *granted*
113
+ * shares couldn't reach its people until they happened to use an agent: copies would sit unsent.
114
+ * Retries back off per share (15 s up to 10 min); a failed dial costs nothing.
115
+ */
116
+ _presenceTick() {
117
+ clearTimeout(this._presenceTimer);
118
+ if (!this.serverEnabled || this._closed) return;
119
+ for (const s of this._shares) {
120
+ if (s.as !== 'requester' || s.status !== 'active' || !this._verifiedGrant(s)) continue;
121
+ const cur = this._links.get(s.id);
122
+ const b = (this._backoff ??= new Map());
123
+ if ((cur?.ready && !cur.closed) || this._linking.has(s.id)) { b.delete(s.id); continue; }
124
+ const st = b.get(s.id) || { next: 0, wait: 15_000 };
125
+ if (Date.now() < st.next) continue;
126
+ b.set(s.id, { next: Date.now() + st.wait, wait: Math.min(st.wait * 2, 10 * 60_000) });
127
+ this._link(s.id).then(() => b.delete(s.id)).catch(e => this.log.info?.(`[sharing] presence ${s.id}: ${e.message}`));
128
+ }
129
+ this._presenceTimer = setTimeout(() => this._presenceTick(), 15_000);
130
+ this._presenceTimer.unref?.();
131
+ }
132
+
133
+ /** Team chats follow the connection: people and agents of an ended share leave their rooms. */
134
+ _sharesChanged() { try { this.onSharesChanged?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } }
135
+
107
136
  /** The signal server says a share ended (revoke/decline): stop at once. */
108
137
  onShareRevoked(shareId) {
109
138
  this._revokeLocal(shareId);
110
139
  this._links.get(shareId)?.close();
111
140
  this._links.delete(shareId);
112
141
  this._changed();
142
+ this._sharesChanged();
113
143
  }
114
144
 
115
145
  _changed() { this.broadcast(JSON.stringify({ type: 'clawchats', event: 'sharing-changed' })); }
@@ -207,7 +237,7 @@ export class SharingManager {
207
237
  if (!s) throw new Error('No such request');
208
238
  if (!s.requester?.pubKey || !s.requester?.gatewayId) throw new Error("The requester's gateway hasn't connected with sharing support yet");
209
239
  const list = (Array.isArray(agents) ? agents : []).filter(a => a && typeof a.id === 'string' && a.id).map(a => ({ id: a.id, name: String(a.name || a.id).slice(0, 80) }));
210
- if (!list.length) throw new Error('Pick at least one agent');
240
+ // No agents is fine: a connection can be just for chatting (team chats with people).
211
241
  if (!ACCESS_MODES[access]) throw new Error('Unknown access level');
212
242
  // A changed grant keeps the requester key it was first approved for: the signal server can't swap it.
213
243
  const prev = this._db().prepare('SELECT grant_json FROM peer_grants WHERE share_id = ?').get(shareId);
@@ -314,6 +344,43 @@ export class SharingManager {
314
344
 
315
345
  contact(personId) { return this.contacts().find(c => c.personId === personId) || null; }
316
346
 
347
+ /** Whether any share (either direction, verified or not) is active with that gateway. */
348
+ hasShareWith(gatewayId) {
349
+ return this._shares.some(s => s.status === 'active' && this._other(s).gatewayId === gatewayId);
350
+ }
351
+
352
+ /**
353
+ * How a person's name shows next to their agents ("Jarvis · Kamil"): the first name, or the full
354
+ * name when two people here (this gateway's person included) share a first name.
355
+ */
356
+ labelOf(gatewayId, fullName) {
357
+ const first = n => cleanName(String(n || '').trim().split(/[\s@]/)[0], 30) || 'Someone';
358
+ // Everyone known here by id (cached: remoteAgents() calls this per agent, and contacts() verifies grants).
359
+ if (!this._nameCache || Date.now() - this._nameCache.at > 5000) {
360
+ const known = new Map();
361
+ for (const c of this.contacts()) known.set(c.personId, c.name);
362
+ if (this.gatewayId?.()) known.set(this.gatewayId(), this.selfName() || '');
363
+ this._nameCache = { at: Date.now(), known };
364
+ }
365
+ const people = new Map(this._nameCache.known);
366
+ if (gatewayId && fullName) people.set(gatewayId, fullName);
367
+ const mine = first(fullName);
368
+ const clash = [...people].some(([id, n]) => id !== gatewayId && first(n).toLowerCase() === mine.toLowerCase());
369
+ return clash ? cleanName(fullName, 60) || mine : mine;
370
+ }
371
+
372
+ /** The room (and who asked) behind a guest session of this gateway, or null. */
373
+ guestSessionOf(key) {
374
+ if (!this._guestKeys) {
375
+ this._guestKeys = new Map();
376
+ for (const r of this._db().prepare('SELECT share_id, room_id, session_key FROM peer_sessions').all()) {
377
+ const g = this._grant(r.share_id);
378
+ if (g?.grant.requesterGatewayId) this._guestKeys.set(r.session_key, { requesterGatewayId: g.grant.requesterGatewayId, roomId: r.room_id, shareId: r.share_id });
379
+ }
380
+ }
381
+ return this._guestKeys.get(key) || null;
382
+ }
383
+
317
384
  /** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
318
385
  ownerOf(remoteAgentId) {
319
386
  const id = SharingManager.parseRemoteId(remoteAgentId);
@@ -451,6 +518,7 @@ export class SharingManager {
451
518
  await create(`${name} · ${roomTitle} · ${tag}-${crypto.randomBytes(2).toString('hex')}`);
452
519
  }
453
520
  db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
521
+ this._guestKeys = null;
454
522
  return key;
455
523
  }
456
524
 
@@ -506,7 +574,7 @@ export class SharingManager {
506
574
  for (const s of this._shares) {
507
575
  const grant = this._verifiedGrant(s);
508
576
  if (!grant) continue;
509
- const owner = firstName(s.owner);
577
+ const owner = this.labelOf(s.owner?.gatewayId, s.owner?.name || s.owner?.email) || firstName(s.owner);
510
578
  for (const a of grant.agents) {
511
579
  if (typeof a?.id !== 'string' || !a.id || a.id.length > 100) continue;
512
580
  out.push({ agentId: `peer:${s.id}:${a.id}`, name: `${cleanName(a.name || a.id) || 'Agent'} · ${owner}`, ownerName: owner, shareId: s.id, remoteId: a.id });
@@ -611,6 +679,8 @@ export class SharingManager {
611
679
  }
612
680
 
613
681
  close() {
682
+ this._closed = true;
683
+ clearTimeout(this._presenceTimer);
614
684
  for (const l of this._links.values()) l.close();
615
685
  for (const l of this._served) l.close();
616
686
  this._links.clear();
@@ -422,3 +422,29 @@ test('a peer request cannot pick the owner-room note', async () => {
422
422
  await link.request('turn', { turnId: 't1', agentId: 'jarvis-guest', roomId: 'r', message: 'hi', inOwnerRoom: true }, { timeoutMs: 5000 });
423
423
  assert.match(s.ownerCalls.find(c => c.method === 'chat.send').params.message, /you are answering Houman S's team chat/);
424
424
  });
425
+
426
+ test('presence: the side that asked keeps a link open, so the side that granted can reach it (room copies)', async () => {
427
+ const s = setup();
428
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
429
+ s.activate();
430
+ for (let i = 0; i < 20 && !s.req._links.get('sh1')?.ready; i++) await new Promise(r => setTimeout(r, 25));
431
+ assert.ok(s.req._links.get('sh1')?.ready, 'requester dialled without anyone using an agent');
432
+ // The owner can now call the requester over that link (what room.sync does).
433
+ let got = null;
434
+ s.req._links.get('sh1').handle('room.sync', async p => { got = p; return { ok: true }; });
435
+ const res = await s.owner.personRequest('gwH', 'room.sync', { roomId: 'r1' });
436
+ assert.deepEqual(res, { ok: true });
437
+ assert.equal(got.roomId, 'r1');
438
+ s.req.close(); s.owner.close();
439
+ });
440
+
441
+ test('names next to agents: first name, full name when two people here share it', () => {
442
+ const s = setup();
443
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
444
+ s.activate();
445
+ assert.equal(s.req.labelOf('gwK', 'Kamil Gronowski'), 'Kamil');
446
+ // This gateway's own person is "Houman S": another Houman next to their agents shows in full, and so does ours.
447
+ assert.equal(s.req.labelOf('gwX', 'Houman Test'), 'Houman Test');
448
+ assert.equal(s.req.labelOf('gwH', 'Houman S'), 'Houman', 'a person never clashes with themselves');
449
+ s.req.close(); s.owner.close();
450
+ });
@@ -229,6 +229,9 @@ export class SessionLens {
229
229
  if (payload.reason === 'delete' && this.team) {
230
230
  try { this.team.onSessionDeleted(key); } catch (e) { this.log.warn?.(`[lens] team delete: ${e.message}`); }
231
231
  }
232
+ if (payload.reason === 'patch' && this.team?.onSessionPatched) {
233
+ this.team.onSessionPatched(key).catch(e => this.log.warn?.(`[lens] team patch: ${e.message}`));
234
+ }
232
235
  if (!this.observe(key, payload.session || payload)) return null;
233
236
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
234
237
  const out = trimEvent(payload);
@@ -226,3 +226,11 @@ test('list responses keep children whose parent is listed later on the page', ()
226
226
  { key: CHAT, kind: 'direct', label: 'c' },
227
227
  ]);
228
228
  });
229
+
230
+ test('a patched session tells the team coordinator (a renamed room reaches its copies)', async () => {
231
+ const patched = [];
232
+ const { l } = lens({});
233
+ l.team = { isWorkKey: () => false, onSessionPatched: async key => { patched.push(key); } };
234
+ l.sessionsChanged({ sessionKey: CHAT, reason: 'patch', label: 'New name' });
235
+ assert.deepEqual(patched, [CHAT]);
236
+ });
@@ -16,6 +16,9 @@
16
16
  // team_rooms.host_* a live copy of someone else's room (this gateway is a member, not the host):
17
17
  // host_gateway_id/host_room/host_name; replica_json = the host's members and people
18
18
  // team_mirror host entry id -> local message id in a live copy (each host entry injected once)
19
+ // team_entries.host_ts/owner_id/ref a mirrored entry's original time, its agent's owner and room-wide agent ref
20
+ // team_entries author_type 'system': a line like "Kamil joined" (same on every screen)
21
+ // team_rooms.mention_only agents answer only when @mentioned (human chats with silent agents)
19
22
 
20
23
  const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
21
24
  const MAX_ROUNDS = 10;
@@ -24,6 +27,7 @@ function roomRow(r, members, people = []) {
24
27
  return {
25
28
  roomKey: r.room_key,
26
29
  discuss: !!r.discuss,
30
+ mentionOnly: !!r.mention_only,
27
31
  rounds: r.rounds || DISCUSS_ROUNDS,
28
32
  sourceKey: r.source_key || null,
29
33
  createdAt: r.created_at,
@@ -49,6 +53,11 @@ export function createTeamStore(getGlobalDb) {
49
53
  if (!cols('team_members').has('history')) g.exec('ALTER TABLE team_members ADD COLUMN history TEXT');
50
54
  const rc = cols('team_rooms');
51
55
  for (const c of ['host_gateway_id', 'host_room', 'host_name', 'host_ended', 'replica_json']) if (!rc.has(c)) g.exec(`ALTER TABLE team_rooms ADD COLUMN ${c} TEXT`);
56
+ if (!rc.has('mention_only')) g.exec('ALTER TABLE team_rooms ADD COLUMN mention_only INTEGER NOT NULL DEFAULT 0');
57
+ const ec = cols('team_entries');
58
+ if (!ec.has('host_ts')) g.exec('ALTER TABLE team_entries ADD COLUMN host_ts INTEGER');
59
+ if (!ec.has('owner_id')) g.exec('ALTER TABLE team_entries ADD COLUMN owner_id TEXT');
60
+ if (!ec.has('ref')) g.exec('ALTER TABLE team_entries ADD COLUMN ref TEXT');
52
61
  g.exec(`CREATE TABLE IF NOT EXISTS team_people (room_key TEXT NOT NULL, person_id TEXT NOT NULL, name TEXT NOT NULL, email TEXT, history_from INTEGER NOT NULL DEFAULT 0, added_at INTEGER NOT NULL, removed INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (room_key, person_id))`);
53
62
  g.exec(`CREATE TABLE IF NOT EXISTS team_mirror (room_key TEXT NOT NULL, host_entry_id TEXT NOT NULL, message_id TEXT, PRIMARY KEY (room_key, host_entry_id))`);
54
63
  ready = true;
@@ -72,12 +81,12 @@ export function createTeamStore(getGlobalDb) {
72
81
  },
73
82
 
74
83
  /** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
75
- createRoom(roomKey, memberList, { discuss = false, sourceKey = null } = {}) {
84
+ createRoom(roomKey, memberList, { discuss = false, sourceKey = null, mentionOnly = false } = {}) {
76
85
  const g = db();
77
86
  const now = Date.now();
78
87
  g.exec('BEGIN');
79
88
  try {
80
- g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now);
89
+ g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, mention_only) VALUES (?, ?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now, mentionOnly ? 1 : 0);
81
90
  memberList.forEach((m, i) => g.prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, ?, ?, ?)').run(roomKey, m.agentId, m.workKey || null, m.seenAt || 0, i));
82
91
  g.exec('COMMIT');
83
92
  } catch (e) { g.exec('ROLLBACK'); throw e; }
@@ -158,6 +167,10 @@ export function createTeamStore(getGlobalDb) {
158
167
  db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
159
168
  },
160
169
 
170
+ setMentionOnly(roomKey, on) {
171
+ db().prepare('UPDATE team_rooms SET mention_only = ?, updated_at = ? WHERE room_key = ?').run(on ? 1 : 0, Date.now(), roomKey);
172
+ },
173
+
161
174
  setRounds(roomKey, rounds) {
162
175
  db().prepare('UPDATE team_rooms SET rounds = ?, updated_at = ? WHERE room_key = ?').run(rounds, Date.now(), roomKey);
163
176
  },
@@ -189,18 +202,22 @@ export function createTeamStore(getGlobalDb) {
189
202
  * type 'user' (this gateway's own person), 'person' (someone else; agentId holds their person id
190
203
  * and actingFor their name), or 'agent' (actingFor: whose request it answered, if not its owner's).
191
204
  */
192
- recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
193
- db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for) VALUES (?, ?, ?, ?, ?, ?)')
194
- .run(roomKey, messageId, ['user', 'person'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor);
205
+ recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null, ts = null, ownerId = null, ref = null }) {
206
+ db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for, host_ts, owner_id, ref) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
207
+ .run(roomKey, messageId, ['user', 'person', 'system'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor, ts || null, ownerId, ref);
195
208
  },
196
209
 
197
- /** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
210
+ /**
211
+ * { [messageId]: { type: 'user'|'agent'|'system', agentId, actingFor?, ts?, ownerId?, ref? } | { type: 'person', personId, name } }
212
+ * ts: the entry's original time when this is a copy of someone else's room.
213
+ */
198
214
  authors(roomKey) {
199
215
  const out = {};
200
- for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for FROM team_entries WHERE room_key = ?').all(roomKey)) {
216
+ for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for, host_ts, owner_id, ref FROM team_entries WHERE room_key = ?').all(roomKey)) {
217
+ const extra = { ...(r.host_ts ? { ts: r.host_ts } : {}), ...(r.owner_id ? { ownerId: r.owner_id } : {}), ...(r.ref ? { ref: r.ref } : {}) };
201
218
  out[r.message_id] = r.author_type === 'person'
202
- ? { type: 'person', personId: r.agent_id, name: r.acting_for }
203
- : { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}) };
219
+ ? { type: 'person', personId: r.agent_id, name: r.acting_for, ...extra }
220
+ : { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}), ...extra };
204
221
  }
205
222
  return out;
206
223
  },