@clawchatsai/connector 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server/index.js +27 -4
- package/server/peer/sharing.js +148 -3
- package/server/peer/sharing.test.js +42 -0
- package/server/store/team-store.js +100 -17
- package/server/team.js +497 -28
- package/server/team.test.js +203 -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');
|
|
@@ -284,14 +284,37 @@ export function createApp(config = {}) {
|
|
|
284
284
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
285
285
|
}
|
|
286
286
|
if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
|
|
287
|
-
const
|
|
287
|
+
const body = await parseBody(req);
|
|
288
|
+
let room = team.room(p.room);
|
|
289
|
+
if (room && body.discuss !== undefined) {
|
|
290
|
+
try { room = team.setDiscuss(p.room, body.discuss); } catch (e) { return sendError(res, 400, e.message); }
|
|
291
|
+
}
|
|
292
|
+
if (room && body.rounds !== undefined) {
|
|
293
|
+
try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
|
|
294
|
+
}
|
|
288
295
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
289
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
|
+
}
|
|
290
313
|
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
|
|
291
|
-
const { agentId } = await parseBody(req);
|
|
314
|
+
const { agentId, history } = await parseBody(req);
|
|
292
315
|
if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
|
|
293
316
|
try {
|
|
294
|
-
const room = await team.addAgent(p.room, agentId);
|
|
317
|
+
const room = await team.addAgent(p.room, agentId, { history });
|
|
295
318
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
296
319
|
} catch (e) { return sendError(res, 400, e.message); }
|
|
297
320
|
}
|
package/server/peer/sharing.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import crypto from 'node:crypto';
|
|
17
17
|
import { PeerLink } from './link.js';
|
|
18
18
|
import { canonicalJson, verifySignature, fingerprint } from './keys.js';
|
|
19
|
-
import { hasGuestRestrictions, ensureGuestRestrictions } from './guest-agent.js';
|
|
19
|
+
import { hasGuestRestrictions, ensureGuestRestrictions, findGuestAgent } from './guest-agent.js';
|
|
20
20
|
|
|
21
21
|
const TURN_TIMEOUT_MS = 10 * 60_000;
|
|
22
22
|
const DEFAULT_DAILY_CAP = 50;
|
|
@@ -33,6 +33,8 @@ export const defangLocalPaths = text => text
|
|
|
33
33
|
.replace(/file:\/\//gi, 'file:\u200b//')
|
|
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
|
+
// The same agent in its owner's own team chat, answering another person's agent (localTurnFor).
|
|
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.)`;
|
|
36
38
|
|
|
37
39
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
38
40
|
/** A name that came from the other side, safe to show and to use as a chat label (no brackets, newlines, controls). */
|
|
@@ -92,12 +94,14 @@ export class SharingManager {
|
|
|
92
94
|
|
|
93
95
|
/** `share-list` from the signal server. Ends links/grants for shares that are gone. */
|
|
94
96
|
setShares(shares) {
|
|
97
|
+
const first = !this.serverEnabled;
|
|
95
98
|
this.serverEnabled = true;
|
|
96
99
|
this._shares = Array.isArray(shares) ? shares : [];
|
|
97
100
|
const live = new Set(this._shares.filter(s => s.status === 'active').map(s => s.id));
|
|
98
101
|
for (const [shareId, link] of this._links) if (!live.has(shareId)) { link.close(); this._links.delete(shareId); }
|
|
99
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);
|
|
100
103
|
this._changed();
|
|
104
|
+
if (first) setImmediate(() => { try { this.onFirstShares?.(); } catch (e) { this.log.warn?.(`[sharing] ${e.message}`); } });
|
|
101
105
|
}
|
|
102
106
|
|
|
103
107
|
/** The signal server says a share ended (revoke/decline): stop at once. */
|
|
@@ -258,11 +262,97 @@ export class SharingManager {
|
|
|
258
262
|
this._served.add(link);
|
|
259
263
|
link.on('closed', () => this._served.delete(link));
|
|
260
264
|
link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
|
|
261
|
-
link.handle('turn', (p, emit) => this._guestTurn(shareId, p, emit));
|
|
265
|
+
link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false, byPerson: false }, emit)); // only localTurnFor sets these
|
|
262
266
|
link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
|
|
267
|
+
this._wireRooms(link, requesterGatewayId);
|
|
263
268
|
return link;
|
|
264
269
|
}
|
|
265
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
|
+
|
|
266
356
|
/** Run one guest turn in this gateway's session for (share, room, agent); stream text back. */
|
|
267
357
|
async _guestTurn(shareId, p, emit) {
|
|
268
358
|
const g = this._grant(shareId);
|
|
@@ -320,7 +410,7 @@ export class SharingManager {
|
|
|
320
410
|
try {
|
|
321
411
|
if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
|
|
322
412
|
await this.request('chat.send', {
|
|
323
|
-
sessionKey, message: defangLocalPaths(`${GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
413
|
+
sessionKey, message: defangLocalPaths(`${p.inOwnerRoom ? ACTING_FOR_NOTE(name, p.byPerson) : GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
324
414
|
timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
|
|
325
415
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
326
416
|
}, 30_000);
|
|
@@ -442,6 +532,7 @@ export class SharingManager {
|
|
|
442
532
|
await new Promise((resolve, reject) => { link.once('ready', resolve); link.once('closed', () => reject(new Error(`Couldn't reach ${firstName(s.owner)}'s gateway`))); });
|
|
443
533
|
this._links.set(shareId, link);
|
|
444
534
|
link.on('closed', () => { if (this._links.get(shareId) === link) this._links.delete(shareId); });
|
|
535
|
+
this._wireRooms(link, s.owner?.gatewayId);
|
|
445
536
|
return link;
|
|
446
537
|
})().finally(() => this._linking.delete(shareId));
|
|
447
538
|
this._linking.set(shareId, p);
|
|
@@ -459,6 +550,60 @@ export class SharingManager {
|
|
|
459
550
|
});
|
|
460
551
|
}
|
|
461
552
|
|
|
553
|
+
// ── Acting for someone else (team chats on this gateway) ──────────
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Who another person's agent belongs to, as this gateway's owner-side grant to that person: the
|
|
557
|
+
* active share where they asked for this gateway's agents, matched by their gateway (else email).
|
|
558
|
+
* Returns { shareId, grant } or null when this gateway shares nothing with them.
|
|
559
|
+
*/
|
|
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
|
+
}
|
|
572
|
+
const candidates = this._shares.filter(s => s.as === 'owner' && s.status === 'active');
|
|
573
|
+
const mine = candidates.find(s => gw && s.requester?.gatewayId === gw)
|
|
574
|
+
|| candidates.find(s => email && String(s.requester?.email || '').toLowerCase() === email);
|
|
575
|
+
const g = mine && this._grant(mine.id);
|
|
576
|
+
return g ? { shareId: mine.id, grant: g.grant } : null;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** The name to show for whom a local agent acts ("Kamil"), or null. */
|
|
580
|
+
actingForName(remoteAgentId) {
|
|
581
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
582
|
+
return g ? (firstName({ name: g.grant.requesterName }) || 'Someone') : null;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Run one of this gateway's agents because another person's agent asked (a team chat here):
|
|
587
|
+
* authority comes from who asked (specs/sharing-people.md), so it runs as the version shared with
|
|
588
|
+
* that person (its guest copy, normally) under their grant: access level, daily cap, its own
|
|
589
|
+
* session in "Shared with <name>". Returns null when that agent isn't shared with them.
|
|
590
|
+
*/
|
|
591
|
+
async localTurnFor(localAgentId, remoteAgentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
|
|
592
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
593
|
+
if (!g) return null;
|
|
594
|
+
const agents = (await this.request('agents.list', {}))?.agents || [];
|
|
595
|
+
const guestId = findGuestAgent(agents, localAgentId)?.id;
|
|
596
|
+
const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
|
|
597
|
+
if (!shared) return null;
|
|
598
|
+
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true, byPerson: String(remoteAgentId).startsWith('person:') },
|
|
599
|
+
(event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); });
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async abortLocalFor(localAgentId, remoteAgentId, turnId) {
|
|
603
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
604
|
+
if (g) await this._guestAbort(g.shareId, turnId);
|
|
605
|
+
}
|
|
606
|
+
|
|
462
607
|
async abort(agentId, turnId) {
|
|
463
608
|
const id = SharingManager.parseRemoteId(agentId);
|
|
464
609
|
const link = id && this._links.get(id.shareId);
|
|
@@ -380,3 +380,45 @@ test('a reply that fails without text is not counted against the daily cap; one
|
|
|
380
380
|
await assert.rejects(p);
|
|
381
381
|
assert.equal(s.owner.list()[0].usedToday, 1);
|
|
382
382
|
});
|
|
383
|
+
|
|
384
|
+
test("acting for someone: this gateway's agent answers their agent as the version shared with them, under their grant", async () => {
|
|
385
|
+
const s = setup();
|
|
386
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }], access: 'restricted', dailyCap: 5 });
|
|
387
|
+
const active = s.activate();
|
|
388
|
+
// Kamil (this gateway, gwK) also uses Houman's main: share sh2, Kamil as requester, Houman's gateway gwH.
|
|
389
|
+
const theirs = { id: 'sh2', as: 'requester', status: 'active', requester: s.people.owner, owner: s.people.requester, agents: [{ id: 'main-guest', name: 'main' }] };
|
|
390
|
+
s.owner.setShares([{ ...active, as: 'owner' }, theirs]);
|
|
391
|
+
const orig = s.owner.request;
|
|
392
|
+
s.owner.request = async (m, p) => (m === 'agents.list'
|
|
393
|
+
? { agents: [{ id: 'jarvis', name: 'Jarvis' }, { id: 'jarvis-guest', name: 'Jarvis (guest)' }, { id: 'dev', name: 'Dev' }] }
|
|
394
|
+
: orig(m, p));
|
|
395
|
+
|
|
396
|
+
assert.equal(s.owner.actingForName('peer:sh2:main-guest'), 'Houman');
|
|
397
|
+
const deltas = [];
|
|
398
|
+
const r = await s.owner.localTurnFor('jarvis', 'peer:sh2:main-guest', { turnId: 'x1', roomId: 'kamils-room', roomTitle: 'Crash', message: 'how did you fix it?' }, { onDelta: d => deltas.push(d) });
|
|
399
|
+
assert.equal(r.state, 'final');
|
|
400
|
+
assert.deepEqual(deltas, ['jar']);
|
|
401
|
+
const create = s.ownerCalls.find(c => c.method === 'sessions.create').params;
|
|
402
|
+
assert.equal(create.agentId, 'jarvis-guest', 'the guest copy, never the real agent');
|
|
403
|
+
assert.equal(create.permissionMode, 'read-only');
|
|
404
|
+
assert.equal(create.category, 'Shared with Houman S');
|
|
405
|
+
const send = s.ownerCalls.find(c => c.method === 'chat.send').params;
|
|
406
|
+
assert.match(send.message, /in your owner's team chat, you are answering Houman S's agent/);
|
|
407
|
+
assert.equal(s.owner.list().find(x => x.id === 'sh1').usedToday, 1, "counts toward Houman's daily cap");
|
|
408
|
+
|
|
409
|
+
// An agent not shared with them, an unknown asker, or a share that ended: no run at all.
|
|
410
|
+
assert.equal(await s.owner.localTurnFor('dev', 'peer:sh2:main-guest', { turnId: 'x2', roomId: 'kamils-room', message: 'hi' }), null);
|
|
411
|
+
assert.equal(await s.owner.localTurnFor('jarvis', 'peer:sh9:main-guest', { turnId: 'x3', roomId: 'kamils-room', message: 'hi' }), null);
|
|
412
|
+
s.owner.setShares([theirs]);
|
|
413
|
+
assert.equal(await s.owner.localTurnFor('jarvis', 'peer:sh2:main-guest', { turnId: 'x4', roomId: 'kamils-room', message: 'hi' }), null);
|
|
414
|
+
assert.equal(s.ownerCalls.filter(c => c.method === 'chat.send').length, 1);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
test('a peer request cannot pick the owner-room note', async () => {
|
|
418
|
+
const s = setup();
|
|
419
|
+
s.owner.approve('sh1', { agents: [{ id: 'jarvis-guest', name: 'Jarvis' }] });
|
|
420
|
+
s.activate();
|
|
421
|
+
const link = await s.req._link('sh1'); // a crafted request straight over the link, not through turn()
|
|
422
|
+
await link.request('turn', { turnId: 't1', agentId: 'jarvis-guest', roomId: 'r', message: 'hi', inOwnerRoom: true }, { timeoutMs: 5000 });
|
|
423
|
+
assert.match(s.ownerCalls.find(c => c.method === 'chat.send').params.message, /you are answering Houman S's team chat/);
|
|
424
|
+
});
|
|
@@ -7,17 +7,29 @@
|
|
|
7
7
|
// seen_at = timestamp of the newest room entry the agent has been given;
|
|
8
8
|
// removed = 1: agent taken out of the room; its session stays hidden and is reused
|
|
9
9
|
// if the agent is added back
|
|
10
|
-
// team_entries author of each injected room entry (the transcript only has a "[Label]" prefix)
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
10
|
+
// team_entries author of each injected room entry (the transcript only has a "[Label]" prefix);
|
|
11
|
+
// acting_for = whose request an agent answered when it wasn't its owner's ("Kamil")
|
|
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)
|
|
19
|
+
|
|
20
|
+
const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
|
|
21
|
+
const MAX_ROUNDS = 10;
|
|
22
|
+
|
|
23
|
+
function roomRow(r, members, people = []) {
|
|
15
24
|
return {
|
|
16
25
|
roomKey: r.room_key,
|
|
17
26
|
discuss: !!r.discuss,
|
|
27
|
+
rounds: r.rounds || DISCUSS_ROUNDS,
|
|
18
28
|
sourceKey: r.source_key || null,
|
|
19
29
|
createdAt: r.created_at,
|
|
20
|
-
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 || '{}') } } : {}),
|
|
21
33
|
};
|
|
22
34
|
}
|
|
23
35
|
|
|
@@ -31,22 +43,32 @@ export function createTeamStore(getGlobalDb) {
|
|
|
31
43
|
g.exec(`CREATE INDEX IF NOT EXISTS team_members_work ON team_members (work_key)`);
|
|
32
44
|
if (!g.prepare('PRAGMA table_info(team_members)').all().some(c => c.name === 'removed')) g.exec('ALTER TABLE team_members ADD COLUMN removed INTEGER NOT NULL DEFAULT 0');
|
|
33
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))`);
|
|
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');
|
|
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))`);
|
|
34
54
|
ready = true;
|
|
35
55
|
}
|
|
36
56
|
return g;
|
|
37
57
|
}
|
|
38
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);
|
|
39
60
|
|
|
40
61
|
return {
|
|
41
62
|
DISCUSS_ROUNDS,
|
|
63
|
+
MAX_ROUNDS,
|
|
42
64
|
|
|
43
65
|
getRoom(roomKey) {
|
|
44
66
|
const r = db().prepare('SELECT * FROM team_rooms WHERE room_key = ?').get(roomKey);
|
|
45
|
-
return r ? roomRow(r, members(roomKey)) : null;
|
|
67
|
+
return r ? roomRow(r, members(roomKey), people(roomKey)) : null;
|
|
46
68
|
},
|
|
47
69
|
|
|
48
70
|
listRooms() {
|
|
49
|
-
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)));
|
|
50
72
|
},
|
|
51
73
|
|
|
52
74
|
/** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
|
|
@@ -62,14 +84,63 @@ export function createTeamStore(getGlobalDb) {
|
|
|
62
84
|
return this.getRoom(roomKey);
|
|
63
85
|
},
|
|
64
86
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
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 } = {}) {
|
|
67
92
|
if (!this.getRoom(roomKey)) return false;
|
|
68
93
|
const pos = db().prepare('SELECT COALESCE(MAX(position), -1) + 1 AS p FROM team_members WHERE room_key = ?').get(roomKey).p;
|
|
69
|
-
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');
|
|
96
|
+
return true;
|
|
97
|
+
},
|
|
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());
|
|
70
105
|
return true;
|
|
71
106
|
},
|
|
72
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
|
+
|
|
73
144
|
/** Takes an agent out of the room; its working session stays hidden (reused if it's added back). */
|
|
74
145
|
removeMember(roomKey, agentId) {
|
|
75
146
|
db().prepare('UPDATE team_members SET removed = 1 WHERE room_key = ? AND agent_id = ?').run(roomKey, agentId);
|
|
@@ -87,12 +158,18 @@ export function createTeamStore(getGlobalDb) {
|
|
|
87
158
|
db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
|
|
88
159
|
},
|
|
89
160
|
|
|
161
|
+
setRounds(roomKey, rounds) {
|
|
162
|
+
db().prepare('UPDATE team_rooms SET rounds = ?, updated_at = ? WHERE room_key = ?').run(rounds, Date.now(), roomKey);
|
|
163
|
+
},
|
|
164
|
+
|
|
90
165
|
/** Drops the room; returns the working session keys it had. */
|
|
91
166
|
deleteRoom(roomKey) {
|
|
92
167
|
const work = db().prepare('SELECT work_key FROM team_members WHERE room_key = ? AND work_key IS NOT NULL').all(roomKey).map(m => m.work_key);
|
|
93
168
|
const g = db();
|
|
94
169
|
g.prepare('DELETE FROM team_members WHERE room_key = ?').run(roomKey);
|
|
95
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);
|
|
96
173
|
g.prepare('DELETE FROM team_rooms WHERE room_key = ?').run(roomKey);
|
|
97
174
|
return work;
|
|
98
175
|
},
|
|
@@ -108,16 +185,22 @@ export function createTeamStore(getGlobalDb) {
|
|
|
108
185
|
return new Set(db().prepare('SELECT work_key FROM team_members WHERE work_key IS NOT NULL').all().map(r => r.work_key));
|
|
109
186
|
},
|
|
110
187
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
+
*/
|
|
192
|
+
recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
|
|
193
|
+
db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at, acting_for) VALUES (?, ?, ?, ?, ?, ?)')
|
|
194
|
+
.run(roomKey, messageId, ['user', 'person'].includes(type) ? type : 'agent', agentId, Date.now(), actingFor);
|
|
114
195
|
},
|
|
115
196
|
|
|
116
|
-
/** { [messageId]: { type: 'user'|'agent', agentId } } */
|
|
197
|
+
/** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } | { type: 'person', personId, name } } */
|
|
117
198
|
authors(roomKey) {
|
|
118
199
|
const out = {};
|
|
119
|
-
for (const r of db().prepare('SELECT message_id, author_type, agent_id FROM team_entries WHERE room_key = ?').all(roomKey)) {
|
|
120
|
-
out[r.message_id] =
|
|
200
|
+
for (const r of db().prepare('SELECT message_id, author_type, agent_id, acting_for FROM team_entries WHERE room_key = ?').all(roomKey)) {
|
|
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 } : {}) };
|
|
121
204
|
}
|
|
122
205
|
return out;
|
|
123
206
|
},
|