@clawchatsai/connector 0.1.36 → 0.1.38

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.38",
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
@@ -48,7 +48,8 @@ export function createApp(config = {}) {
48
48
 
49
49
  fs.mkdirSync(DATA_DIR, { recursive: true });
50
50
 
51
- function closeAll() { sharing?.close(); gatewayClient?.close(); globalDbCache.close?.(); }
51
+ let namesTimer = null;
52
+ function closeAll() { clearInterval(namesTimer); sharing?.close(); gatewayClient?.close(); globalDbCache.close?.(); }
52
53
 
53
54
  // Global DB (custom emojis, cross-workspace data)
54
55
  let _globalDb = null;
@@ -90,6 +91,13 @@ export function createApp(config = {}) {
90
91
  gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
91
92
  gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
92
93
  gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
94
+ // Renamed agents: shares re-issued with the new names, copies of rooms here told (peer/sharing.js, team.js).
95
+ const quiet = what => e => { if (!/not connected|closed/i.test(e.message)) console.warn(`[${what}] names: ${e.message}`); };
96
+ namesTimer = setInterval(() => {
97
+ sharing?.syncAgentNames().catch(quiet('sharing'));
98
+ team.refreshNames().catch(quiet('team'));
99
+ }, 60_000);
100
+ namesTimer.unref?.();
93
101
 
94
102
  // A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
95
103
  // spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
@@ -249,6 +257,18 @@ export function createApp(config = {}) {
249
257
  if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
250
258
  return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null });
251
259
  }
260
+ // The project a person's chats go to (peer/sharing.js funnel). Keyed by email.
261
+ if (method === 'GET' && urlPath === '/api/sharing/funnel') return send(res, 200, { funnel: sharing?.funnels() || {} });
262
+ if (method === 'PUT' && urlPath === '/api/sharing/funnel') {
263
+ if (!sharing) return sendError(res, 404, 'Sharing is not available');
264
+ const { email, project } = await parseBody(req);
265
+ try { return send(res, 200, await sharing.setFunnel(email, project)); }
266
+ catch (e) { return sendError(res, 400, e.message); }
267
+ }
268
+ if (method === 'POST' && urlPath === '/api/sharing/funnel/rename') {
269
+ const { from, to } = await parseBody(req);
270
+ return send(res, 200, { changed: sharing?.renameFunnel(from, to) || 0 });
271
+ }
252
272
  if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/approve'))) {
253
273
  if (!sharing) return sendError(res, 404, 'Sharing is not available');
254
274
  try { return send(res, 200, { grant: sharing.approve(p.id, await parseBody(req)) }); }
@@ -289,6 +309,9 @@ export function createApp(config = {}) {
289
309
  if (room && body.discuss !== undefined) {
290
310
  try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
291
311
  }
312
+ if (room && body.mentionOnly !== undefined) {
313
+ try { room = team.setMentionOnly(p.room, body.mentionOnly); } catch (e) { return sendError(res, 400, e.message); }
314
+ }
292
315
  if (room && body.rounds !== undefined) {
293
316
  try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
294
317
  }
@@ -298,16 +321,16 @@ export function createApp(config = {}) {
298
321
  const { personId, history } = await parseBody(req);
299
322
  if (typeof personId !== 'string' || !personId) return sendError(res, 400, 'personId is required');
300
323
  try {
301
- const room = await team.addPerson(p.room, personId, { history });
324
+ const room = await team.addPerson(p.room, personId, { history, quietAgents: true });
302
325
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
303
326
  } catch (e) { return sendError(res, 400, e.message); }
304
327
  }
305
328
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/people/:personId'))) {
306
- const room = team.removePerson(p.room, p.personId);
329
+ const room = await team.removePerson(p.room, p.personId);
307
330
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat you host');
308
331
  }
309
332
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/leave'))) {
310
- try { return send(res, 200, { room: await team.leave(p.room) }); }
333
+ try { return send(res, 200, { room: await team.leave(p.room, await parseBody(req).catch(() => ({}))) }); }
311
334
  catch (e) { return sendError(res, 400, e.message); }
312
335
  }
313
336
  if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
@@ -320,7 +343,7 @@ export function createApp(config = {}) {
320
343
  }
321
344
  if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
322
345
  try {
323
- const room = team.removeAgent(p.room, p.agentId);
346
+ const room = await team.removeAgent(p.room, p.agentId);
324
347
  return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
325
348
  } catch (e) { return sendError(res, 400, e.message); }
326
349
  }
@@ -78,7 +78,11 @@ async function waitForAgent(request, agentId, { tries = 40, ms = 250 } = {}) {
78
78
  /** The guest version of `agentId` if it already exists (by name). */
79
79
  export function findGuestAgent(agents, agentId) {
80
80
  const src = agents.find(a => a.id === agentId);
81
- return src ? agents.find(a => agentName(a) === guestName(agentName(src))) || null : null;
81
+ if (!src) return null;
82
+ // By name ("Jarvis (guest)"), or by the id it was made with ("main-guest"): renaming the original
83
+ // ("main" -> "homiabot") changes the name it looks for, not the guest that already exists.
84
+ return agents.find(a => agentName(a) === guestName(agentName(src)))
85
+ || agents.find(a => a.id === `${agentId}-guest` && /\(guest\)$/.test(agentName(a))) || null;
82
86
  }
83
87
 
84
88
  /**
@@ -79,3 +79,17 @@ test('hasGuestRestrictions: only a policy at least as narrow as the guest one pa
79
79
  // A guest made before view_image/pdf were removed (still in alsoAllow) no longer passes.
80
80
  assert.equal(hasGuestRestrictions({ ...GUEST_TOOLS, alsoAllow: ['group:fs', 'group:runtime', 'view_image', 'pdf'] }), false);
81
81
  });
82
+
83
+ test('findGuestAgent: the guest made as "main (guest)" is still found after the original is renamed', async () => {
84
+ const { findGuestAgent } = await import('./guest-agent.js');
85
+ const agents = [
86
+ { id: 'main', identity: { name: 'homiabot' } },
87
+ { id: 'main-guest', identity: { name: 'main (guest)' } },
88
+ { id: 'dev', name: 'dev' },
89
+ { id: 'dev-guest', name: 'dev (guest)' },
90
+ ];
91
+ assert.equal(findGuestAgent(agents, 'main')?.id, 'main-guest');
92
+ assert.equal(findGuestAgent(agents, 'dev')?.id, 'dev-guest');
93
+ // An agent that merely has the id shape isn't taken for a guest.
94
+ assert.equal(findGuestAgent([{ id: 'x', name: 'x' }, { id: 'x-guest', name: 'something else' }], 'x'), null);
95
+ });
@@ -75,6 +75,7 @@ export class SharingManager {
75
75
  const g = this.getDb();
76
76
  if (!this._ready) {
77
77
  g.exec(`CREATE TABLE IF NOT EXISTS peer_grants (share_id TEXT PRIMARY KEY, grant_json TEXT NOT NULL, sig TEXT NOT NULL, created_at INTEGER NOT NULL, revoked_at INTEGER)`);
78
+ g.exec(`CREATE TABLE IF NOT EXISTS peer_funnel (email TEXT PRIMARY KEY, project TEXT NOT NULL, updated_at INTEGER NOT NULL)`);
78
79
  g.exec(`CREATE TABLE IF NOT EXISTS peer_pins (share_id TEXT PRIMARY KEY, owner_pubkey TEXT NOT NULL, created_at INTEGER NOT NULL)`);
79
80
  g.exec(`CREATE TABLE IF NOT EXISTS peer_sessions (share_id TEXT NOT NULL, room_id TEXT NOT NULL, agent_id TEXT NOT NULL, session_key TEXT NOT NULL, PRIMARY KEY (share_id, room_id, agent_id))`);
80
81
  g.exec(`CREATE TABLE IF NOT EXISTS peer_usage (share_id TEXT NOT NULL, day TEXT NOT NULL, turns INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (share_id, day))`);
@@ -94,6 +95,7 @@ export class SharingManager {
94
95
 
95
96
  /** `share-list` from the signal server. Ends links/grants for shares that are gone. */
96
97
  setShares(shares) {
98
+ this._nameCache = null;
97
99
  const first = !this.serverEnabled;
98
100
  this.serverEnabled = true;
99
101
  this._shares = Array.isArray(shares) ? shares : [];
@@ -102,14 +104,43 @@ export class SharingManager {
102
104
  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
105
  this._changed();
104
106
  if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
107
+ this._sharesChanged();
108
+ this._presenceTick();
105
109
  }
106
110
 
111
+ /**
112
+ * Presence: a gateway that asked for someone's agents is the one that can open the link to them, so
113
+ * it keeps one open (and re-opens it when it drops). Without that, a room host that only *granted*
114
+ * shares couldn't reach its people until they happened to use an agent: copies would sit unsent.
115
+ * Retries back off per share (15 s up to 10 min); a failed dial costs nothing.
116
+ */
117
+ _presenceTick() {
118
+ clearTimeout(this._presenceTimer);
119
+ if (!this.serverEnabled || this._closed) return;
120
+ for (const s of this._shares) {
121
+ if (s.as !== 'requester' || s.status !== 'active' || !this._verifiedGrant(s)) continue;
122
+ const cur = this._links.get(s.id);
123
+ const b = (this._backoff ??= new Map());
124
+ if ((cur?.ready && !cur.closed) || this._linking.has(s.id)) { b.delete(s.id); continue; }
125
+ const st = b.get(s.id) || { next: 0, wait: 15_000 };
126
+ if (Date.now() < st.next) continue;
127
+ b.set(s.id, { next: Date.now() + st.wait, wait: Math.min(st.wait * 2, 10 * 60_000) });
128
+ this._link(s.id).then(() => b.delete(s.id)).catch(e => this.log.info?.(`[sharing] presence ${s.id}: ${e.message}`));
129
+ }
130
+ this._presenceTimer = setTimeout(() => this._presenceTick(), 15_000);
131
+ this._presenceTimer.unref?.();
132
+ }
133
+
134
+ /** Team chats follow the connection: people and agents of an ended share leave their rooms. */
135
+ _sharesChanged() { try { this.onSharesChanged?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } }
136
+
107
137
  /** The signal server says a share ended (revoke/decline): stop at once. */
108
138
  onShareRevoked(shareId) {
109
139
  this._revokeLocal(shareId);
110
140
  this._links.get(shareId)?.close();
111
141
  this._links.delete(shareId);
112
142
  this._changed();
143
+ this._sharesChanged();
113
144
  }
114
145
 
115
146
  _changed() { this.broadcast(JSON.stringify({ type: 'clawchats', event: 'sharing-changed' })); }
@@ -207,7 +238,7 @@ export class SharingManager {
207
238
  if (!s) throw new Error('No such request');
208
239
  if (!s.requester?.pubKey || !s.requester?.gatewayId) throw new Error("The requester's gateway hasn't connected with sharing support yet");
209
240
  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');
241
+ // No agents is fine: a connection can be just for chatting (team chats with people).
211
242
  if (!ACCESS_MODES[access]) throw new Error('Unknown access level');
212
243
  // A changed grant keeps the requester key it was first approved for: the signal server can't swap it.
213
244
  const prev = this._db().prepare('SELECT grant_json FROM peer_grants WHERE share_id = ?').get(shareId);
@@ -314,6 +345,43 @@ export class SharingManager {
314
345
 
315
346
  contact(personId) { return this.contacts().find(c => c.personId === personId) || null; }
316
347
 
348
+ /** Whether any share (either direction, verified or not) is active with that gateway. */
349
+ hasShareWith(gatewayId) {
350
+ return this._shares.some(s => s.status === 'active' && this._other(s).gatewayId === gatewayId);
351
+ }
352
+
353
+ /**
354
+ * How a person's name shows next to their agents ("Jarvis · Kamil"): the first name, or the full
355
+ * name when two people here (this gateway's person included) share a first name.
356
+ */
357
+ labelOf(gatewayId, fullName) {
358
+ const first = n => cleanName(String(n || '').trim().split(/[\s@]/)[0], 30) || 'Someone';
359
+ // Everyone known here by id (cached: remoteAgents() calls this per agent, and contacts() verifies grants).
360
+ if (!this._nameCache || Date.now() - this._nameCache.at > 5000) {
361
+ const known = new Map();
362
+ for (const c of this.contacts()) known.set(c.personId, c.name);
363
+ if (this.gatewayId?.()) known.set(this.gatewayId(), this.selfName() || '');
364
+ this._nameCache = { at: Date.now(), known };
365
+ }
366
+ const people = new Map(this._nameCache.known);
367
+ if (gatewayId && fullName) people.set(gatewayId, fullName);
368
+ const mine = first(fullName);
369
+ const clash = [...people].some(([id, n]) => id !== gatewayId && first(n).toLowerCase() === mine.toLowerCase());
370
+ return clash ? cleanName(fullName, 60) || mine : mine;
371
+ }
372
+
373
+ /** The room (and who asked) behind a guest session of this gateway, or null. */
374
+ guestSessionOf(key) {
375
+ if (!this._guestKeys) {
376
+ this._guestKeys = new Map();
377
+ for (const r of this._db().prepare('SELECT share_id, room_id, session_key FROM peer_sessions').all()) {
378
+ const g = this._grant(r.share_id);
379
+ if (g?.grant.requesterGatewayId) this._guestKeys.set(r.session_key, { requesterGatewayId: g.grant.requesterGatewayId, roomId: r.room_id, shareId: r.share_id });
380
+ }
381
+ }
382
+ return this._guestKeys.get(key) || null;
383
+ }
384
+
317
385
  /** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
318
386
  ownerOf(remoteAgentId) {
319
387
  const id = SharingManager.parseRemoteId(remoteAgentId);
@@ -434,16 +502,21 @@ export class SharingManager {
434
502
  async _guestSession(shareId, roomId, agentId, { name, roomTitle, permissionMode, toolOverrides }) {
435
503
  const db = this._db();
436
504
  const row = db.prepare('SELECT session_key FROM peer_sessions WHERE share_id = ? AND room_id = ? AND agent_id = ?').get(shareId, roomId, agentId);
437
- if (row) {
505
+ // The owner may have deleted it from their chat list: then it's made again (same key, so the
506
+ // room keeps pointing at it), in "Shared with <name>" with its label, instead of the gateway
507
+ // bringing it back as an untitled chat that ClawChats hides.
508
+ const exists = row && await this.request('sessions.describe', { key: row.session_key }, 5000).then(r => !(r && 'session' in r && !r.session), () => true);
509
+ if (exists) {
438
510
  // Re-apply the policy each turn: the owner may have changed the access level since.
439
511
  await this.request('sessions.patch', { key: row.session_key, permissionMode, toolOverrides }).catch(() => {});
440
512
  return row.session_key;
441
513
  }
442
- const key = `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
514
+ const key = row?.session_key || `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
515
+ const category = this.funnelOf(this._shares.find(x => x.id === shareId && x.as === 'owner')?.requester?.email, name);
443
516
  // Labels are unique per gateway, and untitled rooms all fall back to "team chat": tag each room.
444
517
  const tag = crypto.createHash('sha256').update(`${shareId}|${roomId}`).digest('hex').slice(0, 6);
445
518
  const create = label => this.request('sessions.create', {
446
- key, agentId, permissionMode, toolOverrides, label: label.slice(0, 200), category: `Shared with ${name}`.slice(0, 100),
519
+ key, agentId, permissionMode, toolOverrides, label: label.slice(0, 200), category,
447
520
  });
448
521
  try { await create(`${name} · ${roomTitle} · ${tag}`); }
449
522
  catch (e) {
@@ -451,6 +524,7 @@ export class SharingManager {
451
524
  await create(`${name} · ${roomTitle} · ${tag}-${crypto.randomBytes(2).toString('hex')}`);
452
525
  }
453
526
  db.prepare('INSERT OR REPLACE INTO peer_sessions (share_id, room_id, agent_id, session_key) VALUES (?, ?, ?, ?)').run(shareId, roomId, agentId, key);
527
+ this._guestKeys = null;
454
528
  return key;
455
529
  }
456
530
 
@@ -506,7 +580,7 @@ export class SharingManager {
506
580
  for (const s of this._shares) {
507
581
  const grant = this._verifiedGrant(s);
508
582
  if (!grant) continue;
509
- const owner = firstName(s.owner);
583
+ const owner = this.labelOf(s.owner?.gatewayId, s.owner?.name || s.owner?.email) || firstName(s.owner);
510
584
  for (const a of grant.agents) {
511
585
  if (typeof a?.id !== 'string' || !a.id || a.id.length > 100) continue;
512
586
  out.push({ agentId: `peer:${s.id}:${a.id}`, name: `${cleanName(a.name || a.id) || 'Agent'} · ${owner}`, ownerName: owner, shareId: s.id, remoteId: a.id });
@@ -582,6 +656,87 @@ export class SharingManager {
582
656
  return g ? (firstName({ name: g.grant.requesterName }) || 'Someone') : null;
583
657
  }
584
658
 
659
+ /**
660
+ * Shared agents renamed since they were approved ("main" -> "homiabot"): re-issue those grants with
661
+ * the new names, same agents, access and cap, so the people they're shared with see the new name.
662
+ * A guest version is shown under its original's name, as when it was approved. Runs on a timer (index.js).
663
+ */
664
+ async syncAgentNames() {
665
+ const grants = this._localGrants();
666
+ if (!grants.length) return [];
667
+ const agents = (await this.request('agents.list', {}))?.agents || [];
668
+ const label = a => a?.identity?.name || a?.name || a?.id;
669
+ const shown = id => {
670
+ const a = agents.find(x => x.id === id);
671
+ if (!a) return null;
672
+ if (!/\(guest\)$/.test(label(a))) return label(a);
673
+ const src = agents.find(o => o.id !== id && findGuestAgent(agents, o.id)?.id === id);
674
+ return src ? label(src) : null;
675
+ };
676
+ const reissued = [];
677
+ for (const r of grants) {
678
+ const grant = JSON.parse(r.grant_json);
679
+ const live = this._shares.find(x => x.id === r.share_id && x.as === 'owner' && x.status === 'active');
680
+ if (!live || !Array.isArray(grant.agents)) continue;
681
+ const next = grant.agents.map(a => ({ id: a.id, name: String(shown(a.id) || a.name).slice(0, 80) }));
682
+ if (next.every((a, i) => a.name === grant.agents[i].name)) continue;
683
+ try { this.approve(r.share_id, { agents: next, access: grant.access, dailyCap: grant.dailyCap }); reissued.push(r.share_id); }
684
+ catch (e) { this.log?.warn?.(`[sharing] rename ${r.share_id}: ${e.message}`); }
685
+ }
686
+ return reissued;
687
+ }
688
+
689
+ // ── Funnel: the project one person's chats go to ───────────────────
690
+ // Set when the person is added (invite or accept) and changeable in Settings → People. It covers
691
+ // both what they host (our copies of their chats) and our agents' guest sessions for them. Stored by
692
+ // name; ClawChats renames follow it (renameFunnel), a deleted project is made again by the next chat.
693
+ // Keyed by the person's email: known from the invite on, before any gateway id.
694
+
695
+ funnelOf(email, name) {
696
+ const row = email && this._db().prepare('SELECT project FROM peer_funnel WHERE email = ?').get(String(email).toLowerCase());
697
+ return row?.project || `Shared with ${cleanName(name, 60) || 'someone'}`.slice(0, 100);
698
+ }
699
+
700
+ funnels() {
701
+ return Object.fromEntries(this._db().prepare('SELECT email, project FROM peer_funnel').all().map(r => [r.email, r.project]));
702
+ }
703
+
704
+ /** Where this person's chats go from now on, and move the ones already here. Returns how many moved. */
705
+ async setFunnel(email, project) {
706
+ const e = String(email || '').toLowerCase().trim();
707
+ const name = cleanName(project, 100);
708
+ if (!e || !name) throw new Error('email and project are required');
709
+ this._db().prepare('INSERT INTO peer_funnel (email, project, updated_at) VALUES (?, ?, ?) ON CONFLICT(email) DO UPDATE SET project = excluded.project, updated_at = excluded.updated_at').run(e, name, Date.now());
710
+ let moved = 0;
711
+ for (const key of this._guestSessionKeysOf(e)) {
712
+ if (await this.request('sessions.patch', { key, category: name }).then(() => true, () => false)) moved++;
713
+ }
714
+ moved += (await this.onFunnelChanged?.(e, name)) || 0; // copies of their chats (team.js)
715
+ this._changed();
716
+ return { moved };
717
+ }
718
+
719
+ /** A project was renamed in ClawChats: whoever is funnelled there follows. */
720
+ renameFunnel(from, to) {
721
+ if (!from || !to || from === to) return 0;
722
+ return this._db().prepare('UPDATE peer_funnel SET project = ?, updated_at = ? WHERE project = ?').run(String(to).slice(0, 100), Date.now(), from).changes;
723
+ }
724
+
725
+ _guestSessionKeysOf(email) {
726
+ const keys = [];
727
+ for (const r of this._db().prepare('SELECT share_id, session_key FROM peer_sessions').all()) {
728
+ const sh = this._shares.find(x => x.id === r.share_id && x.as === 'owner');
729
+ if (String(sh?.requester?.email || '').toLowerCase() === email) keys.push(r.session_key);
730
+ }
731
+ return keys;
732
+ }
733
+
734
+ /** The guest session that answers `who` in a team chat here (TeamCoordinator lanes): one per share, like _guestSession. */
735
+ laneFor(who) {
736
+ const g = this._grantToOwnerOf(who);
737
+ return g ? `guest:${g.shareId}` : null;
738
+ }
739
+
585
740
  /**
586
741
  * Run one of this gateway's agents because another person's agent asked (a team chat here):
587
742
  * authority comes from who asked (specs/sharing-people.md), so it runs as the version shared with
@@ -611,6 +766,8 @@ export class SharingManager {
611
766
  }
612
767
 
613
768
  close() {
769
+ this._closed = true;
770
+ clearTimeout(this._presenceTimer);
614
771
  for (const l of this._links.values()) l.close();
615
772
  for (const l of this._served) l.close();
616
773
  this._links.clear();
@@ -66,6 +66,71 @@ function setup({ reply = p => `jarvis says: ${p.message.split('\n\n').pop()}`, c
66
66
  return { owner, req, ownerCalls, ownerSignals, reqSignals, activate, kOwner, kReq, people };
67
67
  }
68
68
 
69
+ test('a guest session the owner deleted is made again on the next turn, with its label in "Shared with <name>"', async () => {
70
+ const s = setup();
71
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'restricted', dailyCap: 10 });
72
+ s.activate();
73
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'hi' });
74
+ const first = s.ownerCalls.find(c => c.method === 'sessions.create').params;
75
+
76
+ // Deleted from the owner's chat list: the gateway no longer has it.
77
+ const request = s.owner.request;
78
+ s.owner.request = async (method, params) => (method === 'sessions.describe' && params.key === first.key ? { session: null } : request(method, params));
79
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'room1', roomTitle: 'Rivers', message: 'still there?' });
80
+ const creates = s.ownerCalls.filter(c => c.method === 'sessions.create').map(c => c.params);
81
+ assert.equal(creates.length, 2);
82
+ assert.deepEqual([creates[1].key, creates[1].label, creates[1].category, creates[1].permissionMode], [first.key, first.label, 'Shared with Houman S', 'read-only']);
83
+ assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').at(-1).params.sessionKey, first.key);
84
+
85
+ // Still there: reused, no new session.
86
+ s.owner.request = request;
87
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't3', roomId: 'room1', message: 'and again' });
88
+ assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.create').length, 2);
89
+ });
90
+
91
+ test('a shared agent renamed by its owner: the grant is re-issued with the new name, same access and cap', async () => {
92
+ const s = setup();
93
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'trusted', dailyCap: 7 });
94
+ s.activate();
95
+ let agents = [{ id: 'jarvis', identity: { name: 'Jarvis' } }, { id: 'jarvis-guest', identity: { name: 'Jarvis (guest)' } }];
96
+ const request = s.owner.request;
97
+ s.owner.request = async (method, params) => (method === 'agents.list' ? { agents } : request(method, params));
98
+ assert.deepEqual(await s.owner.syncAgentNames(), [], 'nothing renamed: no new grant');
99
+
100
+ agents = [{ id: 'jarvis', identity: { name: 'Jarvy' } }, { id: 'jarvis-guest', identity: { name: 'Jarvis (guest)' } }];
101
+ assert.deepEqual(await s.owner.syncAgentNames(), ['sh1']);
102
+ const g = s.ownerSignals.filter(m => m.type === 'share-grant').at(-1).grant;
103
+ assert.deepEqual([g.agents, g.access, g.dailyCap], [[{ id: 'jarvis-guest', name: 'Jarvy' }], 'trusted', 7]);
104
+ s.activate();
105
+ assert.equal(s.req.remoteAgents()[0].name, 'Jarvy · Kamil', 'the requester sees the new name');
106
+ assert.deepEqual(await s.owner.syncAgentNames(), [], 'once');
107
+ });
108
+
109
+ test("funnel: a person's chats go to the project chosen for them; renames follow, moving existing chats, default until chosen", async () => {
110
+ const s = setup();
111
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'restricted', dailyCap: 10 });
112
+ s.activate();
113
+ assert.equal(s.owner.funnelOf('h@x.dev', 'Houman S'), 'Shared with Houman S', 'nothing chosen: named after them');
114
+
115
+ // Chosen at invite/accept time (before any chat): the first guest session is made there.
116
+ await s.owner.setFunnel('H@x.dev', 'Friends');
117
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't1', roomId: 'room1', roomTitle: 'Rivers', message: 'hi' });
118
+ const create = s.ownerCalls.find(c => c.method === 'sessions.create').params;
119
+ assert.equal(create.category, 'Friends');
120
+
121
+ // Changed later: chats already there move.
122
+ const moved = await s.owner.setFunnel('h@x.dev', 'Work friends');
123
+ assert.equal(moved.moved, 1);
124
+ assert.deepEqual(s.ownerCalls.filter(c => c.method === 'sessions.patch' && c.params.category).map(c => [c.params.key, c.params.category]), [[create.key, 'Work friends']]);
125
+
126
+ // The project is renamed in ClawChats: they follow. Deleted: the next chat makes it again (sessions.create names it).
127
+ assert.equal(s.owner.renameFunnel('Work friends', 'Team'), 1);
128
+ assert.equal(s.owner.funnelOf('h@x.dev', 'Houman S'), 'Team');
129
+ await s.req.turn('peer:sh1:jarvis-guest', { turnId: 't2', roomId: 'room2', roomTitle: 'Lakes', message: 'again' });
130
+ assert.equal(s.ownerCalls.filter(c => c.method === 'sessions.create').at(-1).params.category, 'Team');
131
+ assert.deepEqual(s.owner.funnels(), { 'h@x.dev': 'Team' });
132
+ });
133
+
69
134
  test('approve → verified on the requester → turn runs in a guest session on the owner, text streams back', async () => {
70
135
  const s = setup();
71
136
  assert.deepEqual(s.req.remoteAgents(), []);
@@ -422,3 +487,29 @@ test('a peer request cannot pick the owner-room note', async () => {
422
487
  await link.request('turn', { turnId: 't1', agentId: 'jarvis-guest', roomId: 'r', message: 'hi', inOwnerRoom: true }, { timeoutMs: 5000 });
423
488
  assert.match(s.ownerCalls.find(c => c.method === 'chat.send').params.message, /you are answering Houman S's team chat/);
424
489
  });
490
+
491
+ test('presence: the side that asked keeps a link open, so the side that granted can reach it (room copies)', async () => {
492
+ const s = setup();
493
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
494
+ s.activate();
495
+ for (let i = 0; i < 20 && !s.req._links.get('sh1')?.ready; i++) await new Promise(r => setTimeout(r, 25));
496
+ assert.ok(s.req._links.get('sh1')?.ready, 'requester dialled without anyone using an agent');
497
+ // The owner can now call the requester over that link (what room.sync does).
498
+ let got = null;
499
+ s.req._links.get('sh1').handle('room.sync', async p => { got = p; return { ok: true }; });
500
+ const res = await s.owner.personRequest('gwH', 'room.sync', { roomId: 'r1' });
501
+ assert.deepEqual(res, { ok: true });
502
+ assert.equal(got.roomId, 'r1');
503
+ s.req.close(); s.owner.close();
504
+ });
505
+
506
+ test('names next to agents: first name, full name when two people here share it', () => {
507
+ const s = setup();
508
+ s.owner.approve('sh1', { agents: [{ id: 'jarvis', name: 'Jarvis' }] });
509
+ s.activate();
510
+ assert.equal(s.req.labelOf('gwK', 'Kamil Gronowski'), 'Kamil');
511
+ // This gateway's own person is "Houman S": another Houman next to their agents shows in full, and so does ours.
512
+ assert.equal(s.req.labelOf('gwX', 'Houman Test'), 'Houman Test');
513
+ assert.equal(s.req.labelOf('gwH', 'Houman S'), 'Houman', 'a person never clashes with themselves');
514
+ s.req.close(); s.owner.close();
515
+ });
@@ -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,15 @@
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)
22
+ // team_entries.via which of its sessions an agent wrote from: 'owner' (its owner's own session,
23
+ // here or in its owner's copy) or 'guest:<who>' (a session it ran in for someone else).
24
+ // NULL on older rows: treated as the session asking, as before.
25
+ // team_lanes seen_at for an agent's other sessions in a room ('guest:<who>'); its owner session
26
+ // keeps team_members.seen_at. One agent can answer in several sessions, and each
27
+ // must be given what it hasn't seen itself.
19
28
 
20
29
  const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
21
30
  const MAX_ROUNDS = 10;
@@ -24,6 +33,7 @@ function roomRow(r, members, people = []) {
24
33
  return {
25
34
  roomKey: r.room_key,
26
35
  discuss: !!r.discuss,
36
+ mentionOnly: !!r.mention_only,
27
37
  rounds: r.rounds || DISCUSS_ROUNDS,
28
38
  sourceKey: r.source_key || null,
29
39
  createdAt: r.created_at,
@@ -49,7 +59,14 @@ export function createTeamStore(getGlobalDb) {
49
59
  if (!cols('team_members').has('history')) g.exec('ALTER TABLE team_members ADD COLUMN history TEXT');
50
60
  const rc = cols('team_rooms');
51
61
  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`);
62
+ if (!rc.has('mention_only')) g.exec('ALTER TABLE team_rooms ADD COLUMN mention_only INTEGER NOT NULL DEFAULT 0');
63
+ const ec = cols('team_entries');
64
+ if (!ec.has('host_ts')) g.exec('ALTER TABLE team_entries ADD COLUMN host_ts INTEGER');
65
+ if (!ec.has('owner_id')) g.exec('ALTER TABLE team_entries ADD COLUMN owner_id TEXT');
66
+ if (!ec.has('ref')) g.exec('ALTER TABLE team_entries ADD COLUMN ref TEXT');
52
67
  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))`);
68
+ if (!ec.has('via')) g.exec('ALTER TABLE team_entries ADD COLUMN via TEXT');
69
+ g.exec(`CREATE TABLE IF NOT EXISTS team_lanes (room_key TEXT NOT NULL, agent_id TEXT NOT NULL, lane TEXT NOT NULL, seen_at INTEGER NOT NULL, PRIMARY KEY (room_key, agent_id, lane))`);
53
70
  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
71
  ready = true;
55
72
  }
@@ -72,12 +89,12 @@ export function createTeamStore(getGlobalDb) {
72
89
  },
73
90
 
74
91
  /** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
75
- createRoom(roomKey, memberList, { discuss = false, sourceKey = null } = {}) {
92
+ createRoom(roomKey, memberList, { discuss = false, sourceKey = null, mentionOnly = false } = {}) {
76
93
  const g = db();
77
94
  const now = Date.now();
78
95
  g.exec('BEGIN');
79
96
  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);
97
+ 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
98
  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
99
  g.exec('COMMIT');
83
100
  } catch (e) { g.exec('ROLLBACK'); throw e; }
@@ -154,10 +171,23 @@ export function createTeamStore(getGlobalDb) {
154
171
  db().prepare('UPDATE team_members SET seen_at = MAX(seen_at, ?) WHERE room_key = ? AND agent_id = ?').run(seenAt, roomKey, agentId);
155
172
  },
156
173
 
174
+ /** An agent's other session in the room (lane 'guest:<who>'): the newest entry it was given, or null before its first turn. */
175
+ laneSeenAt(roomKey, agentId, lane) {
176
+ return db().prepare('SELECT seen_at FROM team_lanes WHERE room_key = ? AND agent_id = ? AND lane = ?').get(roomKey, agentId, lane)?.seen_at ?? null;
177
+ },
178
+
179
+ setLaneSeenAt(roomKey, agentId, lane, seenAt) {
180
+ db().prepare('INSERT INTO team_lanes (room_key, agent_id, lane, seen_at) VALUES (?, ?, ?, ?) ON CONFLICT(room_key, agent_id, lane) DO UPDATE SET seen_at = MAX(seen_at, excluded.seen_at)').run(roomKey, agentId, lane, seenAt);
181
+ },
182
+
157
183
  setDiscuss(roomKey, discuss) {
158
184
  db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
159
185
  },
160
186
 
187
+ setMentionOnly(roomKey, on) {
188
+ db().prepare('UPDATE team_rooms SET mention_only = ?, updated_at = ? WHERE room_key = ?').run(on ? 1 : 0, Date.now(), roomKey);
189
+ },
190
+
161
191
  setRounds(roomKey, rounds) {
162
192
  db().prepare('UPDATE team_rooms SET rounds = ?, updated_at = ? WHERE room_key = ?').run(rounds, Date.now(), roomKey);
163
193
  },
@@ -170,6 +200,7 @@ export function createTeamStore(getGlobalDb) {
170
200
  g.prepare('DELETE FROM team_entries WHERE room_key = ?').run(roomKey);
171
201
  g.prepare('DELETE FROM team_people WHERE room_key = ?').run(roomKey);
172
202
  g.prepare('DELETE FROM team_mirror WHERE room_key = ?').run(roomKey);
203
+ g.prepare('DELETE FROM team_lanes WHERE room_key = ?').run(roomKey);
173
204
  g.prepare('DELETE FROM team_rooms WHERE room_key = ?').run(roomKey);
174
205
  return work;
175
206
  },
@@ -189,18 +220,22 @@ export function createTeamStore(getGlobalDb) {
189
220
  * type 'user' (this gateway's own person), 'person' (someone else; agentId holds their person id
190
221
  * and actingFor their name), or 'agent' (actingFor: whose request it answered, if not its owner's).
191
222
  */
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);
223
+ recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null, ts = null, ownerId = null, ref = null, via = null }) {
224
+ 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, via) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
225
+ .run(roomKey, messageId, ['user', 'person', 'system'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor, ts || null, ownerId, ref, via);
195
226
  },
196
227
 
197
- /** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
228
+ /**
229
+ * { [messageId]: { type: 'user'|'agent'|'system', agentId, actingFor?, ts?, ownerId?, ref?, via? } | { type: 'person', personId, name } }
230
+ * ts: the entry's original time when this is a copy of someone else's room.
231
+ */
198
232
  authors(roomKey) {
199
233
  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)) {
234
+ for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for, host_ts, owner_id, ref, via FROM team_entries WHERE room_key = ?').all(roomKey)) {
235
+ const extra = { ...(r.host_ts ? { ts: r.host_ts } : {}), ...(r.owner_id ? { ownerId: r.owner_id } : {}), ...(r.ref ? { ref: r.ref } : {}), ...(r.via ? { via: r.via } : {}) };
201
236
  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 } : {}) };
237
+ ? { type: 'person', personId: r.agent_id, name: r.acting_for, ...extra }
238
+ : { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}), ...extra };
204
239
  }
205
240
  return out;
206
241
  },