@clawchatsai/connector 0.1.26 → 0.1.27
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/controllers/title.js +21 -5
- package/server/gateway.js +3 -0
- package/server/index.js +53 -2
- package/server/session-lens.js +12 -5
- package/server/store/team-store.js +125 -0
- package/server/team.js +518 -0
- package/server/team.test.js +297 -0
package/package.json
CHANGED
|
@@ -19,12 +19,12 @@ export function normalizeTitle(raw) {
|
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
+
* Direct completion where the main model's provider has a direct transport; CLI and harness
|
|
23
|
+
* runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
|
|
22
24
|
* @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
|
|
23
25
|
*/
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
// runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
|
|
27
|
-
async function complete(message) {
|
|
26
|
+
function createCompletion(llm) {
|
|
27
|
+
return async function complete(message) {
|
|
28
28
|
const base = { messages: [{ role: 'user', content: message }], systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 };
|
|
29
29
|
try {
|
|
30
30
|
return await llm.complete(base);
|
|
@@ -32,7 +32,23 @@ export function createTitleHandler(llm) {
|
|
|
32
32
|
if (err?.code === 'LLM_COMPLETION_NOT_AUTHORIZED') throw err;
|
|
33
33
|
return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
|
|
34
34
|
}
|
|
35
|
-
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** message → title or null (null also when the host has no plugin model completion). */
|
|
39
|
+
export function createTitler(llm) {
|
|
40
|
+
const complete = createCompletion(llm);
|
|
41
|
+
return async message => {
|
|
42
|
+
if (typeof llm?.complete !== 'function' || typeof message !== 'string' || !message.trim()) return null;
|
|
43
|
+
return normalizeTitle((await complete(Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join('')))?.text);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
|
|
49
|
+
*/
|
|
50
|
+
export function createTitleHandler(llm) {
|
|
51
|
+
const complete = createCompletion(llm);
|
|
36
52
|
|
|
37
53
|
return async function handleTitle(req, res) {
|
|
38
54
|
if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
|
package/server/gateway.js
CHANGED
|
@@ -91,6 +91,9 @@ export class GatewayClient {
|
|
|
91
91
|
return;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
// Connector-side observers (team chat run tracking) see every event before the lens filters.
|
|
95
|
+
if (msg.type === 'event' && this.onEvent) { try { this.onEvent(msg); } catch (e) { console.error('[gateway] event observer:', e.message); } }
|
|
96
|
+
|
|
94
97
|
if (msg.type === 'event' && msg.event === 'connect.challenge') {
|
|
95
98
|
this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
|
|
96
99
|
return;
|
package/server/index.js
CHANGED
|
@@ -13,11 +13,13 @@ import { handleTranscribe } from './controllers/transcribe.js';
|
|
|
13
13
|
import { createGatewayMediaHandler } from './controllers/gateway-media.js';
|
|
14
14
|
import { handleStatic } from './controllers/static.js';
|
|
15
15
|
import { handleAgents } from './controllers/agents.js';
|
|
16
|
-
import { createTitleHandler } from './controllers/title.js';
|
|
16
|
+
import { createTitleHandler, createTitler } from './controllers/title.js';
|
|
17
17
|
import { createSettingsHandlers } from './controllers/settings.js';
|
|
18
18
|
import { createWorkspaceStore } from './store/workspace-store.js';
|
|
19
19
|
import { createExtrasStore } from './store/extras-store.js';
|
|
20
|
+
import { createTeamStore } from './store/team-store.js';
|
|
20
21
|
import { SessionLens } from './session-lens.js';
|
|
22
|
+
import { TeamCoordinator } from './team.js';
|
|
21
23
|
import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
|
|
22
24
|
|
|
23
25
|
// PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
|
|
@@ -70,7 +72,11 @@ export function createApp(config = {}) {
|
|
|
70
72
|
const extras = createExtrasStore(() => globalDbCache.get());
|
|
71
73
|
try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
|
|
72
74
|
catch (e) { console.error('[extras] style seed failed:', e.message); }
|
|
73
|
-
|
|
75
|
+
const gwRequest = (m, p, t) => gatewayClient.request(m, p, t);
|
|
76
|
+
// Team chats: several agents in one thread (server/team.js).
|
|
77
|
+
const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm) });
|
|
78
|
+
gatewayClient.onEvent = msg => team.onGatewayEvent(msg);
|
|
79
|
+
gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
|
|
74
80
|
|
|
75
81
|
// A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
|
|
76
82
|
// spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
|
|
@@ -216,6 +222,50 @@ export function createApp(config = {}) {
|
|
|
216
222
|
return send(res, 200, { ok: true });
|
|
217
223
|
}
|
|
218
224
|
|
|
225
|
+
// Team chats (server/team.js; EXTRAS.md). Room keys contain ':' and are URL-encoded.
|
|
226
|
+
if (method === 'GET' && urlPath === '/api/team') return send(res, 200, { rooms: team.rooms() });
|
|
227
|
+
if (method === 'POST' && urlPath === '/api/team') {
|
|
228
|
+
const body = await parseBody(req);
|
|
229
|
+
try { return send(res, 200, { room: await team.createRoom(body) }); }
|
|
230
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
231
|
+
}
|
|
232
|
+
if ((p = matchRoute(method, urlPath, 'GET /api/team/:room'))) {
|
|
233
|
+
const room = team.room(p.room);
|
|
234
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
235
|
+
}
|
|
236
|
+
if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
|
|
237
|
+
const room = team.setDiscuss(p.room, (await parseBody(req)).discuss);
|
|
238
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
239
|
+
}
|
|
240
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
|
|
241
|
+
const { agentId } = await parseBody(req);
|
|
242
|
+
if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
|
|
243
|
+
try {
|
|
244
|
+
const room = await team.addAgent(p.room, agentId);
|
|
245
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
246
|
+
} catch (e) { return sendError(res, 400, e.message); }
|
|
247
|
+
}
|
|
248
|
+
if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
|
|
249
|
+
try {
|
|
250
|
+
const room = team.removeAgent(p.room, p.agentId);
|
|
251
|
+
return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
|
|
252
|
+
} catch (e) { return sendError(res, 400, e.message); }
|
|
253
|
+
}
|
|
254
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/send'))) {
|
|
255
|
+
try { return send(res, 200, await team.send(p.room, await parseBody(req))); }
|
|
256
|
+
catch (e) { return sendError(res, 400, e.message); }
|
|
257
|
+
}
|
|
258
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/unconvert'))) {
|
|
259
|
+
try {
|
|
260
|
+
const sourceKey = await team.unconvert(p.room);
|
|
261
|
+
return sourceKey ? send(res, 200, { sourceKey }) : sendError(res, 404, 'Not a team chat');
|
|
262
|
+
} catch (e) { return sendError(res, 400, e.message); }
|
|
263
|
+
}
|
|
264
|
+
if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/stop'))) {
|
|
265
|
+
await team.stop(p.room);
|
|
266
|
+
return send(res, 200, { ok: true });
|
|
267
|
+
}
|
|
268
|
+
|
|
219
269
|
|
|
220
270
|
sendError(res, 404, `Not found: ${method} ${urlPath}`);
|
|
221
271
|
} catch (err) {
|
|
@@ -269,6 +319,7 @@ export function createApp(config = {}) {
|
|
|
269
319
|
shutdown: closeAll,
|
|
270
320
|
gatewayClient,
|
|
271
321
|
extras,
|
|
322
|
+
team,
|
|
272
323
|
setupBrowserWs,
|
|
273
324
|
debugLogger,
|
|
274
325
|
dataDir: DATA_DIR,
|
package/server/session-lens.js
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
//
|
|
15
15
|
// Visible = a root, direct, user chat: `agent:<id>:dashboard:<id>` (gateway-created) or
|
|
16
16
|
// `agent:<id>:<project>:chat:<id>` (legacy ClawChats). Everything else is hidden.
|
|
17
|
+
// Team chat working sessions (server/team.js) are hidden too, but their run events are
|
|
18
|
+
// forwarded: the room shows each agent's reply streaming.
|
|
17
19
|
|
|
18
20
|
const DASHBOARD_KEY = /^agent:[^:]+:dashboard:[^:]+$/;
|
|
19
21
|
const LEGACY_CHAT_KEY = /^agent:[^:]+:[^:]+:chat:[^:]+$/;
|
|
@@ -116,11 +118,13 @@ export class SessionLens {
|
|
|
116
118
|
* @param {(data: string) => void} opts.broadcast send a frame to all browsers
|
|
117
119
|
* @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} [opts.request] connector-originated gateway RPC
|
|
118
120
|
* @param {object} [opts.extras] ExtrasStore (project style side effects)
|
|
121
|
+
* @param {object} [opts.team] TeamCoordinator (`isWorkKey`, `onSessionDeleted`)
|
|
119
122
|
*/
|
|
120
|
-
constructor({ broadcast, request, extras, logger = console }) {
|
|
123
|
+
constructor({ broadcast, request, extras, team, logger = console }) {
|
|
121
124
|
this.broadcast = broadcast;
|
|
122
125
|
this.request = request;
|
|
123
126
|
this.extras = extras;
|
|
127
|
+
this.team = team;
|
|
124
128
|
this.log = logger;
|
|
125
129
|
this.hidden = new Set(); // candidate-shaped keys a row revealed as not a user chat
|
|
126
130
|
this.pending = new Map(); // browser req id -> { method, params }
|
|
@@ -137,16 +141,16 @@ export class SessionLens {
|
|
|
137
141
|
const verdict = rowVerdict(row);
|
|
138
142
|
if (verdict === true) this.hidden.add(key);
|
|
139
143
|
else if (verdict === false) this.hidden.delete(key);
|
|
140
|
-
return
|
|
144
|
+
return this.isVisible(key);
|
|
141
145
|
}
|
|
142
146
|
|
|
143
147
|
isVisible(key) {
|
|
144
|
-
return isCandidateKey(key) && !this.hidden.has(key);
|
|
148
|
+
return isCandidateKey(key) && !this.hidden.has(key) && !this.team?.isWorkKey(key);
|
|
145
149
|
}
|
|
146
150
|
|
|
147
|
-
/** chat/agent run events: visible chats
|
|
151
|
+
/** chat/agent run events: visible chats, team chat working sessions, utility sessions. */
|
|
148
152
|
forwardsRunEvent(key) {
|
|
149
|
-
return isUtilityKey(key) || this.isVisible(key);
|
|
153
|
+
return isUtilityKey(key) || this.isVisible(key) || !!this.team?.isWorkKey(key);
|
|
150
154
|
}
|
|
151
155
|
|
|
152
156
|
/** Seed `hidden` from a full roster so partial events of child sessions stay hidden. */
|
|
@@ -169,6 +173,9 @@ export class SessionLens {
|
|
|
169
173
|
if (!payload || typeof payload !== 'object') return null;
|
|
170
174
|
const key = payload.sessionKey;
|
|
171
175
|
if (!key) return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) }; // catalog/groups
|
|
176
|
+
if (payload.reason === 'delete' && this.team) {
|
|
177
|
+
try { this.team.onSessionDeleted(key); } catch (e) { this.log.warn?.(`[lens] team delete: ${e.message}`); }
|
|
178
|
+
}
|
|
172
179
|
if (!this.observe(key, payload.session || payload)) return null;
|
|
173
180
|
if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
|
|
174
181
|
return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// TeamStore: team chats (several agents in one ClawChats thread). Lives in the global DB.
|
|
2
|
+
// Registry entry: EXTRAS.md. Coordinator: server/team.js.
|
|
3
|
+
//
|
|
4
|
+
// team_rooms a room = a gateway session that never runs; its transcript is the shared timeline;
|
|
5
|
+
// source_key = the chat it was converted from (its history shows above the room)
|
|
6
|
+
// team_members one working session per agent per room (created on the agent's first turn);
|
|
7
|
+
// seen_at = timestamp of the newest room entry the agent has been given;
|
|
8
|
+
// removed = 1: agent taken out of the room; its session stays hidden and is reused
|
|
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
|
+
const DISCUSS_ROUNDS = 3;
|
|
13
|
+
|
|
14
|
+
function roomRow(r, members) {
|
|
15
|
+
return {
|
|
16
|
+
roomKey: r.room_key,
|
|
17
|
+
discuss: !!r.discuss,
|
|
18
|
+
sourceKey: r.source_key || null,
|
|
19
|
+
createdAt: r.created_at,
|
|
20
|
+
members: members.map(m => ({ agentId: m.agent_id, workKey: m.work_key || null, seenAt: m.seen_at || 0 })),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createTeamStore(getGlobalDb) {
|
|
25
|
+
let ready = false;
|
|
26
|
+
function db() {
|
|
27
|
+
const g = getGlobalDb();
|
|
28
|
+
if (!ready) {
|
|
29
|
+
g.exec(`CREATE TABLE IF NOT EXISTS team_rooms (room_key TEXT PRIMARY KEY, discuss INTEGER NOT NULL DEFAULT 0, source_key TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`);
|
|
30
|
+
g.exec(`CREATE TABLE IF NOT EXISTS team_members (room_key TEXT NOT NULL, agent_id TEXT NOT NULL, work_key TEXT, seen_at INTEGER NOT NULL DEFAULT 0, position INTEGER NOT NULL, PRIMARY KEY (room_key, agent_id))`);
|
|
31
|
+
g.exec(`CREATE INDEX IF NOT EXISTS team_members_work ON team_members (work_key)`);
|
|
32
|
+
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
|
+
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))`);
|
|
34
|
+
ready = true;
|
|
35
|
+
}
|
|
36
|
+
return g;
|
|
37
|
+
}
|
|
38
|
+
const members = roomKey => db().prepare('SELECT * FROM team_members WHERE room_key = ? AND removed = 0 ORDER BY position').all(roomKey);
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
DISCUSS_ROUNDS,
|
|
42
|
+
|
|
43
|
+
getRoom(roomKey) {
|
|
44
|
+
const r = db().prepare('SELECT * FROM team_rooms WHERE room_key = ?').get(roomKey);
|
|
45
|
+
return r ? roomRow(r, members(roomKey)) : null;
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
listRooms() {
|
|
49
|
+
return db().prepare('SELECT * FROM team_rooms ORDER BY created_at').all().map(r => roomRow(r, members(r.room_key)));
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
/** members: [{ agentId, workKey?, seenAt? }] in display order; sourceKey: the chat it was converted from. */
|
|
53
|
+
createRoom(roomKey, memberList, { discuss = false, sourceKey = null } = {}) {
|
|
54
|
+
const g = db();
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
g.exec('BEGIN');
|
|
57
|
+
try {
|
|
58
|
+
g.prepare('INSERT INTO team_rooms (room_key, discuss, source_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(roomKey, discuss ? 1 : 0, sourceKey, now, now);
|
|
59
|
+
memberList.forEach((m, i) => g.prepare('INSERT INTO team_members (room_key, agent_id, work_key, seen_at, position) VALUES (?, ?, ?, ?, ?)').run(roomKey, m.agentId, m.workKey || null, m.seenAt || 0, i));
|
|
60
|
+
g.exec('COMMIT');
|
|
61
|
+
} catch (e) { g.exec('ROLLBACK'); throw e; }
|
|
62
|
+
return this.getRoom(roomKey);
|
|
63
|
+
},
|
|
64
|
+
|
|
65
|
+
/** Adds an agent at the end (an agent removed earlier comes back with its session). Returns false if the room is unknown. */
|
|
66
|
+
addMember(roomKey, agentId) {
|
|
67
|
+
if (!this.getRoom(roomKey)) return false;
|
|
68
|
+
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, 0, ?) ON CONFLICT(room_key, agent_id) DO UPDATE SET removed = 0, position = excluded.position WHERE removed = 1').run(roomKey, agentId, pos);
|
|
70
|
+
return true;
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
/** Takes an agent out of the room; its working session stays hidden (reused if it's added back). */
|
|
74
|
+
removeMember(roomKey, agentId) {
|
|
75
|
+
db().prepare('UPDATE team_members SET removed = 1 WHERE room_key = ? AND agent_id = ?').run(roomKey, agentId);
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
setWorkKey(roomKey, agentId, workKey) {
|
|
79
|
+
db().prepare('UPDATE team_members SET work_key = ? WHERE room_key = ? AND agent_id = ?').run(workKey, roomKey, agentId);
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
setSeenAt(roomKey, agentId, seenAt) {
|
|
83
|
+
db().prepare('UPDATE team_members SET seen_at = MAX(seen_at, ?) WHERE room_key = ? AND agent_id = ?').run(seenAt, roomKey, agentId);
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
setDiscuss(roomKey, discuss) {
|
|
87
|
+
db().prepare('UPDATE team_rooms SET discuss = ?, updated_at = ? WHERE room_key = ?').run(discuss ? 1 : 0, Date.now(), roomKey);
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
/** Drops the room; returns the working session keys it had. */
|
|
91
|
+
deleteRoom(roomKey) {
|
|
92
|
+
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
|
+
const g = db();
|
|
94
|
+
g.prepare('DELETE FROM team_members WHERE room_key = ?').run(roomKey);
|
|
95
|
+
g.prepare('DELETE FROM team_entries WHERE room_key = ?').run(roomKey);
|
|
96
|
+
g.prepare('DELETE FROM team_rooms WHERE room_key = ?').run(roomKey);
|
|
97
|
+
return work;
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
/** { roomKey, agentId } of a working session, or null. */
|
|
101
|
+
workSession(workKey) {
|
|
102
|
+
const m = db().prepare('SELECT room_key, agent_id FROM team_members WHERE work_key = ? AND removed = 0').get(workKey);
|
|
103
|
+
return m ? { roomKey: m.room_key, agentId: m.agent_id } : null;
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
/** Set of every working session key (the lens hides these). */
|
|
107
|
+
workKeys() {
|
|
108
|
+
return new Set(db().prepare('SELECT work_key FROM team_members WHERE work_key IS NOT NULL').all().map(r => r.work_key));
|
|
109
|
+
},
|
|
110
|
+
|
|
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());
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
/** { [messageId]: { type: 'user'|'agent', agentId } } */
|
|
117
|
+
authors(roomKey) {
|
|
118
|
+
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 };
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
package/server/team.js
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
// TeamCoordinator: several agents in one ClawChats thread (a "team chat").
|
|
2
|
+
//
|
|
3
|
+
// The gateway has no multi-agent session, so a team chat is:
|
|
4
|
+
// - a room session: a normal gateway session that never runs. Its transcript is the shared
|
|
5
|
+
// timeline; every entry is written with `chat.inject` and a "[Label]" prefix (the gateway
|
|
6
|
+
// stores the label as that prefix). Authors are recorded in TeamStore.team_entries.
|
|
7
|
+
// - one working session per agent, where the agent actually runs. Each turn it gets the room
|
|
8
|
+
// entries it hasn't seen yet; its final reply is injected into the room.
|
|
9
|
+
//
|
|
10
|
+
// Routing follows the gateway's broadcast group threads (docs/channels/broadcast-groups.md):
|
|
11
|
+
// @mentioned agents answer; with no mention every agent gets the message but is told to answer
|
|
12
|
+
// NO_REPLY unless it's for them (ClawChats choice); `@all` makes everyone answer. Follow-up rounds
|
|
13
|
+
// (the room's "discuss" toggle) go to agents that replied or were named, with the siblings'
|
|
14
|
+
// replies, until everyone passes or the round/turn caps are hit. Round state is in memory only.
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto';
|
|
17
|
+
|
|
18
|
+
export const SILENT = /^\s*NO_REPLY\s*$/i;
|
|
19
|
+
const LABEL_PREFIX = /^\[([^\]\n]{1,100})\]\n\n/;
|
|
20
|
+
const TURN_TIMEOUT_MS = 15 * 60_000;
|
|
21
|
+
const HISTORY_LIMIT = 80;
|
|
22
|
+
const AGENTS_TTL_MS = 60_000;
|
|
23
|
+
const ALL_WORDS = new Set(['all', 'everyone']);
|
|
24
|
+
|
|
25
|
+
const norm = s => String(s || '').toLowerCase().replace(/\s+/g, '');
|
|
26
|
+
|
|
27
|
+
/** Text of a transcript/chat message (string content or text parts). */
|
|
28
|
+
export function messageText(message) {
|
|
29
|
+
const c = message?.content;
|
|
30
|
+
if (typeof c === 'string') return c;
|
|
31
|
+
if (Array.isArray(c)) return c.filter(p => p?.type === 'text' && typeof p.text === 'string').map(p => p.text).join('\n');
|
|
32
|
+
return typeof message?.text === 'string' ? message.text : '';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Transcript entry id: a `__`-prefixed metadata object with a string id (never named in code). */
|
|
36
|
+
export function entryId(message) {
|
|
37
|
+
for (const k of Object.keys(message || {})) {
|
|
38
|
+
if (k.startsWith('__') && message[k] && typeof message[k] === 'object' && typeof message[k].id === 'string') return message[k].id;
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** "[Label]\n\nbody" → { label, body }. */
|
|
44
|
+
export function splitLabel(text) {
|
|
45
|
+
const m = LABEL_PREFIX.exec(text || '');
|
|
46
|
+
return m ? { label: m[1], body: text.slice(m[0].length) } : { label: null, body: text || '' };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Who a message addresses. `agents`: [{ agentId, name }].
|
|
51
|
+
* Returns { all: true } for @all/@everyone, else { agentIds: [...] } (empty = nobody mentioned).
|
|
52
|
+
*/
|
|
53
|
+
export function parseMentions(text, agents) {
|
|
54
|
+
const ids = new Set();
|
|
55
|
+
const re = /(^|[^\w@])@([\w.-]+)/g;
|
|
56
|
+
let m;
|
|
57
|
+
while ((m = re.exec(text || ''))) {
|
|
58
|
+
const word = norm(m[2]).replace(/[.-]+$/, '');
|
|
59
|
+
if (ALL_WORDS.has(word)) return { all: true };
|
|
60
|
+
for (const a of agents) if (word === norm(a.agentId) || (a.name && word === norm(a.name))) ids.add(a.agentId);
|
|
61
|
+
}
|
|
62
|
+
return { agentIds: [...ids] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Agents a reply names, by @mention or as a whole word (for follow-up eligibility). */
|
|
66
|
+
export function namedIn(text, agents) {
|
|
67
|
+
const out = new Set(parseMentions(text, agents).agentIds || []);
|
|
68
|
+
const lower = (text || '').toLowerCase();
|
|
69
|
+
for (const a of agents) {
|
|
70
|
+
for (const n of [a.agentId, a.name]) {
|
|
71
|
+
if (!n || n.length < 2) continue;
|
|
72
|
+
const esc = n.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
73
|
+
if (new RegExp(`(^|[^\\w])${esc}([^\\w]|$)`).test(lower)) out.add(a.agentId);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return [...out];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class TeamCoordinator {
|
|
80
|
+
/**
|
|
81
|
+
* @param {object} opts
|
|
82
|
+
* @param {object} opts.store TeamStore
|
|
83
|
+
* @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} opts.request gateway RPC
|
|
84
|
+
* @param {(data: string) => void} opts.broadcast frame to all browsers
|
|
85
|
+
*/
|
|
86
|
+
constructor({ store, request, broadcast, titler = null, logger = console }) {
|
|
87
|
+
this.store = store;
|
|
88
|
+
this.request = request;
|
|
89
|
+
this.broadcast = broadcast;
|
|
90
|
+
this.titler = titler; // main-model title fallback (controllers/title.js createTitler)
|
|
91
|
+
this.log = logger;
|
|
92
|
+
this._workKeys = null; // cached Set of working session keys
|
|
93
|
+
this._waiters = new Map(); // runId -> { resolve, timer }
|
|
94
|
+
this._chains = new Map(); // roomKey -> tail promise (one message at a time per room)
|
|
95
|
+
this._rooms = new Map(); // roomKey -> { running: Map<agentId, {workKey, runId}>, queued, stopped }
|
|
96
|
+
this._agents = null; // { at, list }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── Lens hooks ─────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
isWorkKey(key) {
|
|
102
|
+
if (!this._workKeys) this._workKeys = this.store.workKeys();
|
|
103
|
+
return this._workKeys.has(key);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
_workKeysChanged() { this._workKeys = null; }
|
|
107
|
+
|
|
108
|
+
/** The gateway reported a session deleted. */
|
|
109
|
+
onSessionDeleted(key) {
|
|
110
|
+
if (this.store.getRoom(key)) { this._dissolve(key); return; }
|
|
111
|
+
const ws = this.store.workSession(key);
|
|
112
|
+
if (ws) { this.store.setWorkKey(ws.roomKey, ws.agentId, null); this._workKeysChanged(); }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Every gateway event (before the lens filters it). Resolves run waiters. */
|
|
116
|
+
onGatewayEvent(msg) {
|
|
117
|
+
if (msg?.event !== 'chat') return;
|
|
118
|
+
const p = msg.payload;
|
|
119
|
+
const w = p?.runId && this._waiters.get(p.runId);
|
|
120
|
+
if (!w) return; // includes the stray `error` that follows a silent final
|
|
121
|
+
if (p.state === 'delta') {
|
|
122
|
+
// Streamed text so far, kept for a Stop mid-reply: first delta carries the message, later
|
|
123
|
+
// ones the appended text (`replace`: the whole text).
|
|
124
|
+
if (p.message && !w.text) w.text = messageText(p.message);
|
|
125
|
+
else if (typeof p.deltaText === 'string') w.text = p.replace ? p.deltaText : (w.text || '') + p.deltaText;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!['final', 'aborted', 'error'].includes(p.state)) return;
|
|
129
|
+
this._waiters.delete(p.runId);
|
|
130
|
+
clearTimeout(w.timer);
|
|
131
|
+
w.resolve({ ...p, partialText: w.text || '' });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ── Agents ─────────────────────────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
async agents() {
|
|
137
|
+
if (this._agents && Date.now() - this._agents.at < AGENTS_TTL_MS) return this._agents.list;
|
|
138
|
+
const res = await this.request('agents.list', {});
|
|
139
|
+
const list = (res?.agents || []).map(a => ({ agentId: a.id, name: a.identity?.name || a.name || a.id }));
|
|
140
|
+
this._agents = { at: Date.now(), list };
|
|
141
|
+
return list;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async _named(agentIds) {
|
|
145
|
+
const all = await this.agents();
|
|
146
|
+
return agentIds.map(id => all.find(a => a.agentId === id) || { agentId: id, name: id });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ── Rooms ──────────────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
rooms() {
|
|
152
|
+
return this.store.listRooms().map(r => this._publicRoom(r));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
room(roomKey) {
|
|
156
|
+
const r = this.store.getRoom(roomKey);
|
|
157
|
+
return r ? { ...this._publicRoom(r), authors: this.store.authors(roomKey) } : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
_publicRoom(r) {
|
|
161
|
+
const live = this._rooms.get(r.roomKey);
|
|
162
|
+
return {
|
|
163
|
+
roomKey: r.roomKey,
|
|
164
|
+
discuss: r.discuss,
|
|
165
|
+
sourceKey: r.sourceKey,
|
|
166
|
+
createdAt: r.createdAt,
|
|
167
|
+
agents: r.members.map(m => ({ agentId: m.agentId, workKey: m.workKey })),
|
|
168
|
+
running: live ? [...live.running.keys()] : [],
|
|
169
|
+
queued: live?.queued || 0,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Create a team chat. With `sourceKey`, an existing chat becomes the first agent's working
|
|
175
|
+
* session (it keeps its memory) and is hidden from the thread list.
|
|
176
|
+
*/
|
|
177
|
+
async createRoom({ agentIds = [], sourceKey = null, category, label } = {}) {
|
|
178
|
+
const agents = [...new Set(agentIds.filter(a => typeof a === 'string' && a))];
|
|
179
|
+
const members = [];
|
|
180
|
+
if (sourceKey) {
|
|
181
|
+
const src = /^agent:([^:]+):/.exec(sourceKey)?.[1];
|
|
182
|
+
if (!src) throw new Error('invalid sourceKey');
|
|
183
|
+
if (this.isWorkKey(sourceKey) || this.store.getRoom(sourceKey)) throw new Error('chat is already part of a team chat');
|
|
184
|
+
members.push({ agentId: src, workKey: sourceKey, seenAt: Date.now() });
|
|
185
|
+
}
|
|
186
|
+
for (const a of agents) if (!members.some(m => m.agentId === a)) members.push({ agentId: a });
|
|
187
|
+
if (members.length < 2) throw new Error('a team chat needs at least two agents');
|
|
188
|
+
const known = new Set((await this.agents()).map(a => a.agentId));
|
|
189
|
+
const unknown = members.find(m => !known.has(m.agentId));
|
|
190
|
+
if (unknown) throw new Error(`unknown agent: ${unknown.agentId}`);
|
|
191
|
+
|
|
192
|
+
const roomKey = `agent:${members[0].agentId}:dashboard:${crypto.randomUUID()}`;
|
|
193
|
+
// Register first so the lens never shows a working session or forwards a half-made room.
|
|
194
|
+
this.store.createRoom(roomKey, members, { sourceKey });
|
|
195
|
+
this._workKeysChanged();
|
|
196
|
+
try {
|
|
197
|
+
await this.request('sessions.create', {
|
|
198
|
+
key: roomKey, agentId: members[0].agentId,
|
|
199
|
+
...(typeof category === 'string' && category ? { category } : {}),
|
|
200
|
+
...(typeof label === 'string' && label.trim() ? { label: label.trim().slice(0, 200) } : {}),
|
|
201
|
+
});
|
|
202
|
+
} catch (e) {
|
|
203
|
+
this.store.deleteRoom(roomKey);
|
|
204
|
+
this._workKeysChanged();
|
|
205
|
+
throw e;
|
|
206
|
+
}
|
|
207
|
+
this._changed();
|
|
208
|
+
return this.room(roomKey);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Turn a converted team chat back into the chat it came from: the room and the other agents'
|
|
213
|
+
* working sessions go, the original chat stays (with what its agent saw while it was a team).
|
|
214
|
+
* Returns the original chat's key.
|
|
215
|
+
*/
|
|
216
|
+
async unconvert(roomKey) {
|
|
217
|
+
const room = this.store.getRoom(roomKey);
|
|
218
|
+
if (!room) return null;
|
|
219
|
+
if (!room.sourceKey) throw new Error('this team chat was not converted from a chat');
|
|
220
|
+
this._dissolve(roomKey);
|
|
221
|
+
await this.request('sessions.delete', { key: roomKey }).catch(e => this.log.warn?.(`[team] delete room ${roomKey}: ${e.message}`));
|
|
222
|
+
return room.sourceKey;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Forget a room and delete its working sessions — except the chat it was converted from, which is
|
|
227
|
+
* the user's own chat and becomes a normal thread again (deleting the room must never delete it).
|
|
228
|
+
*/
|
|
229
|
+
_dissolve(roomKey) {
|
|
230
|
+
const source = this.store.getRoom(roomKey)?.sourceKey;
|
|
231
|
+
this.stop(roomKey);
|
|
232
|
+
const work = this.store.deleteRoom(roomKey).filter(w => w !== source);
|
|
233
|
+
this._workKeysChanged();
|
|
234
|
+
for (const w of work) this.request('sessions.delete', { key: w }).catch(e => this.log.warn?.(`[team] delete ${w}: ${e.message}`));
|
|
235
|
+
this._changed();
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async addAgent(roomKey, agentId) {
|
|
239
|
+
if (!(await this.agents()).some(a => a.agentId === agentId)) throw new Error(`unknown agent: ${agentId}`);
|
|
240
|
+
if (!this.store.addMember(roomKey, agentId)) return null;
|
|
241
|
+
this._changed();
|
|
242
|
+
return this.room(roomKey);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
removeAgent(roomKey, agentId) {
|
|
246
|
+
const r = this.store.getRoom(roomKey);
|
|
247
|
+
if (!r) return null;
|
|
248
|
+
if (r.members.length <= 2 && r.members.some(m => m.agentId === agentId)) throw new Error('a team chat needs at least two agents');
|
|
249
|
+
// The working session stays, hidden: it's the agent's memory of this room if it's added back.
|
|
250
|
+
this.store.removeMember(roomKey, agentId);
|
|
251
|
+
this._workKeysChanged();
|
|
252
|
+
this._changed();
|
|
253
|
+
return this.room(roomKey);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
setDiscuss(roomKey, discuss) {
|
|
257
|
+
if (!this.store.getRoom(roomKey)) return null;
|
|
258
|
+
this.store.setDiscuss(roomKey, !!discuss);
|
|
259
|
+
this._changed();
|
|
260
|
+
return this.room(roomKey);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── Messages ───────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
/** Post a user message; agents run in the background. Resolves once the message is in the room. */
|
|
266
|
+
async send(roomKey, { text, userLabel = 'User' } = {}) {
|
|
267
|
+
const room = this.store.getRoom(roomKey);
|
|
268
|
+
if (!room) throw new Error('not a team chat');
|
|
269
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('empty message');
|
|
270
|
+
const label = String(userLabel || 'User').replace(/[\[\]\n]/g, '').trim().slice(0, 100) || 'User';
|
|
271
|
+
const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label });
|
|
272
|
+
if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'user' });
|
|
273
|
+
this._maybeTitle(roomKey, text);
|
|
274
|
+
|
|
275
|
+
const live = this._live(roomKey);
|
|
276
|
+
const gen = live.gen; // Stop bumps the generation: everything queued before it is dropped
|
|
277
|
+
live.queued++;
|
|
278
|
+
this._status(roomKey);
|
|
279
|
+
const prev = this._chains.get(roomKey) || Promise.resolve();
|
|
280
|
+
const next = prev.then(async () => {
|
|
281
|
+
live.queued--;
|
|
282
|
+
if (live.gen !== gen) return;
|
|
283
|
+
await this._runMessage(roomKey, text, () => live.gen !== gen);
|
|
284
|
+
}).catch(e => {
|
|
285
|
+
this.log.error?.(`[team] ${roomKey}: ${e.message}`);
|
|
286
|
+
this._status(roomKey, e.message);
|
|
287
|
+
}).finally(() => { if (this._chains.get(roomKey) === next) this._chains.delete(roomKey); this._status(roomKey); });
|
|
288
|
+
this._chains.set(roomKey, next);
|
|
289
|
+
return { messageId: res?.messageId || null };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Abort running agents and drop queued messages. */
|
|
293
|
+
async stop(roomKey) {
|
|
294
|
+
const live = this._rooms.get(roomKey);
|
|
295
|
+
if (!live) return;
|
|
296
|
+
live.gen++;
|
|
297
|
+
await Promise.all([...live.running.values()].map(r =>
|
|
298
|
+
this.request('chat.abort', { sessionKey: r.workKey, runId: r.runId }).catch(e => this.log.warn?.(`[team] abort: ${e.message}`))));
|
|
299
|
+
this._status(roomKey);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async _runMessage(roomKey, text, stopped = () => false) {
|
|
303
|
+
const room = this.store.getRoom(roomKey);
|
|
304
|
+
if (!room) return;
|
|
305
|
+
const agents = await this._named(room.members.map(m => m.agentId));
|
|
306
|
+
const mention = parseMentions(text, agents);
|
|
307
|
+
let targets, mode;
|
|
308
|
+
if (mention.all) { targets = agents.map(a => a.agentId); mode = 'addressed'; }
|
|
309
|
+
else if (mention.agentIds.length) { targets = mention.agentIds; mode = 'addressed'; }
|
|
310
|
+
else { targets = agents.map(a => a.agentId); mode = 'open'; }
|
|
311
|
+
|
|
312
|
+
const maxRounds = room.discuss ? this.store.DISCUSS_ROUNDS : 1;
|
|
313
|
+
const maxTurns = room.discuss ? agents.length * 2 : agents.length;
|
|
314
|
+
let turns = 0;
|
|
315
|
+
for (let round = 1; round <= maxRounds && targets.length && turns < maxTurns && !stopped(); round++) {
|
|
316
|
+
targets = targets.slice(0, maxTurns - turns);
|
|
317
|
+
turns += targets.length;
|
|
318
|
+
const history = await this._roomEntries(roomKey);
|
|
319
|
+
const results = await Promise.all(targets.map(agentId =>
|
|
320
|
+
this._turn(roomKey, agentId, agents, history, round === 1 ? mode : 'followup', stopped)
|
|
321
|
+
.catch(async e => {
|
|
322
|
+
// Shown in the room, like a failed turn in a normal chat, not only as a passing toast.
|
|
323
|
+
this.log.warn?.(`[team] ${agentId} in ${roomKey}: ${e.message}`);
|
|
324
|
+
const self = agents.find(a => a.agentId === agentId) || { agentId, name: agentId };
|
|
325
|
+
const note = `${e.partial ? `${e.partial}\n\n` : ''}⚠️ *Couldn't finish this reply: ${e.message}*`;
|
|
326
|
+
await this._post(roomKey, self, note).catch(() => this._status(roomKey, `${agentId}: ${e.message}`));
|
|
327
|
+
return null;
|
|
328
|
+
})));
|
|
329
|
+
const replied = results.filter(r => r?.text);
|
|
330
|
+
if (!replied.length || stopped()) break;
|
|
331
|
+
// Next round: agents that replied or were named, if a sibling said something they haven't seen.
|
|
332
|
+
const eligible = new Set(replied.map(r => r.agentId));
|
|
333
|
+
for (const r of replied) for (const id of namedIn(r.text, agents)) if (id !== r.agentId) eligible.add(id);
|
|
334
|
+
targets = agents.map(a => a.agentId).filter(id => eligible.has(id) && replied.some(r => r.agentId !== id));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** One agent turn. Returns { agentId, text } (text null when silent/aborted). */
|
|
339
|
+
async _turn(roomKey, agentId, agents, history, mode, stopped = () => false) {
|
|
340
|
+
const room = this.store.getRoom(roomKey);
|
|
341
|
+
const member = room?.members.find(m => m.agentId === agentId);
|
|
342
|
+
if (!member) return null;
|
|
343
|
+
const self = agents.find(a => a.agentId === agentId) || { agentId, name: agentId };
|
|
344
|
+
const authors = this.store.authors(roomKey);
|
|
345
|
+
const fresh = history.filter(e => e.ts > member.seenAt && authors[e.id]?.agentId !== agentId);
|
|
346
|
+
if (!fresh.length) return null;
|
|
347
|
+
|
|
348
|
+
const workKey = member.workKey || await this._createWorkSession(roomKey, self);
|
|
349
|
+
const message = this._prompt(self, agents, fresh, mode);
|
|
350
|
+
const runId = `team-${crypto.randomUUID()}`;
|
|
351
|
+
const live = this._live(roomKey);
|
|
352
|
+
const done = this._waitRun(runId);
|
|
353
|
+
live.running.set(agentId, { workKey, runId });
|
|
354
|
+
this._status(roomKey);
|
|
355
|
+
let result;
|
|
356
|
+
try {
|
|
357
|
+
await this.request('chat.send', { sessionKey: workKey, message, deliver: false, idempotencyKey: runId }, 30_000);
|
|
358
|
+
this.store.setSeenAt(roomKey, agentId, Math.max(...fresh.map(e => e.ts)));
|
|
359
|
+
result = await done;
|
|
360
|
+
} finally {
|
|
361
|
+
this._cancelWait(runId);
|
|
362
|
+
live.running.delete(agentId);
|
|
363
|
+
this._status(roomKey);
|
|
364
|
+
}
|
|
365
|
+
const clean = t => {
|
|
366
|
+
const own = splitLabel((t || '').trim());
|
|
367
|
+
return (own.label && norm(own.label) === norm(self.name) ? own.body : (t || '')).trim(); // agent copied the room format
|
|
368
|
+
};
|
|
369
|
+
if (result.state !== 'final') {
|
|
370
|
+
// Stopped or failed mid-reply: the agent's session keeps what it said, so the room shows it too
|
|
371
|
+
// (a normal chat keeps a stopped reply's partial text the same way).
|
|
372
|
+
const partial = clean(result.partialText);
|
|
373
|
+
if (result.state === 'aborted') {
|
|
374
|
+
if (partial && !SILENT.test(partial)) await this._post(roomKey, self, `${partial}\n\n*[stopped]*`);
|
|
375
|
+
// Some runtimes (claude-cli) finish the reply after the abort was acknowledged: post it once it lands.
|
|
376
|
+
else this._recoverAfterAbort(roomKey, self, workKey);
|
|
377
|
+
return { agentId, text: null };
|
|
378
|
+
}
|
|
379
|
+
throw Object.assign(new Error(result.errorMessage || 'run failed'), { partial });
|
|
380
|
+
}
|
|
381
|
+
const text = clean(result.message ? messageText(result.message) : await this._lastReply(workKey));
|
|
382
|
+
if (!text || SILENT.test(text)) return { agentId, text: null };
|
|
383
|
+
await this._post(roomKey, self, text);
|
|
384
|
+
// A reply that finished after Stop is still posted (the agent said it), but starts no new round.
|
|
385
|
+
return { agentId, text: stopped() ? null : text };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* After Stop, a reply that still landed in the agent's session (the runtime ignored the abort) is
|
|
390
|
+
* posted to the room marked stopped, so the room matches what the agent believes it said.
|
|
391
|
+
* Polls until the session is idle (max ~3 min); gives up if the agent starts another turn.
|
|
392
|
+
*/
|
|
393
|
+
_recoverAfterAbort(roomKey, self, workKey, { intervalMs = 3000, tries = 60 } = {}) {
|
|
394
|
+
let n = 0;
|
|
395
|
+
const check = async () => {
|
|
396
|
+
if (this._rooms.get(roomKey)?.running.has(self.agentId) || !this.store.getRoom(roomKey)) return;
|
|
397
|
+
try {
|
|
398
|
+
const s = (await this.request('sessions.describe', { key: workKey }, 5000))?.session;
|
|
399
|
+
if (s?.hasActiveRun && ++n < tries) { setTimeout(check, intervalMs).unref?.(); return; }
|
|
400
|
+
const text = (await this._lastReply(workKey) || '').trim();
|
|
401
|
+
if (text && !SILENT.test(text)) await this._post(roomKey, self, `${text}\n\n*[stopped]*`);
|
|
402
|
+
} catch (e) { this.log.warn?.(`[team] recover after stop: ${e.message}`); }
|
|
403
|
+
};
|
|
404
|
+
setTimeout(check, intervalMs).unref?.();
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Post an agent's message into the room. */
|
|
408
|
+
async _post(roomKey, self, text) {
|
|
409
|
+
const res = await this.request('chat.inject', { sessionKey: roomKey, message: text, label: self.name.slice(0, 100) });
|
|
410
|
+
if (res?.messageId) this.store.recordEntry(roomKey, res.messageId, { type: 'agent', agentId: self.agentId });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
_prompt(self, agents, fresh, mode) {
|
|
414
|
+
const others = agents.filter(a => a.agentId !== self.agentId).map(a => a.name);
|
|
415
|
+
const lines = fresh.map(e => {
|
|
416
|
+
const { label, body } = splitLabel(e.text);
|
|
417
|
+
return `[${label || 'unknown'}]: ${body}`;
|
|
418
|
+
});
|
|
419
|
+
const instruction = {
|
|
420
|
+
addressed: 'The latest message is addressed to you. Reply to the team chat.',
|
|
421
|
+
open: 'The latest message is not addressed to anyone in particular. Reply only if it is clearly meant for you or you have something distinct to add; otherwise reply with exactly NO_REPLY.',
|
|
422
|
+
followup: 'Other participants just replied (above). Reply only if you have something new to add or were asked something; otherwise reply with exactly NO_REPLY. Do not just agree or repeat what was said.',
|
|
423
|
+
}[mode];
|
|
424
|
+
return [
|
|
425
|
+
`[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.`,
|
|
426
|
+
'',
|
|
427
|
+
'New messages since your last turn:',
|
|
428
|
+
'',
|
|
429
|
+
lines.join('\n\n'),
|
|
430
|
+
'',
|
|
431
|
+
instruction,
|
|
432
|
+
].join('\n');
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async _createWorkSession(roomKey, self) {
|
|
436
|
+
const workKey = `agent:${self.agentId}:dashboard:${crypto.randomUUID()}`;
|
|
437
|
+
this.store.setWorkKey(roomKey, self.agentId, workKey); // before create: the lens hides it from the first event
|
|
438
|
+
this._workKeysChanged();
|
|
439
|
+
try {
|
|
440
|
+
await this.request('sessions.create', { key: workKey, agentId: self.agentId, label: `${self.name} · team chat ${roomKey.slice(-8)}` }); // labels are unique per gateway
|
|
441
|
+
} catch (e) {
|
|
442
|
+
this.store.setWorkKey(roomKey, self.agentId, null);
|
|
443
|
+
this._workKeysChanged();
|
|
444
|
+
throw e;
|
|
445
|
+
}
|
|
446
|
+
this._changed();
|
|
447
|
+
return workKey;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Room transcript entries, oldest first: { id, ts, text }. */
|
|
451
|
+
async _roomEntries(roomKey) {
|
|
452
|
+
const h = await this.request('chat.history', { sessionKey: roomKey, limit: HISTORY_LIMIT }, 30_000);
|
|
453
|
+
return (h?.messages || [])
|
|
454
|
+
.map(m => ({ id: entryId(m), ts: Number(m.timestamp) || 0, text: messageText(m) }))
|
|
455
|
+
.filter(e => e.id && e.text);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Newest assistant text after the last user message (a final without a message). */
|
|
459
|
+
async _lastReply(workKey) {
|
|
460
|
+
const h = await this.request('chat.history', { sessionKey: workKey, limit: 20 }, 30_000);
|
|
461
|
+
const msgs = h?.messages || [];
|
|
462
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
463
|
+
if (msgs[i].role === 'user') return '';
|
|
464
|
+
if (msgs[i].role === 'assistant') { const t = messageText(msgs[i]); if (t.trim()) return t; }
|
|
465
|
+
}
|
|
466
|
+
return '';
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Room sessions never run, so the gateway's first-message titler never fires. Same chain as
|
|
471
|
+
* ClawChats' regenerate-title: the gateway's utility titler, else the main model.
|
|
472
|
+
*/
|
|
473
|
+
_maybeTitle(roomKey, text) {
|
|
474
|
+
this.request('sessions.describe', { key: roomKey }, 5000).then(async res => {
|
|
475
|
+
const s = res?.session;
|
|
476
|
+
if (!s || s.label || s.autoLabel || s.derivedTitle) return;
|
|
477
|
+
const agentId = /^agent:([^:]+):/.exec(roomKey)?.[1];
|
|
478
|
+
const message = Array.from(text).slice(0, 1000).join('');
|
|
479
|
+
let title = (await this.request('sessions.title.prepare', { agentId, message }, 30_000).catch(() => null))?.title;
|
|
480
|
+
if (!title && this.titler) title = await this.titler(message);
|
|
481
|
+
if (title) await this.request('sessions.patch', { key: roomKey, label: title });
|
|
482
|
+
}).catch(e => this.log.warn?.(`[team] title: ${e.message}`));
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ── Plumbing ───────────────────────────────────────────────────────
|
|
486
|
+
|
|
487
|
+
_waitRun(runId) {
|
|
488
|
+
return new Promise(resolve => {
|
|
489
|
+
const timer = setTimeout(() => { this._waiters.delete(runId); resolve({ state: 'error', errorMessage: 'timed out' }); }, TURN_TIMEOUT_MS);
|
|
490
|
+
timer.unref?.();
|
|
491
|
+
this._waiters.set(runId, { resolve, timer });
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
_cancelWait(runId) {
|
|
496
|
+
const w = this._waiters.get(runId);
|
|
497
|
+
if (w) { clearTimeout(w.timer); this._waiters.delete(runId); }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
_live(roomKey) {
|
|
501
|
+
let l = this._rooms.get(roomKey);
|
|
502
|
+
if (!l) { l = { running: new Map(), queued: 0, gen: 0 }; this._rooms.set(roomKey, l); }
|
|
503
|
+
return l;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
_status(roomKey, error) {
|
|
507
|
+
const live = this._rooms.get(roomKey);
|
|
508
|
+
this.broadcast(JSON.stringify({
|
|
509
|
+
type: 'clawchats', event: 'team-status', roomKey,
|
|
510
|
+
running: live ? [...live.running.keys()] : [], queued: live?.queued || 0,
|
|
511
|
+
...(error ? { error } : {}),
|
|
512
|
+
}));
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
_changed() {
|
|
516
|
+
this.broadcast(JSON.stringify({ type: 'clawchats', event: 'team-changed' }));
|
|
517
|
+
}
|
|
518
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { Database } from './bootstrap/native.js';
|
|
4
|
+
import { createTeamStore } from './store/team-store.js';
|
|
5
|
+
import { TeamCoordinator, parseMentions, namedIn, splitLabel, entryId } from './team.js';
|
|
6
|
+
import { SessionLens } from './session-lens.js';
|
|
7
|
+
|
|
8
|
+
const AGENTS = [{ id: 'main', identity: {} }, { id: 'dev', identity: { name: 'Dev' } }, { id: 'atlas', identity: { name: 'Atlas' } }];
|
|
9
|
+
|
|
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 } = {}) {
|
|
12
|
+
const sessions = new Map(); // key -> [{ role, content, timestamp, __m: { id } }]
|
|
13
|
+
const calls = [];
|
|
14
|
+
let clock = 1_000, seq = 0;
|
|
15
|
+
const events = [];
|
|
16
|
+
let team;
|
|
17
|
+
const request = async (method, params) => {
|
|
18
|
+
calls.push({ method, params });
|
|
19
|
+
switch (method) {
|
|
20
|
+
case 'agents.list': return { agents: AGENTS };
|
|
21
|
+
case 'sessions.create': sessions.set(params.key, []); return { ok: true, key: params.key };
|
|
22
|
+
case 'sessions.describe': return { session: { key: params.key } };
|
|
23
|
+
case 'sessions.title.prepare': return { title: preparedTitle };
|
|
24
|
+
case 'sessions.patch': case 'sessions.delete': return { ok: true };
|
|
25
|
+
case 'chat.inject': {
|
|
26
|
+
const id = `m${++seq}`;
|
|
27
|
+
sessions.get(params.sessionKey).push({ role: 'assistant', content: [{ type: 'text', text: `[${params.label}]\n\n${params.message}` }], timestamp: ++clock, __m: { id } });
|
|
28
|
+
return { ok: true, messageId: id };
|
|
29
|
+
}
|
|
30
|
+
case 'chat.history': return { messages: (sessions.get(params.sessionKey) || []).slice(-(params.limit || 80)) };
|
|
31
|
+
case 'chat.send': {
|
|
32
|
+
sessions.get(params.sessionKey).push({ role: 'user', content: params.message, timestamp: ++clock, __m: { id: `u${++seq}` } });
|
|
33
|
+
const agentId = /^agent:([^:]+):/.exec(params.sessionKey)[1];
|
|
34
|
+
const runId = params.idempotencyKey;
|
|
35
|
+
Promise.resolve(reply(agentId, params.message)).then(text => {
|
|
36
|
+
if (text && typeof text === 'object') { // { partial, state }: streamed some text, then aborted/error
|
|
37
|
+
team.onGatewayEvent({ type: 'event', event: 'chat', payload: { runId, sessionKey: params.sessionKey, state: 'delta', message: { role: 'assistant', content: [{ type: 'text', text: text.partial }] } } });
|
|
38
|
+
team.onGatewayEvent({ type: 'event', event: 'chat', payload: { runId, sessionKey: params.sessionKey, state: 'delta', deltaText: ' more' } });
|
|
39
|
+
team.onGatewayEvent({ type: 'event', event: 'chat', payload: { runId, sessionKey: params.sessionKey, state: text.state, errorMessage: text.error } });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const state = text === null ? 'aborted' : 'final';
|
|
43
|
+
const payload = { runId, sessionKey: params.sessionKey, state };
|
|
44
|
+
if (text && text !== 'NO_REPLY') payload.message = { role: 'assistant', content: [{ type: 'text', text }] };
|
|
45
|
+
team.onGatewayEvent({ type: 'event', event: 'chat', payload });
|
|
46
|
+
if (text === 'NO_REPLY') team.onGatewayEvent({ type: 'event', event: 'chat', payload: { runId, sessionKey: params.sessionKey, state: 'error' } });
|
|
47
|
+
});
|
|
48
|
+
return { runId, status: 'started' };
|
|
49
|
+
}
|
|
50
|
+
case 'chat.abort': return { ok: true };
|
|
51
|
+
default: throw new Error(`unexpected ${method}`);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const db = new Database(':memory:');
|
|
55
|
+
team = new TeamCoordinator({ store: createTeamStore(() => db), request, titler, broadcast: d => events.push(JSON.parse(d)), logger: { warn() {}, error() {} } });
|
|
56
|
+
const room = key => (sessions.get(key) || []).map(m => m.content[0].text);
|
|
57
|
+
const settle = async () => { for (let i = 0; i < 50; i++) await new Promise(r => setImmediate(r)); for (const c of team._chains.values()) await c; };
|
|
58
|
+
return { team, calls, room, settle, events, sessions };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
test('parsing helpers', () => {
|
|
62
|
+
const agents = [{ agentId: 'main', name: 'main' }, { agentId: 'atlas', name: 'Atlas' }, { agentId: 'dev', name: 'Dev Bot' }];
|
|
63
|
+
assert.deepEqual(parseMentions('hey @Atlas and @devbot.', agents), { agentIds: ['atlas', 'dev'] });
|
|
64
|
+
assert.deepEqual(parseMentions('mail me at x@atlas.com', agents), { agentIds: [] });
|
|
65
|
+
assert.deepEqual(parseMentions('@all thoughts?', agents), { all: true });
|
|
66
|
+
assert.deepEqual(parseMentions('no mention here', agents), { agentIds: [] });
|
|
67
|
+
assert.deepEqual(namedIn('I agree with Atlas, @main?', agents).sort(), ['atlas', 'main']);
|
|
68
|
+
assert.deepEqual(namedIn('Atlassian is a company', agents), []);
|
|
69
|
+
assert.deepEqual(splitLabel('[Atlas]\n\nhi\n\nthere'), { label: 'Atlas', body: 'hi\n\nthere' });
|
|
70
|
+
assert.deepEqual(splitLabel('plain'), { label: null, body: 'plain' });
|
|
71
|
+
assert.equal(entryId({ role: 'x', __meta: { id: 'e1' } }), 'e1');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('create, open message: everyone asked, silent agents stay out of the room', async () => {
|
|
75
|
+
const h = harness((agent, prompt) => {
|
|
76
|
+
assert.match(prompt, /not addressed to anyone/);
|
|
77
|
+
return agent === 'dev' ? 'dev answer' : 'NO_REPLY';
|
|
78
|
+
});
|
|
79
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
80
|
+
assert.match(roomKey, /^agent:dev:dashboard:/);
|
|
81
|
+
await h.team.send(roomKey, { text: 'what is 2+2?', userLabel: 'Houman' });
|
|
82
|
+
await h.settle();
|
|
83
|
+
assert.deepEqual(h.room(roomKey), ['[Houman]\n\nwhat is 2+2?', '[Dev]\n\ndev answer']);
|
|
84
|
+
const r = h.team.room(roomKey);
|
|
85
|
+
assert.deepEqual(Object.values(r.authors), [{ type: 'user', agentId: null }, { type: 'agent', agentId: 'dev' }]);
|
|
86
|
+
assert.equal(r.agents.every(a => a.workKey), true);
|
|
87
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2);
|
|
88
|
+
assert.equal(h.team.isWorkKey(r.agents[0].workKey), true);
|
|
89
|
+
assert.equal(h.team.isWorkKey(roomKey), false);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('mention gating: only the mentioned agent runs; the other catches up next time', async () => {
|
|
93
|
+
const prompts = {};
|
|
94
|
+
const h = harness((agent, prompt) => { (prompts[agent] ||= []).push(prompt); return `${agent} reply`; });
|
|
95
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
96
|
+
await h.team.send(roomKey, { text: '@atlas first question', userLabel: 'H' });
|
|
97
|
+
await h.settle();
|
|
98
|
+
assert.equal(prompts.dev, undefined);
|
|
99
|
+
assert.match(prompts.atlas[0], /addressed to you/);
|
|
100
|
+
await h.team.send(roomKey, { text: '@dev your turn', userLabel: 'H' });
|
|
101
|
+
await h.settle();
|
|
102
|
+
// dev sees the earlier exchange it missed, but not its own messages
|
|
103
|
+
assert.match(prompts.dev[0], /\[H\]: @atlas first question[\s\S]*\[Atlas\]: atlas reply[\s\S]*\[H\]: @dev your turn/);
|
|
104
|
+
assert.equal(prompts.atlas.length, 1);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('@all makes everyone answer; discuss runs follow-up rounds until everyone passes', async () => {
|
|
108
|
+
let round2 = 0;
|
|
109
|
+
const h = harness((agent, prompt) => {
|
|
110
|
+
if (/just replied/.test(prompt)) { round2++; return agent === 'atlas' && round2 <= 2 ? 'atlas adds one thing' : 'NO_REPLY'; }
|
|
111
|
+
return `${agent} first`;
|
|
112
|
+
});
|
|
113
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
114
|
+
h.team.setDiscuss(roomKey, true);
|
|
115
|
+
await h.team.send(roomKey, { text: '@all go', userLabel: 'H' });
|
|
116
|
+
await h.settle();
|
|
117
|
+
assert.deepEqual(h.room(roomKey), ['[H]\n\n@all go', '[Dev]\n\ndev first', '[Atlas]\n\natlas first', '[Atlas]\n\natlas adds one thing']);
|
|
118
|
+
// round 2: both (each saw a sibling reply). Round 3: only atlas replied and named nobody,
|
|
119
|
+
// so nobody is eligible (dev neither replied nor was named): 2 + 2 sends.
|
|
120
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 4);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('without discuss there is exactly one round', async () => {
|
|
124
|
+
const h = harness(agent => `${agent} says`);
|
|
125
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
126
|
+
await h.team.send(roomKey, { text: '@all hi', userLabel: 'H' });
|
|
127
|
+
await h.settle();
|
|
128
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('stop aborts running agents and drops queued messages; later messages still run', async () => {
|
|
132
|
+
const pending = [];
|
|
133
|
+
const h = harness(agent => new Promise(resolve => pending.push({ agent, resolve })));
|
|
134
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
135
|
+
await h.team.send(roomKey, { text: '@dev one', userLabel: 'H' });
|
|
136
|
+
await h.team.send(roomKey, { text: '@dev two (queued)', userLabel: 'H' });
|
|
137
|
+
for (let i = 0; i < 20; i++) await new Promise(r => setImmediate(r));
|
|
138
|
+
assert.equal(pending.length, 1);
|
|
139
|
+
await h.team.stop(roomKey);
|
|
140
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.abort').length, 1);
|
|
141
|
+
pending[0].resolve(null); // the gateway reports the aborted run
|
|
142
|
+
await h.team.send(roomKey, { text: '@dev three', userLabel: 'H' });
|
|
143
|
+
for (let i = 0; i < 20; i++) await new Promise(r => setImmediate(r));
|
|
144
|
+
assert.equal(pending.length, 2);
|
|
145
|
+
assert.match(h.calls.filter(c => c.method === 'chat.send').at(-1).params.message, /three/);
|
|
146
|
+
pending[1].resolve('done');
|
|
147
|
+
await h.settle();
|
|
148
|
+
// "two" was already in the room when "one" was dispatched, so dev saw it there; it never got a run of its own
|
|
149
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2);
|
|
150
|
+
assert.equal(h.room(roomKey).at(-1), '[Dev]\n\ndone');
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('converting an existing chat keeps it as the agent working session; delete cleans up', async () => {
|
|
154
|
+
const h = harness(agent => `${agent} ok`);
|
|
155
|
+
const source = 'agent:atlas:dashboard:old-chat';
|
|
156
|
+
h.sessions.set(source, []);
|
|
157
|
+
const created = await h.team.createRoom({ sourceKey: source, agentIds: ['dev'], label: 'Old title', category: 'Work' });
|
|
158
|
+
assert.equal(created.agents[0].agentId, 'atlas');
|
|
159
|
+
assert.equal(created.agents[0].workKey, source);
|
|
160
|
+
assert.equal(h.team.isWorkKey(source), true);
|
|
161
|
+
const createCall = h.calls.find(c => c.method === 'sessions.create');
|
|
162
|
+
assert.equal(createCall.params.label, 'Old title');
|
|
163
|
+
assert.equal(createCall.params.category, 'Work');
|
|
164
|
+
await assert.rejects(h.team.createRoom({ sourceKey: source, agentIds: ['main'] }), /already part/);
|
|
165
|
+
|
|
166
|
+
const lens = new SessionLens({ broadcast() {}, team: h.team });
|
|
167
|
+
assert.equal(lens.isVisible(source), false);
|
|
168
|
+
assert.equal(lens.forwardsRunEvent(source), true);
|
|
169
|
+
assert.equal(lens.isVisible(created.roomKey), true);
|
|
170
|
+
|
|
171
|
+
await h.team.send(created.roomKey, { text: '@dev hi', userLabel: 'H' });
|
|
172
|
+
await h.settle();
|
|
173
|
+
const devWork = h.team.room(created.roomKey).agents.find(a => a.agentId === 'dev').workKey;
|
|
174
|
+
lens.sessionsChanged({ sessionKey: created.roomKey, reason: 'delete' });
|
|
175
|
+
assert.equal(h.team.room(created.roomKey), null);
|
|
176
|
+
assert.equal(h.team.isWorkKey(source), false);
|
|
177
|
+
assert.equal(lens.isVisible(source), true); // the user's own chat comes back
|
|
178
|
+
assert.ok(!h.calls.some(c => c.method === 'sessions.delete' && c.params.key === source)); // never deleted
|
|
179
|
+
assert.ok(h.calls.some(c => c.method === 'sessions.delete' && c.params.key === devWork));
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test('unconvert: back to the original chat; only converted rooms', async () => {
|
|
183
|
+
const h = harness(agent => `${agent} ok`);
|
|
184
|
+
const source = 'agent:atlas:dashboard:orig';
|
|
185
|
+
h.sessions.set(source, []);
|
|
186
|
+
const { roomKey } = await h.team.createRoom({ sourceKey: source, agentIds: ['dev'] });
|
|
187
|
+
await h.team.send(roomKey, { text: '@all hi', userLabel: 'H' });
|
|
188
|
+
await h.settle();
|
|
189
|
+
const devWork = h.team.room(roomKey).agents.find(a => a.agentId === 'dev').workKey;
|
|
190
|
+
assert.equal(await h.team.unconvert(roomKey), source);
|
|
191
|
+
assert.equal(h.team.room(roomKey), null);
|
|
192
|
+
assert.equal(h.team.isWorkKey(source), false);
|
|
193
|
+
const deleted = h.calls.filter(c => c.method === 'sessions.delete').map(c => c.params.key);
|
|
194
|
+
assert.deepEqual(deleted.sort(), [devWork, roomKey].sort());
|
|
195
|
+
const fresh = (await h.team.createRoom({ agentIds: ['dev', 'atlas'] })).roomKey;
|
|
196
|
+
await assert.rejects(h.team.unconvert(fresh), /not converted/);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test('room title: gateway titler first, main-model titler when it has no utility model', async () => {
|
|
200
|
+
const a = harness(() => 'NO_REPLY');
|
|
201
|
+
const r1 = (await a.team.createRoom({ agentIds: ['dev', 'atlas'] })).roomKey;
|
|
202
|
+
await a.team.send(r1, { text: 'plan the offsite', userLabel: 'H' });
|
|
203
|
+
await a.settle();
|
|
204
|
+
assert.deepEqual(a.calls.find(c => c.method === 'sessions.patch').params, { key: r1, label: 'Team title' });
|
|
205
|
+
|
|
206
|
+
const b = harness(() => 'NO_REPLY', { preparedTitle: null, titler: async m => `T: ${m}` });
|
|
207
|
+
const r2 = (await b.team.createRoom({ agentIds: ['dev', 'atlas'] })).roomKey;
|
|
208
|
+
await b.team.send(r2, { text: 'plan the offsite', userLabel: 'H' });
|
|
209
|
+
await b.settle();
|
|
210
|
+
assert.deepEqual(b.calls.find(c => c.method === 'sessions.patch').params, { key: r2, label: 'T: plan the offsite' });
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test('a team chat needs two agents; removing down to one is refused', async () => {
|
|
214
|
+
const h = harness(() => 'x');
|
|
215
|
+
await assert.rejects(h.team.createRoom({ agentIds: ['dev'] }), /at least two/);
|
|
216
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
217
|
+
assert.throws(() => h.team.removeAgent(roomKey, 'dev'), /at least two/);
|
|
218
|
+
await h.team.addAgent(roomKey, 'main');
|
|
219
|
+
assert.deepEqual(h.team.removeAgent(roomKey, 'dev').agents.map(a => a.agentId), ['atlas', 'main']);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('stop: a partial reply is posted marked stopped; a reply that finished anyway is posted', async () => {
|
|
223
|
+
const pending = [];
|
|
224
|
+
const h = harness(agent => new Promise(resolve => pending.push({ agent, resolve })));
|
|
225
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
226
|
+
await h.team.send(roomKey, { text: '@all go', userLabel: 'H' });
|
|
227
|
+
for (let i = 0; i < 20; i++) await new Promise(r => setImmediate(r));
|
|
228
|
+
assert.equal(pending.length, 2);
|
|
229
|
+
await h.team.stop(roomKey);
|
|
230
|
+
pending.find(p => p.agent === 'dev').resolve({ partial: 'half an', state: 'aborted' });
|
|
231
|
+
pending.find(p => p.agent === 'atlas').resolve('atlas finished anyway');
|
|
232
|
+
await h.settle();
|
|
233
|
+
const room = h.room(roomKey);
|
|
234
|
+
assert.ok(room.includes('[Dev]\n\nhalf an more\n\n*[stopped]*'));
|
|
235
|
+
assert.ok(room.includes('[Atlas]\n\natlas finished anyway'));
|
|
236
|
+
assert.equal(h.calls.filter(c => c.method === 'chat.send').length, 2); // no follow-up round after Stop
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('a failed turn shows in the room with its partial text', async () => {
|
|
240
|
+
const h = harness(agent => agent === 'dev' ? { partial: 'started', state: 'error', error: 'runtime died' } : 'NO_REPLY');
|
|
241
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
242
|
+
await h.team.send(roomKey, { text: 'hello', userLabel: 'H' });
|
|
243
|
+
await h.settle();
|
|
244
|
+
assert.equal(h.room(roomKey).at(-1), "[Dev]\n\nstarted more\n\n⚠️ *Couldn't finish this reply: runtime died*");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test('working session labels are unique per room; unknown agents are refused', async () => {
|
|
248
|
+
const h = harness(() => 'ok');
|
|
249
|
+
const a = (await h.team.createRoom({ agentIds: ['dev', 'atlas'] })).roomKey;
|
|
250
|
+
const b = (await h.team.createRoom({ agentIds: ['dev', 'atlas'] })).roomKey;
|
|
251
|
+
await h.team.send(a, { text: '@dev hi', userLabel: 'H' });
|
|
252
|
+
await h.team.send(b, { text: '@dev hi', userLabel: 'H' });
|
|
253
|
+
await h.settle();
|
|
254
|
+
const labels = h.calls.filter(c => c.method === 'sessions.create' && c.params.label).map(c => c.params.label);
|
|
255
|
+
assert.equal(labels.length, 2);
|
|
256
|
+
assert.notEqual(labels[0], labels[1]);
|
|
257
|
+
await assert.rejects(h.team.createRoom({ agentIds: ['dev', 'ghost'] }), /unknown agent: ghost/);
|
|
258
|
+
await assert.rejects(h.team.addAgent(a, 'ghost'), /unknown agent/);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
test('stop: a reply the runtime finished after the abort is recovered from the agent session', async () => {
|
|
262
|
+
const h = harness(() => 'x');
|
|
263
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas'] });
|
|
264
|
+
const workKey = 'agent:dev:dashboard:w1';
|
|
265
|
+
h.sessions.set(workKey, [{ role: 'user', content: 'prompt', timestamp: 1 }]);
|
|
266
|
+
h.team._recoverAfterAbort(roomKey, { agentId: 'dev', name: 'Dev' }, workKey, { intervalMs: 1 });
|
|
267
|
+
await new Promise(r => setTimeout(r, 20));
|
|
268
|
+
assert.equal(h.room(roomKey).length, 0); // nothing landed: nothing posted
|
|
269
|
+
h.sessions.get(workKey).push({ role: 'assistant', content: [{ type: 'text', text: 'late full answer' }], timestamp: 2 });
|
|
270
|
+
h.team._recoverAfterAbort(roomKey, { agentId: 'dev', name: 'Dev' }, workKey, { intervalMs: 1 });
|
|
271
|
+
await new Promise(r => setTimeout(r, 20));
|
|
272
|
+
assert.deepEqual(h.room(roomKey), ['[Dev]\n\nlate full answer\n\n*[stopped]*']);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test('a removed agent keeps its hidden session and gets it back when re-added', async () => {
|
|
276
|
+
const h = harness(agent => `${agent} ok`);
|
|
277
|
+
const { roomKey } = await h.team.createRoom({ agentIds: ['dev', 'atlas', 'main'] });
|
|
278
|
+
await h.team.send(roomKey, { text: '@dev hi', userLabel: 'H' });
|
|
279
|
+
await h.settle();
|
|
280
|
+
const devWork = h.team.room(roomKey).agents.find(a => a.agentId === 'dev').workKey;
|
|
281
|
+
h.team.removeAgent(roomKey, 'dev');
|
|
282
|
+
assert.deepEqual(h.team.room(roomKey).agents.map(a => a.agentId), ['atlas', 'main']);
|
|
283
|
+
assert.equal(h.team.isWorkKey(devWork), true); // still hidden from the thread list
|
|
284
|
+
await h.team.addAgent(roomKey, 'dev');
|
|
285
|
+
const back = h.team.room(roomKey).agents.find(a => a.agentId === 'dev');
|
|
286
|
+
assert.equal(back.workKey, devWork);
|
|
287
|
+
h.team.onSessionDeleted(roomKey);
|
|
288
|
+
assert.ok(h.calls.some(c => c.method === 'sessions.delete' && c.params.key === devWork));
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
test('team_members migration adds the removed column to an existing table', () => {
|
|
292
|
+
const db = new Database(':memory:');
|
|
293
|
+
db.exec('CREATE TABLE team_members (room_key TEXT NOT NULL, agent_id TEXT NOT NULL, work_key TEXT, seen_at INTEGER NOT NULL DEFAULT 0, position INTEGER NOT NULL, PRIMARY KEY (room_key, agent_id))');
|
|
294
|
+
const store = createTeamStore(() => db);
|
|
295
|
+
assert.deepEqual(store.listRooms(), []);
|
|
296
|
+
assert.ok(db.prepare('PRAGMA table_info(team_members)').all().some(c => c.name === 'removed'));
|
|
297
|
+
});
|