-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.js
More file actions
3178 lines (2856 loc) · 134 KB
/
bot.js
File metadata and controls
3178 lines (2856 loc) · 134 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
import TelegramBot from 'node-telegram-bot-api';
import { createReadStream, readFileSync } from 'fs';
import { isAllowedUser, getUnauthorizedMessage, alertAdmin } from './security/auth.js';
import { getLogger } from './utils/logger.js';
import { PROVIDERS } from './providers/models.js';
import {
getSkillById,
getCategoryList,
getSkillsByCategory,
loadAllSkills,
saveCustomSkill,
deleteCustomSkill,
getCustomSkills,
} from './skills/loader.js';
import { TTSService } from './services/tts.js';
import { STTService } from './services/stt.js';
import { getClaudeAuthStatus, claudeLogout } from './claude-auth.js';
import { isQuietHours } from './utils/timeUtils.js';
import { CharacterBuilder } from './characters/builder.js';
import { LifeEngine } from './life/engine.js';
import { personaShield } from './utils/persona-shield.js';
import { OnboardingManager } from './onboarding/manager.js';
import { OnboardingFlow } from './onboarding/flow.js';
/**
* Simulate a human-like typing delay based on response length.
* Short replies (casual chat) get a brief pause; longer replies get more.
* Keeps the typing indicator alive during the delay so the user sees "typing...".
*
* @param {TelegramBot} bot - Telegram bot instance
* @param {number} chatId - Chat to show typing in
* @param {string} text - The reply text (used to calculate delay)
* @returns {Promise<void>}
*/
async function simulateTypingDelay(bot, chatId, text) {
const length = (text || '').length;
// ~25ms per character, clamped between 0.4s and 4s
// Short "hey ❤️" (~6 chars) → 0.4s | Medium reply (~120 chars) → 3s | Long reply → 4s cap
const delay = Math.min(4000, Math.max(400, length * 25));
// Add a small random jitter (±15%) so it doesn't feel mechanical
const jitter = delay * (0.85 + Math.random() * 0.3);
const finalDelay = Math.round(jitter);
// Keep the typing indicator alive during the delay
bot.sendChatAction(chatId, 'typing').catch(() => {});
return new Promise((resolve) => setTimeout(resolve, finalDelay));
}
/**
* Simulate a brief pause between consecutive message chunks.
* When a long reply is split into multiple Telegram messages, firing them
* all instantly feels robotic. This adds a short, natural delay with a
* typing indicator so multi-part replies feel more human.
*
* @param {TelegramBot} bot - Telegram bot instance
* @param {number} chatId - Chat to show typing in
* @param {string} nextChunk - The upcoming chunk (used to scale the pause)
* @returns {Promise<void>}
*/
async function simulateInterChunkDelay(bot, chatId, nextChunk) {
// Shorter than the initial typing delay: 0.3s – 1.5s based on chunk length
const length = (nextChunk || '').length;
const base = Math.min(1500, Math.max(300, length * 8));
const jitter = base * (0.85 + Math.random() * 0.3);
bot.sendChatAction(chatId, 'typing').catch(() => {});
return new Promise((resolve) => setTimeout(resolve, Math.round(jitter)));
}
function splitMessage(text, maxLength = 4096) {
if (text.length <= maxLength) return [text];
const chunks = [];
let remaining = text;
while (remaining.length > 0) {
if (remaining.length <= maxLength) {
chunks.push(remaining);
break;
}
// Try to split at a newline near the limit
let splitAt = remaining.lastIndexOf('\n', maxLength);
if (splitAt < maxLength / 2) splitAt = maxLength;
chunks.push(remaining.slice(0, splitAt));
remaining = remaining.slice(splitAt);
}
return chunks;
}
/**
* Create an onUpdate callback that sends or edits Telegram messages.
* Tries Markdown first, falls back to plain text.
*/
function createOnUpdate(bot, chatId) {
const logger = getLogger();
return async (update, opts = {}) => {
if (opts.editMessageId) {
try {
const edited = await bot.editMessageText(update, {
chat_id: chatId,
message_id: opts.editMessageId,
parse_mode: 'Markdown',
});
return edited.message_id;
} catch (mdErr) {
logger.debug(`[Bot] Markdown edit failed for chat ${chatId}, retrying plain: ${mdErr.message}`);
try {
const edited = await bot.editMessageText(update, {
chat_id: chatId,
message_id: opts.editMessageId,
});
return edited.message_id;
} catch (plainErr) {
logger.debug(`[Bot] Plain-text edit also failed for chat ${chatId}, sending new message: ${plainErr.message}`);
}
}
}
const parts = splitMessage(update);
let lastMsgId = null;
for (const part of parts) {
try {
const sent = await bot.sendMessage(chatId, part, { parse_mode: 'Markdown' });
lastMsgId = sent.message_id;
} catch (mdErr) {
logger.debug(`[Bot] Markdown send failed for chat ${chatId}, falling back to plain: ${mdErr.message}`);
try {
const sent = await bot.sendMessage(chatId, part);
lastMsgId = sent.message_id;
} catch (plainErr) {
logger.error(`[Bot] Plain-text send also failed for chat ${chatId}: ${plainErr.message}`);
}
}
}
return lastMsgId;
};
}
/**
* Create a sendPhoto callback that sends a photo with optional caption.
* Tries Markdown caption first, falls back to plain caption.
*/
function createSendPhoto(bot, chatId, logger) {
return async (filePath, caption) => {
const fileOpts = { contentType: 'image/png' };
try {
await bot.sendPhoto(chatId, createReadStream(filePath), {
caption: caption || '',
parse_mode: 'Markdown',
}, fileOpts);
} catch {
try {
await bot.sendPhoto(chatId, createReadStream(filePath), {
caption: caption || '',
}, fileOpts);
} catch (err) {
logger.error(`Failed to send photo: ${err.message}`);
}
}
};
}
/**
* Create a sendReaction callback for reacting to messages with emoji.
*/
function createSendReaction(bot) {
const logger = getLogger();
return async (targetChatId, targetMsgId, emoji, isBig = false) => {
try {
await bot.setMessageReaction(targetChatId, targetMsgId, {
reaction: [{ type: 'emoji', emoji }],
is_big: isBig,
});
} catch (err) {
logger.debug(`[Bot] Failed to set reaction for msg ${targetMsgId} in chat ${targetChatId}: ${err.message}`);
}
};
}
/**
* Simple per-chat queue to serialize agent processing.
* Each chat gets its own promise chain so messages are processed in order.
* Automatically cleans up finished queues to avoid unbounded Map growth.
*/
class ChatQueue {
constructor() {
this.queues = new Map();
}
enqueue(chatId, fn) {
const logger = getLogger();
const key = String(chatId);
const prev = this.queues.get(key) || Promise.resolve();
const next = prev
.then(() => fn())
.catch((err) => {
logger.error(`[ChatQueue] Error processing message for chat ${key}: ${err.message}`);
})
.finally(() => {
// Clean up the queue entry once this is the last item in the chain,
// preventing the Map from growing unboundedly over long-running sessions.
if (this.queues.get(key) === next) {
this.queues.delete(key);
}
});
this.queues.set(key, next);
return next;
}
}
/**
* Convert raw errors into user-friendly messages.
* Uses the Persona Shield to hide technical details from end users.
*/
function _friendlyError(err) {
return personaShield(err);
}
export function startBot(config, agent, conversationManager, jobManager, automationManager, lifeDeps = {}) {
let { lifeEngine, memoryManager, journalManager, shareQueue, evolutionTracker, codebaseKnowledge, characterManager, dashboardHandle, dashboardDeps, consolidation, synthesisLoop, identityAwareness } = lifeDeps;
const logger = getLogger();
const bot = new TelegramBot(config.telegram.bot_token, {
polling: {
params: {
allowed_updates: ['message', 'callback_query', 'message_reaction'],
},
},
});
const chatQueue = new ChatQueue();
const batchWindowMs = config.telegram.batch_window_ms || 3000;
// Initialize voice services
const ttsService = new TTSService(config);
const sttService = new STTService(config);
if (ttsService.isAvailable()) logger.info('[Bot] TTS service enabled (ElevenLabs)');
if (sttService.isAvailable()) logger.info('[Bot] STT service enabled');
/**
* Rebuild the life engine for a different character.
* Stops the current engine, creates a new one with scoped managers, and starts it.
*/
function rebuildLifeEngine(charCtx) {
if (lifeEngine) {
lifeEngine.stop();
}
// Update module-level manager refs so other bot.js code uses the right ones
memoryManager = charCtx.memoryManager;
journalManager = charCtx.journalManager;
shareQueue = charCtx.shareQueue;
evolutionTracker = charCtx.evolutionTracker;
// Switch conversation file to the new character's conversations.json
conversationManager.switchFile(charCtx.conversationFilePath);
const lifeEnabled = config.life?.enabled !== false;
if (!lifeEnabled) {
lifeEngine = null;
return;
}
lifeEngine = new LifeEngine({
config,
agent,
memoryManager: charCtx.memoryManager,
journalManager: charCtx.journalManager,
shareQueue: charCtx.shareQueue,
evolutionTracker: charCtx.evolutionTracker,
codebaseKnowledge,
selfManager: charCtx.selfManager,
basePath: charCtx.lifeBasePath,
characterId: charCtx.characterId,
consolidation,
});
lifeEngine.wakeUp().then(() => {
lifeEngine.start();
logger.info(`[Bot] Life engine rebuilt for character: ${charCtx.characterId}`);
}).catch(err => {
logger.error(`[Bot] Life engine wake-up failed: ${err.message}`);
lifeEngine.start();
});
}
// ── Onboarding ──────────────────────────────────────────────────
let onboardingManager = null;
let onboardingFlow = null;
const onboardingEnabled = config.onboarding?.enabled !== false;
if (onboardingEnabled && agent._brainDB?.isOpen) {
onboardingManager = new OnboardingManager(agent._brainDB);
onboardingFlow = new OnboardingFlow({
onboardingManager,
provider: agent.orchestratorProvider,
characterName: config.bot?.name || 'KernelBot',
personaManager: agent.personaManager,
conversationManager,
identityAwareness,
});
agent.onboardingManager = onboardingManager;
logger.info('[Bot] Onboarding system initialized');
}
// Per-chat message batching: chatId -> { messages[], timer, resolve }
const chatBatches = new Map();
// Load previous conversations from disk
const loaded = conversationManager.load();
if (loaded) {
logger.info('Loaded previous conversations from disk');
}
// Load custom skills from disk
loadAllSkills();
// Register commands in Telegram's menu button
bot.setMyCommands([
{ command: 'character', description: 'Switch or manage characters' },
{ command: 'brain', description: 'Switch worker AI model/provider' },
{ command: 'orchestrator', description: 'Switch orchestrator AI model/provider' },
{ command: 'claudemodel', description: 'Switch Claude Code model' },
{ command: 'claude', description: 'Manage Claude Code authentication' },
{ command: 'skills', description: 'Browse and activate persona skills' },
{ command: 'jobs', description: 'List running and recent jobs' },
{ command: 'cancel', description: 'Cancel running job(s)' },
{ command: 'auto', description: 'Manage recurring automations' },
{ command: 'life', description: 'Inner life engine status and control' },
{ command: 'journal', description: 'View today\'s journal or a past date' },
{ command: 'memories', description: 'View recent memories or search' },
{ command: 'senders', description: 'List known senders with trust levels' },
{ command: 'whois', description: 'Show sender profile (/whois username)' },
{ command: 'trust', description: 'Promote user to trusted (/trust username)' },
{ command: 'restrict', description: 'Demote user to unknown (/restrict username)' },
{ command: 'registerbot', description: 'Register AI agent (/registerbot bot purpose)' },
{ command: 'privacy', description: 'Show knowledge scope stats' },
{ command: 'evolution', description: 'Self-evolution status, history, and lessons' },
{ command: 'linkedin', description: 'Link/unlink LinkedIn account' },
{ command: 'x', description: 'Link/unlink X (Twitter) account' },
{ command: 'dashboard', description: 'Start/stop the monitoring dashboard' },
{ command: 'onboarding', description: 'Show onboarding status or reset' },
{ command: 'context', description: 'Show all models, auth, and context info' },
{ command: 'clean', description: 'Clear conversation and start fresh' },
{ command: 'history', description: 'Show message count in memory' },
{ command: 'help', description: 'Show all available commands' },
]).catch((err) => logger.warn(`Failed to set bot commands menu: ${err.message}`));
logger.info('Telegram bot started with polling');
// Initialize automation manager with bot context
if (automationManager) {
const sendMsg = async (chatId, text) => {
try {
await bot.sendMessage(chatId, text, { parse_mode: 'Markdown' });
} catch {
await bot.sendMessage(chatId, text);
}
};
const sendAction = (chatId, action) => bot.sendChatAction(chatId, action).catch(() => {});
const agentFactory = (chatId) => {
const onUpdate = createOnUpdate(bot, chatId);
const sendPhoto = createSendPhoto(bot, chatId, logger);
return { agent, onUpdate, sendPhoto };
};
automationManager.init({ sendMessage: sendMsg, sendChatAction: sendAction, agentFactory, config });
automationManager.startAll();
logger.info('[Bot] Automation manager initialized and started');
}
// Track pending brain API key input: chatId -> { providerKey, modelId }
const pendingBrainKey = new Map();
// Track pending orchestrator API key input: chatId -> { providerKey, modelId }
const pendingOrchKey = new Map();
// Track pending Claude Code auth input: chatId -> { type: 'api_key' | 'oauth_token' }
const pendingClaudeAuth = new Map();
// Track pending custom skill creation: chatId -> { step: 'name' | 'prompt', name?: string }
const pendingCustomSkill = new Map();
// Track pending custom character build: chatId -> { answers: {}, step: number }
const pendingCharacterBuild = new Map();
// Track pending dashboard credential setup: chatId -> { step: 'username' | 'password', username?: string }
const pendingDashboardCreds = new Map();
// Handle inline keyboard callbacks for /brain
bot.on('callback_query', async (query) => {
const chatId = query.message.chat.id;
const data = query.data;
if (!isAllowedUser(query.from.id, config)) {
await bot.answerCallbackQuery(query.id, { text: 'Unauthorized' });
await alertAdmin(bot, {
userId: query.from.id,
username: query.from.username,
firstName: query.from.first_name,
text: `🔘 زر: ${query.data || 'unknown'}`,
type: 'callback',
});
return;
}
try {
logger.info(`[Bot] Callback query from chat ${chatId}: ${data}`);
if (data.startsWith('brain_provider:')) {
// User picked a provider — show model list
const providerKey = data.split(':')[1];
const providerDef = PROVIDERS[providerKey];
if (!providerDef) {
await bot.answerCallbackQuery(query.id, { text: 'Unknown provider' });
return;
}
const modelButtons = providerDef.models.map((m) => ([{
text: m.label,
callback_data: `brain_model:${providerKey}:${m.id}`,
}]));
modelButtons.push([{ text: 'Cancel', callback_data: 'brain_cancel' }]);
await bot.editMessageText(`Select a *${providerDef.name}* model:`, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: modelButtons },
});
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('brain_model:')) {
// User picked a model — attempt switch
// Use split with limit to avoid truncating model IDs containing colons
const parts = data.split(':');
const providerKey = parts[1];
const modelId = parts.slice(2).join(':');
const providerDef = PROVIDERS[providerKey];
const modelEntry = providerDef?.models.find((m) => m.id === modelId);
const modelLabel = modelEntry ? modelEntry.label : modelId;
await bot.editMessageText(
`⏳ Verifying *${providerDef.name}* / *${modelLabel}*...`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
},
);
logger.info(`[Bot] Brain switch request: ${providerKey}/${modelId} from chat ${chatId}`);
const result = await agent.switchBrain(providerKey, modelId);
if (result && typeof result === 'object' && result.error) {
// Validation failed — keep current model
logger.warn(`[Bot] Brain switch failed: ${result.error}`);
const current = agent.getBrainInfo();
await bot.editMessageText(
`❌ Failed to switch: ${result.error}\n\nKeeping *${current.providerName}* / *${current.modelLabel}*`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
},
);
} else if (result) {
// API key missing — ask for it
logger.info(`[Bot] Brain switch needs API key: ${result} for ${providerKey}/${modelId}`);
pendingBrainKey.set(chatId, { providerKey, modelId });
await bot.editMessageText(
`🔑 *${providerDef.name}* API key is required.\n\nPlease send your \`${result}\` now.\n\nOr send *cancel* to abort.`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
},
);
} else {
const info = agent.getBrainInfo();
logger.info(`[Bot] Brain switched successfully to ${info.providerName}/${info.modelLabel}`);
await bot.editMessageText(
`🧠 Brain switched to *${info.providerName}* / *${info.modelLabel}*`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
},
);
}
await bot.answerCallbackQuery(query.id);
} else if (data === 'brain_cancel') {
pendingBrainKey.delete(chatId);
await bot.editMessageText('Brain change cancelled.', {
chat_id: chatId,
message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
// ── Skill callbacks (multi-skill toggle) ─────────────────────
} else if (data.startsWith('skill_category:')) {
const categoryKey = data.split(':')[1];
const skills = getSkillsByCategory(categoryKey);
const categories = getCategoryList();
const cat = categories.find((c) => c.key === categoryKey);
if (!skills.length) {
await bot.answerCallbackQuery(query.id, { text: 'No skills in this category' });
return;
}
const activeIds = new Set(agent.getActiveSkillIds(chatId));
const buttons = skills.map((s) => ([{
text: `${activeIds.has(s.id) ? '✅ ' : ''}${s.emoji} ${s.name}`,
callback_data: `skill_toggle:${s.id}:${categoryKey}`,
}]));
buttons.push([
{ text: '« Back', callback_data: 'skill_back' },
{ text: 'Done', callback_data: 'skill_cancel' },
]);
const activeSkills = agent.getActiveSkills(chatId);
const activeLine = activeSkills.length > 0
? `Active (${activeSkills.length}): ${activeSkills.map(s => `${s.emoji} ${s.name}`).join(', ')}\n\n`
: '';
await bot.editMessageText(
`${activeLine}${cat ? cat.emoji : ''} *${cat ? cat.name : categoryKey}* — tap to toggle:`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
},
);
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('skill_toggle:')) {
const parts = data.split(':');
const skillId = parts[1];
const categoryKey = parts[2]; // to refresh the category view
const skill = getSkillById(skillId);
if (!skill) {
await bot.answerCallbackQuery(query.id, { text: 'Unknown skill' });
return;
}
const { added, skills: currentSkills } = agent.toggleSkill(chatId, skillId);
if (!added && currentSkills.includes(skillId)) {
// Wasn't added because at max
await bot.answerCallbackQuery(query.id, { text: `Max ${5} skills reached. Remove one first.` });
return;
}
logger.info(`[Bot] Skill ${added ? 'activated' : 'deactivated'}: ${skill.name} (${skillId}) for chat ${chatId} — now ${currentSkills.length} active`);
// Refresh the category view with updated toggles
const catSkills = getSkillsByCategory(categoryKey);
const categories = getCategoryList();
const cat = categories.find((c) => c.key === categoryKey);
const activeIds = new Set(agent.getActiveSkillIds(chatId));
const buttons = catSkills.map((s) => ([{
text: `${activeIds.has(s.id) ? '✅ ' : ''}${s.emoji} ${s.name}`,
callback_data: `skill_toggle:${s.id}:${categoryKey}`,
}]));
buttons.push([
{ text: '« Back', callback_data: 'skill_back' },
{ text: 'Done', callback_data: 'skill_cancel' },
]);
const activeSkills = agent.getActiveSkills(chatId);
const activeLine = activeSkills.length > 0
? `Active (${activeSkills.length}): ${activeSkills.map(s => `${s.emoji} ${s.name}`).join(', ')}\n\n`
: '';
await bot.editMessageText(
`${activeLine}${cat ? cat.emoji : ''} *${cat ? cat.name : categoryKey}* — tap to toggle:`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
},
);
await bot.answerCallbackQuery(query.id, { text: added ? `✅ ${skill.name} on` : `❌ ${skill.name} off` });
} else if (data === 'skill_reset') {
logger.info(`[Bot] Skills cleared for chat ${chatId}`);
agent.clearSkill(chatId);
await bot.editMessageText('🔄 All skills cleared — back to default persona.', {
chat_id: chatId,
message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
} else if (data === 'skill_custom_add') {
pendingCustomSkill.set(chatId, { step: 'name' });
await bot.editMessageText(
'✏️ Send me a *name* for your custom skill:',
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
},
);
await bot.answerCallbackQuery(query.id);
} else if (data === 'skill_custom_manage') {
const customs = getCustomSkills();
if (!customs.length) {
await bot.answerCallbackQuery(query.id, { text: 'No custom skills yet' });
return;
}
const buttons = customs.map((s) => ([{
text: `🗑️ ${s.name}`,
callback_data: `skill_custom_delete:${s.id}`,
}]));
buttons.push([{ text: '« Back', callback_data: 'skill_back' }]);
await bot.editMessageText('🛠️ *Custom Skills* — tap to delete:', {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
});
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('skill_custom_delete:')) {
const skillId = data.slice('skill_custom_delete:'.length);
logger.info(`[Bot] Custom skill delete request: ${skillId} from chat ${chatId}`);
// Remove from active skills if present
const activeIds = agent.getActiveSkillIds(chatId);
if (activeIds.includes(skillId)) {
logger.info(`[Bot] Removing deleted skill from active set: ${skillId}`);
agent.toggleSkill(chatId, skillId);
}
const deleted = deleteCustomSkill(skillId);
const msg = deleted ? '🗑️ Custom skill deleted.' : 'Skill not found.';
await bot.editMessageText(msg, {
chat_id: chatId,
message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
} else if (data === 'skill_back') {
// Re-show category list
const categories = getCategoryList();
const activeSkills = agent.getActiveSkills(chatId);
const buttons = categories.map((cat) => ([{
text: `${cat.emoji} ${cat.name} (${cat.count})`,
callback_data: `skill_category:${cat.key}`,
}]));
// Custom skill management row
const customRow = [{ text: '➕ Add Custom', callback_data: 'skill_custom_add' }];
if (getCustomSkills().length > 0) {
customRow.push({ text: '🗑️ Manage Custom', callback_data: 'skill_custom_manage' });
}
buttons.push(customRow);
const footerRow = [{ text: 'Done', callback_data: 'skill_cancel' }];
if (activeSkills.length > 0) {
footerRow.unshift({ text: '🔄 Clear All', callback_data: 'skill_reset' });
}
buttons.push(footerRow);
const activeLine = activeSkills.length > 0
? `Active (${activeSkills.length}): ${activeSkills.map(s => `${s.emoji} ${s.name}`).join(', ')}\n\n`
: '';
const header = `${activeLine}🎭 *Skills* — select a category:`;
await bot.editMessageText(header, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
});
await bot.answerCallbackQuery(query.id);
} else if (data === 'skill_cancel') {
const activeSkills = agent.getActiveSkills(chatId);
const msg = activeSkills.length > 0
? `🎭 Active skills (${activeSkills.length}): ${activeSkills.map(s => `${s.emoji} ${s.name}`).join(', ')}`
: 'No skills active.';
await bot.editMessageText(msg, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
});
await bot.answerCallbackQuery(query.id);
// ── Job cancellation callbacks ────────────────────────────────
} else if (data.startsWith('cancel_job:')) {
const jobId = data.slice('cancel_job:'.length);
logger.info(`[Bot] Job cancel request via callback: ${jobId} from chat ${chatId}`);
const job = jobManager.cancelJob(jobId);
if (job) {
logger.info(`[Bot] Job cancelled via callback: ${jobId} [${job.workerType}]`);
await bot.editMessageText(`🚫 Cancelled job \`${jobId}\` (${job.workerType})`, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
});
} else {
await bot.editMessageText(`Job \`${jobId}\` not found or already finished.`, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
});
}
await bot.answerCallbackQuery(query.id);
} else if (data === 'cancel_all_jobs') {
logger.info(`[Bot] Cancel all jobs request via callback from chat ${chatId}`);
const cancelled = jobManager.cancelAllForChat(chatId);
const msg = cancelled.length > 0
? `🚫 Cancelled ${cancelled.length} job(s).`
: 'No running jobs to cancel.';
await bot.editMessageText(msg, {
chat_id: chatId,
message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
// ── Automation callbacks ─────────────────────────────────────────
} else if (data.startsWith('auto_pause:')) {
const autoId = data.slice('auto_pause:'.length);
logger.info(`[Bot] Automation pause request: ${autoId} from chat ${chatId}`);
const auto = automationManager?.update(autoId, { enabled: false });
const msg = auto ? `⏸️ Paused automation \`${autoId}\` (${auto.name})` : `Automation \`${autoId}\` not found.`;
await bot.editMessageText(msg, { chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' });
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('auto_resume:')) {
const autoId = data.slice('auto_resume:'.length);
logger.info(`[Bot] Automation resume request: ${autoId} from chat ${chatId}`);
const auto = automationManager?.update(autoId, { enabled: true });
const msg = auto ? `▶️ Resumed automation \`${autoId}\` (${auto.name})` : `Automation \`${autoId}\` not found.`;
await bot.editMessageText(msg, { chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' });
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('auto_delete:')) {
const autoId = data.slice('auto_delete:'.length);
logger.info(`[Bot] Automation delete request: ${autoId} from chat ${chatId}`);
const deleted = automationManager?.delete(autoId);
const msg = deleted ? `🗑️ Deleted automation \`${autoId}\`` : `Automation \`${autoId}\` not found.`;
await bot.editMessageText(msg, { chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' });
await bot.answerCallbackQuery(query.id);
// ── Orchestrator callbacks ─────────────────────────────────────
} else if (data.startsWith('orch_provider:')) {
const providerKey = data.split(':')[1];
const providerDef = PROVIDERS[providerKey];
if (!providerDef) {
await bot.answerCallbackQuery(query.id, { text: 'Unknown provider' });
return;
}
const modelButtons = providerDef.models.map((m) => ([{
text: m.label,
callback_data: `orch_model:${providerKey}:${m.id}`,
}]));
modelButtons.push([{ text: 'Cancel', callback_data: 'orch_cancel' }]);
await bot.editMessageText(`Select a *${providerDef.name}* model for orchestrator:`, {
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: modelButtons },
});
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('orch_model:')) {
// Use split with limit to avoid truncating model IDs containing colons
const parts = data.split(':');
const providerKey = parts[1];
const modelId = parts.slice(2).join(':');
const providerDef = PROVIDERS[providerKey];
const modelEntry = providerDef?.models.find((m) => m.id === modelId);
const modelLabel = modelEntry ? modelEntry.label : modelId;
await bot.editMessageText(
`⏳ Verifying *${providerDef.name}* / *${modelLabel}* for orchestrator...`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
logger.info(`[Bot] Orchestrator switch request: ${providerKey}/${modelId} from chat ${chatId}`);
const result = await agent.switchOrchestrator(providerKey, modelId);
if (result && typeof result === 'object' && result.error) {
const current = agent.getOrchestratorInfo();
await bot.editMessageText(
`❌ Failed to switch: ${result.error}\n\nKeeping *${current.providerName}* / *${current.modelLabel}*`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
} else if (result) {
// API key missing
logger.info(`[Bot] Orchestrator switch needs API key: ${result} for ${providerKey}/${modelId}`);
pendingOrchKey.set(chatId, { providerKey, modelId });
await bot.editMessageText(
`🔑 *${providerDef.name}* API key is required.\n\nPlease send your \`${result}\` now.\n\nOr send *cancel* to abort.`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
} else {
const info = agent.getOrchestratorInfo();
await bot.editMessageText(
`🎛️ Orchestrator switched to *${info.providerName}* / *${info.modelLabel}*`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
}
await bot.answerCallbackQuery(query.id);
} else if (data === 'orch_cancel') {
pendingOrchKey.delete(chatId);
await bot.editMessageText('Orchestrator change cancelled.', {
chat_id: chatId, message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
// ── Claude Code model callbacks ────────────────────────────────
} else if (data.startsWith('ccmodel:')) {
const modelId = data.slice('ccmodel:'.length);
agent.switchClaudeCodeModel(modelId);
const info = agent.getClaudeCodeInfo();
logger.info(`[Bot] Claude Code model switched to ${info.modelLabel} from chat ${chatId}`);
await bot.editMessageText(
`💻 Claude Code model switched to *${info.modelLabel}*`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
await bot.answerCallbackQuery(query.id);
} else if (data === 'ccmodel_cancel') {
await bot.editMessageText('Claude Code model change cancelled.', {
chat_id: chatId, message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
// ── Claude Code auth callbacks ─────────────────────────────────
} else if (data === 'claude_apikey') {
pendingClaudeAuth.set(chatId, { type: 'api_key' });
await bot.editMessageText(
'🔑 Send your *Anthropic API key* for Claude Code.\n\nOr send *cancel* to abort.',
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
await bot.answerCallbackQuery(query.id);
} else if (data === 'claude_oauth') {
pendingClaudeAuth.set(chatId, { type: 'oauth_token' });
await bot.editMessageText(
'🔑 Run `claude setup-token` locally and paste the *OAuth token* here.\n\nThis uses your Pro/Max subscription instead of an API key.\n\nOr send *cancel* to abort.',
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
await bot.answerCallbackQuery(query.id);
} else if (data === 'claude_system') {
agent.setClaudeCodeAuth('system', null);
logger.info(`[Bot] Claude Code auth set to system from chat ${chatId}`);
await bot.editMessageText(
'🔓 Claude Code set to *system auth* — using host machine credentials.',
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
await bot.answerCallbackQuery(query.id);
} else if (data === 'claude_status') {
await bot.answerCallbackQuery(query.id, { text: 'Checking...' });
const status = await getClaudeAuthStatus();
const authConfig = agent.getClaudeAuthConfig();
await bot.editMessageText(
`🔐 *Claude Code Auth*\n\n*Mode:* ${authConfig.mode}\n*Credential:* ${authConfig.credential}\n\n*CLI Status:*\n\`\`\`\n${status.output.slice(0, 500)}\n\`\`\``,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
} else if (data === 'claude_logout') {
await bot.answerCallbackQuery(query.id, { text: 'Logging out...' });
const result = await claudeLogout();
await bot.editMessageText(
`🚪 Claude Code logout: ${result.output || 'Done.'}`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
} else if (data === 'claude_cancel') {
pendingClaudeAuth.delete(chatId);
await bot.editMessageText('Claude Code auth management dismissed.', {
chat_id: chatId, message_id: query.message.message_id,
});
await bot.answerCallbackQuery(query.id);
// ── Character callbacks ────────────────────────────────────────
} else if (data.startsWith('char_select:')) {
const charId = data.slice('char_select:'.length);
if (!characterManager) {
await bot.answerCallbackQuery(query.id, { text: 'Character system not available' });
return;
}
const character = characterManager.getCharacter(charId);
if (!character) {
await bot.answerCallbackQuery(query.id, { text: 'Character not found' });
return;
}
const activeId = agent.getActiveCharacterInfo()?.id;
const isActive = activeId === charId;
const buttons = [];
if (!isActive) {
buttons.push([{ text: `Switch to ${character.emoji} ${character.name}`, callback_data: `char_confirm:${charId}` }]);
}
buttons.push([
{ text: '« Back', callback_data: 'char_back' },
{ text: 'Cancel', callback_data: 'char_cancel' },
]);
const artBlock = character.asciiArt ? `\n\`\`\`\n${character.asciiArt}\n\`\`\`\n` : '\n';
await bot.editMessageText(
`${character.emoji} *${character.name}*\n_${character.origin || 'Original'}_${artBlock}\n"${character.tagline}"\n\n*Age:* ${character.age}\n${isActive ? '_(Currently active)_' : ''}`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
},
);
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('char_confirm:')) {
const charId = data.slice('char_confirm:'.length);
if (!characterManager) {
await bot.answerCallbackQuery(query.id, { text: 'Character system not available' });
return;
}
await bot.editMessageText(
`Switching character...`,
{ chat_id: chatId, message_id: query.message.message_id },
);
try {
const charCtx = await agent.switchCharacter(charId);
// Rebuild life engine with new character's scoped managers
rebuildLifeEngine(charCtx);
const character = characterManager.getCharacter(charId);
if (onboardingFlow) onboardingFlow.setCharacterName(character.name);
logger.info(`[Bot] Character switched to ${character.name} (${charId})`);
await bot.editMessageText(
`${character.emoji} *${character.name}* is now active!\n\n"${character.tagline}"`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
} catch (err) {
logger.error(`[Bot] Character switch failed: ${err.message}`);
await bot.editMessageText(
`Failed to switch character: ${err.message}`,
{ chat_id: chatId, message_id: query.message.message_id },
);
}
await bot.answerCallbackQuery(query.id);
} else if (data === 'char_custom') {
pendingCharacterBuild.set(chatId, { answers: {}, step: 0 });
const builder = new CharacterBuilder(agent.orchestratorProvider);
const nextQ = builder.getNextQuestion({});
if (nextQ) {
await bot.editMessageText(
`*Custom Character Builder* (1/${builder.getTotalQuestions()})\n\n${nextQ.question}\n\n_Examples: ${nextQ.examples}_\n\nSend *cancel* to abort.`,
{ chat_id: chatId, message_id: query.message.message_id, parse_mode: 'Markdown' },
);
}
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('char_delete:')) {
const charId = data.slice('char_delete:'.length);
if (!characterManager) {
await bot.answerCallbackQuery(query.id, { text: 'Character system not available' });
return;
}
const buttons = [
[{ text: `Yes, delete`, callback_data: `char_delete_confirm:${charId}` }],
[{ text: 'Cancel', callback_data: 'char_back' }],
];
const character = characterManager.getCharacter(charId);
await bot.editMessageText(
`Are you sure you want to delete *${character?.name || charId}*?\n\nThis will remove all their memories, journals, and conversation history.`,
{
chat_id: chatId,
message_id: query.message.message_id,
parse_mode: 'Markdown',
reply_markup: { inline_keyboard: buttons },
},
);
await bot.answerCallbackQuery(query.id);
} else if (data.startsWith('char_delete_confirm:')) {
const charId = data.slice('char_delete_confirm:'.length);
try {
characterManager.removeCharacter(charId);
await bot.editMessageText(`Character deleted.`, {
chat_id: chatId, message_id: query.message.message_id,
});
} catch (err) {
await bot.editMessageText(`Cannot delete: ${err.message}`, {
chat_id: chatId, message_id: query.message.message_id,
});