-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.txt
More file actions
2625 lines (2604 loc) · 233 KB
/
Copy pathdiff.txt
File metadata and controls
2625 lines (2604 loc) · 233 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
diff --git a/README.md b/README.md
index eb1581f..cc00dfd 100644
--- a/README.md
+++ b/README.md
@@ -20,23 +20,23 @@
<a href="https://github.com/AlGhozaliRamadhan">
<img src="https://img.shields.io/badge/Author-AGR-111111?style=flat"/>
</a>
- <img src="https://img.shields.io/badge/version-2.0.0-brightgreen?style=flat"/>
+ <img src="https://img.shields.io/badge/version-2.1.0-brightgreen?style=flat"/>
</p>
---
## What is BOZ?
-**BOZ (Behavioral Outlook Zone) v2** is an open-source, full-stack AI market analysis dashboard. It fuses real-time price data, technical indicators, multi-timeframe confluence, macro context, news, and crowd sentiment into structured, actionable intelligence complete with entry, target, stop, and risk/reward.
+**BOZ (Behavioral Outlook Zone) v2.1** is an open-source, full-stack AI market analysis dashboard. It fuses real-time price data, technical indicators, multi-timeframe confluence, macro context, news, and crowd sentiment into structured, actionable intelligence complete with entry, target, stop, and risk/reward.
-Four core modules are available directly from the sleek web interface:
+Analysis is now fully consolidated into a sleek, unified text-based Omni-Agent Chat interface. The UI relies entirely on natural conversational prompts and slash commands:
-| Mode | Horizon | Focus |
-|---|---|---|
-| **Market Intraday** | 2ΓÇô6 hours | MTF confluence, momentum, volatility (searchable ticker/asset) |
-| **Market Long-term** | 3ΓÇô12 months | SMA structure, 52-week context, trend integrity (searchable ticker/asset) |
-| **News Intel Analyzer** | Cross-asset | Multi-source news aggregation, cross-asset opportunity detection |
-| **Interactive Chat Agent** | Adaptive | Autonomous conversational agent with persistent memory, concurrent tool execution, and sub-agent delegation. |
+| Feature | Description |
+|---|---|
+| **Unified Omni-Agent** | The core borderless interface for BOZ. All analysis runs through a single immersive chat terminal without clunky cards. |
+| **Intraday Commands** | Use `/intraday [ticker]` for 2-6 hour momentum, volatility, and MTF confluence analysis returned in crisp markdown. |
+| **Long-term Commands** | Use `/longterm [ticker]` for 3-12 month SMA structure and 52-week context. |
+| **News Intel** | Use `/newsintel` for cross-asset multi-source news aggregation and crowd sentiment scoring. |
Three AI providers are supported, configurable via the Settings page or `.env`:
diff --git a/package.json b/package.json
index 054d10c..3d1d94e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "boz",
- "version": "2.0.0",
+ "version": "2.1.0",
"description": "Open-source AI market analyzer that combines real-time data, technical indicators, macro context, news, and sentiment into structured insights.",
"main": "dist/main.js",
"bin": {
diff --git a/src/app/api/analyze/intraday/verdict/route.ts b/src/app/api/analyze/intraday/verdict/route.ts
new file mode 100644
index 0000000..8678f0c
--- /dev/null
+++ b/src/app/api/analyze/intraday/verdict/route.ts
@@ -0,0 +1,75 @@
+import { NextRequest } from 'next/server';
+import { jsonResponse, errorResponse, parseBody } from '@/app/lib/api-helpers';
+import { AIService } from '@/services/ai/ai.service';
+import { buildTradeLevels } from '@/shared/trade-levels';
+
+export async function POST(request: NextRequest) {
+ try {
+ const { ticker, marketData, macro, sentiment, chartPatterns } = await parseBody<{
+ ticker: string,
+ marketData: any,
+ macro: any,
+ sentiment: any,
+ chartPatterns: any
+ }>(request);
+
+ if (!ticker) return errorResponse('Ticker is required', 400);
+ if (!marketData || !marketData.lastCandleFull) return errorResponse('Market data missing', 400);
+
+ const aiService = new AIService();
+ const prompt = buildIntradayPrompt(ticker, marketData.lastCandleFull, macro, sentiment, chartPatterns);
+ const verdict = await aiService.analyze(prompt);
+
+ let tradeLevels = null;
+ if (verdict.status === 'ok') {
+ const action = verdict.prediction === 'UP' ? 'BUY' : verdict.prediction === 'DOWN' ? 'SELL' : 'WATCH';
+ tradeLevels = buildTradeLevels(marketData.lastCandleFull.close, action as 'BUY' | 'SELL' | 'WATCH', verdict.confidence, '');
+ }
+
+ return jsonResponse({
+ verdict,
+ tradeLevels,
+ });
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : 'Unknown error';
+ return errorResponse(msg);
+ }
+}
+
+function buildIntradayPrompt(
+ ticker: string,
+ last: any,
+ macro: any,
+ sentiment: any,
+ chartPatterns: any,
+): string {
+ const fmt = (v: number | null | undefined, decimals = 2) =>
+ v != null ? v.toFixed(decimals) : 'N/A';
+
+ return `Analyze ${ticker} for intraday trading (2-6 hour horizon).
+
+Current Price: $${fmt(last.close)}
+RSI(14): ${fmt(last.RSI, 1)}
+MACD: ${fmt(last.MACD, 4)} / Signal: ${fmt(last.MACD_Signal, 4)}
+SMA20: ${fmt(last.SMA_20)} | SMA50: ${fmt(last.SMA_50)}
+ATR: ${fmt(last.ATR)} (${fmt(last.ATR_Percent)}%)
+BB Width: ${fmt(last.BB_Width)}
+Volume Ratio: ${fmt(last.Volume_Ratio)}
+OBV Trend: ${last.OBV_Trend ? 'Bullish' : 'Bearish'}
+
+Macro Context:
+- Market Regime: ${macro.market_regime}
+- Risk Sentiment: ${macro.risk_sentiment}
+- SPY Correlation: ${macro.sp500_correlation}
+- VIX: ${macro.vix_level ?? 'N/A'}
+
+Sentiment:
+- Fear & Greed: ${sentiment.fear_greed?.value ?? 'N/A'} (${sentiment.fear_greed?.label ?? 'N/A'})
+- StockTwits Bull Ratio: ${sentiment.stocktwits_data?.bull_ratio != null ? sentiment.stocktwits_data.bull_ratio.toFixed(0) + '%' : 'N/A'}
+
+Chart Patterns: ${chartPatterns.patterns?.join(', ') || 'None'}
+Candle Pattern: ${chartPatterns.candle_patterns?.summary_text || 'None'}
+Fibonacci Position: ${chartPatterns.fibonacci_position || 'N/A'}
+Nearest Support: $${fmt(chartPatterns.nearest_support)}
+Nearest Resistance: $${fmt(chartPatterns.nearest_resistance)}`;
+}
diff --git a/src/app/api/analyze/longterm/verdict/route.ts b/src/app/api/analyze/longterm/verdict/route.ts
new file mode 100644
index 0000000..bc74cd4
--- /dev/null
+++ b/src/app/api/analyze/longterm/verdict/route.ts
@@ -0,0 +1,90 @@
+import { NextRequest } from 'next/server';
+import { jsonResponse, errorResponse, parseBody } from '@/app/lib/api-helpers';
+import { AIService } from '@/services/ai/ai.service';
+import { buildTradeLevels } from '@/shared/trade-levels';
+
+export async function POST(request: NextRequest) {
+ try {
+ const { ticker, marketData, macro, sentiment, chartPatterns } = await parseBody<{
+ ticker: string,
+ marketData: any,
+ macro: any,
+ sentiment: any,
+ chartPatterns: any
+ }>(request);
+
+ if (!ticker) return errorResponse('Ticker is required', 400);
+ if (!marketData || !marketData.lastCandleFull) return errorResponse('Market data missing', 400);
+
+ const context52w = {
+ high52w: marketData.fiftyTwoWeekHigh,
+ low52w: marketData.fiftyTwoWeekLow,
+ from52wHigh: marketData.from52wHigh,
+ from52wLow: marketData.from52wLow
+ };
+
+ const aiService = new AIService();
+ const prompt = buildLongtermPrompt(ticker, marketData.lastCandleFull, macro, sentiment, chartPatterns, context52w);
+ const verdict = await aiService.analyze(prompt);
+
+ let tradeLevels = null;
+ if (verdict.status === 'ok') {
+ const action = verdict.prediction === 'UP' ? 'BUY' : verdict.prediction === 'DOWN' ? 'SELL' : 'WATCH';
+ tradeLevels = buildTradeLevels(marketData.lastCandleFull.close, action as 'BUY' | 'SELL' | 'WATCH', verdict.confidence, '');
+ }
+
+ return jsonResponse({
+ verdict,
+ tradeLevels,
+ });
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : 'Unknown error';
+ return errorResponse(msg);
+ }
+}
+
+function buildLongtermPrompt(
+ ticker: string,
+ last: any,
+ macro: any,
+ sentiment: any,
+ chartPatterns: any,
+ context52w: { high52w: number; low52w: number; from52wHigh: number; from52wLow: number },
+): string {
+ const fmt = (v: number | null | undefined, decimals = 2) =>
+ v != null ? v.toFixed(decimals) : 'N/A';
+
+ return `Analyze ${ticker} for long-term positioning (3-12 month investment horizon).
+
+Current Price: $${fmt(last.close)}
+RSI(14): ${fmt(last.RSI, 1)}
+MACD: ${fmt(last.MACD, 4)} / Signal: ${fmt(last.MACD_Signal, 4)}
+SMA20: ${fmt(last.SMA_20)} | SMA50: ${fmt(last.SMA_50)} | SMA200: ${fmt(last.SMA_200)}
+ATR: ${fmt(last.ATR)} (${fmt(last.ATR_Percent)}%)
+BB Width: ${fmt(last.BB_Width)}
+Volume Ratio: ${fmt(last.Volume_Ratio)}
+OBV Trend: ${last.OBV_Trend ? 'Bullish' : 'Bearish'}
+
+52-Week Context:
+- 52w High: $${fmt(context52w.high52w)} (${fmt(context52w.from52wHigh, 1)}% away)
+- 52w Low: $${fmt(context52w.low52w)} (+${fmt(context52w.from52wLow, 1)}% above)
+
+Macro Context:
+- Market Regime: ${macro.market_regime}
+- Risk Sentiment: ${macro.risk_sentiment}
+- SPY Correlation: ${macro.sp500_correlation}
+- VIX: ${macro.vix_level ?? 'N/A'}
+- 10Y Treasury Yield: ${macro.tnx_yield != null ? macro.tnx_yield.toFixed(2) + '%' : 'N/A'}
+
+Sentiment:
+- Fear & Greed: ${sentiment.fear_greed?.value ?? 'N/A'} (${sentiment.fear_greed?.label ?? 'N/A'})
+- StockTwits Bull Ratio: ${sentiment.stocktwits_data?.bull_ratio != null ? sentiment.stocktwits_data.bull_ratio.toFixed(0) + '%' : 'N/A'}
+
+Chart Patterns (Daily): ${chartPatterns.patterns?.join(', ') || 'None'}
+Candle Pattern: ${chartPatterns.candle_patterns?.summary_text || 'None'}
+Fibonacci Position: ${chartPatterns.fibonacci_position || 'N/A'}
+Support: $${fmt(chartPatterns.nearest_support)}
+Resistance: $${fmt(chartPatterns.nearest_resistance)}
+
+Focus on: secular trends, institutional accumulation/distribution, macro cycle positioning, and multi-month risk/reward setups. Provide target_price for 3-6 month horizon.`;
+}
diff --git a/src/app/api/chat/chat.engine.ts b/src/app/api/chat/chat.engine.ts
new file mode 100644
index 0000000..0293c31
--- /dev/null
+++ b/src/app/api/chat/chat.engine.ts
@@ -0,0 +1,912 @@
+// ΓöÇΓöÇΓöÇ chat.engine.ts ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+// Server-side chat engine for BOZ web app.
+// Brings CLI-level intelligence to the browser: tool calling, evidence ledger,
+// sub-agent delegation, two-pass reasoning, model fallback, and SSE streaming.
+
+import { LLMAdapter } from '@/services/ai/llm.adapter';
+import { config } from '@/config/config';
+import { yahooFinance } from '@/services/market/yahoo.service';
+import { newsFetchService } from '@/services/news/news.fetch.service';
+import { SentimentService } from '@/services/market/sentiment.service';
+import { webSearchService } from '@/services/search/web.search.service';
+import { idxScannerService } from '@/services/market/idx.scanner.service';
+import { memoryService } from '@/services/memory.service';
+import { resolveSymbolIDX } from '@/shared/market-constants';
+import { GITHUB_MODELS } from '@/config/github.config';
+import { NVIDIA_MODELS } from '@/config/nvidia.config';
+import type { LLMMessage, RawToolCall } from '@/types/llm.types';
+
+// ΓöÇΓöÇΓöÇ Types ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+export interface ChatEvent {
+ type: 'tool_start' | 'tool_result' | 'reasoning_start' | 'token' | 'done' | 'error';
+ data: any;
+}
+
+interface LedgerEntry {
+ step: number;
+ tool: string;
+ fact: string;
+ quality: 'confirmed' | 'partial' | 'empty';
+}
+
+interface ParsedToolCall {
+ name: string;
+ arguments: Record<string, any>;
+}
+
+// ΓöÇΓöÇΓöÇ Constants ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+const MAX_TOOL_ROUNDS = 15;
+const MAX_HISTORY_MESSAGES = 14;
+
+// ΓöÇΓöÇΓöÇ WebChatEngine ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+export class WebChatEngine {
+ private llm = new LLMAdapter();
+ private sentimentService = new SentimentService();
+
+ // ΓöÇΓöÇΓöÇ Main entry point ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ // Yields streaming ChatEvent objects for the SSE route to emit.
+
+ async *run(params: {
+ message: string;
+ history?: Array<{ role: 'user' | 'assistant'; content: string }>;
+ }): AsyncGenerator<ChatEvent> {
+ const { message, history } = params;
+
+ // ΓöÇΓöÇ Build message list ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ const messages: LLMMessage[] = [
+ { role: 'system', content: this.buildSystemPrompt() },
+ ];
+
+ if (history?.length) {
+ for (const msg of history.slice(-MAX_HISTORY_MESSAGES)) {
+ messages.push({ role: msg.role, content: msg.content });
+ }
+ }
+
+ messages.push({ role: 'user', content: message });
+
+ // ΓöÇΓöÇ First AI call ΓÇö with tools ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ let aiMessage: LLMMessage;
+ try {
+ aiMessage = await this.callWithFallback(messages, this.getToolDefinitions(), 0.3);
+ } catch (err) {
+ yield { type: 'error', data: { message: err instanceof Error ? err.message : 'AI call failed' } };
+ return;
+ }
+
+ // ΓöÇΓöÇ Evidence ledger ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ const ledger: LedgerEntry[] = [];
+ let step = 0;
+ let toolRounds = 0;
+
+ // ΓöÇΓöÇ Tool-calling loop ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ while (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {
+ toolRounds++;
+ if (toolRounds > MAX_TOOL_ROUNDS) break;
+
+ messages.push(aiMessage);
+
+ // Emit tool_start events for all tools in this round
+ const parsed: Array<{ raw: RawToolCall; call: ParsedToolCall }> = [];
+ for (const raw of aiMessage.tool_calls) {
+ const call = this.parseToolCall(raw);
+ parsed.push({ raw, call });
+ yield {
+ type: 'tool_start',
+ data: { tool: call.name, args: call.arguments, step: step + parsed.length },
+ };
+ }
+
+ // Execute all tool calls concurrently
+ const results = await Promise.all(
+ parsed.map(async ({ raw, call }) => {
+ let obs: string;
+ let success = true;
+ try {
+ obs = await this.executeTool(call.name, call.arguments, messages, ledger);
+ if (obs.includes('Tool execution failed') || obs.includes('returned no results') || obs.includes('No news found')) {
+ success = false;
+ }
+ } catch (e) {
+ success = false;
+ obs = 'Tool execution failed: ' + (e instanceof Error ? e.message : String(e));
+ }
+ return { raw, call, obs, success };
+ }),
+ );
+
+ // Process results: extract facts, emit events, push tool messages
+ for (const { raw, call, obs, success } of results) {
+ step++;
+ const fact = this.extractFact(call.name, call.arguments, obs);
+ if (fact) {
+ fact.step = step;
+ ledger.push(fact);
+ }
+
+ yield {
+ type: 'tool_result',
+ data: {
+ tool: call.name,
+ fact: fact?.fact || obs.slice(0, 120),
+ quality: fact?.quality || 'empty',
+ step,
+ success,
+ },
+ };
+
+ messages.push({
+ role: 'tool',
+ content: obs,
+ name: call.name,
+ tool_call_id: raw.id,
+ });
+ }
+
+ // Next AI call ΓÇö decide if more tools or final answer
+ try {
+ aiMessage = await this.callWithFallback(messages, this.getToolDefinitions(), 0.3);
+ } catch (err) {
+ yield { type: 'error', data: { message: err instanceof Error ? err.message : 'AI follow-up call failed' } };
+ return;
+ }
+ }
+
+ // ΓöÇΓöÇ Final response ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ if (ledger.length > 0) {
+ // Two-pass: run reasoning agent with evidence ledger
+ const confirmedCount = ledger.filter(e => e.quality === 'confirmed').length;
+ yield { type: 'reasoning_start', data: { confirmedFacts: confirmedCount, totalSteps: step } };
+
+ try {
+ const reasoningMessages = this.buildReasoningMessages(messages, ledger);
+ for await (const chunk of this.llm.callTextStream({
+ messages: reasoningMessages,
+ temperature: 0.5,
+ maxTokens: 4096,
+ })) {
+ // Strip thinking tags from streamed output
+ const cleaned = this.stripThinkingFromChunk(chunk);
+ if (cleaned) {
+ yield { type: 'token', data: cleaned };
+ }
+ }
+ } catch (err) {
+ yield { type: 'error', data: { message: 'Reasoning agent failed: ' + (err instanceof Error ? err.message : String(err)) } };
+ return;
+ }
+ } else if (aiMessage.content) {
+ // Simple response ΓÇö no tools were called. Stream directly.
+ // The content is already complete from callWithTools, so emit as one chunk.
+ const cleaned = this.stripThinkingFull(aiMessage.content);
+ yield { type: 'token', data: cleaned };
+ } else {
+ yield { type: 'token', data: 'I couldn\'t generate a response. Please try again.' };
+ }
+
+ yield { type: 'done', data: { totalSteps: step } };
+ }
+
+ // ΓöÇΓöÇΓöÇ System prompt (ported from CLI, adapted for web) ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private buildSystemPrompt(): string {
+ const memory = memoryService.getMemory();
+ const prefs = memory.preferences.length
+ ? `\nUSER PREFERENCES:\n${memory.preferences.map(p => ' - ' + p).join('\n')}`
+ : '';
+ const facts = memory.facts.length
+ ? `\nUSER FACTS:\n${memory.facts.map(f => ' - ' + f).join('\n')}`
+ : '';
+
+ return [
+ 'You are BOZ (Behavioral Outlook Zone), an elite AI market assistant and quantitative analyst.',
+ 'You think like a hedge fund analyst ΓÇö skeptical, data-driven, always asking "is this enough?"',
+ prefs,
+ facts,
+ '',
+ 'CONVERSATIONAL AI RULES:',
+ ' - You have FULL AUTONOMY to decide whether tools are needed.',
+ ' - If the user is greeting you, asking a generic question, or asking a follow-up that',
+ ' can be answered from conversation history, DO NOT call tools. Just answer naturally.',
+ ' - If you genuinely need live data, news, or a fresh scan, then call the tools.',
+ ' - ANTI-LOOP RULE: If you just ran tools 1 turn ago and the user asks a follow-up about',
+ ' the SAME topic, it is almost always WRONG to call tools again. Answer from context.',
+ ' - COST AWARENESS: Every tool call takes 10-30 seconds. Be frugal.',
+ '',
+ 'TOOLS:',
+ ' fetch_price(symbol_or_name) ΓÇö live price for any asset',
+ ' fetch_news(query, category?) ΓÇö market news; query is a free-text search string',
+ ' fetch_sentiment() ΓÇö Fear & Greed + StockTwits crowd data',
+ ' web_search(query) ΓÇö live web search; use when other tools give nothing',
+ ' scan_indonesia_momentum(sector?, ΓÇö IDX scanner; screens the full IDX universe',
+ ' signal_type?, setup?, scan_mode?) for momentum candidates. Deep mode is exhaustive.',
+ ' update_memory(fact, is_preference)ΓÇö save long-term user facts or preferences',
+ '',
+ 'THINKING RULES:',
+ ' 1. After each tool result, reflect: What did I learn? Is this enough? What next?',
+ ' 2. If a tool returns empty/irrelevant results, pivot to web_search with a better query.',
+ ' 3. Build a picture iteratively. Each tool call should add NEW information.',
+ ' 4. You may call 6-10 tools per query if needed. More data = better analysis.',
+ ' 5. Maintain a global market focus unless the user asks about a specific region.',
+ ' 6. FOLLOW-UP QUESTIONS: If the user asks about the analysis you JUST provided,',
+ ' DO NOT call tools again. Answer directly from the conversation context.',
+ '',
+ 'INDONESIAN STOCK HUNTING RULES:',
+ ' - When asked for IDX stocks to buy/invest/watch: ALWAYS call scan_indonesia_momentum.',
+ ' Autonomously pick the best setup filter ("rebound", "breakout", "oversold", "momentum").',
+ ' - After the scan, call fetch_price on the top 2-3 BUY candidates to confirm live prices.',
+ ' - Then call fetch_news WITH THE SPECIFIC COMPANY NAME AND SYMBOL to check for catalysts.',
+ ' - If news is irrelevant, call web_search for deep fundamentals.',
+ ' - Do NOT just name BBCA/BBRI/TLKM from memory ΓÇö those are lazy defaults.',
+ ' - Cite the score, volume ratio, and 52w range position.',
+ '',
+ 'SUB-AGENT DELEGATION:',
+ ' - You have a team: QuantBrain, NewsHound, RiskManager, DataGoblin.',
+ ' - For complex analysis, summon 2-3 sub-agents CONCURRENTLY to analyze different angles.',
+ ' - Do not try to analyze complex stocks alone. Delegate the heavy thinking.',
+ '',
+ 'EVIDENCE RULES ΓÇö IMMUTABLE:',
+ ' - Facts confirmed from tool results are locked. You cannot contradict them.',
+ ' - If price data says +1.1%, your analysis must reflect that.',
+ ' - If news returned nothing, say exactly that. Do not invent headlines.',
+ '',
+ 'CONTRARIAN ANALYSIS:',
+ ' - StockTwits >70% bullish = caution (retail euphoria precedes reversals)',
+ ' - StockTwits <30% bullish = buy signal (panic = opportunity)',
+ ' - Fear & Greed >75 = reduce long confidence',
+ ' - Fear & Greed <25 = strong buy signal',
+ '',
+ 'OUTPUT FORMAT:',
+ ' - Reply in a natural, conversational style. Direct, confident, professional.',
+ ' - Use rich markdown formatting: **bold**, headers, bullet lists, tables, code blocks.',
+ ' - For stock recommendations: rank your picks, give entry zone, stop-loss, and reasoning.',
+ ' - Cite data and reasoning, never vague hand-waving.',
+ ' - Acknowledge uncertainty honestly.',
+ ' - Never pad with filler. Be sharp and direct.',
+ ' - Rarely use emojis.',
+ ].join('\n');
+ }
+
+ // ΓöÇΓöÇΓöÇ Tool definitions ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private getToolDefinitions(): object[] {
+ return [
+ {
+ type: 'function',
+ function: {
+ name: 'update_memory',
+ description: 'Save a persistent fact or preference about the user across sessions.',
+ parameters: {
+ type: 'object',
+ properties: {
+ fact: { type: 'string', description: 'The fact or preference to save.' },
+ is_preference: { type: 'boolean', description: 'True if rule/preference, false if general fact.' },
+ },
+ required: ['fact', 'is_preference'],
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'summon_agent',
+ description: 'Summon a specialized sub-agent for complex analysis. Use for deep-thinking tasks.',
+ parameters: {
+ type: 'object',
+ properties: {
+ agent_name: {
+ type: 'string',
+ enum: ['NewsHound', 'DataGoblin', 'QuantBrain', 'RiskManager'],
+ description: 'Which agent to summon.',
+ },
+ task: { type: 'string', description: 'The specific task and data to analyze.' },
+ },
+ required: ['agent_name', 'task'],
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'fetch_price',
+ description: 'Fetch live market price for any asset ΓÇö stocks, indices, crypto, forex, commodities.',
+ parameters: {
+ type: 'object',
+ properties: {
+ symbol_or_name: {
+ type: 'string',
+ description: 'Ticker or name. E.g.: BTC, AAPL, IHSG, BBCA, GOLD, EURUSD',
+ },
+ },
+ required: ['symbol_or_name'],
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'fetch_news',
+ description: [
+ 'Fetch recent market news using a free-text search query.',
+ 'Checks Indonesian RSS feeds (CNBC Indonesia, Bisnis.com, Kontan, Detik Finance)',
+ 'as well as global sources.',
+ 'If this returns empty, follow up with web_search.',
+ ].join(' '),
+ parameters: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Free-text search. Use local language terms for Indonesian assets.',
+ },
+ category: {
+ type: 'string',
+ enum: ['crypto', 'stocks', 'macro', 'broad', 'indonesia'],
+ description: 'Optional category hint.',
+ },
+ },
+ required: ['query'],
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'fetch_sentiment',
+ description: 'Fetch global crowd sentiment ΓÇö CNN Fear & Greed index + StockTwits crowd ratio.',
+ parameters: { type: 'object', properties: {} },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'web_search',
+ description: [
+ 'Search the live web for current information.',
+ 'Use when other tools return empty or insufficient results.',
+ 'Useful for: market news, sector analysis, macro events, company news.',
+ ].join(' '),
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Search query.' },
+ },
+ required: ['query'],
+ },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'scan_indonesia_momentum',
+ description: [
+ 'Scan the IDX universe for hidden momentum setups.',
+ 'Fast mode quote-screens all IDX stocks then chart-scans the strongest.',
+ 'Deep mode chart-scans every valid IDX quote for exhaustive coverage.',
+ 'Returns ranked BUY candidates and WATCH list sorted by score.',
+ ].join(' '),
+ parameters: {
+ type: 'object',
+ properties: {
+ sector: {
+ type: 'string',
+ enum: ['all', 'banking', 'consumer', 'mining', 'energy', 'tech', 'property', 'telecom', 'healthcare', 'industrial'],
+ description: 'Filter by sector.',
+ },
+ signal_type: {
+ type: 'string',
+ enum: ['buy', 'sell', 'any'],
+ description: '"buy" for positive momentum, "sell" for deteriorating, "any" for all.',
+ },
+ setup: {
+ type: 'string',
+ enum: ['momentum', 'rebound', 'all_time_low', 'downtrend', 'breakout', 'oversold'],
+ description: 'Filter by setup type. Pick the best one based on market context.',
+ },
+ scan_mode: {
+ type: 'string',
+ enum: ['fast', 'deep'],
+ description: '"fast" (default) quote-screens first. "deep" is exhaustive.',
+ },
+ },
+ required: [],
+ },
+ },
+ },
+ ];
+ }
+
+ // ΓöÇΓöÇΓöÇ Tool executor ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private async executeTool(
+ name: string,
+ args: Record<string, any>,
+ messages: LLMMessage[],
+ ledger: LedgerEntry[],
+ ): Promise<string> {
+ switch (name) {
+
+ case 'summon_agent': {
+ const agentName = (args.agent_name as string) ?? 'UnknownAgent';
+ const task = (args.task as string) ?? '';
+ return await this.simulateSubAgent(agentName, task, messages, ledger);
+ }
+
+ case 'fetch_price': {
+ const raw = args.symbol_or_name as string;
+ const symbol = resolveSymbolIDX(raw) || raw.toUpperCase();
+ const quote = await this.retrySimple(() => yahooFinance.quote(symbol), 3, 2000);
+ const price = (quote as any).regularMarketPrice;
+ const change = (quote as any).regularMarketChangePercent;
+ if (price === undefined || price === null) {
+ return `No price data for ${symbol}. Yahoo Finance may not support this symbol or market is closed.`;
+ }
+ const chgNum = typeof change === 'number' ? change : 0;
+ const name_ = (quote as any).shortName || (quote as any).longName || symbol;
+ const dayHigh = (quote as any).regularMarketDayHigh;
+ const dayLow = (quote as any).regularMarketDayLow;
+ const prevClose = (quote as any).regularMarketPreviousClose;
+ return [
+ `Symbol: ${symbol} | Name: ${name_} | Price: ${price} (Change: ${chgNum.toFixed(2)}%)`,
+ dayHigh != null ? `Day Range: ${dayLow} ΓÇô ${dayHigh}` : '',
+ prevClose != null ? `Prev Close: ${prevClose}` : '',
+ ].filter(Boolean).join(' | ');
+ }
+
+ case 'update_memory': {
+ const fact = (args.fact as string) ?? '';
+ const isPref = (args.is_preference as boolean) ?? false;
+ if (isPref) { memoryService.addPreference(fact); }
+ else { memoryService.addFact(fact); }
+ return `Successfully saved memory: ${fact}`;
+ }
+
+ case 'fetch_news': {
+ const query = (args.query as string) ?? '';
+ const category = (args.category as string) ?? 'broad';
+ const items: string[] = [];
+
+ const fetchers: Promise<any[]>[] = [];
+ if (category === 'indonesia' || category === 'stocks' || category === 'broad') {
+ fetchers.push(newsFetchService.fetchIndonesiaNews().catch(() => []));
+ }
+ if (category === 'crypto') {
+ fetchers.push(newsFetchService.fetchCryptoNews().catch(() => []));
+ }
+ if (category === 'stocks' || category === 'broad') {
+ fetchers.push(newsFetchService.fetchStockNews().catch(() => []));
+ fetchers.push(newsFetchService.fetchBroadMarketNews().catch(() => []));
+ }
+ if (category === 'macro') {
+ fetchers.push(newsFetchService.fetchMacroNews().catch(() => []));
+ fetchers.push(newsFetchService.fetchBroadMarketNews().catch(() => []));
+ }
+ if (fetchers.length === 0) {
+ fetchers.push(newsFetchService.fetchBroadMarketNews().catch(() => []));
+ fetchers.push(newsFetchService.fetchIndonesiaNews().catch(() => []));
+ }
+
+ const settled = await Promise.all(fetchers);
+ const fetched: any[] = settled.flat();
+
+ // Relevance scoring against query
+ const queryWords = query.toLowerCase().split(/\s+/).filter(w => w.length > 1);
+ const scored = fetched
+ .map(n => {
+ const title = (n.title ?? '').toLowerCase();
+ const blob = `${title} ${n.details ?? ''} ${(n.assets ?? []).join(' ')} ${n.source ?? ''}`.toLowerCase();
+ let score = 0;
+ for (const w of queryWords) {
+ if (title.includes(w)) score += 2;
+ else if (blob.includes(w)) score += 1;
+ }
+ return { n, score };
+ })
+ .filter(({ score }) => queryWords.length === 0 || score > 0)
+ .sort((a, b) => {
+ if (b.score !== a.score) return b.score - a.score;
+ const imp: Record<string, number> = { high: 2, medium: 1, low: 0 };
+ return (imp[b.n.impact] ?? 0) - (imp[a.n.impact] ?? 0);
+ })
+ .slice(0, 10);
+
+ for (const { n } of scored) {
+ const src = n.source ? ` (${n.source})` : '';
+ items.push(`- ${n.title}${src}`);
+ }
+
+ if (items.length === 0) {
+ return `No news found for "${query}". [HINT: call web_search with query "${query}" to get live results]`;
+ }
+ return items.join('\n');
+ }
+
+ case 'fetch_sentiment': {
+ const data = await this.sentimentService.fetchCrowdSentiment();
+ return JSON.stringify({
+ fear_greed: data.fear_greed,
+ reddit_buzz: { stocktwits: data.stocktwits_data ?? null, social: data.social_buzz ?? [] },
+ overall_signals: data.summary.overall_signals,
+ }, null, 2);
+ }
+
+ case 'web_search': {
+ const query = (args.query as string) ?? '';
+ return await webSearchService.search(query);
+ }
+
+ case 'scan_indonesia_momentum': {
+ const sector = (args.sector as string) ?? 'all';
+ const signalType = (args.signal_type as string) ?? 'buy';
+ const setup = (args.setup as string) ?? 'momentum';
+ const scanMode = (args.scan_mode as string) ?? 'fast';
+ const result = await idxScannerService.scan(
+ sector as any, signalType as any, setup as any, scanMode as any,
+ );
+ return result.formatted;
+ }
+
+ default:
+ return 'Unknown tool: ' + name;
+ }
+ }
+
+ // ΓöÇΓöÇΓöÇ Sub-agent simulation ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private async simulateSubAgent(
+ agentName: string,
+ task: string,
+ conversationMessages: LLMMessage[],
+ ledger: LedgerEntry[],
+ ): Promise<string> {
+ const lower = agentName.toLowerCase();
+ let persona: string;
+
+ if (lower === 'quantbrain') {
+ persona = 'You are QuantBrain, a ruthless quantitative analyst. You focus PURELY on mathematics, risk-reward ratios, technicals, and volume flow. You ignore sentiment and hype. Give a highly empirical, data-dense analysis.';
+ } else if (lower === 'newshound') {
+ persona = 'You are NewsHound, a macro-economic intelligence agent. You read between the lines of global events, institutional money flow, and social sentiment. You connect seemingly unrelated geopolitical or economic events to the asset in question.';
+ } else if (lower === 'riskmanager') {
+ persona = 'You are RiskManager, a highly skeptical devil\'s advocate and former hedge fund auditor. Your ONLY job is to find reasons NOT to buy. Hunt for hidden red flags, overvaluation, regulatory risks, and structural flaws.';
+ } else if (lower === 'datagoblin') {
+ persona = 'You are DataGoblin, obsessed with obscure metrics, historical statistical anomalies, and relative valuations. You cross-reference sectors and peer groups to find absolute truths in the numbers.';
+ } else {
+ persona = `You are ${agentName}, a specialized analysis sub-agent.`;
+ }
+
+ const confirmedFacts = ledger
+ .filter(e => e.quality === 'confirmed')
+ .map(e => ` ΓÇó ${e.fact}`)
+ .join('\n');
+
+ const recentConversation = conversationMessages
+ .filter(m => (m.role === 'user' || m.role === 'assistant') && !m.tool_calls && typeof m.content === 'string' && m.content?.trim())
+ .slice(-6)
+ .map(m => `${m.role.toUpperCase()}: ${String(m.content).slice(0, 900)}`)
+ .join('\n\n');
+
+ const subAgentMessages: LLMMessage[] = [
+ {
+ role: 'system',
+ content: [
+ persona,
+ 'Your job is to deeply analyze the task below.',
+ 'You are not allowed to call tools, summon another agent, delegate, or output XML/tool syntax.',
+ 'Return only your final specialist report in concise Markdown.',
+ 'Use the provided task, conversation summary, and confirmed data ledger only.',
+ 'If data is insufficient, say what is missing and still give the best risk-aware view.',
+ ].join('\n'),
+ },
+ {
+ role: 'user',
+ content: [
+ `Task: "${task}"`,
+ '',
+ 'RECENT CONVERSATION SUMMARY:',
+ recentConversation || ' (none)',
+ '',
+ 'CONFIRMED DATA GATHERED BY BOZ:',
+ confirmedFacts || ' (none)',
+ '',
+ 'Output format:',
+ `### ${agentName} Report`,
+ '- **Thesis:** ...',
+ '- **Evidence:** ...',
+ '- **Risks / caveats:** ...',
+ '- **Actionable conclusion:** ...',
+ ].join('\n'),
+ },
+ ];
+
+ try {
+ const report = await this.llm.callText({
+ messages: subAgentMessages,
+ temperature: 0.5,
+ maxTokens: 2000,
+ });
+ const cleaned = this.stripThinkingFull(report);
+ return `[REPORT FROM ${agentName}]\n${cleaned || 'Sub-agent returned no usable report.'}`;
+ } catch (e) {
+ return `Failed to summon ${agentName}: ` + (e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ // ΓöÇΓöÇΓöÇ Evidence ledger builder ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private extractFact(toolName: string, args: Record<string, any>, obs: string): LedgerEntry | null {
+ const wasEmpty = obs.includes('No news found') || obs.includes('returned no results') ||
+ obs.includes('Tool execution failed') || obs.includes('no data');
+
+ if (toolName === 'fetch_price') {
+ const pm = obs.match(/Price:\s*([\d,.]+)/);
+ const cm = obs.match(/Change:\s*([-\d.]+)%/);
+ const nm = obs.match(/Name:\s*([^|]+)/);
+ if (pm) {
+ return {
+ step: 0, tool: toolName,
+ fact: `${nm?.[1]?.trim() ?? args.symbol_or_name}: price ${pm[1]}${cm ? ', change ' + cm[1] + '%' : ''}`,
+ quality: 'confirmed',
+ };
+ }
+ }
+
+ if (toolName === 'fetch_news') {
+ const lines = obs.split('\n').filter(l => l.trim().startsWith('-'));
+ if (lines.length > 0) {
+ return {
+ step: 0, tool: toolName,
+ fact: `News for "${args.query}": ${lines.length} headlines found. Top: ${lines[0].replace(/^-\s*/, '').slice(0, 80)}`,
+ quality: 'confirmed',
+ };
+ }
+ return { step: 0, tool: toolName, fact: `News for "${args.query}": no relevant headlines`, quality: 'empty' };
+ }
+
+ if (toolName === 'fetch_sentiment') {
+ try {
+ const json = JSON.parse(obs);
+ const fg = json.fear_greed?.value;
+ const fgl = json.fear_greed?.label;
+ const st = json.reddit_buzz?.stocktwits;
+ const sig = (json.overall_signals ?? []).join(', ');
+ const stStr = st ? `, StockTwits ${st.bull_ratio?.toFixed(0)}% bullish` : '';
+ return {
+ step: 0, tool: toolName,
+ fact: `Sentiment: Fear & Greed ${fg} (${fgl})${stStr}, signals: [${sig}]`,
+ quality: 'confirmed',
+ };
+ } catch { /* fall through */ }
+ }
+
+ if (toolName === 'web_search') {
+ const lines = obs.split('\n').filter(l => l.trim().startsWith('-'));
+ if (lines.length > 0) {
+ return {
+ step: 0, tool: toolName,
+ fact: `Web search "${args.query}": ${lines.length} results. Top: ${lines[0].replace(/^-\s*/, '').slice(0, 80)}`,
+ quality: 'confirmed',
+ };
+ }
+ return { step: 0, tool: toolName, fact: `Web search "${args.query}": no results`, quality: 'empty' };
+ }
+
+ if (toolName === 'scan_indonesia_momentum') {
+ const buyMatch = obs.match(/BUY:\s*(\d+)/);
+ const watchMatch = obs.match(/WATCH:\s*(\d+)/);
+ const scannedMatch = obs.match(/scanned:\s*(\d+)/);
+ const breadthMatch = obs.match(/breadth signal:\s*([^\n]+)/);
+ const topBuyMatch = obs.match(/\[SCORE\s+(\d+)\]\s+([A-Z]+)\s+ΓÇó\s+([^[\n]+)/);
+ const topBuyName = topBuyMatch ? `${topBuyMatch[2]} (${topBuyMatch[3].trim()})` : null;
+ const scanned = scannedMatch?.[1] ?? '?';
+ const buyCount = buyMatch?.[1] ?? '0';
+ const watchCount = watchMatch?.[1] ?? '0';
+ const breadth = breadthMatch?.[1]?.trim() ?? '';
+ const topStr = topBuyName ? `. Top pick: ${topBuyName}` : '';
+ return {
+ step: 0, tool: toolName,
+ fact: `IDX scan (${args.sector ?? 'all'}): ${scanned} scanned, ${buyCount} BUY / ${watchCount} WATCH. ${breadth}${topStr}`,
+ quality: Number(buyCount) > 0 ? 'confirmed' : 'partial',
+ };
+ }
+
+ if (toolName === 'summon_agent') {
+ const reportLines = obs.split('\n').filter(l => l.trim()).slice(0, 5);
+ return {
+ step: 0, tool: toolName,
+ fact: `${args.agent_name} report received (${obs.length} chars)`,
+ quality: obs.includes('Failed') || obs.includes('no usable') ? 'empty' : 'confirmed',
+ };
+ }
+
+ return wasEmpty
+ ? { step: 0, tool: toolName, fact: `${toolName} returned no data`, quality: 'empty' }
+ : null;
+ }
+
+ // ΓöÇΓöÇΓöÇ Reasoning agent messages ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+
+ private buildReasoningMessages(messages: LLMMessage[], ledger: LedgerEntry[]): LLMMessage[] {
+ const confirmedFacts = ledger.filter(e => e.quality === 'confirmed').map(e => ` ΓÇó ${e.fact}`).join('\n');
+ const emptyFacts = ledger.filter(e => e.quality === 'empty').map(e => ` ΓÇó ${e.fact}`).join('\n');
+
+ const reasoningSystemPrompt = [
+ 'You are the ANALYSIS ENGINE inside BOZ, a quantitative market analyst AI.',
+ 'You receive a locked evidence ledger from the data-gathering phase, along with conversation history.',
+ 'Your job: produce the final market analysis and action plan.',
+ '',
+ 'HARD CONSTRAINTS:',
+ ' 1. You MUST use every confirmed fact. Do not ignore any.',
+ ' 2. You CANNOT contradict confirmed facts.',
+ ' 3. For empty results: acknowledge honestly. Do not invent data.',
+ ' 4. Apply contrarian analysis:',
+ ' StockTwits >70% bullish = crowd euphoria = caution',
+ ' Fear & Greed >75 = reduce long confidence',
+ ' Fear & Greed <25 = strong buy signal',
+ ' 5. Incorporate fundamental reality and warn about speculative micro-caps.',
+ '',
+ 'OUTPUT FORMAT:',
+ ' - Natural, conversational style with rich markdown formatting.',
+ ' - Use **bold**, headers, bullet lists, and tables when helpful.',
+ ' - Focus on actionable insights and clear takeaways.',
+ ' - Maintain a global perspective unless explicitly asked otherwise.',
+ ' - End with a clear Action Plan: Buy / Hold / Wait, with entry, stop-loss, target if applicable.',
+ ].join('\n');
+
+ const reasoningUserPrompt = [
+ 'CONFIRMED DATA (immutable ΓÇö you must use and cannot contradict):',
+ confirmedFacts || ' (none)',
+ '',
+ emptyFacts ? ('GAPS IN DATA (be honest about these):\n' + emptyFacts) : '',
+ '',
+ 'Produce a complete, accurate market analysis and action plan based strictly on the above data and the conversation history.',
+ ].filter(Boolean).join('\n');
+
+ // Include conversation context but prune tool messages for token efficiency
+ const conversationContext = messages.filter(