@chrisromp/copilot-bridge 0.6.0-dev.2

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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -0
  3. package/bin/copilot-bridge.js +61 -0
  4. package/config.sample.json +100 -0
  5. package/dist/channels/mattermost/adapter.d.ts +55 -0
  6. package/dist/channels/mattermost/adapter.d.ts.map +1 -0
  7. package/dist/channels/mattermost/adapter.js +524 -0
  8. package/dist/channels/mattermost/adapter.js.map +1 -0
  9. package/dist/channels/mattermost/streaming.d.ts +29 -0
  10. package/dist/channels/mattermost/streaming.d.ts.map +1 -0
  11. package/dist/channels/mattermost/streaming.js +151 -0
  12. package/dist/channels/mattermost/streaming.js.map +1 -0
  13. package/dist/config.d.ts +107 -0
  14. package/dist/config.d.ts.map +1 -0
  15. package/dist/config.js +817 -0
  16. package/dist/config.js.map +1 -0
  17. package/dist/core/bridge.d.ts +73 -0
  18. package/dist/core/bridge.d.ts.map +1 -0
  19. package/dist/core/bridge.js +166 -0
  20. package/dist/core/bridge.js.map +1 -0
  21. package/dist/core/channel-idle.d.ts +40 -0
  22. package/dist/core/channel-idle.d.ts.map +1 -0
  23. package/dist/core/channel-idle.js +120 -0
  24. package/dist/core/channel-idle.js.map +1 -0
  25. package/dist/core/command-handler.d.ts +51 -0
  26. package/dist/core/command-handler.d.ts.map +1 -0
  27. package/dist/core/command-handler.js +393 -0
  28. package/dist/core/command-handler.js.map +1 -0
  29. package/dist/core/inter-agent.d.ts +52 -0
  30. package/dist/core/inter-agent.d.ts.map +1 -0
  31. package/dist/core/inter-agent.js +179 -0
  32. package/dist/core/inter-agent.js.map +1 -0
  33. package/dist/core/onboarding.d.ts +44 -0
  34. package/dist/core/onboarding.d.ts.map +1 -0
  35. package/dist/core/onboarding.js +205 -0
  36. package/dist/core/onboarding.js.map +1 -0
  37. package/dist/core/scheduler.d.ts +38 -0
  38. package/dist/core/scheduler.d.ts.map +1 -0
  39. package/dist/core/scheduler.js +253 -0
  40. package/dist/core/scheduler.js.map +1 -0
  41. package/dist/core/session-manager.d.ts +166 -0
  42. package/dist/core/session-manager.d.ts.map +1 -0
  43. package/dist/core/session-manager.js +1732 -0
  44. package/dist/core/session-manager.js.map +1 -0
  45. package/dist/core/stream-formatter.d.ts +14 -0
  46. package/dist/core/stream-formatter.d.ts.map +1 -0
  47. package/dist/core/stream-formatter.js +198 -0
  48. package/dist/core/stream-formatter.js.map +1 -0
  49. package/dist/core/thread-utils.d.ts +22 -0
  50. package/dist/core/thread-utils.d.ts.map +1 -0
  51. package/dist/core/thread-utils.js +44 -0
  52. package/dist/core/thread-utils.js.map +1 -0
  53. package/dist/core/workspace-manager.d.ts +38 -0
  54. package/dist/core/workspace-manager.d.ts.map +1 -0
  55. package/dist/core/workspace-manager.js +230 -0
  56. package/dist/core/workspace-manager.js.map +1 -0
  57. package/dist/index.d.ts +2 -0
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +1286 -0
  60. package/dist/index.js.map +1 -0
  61. package/dist/logger.d.ts +9 -0
  62. package/dist/logger.d.ts.map +1 -0
  63. package/dist/logger.js +34 -0
  64. package/dist/logger.js.map +1 -0
  65. package/dist/state/store.d.ts +124 -0
  66. package/dist/state/store.d.ts.map +1 -0
  67. package/dist/state/store.js +523 -0
  68. package/dist/state/store.js.map +1 -0
  69. package/dist/types.d.ts +185 -0
  70. package/dist/types.d.ts.map +1 -0
  71. package/dist/types.js +2 -0
  72. package/dist/types.js.map +1 -0
  73. package/package.json +61 -0
  74. package/scripts/check.ts +267 -0
  75. package/scripts/com.copilot-bridge.plist +41 -0
  76. package/scripts/copilot-bridge.service +30 -0
  77. package/scripts/init.ts +250 -0
  78. package/scripts/install-service.ts +123 -0
  79. package/scripts/lib/config-gen.ts +129 -0
  80. package/scripts/lib/mattermost.ts +109 -0
  81. package/scripts/lib/output.ts +69 -0
  82. package/scripts/lib/prerequisites.ts +86 -0
  83. package/scripts/lib/prompts.ts +65 -0
  84. package/scripts/lib/service.ts +191 -0
  85. package/scripts/uninstall-service.ts +90 -0
  86. package/templates/admin/AGENTS.md +325 -0
  87. package/templates/admin/MEMORY.md +4 -0
  88. package/templates/agents/AGENTS.md +97 -0
  89. package/templates/agents/MEMORY.md +4 -0
@@ -0,0 +1,524 @@
1
+ import { Client4, WebSocketClient } from '@mattermost/client';
2
+ import WebSocket from 'ws';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { createLogger } from '../../logger.js';
6
+ const log = createLogger('mattermost');
7
+ // Node.js polyfills for @mattermost/client (expects browser globals)
8
+ if (!globalThis.WebSocket) {
9
+ globalThis.WebSocket = WebSocket;
10
+ }
11
+ if (typeof window === 'undefined') {
12
+ globalThis.window = {
13
+ addEventListener: () => { },
14
+ removeEventListener: () => { },
15
+ navigator: { userAgent: 'copilot-bridge/0.1.0 (Node.js)' },
16
+ };
17
+ }
18
+ export class MattermostAdapter {
19
+ platform;
20
+ client;
21
+ wsClient;
22
+ botId = '';
23
+ botUsername = '';
24
+ url;
25
+ token;
26
+ messageHandlers = [];
27
+ reactionHandlers = [];
28
+ // WebSocket reconnect replay
29
+ disconnectedAt = null;
30
+ lastServerTimestamp = null; // server-side create_at from last received post
31
+ activeChannels = new Map(); // channelId → last activity timestamp
32
+ recentPostIds = new Set();
33
+ isReplaying = false;
34
+ pendingReplay = null;
35
+ static MAX_RECENT_POSTS = 500;
36
+ static MAX_REPLAY_WINDOW_MS = 60_000;
37
+ static CHANNEL_STALENESS_MS = 3_600_000; // 1 hour
38
+ constructor(platformName, url, token) {
39
+ this.platform = platformName;
40
+ this.url = url.replace(/\/+$/, '');
41
+ this.token = token;
42
+ this.client = new Client4();
43
+ this.wsClient = new WebSocketClient();
44
+ }
45
+ async connect() {
46
+ this.client.setUrl(this.url);
47
+ this.client.setToken(this.token);
48
+ // Fetch bot identity
49
+ const me = await this.client.getMe();
50
+ this.botId = me.id;
51
+ this.botUsername = me.username;
52
+ // Build WebSocket URL
53
+ const wsScheme = this.url.startsWith('https') ? 'wss' : 'ws';
54
+ const host = this.url.replace(/^https?:\/\//, '');
55
+ const wsUrl = `${wsScheme}://${host}/api/v4/websocket`;
56
+ this.wsClient.addMissedMessageListener(() => {
57
+ log.warn(`WebSocket reconnected — missed events, resetting state`);
58
+ });
59
+ this.wsClient.addCloseListener((failCount) => {
60
+ if (!this.disconnectedAt) {
61
+ this.disconnectedAt = Date.now();
62
+ log.warn(`WebSocket closed (failCount=${failCount}), tracking disconnect time`);
63
+ }
64
+ });
65
+ this.wsClient.addErrorListener((event) => {
66
+ log.warn(`WebSocket error:`, event?.message ?? event.type);
67
+ });
68
+ this.wsClient.addReconnectListener(() => {
69
+ const disconnectedAt = this.disconnectedAt;
70
+ this.disconnectedAt = null;
71
+ if (disconnectedAt) {
72
+ const gapMs = Date.now() - disconnectedAt;
73
+ // Use last known server timestamp (immune to clock skew), fall back to client time with safety buffer
74
+ const sinceTimestamp = this.lastServerTimestamp ?? (disconnectedAt - 5_000);
75
+ log.info(`WebSocket reconnected after ${(gapMs / 1000).toFixed(1)}s`);
76
+ this.replayMissedMessages(sinceTimestamp, gapMs).catch(err => log.error('Failed to replay missed messages:', err));
77
+ }
78
+ });
79
+ await this.wsClient.initialize(wsUrl, this.token);
80
+ this.wsClient.addMessageListener((msg) => {
81
+ log.debug(`WS event: ${msg.event}`);
82
+ if (msg.event === 'posted') {
83
+ this.handlePosted(msg);
84
+ }
85
+ else if (msg.event === 'reaction_added' || msg.event === 'reaction_removed') {
86
+ this.handleReaction(msg);
87
+ }
88
+ });
89
+ log.info(`Connected as @${this.botUsername} (${this.botId})`);
90
+ }
91
+ async disconnect() {
92
+ this.wsClient.close();
93
+ }
94
+ /**
95
+ * Discover existing DM channels for this bot via the Mattermost API.
96
+ * Returns channel IDs for direct message conversations the bot is already part of.
97
+ */
98
+ async discoverDMChannels() {
99
+ try {
100
+ const baseUrl = this.client.getBaseRoute();
101
+ const resp = await fetch(`${baseUrl}/users/${this.botId}/channels`, {
102
+ headers: { 'Authorization': `Bearer ${this.token}` },
103
+ });
104
+ if (!resp.ok) {
105
+ log.warn(`Failed to discover DM channels: ${resp.status} ${resp.statusText}`);
106
+ return [];
107
+ }
108
+ const channels = await resp.json();
109
+ return channels
110
+ .filter(ch => ch.type === 'D')
111
+ .map(ch => {
112
+ // DM channel names are "{userId1}__{userId2}"
113
+ const parts = ch.name.split('__');
114
+ const otherUserId = parts.find(p => p !== this.botId) ?? parts[0];
115
+ return { channelId: ch.id, otherUserId };
116
+ });
117
+ }
118
+ catch (err) {
119
+ log.warn(`Error discovering DM channels:`, err);
120
+ return [];
121
+ }
122
+ }
123
+ onMessage(handler) {
124
+ this.messageHandlers.push(handler);
125
+ }
126
+ onReaction(handler) {
127
+ this.reactionHandlers.push(handler);
128
+ }
129
+ async sendMessage(channelId, content, opts) {
130
+ const post = await this.client.createPost({
131
+ channel_id: channelId,
132
+ message: content,
133
+ root_id: opts?.threadRootId ?? '',
134
+ });
135
+ return post.id;
136
+ }
137
+ async updateMessage(_channelId, messageId, content) {
138
+ await this.client.patchPost({ id: messageId, message: content });
139
+ }
140
+ async deleteMessage(_channelId, messageId) {
141
+ await this.client.deletePost(messageId);
142
+ }
143
+ async setTyping(channelId) {
144
+ try {
145
+ const baseUrl = this.client.getBaseRoute();
146
+ await fetch(`${baseUrl}/users/me/typing`, {
147
+ method: 'POST',
148
+ headers: {
149
+ Authorization: `Bearer ${this.token}`,
150
+ 'Content-Type': 'application/json',
151
+ },
152
+ body: JSON.stringify({ channel_id: channelId }),
153
+ });
154
+ }
155
+ catch {
156
+ // Typing indicator is best-effort
157
+ }
158
+ }
159
+ async replyInThread(channelId, rootId, content) {
160
+ return this.sendMessage(channelId, content, { threadRootId: rootId });
161
+ }
162
+ getBotUserId() {
163
+ return this.botId;
164
+ }
165
+ async addReaction(postId, emoji) {
166
+ try {
167
+ const baseUrl = this.client.getBaseRoute();
168
+ await fetch(`${baseUrl}/reactions`, {
169
+ method: 'POST',
170
+ headers: {
171
+ Authorization: `Bearer ${this.token}`,
172
+ 'Content-Type': 'application/json',
173
+ },
174
+ body: JSON.stringify({
175
+ user_id: this.botId,
176
+ post_id: postId,
177
+ emoji_name: emoji,
178
+ }),
179
+ });
180
+ }
181
+ catch {
182
+ // Reactions are best-effort
183
+ }
184
+ }
185
+ handlePosted(msg) {
186
+ try {
187
+ const post = JSON.parse(msg.data.post);
188
+ // Ignore own messages
189
+ if (post.user_id === this.botId)
190
+ return;
191
+ // Track for reconnect replay
192
+ this.trackPost(post.id, post.channel_id, post.create_at);
193
+ const channelType = msg.data.channel_type ?? '';
194
+ const isDM = channelType === 'D' || channelType === 'G';
195
+ const mentionsBot = isDM || post.message?.includes(`@${this.botUsername}`);
196
+ const inbound = {
197
+ platform: this.platform,
198
+ channelId: post.channel_id,
199
+ userId: post.user_id,
200
+ username: (msg.data.sender_name ?? '').replace(/^@/, ''),
201
+ text: post.message ?? '',
202
+ postId: post.id,
203
+ threadRootId: post.root_id || undefined,
204
+ mentionsBot,
205
+ isDM,
206
+ attachments: this.extractAttachments(post),
207
+ };
208
+ log.info(`Received: "${inbound.text.slice(0, 80)}" from ${inbound.username} in ${inbound.channelId} (isDM=${isDM})`);
209
+ for (const handler of this.messageHandlers) {
210
+ try {
211
+ const result = handler(inbound);
212
+ if (result && typeof result.catch === 'function') {
213
+ result.catch((err) => log.error('Handler error:', err));
214
+ }
215
+ }
216
+ catch (err) {
217
+ log.error('Handler error:', err);
218
+ }
219
+ }
220
+ }
221
+ catch (err) {
222
+ log.error('Failed to parse posted event:', err);
223
+ }
224
+ }
225
+ extractAttachments(post) {
226
+ const fileIds = post.file_ids ?? [];
227
+ const metadata = post.metadata?.files;
228
+ if (fileIds.length === 0)
229
+ return undefined;
230
+ return fileIds.map((id, i) => {
231
+ const info = metadata?.[i];
232
+ const name = info?.name ?? `file-${id}`;
233
+ const mimeType = info?.mime_type ?? '';
234
+ const ext = info?.extension ?? '';
235
+ const size = info?.size;
236
+ let type = 'file';
237
+ if (mimeType.startsWith('image/'))
238
+ type = 'image';
239
+ else if (mimeType.startsWith('video/'))
240
+ type = 'video';
241
+ else if (mimeType.startsWith('audio/'))
242
+ type = 'audio';
243
+ const baseUrl = this.client.getBaseRoute();
244
+ const url = `${baseUrl}/files/${id}`;
245
+ return { id, type, url, name: name + (ext && !name.endsWith(`.${ext}`) ? `.${ext}` : ''), mimeType, size };
246
+ });
247
+ }
248
+ async downloadFile(fileId, destPath) {
249
+ const baseUrl = this.client.getBaseRoute();
250
+ const resp = await fetch(`${baseUrl}/files/${fileId}`, {
251
+ headers: { 'Authorization': `Bearer ${this.token}` },
252
+ });
253
+ if (!resp.ok)
254
+ throw new Error(`Failed to download file ${fileId}: ${resp.status}`);
255
+ const dir = path.dirname(destPath);
256
+ if (!fs.existsSync(dir))
257
+ fs.mkdirSync(dir, { recursive: true });
258
+ const buffer = Buffer.from(await resp.arrayBuffer());
259
+ fs.writeFileSync(destPath, buffer);
260
+ log.info(`Downloaded file ${fileId} to ${destPath} (${buffer.length} bytes)`);
261
+ return destPath;
262
+ }
263
+ async sendFile(channelId, filePath, message, opts) {
264
+ const baseUrl = this.client.getBaseRoute();
265
+ const fileName = path.basename(filePath);
266
+ // Async read to avoid blocking the event loop
267
+ const fileBuffer = await fs.promises.readFile(filePath);
268
+ // Upload the file
269
+ const form = new FormData();
270
+ form.append('files', new Blob([fileBuffer]), fileName);
271
+ form.append('channel_id', channelId);
272
+ const uploadResp = await fetch(`${baseUrl}/files`, {
273
+ method: 'POST',
274
+ headers: { 'Authorization': `Bearer ${this.token}` },
275
+ body: form,
276
+ });
277
+ if (!uploadResp.ok)
278
+ throw new Error(`Failed to upload file: ${uploadResp.status}`);
279
+ const uploadResult = await uploadResp.json();
280
+ const fileIds = uploadResult.file_infos.map(f => f.id);
281
+ // Create post with the file
282
+ const post = await this.client.createPost({
283
+ channel_id: channelId,
284
+ message: message ?? '',
285
+ root_id: opts?.threadRootId ?? '',
286
+ file_ids: fileIds,
287
+ });
288
+ log.info(`Sent file "${fileName}" to channel ${channelId.slice(0, 8)}...`);
289
+ return post.id;
290
+ }
291
+ // --- Admin operations ---
292
+ async createChannel(opts) {
293
+ const channel = await this.client.createChannel({
294
+ team_id: opts.teamId,
295
+ name: opts.name,
296
+ display_name: opts.displayName,
297
+ type: opts.private ? 'P' : 'O',
298
+ });
299
+ log.info(`Created ${opts.private ? 'private' : 'public'} channel "${opts.name}" (${channel.id})`);
300
+ return channel.id;
301
+ }
302
+ async addUserToChannel(channelId, userId) {
303
+ try {
304
+ await this.client.addToChannel(userId, channelId);
305
+ }
306
+ catch (err) {
307
+ // If user isn't on the team, add them to the team first
308
+ if (err?.server_error_id === 'app.team.get_member.missing.app_error') {
309
+ const baseUrl = this.client.getBaseRoute();
310
+ // Get the channel's team ID
311
+ const chResp = await fetch(`${baseUrl}/channels/${channelId}`, {
312
+ headers: { 'Authorization': `Bearer ${this.token}` },
313
+ });
314
+ if (!chResp.ok)
315
+ throw new Error(`Failed to get channel info: ${chResp.status}`);
316
+ const chData = await chResp.json();
317
+ // Add user to team
318
+ await this.client.addToTeam(chData.team_id, userId);
319
+ log.info(`Added user ${userId} to team ${chData.team_id}`);
320
+ // Retry adding to channel
321
+ await this.client.addToChannel(userId, channelId);
322
+ }
323
+ else {
324
+ throw err;
325
+ }
326
+ }
327
+ log.info(`Added user ${userId} to channel ${channelId.slice(0, 8)}...`);
328
+ }
329
+ async getTeams() {
330
+ const teams = await this.client.getMyTeams();
331
+ return teams.map((t) => ({
332
+ id: t.id,
333
+ name: t.name,
334
+ displayName: t.display_name,
335
+ }));
336
+ }
337
+ async getChannelByName(teamId, name) {
338
+ try {
339
+ const channel = await this.client.getChannelByName(teamId, name);
340
+ return {
341
+ id: channel.id,
342
+ name: channel.name,
343
+ displayName: channel.display_name,
344
+ type: channel.type,
345
+ teamId: channel.team_id,
346
+ };
347
+ }
348
+ catch (err) {
349
+ if (err?.status_code === 404)
350
+ return null;
351
+ throw err;
352
+ }
353
+ }
354
+ handleReaction(msg) {
355
+ try {
356
+ const reaction = JSON.parse(msg.data.reaction);
357
+ const inbound = {
358
+ platform: this.platform,
359
+ channelId: msg.broadcast?.channel_id ?? '',
360
+ userId: reaction.user_id,
361
+ postId: reaction.post_id,
362
+ emoji: reaction.emoji_name,
363
+ action: msg.event === 'reaction_added' ? 'added' : 'removed',
364
+ };
365
+ for (const handler of this.reactionHandlers) {
366
+ try {
367
+ const result = handler(inbound);
368
+ if (result && typeof result.catch === 'function') {
369
+ result.catch((err) => log.error('Reaction handler error:', err));
370
+ }
371
+ }
372
+ catch (err) {
373
+ log.error('Reaction handler error:', err);
374
+ }
375
+ }
376
+ }
377
+ catch (err) {
378
+ log.error('Failed to parse reaction event:', err);
379
+ }
380
+ }
381
+ /** Track a post ID and its channel for deduplication and replay targeting. */
382
+ trackPost(postId, channelId, serverTimestamp) {
383
+ this.activeChannels.set(channelId, Date.now());
384
+ this.recentPostIds.add(postId);
385
+ // Track server-side timestamp for clock-skew-immune replay
386
+ if (serverTimestamp && (!this.lastServerTimestamp || serverTimestamp > this.lastServerTimestamp)) {
387
+ this.lastServerTimestamp = serverTimestamp;
388
+ }
389
+ // Bound the set to prevent unbounded growth
390
+ if (this.recentPostIds.size > MattermostAdapter.MAX_RECENT_POSTS) {
391
+ const iter = this.recentPostIds.values();
392
+ for (let i = 0; i < 100; i++) {
393
+ const val = iter.next().value;
394
+ if (val != null)
395
+ this.recentPostIds.delete(val);
396
+ }
397
+ }
398
+ }
399
+ /** Fetch and replay messages missed during a WebSocket disconnect. */
400
+ async replayMissedMessages(sinceTimestamp, gapMs) {
401
+ if (gapMs > MattermostAdapter.MAX_REPLAY_WINDOW_MS) {
402
+ log.warn(`Disconnect lasted ${(gapMs / 1000).toFixed(1)}s (>${MattermostAdapter.MAX_REPLAY_WINDOW_MS / 1000}s cap) — skipping replay`);
403
+ return;
404
+ }
405
+ // Concurrency guard: queue latest replay request if one is in progress
406
+ if (this.isReplaying) {
407
+ log.info('Replay in progress — queuing latest reconnect for retry');
408
+ this.pendingReplay = { sinceTimestamp, gapMs };
409
+ return;
410
+ }
411
+ this.isReplaying = true;
412
+ try {
413
+ // Filter to recently active channels only
414
+ const now = Date.now();
415
+ const channels = Array.from(this.activeChannels.entries())
416
+ .filter(([, lastActivity]) => now - lastActivity < MattermostAdapter.CHANNEL_STALENESS_MS)
417
+ .map(([id]) => id);
418
+ if (channels.length === 0) {
419
+ log.info('No active channels to replay');
420
+ return;
421
+ }
422
+ log.info(`Replaying missed messages for ${channels.length} channel(s), gap=${(gapMs / 1000).toFixed(1)}s`);
423
+ // Pre-fetch channel types for isDM detection
424
+ const channelTypes = new Map();
425
+ for (const channelId of channels) {
426
+ try {
427
+ const baseUrl = this.client.getBaseRoute();
428
+ const resp = await fetch(`${baseUrl}/channels/${channelId}`, {
429
+ headers: { 'Authorization': `Bearer ${this.token}` },
430
+ });
431
+ if (resp.ok) {
432
+ const ch = await resp.json();
433
+ channelTypes.set(channelId, ch.type);
434
+ }
435
+ }
436
+ catch { /* best effort */ }
437
+ }
438
+ // Cache for user lookups
439
+ const usernames = new Map();
440
+ let replayCount = 0;
441
+ for (const channelId of channels) {
442
+ try {
443
+ const baseUrl = this.client.getBaseRoute();
444
+ const resp = await fetch(`${baseUrl}/channels/${channelId}/posts?since=${sinceTimestamp}`, { headers: { 'Authorization': `Bearer ${this.token}` } });
445
+ if (!resp.ok) {
446
+ log.warn(`Failed to fetch posts for channel ${channelId.slice(0, 8)}: ${resp.status}`);
447
+ continue;
448
+ }
449
+ const data = await resp.json();
450
+ // Process in chronological order (order is newest-first)
451
+ const postIds = [...(data.order ?? [])].reverse();
452
+ for (const postId of postIds) {
453
+ if (this.recentPostIds.has(postId))
454
+ continue;
455
+ const post = data.posts[postId];
456
+ if (!post || post.user_id === this.botId)
457
+ continue;
458
+ if (post.delete_at > 0)
459
+ continue;
460
+ this.trackPost(postId, channelId, post.create_at);
461
+ // Resolve username (cached)
462
+ let username = usernames.get(post.user_id) ?? '';
463
+ if (!username) {
464
+ try {
465
+ const userResp = await fetch(`${baseUrl}/users/${post.user_id}`, {
466
+ headers: { 'Authorization': `Bearer ${this.token}` },
467
+ });
468
+ if (userResp.ok) {
469
+ const user = await userResp.json();
470
+ username = user.username;
471
+ usernames.set(post.user_id, username);
472
+ }
473
+ }
474
+ catch { /* best effort */ }
475
+ }
476
+ const channelType = channelTypes.get(channelId) ?? '';
477
+ const isDM = channelType === 'D' || channelType === 'G';
478
+ const mentionsBot = isDM || post.message?.includes(`@${this.botUsername}`);
479
+ const inbound = {
480
+ platform: this.platform,
481
+ channelId: post.channel_id,
482
+ userId: post.user_id,
483
+ username,
484
+ text: post.message ?? '',
485
+ postId: post.id,
486
+ threadRootId: post.root_id || undefined,
487
+ mentionsBot,
488
+ isDM,
489
+ attachments: this.extractAttachments(post),
490
+ };
491
+ log.info(`Replaying missed post ${postId.slice(0, 8)} from ${username || 'unknown'} in channel ${channelId.slice(0, 8)}`);
492
+ for (const handler of this.messageHandlers) {
493
+ try {
494
+ const result = handler(inbound);
495
+ if (result && typeof result.catch === 'function') {
496
+ result.catch((err) => log.error('Replay handler error:', err));
497
+ }
498
+ }
499
+ catch (err) {
500
+ log.error('Replay handler error:', err);
501
+ }
502
+ }
503
+ replayCount++;
504
+ }
505
+ }
506
+ catch (err) {
507
+ log.error(`Error replaying channel ${channelId.slice(0, 8)}:`, err);
508
+ }
509
+ }
510
+ log.info(`Replay complete: ${replayCount} message(s) replayed across ${channels.length} channel(s)`);
511
+ }
512
+ finally {
513
+ this.isReplaying = false;
514
+ // Process queued replay if a newer reconnect occurred during this replay
515
+ const pending = this.pendingReplay;
516
+ if (pending) {
517
+ this.pendingReplay = null;
518
+ log.info('Processing queued replay from concurrent reconnect');
519
+ this.replayMissedMessages(pending.sinceTimestamp, pending.gapMs).catch(err => log.error('Failed to process queued replay:', err));
520
+ }
521
+ }
522
+ }
523
+ }
524
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+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CAAC,kCAAkC,EAAE,GAAG,CAAC,CACnD,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC"}
@@ -0,0 +1,29 @@
1
+ import type { ChannelAdapter } from '../../types.js';
2
+ export declare class StreamingHandler {
3
+ private adapter;
4
+ private activeStreams;
5
+ private throttleMs;
6
+ constructor(adapter: ChannelAdapter, throttleMs?: number);
7
+ /** Start a new streaming response. Posts initial placeholder and returns stream key. */
8
+ startStream(channelId: string, threadRootId?: string, initialContent?: string): Promise<string>;
9
+ /** Append delta content to a stream. Updates are throttled. */
10
+ appendDelta(streamKey: string, delta: string): void;
11
+ /** Replace the entire stream content (for non-delta updates). */
12
+ replaceContent(streamKey: string, content: string): void;
13
+ /** Finalize the stream with the complete content. */
14
+ finalizeStream(streamKey: string, finalContent?: string): Promise<void>;
15
+ /** Cancel and clean up a stream. */
16
+ cancelStream(streamKey: string, errorMessage?: string): Promise<void>;
17
+ /** Get the message ID for a stream (useful for threading). */
18
+ getStreamMessageId(streamKey: string): string | undefined;
19
+ /** Get current content of a stream (undefined if not found). */
20
+ getStreamContent(streamKey: string): string | undefined;
21
+ /** Get the thread root ID for a stream. */
22
+ getStreamThreadRootId(streamKey: string): string | undefined;
23
+ /** Delete a stream's message and clean up without posting anything. */
24
+ deleteStream(streamKey: string): Promise<void>;
25
+ private flushUpdate;
26
+ /** Clean up all active streams. */
27
+ cleanup(): Promise<void>;
28
+ }
29
+ //# sourceMappingURL=streaming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../src/channels/mattermost/streaming.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAIrD,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,OAAO,CAAiB;IAChC,OAAO,CAAC,aAAa,CAOhB;IAEL,OAAO,CAAC,UAAU,CAAS;gBAEf,OAAO,EAAE,cAAc,EAAE,UAAU,SAAM;IAKrD,wFA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