Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1615 lines (1541 loc) · 66.9 KB
/
Copy pathindex.js
File metadata and controls
1615 lines (1541 loc) · 66.9 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const answerTrace = require('./answerTrace');
require('dotenv').config();
const { Client, GatewayIntentBits, Events, Partials } = require('discord.js');
const express = require('express');
const db = require('./db');
const { queryAgent, reviewAnswer, understandQuestion, contextualQuestion, officialHandoffLinks } = require('./commandcode');
const { splitHistory } = require('./supportContextFormat');
const telegram = require('./telegram');
const {
isOnCooldown,
markReplied,
wasRecentlyAnsweredText,
markAnsweredText,
typingDelay,
clipForDiscord,
clipThreadHistory,
escalateReply,
inThreadReply,
rewriteUserMentions,
wantsAuthorPing,
attachAuthorMention,
replyMentions,
isUnknownMessageRef,
} = require('./utils');
const { hasUsableAttachment, fetchTextAttachments, formatQuestion, shouldMentionUnreadMedia, unreadMediaSentence, imageErrorLines, videoErrorLines, chatFiles } = require('./attachments');
const {
notifyStaff,
sendToStaffChannel,
canNotifyStaff,
isHandoffThread,
isHelpForumThread,
clipUserQuestion,
canSaveFaq,
applyThreadName,
staffMentionIds,
findOpenHandoff,
rememberOpenHandoff,
shouldReuseOpenHandoff,
forumStarterPrefix,
threadHasKnownIssueTag,
} = require('./handoff');
const knowledge = require('./knowledge');
const shopify = require('./shopify');
const shopifyBind = require('./shopifyBind');
const orderFlow = require('./orderFlow');
const { publicReplyPrivacy } = require('./publicReplyPrivacy');
const router = require('./router');
const plannerPolicy = require('./plannerPolicy');
const { decideEscalation } = require('./escalationPolicy');
const github = require('./github');
const commands = require('./commands');
const { buildToolFacts, OFFICIAL } = require('./prompt');
const { relevantDocs, canonicalizeGithubDocsEvidence } = require('./docs');
const { relevantFeedback } = require('./feedback');
const { combineEvidence } = require('./retrieval');
const { matchingRelease } = require('./releases');
const { prepareDraftForReview, prepareDraftForReviewWithAudit, presentReviewedAnswer, fitPublicReply, ensureNonEmptyAnswer, addUnsyncedDataWarning, hasUnsyncedDataRisk, stripUnverifiedOrderClaims } = require('./answerPipeline');
const { getRemovalAudit } = require('./answerFilterAudit');
const { newUsageCounters, addStageUsage, timingLogLine } = require('./timing');
const { approvedReview, reviewWithSecondLook } = require('./reviewDecision');
const { reviewRejectionReply } = require('./supportReplyCopy');
const githubNotices = require('./githubNoticeReceipts');
const { recordStage } = require('./answerStageEvidence');
const triage = require('./triage');
const supportCases = require('./supportCases');
const { isDedicatedCustomerThread } = require('./customerThreadScope');
const supportIssueLinks = require('./supportIssueLinks');
const githubFlow = require('./githubFlow').createGithubFlow();
const supportThreadLanguage = require('./supportThreadLanguage');
const caseCards = require('./caseCards');
const staffDestination = require('./staffDestination');
const { ensureSupportIdentity } = require('./supportVoice');
const supportLearning = require('./supportLearning');
const learning = () => supportLearning.getObserver(client.user?.id);
const observeSupport = operation => {
const observer = learning();
if (!observer.enabled) return;
runtime.track(() => operation(observer)).catch(() => console.error('[SupportMemory] optional observation failed'));
};
const { SupportRuntime, PostgresRuntimeStore, MemoryRuntimeStore, questionFingerprint, assertCurrentOwnership, markCurrentReplySent, isLeaseLost } = require('./supportRuntime');
const HELP_FORUM_CHANNEL_ID = process.env.HELP_FORUM_CHANNEL_ID;
const VECTOR_TEST_CHANNEL_ID = process.env.VECTOR_TEST_CHANNEL_ID;
const PORT = process.env.PORT || 3000;
const KNOWLEDGE_REFRESH_MS = 6 * 60 * 60 * 1000;
const telegramReady = Boolean(process.env.TELEGRAM_TOKEN && process.env.TELEGRAM_CHAT_ID);
const dbReady = Boolean(process.env.DATABASE_URL);
const runtime = new SupportRuntime({ store: dbReady ? new PostgresRuntimeStore(db.pool) : new MemoryRuntimeStore() });
// Cosmetic status-note suppression only, never an answer claim or DB fallback.
// Background recovery never repeats intake notes, including after a restart.
const outageNoteAttempts = new Map();
function attemptOutageNote(messageId) {
const now = Date.now();
for (const [id, at] of outageNoteAttempts) if (now - at >= 24 * 60 * 60_000) outageNoteAttempts.delete(id);
if (outageNoteAttempts.has(messageId)) return false;
outageNoteAttempts.set(messageId, now);
if (outageNoteAttempts.size > 1000) outageNoteAttempts.delete(outageNoteAttempts.keys().next().value);
return true;
}
let coordinationReady = !dbReady;
let httpServer;
let shutdownPromise;
let recoveryTimer;
let caseCardTimer;
let unsubscribeCaseCards;
let supportMemoryTimer;
let threadLanguageTimer;
let knowledgeCleanup, noticeCleanup;
const { createKnowledgeCleanup } = require('./knowledgeCleanup');
const BOT_REPLY_MEMORY_MAX = 2000;
const BOT_REPLY_MEMORY_MS = 24 * 60 * 60 * 1000;
const botReplyOwners = new Map();
const client = new Client({
partials: [Partials.Message],
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const app = express();
app.get('/health', (_req, res) => {
const ready = client.isReady() && coordinationReady && !runtime.stopping;
res.status(ready ? 200 : 503).json({
status: ready ? 'ok' : 'not_ready',
staffHandoff: process.env.STAFF_ALERT_CHANNEL_ID || telegram.isReady() ? 'configured' : 'missing',
});
});
app.get('/ratings', async (_req, res) => {
try {
const { ratingCounts } = require('./ratings');
const counts = await ratingCounts();
res.type('html').send(`<!doctype html>
<meta charset="utf-8">
<title>Omi Support ratings</title>
<body style="font-family: Georgia, serif; background:#111; color:#f4f1ea; margin:48px;">
<h1>Did this help?</h1>
<p>Answers from the customer who opened the post.</p>
<p style="font-size:32px;">Helpful: ${counts.yes}</p>
<p style="font-size:32px;">Still need help: ${counts.no}</p>
</body>`);
} catch {
console.error('[Bot] support feedback totals unavailable');
res.status(503).type('text').send('Support feedback totals are temporarily unavailable.');
}
});
app.post('/github-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.body || '');
if (!github.verifyWebhook(raw, req.headers['x-hub-signature-256'])) {
res.status(401).send('bad signature');
return;
}
let payload;
try {
payload = JSON.parse(raw.toString('utf8'));
} catch {
res.status(400).send('bad json');
return;
}
if (!github.webhookRepoOk(payload)) {
res.send('ok');
return;
}
const event = github.describeWebhookEvent(payload);
if (event) {
const deliveryId = req.headers['x-github-delivery'];
const expectedType = payload.pull_request ? 'pull_request' : payload.comment ? 'issue_comment' : 'issues';
if (!githubNotices.validDeliveryId(deliveryId) || req.headers['x-github-event'] !== expectedType) {
res.status(400).send('invalid delivery headers');
return;
}
const occurredAt = githubNotices.eventTimestamp(payload);
if (occurredAt === null || occurredAt > Date.now() + 5 * 60000) return res.status(400).json({ error: 'invalid_event_time' });
if (!githubNotices.recent(occurredAt)) return res.status(200).json({ ok: true, ignored: 'expired_event' });
try {
await commands.notifyLinkedThreads(client, { ...event, deliveryId, occurredAt });
} catch {
console.error('[GitHub] webhook notice coordination unavailable');
res.status(503).send('notice coordination unavailable');
return;
}
}
res.send('ok');
});
function rememberBotReply(sent, message) {
const replyId = String(sent?.id || '');
const customerId = String(message?.author?.id || '');
const channelId = String(message?.channel?.id || '');
if (!replyId || !customerId || !channelId) return;
const now = Date.now();
botReplyOwners.set(replyId, { customerId, channelId, at: now });
for (const [id, item] of botReplyOwners) {
if (botReplyOwners.size <= BOT_REPLY_MEMORY_MAX && now - item.at <= BOT_REPLY_MEMORY_MS) break;
botReplyOwners.delete(id);
}
}
// Discord hides a typing indicator after about ten seconds, while a reviewed
// answer takes far longer. Keep it visible until the first reply. It is only a
// courtesy: a failed typing call must never cost the customer their answer.
const TYPING_REFRESH_MS = 8_000;
const typingStops = new WeakMap();
function keepTyping(message, channel, intervalMs = TYPING_REFRESH_MS) {
let stopped = false;
const ping = () => {
if (stopped || typeof channel?.sendTyping !== 'function') return;
Promise.resolve().then(() => channel.sendTyping()).catch(() => {});
};
const timer = setInterval(ping, intervalMs);
timer.unref?.();
const stop = () => { stopped = true; clearInterval(timer); typingStops.delete(message); };
typingStops.set(message, stop);
ping();
return stop;
}
async function replySafe(message, content, { pingAuthor = false, privacy = {} } = {}) {
typingStops.get(message)?.();
await assertCurrentOwnership();
recordStage('send_input', content);
const guarded = publicReplyPrivacy(content, { question: message.content, orderAvailable: orderFlow.isLive(), ...privacy });
answerTrace.filter('final_privacy', content, guarded.text);
let text = ensureNonEmptyAnswer(rewriteUserMentions(ensureNonEmptyAnswer(fitPublicReply(guarded)), message));
if (pingAuthor) text = attachAuthorMention(text, message);
recordStage('send_payload', text);
const payload = {
content: text,
allowedMentions: replyMentions(message, { pingAuthor, repliedUser: false }),
};
answerTrace.delivery('reply', 'attempted');
try {
const sent = await message.reply({
...payload,
allowedMentions: replyMentions(message, { pingAuthor, repliedUser: true }),
});
answerTrace.delivery('reply', 'confirmed');
answerTrace.stage('delivery', 'ok');
markCurrentReplySent();
rememberBotReply(sent, message);
return sent;
} catch (err) {
if (!isUnknownMessageRef(err) || typeof message.channel?.send !== 'function') {
throw err;
}
console.error('[Bot] reply reference missing, sending in channel:', err.message);
const sent = await message.channel.send(payload);
answerTrace.delivery('reply', 'confirmed');
answerTrace.stage('delivery', 'ok');
markCurrentReplySent();
rememberBotReply(sent, message);
return sent;
}
}
function isHelpThread(channel) {
return isHelpForumThread(channel);
}
function isTestChannel(channel) {
if (!VECTOR_TEST_CHANNEL_ID) return false;
if (channel.id === VECTOR_TEST_CHANNEL_ID) return true;
return channel.isThread() && channel.parentId === VECTOR_TEST_CHANNEL_ID;
}
function isTrustedHandoffThread(channel) {
if (!isHandoffThread(channel)) return false;
if (isTestChannel(channel)) return true;
const ownerId = String(channel?.ownerId || channel?.owner_id || '');
return Boolean(ownerId && ownerId === String(client.user?.id || ''));
}
function memberHasRole(member, roleIds) {
const roles = member?.roles?.cache;
if (!roles || !roleIds.length) return false;
if (typeof roles.has === 'function') return roleIds.some((id) => roles.has(id));
if (typeof roles.includes === 'function') return roleIds.some((id) => roles.includes(id));
return false;
}
function memberCanModerate(member) {
const permissions = member?.permissions;
if (!permissions || typeof permissions.has !== 'function') return false;
try {
return (
permissions.has('ManageThreads', true) ||
permissions.has('ManageMessages', true) ||
permissions.has('Administrator', true)
);
} catch {
return false;
}
}
function isStaffMessage(message) {
const { users, roles } = staffMentionIds();
return (
users.includes(String(message.author?.id || '')) ||
memberHasRole(message.member, roles) ||
memberCanModerate(message.member)
);
}
function messageCaption(content) {
return String(content || '')
.replace(/<@!?\d+>|<@&\d+>|<#\d+>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function directlyMentionsBot(content) {
const id = String(client.user?.id || '');
if (!/^\d+$/.test(id)) return false;
return String(content || '').includes(`<@${id}>`) || String(content || '').includes(`<@!${id}>`);
}
function isActionableMessage(message) {
const caption = messageCaption(message.content);
if (/^\/[a-z][\w-]*(?:\s|$)/i.test(caption)) return false;
if (caption.length < 5 && !hasUsableAttachment(message) && !forumStarterPrefix(message)) return false;
if (/^(thanks|thank you|thx|ok|okay|got it|cool|lol|ty|hello|hi|hey)[.!\s]*$/i.test(caption)) return false;
if (
/^(?:(?:sweet|great|awesome|perfect|nice|cool|okay|ok|got it)[,!.\s]+)*(?:thanks(?:\s+(?:a lot|so much))?|thank you(?:\s+so much)?|thx|ty)[.!\s]*$/i.test(
caption
)
) {
return false;
}
const hasAttachment = Number(message.attachments?.size || 0) > 0;
if (!hasAttachment && (isIdentifierOnlyUpdate(caption) || isDeliveryAcknowledgment(caption))) {
return false;
}
return true;
}
function isIdentifierOnlyUpdate(text) {
const value = String(text || '').trim();
if (!value || !/\d/.test(value)) return false;
const remainder = value
.replace(/\b(?:ticket|case|request|order)\b/gi, ' ')
.replace(/\b(?:number|no\.?|id)\b/gi, ' ')
.replace(/[#,:;()[\]]/g, ' ')
.trim();
const tokens = remainder.match(/[A-Za-z0-9-]+/g) || [];
return Boolean(tokens.length) && tokens.every((token) => /\d/.test(token));
}
function isDeliveryAcknowledgment(text) {
const value = String(text || '').trim();
if (!value || /[?]/.test(value)) return false;
const sending =
/\b(?:i(?:['’]ll|\s+will|['’]m|\s+am)\s+(?:send|email|attach|upload|provide|share)|i(?:['’]ve|\s+have)\s+(?:sent|emailed|attached|uploaded|provided|shared))\b/i.test(
value
);
if (!sending) return false;
return !/\b(?:still|waiting|no (?:reply|response|answer)|problem|issue|error|fail(?:ed|ing)?|crash(?:ed|ing)?|not working|doesn['’]?t|cannot|can['’]?t|won['’]?t|help)\b/i.test(
value
);
}
function shouldHandle(message) {
if (message.author.bot) return false;
// Staff replies in live support threads are interventions, not new customer
// questions. Keep #vector-test available for staff to exercise the bot.
if ((isTrustedHandoffThread(message.channel) || isHelpThread(message.channel)) && isStaffMessage(message)) {
return false;
}
if (!isActionableMessage(message)) return false;
if (isTrustedHandoffThread(message.channel)) {
if (isTestChannel(message.channel)) return true;
const { users } = staffMentionIds();
if (users.length && canSaveFaq(message.author.id)) return false;
return true;
}
if (isTestChannel(message.channel)) return true;
if (isHelpThread(message.channel)) return true;
if (directlyMentionsBot(message.content)) return true;
return false;
}
async function fetchReferencedMessage(message) {
if (!message?.reference?.messageId && typeof message?.fetchReference !== 'function') return null;
try {
if (typeof message.fetchReference === 'function') return await message.fetchReference();
} catch {
return null;
}
const id = String(message.reference?.messageId || '');
if (!id) return null;
const cached = message.channel?.messages?.cache?.get?.(id);
if (cached) return cached;
try {
return await message.channel?.messages?.fetch?.(id);
} catch {
return null;
}
}
async function repliesToDifferentHuman(message) {
if (!message?.reference?.messageId && typeof message?.fetchReference !== 'function') return false;
const referenced = await fetchReferencedMessage(message);
if (!referenced || referenced.author?.bot) return false;
const targetId = String(referenced.author?.id || '');
const authorId = String(message.author?.id || '');
return Boolean(targetId && authorId && targetId !== authorId);
}
async function directContinuationHistory(message) {
if (!isActionableMessage(message) || directlyMentionsBot(message.content)) return [];
if (
isHelpThread(message.channel) ||
isTrustedHandoffThread(message.channel) ||
isTestChannel(message.channel)
) {
return [];
}
const referenced = await fetchReferencedMessage(message);
if (String(referenced?.author?.id || '') !== String(client.user?.id || '')) return [];
const replyId = String(referenced.id || message.reference?.messageId || '');
const remembered = botReplyOwners.get(replyId);
let original = null;
if (remembered) {
if (
remembered.customerId !== String(message.author?.id || '') ||
remembered.channelId !== String(message.channel?.id || '') ||
Date.now() - remembered.at > BOT_REPLY_MEMORY_MS
) {
return [];
}
} else {
original = await fetchReferencedMessage(referenced);
if (String(original?.author?.id || '') !== String(message.author?.id || '')) return [];
}
if (!original) {
original = await fetchReferencedMessage(referenced);
}
const entries = [];
const originalText = messageCaption(original?.content || '');
if (originalText) {
entries.push({ author: original?.author?.username || 'customer', content: originalText });
}
const botText = String(referenced.content || '').trim();
if (botText) entries.push({ author: 'bot', content: botText });
return clipThreadHistory(entries);
}
async function hasEarlierMessages(channel, messageId) {
if (!channel?.isThread?.()) return false;
try {
const messages = await channel.messages.fetch({ limit: 12 });
return [...messages.values()].some((m) => m.id !== messageId);
} catch {
return false;
}
}
async function getHistory(channel, excludeId, customerId) {
// Parent #vector-test is a pile of unrelated tickets. Only follow-ups
// inside an existing Handoff or help post may see prior messages.
const samePost = channel.isThread?.() && (isHelpThread(channel) || isTestChannel(channel));
if (!isTrustedHandoffThread(channel) && !samePost) return [];
const messages = await channel.messages.fetch({ limit: 50 });
if (learning().contextEnabled && learning().supports(channel)) return clipThreadHistory(await learning().history(channel, excludeId, [...messages.values()], customerId));
const entries = [...messages.values()]
.reverse()
.filter((m) => m.id !== excludeId)
.map((m) => ({
author: m.author.bot ? 'bot' : m.author.username,
content: m.content,
}));
return clipThreadHistory(entries);
}
async function searchKnowledge(question, guildId) {
// Legacy database notes have no author/provenance field, so do not expose
// them to the model until they can be reviewed or migrated.
return knowledge.searchForAnswers(question, { guildId });
}
async function handleFaqSave(message) {
if (message.author?.bot) return false;
if (!isTrustedHandoffThread(message.channel)) return false;
const commanded = knowledge.parseFaqCommand(message.content);
const snippet = commanded;
if (!snippet) return false;
if (!canSaveFaq(message.author.id)) {
try {
await replySafe(message, 'Only named staff can save a faq line.');
} catch (err) {
console.error('[Knowledge] reply failed:', err.message);
}
return true;
}
const saved = knowledge.addSnippet(snippet);
if (!saved.ok) {
const why =
saved.reason === 'lie'
? 'I will not save that. It claims a ping I did not make.'
: saved.reason === 'stale'
? 'Order lookup is already on. I will not save that I cannot see Shopify.'
: 'Nothing to save. Use `faq: short true sentence`.';
try {
await replySafe(message, why);
} catch (err) {
console.error('[Knowledge] reply failed:', err.message);
}
return true;
}
try {
await replySafe(message, 'Saved as a staff note. Answers still require official-source review.');
} catch (err) {
console.error('[Knowledge] reply failed:', err.message);
}
return true;
}
async function noteCustomerLead(channel, message) {
if (!github.isConfigured() || !github.isApprovalReady() || !channel.isThread?.() ||
!github.isImportantLead(message.content, message.attachments)) return;
try {
const value = await supportCases.getCaseByThread(channel.id, message.author.id);
if (!value || value.customerId !== String(message.author.id)) return;
if (!(await isDedicatedCustomerThread(channel, value))) return;
const rows = await supportIssueLinks.listForThread(value.id, github.repo(), channel.id);
const linked = [...new Map(rows.filter((row) => row.customerId === String(message.author.id))
.map((row) => [`${row.repo}:${row.issueNumber}`, row])).values()];
if (linked.length !== 1) return;
const approval = await githubFlow.prepare({ message, client, supportCase: value, kind: 'comment', issueNumber: linked[0].issueNumber });
if (!approval || approval.created !== true || approval.cardMessageId || approval.status !== 'pending') return;
const payload = githubFlow.approvalCard(approval, message.url);
await sendToStaffChannel(client, payload, channel.id, null, { onSent: async (sent) => { await githubFlow.bindCard(approval, sent); } });
} catch (err) {
if (isLeaseLost(err)) throw err;
console.error('[GitHubFlow] customer update staging failed');
}
}
async function postIssueCard(channel, draft, githubHit) {
if (!channel?.send || !draft) return;
const url = githubHit?.duplicate?.url || '';
try {
await assertCurrentOwnership();
await channel.send({ embeds: [github.formatIssueCard(draft, { url })] });
} catch (err) {
if (isLeaseLost(err)) throw err;
console.error('[Bot] issue card failed:', err.message);
}
}
async function postShopTicketCard(channel, triaged) {
if (!channel?.send || !triaged) return;
try {
await assertCurrentOwnership();
await channel.send({
embeds: [
github.formatShopTicketCard({
title: triaged.topic,
labels: triaged.labels,
}),
],
});
} catch (err) {
if (isLeaseLost(err)) throw err;
console.error('[Bot] shop ticket card failed:', err.message);
}
}
function redactStaffQuestion(text) {
const orders = [];
let s = String(text || '')
.replace(/\s*\n+\s*/g, ' ')
.trim()
.replace(/#\d{3,}/g, (match) => {
orders.push(match);
return `§${orders.length - 1}§`;
});
s = s.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '[email]');
s = s.replace(
/\b\d{1,5}\s+(?:(?:[A-Za-z][A-Za-z.'-]*|\d{1,3}(?:st|nd|rd|th))\s+){0,4}(?:street|st|avenue|ave|road|rd|blvd)\b\.?/gi,
'[address]'
);
s = s.replace(/(?<![\d#])\+?(?:\d[\s().-]*){6,14}\d(?!\d)/g, (match) => {
const digits = match.replace(/\D/g, '');
if (digits.length < 7 || digits.length > 15) return match;
return '[phone]';
});
return s.replace(/§(\d+)§/g, (_, i) => orders[Number(i)] || '');
}
async function handleMessage(message, { recovery = false } = {}) {
if (runtime.stopping || !coordinationReady) return { status: 'stopping' };
// Observe quiet staff/customer continuations too, without making them reply
// triggers. The observer independently enforces its approved forum boundary.
observeSupport(observer => observer.capture(message));
if (
!directlyMentionsBot(message.content) &&
(isHelpThread(message.channel) || isTrustedHandoffThread(message.channel)) &&
(await repliesToDifferentHuman(message))
) {
return { status: 'ignored' };
}
let directHistory = [];
if (!shouldHandle(message)) {
directHistory = await directContinuationHistory(message);
if (!directHistory.length) return { status: 'ignored' };
}
if (
message.channel?.isThread?.() &&
wasRecentlyAnsweredText(message.channel.id, message.author?.id, message.content)
) {
return { status: 'ignored' };
}
const channel = message.channel;
const replyCooldownKey = `${channel.id}:${message.author.id}`;
// In ordinary channels, rate-limit each customer independently. A direct
// reply continuation may proceed immediately; it is already opt-in scoped.
if (
!directHistory.length &&
isOnCooldown(replyCooldownKey) &&
!isTestChannel(channel) &&
!channel.isThread?.()
) {
console.log(`[Bot] Cooldown active for ${channel.id}, skipping`);
return { status: 'ignored' };
}
const input = {
messageId: message.id,
caseKey: replyCooldownKey,
fingerprint: channel.isThread?.() ? questionFingerprint(message.content) : null,
};
let workStarted = false;
try {
return await runtime.run(input, () => {
workStarted = true;
// A concurrently queued ordinary-channel question must observe the
// reply cooldown established by the preceding job, not its arrival time.
if (!directHistory.length && !isTestChannel(channel) && !channel.isThread?.() && isOnCooldown(replyCooldownKey)) return false;
return answerMessage(message, { directHistory });
});
} catch (err) {
console.error('[SupportRuntime] request coordination failed');
// Answers and uncertain sends always keep their ownership fence. A fixed
// pre-work outage note is not an answer or proof that the request was saved.
if (workStarted || err.replyAlreadySent || err?.message === 'support lease lost' || recovery ||
!attemptOutageNote(message.id)) return { status: 'failed' };
try {
// Do not require the unavailable database to report its own outage, and
// never retire a recoverable claim because this informational note sent.
await answerTrace.run(async () => {
answerTrace.delivery('reply', 'attempted');
await message.reply({
content: 'I am having trouble saving this support request. Please email help@omi.me so the team can receive it.',
allowedMentions: { parse: [], repliedUser: false },
});
answerTrace.delivery('reply', 'confirmed');
});
} catch { console.error('[SupportRuntime] outage note delivery unavailable'); }
return { status: 'failed' };
}
}
async function recoverQueuedRequest(input) {
const [channelId, customerId] = input.caseKey.split(':');
try {
const channel = await client.channels.fetch(channelId);
const message = await channel?.messages?.fetch?.(input.messageId);
if (!message || String(message.author?.id) !== customerId || !shouldHandle(message)) {
// Direct-reply continuations also require their original customer proof.
if (!message || String(message.author?.id) !== customerId || !(await directContinuationHistory(message)).length) {
await runtime.store.discard(input); return;
}
}
const result = await handleMessage(message, { recovery: true });
if (['ignored', 'duplicate'].includes(result?.status)) await runtime.store.discard(input);
} catch (err) {
if ([10003, 10008, 50001, 50013].includes(Number(err.code))) await runtime.store.discard(input);
else console.error('[SupportRuntime] queued request recovery failed');
}
}
async function answerMessage(message, options = {}) {
return answerTrace.run(() => answerMessageImpl(message, options));
}
async function answerMessageImpl(message, { directHistory = [] } = {}) {
const startedAt = performance.now();
const stageMs = { planner: 0, retrieval: 0, answer: 0, review: 0 };
const stageUsage = newUsageCounters();
const onUsage = (event) => addStageUsage(stageUsage, event);
let didReply = false;
let answered = false;
const channel = message.channel;
const caption = messageCaption(message.content);
const files = await fetchTextAttachments(message.attachments);
const read = { image: false, video: false };
if (process.env.VECTOR_OCR === '1') {
const screenText = await imageErrorLines(message.attachments);
const videoText = await videoErrorLines(message.attachments);
if (screenText) {
read.image = true;
files.push({ name: 'screen.txt', text: screenText });
}
if (videoText) {
read.video = true;
files.push({ name: 'video.txt', text: videoText });
}
}
const unreadMedia = shouldMentionUnreadMedia(message.attachments, files, read);
let asked = clipUserQuestion(caption) || caption;
const forumPrefix = forumStarterPrefix(message);
if (forumPrefix) asked = [forumPrefix, asked].filter(Boolean).join('\n');
const embedNote = github.textFromEmbeds(message.embeds);
if (embedNote) asked = [asked, embedNote].filter(Boolean).join('\n');
const question = formatQuestion(asked, files);
const changes = github.linkedChanges(question);
if (question.length < 5) {
if (unreadMedia && !changes.length) {
await assertCurrentOwnership();
answerTrace.delivery('reply', 'attempted');
await message.reply({
content: unreadMediaSentence(),
allowedMentions: replyMentions(message, { pingAuthor: false, repliedUser: false }),
}).then(() => answerTrace.delivery('reply', 'confirmed')).catch((err) => console.error('[Bot] media note failed:', err.message));
}
return;
}
console.log(`[Bot] Processing in ${channel.id}`);
const stopTyping = keepTyping(message, channel);
try {
const useThreadMetadata =
isHelpThread(channel) || isTrustedHandoffThread(channel) || isTestChannel(channel);
const routeSource = [useThreadMetadata && channel.isThread?.() ? channel.name : '', question]
.filter(Boolean)
.join('\n');
let contextHistory = directHistory;
let prior = contextHistory.map((entry) => entry.content).join('\n');
if (
channel.isThread?.() &&
(isHelpThread(channel) || isTrustedHandoffThread(channel) || isTestChannel(channel))
) {
try {
contextHistory = await getHistory(channel, message.id, message.author.id);
prior = splitHistory(contextHistory).current.map((entry) => entry.content).join('\n');
} catch (err) {
console.error('[Bot] thread context failed:', err.message);
}
}
const caseQuestion = contextualQuestion(question, contextHistory);
const routeText = [routeSource, prior].filter(Boolean).join('\n');
const groundedShop = router.needsGroundedShopAnswer(asked || question);
const classifiedCurrent = router.classify(asked || question);
const currentRoute = groundedShop
? { ...classifiedCurrent, area: 'shop', lane: 'shop', escalate: true, responseMode: 'grounded' }
: classifiedCurrent;
const contextRoute = router.classify(routeText);
const failedSelfService = splitHistory(contextHistory).current.some(entry => entry.author === 'bot') &&
router.isFailedSupportFollowup(asked || question);
// History preserves the ticket topic, but only the newest customer message
// decides whether they are currently asking for a human.
let route = {
...contextRoute,
wantHuman: Boolean(currentRoute.wantHuman),
escalate: Boolean(contextRoute.escalate || currentRoute.escalate || failedSelfService),
};
if (groundedShop) route = { ...route, area: 'shop', lane: 'shop', escalate: true, responseMode: 'grounded' };
if (plannerPolicy.suppressAcknowledgment(null, asked || question)) return;
const cannedEnglish = plannerPolicy.skipPlannerForCanned(currentRoute, asked || question);
const holdPublicCopy = isHelpThread(channel) && !router.isPublicForumSafe(asked || question);
answerTrace.route(route.lane);
let searchPlan = {
standaloneQuestion: caseQuestion,
customerGoal: asked || question,
mustAnswer: [asked || question],
customerFacts: [],
supportKind: 'other',
queries: [],
};
if (!cannedEnglish && process.env.CMD_API_KEY) {
answerTrace.stage('planner','started');
const stageStart = performance.now();
try {
searchPlan = await understandQuestion({
question: asked || question,
threadHistory: contextHistory,
route,
onUsage,
sessionId: `discord-${channel.id}-search`,
});
answerTrace.stage('planner','ok');
} catch (err) {
answerTrace.stage('planner','failed');
console.error('[Bot] search planning failed:', err.message);
} finally {
stageMs.planner += Math.round(performance.now() - stageStart);
}
}
if (plannerPolicy.suppressAcknowledgment(searchPlan, asked || question)) return;
if (plannerPolicy.suppressOffTopic(searchPlan, currentRoute)) return;
answerTrace.route(route.lane);
const replyLanguage = searchPlan.replyLanguage === 'hi'
? /\p{Script=Devanagari}/u.test(asked || question) ? 'hi-Deva' : 'hi-Latn' : searchPlan.replyLanguage || 'en';
const plannedPersonKind = cannedEnglish ? '' : plannerPolicy.personKind(searchPlan);
route = cannedEnglish
? currentRoute
: plannerPolicy.routeWithUnderstanding(route, searchPlan, asked || question);
if (groundedShop) route = { ...route, area: 'shop', lane: 'shop', escalate: true, responseMode: 'grounded' };
answerTrace.route(route.lane);
const forceGroundedPersonAnswer = Boolean(plannedPersonKind);
const cannedEnglishReply = cannedEnglish ? router.cannedReply(route, asked || question) : '';
const supportFollowup =
Boolean(currentRoute.wantHuman) || failedSelfService || router.looksLikeSupportNudge(asked || question);
const handoffPlanned = Boolean(route.escalate || forceGroundedPersonAnswer ||
searchPlan.dataLossRisk || hasUnsyncedDataRisk(asked || question));
if (holdPublicCopy) {
console.log('[Bot] PII/order/privacy stays off the public help copy');
}
if (!holdPublicCopy && router.isTechLane(route) && !changes.length) {
const found = await github.searchPulls(caseQuestion);
if (found) changes.push(found);
}
const binding = await shopifyBind.get(message.author.id);
const verifiedEmail = binding?.email || '';
const useShopify = shopify.shouldLookup(route, asked || question, { verifiedEmail });
let shopifyLookup = null;
let githubHit = null;
let fileIssueId;
let aiResponse;
let threadHistory = [];
let cleanAnswer;
let skipModel = false;
let reviewedGrounded = false;
let retrievedSourceUrls = [];
let snippets = [];
let privateIntakeNeeded = false;
const publicPrivacy = { question: [question, caseQuestion, ...contextHistory.map(row => row.content)].filter(Boolean).join('\n'),
language: replyLanguage, orderAvailable: orderFlow.isLive(), financialContext:route.lane==='money' };
const onPrivacy = value => { privateIntakeNeeded ||= value.privateIntakeNeeded; };
if (useShopify) {
shopifyLookup = await shopify.lookupOrder(asked || question, { verifiedEmail });
console.log(`[Shopify] lookup key=${shopifyLookup.reason === 'no-key' ? 'none' : 'set'} status=${shopifyLookup.reason || 'hit'}`);
}
if (!holdPublicCopy && github.isConfigured() && router.isTechLane(route)) {
githubHit = await github.searchIssues(caseQuestion);
}
const relatedPull = changes.find((change) => change.kind === 'pull');
const relatedPullLookup = relatedPull ? await github.lookupChange(relatedPull) : null;
const relatedPullEvidence = relatedPull
? [
'[Related GitHub pull request | lower priority than the Help Center, docs, and release notes; not proof of a customer fix]',
`#${relatedPull.number}: ${String(relatedPull.title || '').replace(/\s+/g, ' ').slice(0, 200)}`,
`Status: ${relatedPullLookup?.ok ? relatedPullLookup.state : 'unverified'}`,
relatedPull.url,
"Mention this only if it is directly relevant, and say: There's a related change on GitHub; I can't confirm it fixes your case.",
].join('\n')
: '';
if (holdPublicCopy || cannedEnglishReply ||
(!forceGroundedPersonAnswer && !router.requiresGroundedAnswer(route))) {
skipModel = true;
aiResponse = {
final_answer: '',
confidence: 0.9,
escalate: true,
reason: router.staffReason(route, asked || question),
};
cleanAnswer = clipForDiscord(cannedEnglishReply || router.cannedReply(route, asked || question) || '');
if (shopifyLookup?.reason) {
aiResponse.reason = aiResponse.reason || shopify.staffReason(shopifyLookup, asked || question);
}
}
if (!skipModel) {
const knowledgeSnippets = await searchKnowledge(caseQuestion, channel.guild?.id || channel.guildId || message.guildId);
threadHistory = contextHistory;
snippets = knowledge.filterSnippetsForLane(
shopify.filterKnowledge(knowledgeSnippets),
route.lane
);
// Chat replies are not ephemeral. Even a verified customer's order facts
// belong in /order or the private staff card, never a public model prompt.
const shopifyText = '';
const sourceQuestion = contextualQuestion(
searchPlan.standaloneQuestion || asked || question,
threadHistory
);
answerTrace.stage('retrieval','started');
const retrievalStart = performance.now();
const sourceUrls = [];
const onSources = urls => sourceUrls.push(...urls);
const [docsText, officialCodeText, feedbackText, releaseText] = await Promise.all([
relevantDocs(sourceQuestion, { queries: searchPlan.queries, subQuestions: searchPlan.subQuestions, onSources }),
route.area === 'shop' ? '' : github.searchOfficialCode(sourceQuestion, { queries: searchPlan.queries, onSources }),
router.isTechLane(route) || route.lane === 'unknown'
? relevantFeedback(sourceQuestion, { queries: searchPlan.queries })
: '',
matchingRelease(sourceQuestion, { onSources }),
]);
stageMs.retrieval += Math.round(performance.now() - retrievalStart);
const retrievedEvidence = await canonicalizeGithubDocsEvidence(
combineEvidence(docsText, feedbackText, officialCodeText),
{ sourceUrls, onSources: urls => { retrievedSourceUrls = urls; } }
);
answerTrace.sources(retrievedSourceUrls);
answerTrace.stage('retrieval','ok');
// Only application-owned source metadata can grant the confidence-only
// exception. Feedback prose, static notes and model links cannot add it.
if (!String(retrievedEvidence || '').trim()) observeSupport(observer => observer.signal(channel, {
eventId: `${message.id}-no-source`, kind: 'no_official_source', area: route.area,
}, message.author.id));
const toolFacts = buildToolFacts({
route,
shopifyText,
githubText: githubHit?.duplicate?.url || '',
docsText: retrievedEvidence,
releaseText,
});
const verifiedCanned = plannerPolicy.verifiedCannedReply(route, asked || question, retrievedEvidence);
if (verifiedCanned) {
skipModel = true;
aiResponse = { final_answer: verifiedCanned, confidence: 0.95, escalate: false, reason: '' };
cleanAnswer = verifiedCanned;
} else try {
answerTrace.stage('answer','started');
const answerStart = performance.now();
try {
aiResponse = await queryAgent({
question,
threadHistory,
knowledgeSnippets: snippets,
route,
toolFacts,
understanding: searchPlan,
handoffPlanned,
onUsage,
sessionId: `discord-${channel.id}`,
canNotifyStaff: canNotifyStaff({ discordReady: true }),
});
} finally {
stageMs.answer += Math.round(performance.now() - answerStart);
}
answerTrace.stage('answer','ok');
recordStage('generated', aiResponse?.final_answer);
if (aiResponse?.final_answer) {
const draftLane = triage.merge(route, aiResponse, question).lane;
const prepared = prepareDraftForReviewWithAudit(
aiResponse.final_answer,
draftLane,
caseQuestion,
{ earlierAudit: getRemovalAudit(aiResponse) }
);
aiResponse.final_answer = prepared.draft;
try {
answerTrace.stage('review','started');
const reviewStart = performance.now();
let checked;
try {
checked = await reviewWithSecondLook({
question,
threadHistory,
draft: aiResponse.final_answer,
removedBySafetyFilters: prepared.removed,
safetyAuditTruncated: prepared.auditTruncated,
understanding: searchPlan,
policy: toolFacts,
lane: draftLane,
handoffPlanned: handoffPlanned || aiResponse.escalate === true,
onUsage,
sources: [
retrievedEvidence,
releaseText ? `[S99 | Official release note]\n${releaseText}` : '',
`[Static fallback | lower priority than retrieved Help Center and docs]\n${OFFICIAL}`,
relatedPullEvidence,
]
.filter(Boolean)
.join('\n\n'),
sessionId: `discord-${channel.id}-review`,
}, { review: reviewAnswer });
} finally {
stageMs.review += Math.round(performance.now() - reviewStart);
}
answerTrace.stage('review','ok');
answerTrace.review(checked,{selected:true});
const approved = approvedReview(checked);
if (!approved) observeSupport(observer => observer.signal(channel, {