-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOllamaClient.cpp
More file actions
2021 lines (1900 loc) · 102 KB
/
Copy pathOllamaClient.cpp
File metadata and controls
2021 lines (1900 loc) · 102 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
// OllamaClient.cpp
#include "OllamaClient.h"
#include "DecodiumConfig.h"
#include "Synapse.h" // recupero associativo della memoria ("sinapsi") + codec ham
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <QUrlQuery>
#include <QRegularExpression>
#include <QDir>
#include <QFileInfo>
#include <QFile>
#include <QProcess>
#include <QLocale>
#include <QCoreApplication>
#include <QtMath>
#include <QDateTime>
#include <QStandardPaths>
#include <QSettings>
#include <utility>
// Limite massimo di round di tool calling per una singola domanda (anti-loop).
static constexpr int kMaxToolRounds = 5;
// ───────────────────────── Strumenti locali ─────────────────────────
// Elenca il contenuto di una cartella. Ritorna testo pronto per il modello.
static QString runScanFolder(const QJsonObject& args) {
const QString path = args.value("path").toString();
if (path.isEmpty())
return QStringLiteral("Errore: nessun percorso indicato.");
const QFileInfo fi(path);
if (!fi.exists())
return QStringLiteral("Errore: il percorso \"%1\" non esiste.").arg(path);
if (!fi.isDir())
return QStringLiteral("Errore: \"%1\" non è una cartella.").arg(path);
QDir dir(path);
const QFileInfoList entries =
dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot,
QDir::DirsFirst | QDir::Name | QDir::IgnoreCase);
const int cap = 200; // tetto per non saturare il contesto del modello
QString out = QStringLiteral("Contenuto di \"%1\" (%2 elementi):\n")
.arg(QDir::toNativeSeparators(path)).arg(entries.size());
int n = 0;
for (const QFileInfo& e : entries) {
if (n++ >= cap) {
out += QStringLiteral("... e altri %1 elementi non elencati.\n")
.arg(entries.size() - cap);
break;
}
if (e.isDir())
out += QStringLiteral("[DIR] %1\n").arg(e.fileName());
else
out += QStringLiteral(" %1 (%2)\n")
.arg(e.fileName(), QLocale().formattedDataSize(e.size()));
}
return out;
}
// Legge il contenuto testuale di un file. Ritorna testo pronto per il modello.
static QString runReadFile(const QJsonObject& args) {
const QString path = args.value("path").toString();
if (path.isEmpty())
return QStringLiteral("Errore: nessun percorso indicato.");
const QFileInfo fi(path);
if (!fi.exists())
return QStringLiteral("Errore: il file \"%1\" non esiste.").arg(path);
if (fi.isDir())
return QStringLiteral("Errore: \"%1\" è una cartella, non un file.").arg(path);
QFile f(path);
if (!f.open(QIODevice::ReadOnly))
return QStringLiteral("Errore: impossibile aprire \"%1\".").arg(path);
const qint64 cap = 64 * 1024; // 64 KB: tetto per non saturare il contesto
const QByteArray raw = f.read(cap);
const bool truncated = fi.size() > cap;
f.close();
// File binario: presenza di byte NUL -> non leggibile come testo.
if (raw.contains('\0'))
return QStringLiteral("Il file \"%1\" sembra binario (%2): non leggibile come testo.")
.arg(QDir::toNativeSeparators(path),
QLocale().formattedDataSize(fi.size()));
QString out = QStringLiteral("Contenuto di \"%1\" (%2%3):\n")
.arg(QDir::toNativeSeparators(path),
QLocale().formattedDataSize(fi.size()),
truncated ? QStringLiteral(", troncato ai primi 64 KB") : QString());
out += QString::fromUtf8(raw);
return out;
}
// Consulta la knowledge base radioamatori (decodius_ham_kb.md accanto all'exe),
// restituendo i paragrafi pertinenti all'argomento richiesto.
static QString runHamKb(const QJsonObject& args) {
const QString topic = args.value("topic").toString().trimmed();
QFile f(QCoreApplication::applicationDirPath() + QStringLiteral("/decodius_ham_kb.md"));
if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
return QStringLiteral("Knowledge base radioamatori non disponibile.");
const QString kb = QString::fromUtf8(f.readAll());
f.close();
if (topic.isEmpty()) {
QString idx;
const auto lines = kb.split(QLatin1Char('\n'));
for (const QString& l : lines)
if (l.startsWith(QLatin1Char('#'))) idx += l.trimmed() + QLatin1Char('\n');
return QStringLiteral("Sezioni della knowledge base radioamatori:\n") + idx;
}
const QStringList toks = topic.toLower().split(QRegularExpression(QStringLiteral("\\s+")),
Qt::SkipEmptyParts);
const QStringList paras = kb.split(QRegularExpression(QStringLiteral("\\n\\s*\\n")));
QString out;
for (const QString& p : paras) {
const QString lp = p.toLower();
bool hit = false;
for (const QString& t : toks)
if (t.size() >= 3 && lp.contains(t)) { hit = true; break; }
if (hit) {
out += p.trimmed() + QStringLiteral("\n\n");
if (out.size() > 5000) break;
}
}
if (out.trimmed().isEmpty())
return QStringLiteral("Nessuna sezione specifica per \"%1\"; prova un termine più generale o usa web_search.").arg(topic);
return QStringLiteral("Dalla knowledge base radioamatori (argomento: %1):\n%2").arg(topic, out.trimmed());
}
// ── Helper: legge un numero da JSON che sia number o string ("14,2" o "14.2") ──
static double argNum(const QJsonObject& a, const QString& k, double def = 0.0) {
const QJsonValue v = a.value(k);
if (v.isDouble()) return v.toDouble();
if (v.isString()) {
bool ok = false;
double d = v.toString().trimmed().replace(',', '.').toDouble(&ok);
return ok ? d : def;
}
return def;
}
static bool hasArg(const QJsonObject& a, const QString& k) {
const QJsonValue v = a.value(k);
return !(v.isUndefined() || v.isNull() || (v.isString() && v.toString().trimmed().isEmpty()));
}
// Calcoli radioamatoriali esatti (gemma4 spesso sbaglia l'aritmetica).
static QString runHamCalc(const QJsonObject& args) {
const QString op = args.value("operazione").toString().toLower().trimmed();
if (op == "dipolo") {
double f = argNum(args, "freq_mhz");
if (f <= 0) return QStringLiteral("Errore: serve freq_mhz (frequenza in MHz).");
double tot = 142.5 / f;
return QStringLiteral("Dipolo a mezz'onda per %1 MHz: lunghezza totale ~%2 m, ogni braccio ~%3 m "
"(formula 142,5/f, fattore di velocità 0,95 per filo).")
.arg(f, 0, 'f', 3).arg(tot, 0, 'f', 2).arg(tot / 2.0, 0, 'f', 2);
}
if (op == "verticale" || op == "verticale_quarto" || op == "quarto_onda") {
double f = argNum(args, "freq_mhz");
if (f <= 0) return QStringLiteral("Errore: serve freq_mhz.");
return QStringLiteral("Verticale a quarto d'onda per %1 MHz: ~%2 m (formula 71,25/f).")
.arg(f, 0, 'f', 3).arg(71.25 / f, 0, 'f', 2);
}
if (op == "lunghezza_onda" || op == "lambda") {
double f = argNum(args, "freq_mhz");
if (f <= 0) return QStringLiteral("Errore: serve freq_mhz.");
double l = 300.0 / f;
return QStringLiteral("Lunghezza d'onda a %1 MHz: λ = %2 m (λ/2 = %3 m, λ/4 = %4 m).")
.arg(f, 0, 'f', 3).arg(l, 0, 'f', 2).arg(l / 2.0, 0, 'f', 2).arg(l / 4.0, 0, 'f', 2);
}
if (op == "ohm") {
bool hv = hasArg(args, "v"), hi = hasArg(args, "i"), hr = hasArg(args, "r");
double v = argNum(args, "v"), i = argNum(args, "i"), r = argNum(args, "r");
if ((int)hv + (int)hi + (int)hr < 2)
return QStringLiteral("Errore: per la legge di Ohm servono due tra v (volt), i (ampere), r (ohm).");
if (!hv) v = i * r;
else if (!hi) { if (r == 0) return QStringLiteral("Errore: r non può essere 0."); i = v / r; }
else if (!hr) { if (i == 0) return QStringLiteral("Errore: i non può essere 0."); r = v / i; }
return QStringLiteral("Legge di Ohm: V = %1 V, I = %2 A, R = %3 Ω, P = %4 W.")
.arg(v, 0, 'f', 3).arg(i, 0, 'f', 3).arg(r, 0, 'f', 2).arg(v * i, 0, 'f', 3);
}
if (op == "dbm_to_watt") {
double d = argNum(args, "valore");
double w = qPow(10.0, (d - 30.0) / 10.0);
return QStringLiteral("%1 dBm = %2 W (%3 mW).").arg(d, 0, 'f', 1).arg(w, 0, 'f', 4).arg(w * 1000.0, 0, 'f', 1);
}
if (op == "watt_to_dbm") {
double w = argNum(args, "valore");
if (w <= 0) return QStringLiteral("Errore: la potenza in watt deve essere > 0.");
return QStringLiteral("%1 W = %2 dBm.").arg(w, 0, 'f', 3).arg(10.0 * std::log10(w) + 30.0, 0, 'f', 1);
}
return QStringLiteral("Errore: operazione ham_calc sconosciuta. Usa: dipolo, verticale, "
"lunghezza_onda, ohm, dbm_to_watt, watt_to_dbm.");
}
// ── Maidenhead (locatore) <-> lat/lon + distanza/azimuth ──
static bool gridToLatLon(const QString& g0, double& lat, double& lon) {
const QString g = g0.trimmed().toUpper();
if (g.size() < 4) return false;
if (g[0] < 'A' || g[0] > 'R' || g[1] < 'A' || g[1] > 'R') return false;
if (!g[2].isDigit() || !g[3].isDigit()) return false;
lon = (g[0].toLatin1() - 'A') * 20.0 - 180.0 + (g[2].toLatin1() - '0') * 2.0;
lat = (g[1].toLatin1() - 'A') * 10.0 - 90.0 + (g[3].toLatin1() - '0') * 1.0;
if (g.size() >= 6 && g[4].isLetter() && g[5].isLetter()) {
lon += (g[4].toLatin1() - 'A') * (2.0 / 24.0) + (2.0 / 24.0) / 2.0;
lat += (g[5].toLatin1() - 'A') * (1.0 / 24.0) + (1.0 / 24.0) / 2.0;
} else {
lon += 1.0; lat += 0.5; // centro del quadrato
}
return true;
}
static QString latLonToGrid(double lat, double lon) {
double lo = lon + 180.0, la = lat + 90.0;
QString g;
g += QChar('A' + int(lo / 20.0));
g += QChar('A' + int(la / 10.0));
g += QChar('0' + int(std::fmod(lo, 20.0) / 2.0));
g += QChar('0' + int(std::fmod(la, 10.0) / 1.0));
g += QChar('a' + int(std::fmod(lo, 2.0) / (2.0 / 24.0)));
g += QChar('a' + int(std::fmod(la, 1.0) / (1.0 / 24.0)));
return g;
}
static QString runLocatore(const QJsonObject& args) {
const QString op = args.value("operazione").toString().toLower().trimmed();
if (op == "grid_to_latlon" || op == "to_latlon") {
double la, lo;
if (!gridToLatLon(args.value("grid").toString(), la, lo))
return QStringLiteral("Errore: locatore non valido (es. JN61na).");
return QStringLiteral("Locatore %1: centro a lat %2, lon %3.")
.arg(args.value("grid").toString().toUpper()).arg(la, 0, 'f', 4).arg(lo, 0, 'f', 4);
}
if (op == "latlon_to_grid" || op == "from_latlon") {
double la = argNum(args, "lat", 1000), lo = argNum(args, "lon", 1000);
if (la < -90 || la > 90 || lo < -180 || lo > 180)
return QStringLiteral("Errore: servono lat e lon validi.");
return QStringLiteral("Lat %1, lon %2: locatore %3.")
.arg(la, 0, 'f', 4).arg(lo, 0, 'f', 4).arg(latLonToGrid(la, lo));
}
if (op == "distanza" || op == "distance") {
double la1, lo1, la2, lo2;
if (!gridToLatLon(args.value("grid1").toString(), la1, lo1) ||
!gridToLatLon(args.value("grid2").toString(), la2, lo2))
return QStringLiteral("Errore: servono due locatori validi (grid1 e grid2).");
const double R = 6371.0;
double p1 = qDegreesToRadians(la1), p2 = qDegreesToRadians(la2);
double dp = qDegreesToRadians(la2 - la1), dl = qDegreesToRadians(lo2 - lo1);
double a = qSin(dp / 2) * qSin(dp / 2) + qCos(p1) * qCos(p2) * qSin(dl / 2) * qSin(dl / 2);
double km = R * 2 * qAtan2(qSqrt(a), qSqrt(1 - a));
double y = qSin(dl) * qCos(p2);
double x = qCos(p1) * qSin(p2) - qSin(p1) * qCos(p2) * qCos(dl);
double brg = std::fmod(qRadiansToDegrees(qAtan2(y, x)) + 360.0, 360.0);
return QStringLiteral("Da %1 a %2: distanza ~%3 km, azimuth ~%4° (per puntare l'antenna).")
.arg(args.value("grid1").toString().toUpper(), args.value("grid2").toString().toUpper())
.arg(km, 0, 'f', 0).arg(brg, 0, 'f', 0);
}
return QStringLiteral("Errore: operazione locatore sconosciuta. Usa: grid_to_latlon, "
"latlon_to_grid, distanza.");
}
// Ora/data UTC (gli orari ham sono in UTC; il modello non conosce l'ora reale).
static QString runOraUtc(const QJsonObject&) {
QLocale it(QLocale::Italian);
const QDateTime u = QDateTime::currentDateTimeUtc();
const QDateTime l = QDateTime::currentDateTime();
return QStringLiteral("Ora UTC: %1. Ora locale: %2.")
.arg(it.toString(u, "dddd d MMMM yyyy, HH:mm:ss 'UTC'"))
.arg(it.toString(l, "HH:mm:ss"));
}
// Registra un QSO in un log ADIF standard (Documenti/decodius_log.adi).
static QString adifField(const QString& name, const QString& val) {
if (val.trimmed().isEmpty()) return QString();
const QString v = val.trimmed();
return QStringLiteral("<%1:%2>%3 ").arg(name).arg(v.toUtf8().size()).arg(v);
}
static QString runLogQso(const QJsonObject& args) {
const QString call = args.value("call").toString().trimmed().toUpper();
if (call.isEmpty()) return QStringLiteral("Errore: serve il nominativo (call) del corrispondente.");
const QString banda = args.value("banda").toString().trimmed();
const QString modo = args.value("modo").toString().trimmed().toUpper();
const QString rstS = args.value("rst_inviato").toString().trimmed();
const QString rstR = args.value("rst_ricevuto").toString().trimmed();
const QString nota = args.value("nota").toString().trimmed();
const QDateTime u = QDateTime::currentDateTimeUtc();
const QString date = u.toString("yyyyMMdd"), time = u.toString("hhmm");
const QString path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
+ QStringLiteral("/decodius_log.adi");
QFile f(path);
const bool isNew = !f.exists();
if (!f.open(QIODevice::Append | QIODevice::Text))
return QStringLiteral("Errore: impossibile aprire il log %1.").arg(path);
QString rec;
if (isNew) rec += QStringLiteral("Decodius ADIF log\n<ADIF_VER:5>3.1.4<PROGRAMID:8>Decodius<EOH>\n");
rec += adifField("CALL", call) + adifField("QSO_DATE", date) + adifField("TIME_ON", time)
+ adifField("BAND", banda) + adifField("MODE", modo)
+ adifField("RST_SENT", rstS) + adifField("RST_RCVD", rstR)
+ adifField("COMMENT", nota) + QStringLiteral("<EOR>\n");
f.write(rec.toUtf8());
f.close();
QString rst = (rstS.isEmpty() && rstR.isEmpty()) ? QString()
: QStringLiteral(", RST %1/%2").arg(rstS.isEmpty() ? "-" : rstS, rstR.isEmpty() ? "-" : rstR);
return QStringLiteral("QSO registrato: %1, %2 UTC, banda %3, modo %4%5. Salvato in %6.")
.arg(call, u.toString("dd/MM/yyyy HH:mm"),
banda.isEmpty() ? "?" : banda, modo.isEmpty() ? "?" : modo, rst, path);
}
// ── Memoria persistente come VAULT OBSIDIAN: note Markdown in una cartella ──
// La memoria di Decodius È un vault Obsidian (cartella di .md): le note sono leggibili e
// modificabili in Obsidian, con [[wikilink]]. La cartella si configura in
// decodius_obsidian.txt (riga 1 = percorso del vault); default <Documenti>/Decodius.
static QString obsidianVaultPath() {
QString p;
QFile cf(QCoreApplication::applicationDirPath() + QStringLiteral("/decodius_obsidian.txt"));
if (cf.open(QIODevice::ReadOnly | QIODevice::Text)) {
p = QString::fromUtf8(cf.readAll()).split('\n').value(0).trimmed();
cf.close();
}
if (p.isEmpty())
p = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QStringLiteral("/Decodius");
QDir().mkpath(p);
return p;
}
// Nota principale della memoria (l'indice dei fatti). La crea (con frontmatter) se manca,
// migrando una volta sola la vecchia memoria piatta decodius_memoria.txt se presente.
static QString memoriaNotePath() {
const QString path = obsidianVaultPath() + QStringLiteral("/Decodius - Memoria.md");
if (!QFileInfo::exists(path)) {
QString body = QStringLiteral("---\ntags: [decodius, memoria]\n---\n\n# Decodius — Memoria\n\n"
"Fatti che Decodius ricorda tra le sessioni (modificabili qui in Obsidian).\n\n");
QFile old(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
+ QStringLiteral("/decodius_memoria.txt"));
if (old.open(QIODevice::ReadOnly | QIODevice::Text)) { // migrazione una tantum
const QString prev = QString::fromUtf8(old.readAll()).trimmed();
old.close();
if (!prev.isEmpty()) body += prev + QStringLiteral("\n");
}
QFile nf(path);
if (nf.open(QIODevice::WriteOnly | QIODevice::Text)) { nf.write(body.toUtf8()); nf.close(); }
}
return path;
}
// Lettura della memoria (solo le righe-fatto "- ...") per il system prompt di Assistant.
QString decodiusLeggiMemoria() {
QFile f(memoriaNotePath());
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) return QString();
const QString c = QString::fromUtf8(f.readAll());
f.close();
QStringList facts;
const QStringList lines = c.split('\n');
for (const QString& l : lines)
if (l.trimmed().startsWith(QStringLiteral("- "))) facts << l.trimmed();
return facts.join('\n');
}
// Nome file sicuro da un titolo nota (toglie i caratteri vietati su Windows).
static QString safeNoteName(QString t) {
t.replace(QRegularExpression(QStringLiteral("[\\\\/:*?\"<>|]")), QStringLiteral(" "));
return t.simplified();
}
static QString runMemoria(const QJsonObject& args) {
const QString azione = args.value("azione").toString().trimmed().toLower();
const QString vault = obsidianVaultPath();
// CERCA: grep su TUTTE le note .md del vault (anche quelle scritte dall'utente in Obsidian).
if (azione.startsWith(QStringLiteral("cerc"))) {
const QString q = args.value("contenuto").toString().trimmed();
if (q.isEmpty()) return QStringLiteral("Errore: indica cosa cercare in 'contenuto'.");
QDir d(vault);
QString out; int n = 0;
const QStringList files = d.entryList(QStringList{QStringLiteral("*.md")}, QDir::Files, QDir::Time);
for (const QString& fn : files) {
QFile f(d.filePath(fn));
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) continue;
const QStringList ls = QString::fromUtf8(f.readAll()).split('\n');
f.close();
for (const QString& line : ls) {
if (line.contains(q, Qt::CaseInsensitive) && line.trimmed().size() > 2
&& !line.trimmed().startsWith(QStringLiteral("#")) && !line.contains(QStringLiteral(": ["))) {
out += QStringLiteral("• [[%1]] %2\n").arg(fn.chopped(3), line.trimmed());
if (++n >= 12) break;
}
}
if (n >= 12) break;
}
return out.isEmpty() ? QStringLiteral("Niente trovato per \"%1\" nel vault Obsidian.").arg(q)
: QStringLiteral("Trovato nel vault Obsidian:\n%1").arg(out);
}
// LEGGI: la nota memoria principale.
if (azione == QLatin1String("leggi") || azione == QLatin1String("elenca")) {
const QString c = decodiusLeggiMemoria();
return c.isEmpty() ? QStringLiteral("Memoria vuota: non ricordo ancora nulla.")
: (QStringLiteral("Cose che ricordo:\n") + c);
}
// SALVA (default): scrive un fatto come riga Markdown nel vault.
const QString contenuto = args.value("contenuto").toString().trimmed();
if (contenuto.isEmpty()) return QStringLiteral("Errore: indica il 'contenuto' da ricordare.");
const QString titolo = args.value("titolo").toString().trimmed();
const QString date = QDateTime::currentDateTimeUtc().toString(QStringLiteral("yyyy-MM-dd"));
// Con 'titolo' -> nota per argomento <titolo>.md; senza -> nota memoria principale.
QString path, label;
if (!titolo.isEmpty()) { path = vault + QStringLiteral("/") + safeNoteName(titolo) + QStringLiteral(".md"); label = titolo; }
else { path = memoriaNotePath(); label = QStringLiteral("Memoria"); }
const bool isNew = !QFileInfo::exists(path);
QFile f(path);
if (!f.open(QIODevice::Append | QIODevice::Text))
return QStringLiteral("Errore: impossibile scrivere nel vault Obsidian.");
if (isNew && !titolo.isEmpty())
f.write(QStringLiteral("---\ntags: [decodius]\n---\n\n# %1\n\n").arg(titolo).toUtf8());
f.write(QStringLiteral("- [%1] %2\n").arg(date, contenuto).toUtf8());
f.close();
return QStringLiteral("Annotato in Obsidian (%1): %2").arg(label, contenuto);
}
// ── Lookup nominativi: prefisso -> Paese/DXCC (tabella offline) ──
// Match dal prefisso più lungo (3) al più corto (1). Copertura: tutta l'Europa,
// Nord/Sud America, principali entità di Asia/Africa/Oceania.
struct PfxEntry { const char* pfx; const char* country; };
static const PfxEntry kPrefixes[] = {
// Italia e dintorni
{"IS0","Italia (Sardegna)"}, {"IM0","Italia (Sardegna)"}, {"I","Italia"},
// USA / Canada
{"K","Stati Uniti"}, {"W","Stati Uniti"}, {"N","Stati Uniti"},
{"AA","Stati Uniti"}, {"AB","Stati Uniti"}, {"AC","Stati Uniti"}, {"AD","Stati Uniti"},
{"AE","Stati Uniti"}, {"AF","Stati Uniti"}, {"AG","Stati Uniti"}, {"AI","Stati Uniti"},
{"AJ","Stati Uniti"}, {"AK","Stati Uniti"}, {"AL","Stati Uniti"},
{"KH6","Stati Uniti (Hawaii)"}, {"KL","Stati Uniti (Alaska)"}, {"KP4","Porto Rico"},
{"VE","Canada"}, {"VA","Canada"}, {"VO","Canada"}, {"VY","Canada"}, {"VK","Australia"},
// Europa occidentale
{"G","Regno Unito"}, {"M","Regno Unito"}, {"2E","Regno Unito"},
{"GW","Galles"}, {"MW","Galles"}, {"GM","Scozia"}, {"MM","Scozia"},
{"GI","Irlanda del Nord"}, {"GD","Isola di Man"}, {"GU","Guernsey"}, {"GJ","Jersey"},
{"DA","Germania"}, {"DB","Germania"}, {"DC","Germania"}, {"DD","Germania"}, {"DF","Germania"},
{"DG","Germania"}, {"DH","Germania"}, {"DJ","Germania"}, {"DK","Germania"}, {"DL","Germania"},
{"DM","Germania"}, {"DO","Germania"}, {"DP","Germania"}, {"DR","Germania"},
{"F","Francia"}, {"TK","Corsica"},
{"EA","Spagna"}, {"EB","Spagna"}, {"EC","Spagna"}, {"ED","Spagna"}, {"EE","Spagna"},
{"EA6","Spagna (Baleari)"}, {"EA8","Spagna (Canarie)"}, {"EA9","Ceuta e Melilla"},
{"CT","Portogallo"}, {"CT3","Madeira"}, {"CU","Azzorre"},
{"ON","Belgio"}, {"OT","Belgio"}, {"PA","Paesi Bassi"}, {"PB","Paesi Bassi"}, {"PD","Paesi Bassi"},
{"PE","Paesi Bassi"}, {"PI","Paesi Bassi"}, {"LX","Lussemburgo"},
{"HB9","Svizzera"}, {"HB0","Liechtenstein"}, {"OE","Austria"},
{"EI","Irlanda"}, {"EJ","Irlanda"},
// Europa nordica
{"LA","Norvegia"}, {"LB","Norvegia"}, {"LG","Norvegia"}, {"SM","Svezia"}, {"SA","Svezia"},
{"SK","Svezia"}, {"OH","Finlandia"}, {"OF","Finlandia"}, {"OH0","Isole Åland"},
{"OZ","Danimarca"}, {"OU","Danimarca"}, {"OX","Groenlandia"}, {"OY","Isole Fær Øer"},
{"TF","Islanda"},
// Europa centro-orientale
{"SP","Polonia"}, {"SQ","Polonia"}, {"SN","Polonia"}, {"OK","Repubblica Ceca"}, {"OL","Repubblica Ceca"},
{"OM","Slovacchia"}, {"HA","Ungheria"}, {"HG","Ungheria"}, {"YO","Romania"}, {"YP","Romania"},
{"YR","Romania"}, {"LZ","Bulgaria"}, {"S5","Slovenia"}, {"9A","Croazia"}, {"E7","Bosnia ed Erzegovina"},
{"YU","Serbia"}, {"YT","Serbia"}, {"4O","Montenegro"}, {"Z3","Macedonia del Nord"}, {"ZA","Albania"},
{"SV","Grecia"}, {"SW","Grecia"}, {"SY","Grecia"}, {"SV9","Creta"}, {"SV5","Dodecaneso"},
{"5B","Cipro"}, {"YL","Lettonia"}, {"LY","Lituania"}, {"ES","Estonia"},
{"UR","Ucraina"}, {"US","Ucraina"}, {"UT","Ucraina"}, {"UU","Ucraina"}, {"UX","Ucraina"},
{"EU","Bielorussia"}, {"EW","Bielorussia"}, {"ER","Moldavia"},
// Russia e ex-URSS
{"R","Russia"}, {"UA","Russia"}, {"UB","Russia"}, {"UC","Russia"}, {"UD","Russia"},
{"RA","Russia"}, {"RK","Russia"}, {"RN","Russia"}, {"RU","Russia"}, {"RV","Russia"},
{"EK","Armenia"}, {"4J","Azerbaigian"}, {"4K","Azerbaigian"}, {"4L","Georgia"},
{"UN","Kazakistan"}, {"EX","Kirghizistan"}, {"EY","Tagikistan"}, {"EZ","Turkmenistan"}, {"UK","Uzbekistan"},
// Medio Oriente / Asia
{"TA","Turchia"}, {"TC","Turchia"}, {"4X","Israele"}, {"4Z","Israele"}, {"JY","Giordania"},
{"YK","Siria"}, {"OD","Libano"}, {"YI","Iraq"}, {"EP","Iran"}, {"A4","Oman"}, {"A6","Emirati Arabi Uniti"},
{"A7","Qatar"}, {"A9","Bahrein"}, {"HZ","Arabia Saudita"}, {"9K","Kuwait"}, {"YA","Afghanistan"},
{"AP","Pakistan"}, {"VU","India"}, {"4S","Sri Lanka"}, {"S2","Bangladesh"}, {"XZ","Myanmar"},
{"HS","Thailandia"}, {"E2","Thailandia"}, {"XV","Vietnam"}, {"XU","Cambogia"}, {"9M","Malaysia"},
{"9V","Singapore"}, {"YB","Indonesia"}, {"YC","Indonesia"}, {"DU","Filippine"}, {"DV","Filippine"},
{"BY","Cina"}, {"BG","Cina"}, {"BA","Cina"}, {"BD","Cina"}, {"BV","Taiwan"},
{"JA","Giappone"}, {"JE","Giappone"}, {"JF","Giappone"}, {"JG","Giappone"}, {"JH","Giappone"},
{"JI","Giappone"}, {"JJ","Giappone"}, {"JK","Giappone"}, {"JR","Giappone"}, {"7K","Giappone"},
{"HL","Corea del Sud"}, {"DS","Corea del Sud"}, {"P5","Corea del Nord"},
// Oceania
{"ZL","Nuova Zelanda"}, {"FK","Nuova Caledonia"}, {"FO","Polinesia Francese"}, {"KH2","Guam"},
// Africa
{"ZS","Sudafrica"}, {"SU","Egitto"}, {"CN","Marocco"}, {"7X","Algeria"}, {"3V","Tunisia"},
{"5A","Libia"}, {"5N","Nigeria"}, {"5Z","Kenya"}, {"ET","Etiopia"}, {"EL","Liberia"},
{"FR","Riunione"}, {"3B8","Mauritius"}, {"D4","Capo Verde"}, {"ZD7","Sant'Elena"},
// Americhe (centro/sud)
{"XE","Messico"}, {"XF","Messico"}, {"CO","Cuba"}, {"CM","Cuba"}, {"HI","Rep. Dominicana"},
{"HH","Haiti"}, {"TG","Guatemala"}, {"YS","El Salvador"}, {"HR","Honduras"}, {"YN","Nicaragua"},
{"TI","Costa Rica"}, {"HP","Panama"}, {"PY","Brasile"}, {"PP","Brasile"}, {"PT","Brasile"},
{"PU","Brasile"}, {"LU","Argentina"}, {"CE","Cile"}, {"CX","Uruguay"}, {"CP","Bolivia"},
{"OA","Perù"}, {"HC","Ecuador"}, {"HK","Colombia"}, {"YV","Venezuela"}, {"ZP","Paraguay"},
{"PJ","Antille Olandesi"}, {"FY","Guyana Francese"}, {"8R","Guyana"},
};
static QString resolveCallsignPrefix(const QString& call) {
const QString c = call.toUpper();
for (int len = qMin(3, c.size()); len >= 1; --len) {
const QString p = c.left(len);
for (const auto& e : kPrefixes)
if (p == QLatin1String(e.pfx))
return QString::fromUtf8(e.country);
}
return QString();
}
static bool isUsCall(const QString& call) {
const QString c = call.toUpper();
if (c.isEmpty()) return false;
const QChar f = c[0];
if (f == 'K' || f == 'N' || f == 'W') return true;
if (f == 'A' && c.size() >= 2 && c[1] >= 'A' && c[1] <= 'L') return true;
return false;
}
// Smista la chiamata al tool giusto.
static QString runTool(const QString& name, const QJsonObject& args) {
if (name == QLatin1String("scan_folder"))
return runScanFolder(args);
if (name == QLatin1String("read_file"))
return runReadFile(args);
if (name == QLatin1String("ham_kb"))
return runHamKb(args);
if (name == QLatin1String("ham_calc"))
return runHamCalc(args);
if (name == QLatin1String("locatore"))
return runLocatore(args);
if (name == QLatin1String("ora_utc"))
return runOraUtc(args);
if (name == QLatin1String("log_qso"))
return runLogQso(args);
if (name == QLatin1String("memoria"))
return runMemoria(args);
return QStringLiteral("Errore: strumento sconosciuto \"%1\".").arg(name);
}
// Vedi dichiarazione in OllamaClient.h.
QString decodiusConfigPath(const QString& fileName, bool forWrite) {
const QString userDir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
if (!userDir.isEmpty()) {
const QString userFile = userDir + '/' + fileName;
if (forWrite) { QDir().mkpath(userDir); return userFile; } // scrittura: sempre nella copia utente
if (QFileInfo::exists(userFile)) return userFile; // lettura: override utente se presente
}
return QCoreApplication::applicationDirPath() + '/' + fileName; // default dell'installer (sola lettura)
}
OllamaClient::OllamaClient(QObject* parent) : QObject(parent) {
// Timeout di inattività: scatta solo se non arriva alcun token entro
// m_timeoutMs; viene riarmato a ogni chunk ricevuto (vedi onReadyRead).
m_idleTimer.setSingleShot(true);
connect(&m_idleTimer, &QTimer::timeout, this, [this]() { abortCurrent(); });
// Modello configurabile da file (decodius_model.txt) senza ricompilare: utile
// per cambiare cervello (es. qwen3-coder:30b, qwen3:30b, gemma4 per la vision).
QFile mf(decodiusConfigPath(QStringLiteral("decodius_model.txt")));
if (mf.open(QIODevice::ReadOnly | QIODevice::Text)) {
// 1a riga = modello primario (può essere ":cloud"); 2a riga (opzionale) = modello
// LOCALE di riserva, usato in automatico se il cloud fallisce (crediti/rate/rete).
QStringList models;
QString cont = QString::fromUtf8(mf.readAll());
if (cont.startsWith(QChar(0xFEFF))) cont.remove(0, 1); // toglie il BOM UTF-8 (PowerShell Set-Content -Encoding UTF8 lo aggiunge: senza questo il nome modello diventa "qwen3..." -> 404)
const QStringList lines = cont.split('\n');
for (const QString& raw : lines) {
const QString l = raw.trimmed();
if (!l.isEmpty() && !l.startsWith('#')) models << l;
}
if (!models.isEmpty()) m_model = models.first();
if (models.size() >= 2) m_modelFallback = models.at(1);
mf.close();
}
m_primaryIsCloud = m_model.contains(QStringLiteral(":cloud"));
// Cervello alternativo via provider OpenAI-compatibile (es. NVIDIA NIM, OpenRouter,
// DeepSeek, Gemini). File decodius_provider.txt con righe key=value:
// base_url=https://integrate.api.nvidia.com/v1
// api_key=nvapi-...
// model=nvidia/llama-3.3-nemotron-super-49b-v1
// Se base_url e api_key sono presenti, Decodius usa quel provider invece di Ollama.
QFile pf(decodiusConfigPath(QStringLiteral("decodius_provider.txt")));
if (pf.open(QIODevice::ReadOnly | QIODevice::Text)) {
QString base, key, mdl;
QString pcont = QString::fromUtf8(pf.readAll());
if (pcont.startsWith(QChar(0xFEFF))) pcont.remove(0, 1); // toglie il BOM UTF-8
const QStringList lines = pcont.split('\n');
for (const QString& raw : lines) {
const QString l = raw.trimmed();
if (l.isEmpty() || l.startsWith('#')) continue;
const int eq = l.indexOf('=');
if (eq < 0) continue;
const QString k = l.left(eq).trimmed().toLower();
const QString v = l.mid(eq + 1).trimmed();
if (k == QLatin1String("base_url")) base = v;
else if (k == QLatin1String("api_key")) key = v;
else if (k == QLatin1String("model")) mdl = v;
}
pf.close();
if (!base.isEmpty() && !key.isEmpty()) {
while (base.endsWith('/')) base.chop(1); // niente slash finale
m_openai = true;
m_host = base;
m_apiKey = key;
if (!mdl.isEmpty()) m_model = mdl;
}
}
if (!m_openai && !m_primaryIsCloud)
warmUp(); // precarica il modello in VRAM (solo Ollama locale; non per il cloud)
// Descrizione degli strumenti esposti al modello (schema JSON).
QJsonObject scanFolder{
{"type", "function"},
{"function", QJsonObject{
{"name", "scan_folder"},
{"description",
"Elenca file e sottocartelle di una cartella locale sul PC di Martino. "
"Usalo quando l'utente chiede cosa c'è in una cartella o di esplorare il disco."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"path", QJsonObject{
{"type", "string"},
{"description", "Percorso assoluto della cartella, es. C:\\\\Users"}
}}
}},
{"required", QJsonArray{"path"}}
}}
}}
};
m_tools.append(scanFolder);
QJsonObject readFile{
{"type", "function"},
{"function", QJsonObject{
{"name", "read_file"},
{"description",
"Legge il contenuto testuale di un file locale sul PC di Martino. "
"Usalo quando l'utente chiede di leggere, aprire o mostrare cosa contiene un file."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"path", QJsonObject{
{"type", "string"},
{"description", "Percorso assoluto del file, es. C:\\\\Users\\\\IU8LMC\\\\nota.txt"}
}}
}},
{"required", QJsonArray{"path"}}
}}
}}
};
m_tools.append(readFile);
QJsonObject webSearch{
{"type", "function"},
{"function", QJsonObject{
{"name", "web_search"},
{"description",
"Cerca informazioni sul web (motore DuckDuckGo). Usalo quando l'utente "
"chiede fatti, notizie o informazioni che non sono sul PC locale."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"query", QJsonObject{
{"type", "string"},
{"description", "I termini da cercare"}
}}
}},
{"required", QJsonArray{"query"}}
}}
}}
};
m_tools.append(webSearch);
QJsonObject hamKb{
{"type", "function"},
{"function", QJsonObject{
{"name", "ham_kb"},
{"description",
"Knowledge base radioamatoriale interna: bande/frequenze, codici Q, RST, fonetico, "
"modi FT/CW/SSB, antenne, contest, DX, satelliti, normativa italiana. Per i dettagli tecnici."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"topic", QJsonObject{
{"type", "string"},
{"description", "argomento da cercare, es. 'FT8 frequenze', 'dipolo', 'QO-100', 'potenza Italia'"}
}}
}},
{"required", QJsonArray{"topic"}}
}}
}}
};
m_tools.append(hamKb);
QJsonObject createFile{
{"type", "function"},
{"function", QJsonObject{
{"name", "create_file"},
{"description",
"Crea (o sovrascrive) un file di testo sul PC di Martino con il contenuto indicato. "
"Richiede una conferma esplicita dell'utente prima di scrivere. "
"Usalo quando l'utente chiede di creare, salvare o scrivere un file."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"path", QJsonObject{
{"type", "string"},
{"description", "Percorso assoluto del file da creare, es. C:\\\\Users\\\\IU8LMC\\\\nota.txt"}
}},
{"content", QJsonObject{
{"type", "string"},
{"description", "Il contenuto testuale da scrivere nel file"}
}}
}},
{"required", QJsonArray{"path", "content"}}
}}
}}
};
m_tools.append(createFile);
// ham_calc: calcoli radioamatoriali esatti (antenne, Ohm, dBm/W).
QJsonObject hamCalc{
{"type", "function"},
{"function", QJsonObject{
{"name", "ham_calc"},
{"description",
"Esegue calcoli radioamatoriali ESATTI. Usalo SEMPRE per qualsiasi calcolo "
"numerico di antenne o elettricità invece di calcolare a mente. Operazioni: "
"'dipolo' e 'verticale' (servono freq_mhz), 'lunghezza_onda' (freq_mhz), "
"'ohm' (due tra v,i,r), 'dbm_to_watt' e 'watt_to_dbm' (valore)."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"operazione", QJsonObject{{"type", "string"},
{"description", "dipolo|verticale|lunghezza_onda|ohm|dbm_to_watt|watt_to_dbm"}}},
{"freq_mhz", QJsonObject{{"type", "number"}, {"description", "frequenza in MHz"}}},
{"v", QJsonObject{{"type", "number"}, {"description", "tensione in volt (per ohm)"}}},
{"i", QJsonObject{{"type", "number"}, {"description", "corrente in ampere (per ohm)"}}},
{"r", QJsonObject{{"type", "number"}, {"description", "resistenza in ohm (per ohm)"}}},
{"valore", QJsonObject{{"type", "number"}, {"description", "valore per dbm/watt"}}}
}},
{"required", QJsonArray{"operazione"}}
}}
}}
};
m_tools.append(hamCalc);
// locatore: Maidenhead <-> lat/lon, distanza e azimuth.
QJsonObject locatore{
{"type", "function"},
{"function", QJsonObject{
{"name", "locatore"},
{"description",
"Converte locatori Maidenhead e calcola distanza/azimuth ESATTI. Operazioni: "
"'grid_to_latlon' (serve grid), 'latlon_to_grid' (lat, lon), 'distanza' (grid1, grid2: "
"ritorna km e azimuth per puntare l'antenna)."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"operazione", QJsonObject{{"type", "string"},
{"description", "grid_to_latlon|latlon_to_grid|distanza"}}},
{"grid", QJsonObject{{"type", "string"}, {"description", "locatore, es. JN61na"}}},
{"grid1", QJsonObject{{"type", "string"}, {"description", "primo locatore (distanza)"}}},
{"grid2", QJsonObject{{"type", "string"}, {"description", "secondo locatore (distanza)"}}},
{"lat", QJsonObject{{"type", "number"}, {"description", "latitudine"}}},
{"lon", QJsonObject{{"type", "number"}, {"description", "longitudine"}}}
}},
{"required", QJsonArray{"operazione"}}
}}
}}
};
m_tools.append(locatore);
// ora_utc: data/ora UTC corrente.
QJsonObject oraUtc{
{"type", "function"},
{"function", QJsonObject{
{"name", "ora_utc"},
{"description",
"Data e ora UTC (e locale) correnti. Usalo quando serve l'orario (gli orari ham sono UTC). Nessun parametro."},
{"parameters", QJsonObject{{"type", "object"}, {"properties", QJsonObject{}}}}
}}
};
m_tools.append(oraUtc);
// log_qso: registra un collegamento in un log ADIF.
QJsonObject logQso{
{"type", "function"},
{"function", QJsonObject{
{"name", "log_qso"},
{"description",
"Registra un collegamento (QSO) nel log ADIF di Martino (data/ora UTC automatiche). "
"Usalo quando l'utente dice di aver collegato/lavorato una stazione e vuole annotarla."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"call", QJsonObject{{"type", "string"}, {"description", "nominativo del corrispondente"}}},
{"banda", QJsonObject{{"type", "string"}, {"description", "banda, es. 20m, 40m"}}},
{"modo", QJsonObject{{"type", "string"}, {"description", "modo, es. SSB, CW, FT8, FT2"}}},
{"rst_inviato", QJsonObject{{"type", "string"}, {"description", "RST dato, es. 59"}}},
{"rst_ricevuto", QJsonObject{{"type", "string"}, {"description", "RST ricevuto, es. 57"}}},
{"nota", QJsonObject{{"type", "string"}, {"description", "nota libera (facoltativa)"}}}
}},
{"required", QJsonArray{"call"}}
}}
}}
};
m_tools.append(logQso);
// memoria: ricorda fatti tra le sessioni (stazioni lavorate, preferenze, ecc.).
QJsonObject memoria{
{"type", "function"},
{"function", QJsonObject{
{"name", "memoria"},
{"description",
"Memoria persistente (note Markdown in un vault Obsidian). azione 'salva' (con "
"'contenuto', opz. 'titolo' per una nota per argomento) memorizza un fatto duraturo; "
"'leggi' rilegge la memoria; 'cerca' (con 'contenuto'=parola chiave) cerca in tutto il "
"vault. Solo fatti utili a lungo termine; nel contenuto puoi usare i [[wikilink]]."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"azione", QJsonObject{{"type", "string"}, {"description", "salva | leggi | cerca"}}},
{"contenuto", QJsonObject{{"type", "string"}, {"description", "il fatto da ricordare (salva) o la parola chiave (cerca)"}}},
{"titolo", QJsonObject{{"type", "string"}, {"description", "opzionale: titolo della nota per argomento (azione salva)"}}}
}},
{"required", QJsonArray{"azione"}}
}}
}}
};
m_tools.append(memoria);
// propagazione: dati solari/propagazione live (via web, async).
QJsonObject propag{
{"type", "function"},
{"function", QJsonObject{
{"name", "propagazione"},
{"description",
"Recupera i dati di propagazione/solari in tempo reale (SFI, A-index, K-index, "
"macchie solari) da hamqsl. Usalo quando l'utente chiede com'è la propagazione o le "
"condizioni delle bande. Nessun parametro."},
{"parameters", QJsonObject{{"type", "object"}, {"properties", QJsonObject{}}}}
}}
};
m_tools.append(propag);
// dxcluster: spot DX live dal cluster mondiale (dxwatch), con filtro banda.
QJsonObject dxcluster{
{"type", "function"},
{"function", QJsonObject{
{"name", "dxcluster"},
{"description",
"Recupera gli spot DX recenti dal DX Cluster mondiale (quali stazioni DX sono "
"attive ora e su che frequenza, segnalate dagli operatori). Usalo quando l'utente "
"chiede 'quali DX ci sono', 'chi e' spottato', 'cosa c'e' in 20 metri', o cerca un "
"DX da lavorare. Puoi filtrare per banda."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"banda", QJsonObject{{"type", "string"}, {"description", "banda opzionale, es. 20m, 40m, 15m"}}}
}}
}}
}}
};
m_tools.append(dxcluster);
// callsign: lookup nominativi (prefisso->paese sempre; dettagli USA/HamQTH).
QJsonObject callsign{
{"type", "function"},
{"function", QJsonObject{
{"name", "callsign"},
{"description",
"Info su un nominativo (tipo QRZ): paese/DXCC dal prefisso per ogni call, e nome/QTH/grid "
"per i call USA e (se configurato HamQTH) mondiali. Per 'di chi e'/da dove trasmette'."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"call", QJsonObject{{"type", "string"},
{"description", "il nominativo da cercare, es. IU8LMC, W1AW, DL1ABC"}}}
}},
{"required", QJsonArray{"call"}}
}}
}}
};
m_tools.append(callsign);
// decodium: stato in tempo reale del decoder Decodium 4 dell'utente (API locale).
QJsonObject decodium{
{"type", "function"},
{"function", QJsonObject{
{"name", "decodium"},
{"description",
"Legge in TEMPO REALE lo stato del software di decodifica Decodium dell'utente: "
"frequenza, modo (FT8/FT4/FT2/CW), se sta trasmettendo, e l'elenco delle stazioni "
"decodificate ora in banda (chi chiama CQ, DX, paese, rapporto). Usalo quando l'utente "
"chiede cosa sta decodificando, che frequenza/modo usa, chi c'è in banda, quali CQ o DX, "
"o per commentare/assistere il traffico in corso."},
{"parameters", QJsonObject{{"type", "object"}, {"properties", QJsonObject{}}}}
}}
};
m_tools.append(decodium);
// decodium_comando: COMANDA Decodium 4 (cambia modo/banda/frequenza, TX, rispondi a un chiamante).
QJsonObject decCmd{
{"type", "function"},
{"function", QJsonObject{
{"name", "decodium_comando"},
{"description",
"COMANDA Decodium, SOLO su richiesta esplicita di agire sulla radio. Campo 'comando': "
"modo (FT8/FT4/FT2/CW), banda (es. 20m), dial/rx/tx (hz), monitoraggio/autocq/autospot/"
"quickqso (attivo true/false), rispondi (call+grid), tx_on/tx_off, cw (valore=testo Morse; "
"opz. hz, wpm). tx_on/rispondi/autocq/cw mettono in TRASMISSIONE: solo su richiesta chiara."},
{"parameters", QJsonObject{
{"type", "object"},
{"properties", QJsonObject{
{"comando", QJsonObject{{"type", "string"},
{"description", "modo|banda|dial|rx|tx|monitoraggio|autocq|autospot|quickqso|rispondi|tx_on|tx_off|cw"}}},
{"valore", QJsonObject{{"type", "string"}, {"description", "modo/banda (es. FT8, 20m) oppure il TESTO CW da trasmettere (per comando=cw)"}}},
{"hz", QJsonObject{{"type", "number"}, {"description", "frequenza in Hz (dial/rx/tx/cw)"}}},
{"wpm", QJsonObject{{"type", "number"}, {"description", "velocità CW in parole/minuto (per comando=cw, default 22)"}}},
{"attivo", QJsonObject{{"type", "boolean"}, {"description", "on/off per i toggle"}}},
{"call", QJsonObject{{"type", "string"}, {"description", "nominativo da chiamare (rispondi)"}}},
{"grid", QJsonObject{{"type", "string"}, {"description", "locatore del corrispondente (rispondi)"}}}
}},
{"required", QJsonArray{"comando"}}
}}
}}
};
m_tools.append(decCmd);
startMcpBridge(); // tool esterni via MCP, solo se configurati in decodius_mcp.json
}
void OllamaClient::setSystemPrompt(const QString& s) {
reset();
QJsonObject sys{{"role", "system"}, {"content", s}};
m_history.prepend(sys);
warmChat(); // scalda la cache del prefisso (system+tool): primo turno reale veloce
}
// Invia una richiesta "a vuoto" con system prompt + tool e un messaggio banale, così
// Ollama elabora e mette in CACHE il prefisso (costoso sui modelli grandi su CPU).
// La prima domanda reale riusa la cache invece di pagare ~30s di prompt eval.
void OllamaClient::warmChat() {
if (m_openai || m_primaryIsCloud) return; // cloud: niente pre-riscaldamento (consuma quota)
if (m_history.isEmpty()) return;
QJsonArray msgs = m_history; // [system]
msgs.append(QJsonObject{{"role", "user"}, {"content", "ok"}});
QJsonObject body{
{"model", m_model}, {"messages", msgs}, {"tools", m_tools},
{"stream", false}, {"think", false}, {"keep_alive", -1},
{"options", QJsonObject{{"num_ctx", 8192}, {"num_predict", 1}}}
};
QNetworkRequest req{QUrl(m_host + QStringLiteral("/api/chat"))};
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply* r = m_net.post(req, QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(r, &QNetworkReply::finished, r, &QObject::deleteLater);
}
void OllamaClient::reset() {
// mantiene l'eventuale system prompt in testa
if (!m_history.isEmpty() && m_history.first().toObject().value("role").toString() == "system") {
QJsonValue sys = m_history.first();
m_history = QJsonArray();
m_history.append(sys);
} else {
m_history = QJsonArray();
}
}
void OllamaClient::warmUp() {
// Carica il modello in VRAM senza generare nulla (prompt vuoto), e lo tiene
// residente: così la prima richiesta reale non paga i ~10s di caricamento.
QJsonObject body{{"model", m_model}, {"keep_alive", -1}};
QNetworkRequest req{QUrl(m_host + QStringLiteral("/api/generate"))};
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply* r = m_net.post(req, QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(r, &QNetworkReply::finished, r, &QObject::deleteLater);
}
void OllamaClient::abortCurrent() {
if (m_reply && m_reply->isRunning())
m_reply->abort(); // fa scattare onFinished() con OperationCanceledError
}
void OllamaClient::cancel() {
// Interruzione esplicita dell'utente (barge-in): abortisce senza emettere errore.
m_userCancelled = true;
abortCurrent();
}
void OllamaClient::ask(const QString& userText) {
abortCurrent(); // una sola richiesta alla volta
m_toolRounds = 0;
m_turnTools = toolsForTurn(userText); // lazy-loading: tool pertinenti a questo turno
// Cap della history (PC modesti): tieni system + ultimi turni, ripartendo da un messaggio
// utente (così non restano messaggi-tool "orfani" che confonderebbero il modello/il cloud).
if (m_history.size() > 12) {
QJsonArray keep;
if (!m_history.isEmpty()
&& m_history.first().toObject().value("role").toString() == QLatin1String("system"))
keep.append(m_history.first());