-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent.js
More file actions
1891 lines (1632 loc) · 76.4 KB
/
agent.js
File metadata and controls
1891 lines (1632 loc) · 76.4 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 { createProvider, PROVIDERS, MODEL_FALLBACKS } from './providers/index.js';
import { BaseProvider } from './providers/base.js';
import { orchestratorToolDefinitions, executeOrchestratorTool } from './tools/orchestrator-tools.js';
import { getToolsForWorker } from './swarm/worker-registry.js';
import { WORKER_TYPES } from './swarm/worker-registry.js';
import { getOrchestratorPrompt } from './prompts/orchestrator.js';
import { getWorkerPrompt } from './prompts/workers.js';
import { getSkillById, buildSkillPrompt, filterSkillsForWorker } from './skills/loader.js';
import { SkillForge } from './skills/forge.js';
import { WorkerAgent } from './worker.js';
import { getLogger } from './utils/logger.js';
import { getMissingCredential, saveCredential, saveProviderToYaml, saveOrchestratorToYaml, saveClaudeCodeModelToYaml, saveClaudeCodeAuth } from './utils/config.js';
import { resetClaudeCodeSpawner, getSpawner } from './tools/coding.js';
import { truncateToolResult } from './utils/truncate.js';
import { personaShieldDepthLimit } from './utils/persona-shield.js';
/**
* Format a time gap in minutes into natural, human-readable language.
* e.g. 45 → "about 45 minutes", 90 → "about an hour and a half",
* 180 → "about 3 hours", 1500 → "over a day"
*/
function formatTimeGap(minutes) {
if (minutes < 60) return `about ${minutes} minutes`;
const hours = Math.floor(minutes / 60);
const remainingMins = minutes % 60;
if (hours < 24) {
if (hours === 1 && remainingMins < 15) return 'about an hour';
if (hours === 1 && remainingMins >= 15 && remainingMins < 45) return 'about an hour and a half';
if (hours === 1) return 'nearly 2 hours';
if (remainingMins < 15) return `about ${hours} hours`;
if (remainingMins >= 30) return `about ${hours} and a half hours`;
return `about ${hours} hours`;
}
const days = Math.floor(hours / 24);
if (days === 1) return 'over a day';
return `about ${days} days`;
}
export class OrchestratorAgent {
constructor({ config, conversationManager, personaManager, selfManager, jobManager, automationManager, memoryManager, shareQueue, characterManager, brainDB }) {
this.config = config;
this.conversationManager = conversationManager;
this.personaManager = personaManager;
this.selfManager = selfManager || null;
this.jobManager = jobManager;
this.automationManager = automationManager || null;
this.memoryManager = memoryManager || null;
this.shareQueue = shareQueue || null;
this.characterManager = characterManager || null;
this._brainDB = brainDB || null;
this.worldModel = null;
this.feedbackEngine = null;
this.causalMemory = null;
this.behavioralDNA = null;
this.synthesisLoop = null;
this.identityAwareness = null;
this.onboardingManager = null;
this.skillForge = new SkillForge({ agent: this, memoryManager, config });
this._activePersonaMd = null;
this._activeCharacterName = null;
this._activeCharacterId = null;
this._pending = new Map(); // chatId -> pending state
this._pendingOutcomes = new Map(); // jobId -> { timestamp, chatId, userId, characterId }
// Character-scoped conversation keys: prefix chatId with character ID
// so each character has isolated conversation history.
this._chatCallbacks = new Map(); // chatId -> { onUpdate, sendPhoto }
// Orchestrator provider (30s timeout — lean dispatch/summarize calls)
const orchProviderKey = config.orchestrator.provider || 'anthropic';
const orchProviderDef = PROVIDERS[orchProviderKey];
const orchApiKey = config.orchestrator.api_key || (orchProviderDef && process.env[orchProviderDef.envKey]);
this.orchestratorProvider = createProvider({
brain: {
provider: orchProviderKey,
model: config.orchestrator.model,
max_tokens: config.orchestrator.max_tokens,
temperature: config.orchestrator.temperature,
api_key: orchApiKey,
timeout: 30_000,
},
});
// Worker provider uses user's chosen brain
this.workerProvider = createProvider(config);
// Set up job lifecycle event listeners
this._setupJobListeners();
}
/** Build the orchestrator system prompt. */
_getSystemPrompt(chatId, user, temporalContext = null, identityCtx = null) {
const logger = getLogger();
const key = this._chatKey(chatId);
const skillIds = this.conversationManager.getSkills(key);
const skillPrompt = buildSkillPrompt(skillIds);
let userPersona = null;
if (this.personaManager && user?.id) {
userPersona = this.personaManager.getCompactPersona
? this.personaManager.getCompactPersona(user.id, user.username)
: this.personaManager.load(user.id, user.username);
}
let selfData = null;
if (this.behavioralDNA) {
try {
selfData = this.behavioralDNA.buildDNAContext(user?.id || null, this._activeCharacterId || 'default');
} catch (err) {
logger.warn(`[Orchestrator] BehavioralDNA context build failed: ${err.message}`);
}
}
if (!selfData && this.selfManager) {
selfData = this.selfManager.loadAll();
}
// Build memory context block (scope-filtered for non-owner)
let memoriesBlock = null;
if (this.memoryManager) {
let senderType = 'owner';
if (this.identityAwareness && user?.id) {
const sender = this.identityAwareness.getSender(String(user.id));
if (sender) senderType = sender.sender_type;
}
memoriesBlock = this.memoryManager.buildContextBlock(user?.id || null, senderType);
}
// Build share queue block
let sharesBlock = null;
if (this.shareQueue) {
sharesBlock = this.shareQueue.buildShareBlock(user?.id || null);
}
// Build forge expertise profile
const forgeExpertise = this.skillForge.buildExpertiseProfile();
const forgeSkillsSummary = this.skillForge.buildLearnedSkillsSummary();
// Build world model context
let worldContext = null;
if (this.worldModel) {
try {
worldContext = this.worldModel.buildWorldContext(this._activeCharacterId || 'default', user?.id || null);
} catch (err) {
logger.warn(`[Orchestrator] WorldModel context build failed: ${err.message}`);
}
}
// Build task intelligence from causal memory
let taskIntelligence = null;
if (this.causalMemory) {
try {
taskIntelligence = this.causalMemory.buildOrchestratorContext(this._activeCharacterId || 'default');
} catch (err) {
logger.warn(`[Orchestrator] Task intelligence build failed: ${err.message}`);
}
}
// Build feedback adjustments block
let adjustmentsBlock = null;
if (this.feedbackEngine) {
try {
adjustmentsBlock = this.feedbackEngine.buildAdjustmentBlock(
user?.id || null, this._activeCharacterId || 'default'
);
} catch (err) {
logger.warn(`[Orchestrator] Adjustment block build failed: ${err.message}`);
}
}
// Inject user training context from onboarding
if (this.onboardingManager && user?.id) {
try {
const onboardState = this.onboardingManager.getState(user.id);
if (onboardState?.phase === 'complete' && onboardState.training_notes) {
const notes = onboardState.training_notes;
const trainingLines = [];
if (notes.brand_voice) trainingLines.push(`- Brand voice: ${notes.brand_voice}`);
if (notes.workflows) trainingLines.push(`- Workflows: ${notes.workflows}`);
if (notes.custom_instructions) trainingLines.push(`- Instructions: ${notes.custom_instructions}`);
if (notes.tools) trainingLines.push(`- Tools: ${notes.tools}`);
if (trainingLines.length > 0) {
const trainingBlock = `\n## User Training Context\n${trainingLines.join('\n')}`;
userPersona = (userPersona || '') + trainingBlock;
}
}
} catch (err) {
logger.warn(`[Orchestrator] Training context build failed: ${err.message}`);
}
}
logger.debug(`Orchestrator building system prompt for chat ${chatId} | skills=${skillIds.length > 0 ? skillIds.join(',') : 'none'} | persona=${userPersona ? 'yes' : 'none'} | self=${selfData ? 'yes' : 'none'} | memories=${memoriesBlock ? 'yes' : 'none'} | shares=${sharesBlock ? 'yes' : 'none'} | temporal=${temporalContext ? 'yes' : 'none'} | character=${this._activeCharacterId || 'default'} | forge=${forgeExpertise ? 'yes' : 'none'} | world=${worldContext ? 'yes' : 'none'} | adjustments=${adjustmentsBlock ? 'yes' : 'none'} | causal=${taskIntelligence ? 'yes' : 'none'} | identity=${identityCtx ? 'yes' : 'none'}`);
return getOrchestratorPrompt(this.config, skillPrompt || null, userPersona, selfData, memoriesBlock, sharesBlock, temporalContext, this._activePersonaMd, this._activeCharacterName, forgeExpertise, forgeSkillsSummary, worldContext, adjustmentsBlock, taskIntelligence, identityCtx);
}
// ── Multi-skill methods ─────────────────────────────────────────────
/** Toggle a skill on/off for a chat. Returns { added: bool, skills: string[] }. */
toggleSkill(chatId, skillId) {
const key = this._chatKey(chatId);
const current = this.conversationManager.getSkills(key);
if (current.includes(skillId)) {
this.conversationManager.removeSkill(key, skillId);
return { added: false, skills: this.conversationManager.getSkills(key) };
}
const added = this.conversationManager.addSkill(key, skillId);
return { added, skills: this.conversationManager.getSkills(key) };
}
/** Get all active skill IDs for a chat. */
getActiveSkillIds(chatId) {
return this.conversationManager.getSkills(this._chatKey(chatId));
}
/** Get all active skill objects for a chat. */
getActiveSkills(chatId) {
const ids = this.getActiveSkillIds(chatId);
return ids.map(id => getSkillById(id)).filter(Boolean);
}
// Backward-compat aliases
setSkill(chatId, skillId) {
this.conversationManager.setSkill(this._chatKey(chatId), skillId);
}
clearSkill(chatId) {
this.conversationManager.clearSkills(this._chatKey(chatId));
}
getActiveSkill(chatId) {
const skills = this.getActiveSkills(chatId);
return skills.length > 0 ? skills[0] : null;
}
/**
* Load a character's context into the agent.
* Called on startup and on character switch.
*/
async loadCharacter(characterId) {
const logger = getLogger();
if (!this.characterManager) return;
const ctx = await this.characterManager.buildContext(characterId, { brainDB: this._brainDB });
this._activeCharacterId = characterId;
this._activePersonaMd = ctx.personaMd;
this._activeCharacterName = ctx.profile.name;
this.selfManager = ctx.selfManager;
this.memoryManager = ctx.memoryManager;
this.shareQueue = ctx.shareQueue;
// Initialize WorldModel if BrainDB is available
if (this._brainDB?.isOpen && !this.worldModel) {
try {
const { WorldModel } = await import('./brain/world-model.js');
this.worldModel = new WorldModel(this._brainDB);
logger.info('[Agent] WorldModel initialized');
} catch (err) {
logger.warn(`[Agent] WorldModel init failed: ${err.message}`);
}
}
logger.info(`[Agent] Loaded character: ${ctx.profile.name} (${characterId})`);
return ctx;
}
/**
* Switch to a different character at runtime.
* Returns the new context for life engine rebuild.
*/
async switchCharacter(characterId) {
const logger = getLogger();
if (!this.characterManager) throw new Error('CharacterManager not available');
const ctx = await this.loadCharacter(characterId);
this.characterManager.setActiveCharacter(characterId);
logger.info(`[Agent] Switched to character: ${ctx.profile.name} (${characterId})`);
return ctx;
}
/** Get active character info for display. */
getActiveCharacterInfo() {
if (!this.characterManager) return null;
const id = this._activeCharacterId || this.characterManager.getActiveCharacterId();
return this.characterManager.getCharacter(id);
}
/**
* Build a character-scoped conversation key.
* Prefixes chatId with the active character ID so each character
* has its own isolated conversation history.
* Raw chatId is still used for Telegram callbacks, job events, etc.
*/
_chatKey(chatId) {
if (this._activeCharacterId) {
return `${this._activeCharacterId}:${chatId}`;
}
return String(chatId);
}
/** Clear conversation history for a chat (character-scoped). */
clearConversation(chatId) {
this.conversationManager.clear(this._chatKey(chatId));
}
/** Get message count for a chat (character-scoped). */
getMessageCount(chatId) {
return this.conversationManager.getMessageCount(this._chatKey(chatId));
}
/** Get conversation history for a chat (character-scoped). */
getConversationHistory(chatId) {
return this.conversationManager.getHistory(this._chatKey(chatId));
}
/** Return current worker brain info for display. */
getBrainInfo() {
const { provider, model } = this.config.brain;
const providerDef = PROVIDERS[provider];
const providerName = providerDef ? providerDef.name : provider;
const modelEntry = providerDef?.models.find((m) => m.id === model);
const modelLabel = modelEntry ? modelEntry.label : model;
return { provider, providerName, model, modelLabel };
}
/** Return current orchestrator info for display. */
getOrchestratorInfo() {
const provider = this.config.orchestrator.provider || 'anthropic';
const model = this.config.orchestrator.model;
const providerDef = PROVIDERS[provider];
const providerName = providerDef ? providerDef.name : provider;
const modelEntry = providerDef?.models.find((m) => m.id === model);
const modelLabel = modelEntry ? modelEntry.label : model;
return { provider, providerName, model, modelLabel };
}
/** Switch orchestrator provider/model at runtime. */
async switchOrchestrator(providerKey, modelId) {
const logger = getLogger();
const providerDef = PROVIDERS[providerKey];
if (!providerDef) return `Unknown provider: ${providerKey}`;
const envKey = providerDef.envKey;
const apiKey = process.env[envKey];
if (!apiKey) return envKey;
try {
const testProvider = createProvider({
brain: {
provider: providerKey,
model: modelId,
max_tokens: this.config.orchestrator.max_tokens,
temperature: this.config.orchestrator.temperature,
api_key: apiKey,
timeout: 30_000,
},
});
await testProvider.ping();
this.config.orchestrator.provider = providerKey;
this.config.orchestrator.model = modelId;
this.config.orchestrator.api_key = apiKey;
this.orchestratorProvider = testProvider;
saveOrchestratorToYaml(providerKey, modelId);
logger.info(`Orchestrator switched to ${providerDef.name} / ${modelId}`);
return null;
} catch (err) {
logger.error(`Orchestrator switch failed for ${providerDef.name} / ${modelId}: ${err.message}`);
return { error: err.message };
}
}
/** Finalize orchestrator switch after API key was provided via chat. */
async switchOrchestratorWithKey(providerKey, modelId, apiKey) {
const logger = getLogger();
const providerDef = PROVIDERS[providerKey];
try {
const testProvider = createProvider({
brain: {
provider: providerKey,
model: modelId,
max_tokens: this.config.orchestrator.max_tokens,
temperature: this.config.orchestrator.temperature,
api_key: apiKey,
timeout: 30_000,
},
});
await testProvider.ping();
saveCredential(this.config, providerDef.envKey, apiKey);
this.config.orchestrator.provider = providerKey;
this.config.orchestrator.model = modelId;
this.config.orchestrator.api_key = apiKey;
this.orchestratorProvider = testProvider;
saveOrchestratorToYaml(providerKey, modelId);
logger.info(`Orchestrator switched to ${providerDef.name} / ${modelId} (new key saved)`);
return null;
} catch (err) {
logger.error(`Orchestrator switch failed for ${providerDef.name} / ${modelId}: ${err.message}`);
return { error: err.message };
}
}
/** Return current Claude Code model info for display. */
getClaudeCodeInfo() {
const model = this.config.claude_code?.model || 'claude-opus-4-6';
const providerDef = PROVIDERS.anthropic;
const modelEntry = providerDef?.models.find((m) => m.id === model);
const modelLabel = modelEntry ? modelEntry.label : model;
return { model, modelLabel };
}
/** Switch Claude Code model at runtime. */
switchClaudeCodeModel(modelId) {
const logger = getLogger();
this.config.claude_code.model = modelId;
saveClaudeCodeModelToYaml(modelId);
resetClaudeCodeSpawner();
logger.info(`Claude Code model switched to ${modelId}`);
}
/** Return current Claude Code auth config for display. */
getClaudeAuthConfig() {
const mode = this.config.claude_code?.auth_mode || 'system';
const info = { mode };
if (mode === 'api_key') {
const key = this.config.claude_code?.api_key || process.env.CLAUDE_CODE_API_KEY || '';
info.credential = key ? `${key.slice(0, 8)}...${key.slice(-4)}` : '(not set)';
} else if (mode === 'oauth_token') {
const token = this.config.claude_code?.oauth_token || process.env.CLAUDE_CODE_OAUTH_TOKEN || '';
info.credential = token ? `${token.slice(0, 8)}...${token.slice(-4)}` : '(not set)';
} else {
info.credential = 'Using host system login';
}
return info;
}
/** Set Claude Code auth mode + credential at runtime. */
setClaudeCodeAuth(mode, value) {
const logger = getLogger();
saveClaudeCodeAuth(this.config, mode, value);
resetClaudeCodeSpawner();
logger.info(`Claude Code auth mode set to: ${mode}`);
}
/** Switch worker brain provider/model at runtime. */
async switchBrain(providerKey, modelId) {
const logger = getLogger();
const providerDef = PROVIDERS[providerKey];
if (!providerDef) return `Unknown provider: ${providerKey}`;
const envKey = providerDef.envKey;
const apiKey = process.env[envKey];
if (!apiKey) return envKey;
try {
const testConfig = { ...this.config, brain: { ...this.config.brain, provider: providerKey, model: modelId, api_key: apiKey } };
const testProvider = createProvider(testConfig);
await testProvider.ping();
this.config.brain.provider = providerKey;
this.config.brain.model = modelId;
this.config.brain.api_key = apiKey;
this.workerProvider = testProvider;
saveProviderToYaml(providerKey, modelId);
logger.info(`Worker brain switched to ${providerDef.name} / ${modelId}`);
return null;
} catch (err) {
logger.error(`Brain switch failed for ${providerDef.name} / ${modelId}: ${err.message}`);
return { error: err.message };
}
}
/** Finalize brain switch after API key was provided via chat. */
async switchBrainWithKey(providerKey, modelId, apiKey) {
const logger = getLogger();
const providerDef = PROVIDERS[providerKey];
try {
const testConfig = { ...this.config, brain: { ...this.config.brain, provider: providerKey, model: modelId, api_key: apiKey } };
const testProvider = createProvider(testConfig);
await testProvider.ping();
saveCredential(this.config, providerDef.envKey, apiKey);
this.config.brain.provider = providerKey;
this.config.brain.model = modelId;
this.config.brain.api_key = apiKey;
this.workerProvider = testProvider;
saveProviderToYaml(providerKey, modelId);
logger.info(`Worker brain switched to ${providerDef.name} / ${modelId} (new key saved)`);
return null;
} catch (err) {
logger.error(`Brain switch failed for ${providerDef.name} / ${modelId}: ${err.message}`);
return { error: err.message };
}
}
/** Truncate a tool result. Delegates to shared utility. */
_truncateResult(name, result) {
return truncateToolResult(name, result);
}
async processMessage(chatId, userMessage, user, onUpdate, sendPhoto, opts = {}) {
const logger = getLogger();
logger.info(`Orchestrator processing message for chat ${chatId} from ${user?.username || user?.id || 'unknown'}: "${userMessage.slice(0, 120)}"`);
// Store callbacks so workers can use them later
this._chatCallbacks.set(chatId, { onUpdate, sendPhoto, sendReaction: opts.sendReaction, lastUserMessageId: opts.messageId });
// Handle pending responses (confirmation or credential)
const pending = this._pending.get(chatId);
if (pending) {
this._pending.delete(chatId);
logger.debug(`Orchestrator handling pending ${pending.type} response for chat ${chatId}`);
if (pending.type === 'credential') {
return await this._handleCredentialResponse(chatId, userMessage, user, pending, onUpdate);
}
}
const { max_tool_depth } = this.config.orchestrator;
// Character-scoped conversation key
const convKey = this._chatKey(chatId);
// Detect time gap before adding the new message
let temporalContext = null;
const lastTs = this.conversationManager.getLastMessageTimestamp(convKey);
if (lastTs) {
const gapMs = Date.now() - lastTs;
const gapMinutes = Math.floor(gapMs / 60_000);
if (gapMinutes >= 30) {
const gapText = formatTimeGap(gapMinutes);
temporalContext = `[Time gap detected: ${gapText} since last message. User may be starting a new topic — consider a fresh greeting.]`;
logger.info(`Time gap detected for chat ${chatId}: ${gapText}`);
}
}
// Add user message to persistent history
this.conversationManager.addMessage(convKey, 'user', userMessage);
// Build working messages from compressed history
const messages = [...this.conversationManager.getSummarizedHistory(convKey)];
// If an image is attached, upgrade the last user message to a multimodal content array
if (opts.imageAttachment) {
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'user' && typeof messages[i].content === 'string') {
messages[i] = {
role: 'user',
content: [
{ type: 'image', source: opts.imageAttachment },
{ type: 'text', text: messages[i].content },
],
};
break;
}
}
logger.info(`[Orchestrator] Image attached to message for chat ${chatId} (${opts.imageAttachment.media_type})`);
}
// Classify sender and build identity context
let identityCtx = null;
if (this.identityAwareness && opts.telegramUser) {
try {
this.identityAwareness.classifySender(opts.telegramUser, opts.chatInfo);
identityCtx = this.identityAwareness.buildIdentityContext(
String(user?.id), opts.chatInfo || { type: 'private' },
);
} catch (err) {
logger.warn(`[Orchestrator] Identity classification failed: ${err.message}`);
}
}
logger.debug(`Orchestrator conversation context: ${messages.length} messages, max_depth=${max_tool_depth}`);
const reply = await this._runLoop(chatId, messages, user, 0, max_tool_depth, temporalContext, identityCtx);
logger.info(`Orchestrator reply for chat ${chatId}: "${(reply || '').slice(0, 150)}"`);
// Background persona extraction + self-reflection (log failures for diagnostics)
this._extractPersonaBackground(userMessage, reply, user).catch((err) => {
logger.warn(`[Orchestrator] Background persona extraction failed: ${err.message}`);
});
this._reflectOnSelfBackground(userMessage, reply, user).catch((err) => {
logger.warn(`[Orchestrator] Background self-reflection failed: ${err.message}`);
});
this._extractWorldModelBackground(userMessage, reply, user).catch((err) => {
logger.warn(`[Orchestrator] Background world model extraction failed: ${err.message}`);
});
this._detectFeedbackBackground(userMessage, reply, user, chatId).catch((err) => {
logger.warn(`[Orchestrator] Background feedback detection failed: ${err.message}`);
});
// Check pending task outcomes — if user message references a completed job
this._checkPendingOutcomes(chatId, userMessage);
// Mark pending shares as shared (they were in the prompt, bot wove them in)
if (this.shareQueue && user?.id) {
const pending = this.shareQueue.getPending(user.id, 3);
for (const item of pending) {
this.shareQueue.markShared(item.id, user.id);
}
}
return reply;
}
async _sendUpdate(chatId, text, opts) {
const callbacks = this._chatCallbacks.get(chatId);
if (callbacks?.onUpdate) {
try {
return await callbacks.onUpdate(text, opts);
} catch (err) {
const logger = getLogger();
logger.error(`[Orchestrator] _sendUpdate failed for chat ${chatId}: ${err.message}`);
}
} else {
const logger = getLogger();
logger.warn(`[Orchestrator] _sendUpdate: no callbacks for chat ${chatId}`);
}
return null;
}
async _handleCredentialResponse(chatId, userMessage, user, pending, onUpdate) {
const logger = getLogger();
const value = userMessage.trim();
if (value.toLowerCase() === 'skip' || value.toLowerCase() === 'cancel') {
logger.info(`User skipped credential: ${pending.credential.envKey}`);
return 'Credential skipped. You can provide it later.';
}
saveCredential(this.config, pending.credential.envKey, value);
logger.info(`Saved credential: ${pending.credential.envKey}`);
return `Saved ${pending.credential.label}. You can now try the task again.`;
}
/** Set up listeners for job lifecycle events. */
_setupJobListeners() {
const logger = getLogger();
this.jobManager.on('job:completed', async (job) => {
const chatId = job.chatId;
const convKey = this._chatKey(chatId);
const workerDef = WORKER_TYPES[job.workerType] || {};
const label = workerDef.label || job.workerType;
logger.info(`[Orchestrator] Job completed event: ${job.id} [${job.workerType}] in chat ${chatId} (${job.duration}s) — result length: ${(job.result || '').length} chars, structured: ${!!job.structuredResult}`);
// Track task outcome via feedback engine
if (this.feedbackEngine) {
try {
const taskSummary = job.structuredResult?.summary || (job.result || '').slice(0, 200);
this.feedbackEngine.recordJobCompletion(job.id, job.workerType, taskSummary, job.userId || null, this._activeCharacterId || null);
this._pendingOutcomes.set(job.id, { timestamp: Date.now(), chatId, userId: job.userId || null, characterId: this._activeCharacterId || null });
} catch (err) {
logger.warn(`[FeedbackEngine] Job completion tracking failed: ${err.message}`);
}
}
// Record causal event for the completed job
if (this.causalMemory) {
try {
const sr = job.structuredResult;
const outcomeType = sr?.status === 'success' ? 'success' : sr?.status === 'failed' ? 'failure' : 'partial';
this.causalMemory.recordEvent({
jobId: job.id,
trigger: `User requested: ${(job.task || '').slice(0, 200)}`,
goal: (job.task || '').slice(0, 500),
approach: `${job.workerType} worker`,
toolsUsed: [job.workerType],
outcome: sr?.summary || (job.result || '').slice(0, 500),
outcomeType,
userId: job.userId || null,
characterId: this._activeCharacterId || null,
durationMs: job.duration ? job.duration * 1000 : null,
}).catch(err => logger.warn(`[CausalMemory] Event recording failed: ${err.message}`));
} catch (err) {
logger.warn(`[CausalMemory] Event recording failed: ${err.message}`);
}
}
// 1. Store the job result in conversation history so the Orchestrator has full context
const resultEntry = this._buildResultHistoryEntry(job);
this.conversationManager.addMessage(convKey, 'assistant', resultEntry);
// 2. Trigger a proactive Orchestrator generation — inject the job result as context
// and let the Orchestrator speak naturally (present results, suggest next steps, etc.)
try {
const sr = job.structuredResult;
let resultContext;
if (sr?.structured) {
const parts = [`Summary: ${sr.summary}`, `Status: ${sr.status}`];
if (sr.artifacts?.length > 0) {
parts.push(`Artifacts: ${sr.artifacts.map(a => `${a.title || a.type}: ${a.url || a.path || ''}`).join(', ')}`);
}
if (sr.followUp) parts.push(`Follow-up: ${sr.followUp}`);
if (sr.details) {
const d = typeof sr.details === 'string' ? sr.details : JSON.stringify(sr.details, null, 2);
parts.push(`Details:\n${d.slice(0, 4000)}`);
}
resultContext = parts.join('\n');
} else {
resultContext = (job.result || 'Done.').slice(0, 4000);
}
const triggerMessage = `[System: The ${label} worker just finished job \`${job.id}\` (took ${job.duration}s). Results:\n\n${resultContext}\n\nProactively notify the user about the completed task. Present the results naturally, celebrate if appropriate, and suggest next steps. Do NOT mention "worker" or internal job details — speak as if you did the work yourself.]`;
// Add trigger as a transient user message (not stored in persistent history)
const messages = [...this.conversationManager.getSummarizedHistory(convKey)];
messages.push({ role: 'user', content: triggerMessage });
logger.info(`[Orchestrator] Triggering proactive follow-up for job ${job.id} in chat ${chatId}`);
const { max_tool_depth } = this.config.orchestrator;
const reply = await this._runLoop(chatId, messages, null, 0, max_tool_depth);
if (reply) {
logger.info(`[Orchestrator] Proactive reply for job ${job.id}: "${reply.slice(0, 200)}"`);
// _runLoop already stores the reply in conversation history
await this._sendUpdate(chatId, reply);
}
} catch (err) {
logger.error(`[Orchestrator] Proactive follow-up failed for job ${job.id}: ${err.message}`);
// Fallback: send a simple formatted summary so the user isn't left hanging
const fallback = this._buildSummaryFallback(job, label);
this.conversationManager.addMessage(convKey, 'assistant', fallback);
await this._sendUpdate(chatId, fallback).catch(() => {});
}
});
// Handle jobs whose dependencies are now met
this.jobManager.on('job:ready', async (job) => {
const chatId = job.chatId;
logger.info(`[Orchestrator] Job ready event: ${job.id} [${job.workerType}] — dependencies met, spawning worker`);
try {
await this._spawnWorker(job);
} catch (err) {
logger.error(`[Orchestrator] Failed to spawn ready job ${job.id}: ${err.message}`);
if (!job.isTerminal) {
this.jobManager.failJob(job.id, err.message);
}
}
});
this.jobManager.on('job:failed', async (job) => {
const chatId = job.chatId;
const convKey = this._chatKey(chatId);
const workerDef = WORKER_TYPES[job.workerType] || {};
const label = workerDef.label || job.workerType;
logger.error(`[Orchestrator] Job failed event: ${job.id} [${job.workerType}] in chat ${chatId} — ${job.error}`);
// Store failure context in history
const failMsg = `[${label} failed — job ${job.id}]: ${job.error}`;
this.conversationManager.addMessage(convKey, 'assistant', failMsg);
// Trigger proactive Orchestrator follow-up for the failure
try {
const triggerMessage = `[System: The ${label} worker failed on job \`${job.id}\`. Error: ${job.error}\n\nProactively notify the user about the failure. Explain what went wrong in simple terms, apologize if appropriate, and suggest how to fix or retry. Do NOT mention "worker" or internal job details — speak as if you encountered the issue yourself.]`;
const messages = [...this.conversationManager.getSummarizedHistory(convKey)];
messages.push({ role: 'user', content: triggerMessage });
logger.info(`[Orchestrator] Triggering proactive follow-up for failed job ${job.id} in chat ${chatId}`);
const { max_tool_depth } = this.config.orchestrator;
const reply = await this._runLoop(chatId, messages, null, 0, max_tool_depth);
if (reply) {
logger.info(`[Orchestrator] Proactive failure reply for job ${job.id}: "${reply.slice(0, 200)}"`);
await this._sendUpdate(chatId, reply);
}
} catch (err) {
logger.error(`[Orchestrator] Proactive failure follow-up failed for job ${job.id}: ${err.message}`);
// Fallback: send the simple failure message
const fallback = `❌ **${label} failed** (\`${job.id}\`): ${job.error}`;
await this._sendUpdate(chatId, fallback).catch(() => {});
}
});
this.jobManager.on('job:cancelled', (job) => {
const chatId = job.chatId;
const workerDef = WORKER_TYPES[job.workerType] || {};
const label = workerDef.label || job.workerType;
logger.info(`[Orchestrator] Job cancelled event: ${job.id} [${job.workerType}] in chat ${chatId}`);
const msg = `🚫 **${label} cancelled** (\`${job.id}\`)`;
this._sendUpdate(chatId, msg).catch(() => {});
});
}
/**
* Build a compact history entry for a completed job result.
* Stored as role: 'assistant' (not fake 'user') with up to 6000 chars of detail.
*/
_buildResultHistoryEntry(job) {
const workerDef = WORKER_TYPES[job.workerType] || {};
const label = workerDef.label || job.workerType;
const sr = job.structuredResult;
const parts = [`[${label} result — job ${job.id}, ${job.duration}s]`];
if (sr?.structured) {
parts.push(`Summary: ${sr.summary}`);
parts.push(`Status: ${sr.status}`);
if (sr.artifacts?.length > 0) {
const artifactLines = sr.artifacts.map(a => `- ${a.title || a.type}: ${a.url || a.path || ''}`);
parts.push(`Artifacts:\n${artifactLines.join('\n')}`);
}
if (sr.followUp) parts.push(`Follow-up: ${sr.followUp}`);
if (sr.details) {
const d = typeof sr.details === 'string' ? sr.details : JSON.stringify(sr.details, null, 2);
const details = d.length > 6000
? d.slice(0, 6000) + '\n... [details truncated]'
: d;
parts.push(`Details:\n${details}`);
}
} else {
// Raw text result
const resultText = job.result || 'Done.';
if (resultText.length > 6000) {
parts.push(resultText.slice(0, 6000) + '\n... [result truncated]');
} else {
parts.push(resultText);
}
}
return parts.join('\n\n');
}
/**
* Build a fallback summary when LLM summarization fails.
* Shows structured summary + artifacts directly instead of "ask me for details".
*/
_buildSummaryFallback(job, label) {
const sr = job.structuredResult;
if (sr?.structured) {
const parts = [`✅ **${label}** finished (\`${job.id}\`, ${job.duration}s)`];
parts.push(`\n${sr.summary}`);
if (sr.artifacts?.length > 0) {
const artifactLines = sr.artifacts.map(a => {
const link = a.url ? `[${a.title || a.type}](${a.url})` : (a.title || a.path || a.type);
return `- ${link}`;
});
parts.push(`\n${artifactLines.join('\n')}`);
}
if (sr.details) {
const d = typeof sr.details === 'string' ? sr.details : JSON.stringify(sr.details, null, 2);
const details = d.length > 1500 ? d.slice(0, 1500) + '\n... [truncated]' : d;
parts.push(`\n${details}`);
}
if (sr.followUp) parts.push(`\n💡 ${sr.followUp}`);
return parts.join('');
}
// No structured result — show first 300 chars of raw result
const snippet = (job.result || '').slice(0, 300);
return `✅ **${label}** finished (\`${job.id}\`, ${job.duration}s)${snippet ? `\n\n${snippet}${job.result?.length > 300 ? '...' : ''}` : ''}`;
}
/**
* Build structured context for a worker.
* Assembles: orchestrator-provided context, recent user messages, user persona, dependency results.
*/
async _buildWorkerContext(job) {
const logger = getLogger();
const sections = [];
// 1. Orchestrator-provided context
if (job.context) {
sections.push(`## Context\n${job.context}`);
}
// 2. Last 5 user messages from conversation history
try {
const history = this.conversationManager.getSummarizedHistory(this._chatKey(job.chatId));
const userMessages = history
.filter(m => m.role === 'user' && typeof m.content === 'string')
.slice(-5)
.map(m => m.content.slice(0, 500));
if (userMessages.length > 0) {
sections.push(`## Recent Conversation\n${userMessages.map(m => `> ${m}`).join('\n\n')}`);
}
} catch (err) {
logger.debug(`[Worker ${job.id}] Failed to load conversation history for context: ${err.message}`);
}
// 3. User persona
if (this.personaManager && job.userId) {
try {
const persona = this.personaManager.load(job.userId);
if (persona && persona.trim() && !persona.includes('No profile')) {
sections.push(`## User Profile\n${persona}`);
}
} catch (err) {
logger.debug(`[Worker ${job.id}] Failed to load persona for context: ${err.message}`);
}
}
// 4. Dependency job results
if (job.dependsOn.length > 0) {
const depResults = [];
for (const depId of job.dependsOn) {
const depJob = this.jobManager.getJob(depId);
if (!depJob || depJob.status !== 'completed') continue;
const workerDef = WORKER_TYPES[depJob.workerType] || {};
const label = workerDef.label || depJob.workerType;
const sr = depJob.structuredResult;
if (sr?.structured) {
const parts = [`### ${label} (${depId}) — ${sr.status}`];
parts.push(sr.summary);
if (sr.artifacts?.length > 0) {
parts.push(`Artifacts: ${sr.artifacts.map(a => `${a.title || a.type}: ${a.url || a.path || ''}`).join(', ')}`);
}
if (sr.details) {
const d = typeof sr.details === 'string' ? sr.details : JSON.stringify(sr.details, null, 2);
parts.push(d.slice(0, 4000));
}
depResults.push(parts.join('\n'));
} else if (depJob.result) {
depResults.push(`### ${label} (${depId})\n${depJob.result.slice(0, 4000)}`);
}
}
if (depResults.length > 0) {
sections.push(`## Prior Worker Results\n${depResults.join('\n\n')}`);
}
}
// 5. Causal context — past experience with similar tasks
if (this.causalMemory) {
try {
const causalCtx = await this.causalMemory.buildCausalContext(job.task, 3);
if (causalCtx) {
sections.push(causalCtx);
}
} catch (err) {
logger.debug(`[Worker ${job.id}] Failed to load causal context: ${err.message}`);
}
}
if (sections.length === 0) return null;
return sections.join('\n\n');
}
/**
* Spawn a worker for a job — called from dispatch_task handler.
* Creates smart progress reporting via editable Telegram message.
*/
async _spawnWorker(job) {
const logger = getLogger();
// Direct dispatch for coding tasks — bypass worker LLM, go straight to Claude Code CLI
if (job.workerType === 'coding') {
return this._spawnDirectCoding(job);
}
const chatId = job.chatId;
const callbacks = this._chatCallbacks.get(chatId) || {};
const onUpdate = callbacks.onUpdate;
const sendPhoto = callbacks.sendPhoto;
logger.info(`[Orchestrator] Spawning worker for job ${job.id} [${job.workerType}] in chat ${chatId} — task: "${job.task.slice(0, 120)}"`);
const workerDef = WORKER_TYPES[job.workerType] || {};
const abortController = new AbortController();
// Smart progress: editable Telegram message (same pattern as coder.js)
let statusMsgId = null;
let activityLines = [];
let flushTimer = null;
const MAX_VISIBLE = 10;
const buildStatusText = (finalState = null) => {
const visible = activityLines.slice(-MAX_VISIBLE);
const countInfo = activityLines.length > MAX_VISIBLE
? `\n_... ${activityLines.length} operations total_\n`
: '';
const header = `${workerDef.emoji || '⚙️'} *${workerDef.label || job.workerType}* (\`${job.id}\`)`;
if (finalState === 'done') return `${header} — Done\n${countInfo}\n${visible.join('\n')}`;
if (finalState === 'error') return `${header} — Failed\n${countInfo}\n${visible.join('\n')}`;
if (finalState === 'cancelled') return `${header} — Cancelled\n${countInfo}\n${visible.join('\n')}`;
return `${header} — Working...\n${countInfo}\n${visible.join('\n')}`;
};
const flushStatus = async () => {
flushTimer = null;