@clawchatsai/connector 0.1.33 → 0.1.34
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 +6 -1
- package/server/peer/sharing.js +52 -3
- package/server/peer/sharing.test.js +42 -0
- package/server/store/team-store.js +19 -8
- package/server/team.js +79 -11
- package/server/team.test.js +64 -0
package/package.json
CHANGED
package/server/index.js
CHANGED
|
@@ -284,7 +284,12 @@ 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) room = team.setDiscuss(p.room, body.discuss);
|
|
290
|
+
if (room && body.rounds !== undefined) {
|
|
291
|
+
try { room = team.setRounds(p.room, body.rounds); } catch (e) { return sendError(res, 400, e.message); }
|
|
292
|
+
}
|
|
288
293
|
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
289
294
|
}
|
|
290
295
|
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
|
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 => `(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.)`;
|
|
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). */
|
|
@@ -258,7 +260,7 @@ export class SharingManager {
|
|
|
258
260
|
this._served.add(link);
|
|
259
261
|
link.on('closed', () => this._served.delete(link));
|
|
260
262
|
link.handle('agents', async () => ({ agents: this._grant(shareId)?.grant.agents || [] }));
|
|
261
|
-
link.handle('turn', (p, emit) => this._guestTurn(shareId, p, emit));
|
|
263
|
+
link.handle('turn', (p, emit) => this._guestTurn(shareId, { ...p, inOwnerRoom: false }, emit)); // only localTurnFor sets it
|
|
262
264
|
link.handle('abort', async p => this._guestAbort(shareId, p?.turnId));
|
|
263
265
|
return link;
|
|
264
266
|
}
|
|
@@ -320,7 +322,7 @@ export class SharingManager {
|
|
|
320
322
|
try {
|
|
321
323
|
if (!this._grant(shareId)) throw Object.assign(new Error('Sharing has ended'), { code: 'revoked' }); // revoked while setting up
|
|
322
324
|
await this.request('chat.send', {
|
|
323
|
-
sessionKey, message: defangLocalPaths(`${GUEST_NOTE(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
325
|
+
sessionKey, message: defangLocalPaths(`${(p.inOwnerRoom ? ACTING_FOR_NOTE : GUEST_NOTE)(name)}\n\n${p.message}`), deliver: false, idempotencyKey: runId,
|
|
324
326
|
timeoutMs: TURN_TIMEOUT_MS, suppressCommandInterpretation: true,
|
|
325
327
|
expectedPermissionMode: permissionMode, expectedToolOverrides: toolOverrides,
|
|
326
328
|
}, 30_000);
|
|
@@ -459,6 +461,53 @@ export class SharingManager {
|
|
|
459
461
|
});
|
|
460
462
|
}
|
|
461
463
|
|
|
464
|
+
// ── Acting for someone else (team chats on this gateway) ──────────
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Who another person's agent belongs to, as this gateway's owner-side grant to that person: the
|
|
468
|
+
* active share where they asked for this gateway's agents, matched by their gateway (else email).
|
|
469
|
+
* Returns { shareId, grant } or null when this gateway shares nothing with them.
|
|
470
|
+
*/
|
|
471
|
+
_grantToOwnerOf(remoteAgentId) {
|
|
472
|
+
const id = SharingManager.parseRemoteId(remoteAgentId);
|
|
473
|
+
const theirs = id && this._shares.find(s => s.id === id.shareId && s.as === 'requester');
|
|
474
|
+
if (!theirs) return null;
|
|
475
|
+
const gw = theirs.owner?.gatewayId, email = String(theirs.owner?.email || '').toLowerCase();
|
|
476
|
+
const candidates = this._shares.filter(s => s.as === 'owner' && s.status === 'active');
|
|
477
|
+
const mine = candidates.find(s => gw && s.requester?.gatewayId === gw)
|
|
478
|
+
|| candidates.find(s => email && String(s.requester?.email || '').toLowerCase() === email);
|
|
479
|
+
const g = mine && this._grant(mine.id);
|
|
480
|
+
return g ? { shareId: mine.id, grant: g.grant } : null;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** The name to show for whom a local agent acts ("Kamil"), or null. */
|
|
484
|
+
actingForName(remoteAgentId) {
|
|
485
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
486
|
+
return g ? (firstName({ name: g.grant.requesterName }) || 'Someone') : null;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Run one of this gateway's agents because another person's agent asked (a team chat here):
|
|
491
|
+
* authority comes from who asked (specs/sharing-people.md), so it runs as the version shared with
|
|
492
|
+
* that person (its guest copy, normally) under their grant: access level, daily cap, its own
|
|
493
|
+
* session in "Shared with <name>". Returns null when that agent isn't shared with them.
|
|
494
|
+
*/
|
|
495
|
+
async localTurnFor(localAgentId, remoteAgentId, { turnId, roomId, roomTitle, message }, { onDelta } = {}) {
|
|
496
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
497
|
+
if (!g) return null;
|
|
498
|
+
const agents = (await this.request('agents.list', {}))?.agents || [];
|
|
499
|
+
const guestId = findGuestAgent(agents, localAgentId)?.id;
|
|
500
|
+
const shared = g.grant.agents.find(a => a.id === guestId) || g.grant.agents.find(a => a.id === localAgentId);
|
|
501
|
+
if (!shared) return null;
|
|
502
|
+
return this._guestTurn(g.shareId, { turnId, agentId: shared.id, roomId, roomTitle, message, inOwnerRoom: true },
|
|
503
|
+
(event, data) => { if (event === 'delta' && typeof data === 'string') onDelta?.(data); });
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async abortLocalFor(localAgentId, remoteAgentId, turnId) {
|
|
507
|
+
const g = this._grantToOwnerOf(remoteAgentId);
|
|
508
|
+
if (g) await this._guestAbort(g.shareId, turnId);
|
|
509
|
+
}
|
|
510
|
+
|
|
462
511
|
async abort(agentId, turnId) {
|
|
463
512
|
const id = SharingManager.parseRemoteId(agentId);
|
|
464
513
|
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,14 +7,18 @@
|
|
|
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)
|
|
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)
|
|
11
13
|
|
|
12
|
-
const DISCUSS_ROUNDS = 3;
|
|
14
|
+
const DISCUSS_ROUNDS = 3; // default; each room can set 1..MAX_ROUNDS
|
|
15
|
+
const MAX_ROUNDS = 10;
|
|
13
16
|
|
|
14
17
|
function roomRow(r, members) {
|
|
15
18
|
return {
|
|
16
19
|
roomKey: r.room_key,
|
|
17
20
|
discuss: !!r.discuss,
|
|
21
|
+
rounds: r.rounds || DISCUSS_ROUNDS,
|
|
18
22
|
sourceKey: r.source_key || null,
|
|
19
23
|
createdAt: r.created_at,
|
|
20
24
|
members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0 })),
|
|
@@ -31,6 +35,8 @@ export function createTeamStore(getGlobalDb) {
|
|
|
31
35
|
g.exec(`CREATE INDEX IF NOT EXISTS team_members_work ON team_members (work_key)`);
|
|
32
36
|
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
37
|
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
|
+
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
|
+
if (!g.prepare('PRAGMA table_info(team_rooms)').all().some(c => c.name === 'rounds')) g.exec('ALTER TABLE team_rooms ADD COLUMN rounds INTEGER');
|
|
34
40
|
ready = true;
|
|
35
41
|
}
|
|
36
42
|
return g;
|
|
@@ -39,6 +45,7 @@ export function createTeamStore(getGlobalDb) {
|
|
|
39
45
|
|
|
40
46
|
return {
|
|
41
47
|
DISCUSS_ROUNDS,
|
|
48
|
+
MAX_ROUNDS,
|
|
42
49
|
|
|
43
50
|
getRoom(roomKey) {
|
|
44
51
|
const r = db().prepare('SELECT * FROM team_rooms WHERE room_key = ?').get(roomKey);
|
|
@@ -87,6 +94,10 @@ export function createTeamStore(getGlobalDb) {
|
|
|
87
94
|
db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
|
|
88
95
|
},
|
|
89
96
|
|
|
97
|
+
setRounds(roomKey, rounds) {
|
|
98
|
+
db().prepare('UPDATE team_rooms SET rounds = ?, updated_at = ? WHERE room_key = ?').run(rounds, Date.now(), roomKey);
|
|
99
|
+
},
|
|
100
|
+
|
|
90
101
|
/** Drops the room; returns the working session keys it had. */
|
|
91
102
|
deleteRoom(roomKey) {
|
|
92
103
|
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);
|
|
@@ -108,16 +119,16 @@ export function createTeamStore(getGlobalDb) {
|
|
|
108
119
|
return new Set(db().prepare('SELECT work_key FROM team_members WHERE work_key IS NOT NULL').all().map(r => r.work_key));
|
|
109
120
|
},
|
|
110
121
|
|
|
111
|
-
recordEntry(roomKey, messageId, { type, agentId = null }) {
|
|
112
|
-
db().prepare('INSERT OR REPLACE INTO team_entries (room_key, message_id, author_type, agent_id, created_at) VALUES (?, ?, ?, ?, ?)')
|
|
113
|
-
.run(roomKey, messageId, type === 'user' ? 'user' : 'agent', agentId, Date.now());
|
|
122
|
+
recordEntry(roomKey, messageId, { type, agentId = null, actingFor = null }) {
|
|
123
|
+
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, type === 'user' ? 'user' : 'agent', agentId, Date.now(), actingFor);
|
|
114
125
|
},
|
|
115
126
|
|
|
116
|
-
/** { [messageId]: { type: 'user'|'agent', agentId } } */
|
|
127
|
+
/** { [messageId]: { type: 'user'|'agent', agentId, actingFor? } } */
|
|
117
128
|
authors(roomKey) {
|
|
118
129
|
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] = { type: r.author_type, agentId: r.agent_id };
|
|
130
|
+
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] = { type: r.author_type, agentId: r.agent_id, ...(r.acting_for ? { actingFor: r.acting_for } : {}) };
|
|
121
132
|
}
|
|
122
133
|
return out;
|
|
123
134
|
},
|
package/server/team.js
CHANGED
|
@@ -183,6 +183,7 @@ export class TeamCoordinator {
|
|
|
183
183
|
return {
|
|
184
184
|
roomKey: r.roomKey,
|
|
185
185
|
discuss: r.discuss,
|
|
186
|
+
rounds: r.rounds,
|
|
186
187
|
sourceKey: r.sourceKey,
|
|
187
188
|
createdAt: r.createdAt,
|
|
188
189
|
agents: r.members.map(m => {
|
|
@@ -287,6 +288,16 @@ export class TeamCoordinator {
|
|
|
287
288
|
return this.room(roomKey);
|
|
288
289
|
}
|
|
289
290
|
|
|
291
|
+
/** Host setting: follow-up rounds per human message when agents discuss (1..MAX_ROUNDS). */
|
|
292
|
+
setRounds(roomKey, rounds) {
|
|
293
|
+
if (!this.store.getRoom(roomKey)) return null;
|
|
294
|
+
const n = Math.floor(Number(rounds));
|
|
295
|
+
if (!(n >= 1 && n <= this.store.MAX_ROUNDS)) throw new Error(`rounds must be 1..${this.store.MAX_ROUNDS}`);
|
|
296
|
+
this.store.setRounds(roomKey, n);
|
|
297
|
+
this._changed();
|
|
298
|
+
return this.room(roomKey);
|
|
299
|
+
}
|
|
300
|
+
|
|
290
301
|
// ── Messages ───────────────────────────────────────────────────────
|
|
291
302
|
|
|
292
303
|
/** Post a user message; agents run in the background. Resolves once the message is in the room. */
|
|
@@ -321,9 +332,11 @@ export class TeamCoordinator {
|
|
|
321
332
|
const live = this._rooms.get(roomKey);
|
|
322
333
|
if (!live) return;
|
|
323
334
|
live.gen++;
|
|
324
|
-
await Promise.all([...live.running.entries()].map(([agentId, r]) => r.
|
|
325
|
-
? this.remote?.
|
|
326
|
-
:
|
|
335
|
+
await Promise.all([...live.running.entries()].map(([agentId, r]) => (r.actingFor
|
|
336
|
+
? this.remote?.abortLocalFor(agentId, r.actingFor, r.runId).catch(e => this.log.warn?.(`[team] abort: ${e.message}`))
|
|
337
|
+
: r.remote
|
|
338
|
+
? this.remote?.abort(agentId, r.runId).catch(e => this.log.warn?.(`[team] remote abort: ${e.message}`))
|
|
339
|
+
: this.request('chat.abort', { sessionKey: r.workKey, runId: r.runId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`)))));
|
|
327
340
|
this._status(roomKey);
|
|
328
341
|
}
|
|
329
342
|
|
|
@@ -337,15 +350,20 @@ export class TeamCoordinator {
|
|
|
337
350
|
else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
|
|
338
351
|
else { targets = agents.map(a => a.agentId); mode = 'open'; }
|
|
339
352
|
|
|
340
|
-
const maxRounds = room.discuss ?
|
|
341
|
-
const maxTurns = room.discuss ? agents.length * 2 : agents.length;
|
|
353
|
+
const maxRounds = room.discuss ? room.rounds : 1;
|
|
354
|
+
const maxTurns = room.discuss ? agents.length * Math.max(2, room.rounds - 1) : agents.length;
|
|
342
355
|
let turns = 0;
|
|
356
|
+
// Authority comes from who asked (specs/sharing-people.md): the first round answers the owner,
|
|
357
|
+
// so this gateway's agents run as themselves. A follow-up answers the previous round's replies:
|
|
358
|
+
// if one came from another person's agent (or from an agent acting for them), this gateway's
|
|
359
|
+
// agents act for that person, as the version shared with them; never as themselves.
|
|
360
|
+
let actingFor = new Map(); // agentId -> remote agent id whose owner it answers this round
|
|
343
361
|
for (let round = 1; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
|
|
344
362
|
targets = targets.slice(0, maxTurns - turns);
|
|
345
363
|
turns += targets.length;
|
|
346
364
|
const history = await this._roomEntries(roomKey);
|
|
347
365
|
const results = await Promise.all(targets.map(agentId =>
|
|
348
|
-
this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped)
|
|
366
|
+
this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped, actingFor.get(agentId) || null)
|
|
349
367
|
.catch(async e => {
|
|
350
368
|
// Shown in the room, like a failed turn in a normal chat, not only as a passing toast.
|
|
351
369
|
this.log.warn?.(`[team] ${agentId} in ${roomKey}: ${e.message}`);
|
|
@@ -360,11 +378,17 @@ export class TeamCoordinator {
|
|
|
360
378
|
const eligible = new Set(replied.map(r => r.agentId));
|
|
361
379
|
for (const r of replied) for (const id of namedIn(r.text, agents)) if (id !== r.agentId) eligible.add(id);
|
|
362
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
|
+
}
|
|
363
387
|
}
|
|
364
388
|
}
|
|
365
389
|
|
|
366
390
|
/** One agent turn. Returns { agentId, text } (text null when silent/aborted). */
|
|
367
|
-
async _turn(roomKey, agentId, agents, history, mode, stopped = () => false) {
|
|
391
|
+
async _turn(roomKey, agentId, agents, history, mode, stopped = () => false, actingFor = null) {
|
|
368
392
|
const room = this.store.getRoom(roomKey);
|
|
369
393
|
const member = room?.members.find(m => m.agentId === agentId);
|
|
370
394
|
if (!member) return null;
|
|
@@ -375,6 +399,7 @@ export class TeamCoordinator {
|
|
|
375
399
|
if (!fresh.length) return null;
|
|
376
400
|
|
|
377
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);
|
|
378
403
|
const workKey = member.workKey || await this._createWorkSession(roomKey, self);
|
|
379
404
|
const message = this._prompt(self, agents, fresh, mode);
|
|
380
405
|
const runId = `team-${crypto.randomUUID()}`;
|
|
@@ -447,7 +472,50 @@ export class TeamCoordinator {
|
|
|
447
472
|
}
|
|
448
473
|
if (!text || SILENT.test(text)) return { agentId, text: null };
|
|
449
474
|
await this._post(roomKey, self, text);
|
|
450
|
-
return { agentId, text: stopped() ? null : text };
|
|
475
|
+
return { agentId, text: stopped() ? null : text, authority: agentId }; // what it says carries its owner's authority
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* One of this gateway's agents answering another person's agent: runs as the version shared with
|
|
480
|
+
* that person, under their grant (peer/sharing.js localTurnFor), streamed like a remote agent.
|
|
481
|
+
* Not shared with them: it stays out, saying so when their agent asked it by name.
|
|
482
|
+
*/
|
|
483
|
+
async _turnFor(roomKey, self, fresh, agents, mode, stopped, actingFor, history) {
|
|
484
|
+
const agentId = self.agentId;
|
|
485
|
+
const asker = agents.find(a => a.agentId === actingFor);
|
|
486
|
+
const forName = this.remote?.actingForName?.(actingFor) || asker?.ownerName || 'someone else';
|
|
487
|
+
const runId = `team-${crypto.randomUUID()}`;
|
|
488
|
+
const live = this._live(roomKey);
|
|
489
|
+
const delta = (text, done = false) => this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-remote-delta', roomKey, agentId, runId, text, ...(done ? { done: true } : {}) }));
|
|
490
|
+
live.running.set(agentId, { actingFor, runId });
|
|
491
|
+
this._status(roomKey);
|
|
492
|
+
let result, partial = '';
|
|
493
|
+
try {
|
|
494
|
+
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) },
|
|
496
|
+
{ onDelta: text => { partial = text; delta(text); } });
|
|
497
|
+
} catch (e) {
|
|
498
|
+
throw Object.assign(e, { partial: (e.partial || partial || '').trim() });
|
|
499
|
+
} finally {
|
|
500
|
+
live.running.delete(agentId);
|
|
501
|
+
delta('', true);
|
|
502
|
+
this._status(roomKey);
|
|
503
|
+
}
|
|
504
|
+
if (!result) {
|
|
505
|
+
const authors = this.store.authors(roomKey);
|
|
506
|
+
const askedByName = history.some(e => authors[e.id]?.agentId === actingFor && e.ts >= Math.min(...fresh.map(f => f.ts))
|
|
507
|
+
&& parseMentions(splitLabel(e.text).body, agents).agentIds?.includes(agentId));
|
|
508
|
+
if (askedByName) await this._post(roomKey, self, `*${self.name} isn't shared with ${forName}, so it doesn't answer ${forName}'s agents.*`);
|
|
509
|
+
return { agentId, text: null };
|
|
510
|
+
}
|
|
511
|
+
const text = String(result.text || '').trim();
|
|
512
|
+
if (result.state === 'aborted') {
|
|
513
|
+
if (text && !SILENT.test(text)) await this._post(roomKey, self, `${text}\n\n*[stopped]*`, { actingFor: forName });
|
|
514
|
+
return { agentId, text: null };
|
|
515
|
+
}
|
|
516
|
+
if (!text || SILENT.test(text)) return { agentId, text: null };
|
|
517
|
+
await this._post(roomKey, self, text, { actingFor: forName });
|
|
518
|
+
return { agentId, text: stopped() ? null : text, authority: actingFor };
|
|
451
519
|
}
|
|
452
520
|
|
|
453
521
|
async _roomTitle(roomKey) {
|
|
@@ -476,10 +544,10 @@ export class TeamCoordinator {
|
|
|
476
544
|
setTimeout(check, intervalMs).unref?.();
|
|
477
545
|
}
|
|
478
546
|
|
|
479
|
-
/** Post an agent's message into the room. */
|
|
480
|
-
async _post(roomKey, self, text) {
|
|
547
|
+
/** Post an agent's message into the room (actingFor: whose request it answered, if not its owner's). */
|
|
548
|
+
async _post(roomKey, self, text, { actingFor = null } = {}) {
|
|
481
549
|
const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label: self.name.slice(0, 100) });
|
|
482
|
-
if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId });
|
|
550
|
+
if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId, actingFor });
|
|
483
551
|
}
|
|
484
552
|
|
|
485
553
|
_prompt(self, agents, fresh, mode) {
|
package/server/team.test.js
CHANGED
|
@@ -403,3 +403,67 @@ test('stop: recovery that finds nothing leaves the marker only when asked for',
|
|
|
403
403
|
await new Promise(r => setTimeout(r, 20));
|
|
404
404
|
assert.deepEqual(h.room(roomKey), ['[Dev]\n\n*[stopped before replying]*']);
|
|
405
405
|
});
|
|
406
|
+
|
|
407
|
+
test("authority comes from who asked: an agent answering someone else's agent runs as the version shared with them", async () => {
|
|
408
|
+
const forCalls = [];
|
|
409
|
+
let shared = true;
|
|
410
|
+
const remote = {
|
|
411
|
+
remoteAgents: () => [{ agentId: 'peer:sh1:jarvis', name: 'Jarvis · Kamil', ownerName: 'Kamil' }],
|
|
412
|
+
turn: async () => ({ state: 'final', text: 'good question, @dev how did you fix it?' }),
|
|
413
|
+
abort: async () => {},
|
|
414
|
+
actingForName: () => (shared ? 'Kamil' : null),
|
|
415
|
+
localTurnFor: async (localId, remoteId, args, { onDelta }) => {
|
|
416
|
+
forCalls.push({ localId, remoteId, args });
|
|
417
|
+
if (!shared) return null;
|
|
418
|
+
onDelta('lim');
|
|
419
|
+
return { state: 'final', text: 'restarted the gateway' };
|
|
420
|
+
},
|
|
421
|
+
};
|
|
422
|
+
const h = harness(agent => `${agent} full answer`, { remote });
|
|
423
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'peer:sh1:jarvis'] });
|
|
424
|
+
h.team.setDiscuss(roomKey, true);
|
|
425
|
+
const devSends = () => h.calls.filter(c => c.method === 'chat.send' && c.params.sessionKey.startsWith('agent:dev:')).length;
|
|
426
|
+
|
|
427
|
+
// The owner asks dev directly: dev runs as itself.
|
|
428
|
+
await h.team.send(roomKey, { text: '@dev status?', userLabel: 'H' });
|
|
429
|
+
await h.settle();
|
|
430
|
+
assert.equal(devSends(), 1);
|
|
431
|
+
|
|
432
|
+
// Kamil's agent asks dev: dev runs for Kamil (sharing's localTurnFor), never as itself.
|
|
433
|
+
await h.team.send(roomKey, { text: '@Jarvis-Kamil seen this crash?', userLabel: 'H' });
|
|
434
|
+
await h.settle();
|
|
435
|
+
assert.equal(devSends(), 1, 'no full-strength run for a request from someone else\'s agent');
|
|
436
|
+
assert.equal(forCalls.length, 1);
|
|
437
|
+
assert.deepEqual([forCalls[0].localId, forCalls[0].remoteId, forCalls[0].args.roomId], ['dev', 'peer:sh1:jarvis', roomKey]);
|
|
438
|
+
assert.ok(h.room(roomKey).includes('[Dev]\n\nrestarted the gateway'));
|
|
439
|
+
const authors = h.team.room(roomKey).authors;
|
|
440
|
+
const entry = Object.values(authors).find(a => a.agentId === 'dev' && a.actingFor);
|
|
441
|
+
assert.equal(entry?.actingFor, 'Kamil');
|
|
442
|
+
assert.ok(h.events.some(e => e.event === 'team-remote-delta' && e.agentId === 'dev' && e.text === 'lim'));
|
|
443
|
+
|
|
444
|
+
// Not shared with Kamil: dev stays out, and says so because Jarvis asked it by name.
|
|
445
|
+
shared = false;
|
|
446
|
+
await h.team.send(roomKey, { text: '@Jarvis-Kamil again?', userLabel: 'H' });
|
|
447
|
+
await h.settle();
|
|
448
|
+
assert.equal(devSends(), 1);
|
|
449
|
+
assert.match(h.room(roomKey).at(-1), /^\[Dev\]\n\n\*Dev isn't shared with Kamil, so it doesn't answer Kamil's agents\.\*$/);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
test('rounds: a per-room host setting, validated', async () => {
|
|
453
|
+
let n = 0;
|
|
454
|
+
const h = harness(agent => `@${agent === 'dev' ? 'Atlas' : 'Dev'} reply ${++n}`);
|
|
455
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
456
|
+
h.team.setDiscuss(roomKey, true);
|
|
457
|
+
assert.equal(h.team.room(roomKey).rounds, 3);
|
|
458
|
+
assert.throws(() => h.team.setRounds(roomKey, 0), /rounds must be/);
|
|
459
|
+
assert.throws(() => h.team.setRounds(roomKey, 11), /rounds must be/);
|
|
460
|
+
h.team.setRounds(roomKey, 1);
|
|
461
|
+
assert.equal(h.team.room(roomKey).rounds, 1);
|
|
462
|
+
await h.team.send(roomKey, { text: '@all go', userLabel: 'H' });
|
|
463
|
+
await h.settle();
|
|
464
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2, 'one round: each agent once');
|
|
465
|
+
h.team.setRounds(roomKey, 5);
|
|
466
|
+
await h.team.send(roomKey, { text: '@all again', userLabel: 'H' });
|
|
467
|
+
await h.settle();
|
|
468
|
+
assert.ok(h.calls.filter(c => c.method === 'chat.send').length > 4, 'more rounds when allowed');
|
|
469
|
+
});
|