-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroups.js
More file actions
249 lines (213 loc) · 6.68 KB
/
Copy pathgroups.js
File metadata and controls
249 lines (213 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// ==========================================
// Group Manager — Multi-agent group conversations
// ==========================================
// Allows multiple AI agents to form groups and collaborate.
// A group can be:
// 1. A real WhatsApp group (all agents added to one group chat)
// 2. A virtual group (this agent fans out messages to all members)
import config from './config.js';
import { createAgentMessage } from './protocol.js';
import { JsonStore } from './storage.js';
// Persistent group store backed by data/groups.json
const store = new JsonStore('groups.json');
// In-memory map kept in sync with disk for fast access
const groups = new Map(store.entries().map(([k, v]) => [k, v]));
function persistGroup(groupId) {
store.set(groupId, groups.get(groupId));
}
/**
* @typedef {Object} GroupMember
* @property {string} phone - WhatsApp number or JID
* @property {string} agentId - Agent identifier
* @property {string} agentName - Display name
* @property {string} role - "admin" | "member"
*/
/**
* @typedef {Object} GroupInfo
* @property {string} groupId
* @property {string} name
* @property {string} purpose - What the group is for
* @property {string} createdBy - agentId of creator
* @property {string} createdAt
* @property {GroupMember[]} members
* @property {Array} history - Shared conversation history
* @property {string} mode - "whatsapp-group" | "virtual"
* @property {string} [whatsappGroupJid] - If mode is whatsapp-group
*/
/**
* Create a new virtual group.
*/
export function createGroup({ name, purpose, members = [] }) {
const groupId = `grp_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
// Always include self as admin
const self = {
phone: 'self',
agentId: config.agent.id,
agentName: config.agent.name,
role: 'admin',
};
const group = {
groupId,
name,
purpose: purpose || '',
createdBy: config.agent.id,
createdAt: new Date().toISOString(),
members: [self, ...members.map(m => ({ ...m, role: m.role || 'member' }))],
history: [],
mode: 'virtual',
};
groups.set(groupId, group);
persistGroup(groupId);
console.log(`[Group] Created "${name}" (${groupId}) with ${group.members.length} members`);
return group;
}
/**
* Register an existing WhatsApp group chat for AI-to-AI use.
*/
export function registerWhatsAppGroup({ whatsappGroupJid, name, purpose, members = [] }) {
const groupId = `wag_${Date.now()}`;
const group = {
groupId,
name,
purpose: purpose || '',
createdBy: config.agent.id,
createdAt: new Date().toISOString(),
members,
history: [],
mode: 'whatsapp-group',
whatsappGroupJid,
};
groups.set(groupId, group);
persistGroup(groupId);
console.log(`[Group] Registered WhatsApp group "${name}" (${whatsappGroupJid})`);
return group;
}
/**
* Add a member to a group.
*/
export function addMember(groupId, member) {
const group = groups.get(groupId);
if (!group) throw new Error(`Group ${groupId} not found`);
if (group.members.some(m => m.phone === member.phone)) {
console.log(`[Group] ${member.agentName} is already in "${group.name}"`);
return group;
}
group.members.push({ ...member, role: member.role || 'member' });
persistGroup(groupId);
console.log(`[Group] Added ${member.agentName} to "${group.name}"`);
return group;
}
/**
* Remove a member from a group.
*/
export function removeMember(groupId, phone) {
const group = groups.get(groupId);
if (!group) throw new Error(`Group ${groupId} not found`);
group.members = group.members.filter(m => m.phone !== phone);
persistGroup(groupId);
return group;
}
/**
* Get all groups this agent is part of.
*/
export function listGroups() {
return [...groups.values()];
}
/**
* Get a specific group.
*/
export function getGroup(groupId) {
return groups.get(groupId) || null;
}
/**
* Find a group by WhatsApp group JID.
*/
export function getGroupByJid(jid) {
for (const group of groups.values()) {
if (group.whatsappGroupJid === jid) return group;
}
return null;
}
/**
* Broadcast a message to all members of a virtual group.
* Sends the protocol message to each member except the sender.
*/
export async function broadcastToGroup(groupId, fromAgent, intent, payload, whatsappClient) {
const group = groups.get(groupId);
if (!group) throw new Error(`Group ${groupId} not found`);
const envelope = createAgentMessage({
from: fromAgent,
to: { groupId, groupName: group.name },
intent,
payload,
conversationId: groupId, // use groupId as ongoing conversation
});
// Add group context to the envelope
envelope.group = {
groupId: group.groupId,
groupName: group.name,
memberCount: group.members.length,
};
// Record in group history
group.history.push({
from: fromAgent,
intent,
payload,
timestamp: envelope.timestamp,
});
// Trim group history
if (group.history.length > 100) {
group.history = group.history.slice(-100);
}
persistGroup(groupId);
const jsonMsg = JSON.stringify(envelope);
if (group.mode === 'whatsapp-group' && group.whatsappGroupJid) {
// Send once to the WhatsApp group
await whatsappClient.sendMessage(group.whatsappGroupJid, jsonMsg);
} else {
// Virtual group: fan out to each member individually
for (const member of group.members) {
if (member.agentId === fromAgent.agentId) continue; // skip self
if (member.phone === 'self') continue;
await whatsappClient.sendMessage(member.phone, jsonMsg);
}
}
console.log(`[Group] Broadcast ${intent} to "${group.name}" (${group.members.length} members)`);
return envelope;
}
/**
* Handle an incoming group message — records it and returns context.
*/
export function recordGroupMessage(groupId, fromAgent, text) {
const group = groups.get(groupId);
if (!group) return null;
group.history.push({
from: fromAgent,
intent: 'chat',
payload: text,
timestamp: new Date().toISOString(),
});
if (group.history.length > 100) {
group.history = group.history.slice(-100);
}
persistGroup(groupId);
return group;
}
/**
* Get a summary of group history for AI context.
*/
export function getGroupContext(groupId) {
const group = groups.get(groupId);
if (!group) return '';
const lines = [
`Group: "${group.name}" | Purpose: ${group.purpose || 'general'}`,
`Members: ${group.members.map(m => m.agentName).join(', ')}`,
'--- Recent messages ---',
];
for (const entry of group.history.slice(-20)) {
const name = entry.from?.agentName || 'Unknown';
const content = typeof entry.payload === 'string' ? entry.payload : JSON.stringify(entry.payload);
lines.push(`[${name}]: ${content}`);
}
return lines.join('\n');
}