-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
1399 lines (1315 loc) · 56.7 KB
/
index.js
File metadata and controls
1399 lines (1315 loc) · 56.7 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
/**
* WhatsApp + configurable LLM. On incoming message → LLM reply → send back.
* Config and state live in ~/.cowcode (or COWCODE_STATE_DIR).
*/
import { getAuthDir, getCronStorePath, getConfigPath, getEnvPath, ensureStateDir, getWorkspaceDir, getUploadsDir, getStateDir, getAgentWorkspaceDir } from './lib/paths.js';
import dotenv from 'dotenv';
dotenv.config({ path: getEnvPath() });
// Log to daemon.log so "tail -f" shows when the process actually started (after cowcode moo start/restart)
console.log(`[${new Date().toISOString().replace(/\.\d{3}Z$/, '')}] cowCode daemon started`);
import * as Baileys from '@whiskeysockets/baileys';
const makeWASocket =
typeof Baileys.makeWASocket === 'function' ? Baileys.makeWASocket : Baileys.default;
const {
useMultiFileAuthState,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
isJidBroadcast,
extractMessageContent,
areJidsSameUser,
downloadMediaMessage,
} = Baileys;
import { loadConfig, chat as llmChat } from './llm.js';
import { runAgentTurn, stripThinking } from './lib/agent.js';
import { join, dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { rmSync, mkdirSync, existsSync, readFileSync, writeFileSync, copyFileSync } from 'fs';
import { spawn } from 'child_process';
import pino from 'pino';
import { startCron, stopCron, scheduleOneShot, runPastDueOneShots } from './cron/runner.js';
import { getSkillsEnabled, getSkillContext, DEFAULT_ENABLED } from './skills/loader.js';
import { initBot, createTelegramSock, isTelegramChatId, isTelegramGroupJid, sendLongText } from './lib/telegram.js';
import { isWhatsAppGroupJid } from './lib/whatsapp.js';
import { addPending as addPendingTelegram, clearPending as clearPendingTelegram, flushPending } from './lib/pending-telegram.js';
import { getChannelsConfig } from './lib/channels-config.js';
import { getSchedulingTimeContext, isInTideInactiveWindow } from './lib/timezone.js';
import { getOwnerConfig, isOwner } from './lib/owner-config.js';
import { getGroupAddedBy, setGroupAddedBy } from './lib/telegram-group-added-by.js';
import { isTelegramGroup } from './lib/group-guard.js';
import { getMemoryConfig } from './lib/memory-config.js';
import { indexChatExchange } from './lib/memory-index.js';
import { appendExchange, appendGroupExchange, readLastGroupExchanges, readLastPrivateExchanges } from './lib/chat-log.js';
import { handleTelegramPrivateMessage } from './lib/telegram-private-handler.js';
import { handleTelegramGroupMessage } from './lib/telegram-group-handler.js';
import { ensureGroupConfigFor } from './lib/group-config.js';
import { loadGroupMd, buildGroupPromptBlock } from './lib/group-prompt.js';
import { buildOneOnOneSystemPrompt } from './lib/system-prompt.js';
import { ensureMainAgentInitialized, resolveAgentIdForGroup, readAgentMd, DEFAULT_AGENT_ID } from './lib/agent-config.js';
import { getGroupDisplayName, setGroupDisplayName, parseSetDisplayNameMessage } from './lib/group-display-names.js';
import { resetBrowseSession } from './lib/executors/browse.js';
import { toUserMessage, getErrorMessageForLog } from './lib/user-error.js';
import { getSpeechConfig, transcribe, synthesizeToBuffer } from './lib/speech-client.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const qrcodeTerminal = require('qrcode-terminal');
const __dirname = dirname(fileURLToPath(import.meta.url));
if (typeof makeWASocket !== 'function') {
throw new Error('Baileys makeWASocket not found. Check @whiskeysockets/baileys version.');
}
const authOnly = process.argv.includes('--auth-only');
const pairIndex = process.argv.indexOf('--pair');
const pairNumber = pairIndex !== -1 ? process.argv[pairIndex + 1] : null;
// Keys we never log (signal/session key material and noisy proto fields)
const REDACT_KEYS = new Set([
'indexInfo', 'baseKey', 'baseKeyType', 'remoteIdentityKey', 'pendingPreKey',
'signedKeyId', 'keyPair', 'private', 'public', 'signature', 'identifierKey',
]);
function redactForLog(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Buffer.isBuffer(obj) || (typeof Uint8Array !== 'undefined' && obj instanceof Uint8Array)) return '[Buffer]';
const out = {};
for (const [k, v] of Object.entries(obj)) {
if (REDACT_KEYS.has(k)) {
out[k] = '[redacted]';
continue;
}
out[k] = redactForLog(v);
}
return out;
}
// In auth mode show connection errors so we can see why linking fails
const pinoLogger = pino({ level: authOnly ? 'error' : 'silent' });
function logWithRedact(pinoInstance, level, a, b) {
if (typeof a === 'string' && b === undefined) {
pinoInstance[level](a);
return;
}
const obj = typeof a === 'object' && a !== null ? redactForLog(a) : a;
const msg = b;
pinoInstance[level](obj, msg);
}
const logger = {
get level() { return pinoLogger.level; },
set level(v) { pinoLogger.level = v; },
child(bindings) {
return wrapForRedaction(pinoLogger.child(bindings));
},
trace(a, b) { logWithRedact(pinoLogger, 'trace', a, b); },
debug(a, b) { logWithRedact(pinoLogger, 'debug', a, b); },
info(a, b) { logWithRedact(pinoLogger, 'info', a, b); },
warn(a, b) { logWithRedact(pinoLogger, 'warn', a, b); },
error(a, b) { logWithRedact(pinoLogger, 'error', a, b); },
};
function writeDaemonStarted() {
try {
const path = join(getStateDir(), 'daemon.started');
writeFileSync(path, JSON.stringify({ startedAt: Date.now() }), 'utf8');
} catch (_) {}
}
function wrapForRedaction(pinoInstance) {
return {
get level() { return pinoInstance.level; },
set level(v) { pinoInstance.level = v; },
child(b) { return wrapForRedaction(pinoInstance.child(b)); },
trace(a, b) { logWithRedact(pinoInstance, 'trace', a, b); },
debug(a, b) { logWithRedact(pinoInstance, 'debug', a, b); },
info(a, b) { logWithRedact(pinoInstance, 'info', a, b); },
warn(a, b) { logWithRedact(pinoInstance, 'warn', a, b); },
error(a, b) { logWithRedact(pinoInstance, 'error', a, b); },
};
}
// Patch console so deps (e.g. Baileys WAM/encode) never log key material to stdout
const _consoleLog = console.log;
const _consoleInfo = console.info;
const _consoleDebug = console.debug;
const _consoleWarn = console.warn;
function redactConsoleArgs(args) {
return args.map((a) => {
if (a !== null && typeof a === 'object') return redactForLog(a);
if (typeof a === 'string' && a.length > 200) {
const t = a.trim();
if (t.startsWith('{') || t.startsWith('[')) return a.slice(0, 60) + '… [truncated]';
}
return a;
});
}
console.log = (...args) => _consoleLog(...redactConsoleArgs(args));
console.info = (...args) => _consoleInfo(...redactConsoleArgs(args));
console.debug = (...args) => _consoleDebug(...redactConsoleArgs(args));
console.warn = (...args) => _consoleWarn(...redactConsoleArgs(args));
const DISCONNECT_REASONS = {
401: 'Logged out',
403: 'Forbidden (e.g. banned)',
408: 'Connection lost / timed out',
411: 'Multi-device not enabled (enable in WhatsApp Settings → Linked devices)',
428: 'Connection closed',
440: 'Connection replaced (another client linked)',
500: 'Bad session',
503: 'WhatsApp service unavailable',
515: 'Restart required (reconnecting…)',
};
const RESTART_REQUIRED_CODE = 515;
/** Codes for which we do not retry reconnect (user must re-auth). */
const NO_RETRY_CODES = new Set([401, 403]);
const RECONNECT_DELAYS_MS = [5000, 15000, 30000, 60000]; // exponential backoff, max 60s
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
/**
* Create WhatsApp socket with saved auth; resolves when connection is open, rejects if closed before open.
* @returns {Promise<ReturnType<makeWASocket>>}
*/
async function connectWhatsApp() {
const { version } = await fetchLatestBaileysVersion();
const { state, saveCreds } = await useMultiFileAuthState(getAuthDir());
const keyStoreLogger = wrapForRedaction(pino({ level: 'silent' }));
const sock = makeWASocket({
version,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, keyStoreLogger),
},
logger,
});
sock.ev.on('creds.update', saveCreds);
return new Promise((resolve, reject) => {
sock.ev.on('connection.update', (u) => {
if (u.connection === 'open') resolve(sock);
if (u.connection === 'close' && u.lastDisconnect) {
const code = u.lastDisconnect.error?.output?.statusCode ?? u.lastDisconnect.error?.statusCode;
reject(Object.assign(new Error('closed'), { code }));
}
});
});
}
/**
* @param {{ continueToBot?: boolean }} opts - If true, after link we continue to run the bot (no exit).
*/
async function runAuthOnly(opts = {}) {
const { version } = await fetchLatestBaileysVersion();
const { state, saveCreds } = await useMultiFileAuthState(getAuthDir());
const keyStoreLogger = wrapForRedaction(pino({ level: 'silent' }));
const sock = makeWASocket({
version,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, keyStoreLogger),
},
logger,
});
sock.ev.on('creds.update', saveCreds);
return new Promise((resolve, reject) => {
sock.ev.on('connection.update', async (u) => {
if (u.connection === 'open') {
if (opts.continueToBot) {
console.log('[connection] connection successful');
console.log('Please send a message to your own number to get started.');
} else {
console.log('[connection] connection successful');
console.log('Linked. You can Ctrl+C and run cowcode moo start.');
}
resolve(sock);
return;
}
if (u.connection === 'close' && u.lastDisconnect) {
const err = u.lastDisconnect.error;
const code = err?.output?.statusCode ?? err?.statusCode;
const reason = DISCONNECT_REASONS[code] || `Code ${code}`;
if (code === RESTART_REQUIRED_CODE) {
try { sock.end(undefined); } catch (_) {}
resolve('restart');
return;
}
reject(new Error(reason));
return;
}
if (u.qr) {
qrcodeTerminal.generate(u.qr, { small: true });
console.log('Scan with WhatsApp (Linked devices).');
}
});
if (pairNumber) {
const digits = pairNumber.replace(/\D/g, '');
if (digits.length < 10) {
reject(new Error('Usage: pnpm run auth -- --pair <full-phone-number> (e.g. 1234567890)'));
return;
}
sock.requestPairingCode(digits)
.then((code) => {
console.log('Pairing code (enter in WhatsApp → Linked devices → Link with phone number):', code);
})
.catch((e) => reject(e));
}
});
}
/** Migration: ensure all default skills (cron, search, browse, vision, memory, speech, etc.) are in skills.enabled so new installs and updates get them without fresh install. */
function migrateSkillsConfigToIncludeDefaults() {
try {
const path = getConfigPath();
if (!existsSync(path)) return;
const raw = readFileSync(path, 'utf8');
const config = JSON.parse(raw);
const skills = config.skills || {};
let enabled = Array.isArray(skills.enabled) ? skills.enabled : [];
let changed = false;
for (const id of DEFAULT_ENABLED) {
if (!enabled.includes(id)) {
enabled = [...enabled, id];
changed = true;
}
}
if (!changed) return;
config.skills = { ...skills, enabled };
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
} catch (_) {}
}
/** Migration: ensure tide config block exists so it can be enabled by the user. Default: enabled false. */
function migrateTideConfig() {
try {
const path = getConfigPath();
if (!existsSync(path)) return;
const raw = readFileSync(path, 'utf8');
const config = JSON.parse(raw);
if (config.tide != null && typeof config.tide === 'object') return;
config.tide = {
enabled: false,
silenceCooldownMinutes: 30,
inactiveStart: '23:00',
inactiveEnd: '06:00',
};
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
} catch (_) {}
}
async function main() {
ensureStateDir();
ensureMainAgentInitialized();
migrateSkillsConfigToIncludeDefaults();
migrateTideConfig();
if (authOnly && existsSync(getAuthDir())) {
rmSync(getAuthDir(), { recursive: true });
mkdirSync(getAuthDir(), { recursive: true });
}
if (authOnly) {
while (true) {
try {
const result = await runAuthOnly();
if (result !== 'restart') break;
await new Promise((r) => setTimeout(r, 2000));
} catch (e) {
console.error(e.message);
process.exit(1);
}
}
return;
}
let sock;
const channelsConfig = getChannelsConfig();
const envTelegramOnly = process.env.COWCODE_TELEGRAM_ONLY === '1' || process.env.COWCODE_TELEGRAM_ONLY === 'true';
const telegramOnlyMode = (envTelegramOnly || (channelsConfig.telegram.enabled && !channelsConfig.whatsapp.enabled)) && !!channelsConfig.telegram.botToken;
const credsPath = join(getAuthDir(), 'creds.json');
const needAuth = !existsSync(getAuthDir()) || !existsSync(credsPath);
// E2E tests need the mock socket regardless of channel config.
if (process.argv.includes('--test')) {
sock = {
sendMessage: async () => ({ key: { id: 'test-' + Date.now() } }),
sendPresenceUpdate: async () => {},
readMessages: async () => {},
};
} else if (telegramOnlyMode) {
sock = null;
} else if (needAuth) {
console.log('');
console.log(' ─────────────────────────────────────────');
console.log(' Link your WhatsApp');
console.log(' ─────────────────────────────────────────');
console.log('');
console.log(' No session found. A QR code will appear below.');
console.log(' Open WhatsApp → Linked devices → Link a device, then scan the code.');
console.log('');
while (true) {
try {
const result = await runAuthOnly({ continueToBot: true });
if (result !== 'restart') {
sock = result;
break;
}
await new Promise((r) => setTimeout(r, 2000));
} catch (e) {
console.error(e.message);
process.exit(1);
}
}
} else {
sock = null; // will be set by connectWhatsApp() in the reconnect loop below
}
/** Current WhatsApp sock for Tide follow-ups (set when connection opens in runBot). */
const whatsappSockRef = { current: null };
/** Set in runBot (WhatsApp: initBot; Telegram-only: opts); null in --test so cron ctx does not throw. */
let telegramBot = null;
/** Returns a function that resolves to the given bot's username (cached after first getMe()). */
function createGetBotUsername(bot) {
let cached = undefined;
return async function getBotUsername() {
if (!bot) return null;
if (cached !== undefined) return cached;
try {
const me = await bot.getMe();
cached = me.username ?? null;
return cached;
} catch {
cached = null;
return null;
}
};
}
const config = loadConfig();
const first = config.models[0];
console.log('LLM config:', config.models.length > 1
? `${config.models.length} models (priority): ${config.models.map(m => m.model).join(' → ')}`
: { baseUrl: first.baseUrl, model: first.model });
const skillsEnabled = getSkillsEnabled();
console.log('Skills enabled:', skillsEnabled?.length ? skillsEnabled.join(', ') : 'cron (default)');
const MAX_REPLIED_IDS = 500;
const MAX_OUR_SENT_IDS = 200;
const MAX_CHAT_HISTORY_EXCHANGES = Math.max(1, Math.floor(Number(config.chatHistoryExchanges)) || 5);
/** Pending WhatsApp replies when send failed (e.g. disconnected); flushed when connection reopens. */
const pendingReplies = [];
/** Last N exchanges (user + assistant) per jid for LLM context. Step 1: chat + history + tools. */
const chatHistoryByJid = new Map();
function getLast5Exchanges(jid) {
const list = chatHistoryByJid.get(jid);
if (!list || list.length === 0) return [];
const out = [];
for (const ex of list) {
out.push({ role: 'user', content: ex.user });
out.push({ role: 'assistant', content: ex.assistant });
}
return out;
}
function pushExchange(jid, userContent, assistantContent) {
let list = chatHistoryByJid.get(jid);
if (!list) list = [];
list.push({ user: userContent, assistant: assistantContent });
if (list.length > MAX_CHAT_HISTORY_EXCHANGES) list = list.slice(-MAX_CHAT_HISTORY_EXCHANGES);
chatHistoryByJid.set(jid, list);
}
// Agent logic: getSkillContext() called on every run; compact list in tool; full doc injected when a skill is called.
/** Tide: one follow-up per "round". When we reply to a private chat, we schedule a single follow-up after silenceCooldownMinutes. If the user replies before then, the timer is cleared and a new one set after our next reply. If they don't reply, we send one follow-up and do not message again until they reply. */
const tideTimerByJid = new Map();
function getTideConfig() {
try {
const raw = readFileSync(getConfigPath(), 'utf8');
if (raw?.trim()) return JSON.parse(raw);
} catch (_) {}
return {};
}
async function runTideForJid(tideJid) {
tideTimerByJid.delete(tideJid);
const tideJidShort = String(tideJid).slice(0, 20) + (String(tideJid).length > 20 ? '…' : '');
let config = getTideConfig();
const tide = config.tide || {};
if (!tide.enabled) return;
const inactiveStart = tide.inactiveStart && String(tide.inactiveStart).trim();
const inactiveEnd = tide.inactiveEnd && String(tide.inactiveEnd).trim();
if (inactiveStart && inactiveEnd && isInTideInactiveWindow(inactiveStart, inactiveEnd)) return;
const isTgJid = isTelegramChatId(tideJid);
const waSock = whatsappSockRef.current;
if (isTgJid && !telegramBot) return;
if (!isTgJid && !waSock?.sendMessage) return;
const isTgGroup = isTelegramGroupJid(tideJid);
const historyMessages = isTgGroup
? readLastGroupExchanges(getWorkspaceDir(), tideJid, 5)
: readLastPrivateExchanges(getWorkspaceDir(), tideJid, 5);
if (historyMessages.length >= 2) {
const lastUserMsg = historyMessages[historyMessages.length - 2];
if (lastUserMsg.role === 'user' && lastUserMsg.content === 'Tide check') return;
}
const payload = JSON.stringify({
jid: tideJid,
storePath: getCronStorePath(),
workspaceDir: getWorkspaceDir(),
historyMessages,
});
let textToSend = '';
try {
textToSend = await new Promise((resolve, reject) => {
const child = spawn(process.execPath, ['cron/run-tide.js'], {
cwd: __dirname,
stdio: ['pipe', 'pipe', 'inherit'],
env: { ...process.env, COWCODE_STATE_DIR: process.env.COWCODE_STATE_DIR },
});
let out = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => { out += chunk; });
child.on('exit', (code, signal) => {
if (code !== 0 && code != null) {
reject(new Error(`run-tide exited with code ${code}`));
return;
}
if (signal) {
reject(new Error(`run-tide killed: ${signal}`));
return;
}
const lastLine = out.trim().split('\n').filter(Boolean).pop() || '';
try {
const parsed = JSON.parse(lastLine);
if (parsed.error) reject(new Error(parsed.error));
else resolve(parsed.textToSend || '');
} catch (e) {
reject(new Error(lastLine.slice(0, 100) || e.message || 'run-tide invalid output'));
}
});
child.on('error', reject);
child.stdin.end(payload, 'utf8');
});
} catch (e) {
console.error('[tide] run-tide failed:', getErrorMessageForLog(e));
return;
}
const rawText = sanitizeOutboundText((textToSend || '').trim());
let text = isTelegramChatId(tideJid) ? rawText.replace(/^\[CowCode\]\s*/i, '').trim() : rawText;
const nothingPhrases = /^(nothing|n\/?a|no(ne)?\s*to\s*do|all\s*good|nothing\s*to\s*report\.?)\s*\.?$/i;
if (!text || (text.length < 50 && nothingPhrases.test(text))) {
text = "What would you like to do next?";
}
try {
if (isTgJid && telegramBot) {
await sendLongText(telegramBot, Number(tideJid), text);
} else if (waSock?.sendMessage) {
await waSock.sendMessage(tideJid, { text });
}
console.log('[tide] Follow-up sent to', tideJidShort);
} catch (e) {
console.error('[tide] Send failed:', getErrorMessageForLog(e));
}
const exchange = { user: 'Tide check', assistant: text, timestampMs: Date.now(), jid: tideJid };
try {
if (isTgGroup) {
appendGroupExchange(getWorkspaceDir(), tideJid, exchange);
} else {
const memoryConfig = getMemoryConfig();
if (memoryConfig) {
await indexChatExchange(memoryConfig, exchange);
} else {
appendExchange(getWorkspaceDir(), exchange);
}
}
} catch (err) {
console.error('[tide] Chat log write failed:', err.message);
}
}
function scheduleTideFollowUp(jid) {
console.log('[tide] scheduleTideFollowUp called for', String(jid).slice(0, 24));
const config = getTideConfig();
const tide = config.tide || {};
if (!tide.enabled) {
console.log('[tide] Skipped (tide.enabled is false in config)');
return;
}
const inactiveStart = tide.inactiveStart && String(tide.inactiveStart).trim();
const inactiveEnd = tide.inactiveEnd && String(tide.inactiveEnd).trim();
if (inactiveStart && inactiveEnd && isInTideInactiveWindow(inactiveStart, inactiveEnd)) return;
const cooldownMinutes = Math.max(1, Number(tide.silenceCooldownMinutes) || 30);
const existing = tideTimerByJid.get(jid);
if (existing?.timeoutId) clearTimeout(existing.timeoutId);
const jidShort = String(jid).slice(0, 20) + (String(jid).length > 20 ? '…' : '');
if (existing?.timeoutId) {
console.log('[tide] Timer reset for', jidShort, '— follow-up in', cooldownMinutes, 'min');
} else {
console.log('[tide] Scheduled follow-up for', jidShort, 'in', cooldownMinutes, 'min');
}
const timeoutId = setTimeout(() => {
tideTimerByJid.delete(jid);
console.log('[tide] Sending follow-up to', jidShort);
runTideForJid(jid).catch((e) => console.error('[tide]', getErrorMessageForLog(e)));
}, cooldownMinutes * 60 * 1000);
tideTimerByJid.set(jid, { timeoutId });
}
function startTide(sockRef, selfJidRef) {
console.log('[tide] startTide() called');
const config = getTideConfig();
const tide = config.tide || {};
if (!tide.enabled) {
console.log('[tide] Disabled. Set tide.enabled to true in config for follow-ups after private replies.');
return;
}
const cooldownMinutes = Math.max(1, Number(tide.silenceCooldownMinutes) || 30);
console.log('[tide] Enabled. One follow-up per private reply after', cooldownMinutes, 'min of no reply.');
}
function stopTide() {
for (const [, entry] of tideTimerByJid) {
if (entry?.timeoutId) clearTimeout(entry.timeoutId);
}
tideTimerByJid.clear();
console.log('[tide] Stopped.');
}
const WHO_AM_I_MD = 'WhoAmI.md';
const MY_HUMAN_MD = 'MyHuman.md';
const SOUL_MD = 'SOUL.md';
const GROUP_MD = 'group.md';
const WORKSPACE_DEFAULT_FILES = [WHO_AM_I_MD, MY_HUMAN_MD, SOUL_MD, GROUP_MD];
const INSTALL_DIR = (process.env.COWCODE_INSTALL_DIR && resolve(process.env.COWCODE_INSTALL_DIR)) || __dirname;
const DEFAULT_WORKSPACE_DIR = join(INSTALL_DIR, 'workspace-default');
function readWorkspaceMd(filename) {
const p = join(getWorkspaceDir(), filename);
try {
if (existsSync(p)) return readFileSync(p, 'utf8').trim();
} catch (_) {}
return '';
}
/** Copy repo workspace-default/*.md into state workspace if they don't exist. */
function ensureWorkspaceDefaults() {
try {
ensureStateDir();
const workspaceDir = getWorkspaceDir();
for (const name of WORKSPACE_DEFAULT_FILES) {
const dest = join(workspaceDir, name);
if (existsSync(dest)) continue;
const src = join(DEFAULT_WORKSPACE_DIR, name);
if (existsSync(src)) copyFileSync(src, dest);
}
} catch (err) {
console.error('[workspace] could not copy default files:', err.message);
}
}
function ensureSoulMd() {
ensureWorkspaceDefaults();
}
/** Read initial soul from workspace-default/SOUL.md when workspace/group have no SOUL.md. */
function readDefaultSoul() {
const p = join(DEFAULT_WORKSPACE_DIR, SOUL_MD);
try {
if (existsSync(p)) return readFileSync(p, 'utf8').trim();
} catch (_) {}
return '';
}
function getBioFromConfig() {
try {
const raw = readFileSync(getConfigPath(), 'utf8');
const full = JSON.parse(raw);
return full.bio || null;
} catch (_) {
return null;
}
}
function isBioSet() {
if (readWorkspaceMd(WHO_AM_I_MD) || readWorkspaceMd(MY_HUMAN_MD)) return true;
const bio = getBioFromConfig();
if (bio == null) return false;
if (typeof bio === 'string') return (bio || '').trim() !== '';
return typeof bio === 'object' && (bio.userName != null || bio.prompt != null);
}
function saveBioToConfig(paragraph) {
const text = (paragraph || '').trim() || '';
try {
const path = getConfigPath();
const raw = existsSync(path) ? readFileSync(path, 'utf8') : '{}';
const config = raw.trim() ? JSON.parse(raw) : {};
config.bio = text;
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
} catch (err) {
console.error('[bio] save failed:', err.message);
}
if (text) {
try {
ensureStateDir();
const whoAmIPath = join(getWorkspaceDir(), WHO_AM_I_MD);
writeFileSync(whoAmIPath, text, 'utf8');
} catch (err) {
console.error('[bio] could not write WhoAmI.md:', err.message);
}
}
}
const BIO_CONFIRM_PROMPT = "Hey, we haven't done some basic setup. Do you want to do it now?";
const BIO_PROMPT =
"Before we continue — I'd like to know you a bit. Please answer in one message (any format is fine):\n\nWhat is my name?\nWhat is your name?\nWho am I?\nWho are you?";
function isYesReply(text) {
const t = (text || '').trim().toLowerCase();
return /^(y|yes|yeah|yep|sure|ok|okay|1|do it|please|go ahead|sounds good)$/.test(t) || t === 'yup';
}
/** Persist config.bio to WhoAmI.md once when workspace has no identity files (same behavior as before shared prompt). */
function ensureBioPersistedToWhoAmI() {
if (readWorkspaceMd(WHO_AM_I_MD) || readWorkspaceMd(MY_HUMAN_MD)) return;
const bio = getBioFromConfig();
const bioText = typeof bio === 'string' && (bio || '').trim() ? bio.trim() : null;
if (!bioText) return;
try {
ensureStateDir();
const whoAmIPath = join(getWorkspaceDir(), WHO_AM_I_MD);
if (!existsSync(whoAmIPath)) writeFileSync(whoAmIPath, bioText, 'utf8');
} catch (_) {}
}
function buildSystemPrompt(opts = {}) {
const agentId = (opts.agentId && String(opts.agentId).trim()) || DEFAULT_AGENT_ID;
const forGroup = !!opts.groupSenderName;
const groupJid = opts.groupJid || 'default';
if (forGroup) {
console.log('[path] buildSystemPrompt branch=group groupJid=', groupJid, 'agentId=', agentId);
ensureGroupConfigFor(groupJid);
} else {
console.log('[path] buildSystemPrompt branch=one-on-one agentId=', agentId);
ensureSoulMd();
ensureBioPersistedToWhoAmI();
return buildOneOnOneSystemPrompt(getAgentWorkspaceDir(agentId));
}
const basePrompt = buildOneOnOneSystemPrompt(getAgentWorkspaceDir(agentId));
const loaded = loadGroupMd(getWorkspaceDir(), DEFAULT_WORKSPACE_DIR);
const groupBlock = buildGroupPromptBlock(loaded, {
groupSenderName: opts.groupSenderName,
groupMentioned: !!opts.groupMentioned,
groupNonOwner: !!opts.groupNonOwner,
});
console.log('[path] buildSystemPrompt groupBlockLen=', (groupBlock || '').length, 'basePromptLen=', basePrompt.length);
return groupBlock ? (basePrompt + '\n\n' + groupBlock) : basePrompt;
}
/** Remove em-dash glyphs from outbound assistant text before sending. */
function sanitizeOutboundText(text) {
if (text == null) return '';
return String(text)
.replace(/\s*—\s*/g, ' ')
.replace(/[ \t]{2,}/g, ' ')
.trim();
}
async function runAgentWithSkills(sock, jid, text, lastSentByJidMap, selfJidForCron, ourSentIdsRef, bioOpts = {}) {
let skillsCalled = [];
console.log('[agent] handling:', text.slice(0, 50) + (text.length > 50 ? '…' : ''));
try {
await sock.sendPresenceUpdate('composing', jid);
} catch (_) {}
const isGroupJid = isTelegramGroupJid(jid) || isWhatsAppGroupJid(jid);
const agentId = (bioOpts.agentIdOverride && String(bioOpts.agentIdOverride).trim())
|| (isGroupJid ? resolveAgentIdForGroup(jid) : DEFAULT_AGENT_ID);
console.log('[path] chat=', isGroupJid ? 'group' : 'one-on-one', 'jid=', jid, 'agentId=', agentId);
const ctx = {
storePath: getCronStorePath(),
jid,
workspaceDir: getWorkspaceDir(),
agentId,
scheduleOneShot,
startCron: () => startCron({ sock, selfJid: selfJidForCron, storePath: getCronStorePath(), telegramBot: telegramBot || undefined }),
groupNonOwner: !!bioOpts.groupNonOwner,
isGroup: isGroupJid,
};
const isGroupNonOwner = !!bioOpts.groupNonOwner;
const skillContext = getSkillContext({ groupJid: isGroupJid ? jid : undefined, agentId });
const toolsForRequest = Array.isArray(skillContext.runSkillTool) && skillContext.runSkillTool.length > 0
? skillContext.runSkillTool
: [];
const toolNames = (toolsForRequest || []).map((t) => t?.function?.name).filter(Boolean);
console.log('[path] toolsCount=', toolsForRequest.length, toolNames.length ? 'tools=' + toolNames.join(',') : '');
const systemPromptOpts = isGroupNonOwner
? {
groupSenderName: bioOpts.groupSenderName,
groupJid: jid,
groupMentioned: !!bioOpts.groupMentioned,
groupNonOwner: true,
agentId,
}
: { groupSenderName: bioOpts.groupSenderName, agentId };
const inMemoryHistory = getLast5Exchanges(jid);
const historyMessages = isGroupJid
? readLastGroupExchanges(getWorkspaceDir(), jid, MAX_CHAT_HISTORY_EXCHANGES)
: (inMemoryHistory.length > 0 ? inMemoryHistory : readLastPrivateExchanges(getWorkspaceDir(), jid, MAX_CHAT_HISTORY_EXCHANGES));
const systemPrompt = buildSystemPrompt(systemPromptOpts);
console.log('[path] runAgentTurn systemPromptLen=', systemPrompt.length, 'toolsCount=', toolsForRequest.length);
const turnResult = await runAgentTurn({
userText: text,
ctx,
systemPrompt,
tools: toolsForRequest,
historyMessages,
getFullSkillDoc: skillContext.getFullSkillDoc,
resolveToolName: skillContext.resolveToolName,
});
let resultToUse = turnResult;
let skillsCalledFromTurn = Array.isArray(turnResult?.skillsCalled) && turnResult.skillsCalled.length ? turnResult.skillsCalled : [];
const hasSearchOrBrowse = (arr) => Array.isArray(arr) && (arr.includes('search') || arr.includes('browse'));
const hasSearchOrBrowseTool = toolsForRequest.some(
(t) => t?.function?.name?.startsWith('search_') || t?.function?.name === 'browse_navigate',
);
const firstReply = sanitizeOutboundText((turnResult?.textToSend || '').trim());
const firstTextForSend = isTelegramChatId(jid) ? firstReply.replace(/^\[CowCode\]\s*/i, '').trim() : firstReply;
if (
hasSearchOrBrowseTool &&
!hasSearchOrBrowse(skillsCalledFromTurn) &&
skillsCalledFromTurn.length === 0 &&
firstTextForSend
) {
// Ask the LLM whether the answer is actually complete before deciding to retry.
// This replaces the old structural check (no tools called = uncertain) which fired
// for greetings, jokes, and any direct answer that legitimately needed no tools.
let needsSearch = false;
try {
const probeReply = await llmChat([
{ role: 'system', content: 'You are a quality checker. Answer only with valid JSON, no prose.' },
{
role: 'user',
content:
`User asked: "${text.slice(0, 300)}"\n\nAssistant answered: "${firstTextForSend.slice(0, 300)}"\n\n` +
`Does the answer fully address the user's question, or does it need real-time / current information from a web search to be complete?\n` +
`Reply with exactly one of:\n{ "complete": true }\n{ "complete": false }`,
},
], llmOptions);
const probe = JSON.parse(stripThinking(probeReply || '').trim());
needsSearch = probe?.complete === false;
} catch (_) {}
if (needsSearch) {
console.log('[agent] LLM probe: answer incomplete, retrying with search instruction');
const retryUserText =
`[Retry with search] The user asked: "${text.slice(0, 500)}${text.length > 500 ? '…' : ''}". Use the search skill (or browse if they gave a URL) to look up current information, then reply with what you find.`;
try {
const retryResult = await runAgentTurn({
userText: retryUserText,
ctx,
systemPrompt,
tools: toolsForRequest,
historyMessages,
getFullSkillDoc: skillContext.getFullSkillDoc,
resolveToolName: skillContext.resolveToolName,
});
if (retryResult?.textToSend?.trim() && hasSearchOrBrowse(retryResult.skillsCalled)) {
resultToUse = retryResult;
skillsCalledFromTurn = Array.isArray(retryResult.skillsCalled) ? retryResult.skillsCalled : skillsCalledFromTurn;
}
} catch (err) {
console.error('[agent] retry with search failed:', getErrorMessageForLog(err));
}
}
}
const { textToSend, voiceReplyText, imageReplyPath, imageReplyCaption, skillsCalled: called } = resultToUse || {};
if (Array.isArray(called) && called.length) skillsCalled = called;
const cleanedTextToSend = sanitizeOutboundText(textToSend || '');
const cleanedVoiceReplyText = sanitizeOutboundText(voiceReplyText || '');
const textForSend = isTelegramChatId(jid) ? cleanedTextToSend.replace(/^\[CowCode\]\s*/i, '').trim() : cleanedTextToSend;
const isGroupNoReply = bioOpts.groupNonOwner && !bioOpts.groupMentioned &&
!(cleanedVoiceReplyText && cleanedVoiceReplyText.trim()) &&
(!textForSend || !textForSend.trim() || /^\[NO_REPLY\]\s*$/i.test(textForSend.trim()));
if (!isGroupNoReply) {
let voiceBuffer = null;
let imageBuffer = null;
if (imageReplyPath && existsSync(imageReplyPath)) {
try {
imageBuffer = readFileSync(imageReplyPath);
} catch (err) {
console.error('[vision] read image failed:', err.message);
}
}
const forceVoiceReply = !!bioOpts.forceVoiceReply;
const textForVoice = (cleanedVoiceReplyText && cleanedVoiceReplyText.trim())
? cleanedVoiceReplyText.trim()
: ((forceVoiceReply && textForSend && textForSend.trim()) ? textForSend.trim() : null);
if (textForVoice && !imageBuffer) {
try {
const speechConfig = getSpeechConfig();
if (speechConfig?.elevenLabsApiKey) {
voiceBuffer = await synthesizeToBuffer(speechConfig.elevenLabsApiKey, textForVoice, speechConfig.defaultVoiceId);
}
} catch (err) {
console.error('[speech] synthesize failed:', err.message);
}
}
const replyText = (cleanedVoiceReplyText && cleanedVoiceReplyText.trim()) ? cleanedVoiceReplyText.trim() : textForSend;
const captionForImage = (replyText && replyText.trim()) ? replyText.replace(/^\[CowCode\]\s*/i, '').trim() : (imageReplyCaption || '');
try {
let sent;
if (voiceBuffer) {
sent = await sock.sendMessage(jid, isTelegramChatId(jid) ? { voice: voiceBuffer } : { audio: voiceBuffer, ptt: true });
} else if (imageBuffer) {
sent = await sock.sendMessage(jid, isTelegramChatId(jid)
? { image: imageBuffer, caption: captionForImage }
: { image: imageBuffer, caption: captionForImage, mimetype: 'image/png' });
} else {
sent = await sock.sendMessage(jid, { text: replyText });
}
if (sent?.key?.id && ourSentIdsRef?.current) {
ourSentIdsRef.current.add(sent.key.id);
if (ourSentIdsRef.current.size > MAX_OUR_SENT_IDS) {
const first = ourSentIdsRef.current.values().next().value;
if (first) ourSentIdsRef.current.delete(first);
}
}
lastSentByJidMap.set(jid, replyText);
pushExchange(jid, text, replyText);
const ts = Date.now();
const exchange = { user: text, assistant: replyText, timestampMs: ts, jid };
if (bioOpts.logExchange) {
bioOpts.logExchange(exchange);
} else {
if (isGroupJid) {
try {
appendGroupExchange(getWorkspaceDir(), jid, exchange);
} catch (err) {
console.error('[group-chat-log] write failed:', err.message);
}
} else {
const memoryConfig = getMemoryConfig();
if (memoryConfig) {
const indexPromise = indexChatExchange(memoryConfig, exchange).catch((err) =>
console.error('[memory] auto-index failed:', err.message)
);
if (process.argv.includes('--test')) await indexPromise;
}
}
}
console.log('[replied]', toolsForRequest.length > 0 ? '(agent + skills)' : '(chat)');
console.log('[replied] question:', text);
const partialLen = 300;
console.log('[replied] answer (partial):', (replyText || '').slice(0, partialLen) + ((replyText || '').length > partialLen ? '…' : ''));
if (Array.isArray(skillsCalled) && skillsCalled.length > 0) {
console.log('[replied] skills called:', skillsCalled.join(', '));
}
if (!isGroupJid || isTelegramGroupJid(jid)) scheduleTideFollowUp(jid);
const alreadySentBioPrompt = bioOpts.bioPromptSentJids?.has(jid);
if (bioOpts.pendingBioConfirmJids != null && !isBioSet() && !alreadySentBioPrompt) {
try {
await sock.sendMessage(jid, { text: BIO_CONFIRM_PROMPT });
bioOpts.pendingBioConfirmJids.add(jid);
bioOpts.bioPromptSentJids?.add(jid);
} catch (_) {
if (isTelegramChatId(jid)) addPendingTelegram(jid, BIO_CONFIRM_PROMPT);
else pendingReplies.push({ jid, text: BIO_CONFIRM_PROMPT });
bioOpts.pendingBioConfirmJids.add(jid);
bioOpts.bioPromptSentJids?.add(jid);
}
}
} catch (sendErr) {
lastSentByJidMap.set(jid, replyText); // E2E can still assert on intended reply when send fails
const errMsg = getErrorMessageForLog(sendErr);
if (!isTelegramChatId(jid)) {
pendingReplies.push({ jid, text: replyText });
console.log('[replied] queued (send failed, will retry after reconnect):', errMsg);
} else {
addPendingTelegram(jid, replyText);
console.log('[replied] Telegram queued (send failed, will retry on next message):', errMsg);
}
if (!isGroupJid || isTelegramGroupJid(jid)) scheduleTideFollowUp(jid);
}
}
return { skillsCalled: skillsCalled || [] };
}
// --test / --test-group: run main code path once with mock socket (set above), then exit. No WhatsApp auth.
// E2E tests capture stdout and parse E2E_REPLY_START...E2E_REPLY_END to assert on the reply.
const testGroupMode = process.argv.includes('--test-group');
if (process.argv.includes('--test') || testGroupMode) {
const testFlag = testGroupMode ? '--test-group' : '--test';
const testIdx = process.argv.indexOf(testFlag);
const argValue = (flag, fallback = '') => {
const idx = process.argv.indexOf(flag);
if (idx === -1) return fallback;
const next = process.argv[idx + 1];
if (!next || String(next).startsWith('--')) return fallback;
return next;
};
const testMsg1 = process.argv[testIdx + 1] || process.env.TEST_MESSAGE || 'Send me hello in 1 minute';
const testMsg2 = process.env.TEST_MESSAGE_2;
const testAgentId = argValue('--test-agent', '');
const testJid = testGroupMode
? argValue('--test-jid', '-1003722613696')
: argValue('--test-jid', 'test@s.whatsapp.net');
const testSender = argValue('--test-sender', 'Test Group User');
const lastSent = new Map();
const sentIds = { current: new Set() };
for (const [i, testMsg] of [testMsg1, testMsg2].filter(Boolean).entries()) {
console.log('[test] Running', testGroupMode ? 'group' : 'one-on-one', 'code path with message', i + 1 + ':', testMsg.slice(0, 60));
let runRet = { skillsCalled: [] };
try {
runRet = await runAgentWithSkills(sock, testJid, testMsg, lastSent, testJid, sentIds, {
...(testGroupMode
? { groupNonOwner: true, groupSenderName: testSender, groupMentioned: true }
: {}),
...(testAgentId ? { agentIdOverride: testAgentId } : {}),
}) || runRet;
} catch (err) {
lastSent.set(testJid, 'Moo — ' + (err && err.message ? err.message : String(err)));
}
const reply = lastSent.get(testJid);
if (reply != null && (testMsg2 ? (i === 1) : true)) {
if (Array.isArray(runRet.skillsCalled) && runRet.skillsCalled.length) {
console.log('E2E_SKILLS_CALLED: ' + runRet.skillsCalled.join(','));
}
console.log('E2E_REPLY_START');
process.stdout.write(reply + '\n');
console.log('E2E_REPLY_END');
}
}
console.log('[test] Done. Check cron/jobs.json.');
process.exit(0);
}
// Telegram-only mode: no WhatsApp; run only Telegram bot and cron.
if (telegramOnlyMode) {
const telegramToken = channelsConfig.telegram.botToken;