-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchannels.ts
More file actions
529 lines (463 loc) · 18.1 KB
/
Copy pathchannels.ts
File metadata and controls
529 lines (463 loc) · 18.1 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/**
* Channel route handlers: list, create, join, leave, messages, archive, etc.
*/
import type { Express, Request, Response } from 'express';
import {
fetchChannelMembers,
fetchChannelMessages,
inviteToChannel,
joinChannel,
leaveChannel,
setChannelArchived,
createChannel,
} from '../relaycast-provider.js';
import { reactionGroupsToRecord } from '../relaycast-provider-helpers.js';
import { resolveIdentity } from '../lib/identity.js';
import type { RouteContext } from '../lib/types.js';
import {
normalizeChannelTarget,
normalizeChannelName,
parseInviteMembers,
safeUsername,
} from '../lib/utils.js';
export function registerChannelRoutes(app: Express, ctx: RouteContext): void {
const projectName = safeUsername();
app.get('/api/channels', async (_req: Request, res: Response) => {
try {
const channels = await ctx.getRelaycastChannels();
res.json({
success: true,
...channels,
});
} catch (err) {
console.error('[dashboard] Failed to fetch Relaycast channels:', err);
res.status(500).json({ error: 'Failed to load channels' });
}
});
app.get('/api/channels/available-members', async (_req: Request, res: Response) => {
try {
const snapshot = await ctx.getRelaycastSnapshot();
const agents = snapshot.agents.map((agent) => ({
id: agent.name,
displayName: agent.name,
entityType: 'agent' as const,
status: (agent.status ?? 'online').toLowerCase() === 'online' ? 'online' : 'offline',
}));
res.json({
success: true,
members: [],
agents,
});
} catch (err) {
console.error('[dashboard] Failed to build available members:', err);
res.status(500).json({ error: 'Failed to load members' });
}
});
app.get('/api/channels/:channel/members', async (req: Request, res: Response) => {
const channelParamRaw = Array.isArray(req.params.channel) ? req.params.channel[0] : req.params.channel;
const channelParam = decodeURIComponent(channelParamRaw ?? '');
const channelName = channelParam.startsWith('#') ? channelParam.slice(1) : channelParam;
if (!channelName) {
res.status(400).json({ error: 'Channel is required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.json({ members: [] });
return;
}
try {
const [members, spawnedAgentNames, localAgentNames] = await Promise.all([
fetchChannelMembers(config, channelName),
ctx.brokerProxyEnabled ? ctx.getSpawnedAgents().then((spawned) => spawned.names) : Promise.resolve(null),
ctx.brokerProxyEnabled ? Promise.resolve(null) : Promise.resolve(ctx.getLocalAgentNames()),
]);
const filteredMembers = ctx.filterPhantomAgents(members, spawnedAgentNames, localAgentNames);
res.json({
members: filteredMembers.map((agent) => ({
id: agent.name,
displayName: agent.name,
entityType: 'agent' as const,
role: 'member' as const,
status: (agent.status ?? 'online').toLowerCase() === 'online' ? 'online' : 'offline',
joinedAt: agent.lastSeen ?? new Date().toISOString(),
})),
});
} catch (err) {
console.error('[dashboard] Failed to fetch channel members:', err);
res.status(500).json({ error: 'Failed to load channel members' });
}
});
app.get('/api/channels/:channel/messages', async (req: Request, res: Response) => {
const channelParamRaw = Array.isArray(req.params.channel) ? req.params.channel[0] : req.params.channel;
const channelParam = decodeURIComponent(channelParamRaw ?? '');
const channelName = channelParam.startsWith('#') ? channelParam.slice(1) : channelParam;
const limitRaw = req.query.limit ? parseInt(req.query.limit as string, 10) : 100;
const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 500) : 100;
const beforeRaw = req.query.before ? parseInt(req.query.before as string, 10) : NaN;
const beforeTs = Number.isFinite(beforeRaw) ? beforeRaw : null;
if (!channelName) {
res.status(400).json({ error: 'Channel is required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.json({ messages: [], hasMore: false });
return;
}
try {
const requestedLimit = beforeTs ? Math.min(limit * 2, 500) : limit;
const messages = await fetchChannelMessages(config, channelName, {
limit: requestedLimit,
before: beforeTs === null ? undefined : beforeTs,
});
const identityConfig = {
projectIdentity: config.projectIdentity?.trim() || projectName,
};
const trimmed = messages.slice(-limit);
const hasMore = messages.length > limit;
res.json({
messages: trimmed.map((message) => ({
id: message.id,
channelId: channelParam.startsWith('#') ? channelParam : `#${channelName}`,
from: resolveIdentity(message.agent_name, identityConfig),
fromEntityType: 'agent' as const,
content: message.text,
timestamp: message.created_at,
threadId: message.thread_id,
threadSummary: typeof message.reply_count === 'number' && message.reply_count > 0 ? {
threadId: message.id,
replyCount: message.reply_count,
lastReplyAt: message.created_at,
} : undefined,
reactions: message.reactions
? reactionGroupsToRecord(message.reactions)
: undefined,
isRead: true,
})),
hasMore,
});
} catch (err) {
console.error('[dashboard] Failed to fetch Relaycast channel messages:', err);
res.status(500).json({ error: 'Failed to load channel messages' });
}
});
const handleRelaycastSend = async (req: Request, res: Response): Promise<void> => {
const { to, from } = req.body ?? {};
const thread = typeof req.body?.thread === 'string' && req.body.thread.trim()
? req.body.thread.trim()
: undefined;
const messageValue = req.body?.message ?? req.body?.text ?? req.body?.body ?? req.body?.content;
const message = typeof messageValue === 'string' ? messageValue.trim() : '';
const requestStartedAt = Date.now();
if (typeof to !== 'string' || !to.trim() || !message) {
console.warn('[dashboard] /api/send missing required fields', {
hasTo: typeof to === 'string',
hasMessage: typeof messageValue === 'string',
});
res.status(400).json({ success: false, error: 'Missing required fields: to, message' });
return;
}
const result = await ctx.sendRelaycastMessage({
to: to.trim(),
message,
from: typeof from === 'string' ? from : undefined,
thread,
});
if (!result.success) {
console.warn(
`[dashboard] /api/send failed: to=${to.trim()} status=${result.status} relayUrl=${ctx.relayUrl} durationMs=${Date.now() - requestStartedAt}`,
);
res.status(result.status).json({
success: false,
error: result.error,
});
return;
}
console.log(
`[dashboard] /api/send completed: to=${to.trim()} messageId=${result.messageId} durationMs=${Date.now() - requestStartedAt}`,
);
res.json({
success: true,
messageId: result.messageId,
});
};
app.post('/api/send', handleRelaycastSend);
app.post('/api/dm', handleRelaycastSend);
app.post('/api/relay/send', handleRelaycastSend);
app.post('/api/channels', async (req: Request, res: Response) => {
const { name, description, topic, isPrivate, visibility, invites } = req.body ?? {};
const username = typeof req.body?.username === 'string' && req.body.username.trim()
? req.body.username.trim()
: projectName;
const rawName = typeof name === 'string' ? name : '';
const channelName = normalizeChannelName(rawName);
if (!channelName || channelName.startsWith('dm:')) {
res.status(400).json({ error: 'name is required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.status(503).json({
success: false,
error: 'Relaycast credentials not configured. Set RELAY_API_KEY or POST /api/relay-config.',
});
return;
}
try {
await createChannel(config, {
name: channelName,
description: typeof description === 'string' ? description : (typeof topic === 'string' ? topic : undefined),
visibility: visibility === 'private' || isPrivate === true ? 'private' : 'public',
creator: username,
dataDir: ctx.dataDir,
});
await joinChannel(config, { channel: channelName, username, dataDir: ctx.dataDir }).catch(() => {});
const inviteMembers = parseInviteMembers(invites);
const inviteResult = inviteMembers.length > 0
? await inviteToChannel(config, {
channel: channelName,
members: inviteMembers,
invitedBy: username,
dataDir: ctx.dataDir,
})
: { invited: [] };
res.json({
success: true,
channel: {
id: `#${channelName}`,
name: channelName,
description: typeof description === 'string' ? description : undefined,
topic: typeof topic === 'string' ? topic : undefined,
visibility: visibility === 'private' || isPrivate === true ? 'private' : 'public',
status: 'active',
createdAt: new Date().toISOString(),
createdBy: username,
memberCount: Math.max(1, inviteResult.invited.filter((member) => member.success).length + 1),
unreadCount: 0,
hasMentions: false,
isDm: false,
},
invited: inviteResult.invited,
});
} catch (err) {
console.error('[dashboard] Failed to create Relaycast channel:', err);
res.status(500).json({ error: (err as Error).message || 'Failed to create channel' });
}
});
app.post('/api/channels/invite', async (req: Request, res: Response) => {
const { channel, invites, invitedBy } = req.body ?? {};
const channelName = typeof channel === 'string' ? normalizeChannelName(channel) : '';
const inviteMembers = parseInviteMembers(invites);
if (!channelName || inviteMembers.length === 0 || channelName.startsWith('dm:')) {
res.status(400).json({ error: 'channel and invites are required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.status(503).json({
success: false,
error: 'Relaycast credentials not configured. Set RELAY_API_KEY or POST /api/relay-config.',
});
return;
}
const inviteResult = await inviteToChannel(config, {
channel: channelName,
members: inviteMembers,
invitedBy: typeof invitedBy === 'string' && invitedBy.trim() ? invitedBy.trim() : projectName,
dataDir: ctx.dataDir,
});
res.json({
channel: normalizeChannelTarget(channelName),
invited: inviteResult.invited,
});
});
app.get('/api/channels/users', (_req: Request, res: Response) => {
res.json({ users: [] });
});
app.post('/api/channels/join', async (req: Request, res: Response) => {
const username = typeof req.body?.username === 'string' ? req.body.username.trim() : '';
const channel = typeof req.body?.channel === 'string' ? req.body.channel : '';
const channelName = normalizeChannelName(channel);
const channelTarget = normalizeChannelTarget(channel);
if (!username || !channelName) {
res.status(400).json({ error: 'username and channel required' });
return;
}
if (channelName.startsWith('dm:')) {
res.json({ success: true, channel: channelTarget });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.status(503).json({
success: false,
error: 'Relaycast credentials not configured. Set RELAY_API_KEY or POST /api/relay-config.',
});
return;
}
try {
await joinChannel(config, { channel: channelName, username, dataDir: ctx.dataDir });
} catch (err) {
console.error('[dashboard] Failed to join Relaycast channel:', err);
res.status(500).json({ error: (err as Error).message || 'Failed to join channel' });
return;
}
res.json({ success: true, channel: channelTarget });
});
app.post('/api/channels/leave', async (req: Request, res: Response) => {
const username = typeof req.body?.username === 'string' ? req.body.username.trim() : '';
const channel = typeof req.body?.channel === 'string' ? normalizeChannelTarget(req.body.channel) : '';
if (!username || !channel) {
res.status(400).json({ error: 'username and channel required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (config) {
try {
await leaveChannel(config, { channel, username });
} catch (err) {
if (ctx.verbose) {
console.warn('[dashboard] Leave channel fallback failed:', (err as Error).message);
}
}
}
res.json({ success: true, channel });
});
app.post('/api/channels/admin-join', async (req: Request, res: Response) => {
const channel = typeof req.body?.channel === 'string' ? normalizeChannelName(req.body.channel) : '';
const member = typeof req.body?.member === 'string' ? req.body.member.trim() : '';
if (!channel || !member || channel.startsWith('dm:')) {
res.status(400).json({ error: 'channel and member required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.status(503).json({
success: false,
error: 'Relaycast credentials not configured. Set RELAY_API_KEY or POST /api/relay-config.',
});
return;
}
try {
await inviteToChannel(config, {
channel,
members: [{ id: member, type: 'agent' }],
invitedBy: projectName,
dataDir: ctx.dataDir,
});
res.json({ success: true, channel: normalizeChannelTarget(channel), member });
} catch (err) {
console.error('[dashboard] Failed to admin-join channel member:', err);
res.status(500).json({ error: (err as Error).message || 'Failed to add member' });
}
});
app.post('/api/channels/admin-remove', (req: Request, res: Response) => {
const channel = typeof req.body?.channel === 'string' ? normalizeChannelTarget(req.body.channel) : '';
const member = typeof req.body?.member === 'string' ? req.body.member.trim() : '';
if (!channel || !member) {
res.status(400).json({ error: 'channel and member required' });
return;
}
res.json({ success: true, channel, member });
});
app.post('/api/channels/subscribe', async (req: Request, res: Response) => {
const username = typeof req.body?.username === 'string' ? req.body.username.trim() : '';
const channelsRaw: unknown[] = Array.isArray(req.body?.channels) ? req.body.channels : ['#general'];
const channelNames = channelsRaw
.filter((entry: unknown): entry is string => typeof entry === 'string')
.map((entry: string) => normalizeChannelName(entry))
.filter(Boolean);
if (!username) {
res.status(400).json({ error: 'username required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (!config) {
res.status(503).json({
success: false,
error: 'Relaycast credentials not configured. Set RELAY_API_KEY or POST /api/relay-config.',
});
return;
}
const joinedChannels: string[] = [];
for (const channelName of channelNames) {
if (channelName.startsWith('dm:')) {
joinedChannels.push(channelName);
continue;
}
try {
await joinChannel(config, { channel: channelName, username, dataDir: ctx.dataDir });
joinedChannels.push(normalizeChannelTarget(channelName));
} catch (err) {
if (ctx.verbose) {
console.warn(`[dashboard] Failed to subscribe ${username} to ${channelName}:`, (err as Error).message);
}
}
}
res.json({
success: true,
channels: joinedChannels,
});
});
app.post('/api/channels/message', async (req: Request, res: Response) => {
const username = typeof req.body?.username === 'string' && req.body.username.trim()
? req.body.username.trim()
: projectName;
const channel = typeof req.body?.channel === 'string' ? req.body.channel : '';
const body = typeof req.body?.body === 'string' ? req.body.body.trim() : '';
if (!channel || !body) {
res.status(400).json({ error: 'username, channel, and body required' });
return;
}
const result = await ctx.sendRelaycastMessage({
to: normalizeChannelTarget(channel),
message: body,
from: username,
});
if (!result.success) {
res.status(result.status).json({
success: false,
error: result.error,
});
return;
}
res.json({ success: true, messageId: result.messageId });
});
app.post('/api/channels/archive', async (req: Request, res: Response) => {
const channel = typeof req.body?.channel === 'string' ? normalizeChannelTarget(req.body.channel) : '';
if (!channel) {
res.status(400).json({ error: 'channel required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (config) {
try {
await setChannelArchived(config, { channel, archived: true, updatedBy: projectName });
} catch (err) {
if (ctx.verbose) {
console.warn('[dashboard] Archive channel fallback failed:', (err as Error).message);
}
}
}
res.json({ success: true, channel });
});
app.post('/api/channels/unarchive', async (req: Request, res: Response) => {
const channel = typeof req.body?.channel === 'string' ? normalizeChannelTarget(req.body.channel) : '';
if (!channel) {
res.status(400).json({ error: 'channel required' });
return;
}
const config = ctx.resolveRelaycastConfig();
if (config) {
try {
await setChannelArchived(config, { channel, archived: false, updatedBy: projectName });
} catch (err) {
if (ctx.verbose) {
console.warn('[dashboard] Unarchive channel fallback failed:', (err as Error).message);
}
}
}
res.json({ success: true, channel });
});
}