@clawchatsai/connector 0.1.33 → 0.1.35

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) {
@@ -183,6 +193,7 @@ export class TeamCoordinator {
183
193
  return {
184
194
  roomKey: r.roomKey,
185
195
  discuss: r.discuss,
196
+ rounds: r.rounds,
186
197
  sourceKey: r.sourceKey,
187
198
  createdAt: r.createdAt,
188
199
  agents: r.members.map(m => {
@@ -194,6 +205,8 @@ export class TeamCoordinator {
194
205
  }),
195
206
  running: live ? [...live.running.keys()] : [],
196
207
  queued: live?.queued || 0,
208
+ people: r.people.map(p => ({ personId: p.personId, name: p.name })),
209
+ ...(r.host ? this._replicaPublic(r) : {}),
197
210
  };
198
211
  }
199
212
 
@@ -254,7 +267,11 @@ export class TeamCoordinator {
254
267
  * the user's own chat and becomes a normal thread again (deleting the room must never delete it).
255
268
  */
256
269
  _dissolve(roomKey) {
257
- 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(() => {});
258
275
  this.stop(roomKey);
259
276
  const work = this.store.deleteRoom(roomKey).filter(w => w !== source);
260
277
  this._workKeysChanged();
@@ -262,16 +279,28 @@ export class TeamCoordinator {
262
279
  this._changed();
263
280
  }
264
281
 
265
- 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");
266
289
  if (!(await this.agents()).some(a => a.agentId === agentId)) throw new Error(`unknown agent: ${agentId}`);
267
- 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
+ }
268
295
  this._changed();
296
+ this._pushSoon(roomKey);
269
297
  return this.room(roomKey);
270
298
  }
271
299
 
272
300
  removeAgent(roomKey, agentId) {
273
301
  const r = this.store.getRoom(roomKey);
274
302
  if (!r) return null;
303
+ if (r.host) throw new Error("Only the chat's host can remove agents");
275
304
  if (r.members.length <= 2 && r.members.some(m => m.agentId === agentId)) throw new Error('a team chat needs at least two agents');
276
305
  // The working session stays, hidden: it's the agent's memory of this room if it's added back.
277
306
  this.store.removeMember(roomKey, agentId);
@@ -282,11 +311,22 @@ export class TeamCoordinator {
282
311
 
283
312
  setDiscuss(roomKey, discuss) {
284
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");
285
315
  this.store.setDiscuss(roomKey, !!discuss);
286
316
  this._changed();
287
317
  return this.room(roomKey);
288
318
  }
289
319
 
320
+ /** Host setting: follow-up rounds per human message when agents discuss (1..MAX_ROUNDS). */
321
+ setRounds(roomKey, rounds) {
322
+ if (!this.store.getRoom(roomKey)) return null;
323
+ const n = Math.floor(Number(rounds));
324
+ if (!(n >= 1 && n <= this.store.MAX_ROUNDS)) throw new Error(`rounds must be 1..${this.store.MAX_ROUNDS}`);
325
+ this.store.setRounds(roomKey, n);
326
+ this._changed();
327
+ return this.room(roomKey);
328
+ }
329
+
290
330
  // ── Messages ───────────────────────────────────────────────────────
291
331
 
292
332
  /** Post a user message; agents run in the background. Resolves once the message is in the room. */
@@ -294,11 +334,19 @@ export class TeamCoordinator {
294
334
  const room = this.store.getRoom(roomKey);
295
335
  if (!room) throw new Error('not a team chat');
296
336
  if (typeof text !== 'string' || !text.trim()) throw new Error('empty message');
337
+ if (room.host) return this._replicaSend(room, text);
297
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
298
340
  const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label });
299
341
  if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'user' });
300
342
  this._maybeTitle(roomKey, text);
343
+ this._pushSoon(roomKey);
344
+ this._enqueue(roomKey, text);
345
+ return { messageId: res?.messageId || null };
346
+ }
301
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 } = {}) {
302
350
  const live = this._live(roomKey);
303
351
  const gen = live.gen; // Stop bumps the generation: everything queued before it is dropped
304
352
  live.queued++;
@@ -307,13 +355,12 @@ export class TeamCoordinator {
307
355
  const next = prev.then(async () => {
308
356
  live.queued--;
309
357
  if (live.gen !== gen) return;
310
- await this._runMessage(roomKey, text, () => live.gen !== gen);
358
+ await this._runMessage(roomKey, text, () => live.gen !== gen, { fromPerson, replied });
311
359
  }).catch(e => {
312
360
  this.log.error?.(`[team] ${roomKey}: ${e.message}`);
313
361
  this._status(roomKey, e.message);
314
362
  }).finally(() => { if (this._chains.get(roomKey) === next) this._chains.delete(roomKey); this._status(roomKey); });
315
363
  this._chains.set(roomKey, next);
316
- return { messageId: res?.messageId || null };
317
364
  }
318
365
 
319
366
  /** Abort running agents and drop queued messages. */
@@ -321,31 +368,52 @@ export class TeamCoordinator {
321
368
  const live = this._rooms.get(roomKey);
322
369
  if (!live) return;
323
370
  live.gen++;
324
- await Promise.all([...live.running.entries()].map(([agentId, r]) => r.remote
325
- ? this.remote?.abort(agentId, r.runId).catch(e => this.log.warn?.(`[team] remote abort: ${e.message}`))
326
- : this.request('chat.abort', { sessionKey: r.workKey, runId: r.runId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`))));
371
+ await Promise.all([...live.running.entries()].map(([agentId, r]) => (r.actingFor
372
+ ? this.remote?.abortLocalFor(agentId, r.actingFor, r.runId).catch(e => this.log.warn?.(`[team] abort: ${e.message}`))
373
+ : r.remote
374
+ ? this.remote?.abort(agentId, r.runId).catch(e => this.log.warn?.(`[team] remote abort: ${e.message}`))
375
+ : this.request('chat.abort', { sessionKey: r.workKey, runId: r.runId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`)))));
327
376
  this._status(roomKey);
328
377
  }
329
378
 
330
- async _runMessage(roomKey, text, stopped = () => false) {
379
+ async _runMessage(roomKey, text, stopped = () => false, { fromPerson = null, replied: firstReplies = null } = {}) {
331
380
  const room = this.store.getRoom(roomKey);
332
381
  if (!room) return;
382
+ if (room.host) return this._replicaRunOwn(room, text, stopped);
333
383
  const agents = await this._named(room.members.map(m => m.agentId));
334
384
  const mention = parseMentions(text, agents);
335
385
  let targets, mode;
336
386
  if (mention.all) { targets = agents.map(a => a.agentId); mode = 'addressed'; }
337
387
  else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
338
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));
339
392
 
340
- const maxRounds = room.discuss ? this.store.DISCUSS_ROUNDS : 1;
341
- const maxTurns = room.discuss ? agents.length * 2 : agents.length;
393
+ const maxRounds = room.discuss ? room.rounds : 1;
394
+ const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length;
342
395
  let turns = 0;
343
- for (let round = 1; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
396
+ // Authority comes from who asked (specs/sharing-people.md): the first round answers the owner,
397
+ // so this gateway's agents run as themselves. A follow-up answers the previous round's replies:
398
+ // if one came from another person's agent (or from an agent acting for them), this gateway's
399
+ // agents act for that person, as the version shared with them; never as themselves.
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++) {
344
412
  targets = targets.slice(0, maxTurns - turns);
345
413
  turns += targets.length;
346
414
  const history = await this._roomEntries(roomKey);
347
415
  const results = await Promise.all(targets.map(agentId =>
348
- this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped)
416
+ this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped, actingFor.get(agentId) || null)
349
417
  .catch(async e => {
350
418
  // Shown in the room, like a failed turn in a normal chat, not only as a passing toast.
351
419
  this.log.warn?.(`[team] ${agentId} in ${roomKey}: ${e.message}`);
@@ -356,27 +424,44 @@ export class TeamCoordinator {
356
424
  })));
357
425
  const replied = results.filter(r => r?.text);
358
426
  if (!replied.length || stopped()) break;
359
- // Next round: agents that replied or were named, if a sibling said something they haven't seen.
360
- const eligible = new Set(replied.map(r => r.agentId));
361
- for (const r of replied) for (const id of namedIn(r.text, agents)) if (id !== r.agentId) eligible.add(id);
362
- targets = agents.map(a => a.agentId).filter(id => eligible.has(id) && replied.some(r => r.agentId !== id));
427
+ ({ targets, actingFor } = this._nextRound(agents, replied));
363
428
  }
364
429
  }
365
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
+
366
445
  /** One agent turn. Returns { agentId, text } (text null when silent/aborted). */
367
- async _turn(roomKey, agentId, agents, history, mode, stopped = () => false) {
446
+ async _turn(roomKey, agentId, agents, history, mode, stopped = () => false, actingFor = null) {
368
447
  const room = this.store.getRoom(roomKey);
369
448
  const member = room?.members.find(m => m.agentId === agentId);
370
449
  if (!member) return null;
371
450
  const self = agents.find(a => a.agentId === agentId) || { agentId, name: agentId };
372
451
  const authors = this.store.authors(roomKey);
373
- 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))
374
455
  .map(e => (TeamCoordinator.isRemote(authors[e.id]?.agentId) ? { ...e, remote: true } : e));
375
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) : '';
376
460
 
377
- if (TeamCoordinator.isRemote(agentId)) return this._remoteTurn(roomKey, self, fresh, agents, mode, stopped);
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);
378
463
  const workKey = member.workKey || await this._createWorkSession(roomKey, self);
379
- const message = this._prompt(self, agents, fresh, mode);
464
+ const message = this._prompt(self, agents, fresh, mode, earlier);
380
465
  const runId = `team-${crypto.randomUUID()}`;
381
466
  const live = this._live(roomKey);
382
467
  const done = this._waitRun(runId);
@@ -419,7 +504,7 @@ export class TeamCoordinator {
419
504
  * A turn of someone else's agent: runs on their gateway over the peer link (peer/sharing.js).
420
505
  * Streamed text reaches the browser as `team-remote-delta` (there's no local working session).
421
506
  */
422
- async _remoteTurn(roomKey, self, fresh, agents, mode, stopped) {
507
+ async _remoteTurn(roomKey, self, fresh, agents, mode, stopped, earlier = '') {
423
508
  if (!this.remote) throw new Error('sharing is not available');
424
509
  const agentId = self.agentId;
425
510
  const runId = `team-${crypto.randomUUID()}`;
@@ -430,7 +515,7 @@ export class TeamCoordinator {
430
515
  let result, partial = '';
431
516
  try {
432
517
  this.store.setSeenAt(roomKey, agentId, Math.max(...fresh.map(e => e.ts)));
433
- 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) },
434
519
  { onDelta: text => { partial = text; delta(text); } });
435
520
  } catch (e) {
436
521
  throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
@@ -447,7 +532,51 @@ export class TeamCoordinator {
447
532
  }
448
533
  if (!text || SILENT.test(text)) return { agentId, text: null };
449
534
  await this._post(roomKey, self, text);
450
- return { agentId, text: stopped() ? null : text };
535
+ return { agentId, text: stopped() ? null : text, authority: agentId }; // what it says carries its owner's authority
536
+ }
537
+
538
+ /**
539
+ * One of this gateway's agents answering another person's agent: runs as the version shared with
540
+ * that person, under their grant (peer/sharing.js localTurnFor), streamed like a remote agent.
541
+ * Not shared with them: it stays out, saying so when their agent asked it by name.
542
+ */
543
+ async _turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history, earlier = '') {
544
+ const agentId = self.agentId;
545
+ const asker = agents.find(a => a.agentId === actingFor);
546
+ const forName = this.remote?.actingForName?.(actingFor) || asker?.ownerName || 'someone else';
547
+ const runId = `team-${crypto.randomUUID()}`;
548
+ const live = this._live(roomKey);
549
+ const delta = (text, done = false) => this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-delta', roomKey, agentId, runId, text, ...(done ? { done: true } : {}) }));
550
+ live.running.set(agentId, { actingFor, runId });
551
+ this._status(roomKey);
552
+ let result, partial = '';
553
+ try {
554
+ this.store.setSeenAt(roomKey, agentId, Math.max(...fresh.map(e => e.ts)));
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) },
556
+ { onDelta: text => { partial = text; delta(text); } });
557
+ } catch (e) {
558
+ throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
559
+ } finally {
560
+ live.running.delete(agentId);
561
+ delta('', true);
562
+ this._status(roomKey);
563
+ }
564
+ if (!result) {
565
+ const authors = this.store.authors(roomKey);
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))
568
+ && parseMentions(splitLabel(e.text).body, agents).agentIds?.includes(agentId));
569
+ if (askedByName) await this._post(roomKey, self, `*${self.name} isn't shared with ${forName}, so it doesn't answer ${forName}'s agents.*`);
570
+ return { agentId, text: null };
571
+ }
572
+ const text = String(result.text || '').trim();
573
+ if (result.state === 'aborted') {
574
+ if (text && !SILENT.test(text)) await this._post(roomKey, self, `${text}\n\n*[stopped]*`, { actingFor: forName });
575
+ return { agentId, text: null };
576
+ }
577
+ if (!text || SILENT.test(text)) return { agentId, text: null };
578
+ await this._post(roomKey, self, text, { actingFor: forName });
579
+ return { agentId, text: stopped() ? null : text, authority: actingFor };
451
580
  }
452
581
 
453
582
  async _roomTitle(roomKey) {
@@ -476,13 +605,16 @@ export class TeamCoordinator {
476
605
  setTimeout(check, intervalMs).unref?.();
477
606
  }
478
607
 
479
- /** Post an agent's message into the room. */
480
- async _post(roomKey, self, text) {
608
+ /** Post an agent's message into the room (actingFor: whose request it answered, if not its owner's). */
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
481
612
  const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label: self.name.slice(0, 100) });
482
- if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId });
613
+ if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId, actingFor });
614
+ this._pushSoon(roomKey);
483
615
  }
484
616
 
485
- _prompt(self, agents, fresh, mode) {
617
+ _prompt(self, agents, fresh, mode, earlier = '') {
486
618
  const others = agents.filter(a => a.agentId !== self.agentId).map(a => a.name);
487
619
  const lines = fresh.map(e => {
488
620
  const { label, body } = splitLabel(e.text);
@@ -498,6 +630,7 @@ export class TeamCoordinator {
498
630
  return [
499
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.`,
500
632
  '',
633
+ ...(earlier ? ['Earlier in this chat (before you joined):', '', earlier, ''] : []),
501
634
  'New messages since your last turn:',
502
635
  '',
503
636
  lines.join('\n\n'),
@@ -571,6 +704,342 @@ export class TeamCoordinator {
571
704
  if (w) { clearTimeout(w.timer); this._waiters.delete(runId); }
572
705
  }
573
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
+
574
1043
  _live(roomKey) {
575
1044
  let l = this._rooms.get(roomKey);
576
1045
  if (!l) { l = { running: new Map(), queued: 0, gen: 0 }; this._rooms.set(roomKey, l); }