@clawchatsai/connector 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/team.js 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
+ }