@clawchatsai/connector 0.1.34 → 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/package.json +1 -1
- package/server/index.js +22 -4
- package/server/peer/sharing.js +105 -9
- package/server/store/team-store.js +82 -10
- package/server/team.js +429 -28
- package/server/team.test.js +139 -2
package/package.json
CHANGED
package/server/index.js
CHANGED
|
@@ -247,7 +247,7 @@ export function createApp(config = {}) {
|
|
|
247
247
|
if (method === 'GET' && urlPath === '/api/sharing') {
|
|
248
248
|
// Enabled once the signal server has sharing on for this account (it then sends share lists).
|
|
249
249
|
if (!sharing?.serverEnabled) return send(res, 200, { enabled: false, shares: [], remoteAgents: [] });
|
|
250
|
-
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents() });
|
|
250
|
+
return send(res, 200, { enabled: true, fingerprint: peerKey.fingerprint, shares: sharing.list(), remoteAgents: sharing.remoteAgents(), contacts: sharing.contacts(), me: sharing.gatewayId?.() || null });
|
|
251
251
|
}
|
|
252
252
|
if ((p = matchRoute(method, urlPath, 'POST /api/sharing/:id/approve'))) {
|
|
253
253
|
if (!sharing) return sendError(res, 404, 'Sharing is not available');
|
|
@@ -286,17 +286,35 @@ export function createApp(config = {}) {
|
|
|
286
286
|
if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
|
|
287
287
|
const body = await parseBody(req);
|
|
288
288
|
let room = team.room(p.room);
|
|
289
|
-
if (room && body.discuss !== undefined)
|
|
289
|
+
if (room && body.discuss !== undefined) {
|
|
290
|
+
try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
|
|
291
|
+
}
|
|
290
292
|
if (room && body.rounds !== undefined) {
|
|
291
293
|
try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
|
|
292
294
|
}
|
|
293
295
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
294
296
|
}
|
|
297
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/people'))) {
|
|
298
|
+
const { personId, history } = await parseBody(req);
|
|
299
|
+
if (typeof personId !== 'string' || !personId) return sendError(res, 400, 'personId is required');
|
|
300
|
+
try {
|
|
301
|
+
const room = await team.addPerson(p.room, personId, { history });
|
|
302
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
303
|
+
} catch (e) { return sendError(res, 400, e.message); }
|
|
304
|
+
}
|
|
305
|
+
if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/people/:personId'))) {
|
|
306
|
+
const room = team.removePerson(p.room, p.personId);
|
|
307
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat you host');
|
|
308
|
+
}
|
|
309
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/leave'))) {
|
|
310
|
+
try { return send(res, 200, { room: await team.leave(p.room) }); }
|
|
311
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
312
|
+
}
|
|
295
313
|
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
|
|
296
|
-
const { agentId } = await parseBody(req);
|
|
314
|
+
const { agentId, history } = await parseBody(req);
|
|
297
315
|
if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
|
|
298
316
|
try {
|
|
299
|
-
const room = await team.addAgent(p.room, agentId);
|
|
317
|
+
const room = await team.addAgent(p.room, agentId, { history });
|
|
300
318
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
301
319
|
} catch (e) { return sendError(res, 400, e.message); }
|
|
302
320
|
}
|
package/server/peer/sharing.js
CHANGED
|
@@ -34,7 +34,7 @@ export const defangLocalPaths = text => text
|
|
|
34
34
|
.replace(/(^|[\s"'`(])(?=(?:\.\.?\/|[~/]|[A-Za-z]:[\\/])[^\s"'`()[\]]*\.[A-Za-z0-9])/g, '$1\u200b');
|
|
35
35
|
const GUEST_NOTE = name => `(Shared session: you are answering ${name}'s team chat on behalf of your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
36
36
|
// The same agent in its owner's own team chat, answering another person's agent (localTurnFor).
|
|
37
|
-
const ACTING_FOR_NOTE = name => `(Shared session: in your owner's team chat, you are answering ${name}'s agent, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
37
|
+
const ACTING_FOR_NOTE = (name, byPerson) => `(Shared session: in your owner's team chat, you are answering ${byPerson ? name : `${name}'s agent`}, so you act for ${name}, not for your owner. ${name} is not your owner — don't reveal your owner's private information or act on your owner's accounts for them.)`;
|
|
38
38
|
|
|
39
39
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
40
40
|
/** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
|
|
@@ -94,12 +94,14 @@ export class SharingManager {
|
|
|
94
94
|
|
|
95
95
|
/** `share-list` from the signal server. Ends links/grants for shares that are gone. */
|
|
96
96
|
setShares(shares) {
|
|
97
|
+
const first = !this.serverEnabled;
|
|
97
98
|
this.serverEnabled = true;
|
|
98
99
|
this._shares = Array.isArray(shares) ? shares : [];
|
|
99
100
|
const live = new Set(this._shares.filter(s => s.status === 'active').map(s => s.id));
|
|
100
101
|
for (const [shareId, link] of this._links) if (!live.has(shareId)) { link.close(); this._links.delete(shareId); }
|
|
101
102
|
for (const s of this._localGrants()) if (!live.has(s.share_id) && !this._shares.some(x => x.id === s.share_id && x.status === 'pending')) this._revokeLocal(s.share_id);
|
|
102
103
|
this._changed();
|
|
104
|
+
if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
|
|
103
105
|
}
|
|
104
106
|
|
|
105
107
|
/** The signal server says a share ended (revoke/decline): stop at once. */
|
|
@@ -260,11 +262,97 @@ export class SharingManager {
|
|
|
260
262
|
this._served.add(link);
|
|
261
263
|
link.on('closed', () => this._served.delete(link));
|
|
262
264
|
link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
|
|
263
|
-
link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false }, emit)); // only localTurnFor sets
|
|
265
|
+
link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit)); // only localTurnFor sets these
|
|
264
266
|
link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
|
|
267
|
+
this._wireRooms(link, requesterGatewayId);
|
|
265
268
|
return link;
|
|
266
269
|
}
|
|
267
270
|
|
|
271
|
+
/**
|
|
272
|
+
* Team chats with people (specs/sharing-people.md) travel over whichever link the two gateways
|
|
273
|
+
* have, in either direction: the room host pushes its room to members (room.sync), members post,
|
|
274
|
+
* leave and ask for a fresh copy (room.post / room.leave / room.fetch). `onRoom` (TeamCoordinator)
|
|
275
|
+
* decides; it gets the other side's gateway id, which the link authenticated.
|
|
276
|
+
*/
|
|
277
|
+
_wireRooms(link, otherGatewayId) {
|
|
278
|
+
for (const method of ['room.sync', 'room.post', 'room.leave', 'room.fetch']) {
|
|
279
|
+
link.handle(method, async p => {
|
|
280
|
+
if (!this.onRoom) throw Object.assign(new Error('team chats are not available'), { code: 'unavailable' });
|
|
281
|
+
return this.onRoom(method, p || {}, otherGatewayId);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
const ready = () => { try { this.onPeerReady?.(otherGatewayId); } catch (e) { this.log.warn?.(`[sharing] peer ready: ${e.message}`); } };
|
|
285
|
+
if (link.ready) setImmediate(ready); else link.once('ready', ready);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── People (contacts) ──────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/** The other person of a share, as this side sees them: { gatewayId, name, email }. */
|
|
291
|
+
_other(s) {
|
|
292
|
+
const p = s.as === 'owner' ? s.requester : s.owner;
|
|
293
|
+
return { gatewayId: p?.gatewayId || null, name: cleanName(p?.name || p?.email, 60) || 'Someone', email: p?.email || null };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* People this gateway is connected with (an active share either way), by their gateway id:
|
|
298
|
+
* [{ personId, name, email, shareIds }]. A team chat here can include any of them.
|
|
299
|
+
*/
|
|
300
|
+
contacts() {
|
|
301
|
+
const out = new Map();
|
|
302
|
+
for (const s of this._shares) {
|
|
303
|
+
if (s.status !== 'active') continue;
|
|
304
|
+
if (s.as === 'requester' && !this._verifiedGrant(s)) continue;
|
|
305
|
+
if (s.as === 'owner' && !this._grant(s.id)) continue;
|
|
306
|
+
const o = this._other(s);
|
|
307
|
+
if (!o.gatewayId) continue;
|
|
308
|
+
const c = out.get(o.gatewayId) || { personId: o.gatewayId, name: o.name, email: o.email, shareIds: [] };
|
|
309
|
+
c.shareIds.push(s.id);
|
|
310
|
+
out.set(o.gatewayId, c);
|
|
311
|
+
}
|
|
312
|
+
return [...out.values()];
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
contact(personId) { return this.contacts().find(c => c.personId === personId) || null; }
|
|
316
|
+
|
|
317
|
+
/** The gateway id of whoever owns a shared agent ('peer:<share>:<agent>'), or null. */
|
|
318
|
+
ownerOf(remoteAgentId) {
|
|
319
|
+
const id = SharingManager.parseRemoteId(remoteAgentId);
|
|
320
|
+
return (id && this._shares.find(s => s.id === id.shareId && s.as === 'requester')?.owner?.gatewayId) || null;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Whether this gateway owns (granted) that share. */
|
|
324
|
+
ownsShare(shareId) { return !!this._grant(shareId); }
|
|
325
|
+
|
|
326
|
+
/** This gateway's person, as the others see them (from any share). */
|
|
327
|
+
selfName() {
|
|
328
|
+
for (const s of this._shares) {
|
|
329
|
+
const me = s.as === 'owner' ? s.owner : s.requester;
|
|
330
|
+
if (me?.name || me?.email) return cleanName(me.name || me.email, 60);
|
|
331
|
+
}
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** An open link with that person's gateway (either direction), else dial one this side may open. */
|
|
336
|
+
async _personLink(personId) {
|
|
337
|
+
for (const [shareId, link] of this._links) {
|
|
338
|
+
const s = this._shares.find(x => x.id === shareId);
|
|
339
|
+
if (link.ready && !link.closed && s && this._other(s).gatewayId === personId) return link;
|
|
340
|
+
}
|
|
341
|
+
for (const link of this._served) {
|
|
342
|
+
if (link.ready && !link.closed && this._grant(link.shareId)?.grant.requesterGatewayId === personId) return link;
|
|
343
|
+
}
|
|
344
|
+
const dial = this._shares.find(s => s.as === 'requester' && s.status === 'active' && s.owner?.gatewayId === personId && this._verifiedGrant(s));
|
|
345
|
+
if (!dial) throw Object.assign(new Error(`Can't reach them until they're online`), { code: 'unreachable' });
|
|
346
|
+
return this._link(dial.id);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Call a room method on a person's gateway. */
|
|
350
|
+
async personRequest(personId, method, params, { timeoutMs = 60_000 } = {}) {
|
|
351
|
+
if (!this.contact(personId)) throw Object.assign(new Error('Not connected with them'), { code: 'not_connected' });
|
|
352
|
+
const link = await this._personLink(personId);
|
|
353
|
+
return link.request(method, params, { timeoutMs });
|
|
354
|
+
}
|
|
355
|
+
|
|
268
356
|
/** Run one guest turn in this gateway's session for (share, room, agent); stream text back. */
|
|
269
357
|
async _guestTurn(shareId, p, emit) {
|
|
270
358
|
const g = this._grant(shareId);
|
|
@@ -322,7 +410,7 @@ export class SharingManager {
|
|
|
322
410
|
try {
|
|
323
411
|
if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
|
|
324
412
|
await this.request('chat.send', {
|
|
325
|
-
sessionKey, message: defangLocalPaths(`${
|
|
413
|
+
sessionKey, message: defangLocalPaths(`${p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
326
414
|
timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
|
|
327
415
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
328
416
|
}, 30_000);
|
|
@@ -444,6 +532,7 @@ export class SharingManager {
|
|
|
444
532
|
await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
|
|
445
533
|
this._links.set(shareId, link);
|
|
446
534
|
link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
|
|
535
|
+
this._wireRooms(link, s.owner?.gatewayId);
|
|
447
536
|
return link;
|
|
448
537
|
})().finally(() => this._linking.delete(shareId));
|
|
449
538
|
this._linking.set(shareId, p);
|
|
@@ -468,11 +557,18 @@ export class SharingManager {
|
|
|
468
557
|
* active share where they asked for this gateway's agents, matched by their gateway (else email).
|
|
469
558
|
* Returns { shareId, grant } or null when this gateway shares nothing with them.
|
|
470
559
|
*/
|
|
471
|
-
_grantToOwnerOf(
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
if (
|
|
475
|
-
|
|
560
|
+
_grantToOwnerOf(who) {
|
|
561
|
+
// `who`: another person's agent ('peer:<share>:<agent>') or a person ('person:<gateway id>').
|
|
562
|
+
let gw, email;
|
|
563
|
+
if (String(who || '').startsWith('person:')) {
|
|
564
|
+
gw = who.slice('person:'.length);
|
|
565
|
+
email = String(this.contact(gw)?.email || '').toLowerCase();
|
|
566
|
+
} else {
|
|
567
|
+
const id = SharingManager.parseRemoteId(who);
|
|
568
|
+
const theirs = id && this._shares.find(s => s.id === id.shareId && s.as === 'requester');
|
|
569
|
+
if (!theirs) return null;
|
|
570
|
+
gw = theirs.owner?.gatewayId; email = String(theirs.owner?.email || '').toLowerCase();
|
|
571
|
+
}
|
|
476
572
|
const candidates = this._shares.filter(s => s.as === 'owner' && s.status === 'active');
|
|
477
573
|
const mine = candidates.find(s => gw && s.requester?.gatewayId === gw)
|
|
478
574
|
|| candidates.find(s => email && String(s.requester?.email || '').toLowerCase() === email);
|
|
@@ -499,7 +595,7 @@ export class SharingManager {
|
|
|
499
595
|
const guestId = findGuestAgent(agents, localAgentId)?.id;
|
|
500
596
|
const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
|
|
501
597
|
if (!shared) return null;
|
|
502
|
-
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true },
|
|
598
|
+
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true, byPerson: String(remoteAgentId).startsWith('person:') },
|
|
503
599
|
(event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); });
|
|
504
600
|
}
|
|
505
601
|
|
|
@@ -10,18 +10,26 @@
|
|
|
10
10
|
// team_entries author of each injected room entry (the transcript only has a "[Label]" prefix);
|
|
11
11
|
// acting_for = whose request an agent answered when it wasn't its owner's ("Kamil")
|
|
12
12
|
// team_rooms.rounds follow-up rounds per human message when agents discuss (host setting)
|
|
13
|
+
// team_members.history 'all' (default: a first turn also gets the chat's earlier history) or 'now'
|
|
14
|
+
// team_people people in a room this gateway hosts (specs/sharing-people.md): a contact, by their
|
|
15
|
+
// gateway id; history_from = the oldest entry time they may see (0 = everything)
|
|
16
|
+
// team_rooms.host_* a live copy of someone else's room (this gateway is a member, not the host):
|
|
17
|
+
// host_gateway_id/host_room/host_name; replica_json = the host's members and people
|
|
18
|
+
// team_mirror host entry id -> local message id in a live copy (each host entry injected once)
|
|
13
19
|
|
|
14
20
|
const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
|
|
15
21
|
const MAX_ROUNDS = 10;
|
|
16
22
|
|
|
17
|
-
function roomRow(r, members) {
|
|
23
|
+
function roomRow(r, members, people = []) {
|
|
18
24
|
return {
|
|
19
25
|
roomKey: r.room_key,
|
|
20
26
|
discuss: !!r.discuss,
|
|
21
27
|
rounds: r.rounds || DISCUSS_ROUNDS,
|
|
22
28
|
sourceKey: r.source_key || null,
|
|
23
29
|
createdAt: r.created_at,
|
|
24
|
-
members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0 })),
|
|
30
|
+
members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0, history: m.history || 'all' })),
|
|
31
|
+
people: people.map(p => ({ personId: p.person_id, name: p.name, email: p.email || null, historyFrom: p.history_from || 0 })),
|
|
32
|
+
...(r.host_gateway_id ? { host: { gatewayId: r.host_gateway_id, roomId: r.host_room, name: r.host_name || 'Someone', ended: r.host_ended || null, ...JSON.parse(r.replica_json || '{}') } } : {}),
|
|
25
33
|
};
|
|
26
34
|
}
|
|
27
35
|
|
|
@@ -37,11 +45,18 @@ export function createTeamStore(getGlobalDb) {
|
|
|
37
45
|
g.exec(`CREATE TABLE IF NOT EXISTS team_entries (room_key TEXT NOT NULL, message_id TEXT NOT NULL, author_type TEXT NOT NULL, agent_id TEXT, created_at INTEGER NOT NULL, PRIMARY KEY (room_key, message_id))`);
|
|
38
46
|
if (!g.prepare('PRAGMA table_info(team_entries)').all().some(c => c.name === 'acting_for')) g.exec('ALTER TABLE team_entries ADD COLUMN acting_for TEXT');
|
|
39
47
|
if (!g.prepare('PRAGMA table_info(team_rooms)').all().some(c => c.name === 'rounds')) g.exec('ALTER TABLE team_rooms ADD COLUMN rounds INTEGER');
|
|
48
|
+
const cols = t => new Set(g.prepare(`PRAGMA table_info(${t})`).all().map(c => c.name));
|
|
49
|
+
if (!cols('team_members').has('history')) g.exec('ALTER TABLE team_members ADD COLUMN history TEXT');
|
|
50
|
+
const rc = cols('team_rooms');
|
|
51
|
+
for (const c of ['host_gateway_id', 'host_room', 'host_name', 'host_ended', 'replica_json']) if (!rc.has(c)) g.exec(`ALTER TABLE team_rooms ADD COLUMN ${c} TEXT`);
|
|
52
|
+
g.exec(`CREATE TABLE IF NOT EXISTS team_people (room_key TEXT NOT NULL, person_id TEXT NOT NULL, name TEXT NOT NULL, email TEXT, history_from INTEGER NOT NULL DEFAULT 0, added_at INTEGER NOT NULL, removed INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (room_key, person_id))`);
|
|
53
|
+
g.exec(`CREATE TABLE IF NOT EXISTS team_mirror (room_key TEXT NOT NULL, host_entry_id TEXT NOT NULL, message_id TEXT, PRIMARY KEY (room_key, host_entry_id))`);
|
|
40
54
|
ready = true;
|
|
41
55
|
}
|
|
42
56
|
return g;
|
|
43
57
|
}
|
|
44
58
|
const members = roomKey => db().prepare('SELECT * FROM team_members WHERE room_key = ? AND removed = 0 ORDER BY position').all(roomKey);
|
|
59
|
+
const people = roomKey => db().prepare('SELECT * FROM team_people WHERE room_key = ? AND removed = 0 ORDER BY added_at').all(roomKey);
|
|
45
60
|
|
|
46
61
|
return {
|
|
47
62
|
DISCUSS_ROUNDS,
|
|
@@ -49,11 +64,11 @@ export function createTeamStore(getGlobalDb) {
|
|
|
49
64
|
|
|
50
65
|
getRoom(roomKey) {
|
|
51
66
|
const r = db().prepare('SELECT * FROM team_rooms WHERE room_key = ?').get(roomKey);
|
|
52
|
-
return r ? roomRow(r, members(roomKey)) : null;
|
|
67
|
+
return r ? roomRow(r, members(roomKey), people(roomKey)) : null;
|
|
53
68
|
},
|
|
54
69
|
|
|
55
70
|
listRooms() {
|
|
56
|
-
return db().prepare('SELECT * FROM team_rooms ORDER BY created_at').all().map(r => roomRow(r, members(r.room_key)));
|
|
71
|
+
return db().prepare('SELECT * FROM team_rooms ORDER BY created_at').all().map(r => roomRow(r, members(r.room_key), people(r.room_key)));
|
|
57
72
|
},
|
|
58
73
|
|
|
59
74
|
/** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
|
|
@@ -69,14 +84,63 @@ export function createTeamStore(getGlobalDb) {
|
|
|
69
84
|
return this.getRoom(roomKey);
|
|
70
85
|
},
|
|
71
86
|
|
|
72
|
-
/**
|
|
73
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Adds an agent at the end (an agent removed earlier comes back with its session). Returns false if
|
|
89
|
+
* the room is unknown. history 'now': it starts from the newest entry, without the earlier chat.
|
|
90
|
+
*/
|
|
91
|
+
addMember(roomKey, agentId, { history = 'all', seenAt = 0 } = {}) {
|
|
74
92
|
if (!this.getRoom(roomKey)) return false;
|
|
75
93
|
const pos = db().prepare('SELECT COALESCE(MAX(position), -1) + 1 AS p FROM team_members WHERE room_key = ?').get(roomKey).p;
|
|
76
|
-
db().prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, NULL,
|
|
94
|
+
db().prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position, history) VALUES (?, ?, NULL, ?, ?, ?) ON CONFLICT(room_key, agent_id) DO UPDATE SET removed = 0, position = excluded.position WHERE removed = 1')
|
|
95
|
+
.run(roomKey, agentId, seenAt, pos, history === 'now' ? 'now' : 'all');
|
|
77
96
|
return true;
|
|
78
97
|
},
|
|
79
98
|
|
|
99
|
+
/** A person joins a room this gateway hosts (or comes back). historyFrom: oldest entry time they see. */
|
|
100
|
+
addPerson(roomKey, { personId, name, email = null, historyFrom = 0 }) {
|
|
101
|
+
if (!this.getRoom(roomKey)) return false;
|
|
102
|
+
db().prepare(`INSERT INTO team_people (room_key, person_id, name, email, history_from, added_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
103
|
+
ON CONFLICT(room_key, person_id) DO UPDATE SET removed = 0, name = excluded.name, email = excluded.email, history_from = excluded.history_from WHERE removed = 1`)
|
|
104
|
+
.run(roomKey, personId, String(name).slice(0, 100), email, historyFrom, Date.now());
|
|
105
|
+
return true;
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
removePerson(roomKey, personId) {
|
|
109
|
+
db().prepare('UPDATE team_people SET removed = 1 WHERE room_key = ? AND person_id = ?').run(roomKey, personId);
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
/** Every room a person is in (this gateway hosting). */
|
|
113
|
+
roomsWithPerson(personId) {
|
|
114
|
+
return db().prepare('SELECT room_key FROM team_people WHERE person_id = ? AND removed = 0').all(personId).map(r => r.room_key);
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
// ── Live copies (this gateway is a member of someone else's room) ──
|
|
118
|
+
|
|
119
|
+
/** The local copy of a host's room, or null. */
|
|
120
|
+
replicaFor(hostGatewayId, hostRoom) {
|
|
121
|
+
return db().prepare('SELECT room_key FROM team_rooms WHERE host_gateway_id = ? AND host_room = ?').get(hostGatewayId, hostRoom)?.room_key || null;
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
createReplica(roomKey, { hostGatewayId, hostRoom, hostName }) {
|
|
125
|
+
const now = Date.now();
|
|
126
|
+
db().prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at, host_gateway_id, host_room, host_name, replica_json) VALUES (?, 0, NULL, ?, ?, ?, ?, ?, ?)')
|
|
127
|
+
.run(roomKey, now, now, hostGatewayId, hostRoom, String(hostName).slice(0, 100), '{}');
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
/** The host's view of its room: { members: [{ agentId, name, ownerGatewayId? }], people: [...], title, discuss }. */
|
|
131
|
+
setReplica(roomKey, { hostName, view, ended }) {
|
|
132
|
+
db().prepare('UPDATE team_rooms SET host_name = COALESCE(?, host_name), replica_json = COALESCE(?, replica_json), host_ended = ?, updated_at = ? WHERE room_key = ?')
|
|
133
|
+
.run(hostName ? String(hostName).slice(0, 100) : null, view ? JSON.stringify(view) : null, ended || null, Date.now(), roomKey);
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
mirrored(roomKey, hostEntryId) {
|
|
137
|
+
return !!db().prepare('SELECT 1 FROM team_mirror WHERE room_key = ? AND host_entry_id = ?').get(roomKey, hostEntryId);
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
recordMirror(roomKey, hostEntryId, messageId) {
|
|
141
|
+
db().prepare('INSERT OR REPLACE INTO team_mirror (room_key, host_entry_id, message_id) VALUES (?, ?, ?)').run(roomKey, hostEntryId, messageId);
|
|
142
|
+
},
|
|
143
|
+
|
|
80
144
|
/** Takes an agent out of the room; its working session stays hidden (reused if it's added back). */
|
|
81
145
|
removeMember(roomKey, agentId) {
|
|
82
146
|
db().prepare('UPDATE team_members SET removed = 1 WHERE room_key = ? AND agent_id = ?').run(roomKey, agentId);
|
|
@@ -104,6 +168,8 @@ export function createTeamStore(getGlobalDb) {
|
|
|
104
168
|
const g = db();
|
|
105
169
|
g.prepare('DELETE FROM team_members WHERE room_key = ?').run(roomKey);
|
|
106
170
|
g.prepare('DELETE FROM team_entries WHERE room_key = ?').run(roomKey);
|
|
171
|
+
g.prepare('DELETE FROM team_people WHERE room_key = ?').run(roomKey);
|
|
172
|
+
g.prepare('DELETE FROM team_mirror WHERE room_key = ?').run(roomKey);
|
|
107
173
|
g.prepare('DELETE FROM team_rooms WHERE room_key = ?').run(roomKey);
|
|
108
174
|
return work;
|
|
109
175
|
},
|
|
@@ -119,16 +185,22 @@ export function createTeamStore(getGlobalDb) {
|
|
|
119
185
|
return new Set(db().prepare('SELECT work_key FROM team_members WHERE work_key IS NOT NULL').all().map(r => r.work_key));
|
|
120
186
|
},
|
|
121
187
|
|
|
188
|
+
/**
|
|
189
|
+
* type 'user' (this gateway's own person), 'person' (someone else; agentId holds their person id
|
|
190
|
+
* and actingFor their name), or 'agent' (actingFor: whose request it answered, if not its owner's).
|
|
191
|
+
*/
|
|
122
192
|
recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
|
|
123
193
|
db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for) VALUES (?, ?, ?, ?, ?, ?)')
|
|
124
|
-
.run(roomKey, messageId,
|
|
194
|
+
.run(roomKey, messageId, ['user', 'person'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor);
|
|
125
195
|
},
|
|
126
196
|
|
|
127
|
-
/** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } } */
|
|
197
|
+
/** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
|
|
128
198
|
authors(roomKey) {
|
|
129
199
|
const out = {};
|
|
130
200
|
for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for FROM team_entries WHERE room_key = ?').all(roomKey)) {
|
|
131
|
-
out[r.message_id] =
|
|
201
|
+
out[r.message_id] = r.author_type === 'person'
|
|
202
|
+
? { type: 'person', personId: r.agent_id, name: r.acting_for }
|
|
203
|
+
: { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}) };
|
|
132
204
|
}
|
|
133
205
|
return out;
|
|
134
206
|
},
|
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
|
|
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
|
-
|
|
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
|
|
361
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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); }
|
package/server/team.test.js
CHANGED
|
@@ -8,7 +8,7 @@ import { SessionLens } from './session-lens.js';
|
|
|
8
8
|
const AGENTS = [{ id: 'main', identity: {} }, { id: 'dev', identity: { name: 'Dev' } }, { id: 'atlas', identity: { name: 'Atlas' } }];
|
|
9
9
|
|
|
10
10
|
/** Fake gateway. `reply(agentId, prompt)` returns the agent's reply text, null (abort) or a promise. */
|
|
11
|
-
function harness(reply, { preparedTitle = 'Team title', titler = null, remote = null } = {}) {
|
|
11
|
+
function harness(reply, { preparedTitle = 'Team title', titler = null, remote = null, agents = AGENTS } = {}) {
|
|
12
12
|
const sessions = new Map(); // key -> [{ role, content, timestamp, __m: { id } }]
|
|
13
13
|
const calls = [];
|
|
14
14
|
let clock = 1_000, seq = 0;
|
|
@@ -17,7 +17,7 @@ function harness(reply, { preparedTitle = 'Team title', titler = null, remote =
|
|
|
17
17
|
const request = async (method, params) => {
|
|
18
18
|
calls.push({ method, params });
|
|
19
19
|
switch (method) {
|
|
20
|
-
case 'agents.list': return { agents
|
|
20
|
+
case 'agents.list': return { agents };
|
|
21
21
|
case 'sessions.create': sessions.set(params.key, []); return { ok: true, key: params.key };
|
|
22
22
|
case 'sessions.describe': return { session: { key: params.key } };
|
|
23
23
|
case 'sessions.title.prepare': return { title: preparedTitle };
|
|
@@ -467,3 +467,140 @@ test('rounds: a per-room host setting, validated', async () => {
|
|
|
467
467
|
await h.settle();
|
|
468
468
|
assert.ok(h.calls.filter(c => c.method === 'chat.send').length > 4, 'more rounds when allowed');
|
|
469
469
|
});
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Two gateways: Houman hosts (gwH), Kamil is a member (gwK). Kamil shares Jarvis (guest) with Houman
|
|
473
|
+
* as share sh1; Houman shares dev with Kamil. Each side's `remote` is a fake sharing manager whose
|
|
474
|
+
* personRequest calls the other coordinator's onRoom, as the peer link would.
|
|
475
|
+
*/
|
|
476
|
+
function twoGateways({ devShared = true } = {}) {
|
|
477
|
+
const forCalls = [];
|
|
478
|
+
const sides = {};
|
|
479
|
+
const mk = (self, other, name) => ({
|
|
480
|
+
gatewayId: () => self,
|
|
481
|
+
selfName: () => name,
|
|
482
|
+
contact: gw => (gw === other ? { personId: other, name: other === 'gwK' ? 'Kamil' : 'Houman', email: null } : null),
|
|
483
|
+
personRequest: async (gw, method, params) => {
|
|
484
|
+
if (gw !== other) throw Object.assign(new Error('not connected'), { code: 'not_connected' });
|
|
485
|
+
return sides[other].team.onRoom(method, JSON.parse(JSON.stringify(params)), self);
|
|
486
|
+
},
|
|
487
|
+
ownerOf: id => (String(id).startsWith('peer:sh1:') && self === 'gwH' ? 'gwK' : null),
|
|
488
|
+
ownsShare: shareId => shareId === 'sh1' && self === 'gwK',
|
|
489
|
+
remoteAgents: () => (self === 'gwH' ? [{ agentId: 'peer:sh1:jarvis-guest', name: 'Jarvis · Kamil', ownerName: 'Kamil' }] : []),
|
|
490
|
+
turn: async () => ({ state: 'final', text: 'guest jarvis here' }),
|
|
491
|
+
abort: async () => {},
|
|
492
|
+
actingForName: () => 'Kamil',
|
|
493
|
+
localTurnFor: async (localId, who, args) => {
|
|
494
|
+
forCalls.push({ localId, who, args });
|
|
495
|
+
return devShared ? { state: 'final', text: `${localId} for kamil` } : null;
|
|
496
|
+
},
|
|
497
|
+
});
|
|
498
|
+
sides.gwH = harness(agent => `${agent} full`, { remote: mk('gwH', 'gwK', 'Houman Satarian') });
|
|
499
|
+
sides.gwK = harness(agent => `${agent} full on kamil`, {
|
|
500
|
+
remote: mk('gwK', 'gwH', 'Kamil Gronowski'),
|
|
501
|
+
agents: [{ id: 'main', identity: {} }, { id: 'jarvis', name: 'Jarvis' }, { id: 'jarvis-guest', name: 'Jarvis (guest)' }],
|
|
502
|
+
});
|
|
503
|
+
const settle = async () => {
|
|
504
|
+
for (let i = 0; i < 6; i++) {
|
|
505
|
+
await new Promise(r => setTimeout(r, 350)); // pushes are batched (300 ms)
|
|
506
|
+
await sides.gwH.settle(); await sides.gwK.settle();
|
|
507
|
+
for (const c of sides.gwK.team._syncChains?.values() || []) await c.catch(() => {});
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
return { H: sides.gwH, K: sides.gwK, settle, forCalls };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
test('people: a person gets a live copy, posts back, their own agent runs on their gateway, removal ends it', async () => {
|
|
514
|
+
const { H, K, settle, forCalls } = twoGateways();
|
|
515
|
+
const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis-guest'] });
|
|
516
|
+
await H.team.send(roomKey, { text: 'before kamil joins', userLabel: 'Houman' });
|
|
517
|
+
await settle();
|
|
518
|
+
await H.team.addPerson(roomKey, 'gwK', { history: 'all' });
|
|
519
|
+
await settle();
|
|
520
|
+
|
|
521
|
+
// Kamil's copy: a local room session, hosted by Houman, with the history (Houman chose "all").
|
|
522
|
+
const copy = K.team.rooms().find(r => r.replica);
|
|
523
|
+
assert.ok(copy, 'a live copy exists on Kamil\'s gateway');
|
|
524
|
+
assert.equal(copy.replica.hostName, 'Houman Satarian');
|
|
525
|
+
assert.ok(K.room(copy.roomKey).some(t => t.endsWith('before kamil joins')));
|
|
526
|
+
assert.deepEqual(copy.people.map(p => [p.name, !!p.host, !!p.me]), [['Houman Satarian', true, false], ['Kamil', false, true]]);
|
|
527
|
+
assert.ok(copy.agents.find(a => a.agentId === 'peer:sh1:jarvis-guest').mine, 'Kamil sees Jarvis as his own agent');
|
|
528
|
+
assert.ok(K.events.some(e => e.event === 'team-invited'));
|
|
529
|
+
|
|
530
|
+
// Kamil asks his own Jarvis: it runs at full strength on Kamil's gateway; Houman's never runs it.
|
|
531
|
+
const kSends = () => K.calls.filter(c => c.method === 'chat.send').map(c => c.params.sessionKey);
|
|
532
|
+
await K.team.send(copy.roomKey, { text: '@Jarvis-Kamil check yours' });
|
|
533
|
+
await settle();
|
|
534
|
+
assert.ok(kSends().some(k => k.startsWith('agent:jarvis:')), 'the real Jarvis ran on Kamil\'s gateway');
|
|
535
|
+
assert.ok(!kSends().some(k => k.startsWith('agent:jarvis-guest:')));
|
|
536
|
+
const hostRoom = H.room(roomKey);
|
|
537
|
+
assert.ok(hostRoom.includes('[Kamil]\n\n@Jarvis-Kamil check yours'), 'Kamil\'s message is in the host room under his name');
|
|
538
|
+
assert.ok(hostRoom.includes('[Jarvis · Kamil]\n\njarvis full on kamil'), 'Jarvis\'s reply reached the host room');
|
|
539
|
+
const hAuthors = H.team.room(roomKey).authors;
|
|
540
|
+
assert.ok(Object.values(hAuthors).some(a => a.type === 'person' && a.personId === 'gwK' && a.name === 'Kamil'));
|
|
541
|
+
// ...and came back to Kamil's copy, where his own message shows as his.
|
|
542
|
+
const kAuthors = K.team.room(copy.roomKey).authors;
|
|
543
|
+
assert.ok(Object.values(kAuthors).some(a => a.type === 'user'));
|
|
544
|
+
assert.ok(K.room(copy.roomKey).some(t => t.endsWith('jarvis full on kamil')));
|
|
545
|
+
|
|
546
|
+
// Kamil asks Houman's dev: dev answers him as the version shared with him, never at full strength.
|
|
547
|
+
const devFull = () => H.calls.filter(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:dev:')).length;
|
|
548
|
+
const before = devFull();
|
|
549
|
+
await K.team.send(copy.roomKey, { text: '@dev what version are you on?' });
|
|
550
|
+
await settle();
|
|
551
|
+
assert.equal(devFull(), before);
|
|
552
|
+
assert.deepEqual(forCalls.map(c => [c.localId, c.who]), [['dev', 'person:gwK']]);
|
|
553
|
+
assert.ok(H.room(roomKey).includes('[Dev]\n\ndev for kamil'));
|
|
554
|
+
assert.ok(Object.values(H.team.room(roomKey).authors).some(a => a.agentId === 'dev' && a.actingFor === 'Kamil'));
|
|
555
|
+
|
|
556
|
+
// Houman removes Kamil: Jarvis leaves with him, the copy ends, sending fails.
|
|
557
|
+
H.team.removePerson(roomKey, 'gwK');
|
|
558
|
+
await settle();
|
|
559
|
+
assert.ok(!H.team.room(roomKey).agents.some(a => a.agentId === 'peer:sh1:jarvis-guest'));
|
|
560
|
+
assert.equal(K.team.room(copy.roomKey).replica.ended, 'removed');
|
|
561
|
+
await assert.rejects(K.team.send(copy.roomKey, { text: 'still here?' }), /removed you/);
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
test("people: adding someone's agent brings them in; 'now' hides the earlier chat; only the host changes the room", async () => {
|
|
565
|
+
const { H, K, settle } = twoGateways();
|
|
566
|
+
const { roomKey } = await H.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
567
|
+
await H.team.send(roomKey, { text: 'secret plan', userLabel: 'Houman' });
|
|
568
|
+
await settle();
|
|
569
|
+
await H.team.addAgent(roomKey, 'peer:sh1:jarvis-guest', { history: 'now' });
|
|
570
|
+
await settle();
|
|
571
|
+
assert.deepEqual(H.team.room(roomKey).people.map(p => p.personId), ['gwK']);
|
|
572
|
+
const copy = K.team.rooms().find(r => r.replica);
|
|
573
|
+
assert.ok(!K.room(copy.roomKey).some(t => t.includes('secret plan')), "'from now on': nothing earlier");
|
|
574
|
+
await assert.rejects(K.team.addAgent(copy.roomKey, 'main'), /host/);
|
|
575
|
+
await assert.rejects(K.team.onRoom('room.post', { roomId: 'agent:dev:dashboard:nope', text: 'x' }, 'gwK'), /not in this team chat/);
|
|
576
|
+
// A stranger can't post into the room.
|
|
577
|
+
await assert.rejects(H.team.onRoom('room.post', { roomId: roomKey, text: 'hi' }, 'gwX'), /not in this team chat/);
|
|
578
|
+
// Kamil leaves: he's out, and so is Jarvis.
|
|
579
|
+
await K.team.leave(copy.roomKey);
|
|
580
|
+
await settle();
|
|
581
|
+
assert.equal(H.team.room(roomKey).people.length, 0);
|
|
582
|
+
assert.equal(K.team.room(copy.roomKey).replica.ended, 'left');
|
|
583
|
+
});
|
|
584
|
+
|
|
585
|
+
test('a chat turned into a team chat: agents added later get its earlier history on their first turn, unless "now"', async () => {
|
|
586
|
+
const h = harness((agent, prompt) => `${agent}: ${/Earlier in this chat/.test(prompt) ? 'saw history' : 'no history'}`);
|
|
587
|
+
// the original chat with its history
|
|
588
|
+
h.sessions.set('agent:main:dashboard:orig', [
|
|
589
|
+
{ role: 'user', content: 'how do I fix the gateway crash?', timestamp: 1, __m: { id: 'o1' } },
|
|
590
|
+
{ role: 'assistant', content: [{ type: 'text', text: 'restart with --safe' }], timestamp: 2, __m: { id: 'o2' } },
|
|
591
|
+
]);
|
|
592
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev'], sourceKey: 'agent:main:dashboard:orig' });
|
|
593
|
+
await h.team.addAgent(roomKey, 'atlas', { history: 'now' });
|
|
594
|
+
await h.team.send(roomKey, { text: '@dev thoughts?', userLabel: 'H' });
|
|
595
|
+
await h.settle();
|
|
596
|
+
const devPrompt = h.calls.find(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:dev:')).params.message;
|
|
597
|
+
assert.match(devPrompt, /Earlier in this chat[\s\S]*how do I fix the gateway crash\?[\s\S]*restart with --safe/);
|
|
598
|
+
assert.ok(h.room(roomKey).includes('[Dev]\n\ndev: saw history'));
|
|
599
|
+
// "From now on": no earlier history, and it starts at the newest entry.
|
|
600
|
+
const atlas = h.team.store.getRoom(roomKey).members.find(m => m.agentId === 'atlas');
|
|
601
|
+
assert.equal(atlas.history, 'now');
|
|
602
|
+
assert.equal(await h.team._earlier(h.team.store.getRoom(roomKey), atlas).then(t => !!t), true, 'history exists, the turn skips it for "now"');
|
|
603
|
+
// The chat's own agent already has it in its session.
|
|
604
|
+
const main = h.team.store.getRoom(roomKey).members.find(m => m.agentId === 'main');
|
|
605
|
+
assert.equal(await h.team._earlier(h.team.store.getRoom(roomKey), main), '');
|
|
606
|
+
});
|