@clawchatsai/connector 0.2.6 → 0.3.0

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
@@ -39,6 +39,8 @@ const AGENTS_TTL_MS = 60_000;
39
39
  const ALL_WORDS = new Set(['all', 'everyone']);
40
40
  /** Rounds of @mention replies when agents don't "discuss": an agent a reply names answers once, and so on. */
41
41
  const MENTION_ROUNDS = 3;
42
+ // Rounds per human message each autonomy tier allows (peer/contact-policy.js AUTONOMY; Notify only: none).
43
+ const ROUND_LIMITS = { bounded: 3, extended: 10 };
42
44
 
43
45
  const norm = s => String(s || '').toLowerCase().replace(/\s+/g, '');
44
46
  /** Room entries up to and including `id` (all of them when it's not given or not among them). */
@@ -292,6 +294,37 @@ export class TeamCoordinator {
292
294
  return this.store.listRooms().map(r => this._publicRoom(r));
293
295
  }
294
296
 
297
+ /** Agents answer only when @mentioned: the host's choice, or automatic (on while another person is in the chat, D12). */
298
+ _mentionOnly(room) { return room.mentionOnly === null || room.mentionOnly === undefined ? !!room.people?.length : room.mentionOnly; }
299
+
300
+ /**
301
+ * What the contact cards allow in this room, both directions, per person in it (people, and the owners of other
302
+ * people's agents): { people: [{ personId, name, mine, theirs }], roundsCap: { n, by, personId, name } | null,
303
+ * quiet(agentId, actingFor) }. Rounds are capped by the strictest tier that lets agents talk at all; Notify only makes
304
+ * that side's agents sit out agent rounds instead (`quiet`).
305
+ */
306
+ _limits(room) {
307
+ const ids = new Set((room.people || []).map(p => p.personId));
308
+ for (const m of room.members || []) if (TeamCoordinator.isRemote(m.agentId)) { const gw = this.remote?.ownerOf?.(m.agentId); if (gw) ids.add(gw); }
309
+ const people = [...ids].map(id => ({ personId: id, name: (room.people || []).find(p => p.personId === id)?.name || this.remote?.contact?.(id)?.name || null, ...(this.remote?.limitsFor?.(id) || {}) }));
310
+ let roundsCap = null;
311
+ for (const p of people) {
312
+ for (const by of ['mine', 'theirs']) {
313
+ const n = ROUND_LIMITS[p[by]?.autonomy];
314
+ if (!n) continue; // unknown, or Notify only (handled by `quiet`)
315
+ if (!roundsCap || n < roundsCap.n) roundsCap = { n, by, personId: p.personId, name: p.name };
316
+ }
317
+ }
318
+ const tierOf = gw => people.find(p => p.personId === gw);
319
+ const quiet = (agentId, actingFor) => {
320
+ if (TeamCoordinator.isRemote(agentId)) return tierOf(this.remote?.ownerOf?.(agentId))?.theirs?.autonomy === 'notify';
321
+ if (!actingFor) return false;
322
+ const gw = String(actingFor).startsWith('person:') ? actingFor.slice('person:'.length) : this.remote?.ownerOf?.(actingFor);
323
+ return tierOf(gw)?.mine?.autonomy === 'notify';
324
+ };
325
+ return { people, roundsCap, quiet };
326
+ }
327
+
295
328
  room(roomKey) {
296
329
  const r = this.store.getRoom(roomKey);
297
330
  return r ? { ...this._publicRoom(r), authors: this.store.authors(roomKey) } : null;
@@ -302,8 +335,10 @@ export class TeamCoordinator {
302
335
  return {
303
336
  roomKey: r.roomKey,
304
337
  discuss: r.discuss,
305
- mentionOnly: r.mentionOnly,
338
+ mentionOnly: r.mentionOnly, // null: automatic (D12)
339
+ mentionAuto: this._mentionOnly(r),
306
340
  rounds: r.rounds,
341
+ ...(r.host ? {} : { limits: this._limits(r) }),
307
342
  sourceKey: r.sourceKey,
308
343
  createdAt: r.createdAt,
309
344
  agents: r.members.map(m => {
@@ -311,7 +346,7 @@ export class TeamCoordinator {
311
346
  const a = this._remoteAgents().find(x => x.agentId === m.agentId);
312
347
  // A share that ended keeps its member, shown as unavailable.
313
348
  const known = a || this._remoteName(m.agentId);
314
- return { agentId: m.agentId, workKey: null, remote: true, name: known?.name || null, ownerName: known?.ownerName || null, available: !!a };
349
+ return { agentId: m.agentId, workKey: null, remote: true, name: known?.name || null, ownerName: known?.ownerName || null, ownerId: this.remote?.ownerOf?.(m.agentId) || null, available: !!a };
315
350
  }),
316
351
  running: live ? [...live.running.keys()] : [],
317
352
  // Remote agents whose run waits for their owner to approve something: { agentId: { owner, what, expiresAtMs } }.
@@ -328,7 +363,7 @@ export class TeamCoordinator {
328
363
  * Create a team chat. With `sourceKey`, an existing chat becomes the first agent's working
329
364
  * session (it keeps its memory) and is hidden from the thread list.
330
365
  */
331
- async createRoom({ agentIds = [], personIds = [], sourceKey = null, category, label, mentionOnly = false } = {}) {
366
+ async createRoom({ agentIds = [], personIds = [], sourceKey = null, category, label, mentionOnly = null } = {}) {
332
367
  const agents = [...new Set(agentIds.filter(a => typeof a === 'string' && a))];
333
368
  const people = [...new Set(personIds.filter(a => typeof a === 'string' && a))];
334
369
  const members = [];
@@ -353,7 +388,7 @@ export class TeamCoordinator {
353
388
 
354
389
  const roomKey = `agent:${members[0].agentId}:dashboard:${crypto.randomUUID()}`;
355
390
  // Register first so the lens never shows a working session or forwards a half-made room.
356
- this.store.createRoom(roomKey, members, { sourceKey, mentionOnly: !!mentionOnly });
391
+ this.store.createRoom(roomKey, members, { sourceKey, mentionOnly: mentionOnly === null || mentionOnly === undefined ? null : !!mentionOnly });
357
392
  this._workKeysChanged();
358
393
  // Labels are unique per gateway and the source chat still holds this one: it steps aside (as the
359
394
  // hidden working session) so the team chat can take it; it gets it back when the room goes.
@@ -480,12 +515,12 @@ export class TeamCoordinator {
480
515
  return this.room(roomKey);
481
516
  }
482
517
 
483
- /** Host setting: agents answer only when @mentioned (chats between people, with the agents quiet). */
518
+ /** Host setting: agents answer only when @mentioned (chats between people, with the agents quiet). null: automatic. */
484
519
  setMentionOnly(roomKey, on) {
485
520
  const r = this.store.getRoom(roomKey);
486
521
  if (!r) return null;
487
522
  if (r.host) throw new Error("Only the chat's host can change this");
488
- this.store.setMentionOnly(roomKey, !!on);
523
+ this.store.setMentionOnly(roomKey, on === null ? null : !!on);
489
524
  this._changed();
490
525
  this._pushSoon(roomKey);
491
526
  return this.room(roomKey);
@@ -570,13 +605,15 @@ export class TeamCoordinator {
570
605
  let targets, mode;
571
606
  if (mention.all) { targets = agents.map(a => a.agentId); mode = 'addressed'; }
572
607
  else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
573
- else { targets = room.mentionOnly ? [] : agents.map(a => a.agentId); mode = 'open'; }
608
+ else { targets = this._mentionOnly(room) ? [] : agents.map(a => a.agentId); mode = 'open'; }
574
609
  // A person's own agents answer them on their own gateway (their connector runs them at full
575
610
  // strength); this gateway never runs them for that person's messages.
576
611
  if (fromPerson) targets = targets.filter(id => !(TeamCoordinator.isRemote(id) && this.remote?.ownerOf?.(id) === fromPerson));
577
612
 
578
- // Without "discuss" an agent still answers once when a reply @mentions it (a few rounds at most).
579
- const maxRounds = room.discuss ? room.rounds : MENTION_ROUNDS;
613
+ // Without "discuss" an agent still answers once when a reply @mentions it (a few rounds at most). Either way no
614
+ // more rounds than the strictest autonomy tier between this gateway and the people in the chat (both directions).
615
+ const limits = this._limits(room);
616
+ const maxRounds = Math.min(room.discuss ? room.rounds : MENTION_ROUNDS, limits.roundsCap?.n ?? Infinity);
580
617
  const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length * 2;
581
618
  let turns = 0;
582
619
  // Authority comes from who asked (specs/sharing-people.md): the first round answers the owner,
@@ -594,7 +631,11 @@ export class TeamCoordinator {
594
631
  mode = room.discuss ? 'followup' : 'addressed';
595
632
  }
596
633
  for (; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
634
+ // Notify only: in agent rounds, agents never answer another agent across that tier (the person can still ask).
635
+ if (round > 1) targets = targets.filter(id => !limits.quiet(id, actingFor.get(id)));
636
+ if (!targets.length) break;
597
637
  targets = targets.slice(0, maxTurns - turns);
638
+ this._live(roomKey).round = round; // for the peer turn: what triggered it (owner-side autonomy check)
598
639
  turns += targets.length;
599
640
  // The first round answers the message itself: what others said after it (still queued, or posted meanwhile)
600
641
  // is for a later turn, so it can never pass for the request this round runs on.
@@ -761,7 +802,8 @@ export class TeamCoordinator {
761
802
  let result, partial = '';
762
803
  try {
763
804
  this._setSeen(roomKey, agentId, REMOTE_LANE, fresh);
764
- result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
805
+ const round = live.round || 1;
806
+ result = await this.remote.turn(agentId, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier), trigger: round > 1 ? 'agent' : 'person', round },
765
807
  {
766
808
  stopped, // a turn whose link dropped is sent again, unless the room was stopped meanwhile
767
809
  onDelta: text => { partial = text; delta(text); },
@@ -803,7 +845,7 @@ export class TeamCoordinator {
803
845
  let result, partial = '';
804
846
  try {
805
847
  this._setSeen(roomKey, agentId, lane, fresh);
806
- result = await this.remote?.localTurnFor(agentId, actingFor, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier) },
848
+ result = await this.remote?.localTurnFor(agentId, actingFor, { turnId: runId, roomId: roomKey, roomTitle: await this._roomTitle(roomKey), message: this._prompt(self, agents, fresh, mode, earlier), round: live.round || 1 },
807
849
  { onDelta: text => { partial = text; delta(text); } });
808
850
  } catch (e) {
809
851
  throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
@@ -1008,7 +1050,7 @@ export class TeamCoordinator {
1008
1050
  const c = this.remote?.contact?.(personId);
1009
1051
  if (!c) throw new Error('Connect with them first (Settings → People)');
1010
1052
  const already = room.people.some(p => p.personId === personId);
1011
- if (quietAgents && !already && !room.people.length && !room.mentionOnly) this.store.setMentionOnly(roomKey, true);
1053
+ if (quietAgents && !already && !room.people.length && room.mentionOnly === false) this.store.setMentionOnly(roomKey, true);
1012
1054
  this.store.addPerson(roomKey, { personId, name: c.name, email: c.email, historyFrom: history === 'now' ? Date.now() : 0 });
1013
1055
  if (!already) await this._note(roomKey, `${c.name} joined`);
1014
1056
  this._changed();
@@ -1104,7 +1146,7 @@ export class TeamCoordinator {
1104
1146
  roomId: room.roomKey, title, hostName: this._hostName(), full: !!full, entries,
1105
1147
  view: {
1106
1148
  discuss: room.discuss,
1107
- mentionOnly: room.mentionOnly,
1149
+ mentionOnly: this._mentionOnly(room),
1108
1150
  members: agents.map(a => {
1109
1151
  const remote = TeamCoordinator.isRemote(a.agentId);
1110
1152
  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 };
@@ -398,7 +398,7 @@ test('shared (remote) agents: in the roster, turns over the peer link, streamed,
398
398
  const h = harness(agent => `${agent} local`, { remote });
399
399
  const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
400
400
  const room = h.team.room(roomKey);
401
- assert.deepEqual(room.agents[1], { agentId: 'peer:sh1:jarvis', workKey: null, remote: true, name: 'Jarvis · Kamil', ownerName: 'Kamil', available: true });
401
+ assert.deepEqual(room.agents[1], { agentId: 'peer:sh1:jarvis', workKey: null, remote: true, name: 'Jarvis · Kamil', ownerName: 'Kamil', ownerId: null, available: true });
402
402
 
403
403
  await h.team.send(roomKey, { text: '@all hi', userLabel: 'H' });
404
404
  await h.settle();
@@ -606,7 +606,7 @@ test('rounds: a per-room host setting, validated', async () => {
606
606
  function twoGateways({ devShared = true, hostReply = null } = {}) {
607
607
  const forCalls = [];
608
608
  const sides = {};
609
- const net = { connected: true, jarvisShared: true };
609
+ const net = { connected: true, jarvisShared: true, limits: {} };
610
610
  const mk = (self, other, name) => ({
611
611
  gatewayId: () => self,
612
612
  selfName: () => name,
@@ -633,6 +633,7 @@ function twoGateways({ devShared = true, hostReply = null } = {}) {
633
633
  },
634
634
  abort: async () => {},
635
635
  actingForName: () => 'Kamil',
636
+ limitsFor: gw => (gw === other ? net.limits[self] || {} : {}),
636
637
  localTurnFor: async (localId, who, args) => {
637
638
  forCalls.push({ localId, who, args });
638
639
  return devShared ? { state: 'final', text: `${localId} for kamil` } : null;
@@ -791,21 +792,24 @@ test('a chat with only people: the agent stays quiet unless @mentioned', async (
791
792
  assert.equal(H.team.room(room.roomKey).mentionOnly, false);
792
793
  });
793
794
 
794
- test('adding the first person from the popover turns "agents reply only when @mentioned" on; later adds and create-time adds leave it', async () => {
795
+ test('"agents reply only when @mentioned" is automatic (D12): on with another person in the chat, off with only agents; a host choice sticks', async () => {
795
796
  const { H, K, settle } = twoGateways();
796
797
  const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
797
- assert.equal(H.team.room(roomKey).mentionOnly, false);
798
- await H.team.addPerson(roomKey, 'gwK', { history: 'all', quietAgents: true });
798
+ assert.deepEqual([H.team.room(roomKey).mentionOnly, H.team.room(roomKey).mentionAuto], [null, false], 'automatic, off: only agents');
799
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
799
800
  await settle();
800
- assert.equal(H.team.room(roomKey).mentionOnly, true, 'first other person: agents go quiet');
801
+ assert.deepEqual([H.team.room(roomKey).mentionOnly, H.team.room(roomKey).mentionAuto], [null, true], 'another person: agents go quiet');
801
802
  assert.equal(K.team.rooms().find(r => r.replica).mentionOnly, true, 'and the copy knows');
802
803
  H.team.setMentionOnly(roomKey, false);
803
804
  await H.team.addPerson(roomKey, 'gwK', { history: 'all', quietAgents: true });
804
- assert.equal(H.team.room(roomKey).mentionOnly, false, 'the host\'s later choice is kept');
805
-
806
- const plain = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
807
- await H.team.addPerson(plain.roomKey, 'gwK', { history: 'all' });
808
- assert.equal(H.team.room(plain.roomKey).mentionOnly, false, 'create-time adds decide for themselves');
805
+ assert.deepEqual([H.team.room(roomKey).mentionOnly, H.team.room(roomKey).mentionAuto], [false, false], "the host's choice is kept");
806
+ H.team.setMentionOnly(roomKey, null);
807
+ assert.deepEqual([H.team.room(roomKey).mentionOnly, H.team.room(roomKey).mentionAuto], [null, true], 'back to automatic');
808
+
809
+ // A room made before automatic (an explicit "off"): the first person still turns it on, as before.
810
+ const old = await H.team.createRoom({ agentIds: ['dev', 'atlas'], mentionOnly: false });
811
+ await H.team.addPerson(old.roomKey, 'gwK', { history: 'all', quietAgents: true });
812
+ assert.equal(H.team.room(old.roomKey).mentionOnly, true);
809
813
  });
810
814
 
811
815
  test("someone's agent answering on its owner's copy and through the host: each session gets what it said in the other", async () => {
@@ -1104,7 +1108,7 @@ test('a host renaming the chat reaches the copies without anyone sending a messa
1104
1108
 
1105
1109
  test("a host can't put your unshared agents in its room, nor write lines as you or your agents", async () => {
1106
1110
  const { H, K, settle } = twoGateways();
1107
- const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
1111
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'], mentionOnly: false });
1108
1112
  await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
1109
1113
  await settle();
1110
1114
  const copy = K.team.rooms().find(r => r.replica);
@@ -1247,3 +1251,33 @@ test("a shared agent's turn gets the room's stopped(), so a dropped link isn't r
1247
1251
  assert.equal(typeof opts?.stopped, 'function');
1248
1252
  assert.equal(opts.stopped(), false);
1249
1253
  });
1254
+
1255
+ test('rounds are capped by the strictest autonomy tier either way, and Notify only keeps that side\'s agents out of agent rounds', async () => {
1256
+ const { H, settle, net } = twoGateways();
1257
+ const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'], mentionOnly: false });
1258
+ await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
1259
+ H.team.setMentionOnly(roomKey, false);
1260
+ H.team.setDiscuss(roomKey, true);
1261
+ H.team.setRounds(roomKey, 10);
1262
+ // Houman's card for Kamil: Bounded (3); Kamil's for Houman: Extended (10).
1263
+ net.limits.gwH = { mine: { access: 'trusted', autonomy: 'bounded' }, theirs: { access: 'trusted', autonomy: 'extended' } };
1264
+ const room = H.team.room(roomKey);
1265
+ assert.deepEqual(room.limits.roundsCap, { n: 3, by: 'mine', personId: 'gwK', name: 'Kamil' });
1266
+ assert.deepEqual(room.limits.people[0].theirs, { access: 'trusted', autonomy: 'extended' });
1267
+
1268
+ const turns = [];
1269
+ const turn = H.team.remote.turn;
1270
+ H.team.remote.turn = async (agentId, args) => { turns.push(args); return turn(agentId, args); };
1271
+ await H.team.send(roomKey, { text: 'what do you both think?' });
1272
+ await settle();
1273
+ assert.ok(turns.length >= 2, 'their agent joins the discussion');
1274
+ assert.equal(Math.max(...turns.map(t => t.round)), 3, 'no fourth round');
1275
+ assert.deepEqual([turns[0].trigger, turns.at(-1).trigger], ['person', 'agent']);
1276
+
1277
+ // Kamil set Notify only for Houman: his agent answers Houman's message, then sits out the agent rounds.
1278
+ net.limits.gwH = { mine: { access: 'trusted', autonomy: 'extended' }, theirs: { access: 'trusted', autonomy: 'notify' } };
1279
+ turns.length = 0;
1280
+ await H.team.send(roomKey, { text: 'and now?' });
1281
+ await settle();
1282
+ assert.deepEqual(turns.map(t => t.round), [1]);
1283
+ });