@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/server/team.js CHANGED
@@ -23,6 +23,8 @@ const TURN_TIMEOUT_MS = 15 * 60_000;
23
23
  const HISTORY_LIMIT = 80;
24
24
  const AGENTS_TTL_MS = 60_000;
25
25
  const ALL_WORDS = new Set(['all', 'everyone']);
26
+ /** Rounds of @mention replies when agents don't "discuss": an agent a reply names answers once, and so on. */
27
+ const MENTION_ROUNDS = 3;
26
28
 
27
29
  const norm = s => String(s || '').toLowerCase().replace(/\s+/g, '');
28
30
 
@@ -42,6 +44,9 @@ export function entryId(message) {
42
44
  return null;
43
45
  }
44
46
 
47
+ /** Appended to a converted chat's label while its team chat holds the title (labels are unique). */
48
+ const SOURCE_LABEL_SUFFIX = ' · before team chat ';
49
+
45
50
  /** "[Label]\n\nbody" → { label, body }. */
46
51
  export function splitLabel(text) {
47
52
  const m = LABEL_PREFIX.exec(text || '');
@@ -56,7 +61,7 @@ export function parseMentions(text, agents) {
56
61
  const ids = new Set();
57
62
  const re = /(^|[^\w@])@([\w.-]+)/g;
58
63
  // Someone else's agent is "Jarvis · Kamil": @Jarvis-Kamil, or @Jarvis when that's unambiguous.
59
- const exact = a => [a.agentId, a.name, a.name && a.name.replace(/\s*·\s*/g, '-')].filter(Boolean).map(norm);
64
+ const exact = a => [a.agentId, a.name, a.name && a.name.replace(/\s*·\s*/g, '-'), a.name && a.name.replace(/\s*·\s*(\S+).*$/, '-$1')].filter(Boolean).map(norm);
60
65
  const short = a => (a.name && a.name.includes('·') ? [norm(a.name.split('·')[0])] : []);
61
66
  let m;
62
67
  while ((m = re.exec(text || ''))) {
@@ -102,26 +107,59 @@ export class TeamCoordinator {
102
107
  this._rooms = new Map(); // roomKey -> { running: Map<agentId, {workKey, runId}>, queued, stopped }
103
108
  this._agents = null; // { at, list }
104
109
  this._pushTimers = new Map(); // roomKey -> timer (live copies to the room's people)
110
+ this._titles = new Map(); // roomKey -> the title last sent to the room's people
105
111
  // Team chats with people travel over the sharing links (peer/sharing.js _wireRooms).
106
112
  if (remote) {
107
113
  remote.onRoom = (method, params, fromGw) => this.onRoom(method, params, fromGw);
108
114
  remote.onPeerReady = gw => this.onPeerReady(gw);
109
115
  remote.onFirstShares = () => this.resyncCopies();
116
+ remote.onSharesChanged = () => this.reconcileConnections();
110
117
  }
111
118
  }
112
119
 
113
120
  /** This gateway's id on the signal server (a person's id in rooms), or null without sharing. */
114
121
  _selfId() { try { return this.remote?.gatewayId?.() || null; } catch { return null; } }
115
122
 
123
+ /**
124
+ * An agent's name for the whole room, the same on every gateway: `<owner gateway>:<agent id as its
125
+ * owner shared it>`. A host's `main` and a guest's `main` never collide, and an entry keeps its
126
+ * author when members come and go.
127
+ */
128
+ _ref(agentId) {
129
+ if (!TeamCoordinator.isRemote(agentId)) return `${this._selfId() || 'local'}:${agentId}`;
130
+ const id = /^peer:([^:]+):(.+)$/.exec(agentId);
131
+ const owner = this.remote?.ownerOf?.(agentId);
132
+ return owner && id ? `${owner}:${id[2]}` : agentId;
133
+ }
134
+
135
+ /** Whether an entry's author is someone else's agent (in a live copy: not one of this gateway's). */
136
+ _isOthersAgent(author) {
137
+ if (!author || author.type !== 'agent') return false;
138
+ if (TeamCoordinator.isRemote(author.agentId)) return true;
139
+ return !!author.ownerId && author.ownerId !== this._selfId();
140
+ }
141
+
116
142
  // ── Lens hooks ─────────────────────────────────────────────────────
117
143
 
118
144
  isWorkKey(key) {
119
145
  if (!this._workKeys) this._workKeys = this.store.workKeys();
120
- return this._workKeys.has(key);
146
+ if (this._workKeys.has(key)) return true;
147
+ // An agent of this gateway answering in someone else's room is internal (like a bot's state), once
148
+ // the room itself is here as a copy. Without a copy it stays listed: the owner sees what it did.
149
+ const g = this.remote?.guestSessionOf?.(key);
150
+ return !!g && !!this.store.replicaFor(g.requesterGatewayId, g.roomId);
121
151
  }
122
152
 
123
153
  _workKeysChanged() { this._workKeys = null; }
124
154
 
155
+ /** The gateway patched a session: a room of mine that was renamed tells its people's copies (they follow its title). */
156
+ async onSessionPatched(key) {
157
+ const room = this.store.getRoom(key);
158
+ if (!room || room.host || !room.people.length) return;
159
+ const title = await this._roomRealTitle(key);
160
+ if (this._titles.get(key) !== title) this._pushSoon(key);
161
+ }
162
+
125
163
  /** The gateway reported a session deleted. */
126
164
  onSessionDeleted(key) {
127
165
  if (this.store.getRoom(key)) { this._dissolve(key); return; }
@@ -193,6 +231,7 @@ export class TeamCoordinator {
193
231
  return {
194
232
  roomKey: r.roomKey,
195
233
  discuss: r.discuss,
234
+ mentionOnly: r.mentionOnly,
196
235
  rounds: r.rounds,
197
236
  sourceKey: r.sourceKey,
198
237
  createdAt: r.createdAt,
@@ -214,8 +253,9 @@ export class TeamCoordinator {
214
253
  * Create a team chat. With `sourceKey`, an existing chat becomes the first agent's working
215
254
  * session (it keeps its memory) and is hidden from the thread list.
216
255
  */
217
- async createRoom({ agentIds = [], sourceKey = null, category, label } = {}) {
256
+ async createRoom({ agentIds = [], personIds = [], sourceKey = null, category, label, mentionOnly = false } = {}) {
218
257
  const agents = [...new Set(agentIds.filter(a => typeof a === 'string' && a))];
258
+ const people = [...new Set(personIds.filter(a => typeof a === 'string' && a))];
219
259
  const members = [];
220
260
  if (sourceKey) {
221
261
  const src = /^agent:([^:]+):/.exec(sourceKey)?.[1];
@@ -224,15 +264,31 @@ export class TeamCoordinator {
224
264
  members.push({ agentId: src, workKey: sourceKey, seenAt: Date.now() });
225
265
  }
226
266
  for (const a of agents) if (!members.some(m => m.agentId === a)) members.push({ agentId: a });
227
- if (members.length < 2) throw new Error('a team chat needs at least two agents');
267
+ for (const pid of people) if (!this.remote?.contact?.(pid)) throw new Error('Connect with them first (Settings → People)');
268
+ // The room's session belongs to one of this gateway's agents. A chat with people and no agent of
269
+ // this gateway picked (people only) keeps the default agent there, quiet unless @mentioned.
270
+ if (!members.some(m => !TeamCoordinator.isRemote(m.agentId))) {
271
+ const list = await this.agents();
272
+ const own = list.find(a => !a.remote);
273
+ if (!own) throw new Error('no agent to host this chat');
274
+ members.unshift({ agentId: own.agentId });
275
+ }
276
+ if (members.length + people.length < 2) throw new Error('a team chat needs at least two participants');
228
277
  const known = new Set((await this.agents()).map(a => a.agentId));
229
278
  const unknown = members.find(m => !known.has(m.agentId));
230
279
  if (unknown) throw new Error(`unknown agent: ${unknown.agentId}`);
231
280
 
232
281
  const roomKey = `agent:${members[0].agentId}:dashboard:${crypto.randomUUID()}`;
233
282
  // Register first so the lens never shows a working session or forwards a half-made room.
234
- this.store.createRoom(roomKey, members, { sourceKey });
283
+ this.store.createRoom(roomKey, members, { sourceKey, mentionOnly: !!mentionOnly });
235
284
  this._workKeysChanged();
285
+ // Labels are unique per gateway and the source chat still holds this one: it steps aside (as the
286
+ // hidden working session) so the team chat can take it; it gets it back when the room goes.
287
+ const title = typeof label === 'string' ? label.trim().slice(0, 200) : '';
288
+ if (sourceKey && title) {
289
+ await this.request('sessions.patch', { key: sourceKey, label: `${title}${SOURCE_LABEL_SUFFIX}${sourceKey.slice(-8)}`.slice(0, 200) })
290
+ .catch(e => this.log.warn?.(`[team] free label of ${sourceKey}: ${e.message}`));
291
+ }
236
292
  try {
237
293
  await this.request('sessions.create', {
238
294
  key: roomKey, agentId: members[0].agentId,
@@ -242,8 +298,12 @@ export class TeamCoordinator {
242
298
  } catch (e) {
243
299
  this.store.deleteRoom(roomKey);
244
300
  this._workKeysChanged();
301
+ if (sourceKey && title) this._restoreSourceLabel(sourceKey);
245
302
  throw e;
246
303
  }
304
+ // Everyone picked comes in, and so does the owner of every shared agent picked (see _ensureOwners).
305
+ for (const pid of people) await this.addPerson(roomKey, pid, { history: 'all' }).catch(e => this.log.warn?.(`[team] add ${pid}: ${e.message}`));
306
+ await this._ensureOwners(roomKey);
247
307
  this._changed();
248
308
  return this.room(roomKey);
249
309
  }
@@ -257,8 +317,9 @@ export class TeamCoordinator {
257
317
  const room = this.store.getRoom(roomKey);
258
318
  if (!room) return null;
259
319
  if (!room.sourceKey) throw new Error('this team chat was not converted from a chat');
260
- this._dissolve(roomKey);
320
+ this._dissolve(roomKey, { restoreLabel: false });
261
321
  await this.request('sessions.delete', { key: roomKey }).catch(e => this.log.warn?.(`[team] delete room ${roomKey}: ${e.message}`));
322
+ await this._restoreSourceLabel(room.sourceKey); // once the room no longer holds the title
262
323
  return room.sourceKey;
263
324
  }
264
325
 
@@ -266,7 +327,7 @@ export class TeamCoordinator {
266
327
  * Forget a room and delete its working sessions — except the chat it was converted from, which is
267
328
  * the user's own chat and becomes a normal thread again (deleting the room must never delete it).
268
329
  */
269
- _dissolve(roomKey) {
330
+ _dissolve(roomKey, { restoreLabel = true } = {}) {
270
331
  const before = this.store.getRoom(roomKey);
271
332
  const source = before?.sourceKey;
272
333
  for (const p of before?.people || []) this._pushEnded(roomKey, p.personId, 'deleted');
@@ -275,10 +336,25 @@ export class TeamCoordinator {
275
336
  this.stop(roomKey);
276
337
  const work = this.store.deleteRoom(roomKey).filter(w => w !== source);
277
338
  this._workKeysChanged();
339
+ if (source && restoreLabel) this._restoreSourceLabel(source);
278
340
  for (const w of work) this.request('sessions.delete', { key: w }).catch(e => this.log.warn?.(`[team] delete ${w}: ${e.message}`));
279
341
  this._changed();
280
342
  }
281
343
 
344
+ /** A converted chat that's a normal chat again takes back the label it gave its team chat. */
345
+ async _restoreSourceLabel(sourceKey) {
346
+ try {
347
+ const label = (await this.request('sessions.describe', { key: sourceKey }, 5000))?.session?.label || '';
348
+ const i = label.lastIndexOf(SOURCE_LABEL_SUFFIX);
349
+ if (i <= 0) return;
350
+ const original = label.slice(0, i);
351
+ await this.request('sessions.patch', { key: sourceKey, label: original }).catch(e => {
352
+ // The title was taken meanwhile (e.g. the deleted room still holds it): keep the stepped-aside one.
353
+ if (!/label already in use/i.test(e.message)) throw e;
354
+ });
355
+ } catch (e) { this.log.warn?.(`[team] restore label of ${sourceKey}: ${e.message}`); }
356
+ }
357
+
282
358
  /**
283
359
  * history 'now': the agent starts from here, without what was said before. Someone else's agent
284
360
  * brings its owner into the room (they can see what their agent sees), with the same history choice.
@@ -286,26 +362,59 @@ export class TeamCoordinator {
286
362
  async addAgent(roomKey, agentId, { history = 'all' } = {}) {
287
363
  const room = this.store.getRoom(roomKey);
288
364
  if (room?.host) throw new Error("Only the chat's host can add agents");
289
- if (!(await this.agents()).some(a => a.agentId === agentId)) throw new Error(`unknown agent: ${agentId}`);
365
+ const named = (await this.agents()).find(a => a.agentId === agentId);
366
+ if (!named) throw new Error(`unknown agent: ${agentId}`);
367
+ const fresh = !room?.members.some(m => m.agentId === agentId);
290
368
  if (!this.store.addMember(roomKey, agentId, { history, seenAt: history === 'now' ? Date.now() : 0 })) return null;
291
- const owner = TeamCoordinator.isRemote(agentId) ? this.remote?.ownerOf?.(agentId) : null;
292
- if (owner && !room.people.some(p => p.personId === owner)) {
293
- await this.addPerson(roomKey, owner, { history }).catch(e => this.log.warn?.(`[team] add ${owner} with their agent: ${e.message}`));
294
- }
369
+ await this._ensureOwners(roomKey, { history });
370
+ if (fresh) await this._note(roomKey, `${named.name} joined`);
295
371
  this._changed();
296
372
  this._pushSoon(roomKey);
297
373
  return this.room(roomKey);
298
374
  }
299
375
 
300
- removeAgent(roomKey, agentId) {
376
+ /**
377
+ * Whoever owns a shared agent in the room is in the room too: they can see what their agent sees,
378
+ * and the room can't hold an agent whose owner has no copy. Called on every membership change.
379
+ */
380
+ async _ensureOwners(roomKey, { history = 'all' } = {}) {
381
+ const room = this.store.getRoom(roomKey);
382
+ if (!room || room.host) return;
383
+ for (const m of room.members) {
384
+ const owner = TeamCoordinator.isRemote(m.agentId) ? this.remote?.ownerOf?.(m.agentId) : null;
385
+ if (owner && !room.people.some(p => p.personId === owner)) {
386
+ await this.addPerson(roomKey, owner, { history: m.history === 'now' ? 'now' : history }).catch(e => this.log.warn?.(`[team] add ${owner} with their agent: ${e.message}`));
387
+ }
388
+ }
389
+ }
390
+
391
+ async removeAgent(roomKey, agentId, { reason = 'removed' } = {}) {
301
392
  const r = this.store.getRoom(roomKey);
302
393
  if (!r) return null;
303
394
  if (r.host) throw new Error("Only the chat's host can remove agents");
304
- if (r.members.length <= 2 && r.members.some(m => m.agentId === agentId)) throw new Error('a team chat needs at least two agents');
395
+ const left = r.members.filter(m => m.agentId !== agentId).length;
396
+ if (!r.members.some(m => m.agentId === agentId)) return this.room(roomKey);
397
+ // Someone has to keep the room's session: the last agent stays unless people are talking without it.
398
+ // (An agent that's no longer shared goes whatever the count: it can't answer any more.)
399
+ if (reason !== 'ended' && (left < 1 || (!r.people.length && left < 2))) throw new Error(r.people.length ? 'a team chat keeps at least one agent' : 'a team chat needs at least two agents');
305
400
  // The working session stays, hidden: it's the agent's memory of this room if it's added back.
306
401
  this.store.removeMember(roomKey, agentId);
307
402
  this._workKeysChanged();
403
+ const name = (await this._named([agentId]))[0]?.name || 'An agent';
404
+ await this._note(roomKey, `${name} ${reason === 'left' ? 'left' : reason === 'ended' ? 'is no longer shared' : 'was removed'}`);
405
+ this._changed();
406
+ this._pushSoon(roomKey);
407
+ return this.room(roomKey);
408
+ }
409
+
410
+ /** Host setting: agents answer only when @mentioned (chats between people, with the agents quiet). */
411
+ setMentionOnly(roomKey, on) {
412
+ const r = this.store.getRoom(roomKey);
413
+ if (!r) return null;
414
+ if (r.host) throw new Error("Only the chat's host can change this");
415
+ this.store.setMentionOnly(roomKey, !!on);
308
416
  this._changed();
417
+ this._pushSoon(roomKey);
309
418
  return this.room(roomKey);
310
419
  }
311
420
 
@@ -385,13 +494,14 @@ export class TeamCoordinator {
385
494
  let targets, mode;
386
495
  if (mention.all) { targets = agents.map(a => a.agentId); mode = 'addressed'; }
387
496
  else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
388
- else { targets = agents.map(a => a.agentId); mode = 'open'; }
497
+ else { targets = room.mentionOnly ? [] : agents.map(a => a.agentId); mode = 'open'; }
389
498
  // A person's own agents answer them on their own gateway (their connector runs them at full
390
499
  // strength); this gateway never runs them for that person's messages.
391
500
  if (fromPerson) targets = targets.filter(id => !(TeamCoordinator.isRemote(id) && this.remote?.ownerOf?.(id) === fromPerson));
392
501
 
393
- const maxRounds = room.discuss ? room.rounds : 1;
394
- const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length;
502
+ // Without "discuss" an agent still answers once when a reply @mentions it (a few rounds at most).
503
+ const maxRounds = room.discuss ? room.rounds : MENTION_ROUNDS;
504
+ const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length * 2;
395
505
  let turns = 0;
396
506
  // Authority comes from who asked (specs/sharing-people.md): the first round answers the owner,
397
507
  // so this gateway's agents run as themselves. A follow-up answers the previous round's replies:
@@ -403,17 +513,16 @@ export class TeamCoordinator {
403
513
  let round = 1;
404
514
  if (firstReplies) {
405
515
  // A person's own agent replied (on their gateway): the follow-up rounds start from that reply.
406
- if (!room.discuss) return;
407
- ({ targets, actingFor } = this._nextRound(agents, firstReplies));
516
+ ({ targets, actingFor } = room.discuss ? this._nextRound(agents, firstReplies) : this._mentionRound(agents, firstReplies));
408
517
  round = 2;
409
- mode = 'followup';
518
+ mode = room.discuss ? 'followup' : 'addressed';
410
519
  }
411
520
  for (; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
412
521
  targets = targets.slice(0, maxTurns - turns);
413
522
  turns += targets.length;
414
523
  const history = await this._roomEntries(roomKey);
415
524
  const results = await Promise.all(targets.map(agentId =>
416
- this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped, actingFor.get(agentId) || null)
525
+ this._turn(roomKey, agentId, agents, history, round === 1 ? mode : room.discuss ? 'followup' : 'addressed', stopped, actingFor.get(agentId) || null)
417
526
  .catch(async e => {
418
527
  // Shown in the room, like a failed turn in a normal chat, not only as a passing toast.
419
528
  this.log.warn?.(`[team] ${agentId} in ${roomKey}: ${e.message}`);
@@ -424,8 +533,22 @@ export class TeamCoordinator {
424
533
  })));
425
534
  const replied = results.filter(r => r?.text);
426
535
  if (!replied.length || stopped()) break;
427
- ({ targets, actingFor } = this._nextRound(agents, replied));
536
+ ({ targets, actingFor } = room.discuss ? this._nextRound(agents, replied) : this._mentionRound(agents, replied));
537
+ }
538
+ }
539
+
540
+ /** Next round without "discuss": only agents a reply @mentions by name (not whole words), never the replier itself. */
541
+ _mentionRound(agents, replied) {
542
+ const targets = [];
543
+ const actingFor = new Map();
544
+ for (const r of replied) {
545
+ for (const id of parseMentions(r.text, agents).agentIds || []) {
546
+ if (id === r.agentId || targets.includes(id)) continue;
547
+ targets.push(id);
548
+ if (!TeamCoordinator.isRemote(id) && r.authority) actingFor.set(id, r.authority);
549
+ }
428
550
  }
551
+ return { targets, actingFor };
429
552
  }
430
553
 
431
554
  /** Next round: agents that replied or were named, if a sibling said something they haven't seen. */
@@ -450,9 +573,10 @@ export class TeamCoordinator {
450
573
  const self = agents.find(a => a.agentId === agentId) || { agentId, name: agentId };
451
574
  const authors = this.store.authors(roomKey);
452
575
  // In a live copy the agent's own replies come back under its id in the host's room.
453
- const ownIds = new Set([agentId, ...(room.host?.members || []).filter(m => m.localAgentId === agentId).map(m => m.agentId)]);
454
- const fresh = history.filter(e => e.ts > member.seenAt && !ownIds.has(authors[e.id]?.agentId))
455
- .map(e => (TeamCoordinator.isRemote(authors[e.id]?.agentId) ? { ...e, remote: true } : e));
576
+ const mineInHost = (room.host?.members || []).filter(m => m.localAgentId === agentId);
577
+ const ownIds = new Set([agentId, ...mineInHost.flatMap(m => [m.agentId, m.ref].filter(Boolean))]);
578
+ const fresh = history.filter(e => e.ts > member.seenAt && authors[e.id]?.type !== 'system' && !ownIds.has(authors[e.id]?.agentId))
579
+ .map(e => (this._isOthersAgent(authors[e.id]) ? { ...e, remote: true } : e));
456
580
  if (!fresh.length) return null;
457
581
  // First turn: the chat's earlier history too (a chat turned into a team chat), unless it was
458
582
  // added "from now on". The chat's own agent already has it in its session.
@@ -580,8 +704,13 @@ export class TeamCoordinator {
580
704
  }
581
705
 
582
706
  async _roomTitle(roomKey) {
707
+ return (await this._roomRealTitle(roomKey)) || 'team chat';
708
+ }
709
+
710
+ /** The room's title, or '' while it has none (copies are then named after who's in the chat). */
711
+ async _roomRealTitle(roomKey) {
583
712
  const s = (await this.request('sessions.describe', { key: roomKey }, 5000).catch(() => null))?.session;
584
- return s?.label || s?.derivedTitle || 'team chat';
713
+ return s?.label || s?.derivedTitle || '';
585
714
  }
586
715
 
587
716
  /**
@@ -708,26 +837,42 @@ export class TeamCoordinator {
708
837
  // specs/sharing-people.md: the room stays on the host's gateway; each person in it gets a live copy
709
838
  // on their own gateway (room.sync over the sharing link) and posts back through it (room.post).
710
839
 
711
- /** Add a contact to a room. history 'now': they see only what's said from here on. */
712
- async addPerson(roomKey, personId, { history = 'all' } = {}) {
840
+ /**
841
+ * Add a contact to a room. history 'now': they see only what's said from here on.
842
+ * quietAgents (adding from the members popover): the chat's first other person turns on "agents
843
+ * reply only when @mentioned"; a chat with people already keeps whatever the host chose. Creating a
844
+ * chat decides that itself, so it doesn't pass this.
845
+ */
846
+ async addPerson(roomKey, personId, { history = 'all', quietAgents = false } = {}) {
713
847
  const room = this.store.getRoom(roomKey);
714
848
  if (!room) return null;
715
849
  if (room.host) throw new Error("Only the chat's host can add people");
716
850
  const c = this.remote?.contact?.(personId);
717
851
  if (!c) throw new Error('Connect with them first (Settings → People)');
852
+ const already = room.people.some(p => p.personId === personId);
853
+ if (quietAgents && !already && !room.people.length && !room.mentionOnly) this.store.setMentionOnly(roomKey, true);
718
854
  this.store.addPerson(roomKey, { personId, name: c.name, email: c.email, historyFrom: history === 'now' ? Date.now() : 0 });
855
+ if (!already) await this._note(roomKey, `${c.name} joined`);
719
856
  this._changed();
720
857
  this._pushPerson(roomKey, personId, { full: true });
721
858
  return this.room(roomKey);
722
859
  }
723
860
 
724
- /** Take a person out (or they left): their agents leave with them; their copy is told. */
725
- removePerson(roomKey, personId, { reason = 'removed' } = {}) {
861
+ /**
862
+ * Take a person out (or they left, or their connection ended): their agents leave with them, the
863
+ * room says so, and their copy is told: it stays as a read-only archive.
864
+ */
865
+ async removePerson(roomKey, personId, { reason = 'removed' } = {}) {
726
866
  const room = this.store.getRoom(roomKey);
727
867
  if (!room || room.host) return null;
868
+ const person = room.people.find(p => p.personId === personId);
869
+ if (!person) return this.room(roomKey);
728
870
  for (const m of room.members) {
729
871
  if (TeamCoordinator.isRemote(m.agentId) && this.remote?.ownerOf?.(m.agentId) === personId) this.store.removeMember(roomKey, m.agentId);
730
872
  }
873
+ await this._note(roomKey, `${person.name} ${reason === 'left' ? 'left' : reason === 'disconnected' ? 'is no longer connected' : 'was removed'}`);
874
+ // The removed person's copy gets the room as it was up to this line, then its ended state.
875
+ if (reason !== 'left') await this._pushPerson(roomKey, personId).catch(() => {});
731
876
  this.store.removePerson(roomKey, personId);
732
877
  this._workKeysChanged();
733
878
  this._changed();
@@ -736,6 +881,15 @@ export class TeamCoordinator {
736
881
  return this.room(roomKey);
737
882
  }
738
883
 
884
+ /** A line in the room's timeline ("Kamil joined"): the same on every screen, never shown to agents. */
885
+ async _note(roomKey, text) {
886
+ try {
887
+ const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label: 'System' });
888
+ if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'system' });
889
+ this._pushSoon(roomKey);
890
+ } catch (e) { this.log.warn?.(`[team] note in ${roomKey}: ${e.message}`); }
891
+ }
892
+
739
893
  /** Something changed in a room: bring every person's copy up to date (batched). */
740
894
  _pushSoon(roomKey) {
741
895
  if (this._pushTimers.has(roomKey)) return;
@@ -776,22 +930,26 @@ export class TeamCoordinator {
776
930
  const { label, body } = splitLabel(text);
777
931
  const a = authors[id];
778
932
  let author;
779
- if (a?.type === 'user') author = { type: 'person', personId: self, name: this._hostName() };
933
+ if (a?.type === 'system') author = { type: 'system', name: 'System' }; // `name`: a host that predates timeline lines still shows it as "System"
934
+ else if (a?.type === 'user') author = { type: 'person', personId: self, name: this._hostName() };
780
935
  else if (a?.type === 'person') author = { type: 'person', personId: a.personId, name: a.name || label };
781
936
  else {
782
937
  const remote = a?.agentId && TeamCoordinator.isRemote(a.agentId);
783
- author = { type: 'agent', agentId: a?.agentId || null, name: label || 'Agent', ownerId: remote ? this.remote?.ownerOf?.(a.agentId) || null : self, ...(a?.actingFor ? { actingFor: a.actingFor } : {}) };
938
+ author = { type: 'agent', agentId: a?.agentId || null, ...(a?.agentId ? { ref: this._ref(a.agentId) } : {}), name: label || 'Agent', ownerId: remote ? this.remote?.ownerOf?.(a.agentId) || null : self, ...(a?.actingFor ? { actingFor: a.actingFor } : {}) };
784
939
  }
785
940
  entries.push({ id, ts, text: body, author });
786
941
  }
787
942
  const agents = await this._named(room.members.map(m => m.agentId));
943
+ const title = await this._roomRealTitle(room.roomKey);
944
+ this._titles.set(room.roomKey, title);
788
945
  return {
789
- roomId: room.roomKey, title: await this._roomTitle(room.roomKey), hostName: this._hostName(), full: !!full, entries,
946
+ roomId: room.roomKey, title, hostName: this._hostName(), full: !!full, entries,
790
947
  view: {
791
948
  discuss: room.discuss,
949
+ mentionOnly: room.mentionOnly,
792
950
  members: agents.map(a => {
793
951
  const remote = TeamCoordinator.isRemote(a.agentId);
794
- return { agentId: a.agentId, name: remote ? a.name : `${a.name} · ${this._hostName().split(/\s+/)[0]}`, ownerId: remote ? this.remote?.ownerOf?.(a.agentId) || null : self };
952
+ return { agentId: a.agentId, ref: this._ref(a.agentId), name: remote ? a.name : `${a.name} · ${this.remote?.labelOf?.(self, this._hostName()) || this._hostName().split(/\s+/)[0]}`, ownerId: remote ? this.remote?.ownerOf?.(a.agentId) || null : self };
795
953
  }),
796
954
  people: [{ personId: self, name: this._hostName(), host: true }, ...room.people.map(p => ({ personId: p.personId, name: p.name }))],
797
955
  },
@@ -808,7 +966,7 @@ export class TeamCoordinator {
808
966
  const id = entryId(m), text = messageText(m).trim();
809
967
  if (!id || !text || !['user', 'assistant'].includes(m.role)) continue;
810
968
  out.push({ id: `src:${id}`, ts: Number(m.timestamp) || 0, text,
811
- author: m.role === 'user' ? { type: 'person', personId: self, name: this._hostName() } : { type: 'agent', agentId: null, name: `${agentName} · ${this._hostName().split(/\s+/)[0]}`, ownerId: self } });
969
+ author: m.role === 'user' ? { type: 'person', personId: self, name: this._hostName() } : { type: 'agent', agentId: null, name: `${agentName} · ${this.remote?.labelOf?.(self, this._hostName()) || this._hostName().split(/\s+/)[0]}`, ownerId: self } });
812
970
  }
813
971
  return out;
814
972
  }
@@ -835,7 +993,16 @@ export class TeamCoordinator {
835
993
  const person = room && !room.host ? room.people.find(x => x.personId === fromGw) : null;
836
994
  if (!person) throw Object.assign(new Error("You're not in this team chat"), { code: 'not_member' });
837
995
  if (method === 'room.fetch') { this._pushPerson(room.roomKey, fromGw, { full: true }); return { ok: true }; }
838
- if (method === 'room.leave') { this.removePerson(room.roomKey, fromGw, { reason: 'left' }); return { ok: true }; }
996
+ if (method === 'room.leave') {
997
+ if (p.agentId) { // just one of their agents
998
+ const m = room.members.find(x => x.agentId === p.agentId || this._ref(x.agentId) === p.agentId);
999
+ if (!m || this.remote?.ownerOf?.(m.agentId) !== fromGw) throw Object.assign(new Error('Not your agent'), { code: 'forbidden' });
1000
+ await this.removeAgent(room.roomKey, m.agentId, { reason: 'left' });
1001
+ return { ok: true };
1002
+ }
1003
+ await this.removePerson(room.roomKey, fromGw, { reason: 'left' });
1004
+ return { ok: true };
1005
+ }
839
1006
  if (method === 'room.post') return this._personPost(room, person, p);
840
1007
  throw Object.assign(new Error('unknown method'), { code: 'bad_request' });
841
1008
  }
@@ -873,12 +1040,17 @@ export class TeamCoordinator {
873
1040
  for (const roomKey of this.store.roomsWithPerson(gw)) this._pushPerson(roomKey, gw, { full: true });
874
1041
  }
875
1042
 
876
- /** On start, each live copy asks its host for what it missed (dials the host when this side can). */
1043
+ /** On start, each live copy asks its host for what it missed (dials the host when this side can); hosted rooms re-check that every agent's owner is in. */
877
1044
  resyncCopies() {
878
1045
  for (const r of this.store.listRooms()) {
879
- if (!r.host || r.host.ended) continue;
1046
+ if (!r.host) { this._ensureOwners(r.roomKey).catch(() => {}); continue; }
1047
+ if (r.host.ended) continue;
880
1048
  this.remote?.personRequest?.(r.host.gatewayId, 'room.fetch', { roomId: r.host.roomId })
881
- .catch(e => this.log.info?.(`[team] copy ${r.roomKey}: host not reachable yet (${e.message})`));
1049
+ .catch(e => {
1050
+ // The host no longer has us in it (it was told while this gateway was off, or the room is gone).
1051
+ if (e?.code === 'not_member') return this._endCopy(r.roomKey, 'removed');
1052
+ this.log.info?.(`[team] copy ${r.roomKey}: host not reachable yet (${e.message})`);
1053
+ });
882
1054
  }
883
1055
  }
884
1056
 
@@ -889,7 +1061,9 @@ export class TeamCoordinator {
889
1061
  const v = r.host;
890
1062
  return {
891
1063
  discuss: !!v.discuss,
892
- agents: (v.members || []).map(m => ({ agentId: m.agentId, workKey: null, remote: true, name: m.name, ownerName: null, available: !v.ended, mine: !!m.localAgentId })),
1064
+ mentionOnly: !!v.mentionOnly,
1065
+ // Keyed by the room-wide ref (the host's `main` and this gateway's `main` are different agents).
1066
+ agents: (v.members || []).map(m => ({ agentId: m.ref || m.agentId, workKey: null, remote: true, name: m.name, ownerName: null, available: !v.ended, mine: !!m.localAgentId })),
893
1067
  people: (v.people || []).map(p => ({ personId: p.personId, name: p.name, ...(p.host ? { host: true } : {}), ...(p.personId === me ? { me: true } : {}) })),
894
1068
  replica: { hostName: v.name, hostId: v.gatewayId, ended: v.ended || null },
895
1069
  };
@@ -911,14 +1085,15 @@ export class TeamCoordinator {
911
1085
  async _replicaSyncNow(p, fromGw, roomId) {
912
1086
  let key = this.store.replicaFor(fromGw, roomId);
913
1087
  if (p.ended) {
914
- if (key) { this.store.setReplica(key, { ended: String(p.ended).slice(0, 20) }); this._changed(); }
1088
+ if (key) await this._endCopy(key, String(p.ended).slice(0, 20));
915
1089
  return { ok: true };
916
1090
  }
917
1091
  const contact = this.remote?.contact?.(fromGw);
918
1092
  if (!contact) throw Object.assign(new Error('Not connected'), { code: 'not_connected' });
919
1093
  const clean = (v, n = 100) => String(v || '').replace(/[\u0000-\u001f\u007f[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, n);
920
1094
  const hostName = clean(p.hostName) || contact.name;
921
- const title = clean(p.title, 120) || 'team chat';
1095
+ const title = clean(p.title, 120); // '' until the host's chat has one: the copy is named after who's in it
1096
+ const prevTitle = this.store.getRoom(key || '')?.host?.title ?? null;
922
1097
  let created = false;
923
1098
  if (!key) {
924
1099
  const list = (await this.request('agents.list', {}))?.agents || [];
@@ -926,22 +1101,29 @@ export class TeamCoordinator {
926
1101
  key = `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
927
1102
  this.store.createReplica(key, { hostGatewayId: fromGw, hostRoom: roomId, hostName });
928
1103
  this._workKeysChanged();
929
- const create = label => this.request('sessions.create', { key, agentId, label: label.slice(0, 200) });
930
- try { await create(`${title} · ${hostName}`); }
1104
+ const create = label => this.request('sessions.create', { key, agentId, ...(label ? { label: label.slice(0, 200) } : {}) });
1105
+ try { await create(title ? `${title} · ${hostName}` : ''); }
931
1106
  catch (e) {
932
1107
  if (!/label already in use/i.test(e.message)) { this.store.deleteRoom(key); throw e; }
933
- await create(`${title} · ${hostName} · ${key.slice(-4)}`);
1108
+ await create(`${title || 'team chat'} · ${hostName} · ${key.slice(-4)}`);
934
1109
  }
935
1110
  created = true;
936
1111
  }
937
1112
  const v = p.view || {};
938
1113
  const view = {
1114
+ title,
939
1115
  discuss: !!v.discuss,
940
- members: (Array.isArray(v.members) ? v.members : []).slice(0, 50).map(m => ({ agentId: clean(m?.agentId, 200), name: clean(m?.name) || 'Agent', ownerId: clean(m?.ownerId, 100) || null })).filter(m => m.agentId),
1116
+ mentionOnly: !!v.mentionOnly,
1117
+ members: (Array.isArray(v.members) ? v.members : []).slice(0, 50).map(m => ({ agentId: clean(m?.agentId, 200), ...(m?.ref ? { ref: clean(m.ref, 240) } : {}), name: clean(m?.name) || 'Agent', ownerId: clean(m?.ownerId, 100) || null })).filter(m => m.agentId),
941
1118
  people: (Array.isArray(v.people) ? v.people : []).slice(0, 50).map(x => ({ personId: clean(x?.personId, 100), name: clean(x?.name) || 'Someone', ...(x?.host ? { host: true } : {}) })).filter(x => x.personId),
942
1119
  };
943
1120
  await this._replicaOwnMembers(key, view);
944
1121
  this.store.setReplica(key, { hostName, view, ended: null });
1122
+ // The host titled its chat (or renamed it): the copy follows.
1123
+ if (!created && title && title !== prevTitle) {
1124
+ const patch = label => this.request('sessions.patch', { key, label: label.slice(0, 200) });
1125
+ await patch(`${title} · ${hostName}`).catch(e => (/label already in use/i.test(e.message) ? patch(`${title} · ${hostName} · ${key.slice(-4)}`) : null)).catch(() => {});
1126
+ }
945
1127
  const me = this._selfId();
946
1128
  const entries = (Array.isArray(p.entries) ? p.entries : []).slice(-300).sort((a, b) => (Number(a?.ts) || 0) - (Number(b?.ts) || 0));
947
1129
  for (const e of entries) {
@@ -950,13 +1132,15 @@ export class TeamCoordinator {
950
1132
  if (!id || !text || this.store.mirrored(key, id)) continue;
951
1133
  const a = e.author || {};
952
1134
  const mine = a.type === 'person' && a.personId === me;
953
- const label = clean(a.name) || (a.type === 'agent' ? 'Agent' : 'Someone');
1135
+ const label = a.type === 'system' ? 'System' : clean(a.name) || (a.type === 'agent' ? 'Agent' : 'Someone');
954
1136
  const res = await this.request('chat.inject', { sessionKey: key, message: text, label });
955
1137
  if (!res?.messageId) continue;
956
1138
  this.store.recordMirror(key, id, res.messageId);
957
- this.store.recordEntry(key, res.messageId, mine ? { type: 'user' }
958
- : a.type === 'person' ? { type: 'person', agentId: clean(a.personId, 100), actingFor: label }
959
- : { type: 'agent', agentId: clean(a.agentId, 200) || null, actingFor: a.actingFor ? clean(a.actingFor, 60) : null });
1139
+ const ts = Number(e.ts) || null;
1140
+ this.store.recordEntry(key, res.messageId, a.type === 'system' ? { type: 'system', ts }
1141
+ : mine ? { type: 'user', ts }
1142
+ : a.type === 'person' ? { type: 'person', agentId: clean(a.personId, 100), actingFor: label, ts }
1143
+ : { type: 'agent', agentId: clean(a.ref || a.agentId, 240) || null, ref: a.ref ? clean(a.ref, 240) : null, ownerId: a.ownerId ? clean(a.ownerId, 100) : null, actingFor: a.actingFor ? clean(a.actingFor, 60) : null, ts });
960
1144
  }
961
1145
  this._changed();
962
1146
  if (created) this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-invited', roomKey: key, hostName, title }));
@@ -974,9 +1158,10 @@ export class TeamCoordinator {
974
1158
  const list = (await this.request('agents.list', {}))?.agents || [];
975
1159
  const nameOf = a => a?.identity?.name || a?.name || a?.id;
976
1160
  for (const m of mine) {
977
- const id = /^peer:([^:]+):(.+)$/.exec(m.agentId);
978
- if (!id || !this.remote?.ownsShare?.(id[1])) continue;
979
- const shared = list.find(a => a.id === id[2]);
1161
+ // `ref` is `<owner gateway>:<agent as shared>`; hosts that predate it name the agent by its share instead.
1162
+ const id = m.ref ? { remote: m.ref.slice(m.ref.indexOf(':') + 1) } : /^peer:([^:]+):(.+)$/.exec(m.agentId);
1163
+ if (!id || (!m.ref && !this.remote?.ownsShare?.(id[1]))) continue;
1164
+ const shared = list.find(a => a.id === (m.ref ? id.remote : id[2]));
980
1165
  const guestOf = shared && /\s\(guest\)$/.test(nameOf(shared)) ? list.find(a => nameOf(a) === nameOf(shared).replace(/\s\(guest\)$/, '')) : null;
981
1166
  const local = guestOf || shared;
982
1167
  if (!local) continue;
@@ -988,7 +1173,7 @@ export class TeamCoordinator {
988
1173
  /** This gateway's person writes in someone else's room: the host gets it; this side's own agents answer here. */
989
1174
  async _replicaSend(room, text) {
990
1175
  const h = room.host;
991
- if (h.ended) throw new Error(h.ended === 'deleted' ? `${h.name} deleted this chat` : h.ended === 'left' ? 'You left this chat' : `${h.name} removed you from this chat`);
1176
+ if (h.ended) throw new Error(h.ended === 'deleted' ? `${h.name} ended this chat` : h.ended === 'left' ? 'You left this chat' : h.ended === 'disconnected' ? `You're no longer connected with ${h.name}` : `${h.name} removed you from this chat`);
992
1177
  try {
993
1178
  await this.remote.personRequest(h.gatewayId, 'room.post', { roomId: h.roomId, kind: 'person', text: text.slice(0, 32_000) });
994
1179
  } catch (e) {
@@ -1010,13 +1195,14 @@ export class TeamCoordinator {
1010
1195
  if (entries.some(e => authors[e.id]?.type === 'user' && splitLabel(e.text).body.trim() === text.trim())) break;
1011
1196
  await new Promise(r => setTimeout(r, 250));
1012
1197
  }
1013
- const all = (view.members || []).map(m => ({ agentId: m.localAgentId || m.agentId, name: m.name }));
1198
+ // Everyone in the room by a name that can't clash: mine by their local id, the rest by their room-wide ref.
1199
+ const all = (view.members || []).map(m => ({ agentId: m.localAgentId || m.ref || m.agentId, name: m.name }));
1014
1200
  const mention = parseMentions(text, all);
1015
1201
  const ownIds = own.map(m => m.localAgentId);
1016
1202
  let targets, mode;
1017
1203
  if (mention.all) { targets = ownIds; mode = 'addressed'; }
1018
1204
  else if (mention.agentIds.length) { targets = mention.agentIds.filter(id => ownIds.includes(id)); mode = 'addressed'; }
1019
- else { targets = ownIds; mode = 'open'; }
1205
+ else { targets = view.mentionOnly ? [] : ownIds; mode = 'open'; }
1020
1206
  if (!targets.length || stopped()) return;
1021
1207
  const history = await this._roomEntries(room.roomKey);
1022
1208
  await Promise.all(targets.map(id => this._turn(room.roomKey, id, all, history, mode, stopped)
@@ -1030,16 +1216,64 @@ export class TeamCoordinator {
1030
1216
  await this.remote.personRequest(room.host.gatewayId, 'room.post', { roomId: room.host.roomId, kind: 'agent', agentId: member.agentId, text: text.slice(0, 32_000) });
1031
1217
  }
1032
1218
 
1033
- /** Leave someone else's room (the copy stays, read-only). */
1034
- async leave(roomKey) {
1219
+ /** Leave someone else's room (the copy stays, read-only), or just take one of this gateway's agents out of it. */
1220
+ async leave(roomKey, { agentId = null } = {}) {
1035
1221
  const room = this.store.getRoom(roomKey);
1036
1222
  if (!room?.host) throw new Error('not a live copy of someone else\'s chat');
1223
+ if (room.host.ended) return this.room(roomKey);
1224
+ if (agentId) {
1225
+ const m = (room.host.members || []).find(x => x.agentId === agentId || x.ref === agentId);
1226
+ if (!m || m.ownerId !== this._selfId()) throw new Error('Not your agent');
1227
+ await this.remote.personRequest(room.host.gatewayId, 'room.leave', { roomId: room.host.roomId, agentId: m.ref || m.agentId });
1228
+ return this.room(roomKey);
1229
+ }
1037
1230
  await this.remote?.personRequest?.(room.host.gatewayId, 'room.leave', { roomId: room.host.roomId }).catch(e => this.log.warn?.(`[team] leave: ${e.message}`));
1038
- this.store.setReplica(roomKey, { ended: 'left' });
1039
- this._changed();
1231
+ await this._endCopy(roomKey, 'left');
1040
1232
  return this.room(roomKey);
1041
1233
  }
1042
1234
 
1235
+ /** A copy stops: read-only archive, with the reason as a line in its timeline (same wording for everyone who sees it). */
1236
+ async _endCopy(key, reason) {
1237
+ const room = this.store.getRoom(key);
1238
+ if (!room?.host || room.host.ended === reason) return;
1239
+ const host = room.host.name || 'The host';
1240
+ this.store.setReplica(key, { ended: reason });
1241
+ const line = { deleted: `${host} ended this chat`, left: 'You left this chat', removed: `${host} removed you from this chat`, disconnected: `You're no longer connected with ${host}` }[reason] || 'This chat ended';
1242
+ // The host's own line about it ("Kamil was removed") may have reached this copy just before: one line per event.
1243
+ const last = reason === 'removed' ? await this.request('chat.history', { sessionKey: key, limit: 1 }).catch(() => null) : null;
1244
+ const said = (last?.messages || []).some(m => /\swas removed$/.test(messageText(m).replace(/^\[System\]\s*/, '').trim()));
1245
+ if (!said) await this._note(key, line);
1246
+ this._changed();
1247
+ }
1248
+
1249
+ /**
1250
+ * Connections changed (a share ended, or the list reloaded): rooms follow, like Discord when someone
1251
+ * is kicked. A person whose connection is gone leaves the rooms we host; a copy of a room hosted by
1252
+ * someone we're no longer connected with stops (kept, read-only); an agent that's no longer shared leaves.
1253
+ */
1254
+ reconcileConnections() {
1255
+ if (!this.remote) return;
1256
+ clearTimeout(this._reconcileTimer);
1257
+ this._reconcileTimer = setTimeout(() => this._reconcileNow().catch(e => this.log.warn?.(`[team] reconcile: ${e.message}`)), 2500);
1258
+ this._reconcileTimer.unref?.();
1259
+ }
1260
+
1261
+ async _reconcileNow() {
1262
+ const live = new Set((this.remote?.remoteAgents?.() || []).map(a => a.agentId));
1263
+ for (const room of this.store.listRooms()) {
1264
+ if (room.host) {
1265
+ if (!room.host.ended && !this.remote.hasShareWith(room.host.gatewayId)) await this._endCopy(room.roomKey, 'disconnected');
1266
+ continue;
1267
+ }
1268
+ for (const person of room.people) {
1269
+ if (!this.remote.hasShareWith(person.personId)) await this.removePerson(room.roomKey, person.personId, { reason: 'disconnected' });
1270
+ }
1271
+ for (const m of this.store.getRoom(room.roomKey).members) {
1272
+ if (TeamCoordinator.isRemote(m.agentId) && !live.has(m.agentId)) await this.removeAgent(room.roomKey, m.agentId, { reason: 'ended' }).catch(e => this.log.warn?.(`[team] ${e.message}`));
1273
+ }
1274
+ }
1275
+ }
1276
+
1043
1277
  _live(roomKey) {
1044
1278
  let l = this._rooms.get(roomKey);
1045
1279
  if (!l) { l = { running: new Map(), queued: 0, gen: 0 }; this._rooms.set(roomKey, l); }