@clawchatsai/connector 0.1.34 → 0.1.36

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
@@ -101,8 +101,18 @@ export class TeamCoordinator {
101
101
  this._chains = new Map(); // roomKey -> tail promise (one message at a time per room)
102
102
  this._rooms = new Map(); // roomKey -> { running: Map<agentId, {workKey, runId}>, queued, stopped }
103
103
  this._agents = null; // { at, list }
104
+ this._pushTimers = new Map(); // roomKey -> timer (live copies to the room's people)
105
+ // Team chats with people travel over the sharing links (peer/sharing.js _wireRooms).
106
+ if (remote) {
107
+ remote.onRoom = (method, params, fromGw) => this.onRoom(method, params, fromGw);
108
+ remote.onPeerReady = gw => this.onPeerReady(gw);
109
+ remote.onFirstShares = () => this.resyncCopies();
110
+ }
104
111
  }
105
112
 
113
+ /** This gateway's id on the signal server (a person's id in rooms), or null without sharing. */
114
+ _selfId() { try { return this.remote?.gatewayId?.() || null; } catch { return null; } }
115
+
106
116
  // ── Lens hooks ─────────────────────────────────────────────────────
107
117
 
108
118
  isWorkKey(key) {
@@ -195,6 +205,8 @@ export class TeamCoordinator {
195
205
  }),
196
206
  running: live ? [...live.running.keys()] : [],
197
207
  queued: live?.queued || 0,
208
+ people: r.people.map(p => ({ personId: p.personId, name: p.name })),
209
+ ...(r.host ? this._replicaPublic(r) : {}),
198
210
  };
199
211
  }
200
212
 
@@ -255,7 +267,11 @@ export class TeamCoordinator {
255
267
  * the user's own chat and becomes a normal thread again (deleting the room must never delete it).
256
268
  */
257
269
  _dissolve(roomKey) {
258
- const source = this.store.getRoom(roomKey)?.sourceKey;
270
+ const before = this.store.getRoom(roomKey);
271
+ const source = before?.sourceKey;
272
+ for (const p of before?.people || []) this._pushEnded(roomKey, p.personId, 'deleted');
273
+ // A live copy deleted here: leave the host's room too.
274
+ if (before?.host && !before.host.ended) this.remote?.personRequest?.(before.host.gatewayId, 'room.leave', { roomId: before.host.roomId }).catch(() => {});
259
275
  this.stop(roomKey);
260
276
  const work = this.store.deleteRoom(roomKey).filter(w => w !== source);
261
277
  this._workKeysChanged();
@@ -263,16 +279,28 @@ export class TeamCoordinator {
263
279
  this._changed();
264
280
  }
265
281
 
266
- async addAgent(roomKey, agentId) {
282
+ /**
283
+ * history 'now': the agent starts from here, without what was said before. Someone else's agent
284
+ * brings its owner into the room (they can see what their agent sees), with the same history choice.
285
+ */
286
+ async addAgent(roomKey, agentId, { history = 'all' } = {}) {
287
+ const room = this.store.getRoom(roomKey);
288
+ if (room?.host) throw new Error("Only the chat's host can add agents");
267
289
  if (!(await this.agents()).some(a => a.agentId === agentId)) throw new Error(`unknown agent: ${agentId}`);
268
- if (!this.store.addMember(roomKey, agentId)) return null;
290
+ 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
+ }
269
295
  this._changed();
296
+ this._pushSoon(roomKey);
270
297
  return this.room(roomKey);
271
298
  }
272
299
 
273
300
  removeAgent(roomKey, agentId) {
274
301
  const r = this.store.getRoom(roomKey);
275
302
  if (!r) return null;
303
+ if (r.host) throw new Error("Only the chat's host can remove agents");
276
304
  if (r.members.length <= 2 && r.members.some(m => m.agentId === agentId)) throw new Error('a team chat needs at least two agents');
277
305
  // The working session stays, hidden: it's the agent's memory of this room if it's added back.
278
306
  this.store.removeMember(roomKey, agentId);
@@ -283,6 +311,7 @@ export class TeamCoordinator {
283
311
 
284
312
  setDiscuss(roomKey, discuss) {
285
313
  if (!this.store.getRoom(roomKey)) return null;
314
+ if (this.store.getRoom(roomKey).host) throw new Error("Only the chat's host can change this");
286
315
  this.store.setDiscuss(roomKey, !!discuss);
287
316
  this._changed();
288
317
  return this.room(roomKey);
@@ -305,11 +334,19 @@ export class TeamCoordinator {
305
334
  const room = this.store.getRoom(roomKey);
306
335
  if (!room) throw new Error('not a team chat');
307
336
  if (typeof text !== 'string' || !text.trim()) throw new Error('empty message');
337
+ if (room.host) return this._replicaSend(room, text);
308
338
  const label = String(userLabel || 'User').replace(/[\[\]\n]/g, '').trim().slice(0, 100) || 'User';
339
+ this._hostLabel = label; // how this gateway's person shows to the room's people
309
340
  const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label });
310
341
  if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'user' });
311
342
  this._maybeTitle(roomKey, text);
343
+ this._pushSoon(roomKey);
344
+ this._enqueue(roomKey, text);
345
+ return { messageId: res?.messageId || null };
346
+ }
312
347
 
348
+ /** Queue a message's agent turns (one message at a time per room). fromPerson: who wrote it, if not this gateway's person. */
349
+ _enqueue(roomKey, text, { fromPerson = null, replied = null } = {}) {
313
350
  const live = this._live(roomKey);
314
351
  const gen = live.gen; // Stop bumps the generation: everything queued before it is dropped
315
352
  live.queued++;
@@ -318,13 +355,12 @@ export class TeamCoordinator {
318
355
  const next = prev.then(async () => {
319
356
  live.queued--;
320
357
  if (live.gen !== gen) return;
321
- await this._runMessage(roomKey, text, () => live.gen !== gen);
358
+ await this._runMessage(roomKey, text, () => live.gen !== gen, { fromPerson, replied });
322
359
  }).catch(e => {
323
360
  this.log.error?.(`[team] ${roomKey}: ${e.message}`);
324
361
  this._status(roomKey, e.message);
325
362
  }).finally(() => { if (this._chains.get(roomKey) === next) this._chains.delete(roomKey); this._status(roomKey); });
326
363
  this._chains.set(roomKey, next);
327
- return { messageId: res?.messageId || null };
328
364
  }
329
365
 
330
366
  /** Abort running agents and drop queued messages. */
@@ -340,15 +376,19 @@ export class TeamCoordinator {
340
376
  this._status(roomKey);
341
377
  }
342
378
 
343
- async _runMessage(roomKey, text, stopped = () => false) {
379
+ async _runMessage(roomKey, text, stopped = () => false, { fromPerson = null, replied: firstReplies = null } = {}) {
344
380
  const room = this.store.getRoom(roomKey);
345
381
  if (!room) return;
382
+ if (room.host) return this._replicaRunOwn(room, text, stopped);
346
383
  const agents = await this._named(room.members.map(m => m.agentId));
347
384
  const mention = parseMentions(text, agents);
348
385
  let targets, mode;
349
386
  if (mention.all) { targets = agents.map(a => a.agentId); mode = 'addressed'; }
350
387
  else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
351
388
  else { targets = agents.map(a => a.agentId); mode = 'open'; }
389
+ // A person's own agents answer them on their own gateway (their connector runs them at full
390
+ // strength); this gateway never runs them for that person's messages.
391
+ if (fromPerson) targets = targets.filter(id => !(TeamCoordinator.isRemote(id) && this.remote?.ownerOf?.(id) === fromPerson));
352
392
 
353
393
  const maxRounds = room.discuss ? room.rounds : 1;
354
394
  const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length;
@@ -357,8 +397,18 @@ export class TeamCoordinator {
357
397
  // so this gateway's agents run as themselves. A follow-up answers the previous round's replies:
358
398
  // if one came from another person's agent (or from an agent acting for them), this gateway's
359
399
  // agents act for that person, as the version shared with them; never as themselves.
360
- let actingFor = new Map(); // agentId -> remote agent id whose owner it answers this round
361
- for (let round = 1; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
400
+ let actingFor = new Map(); // agentId -> remote agent id / 'person:<gw>' whose request it answers this round
401
+ // Someone else wrote it: this gateway's agents answer them as the versions shared with them.
402
+ if (fromPerson) for (const id of targets) if (!TeamCoordinator.isRemote(id)) actingFor.set(id, `person:${fromPerson}`);
403
+ let round = 1;
404
+ if (firstReplies) {
405
+ // 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));
408
+ round = 2;
409
+ mode = 'followup';
410
+ }
411
+ for (; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
362
412
  targets = targets.slice(0, maxTurns - turns);
363
413
  turns += targets.length;
364
414
  const history = await this._roomEntries(roomKey);
@@ -374,19 +424,24 @@ export class TeamCoordinator {
374
424
  })));
375
425
  const replied = results.filter(r => r?.text);
376
426
  if (!replied.length || stopped()) break;
377
- // Next round: agents that replied or were named, if a sibling said something they haven't seen.
378
- const eligible = new Set(replied.map(r => r.agentId));
379
- for (const r of replied) for (const id of namedIn(r.text, agents)) if (id !== r.agentId) eligible.add(id);
380
- targets = agents.map(a => a.agentId).filter(id => eligible.has(id) && replied.some(r => r.agentId !== id));
381
- actingFor = new Map();
382
- for (const id of targets) {
383
- if (TeamCoordinator.isRemote(id)) continue; // their own gateway decides how its agents run
384
- const by = replied.find(r => r.agentId !== id && r.authority);
385
- if (by) actingFor.set(id, by.authority);
386
- }
427
+ ({ targets, actingFor } = this._nextRound(agents, replied));
387
428
  }
388
429
  }
389
430
 
431
+ /** Next round: agents that replied or were named, if a sibling said something they haven't seen. */
432
+ _nextRound(agents, replied) {
433
+ const eligible = new Set(replied.map(r => r.agentId));
434
+ for (const r of replied) for (const id of namedIn(r.text, agents)) if (id !== r.agentId) eligible.add(id);
435
+ const targets = agents.map(a => a.agentId).filter(id => eligible.has(id) && replied.some(r => r.agentId !== id));
436
+ const actingFor = new Map();
437
+ for (const id of targets) {
438
+ if (TeamCoordinator.isRemote(id)) continue; // their own gateway decides how its agents run
439
+ const by = replied.find(r => r.agentId !== id && r.authority);
440
+ if (by) actingFor.set(id, by.authority);
441
+ }
442
+ return { targets, actingFor };
443
+ }
444
+
390
445
  /** One agent turn. Returns { agentId, text } (text null when silent/aborted). */
391
446
  async _turn(roomKey, agentId, agents, history, mode, stopped = () => false, actingFor = null) {
392
447
  const room = this.store.getRoom(roomKey);
@@ -394,14 +449,19 @@ export class TeamCoordinator {
394
449
  if (!member) return null;
395
450
  const self = agents.find(a => a.agentId === agentId) || { agentId, name: agentId };
396
451
  const authors = this.store.authors(roomKey);
397
- const fresh = history.filter(e => e.ts > member.seenAt && authors[e.id]?.agentId !== agentId)
452
+ // 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))
398
455
  .map(e => (TeamCoordinator.isRemote(authors[e.id]?.agentId) ? { ...e, remote: true } : e));
399
456
  if (!fresh.length) return null;
457
+ // First turn: the chat's earlier history too (a chat turned into a team chat), unless it was
458
+ // added "from now on". The chat's own agent already has it in its session.
459
+ const earlier = member.seenAt === 0 && member.history !== 'now' ? await this._earlier(room, member) : '';
400
460
 
401
- if (TeamCoordinator.isRemote(agentId)) return this._remoteTurn(roomKey, self, fresh, agents, mode, stopped);
402
- if (actingFor) return this._turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history);
461
+ if (TeamCoordinator.isRemote(agentId)) return this._remoteTurn(roomKey, self, fresh, agents, mode, stopped, earlier);
462
+ if (actingFor) return this._turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history, earlier);
403
463
  const workKey = member.workKey || await this._createWorkSession(roomKey, self);
404
- const message = this._prompt(self, agents, fresh, mode);
464
+ const message = this._prompt(self, agents, fresh, mode, earlier);
405
465
  const runId = `team-${crypto.randomUUID()}`;
406
466
  const live = this._live(roomKey);
407
467
  const done = this._waitRun(runId);
@@ -444,7 +504,7 @@ export class TeamCoordinator {
444
504
  * A turn of someone else's agent: runs on their gateway over the peer link (peer/sharing.js).
445
505
  * Streamed text reaches the browser as `team-remote-delta` (there's no local working session).
446
506
  */
447
- async _remoteTurn(roomKey, self, fresh, agents, mode, stopped) {
507
+ async _remoteTurn(roomKey, self, fresh, agents, mode, stopped, earlier = '') {
448
508
  if (!this.remote) throw new Error('sharing is not available');
449
509
  const agentId = self.agentId;
450
510
  const runId = `team-${crypto.randomUUID()}`;
@@ -455,7 +515,7 @@ export class TeamCoordinator {
455
515
  let result, partial = '';
456
516
  try {
457
517
  this.store.setSeenAt(roomKey, agentId, Math.max(...fresh.map(e => e.ts)));
458
- result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode) },
518
+ result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
459
519
  { onDelta: text => { partial = text; delta(text); } });
460
520
  } catch (e) {
461
521
  throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
@@ -480,7 +540,7 @@ export class TeamCoordinator {
480
540
  * that person, under their grant (peer/sharing.js localTurnFor), streamed like a remote agent.
481
541
  * Not shared with them: it stays out, saying so when their agent asked it by name.
482
542
  */
483
- async _turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history) {
543
+ async _turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history, earlier = '') {
484
544
  const agentId = self.agentId;
485
545
  const asker = agents.find(a => a.agentId === actingFor);
486
546
  const forName = this.remote?.actingForName?.(actingFor) || asker?.ownerName || 'someone else';
@@ -492,7 +552,7 @@ export class TeamCoordinator {
492
552
  let result, partial = '';
493
553
  try {
494
554
  this.store.setSeenAt(roomKey, agentId, Math.max(...fresh.map(e => e.ts)));
495
- result = await this.remote?.localTurnFor(agentId, actingFor, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode) },
555
+ result = await this.remote?.localTurnFor(agentId, actingFor, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
496
556
  { onDelta: text => { partial = text; delta(text); } });
497
557
  } catch (e) {
498
558
  throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
@@ -503,7 +563,8 @@ export class TeamCoordinator {
503
563
  }
504
564
  if (!result) {
505
565
  const authors = this.store.authors(roomKey);
506
- const askedByName = history.some(e => authors[e.id]?.agentId === actingFor && e.ts >= Math.min(...fresh.map(f => f.ts))
566
+ const isAsker = a => a?.agentId === actingFor || (a?.type === 'person' && `person:${a.personId}` === actingFor);
567
+ const askedByName = history.some(e => isAsker(authors[e.id]) && e.ts >= Math.min(...fresh.map(f => f.ts))
507
568
  && parseMentions(splitLabel(e.text).body, agents).agentIds?.includes(agentId));
508
569
  if (askedByName) await this._post(roomKey, self, `*${self.name} isn't shared with ${forName}, so it doesn't answer ${forName}'s agents.*`);
509
570
  return { agentId, text: null };
@@ -546,11 +607,14 @@ export class TeamCoordinator {
546
607
 
547
608
  /** Post an agent's message into the room (actingFor: whose request it answered, if not its owner's). */
548
609
  async _post(roomKey, self, text, { actingFor = null } = {}) {
610
+ const room = this.store.getRoom(roomKey);
611
+ if (room?.host) return this._replicaPostAgent(room, self, text); // a live copy: the host's room gets it
549
612
  const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label: self.name.slice(0, 100) });
550
613
  if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId, actingFor });
614
+ this._pushSoon(roomKey);
551
615
  }
552
616
 
553
- _prompt(self, agents, fresh, mode) {
617
+ _prompt(self, agents, fresh, mode, earlier = '') {
554
618
  const others = agents.filter(a => a.agentId !== self.agentId).map(a => a.name);
555
619
  const lines = fresh.map(e => {
556
620
  const { label, body } = splitLabel(e.text);
@@ -566,6 +630,7 @@ export class TeamCoordinator {
566
630
  return [
567
631
  `[Team chat] You are ${self.name}. Other agents here: ${others.join(', ') || 'none'}. Your reply is posted to the team chat as ${self.name}; address someone with @name.`,
568
632
  '',
633
+ ...(earlier ? ['Earlier in this chat (before you joined):', '', earlier, ''] : []),
569
634
  'New messages since your last turn:',
570
635
  '',
571
636
  lines.join('\n\n'),
@@ -639,6 +704,342 @@ export class TeamCoordinator {
639
704
  if (w) { clearTimeout(w.timer); this._waiters.delete(runId); }
640
705
  }
641
706
 
707
+ // ── People in rooms (this gateway hosting) ─────────────────────────
708
+ // specs/sharing-people.md: the room stays on the host's gateway; each person in it gets a live copy
709
+ // on their own gateway (room.sync over the sharing link) and posts back through it (room.post).
710
+
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' } = {}) {
713
+ const room = this.store.getRoom(roomKey);
714
+ if (!room) return null;
715
+ if (room.host) throw new Error("Only the chat's host can add people");
716
+ const c = this.remote?.contact?.(personId);
717
+ if (!c) throw new Error('Connect with them first (Settings → People)');
718
+ this.store.addPerson(roomKey, { personId, name: c.name, email: c.email, historyFrom: history === 'now' ? Date.now() : 0 });
719
+ this._changed();
720
+ this._pushPerson(roomKey, personId, { full: true });
721
+ return this.room(roomKey);
722
+ }
723
+
724
+ /** Take a person out (or they left): their agents leave with them; their copy is told. */
725
+ removePerson(roomKey, personId, { reason = 'removed' } = {}) {
726
+ const room = this.store.getRoom(roomKey);
727
+ if (!room || room.host) return null;
728
+ for (const m of room.members) {
729
+ if (TeamCoordinator.isRemote(m.agentId) && this.remote?.ownerOf?.(m.agentId) === personId) this.store.removeMember(roomKey, m.agentId);
730
+ }
731
+ this.store.removePerson(roomKey, personId);
732
+ this._workKeysChanged();
733
+ this._changed();
734
+ this._pushEnded(roomKey, personId, reason);
735
+ this._pushSoon(roomKey);
736
+ return this.room(roomKey);
737
+ }
738
+
739
+ /** Something changed in a room: bring every person's copy up to date (batched). */
740
+ _pushSoon(roomKey) {
741
+ if (this._pushTimers.has(roomKey)) return;
742
+ const t = setTimeout(() => {
743
+ this._pushTimers.delete(roomKey);
744
+ for (const p of this.store.getRoom(roomKey)?.people || []) this._pushPerson(roomKey, p.personId);
745
+ }, 300);
746
+ t.unref?.();
747
+ this._pushTimers.set(roomKey, t);
748
+ }
749
+
750
+ async _pushPerson(roomKey, personId, { full = false } = {}) {
751
+ try {
752
+ const room = this.store.getRoom(roomKey);
753
+ const person = room?.people.find(p => p.personId === personId);
754
+ if (!person) return;
755
+ await this.remote.personRequest(personId, 'room.sync', await this._syncPayload(room, person, { full }));
756
+ } catch (e) { this.log.warn?.(`[team] copy of ${roomKey} to ${personId}: ${e.message}`); }
757
+ }
758
+
759
+ _pushEnded(roomKey, personId, reason) {
760
+ this.remote?.personRequest?.(personId, 'room.sync', { roomId: roomKey, ended: reason })
761
+ .catch(e => this.log.warn?.(`[team] tell ${personId} the chat ended: ${e.message}`));
762
+ }
763
+
764
+ _hostName() { return this.remote?.selfName?.() || this._hostLabel || 'Host'; }
765
+
766
+ /** What a person's copy gets: the room's view and its entries since they may see them. */
767
+ async _syncPayload(room, person, { full }) {
768
+ const self = this._selfId();
769
+ const authors = this.store.authors(room.roomKey);
770
+ const entries = [];
771
+ if (full && !person.historyFrom && room.sourceKey) entries.push(...await this._sourceEntries(room));
772
+ const h = await this.request('chat.history', { sessionKey: room.roomKey, limit: full ? 200 : 40 }, 30_000);
773
+ for (const m of h?.messages || []) {
774
+ const id = entryId(m), ts = Number(m.timestamp) || 0, text = messageText(m);
775
+ if (!id || !text || ts < person.historyFrom) continue;
776
+ const { label, body } = splitLabel(text);
777
+ const a = authors[id];
778
+ let author;
779
+ if (a?.type === 'user') author = { type: 'person', personId: self, name: this._hostName() };
780
+ else if (a?.type === 'person') author = { type: 'person', personId: a.personId, name: a.name || label };
781
+ else {
782
+ 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 } : {}) };
784
+ }
785
+ entries.push({ id, ts, text: body, author });
786
+ }
787
+ const agents = await this._named(room.members.map(m => m.agentId));
788
+ return {
789
+ roomId: room.roomKey, title: await this._roomTitle(room.roomKey), hostName: this._hostName(), full: !!full, entries,
790
+ view: {
791
+ discuss: room.discuss,
792
+ members: agents.map(a => {
793
+ 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 };
795
+ }),
796
+ people: [{ personId: self, name: this._hostName(), host: true }, ...room.people.map(p => ({ personId: p.personId, name: p.name }))],
797
+ },
798
+ };
799
+ }
800
+
801
+ /** The chat's history from before it became a team chat, as entries for a copy. */
802
+ async _sourceEntries(room) {
803
+ const h = await this.request('chat.history', { sessionKey: room.sourceKey, limit: 60 }, 30_000).catch(() => null);
804
+ const agentName = (await this._named([/^agent:([^:]+):/.exec(room.sourceKey)?.[1] || 'agent']))[0]?.name || 'Agent';
805
+ const self = this._selfId();
806
+ const out = [];
807
+ for (const m of h?.messages || []) {
808
+ const id = entryId(m), text = messageText(m).trim();
809
+ if (!id || !text || !['user', 'assistant'].includes(m.role)) continue;
810
+ 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 } });
812
+ }
813
+ return out;
814
+ }
815
+
816
+ /** The chat's earlier history, for an agent's first turn ('' if none, or it's the chat's own agent). */
817
+ async _earlier(room, member) {
818
+ if (!room?.sourceKey || member.workKey === room.sourceKey) return '';
819
+ const h = await this.request('chat.history', { sessionKey: room.sourceKey, limit: 40 }, 30_000).catch(() => null);
820
+ const agentName = (await this._named([/^agent:([^:]+):/.exec(room.sourceKey)?.[1] || 'agent']))[0]?.name || 'Agent';
821
+ const lines = [];
822
+ for (const m of h?.messages || []) {
823
+ const text = messageText(m).trim();
824
+ if (!text || !['user', 'assistant'].includes(m.role)) continue;
825
+ lines.push(`[${m.role === 'user' ? this._hostLabel || 'User' : agentName}]: ${text}`);
826
+ }
827
+ const all = lines.join('\n\n');
828
+ return all.length > 12_000 ? `…${all.slice(-12_000)}` : all;
829
+ }
830
+
831
+ /** A request from another gateway over the sharing link (peer/sharing.js _wireRooms). fromGw is authenticated. */
832
+ async onRoom(method, p, fromGw) {
833
+ if (method === 'room.sync') return this._replicaSync(p, fromGw);
834
+ const room = this.store.getRoom(String(p.roomId || ''));
835
+ const person = room && !room.host ? room.people.find(x => x.personId === fromGw) : null;
836
+ if (!person) throw Object.assign(new Error("You're not in this team chat"), { code: 'not_member' });
837
+ 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 }; }
839
+ if (method === 'room.post') return this._personPost(room, person, p);
840
+ throw Object.assign(new Error('unknown method'), { code: 'bad_request' });
841
+ }
842
+
843
+ /**
844
+ * A person posted in a room hosted here: their message (this gateway's agents answer them as the
845
+ * versions shared with them), or a reply from one of their own agents (run on their gateway).
846
+ */
847
+ async _personPost(room, person, p) {
848
+ const text = String(p.text || '').slice(0, 32_000);
849
+ if (!text.trim()) throw Object.assign(new Error('empty message'), { code: 'bad_request' });
850
+ if (p.kind === 'agent') {
851
+ const member = room.members.find(m => m.agentId === p.agentId);
852
+ if (!member || this.remote?.ownerOf?.(member.agentId) !== person.personId) throw Object.assign(new Error('Not your agent'), { code: 'forbidden' });
853
+ const self = (await this._named([member.agentId]))[0];
854
+ const res = await this.request('chat.inject', { sessionKey: room.roomKey, message: text, label: self.name.slice(0, 100) });
855
+ if (res?.messageId) this.store.recordEntry(room.roomKey, res.messageId, { type: 'agent', agentId: member.agentId });
856
+ this.store.setSeenAt(room.roomKey, member.agentId, Date.now());
857
+ this._pushSoon(room.roomKey);
858
+ // Follow-up rounds start from it, acting for its owner.
859
+ this._enqueue(room.roomKey, text, { replied: [{ agentId: member.agentId, text, authority: `person:${person.personId}` }] });
860
+ return { messageId: res?.messageId || null };
861
+ }
862
+ const label = person.name.replace(/[[\]\n]/g, ' ').trim().slice(0, 100) || 'Someone';
863
+ const res = await this.request('chat.inject', { sessionKey: room.roomKey, message: text, label });
864
+ if (res?.messageId) this.store.recordEntry(room.roomKey, res.messageId, { type: 'person', agentId: person.personId, actingFor: person.name });
865
+ this._maybeTitle(room.roomKey, text);
866
+ this._pushSoon(room.roomKey);
867
+ this._enqueue(room.roomKey, text, { fromPerson: person.personId });
868
+ return { messageId: res?.messageId || null };
869
+ }
870
+
871
+ /** A link with a contact opened: copies of rooms they're in catch up (a member's copy may be stale). */
872
+ onPeerReady(gw) {
873
+ for (const roomKey of this.store.roomsWithPerson(gw)) this._pushPerson(roomKey, gw, { full: true });
874
+ }
875
+
876
+ /** On start, each live copy asks its host for what it missed (dials the host when this side can). */
877
+ resyncCopies() {
878
+ for (const r of this.store.listRooms()) {
879
+ if (!r.host || r.host.ended) continue;
880
+ 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})`));
882
+ }
883
+ }
884
+
885
+ // ── Live copies (someone else hosts the room) ──────────────────────
886
+
887
+ _replicaPublic(r) {
888
+ const me = this._selfId();
889
+ const v = r.host;
890
+ return {
891
+ 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 })),
893
+ people: (v.people || []).map(p => ({ personId: p.personId, name: p.name, ...(p.host ? { host: true } : {}), ...(p.personId === me ? { me: true } : {}) })),
894
+ replica: { hostName: v.name, hostId: v.gatewayId, ended: v.ended || null },
895
+ };
896
+ }
897
+
898
+ /** The host pushed its room: make or update the local copy, mirroring entries not seen yet. */
899
+ _replicaSync(p, fromGw) {
900
+ const roomId = String(p.roomId || '').slice(0, 200);
901
+ if (!roomId) throw Object.assign(new Error('bad sync'), { code: 'bad_request' });
902
+ // One sync at a time per room, so an entry is never injected twice.
903
+ const chainKey = `${fromGw}|${roomId}`;
904
+ const prev = (this._syncChains ??= new Map()).get(chainKey) || Promise.resolve();
905
+ const next = prev.catch(() => {}).then(() => this._replicaSyncNow(p, fromGw, roomId));
906
+ this._syncChains.set(chainKey, next);
907
+ next.finally(() => { if (this._syncChains.get(chainKey) === next) this._syncChains.delete(chainKey); }).catch(() => {});
908
+ return next;
909
+ }
910
+
911
+ async _replicaSyncNow(p, fromGw, roomId) {
912
+ let key = this.store.replicaFor(fromGw, roomId);
913
+ if (p.ended) {
914
+ if (key) { this.store.setReplica(key, { ended: String(p.ended).slice(0, 20) }); this._changed(); }
915
+ return { ok: true };
916
+ }
917
+ const contact = this.remote?.contact?.(fromGw);
918
+ if (!contact) throw Object.assign(new Error('Not connected'), { code: 'not_connected' });
919
+ const clean = (v, n = 100) => String(v || '').replace(/[\u0000-\u001f\u007f[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, n);
920
+ const hostName = clean(p.hostName) || contact.name;
921
+ const title = clean(p.title, 120) || 'team chat';
922
+ let created = false;
923
+ if (!key) {
924
+ const list = (await this.request('agents.list', {}))?.agents || [];
925
+ const agentId = list.find(a => a.default)?.id || list[0]?.id || 'main';
926
+ key = `agent:${agentId}:dashboard:${crypto.randomUUID()}`;
927
+ this.store.createReplica(key, { hostGatewayId: fromGw, hostRoom: roomId, hostName });
928
+ this._workKeysChanged();
929
+ const create = label => this.request('sessions.create', { key, agentId, label: label.slice(0, 200) });
930
+ try { await create(`${title} · ${hostName}`); }
931
+ catch (e) {
932
+ if (!/label already in use/i.test(e.message)) { this.store.deleteRoom(key); throw e; }
933
+ await create(`${title} · ${hostName} · ${key.slice(-4)}`);
934
+ }
935
+ created = true;
936
+ }
937
+ const v = p.view || {};
938
+ const view = {
939
+ 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),
941
+ 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
+ };
943
+ await this._replicaOwnMembers(key, view);
944
+ this.store.setReplica(key, { hostName, view, ended: null });
945
+ const me = this._selfId();
946
+ const entries = (Array.isArray(p.entries) ? p.entries : []).slice(-300).sort((a, b) => (Number(a?.ts) || 0) - (Number(b?.ts) || 0));
947
+ for (const e of entries) {
948
+ const id = String(e?.id || '').slice(0, 200);
949
+ const text = String(e?.text || '').slice(0, 64_000);
950
+ if (!id || !text || this.store.mirrored(key, id)) continue;
951
+ const a = e.author || {};
952
+ const mine = a.type === 'person' && a.personId === me;
953
+ const label = clean(a.name) || (a.type === 'agent' ? 'Agent' : 'Someone');
954
+ const res = await this.request('chat.inject', { sessionKey: key, message: text, label });
955
+ if (!res?.messageId) continue;
956
+ 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 });
960
+ }
961
+ this._changed();
962
+ if (created) this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-invited', roomKey: key, hostName, title }));
963
+ return { ok: true };
964
+ }
965
+
966
+ /**
967
+ * This gateway's own agents in someone else's room: the host lists them by the share it uses
968
+ * (`peer:<share>:<agent>`); here that's a share this gateway owns, and the agent behind its guest
969
+ * version is the one that answers this gateway's person (at full strength, on this gateway).
970
+ */
971
+ async _replicaOwnMembers(key, view) {
972
+ const mine = view.members.filter(m => m.ownerId === this._selfId());
973
+ if (!mine.length) return;
974
+ const list = (await this.request('agents.list', {}))?.agents || [];
975
+ const nameOf = a => a?.identity?.name || a?.name || a?.id;
976
+ 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]);
980
+ const guestOf = shared && /\s\(guest\)$/.test(nameOf(shared)) ? list.find(a => nameOf(a) === nameOf(shared).replace(/\s\(guest\)$/, '')) : null;
981
+ const local = guestOf || shared;
982
+ if (!local) continue;
983
+ m.localAgentId = local.id;
984
+ if (!this.store.getRoom(key)?.members.some(x => x.agentId === local.id)) this.store.addMember(key, local.id);
985
+ }
986
+ }
987
+
988
+ /** This gateway's person writes in someone else's room: the host gets it; this side's own agents answer here. */
989
+ async _replicaSend(room, text) {
990
+ 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`);
992
+ try {
993
+ await this.remote.personRequest(h.gatewayId, 'room.post', { roomId: h.roomId, kind: 'person', text: text.slice(0, 32_000) });
994
+ } catch (e) {
995
+ throw new Error(['unreachable', 'not_connected'].includes(e.code) || /reach|closed|timed out|not ready/i.test(e.message) ? `${h.name}'s gateway is offline: try again when it's back` : e.message);
996
+ }
997
+ this._enqueue(room.roomKey, text);
998
+ return { messageId: null };
999
+ }
1000
+
1001
+ /** In a live copy, this gateway's own agents answer its person's message (the host runs everyone else). */
1002
+ async _replicaRunOwn(room, text, stopped) {
1003
+ const view = room.host;
1004
+ const own = (view.members || []).filter(m => m.localAgentId);
1005
+ if (!own.length) return;
1006
+ // The host echoes the message back into the copy: wait for it so the agents see it.
1007
+ for (let i = 0; i < 40; i++) {
1008
+ const authors = this.store.authors(room.roomKey);
1009
+ const entries = await this._roomEntries(room.roomKey);
1010
+ if (entries.some(e => authors[e.id]?.type === 'user' && splitLabel(e.text).body.trim() === text.trim())) break;
1011
+ await new Promise(r => setTimeout(r, 250));
1012
+ }
1013
+ const all = (view.members || []).map(m => ({ agentId: m.localAgentId || m.agentId, name: m.name }));
1014
+ const mention = parseMentions(text, all);
1015
+ const ownIds = own.map(m => m.localAgentId);
1016
+ let targets, mode;
1017
+ if (mention.all) { targets = ownIds; mode = 'addressed'; }
1018
+ else if (mention.agentIds.length) { targets = mention.agentIds.filter(id => ownIds.includes(id)); mode = 'addressed'; }
1019
+ else { targets = ownIds; mode = 'open'; }
1020
+ if (!targets.length || stopped()) return;
1021
+ const history = await this._roomEntries(room.roomKey);
1022
+ await Promise.all(targets.map(id => this._turn(room.roomKey, id, all, history, mode, stopped)
1023
+ .catch(e => this.log.warn?.(`[team] ${id} in copy ${room.roomKey}: ${e.message}`))));
1024
+ }
1025
+
1026
+ /** One of this gateway's agents replied in a live copy: it goes to the host's room. */
1027
+ async _replicaPostAgent(room, self, text) {
1028
+ const member = (room.host.members || []).find(m => m.localAgentId === self.agentId);
1029
+ if (!member) return;
1030
+ 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
+ }
1032
+
1033
+ /** Leave someone else's room (the copy stays, read-only). */
1034
+ async leave(roomKey) {
1035
+ const room = this.store.getRoom(roomKey);
1036
+ if (!room?.host) throw new Error('not a live copy of someone else\'s chat');
1037
+ 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();
1040
+ return this.room(roomKey);
1041
+ }
1042
+
642
1043
  _live(roomKey) {
643
1044
  let l = this._rooms.get(roomKey);
644
1045
  if (!l) { l = { running: new Map(), queued: 0, gen: 0 }; this._rooms.set(roomKey, l); }