Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1050 lines (995 loc) · 47.2 KB
/
Copy pathmain.cpp
File metadata and controls
1050 lines (995 loc) · 47.2 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
// Copyright(C) 2025-2026 Advanced Micro Devices, Inc. All rights reserved.
// SPDX-License-Identifier: MIT
//
// gaiacpp — the native GAIA agent.
//
// gaiacpp Interactive session
// gaiacpp -p "prompt" [--output-format json] One headless run (prompt from stdin when omitted)
// gaiacpp serve [--host H] [--port N] OpenAI-compatible server (for Lemonade / apps)
// gaiacpp --stdio The GAIA terminal UI's agent child (JSON Lines)
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <gaia/api_server.h>
#include <gaia/clean_console.h>
#include <gaia/console.h>
#include <gaia/mcp_stdio_server.h>
#include <gaia/repl.h>
#include <gaia/session.h>
#include "gaia_agent.h"
#include "sidecar.h"
#include "stdio_server.h"
#ifdef _WIN32
#include <windows.h>
#include <psapi.h>
#else
#include <poll.h>
#include <sys/resource.h>
#include <unistd.h>
#endif
#ifndef GAIACPP_VERSION
#define GAIACPP_VERSION "0.0.0-dev"
#endif
namespace fs = std::filesystem;
namespace {
// CPU seconds (user + system) this process used, children not included.
double selfCpuSeconds() {
#ifdef _WIN32
FILETIME c, e, k, u;
if (!GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &u)) return -1;
auto secs = [](const FILETIME& f) {
return static_cast<double>((static_cast<unsigned long long>(f.dwHighDateTime) << 32) |
f.dwLowDateTime) / 1e7;
};
return secs(k) + secs(u);
#else
struct rusage ru {};
if (getrusage(RUSAGE_SELF, &ru) != 0) return -1;
return static_cast<double>(ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) +
static_cast<double>(ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1e6;
#endif
}
// This process's own peak resident memory in MB (children not included).
double selfPeakRssMb() {
#ifdef _WIN32
PROCESS_MEMORY_COUNTERS pmc{};
if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return -1;
return static_cast<double>(pmc.PeakWorkingSetSize) / (1024.0 * 1024.0);
#else
struct rusage ru {};
if (getrusage(RUSAGE_SELF, &ru) != 0) return -1;
#ifdef __APPLE__
return static_cast<double>(ru.ru_maxrss) / (1024.0 * 1024.0); // bytes on macOS
#else
return static_cast<double>(ru.ru_maxrss) / 1024.0; // kilobytes on Linux
#endif
#endif
}
constexpr const char* kFireworksUrl = "https://api.fireworks.ai/inference/v1";
struct Cli {
enum class Mode { Interactive, Print, Serve, Mcp, Stdio } mode = Mode::Interactive;
std::optional<std::string> prompt;
std::string promptFile;
std::string outputFormat = "text";
std::string model;
std::string baseUrl;
std::string provider;
std::string apiKeyEnv;
std::string nativeTools;
std::string featureTier;
std::string cwd;
std::string mcpConfig;
std::string embeddingModel;
std::string visionModel;
std::string transcribeModel;
std::string imageModel;
std::string configFile;
std::string host = "127.0.0.1";
std::string serveKeyEnv;
std::vector<std::string> allowedOrigins;
int port = 8200;
int maxSteps = 0;
int ctxSize = 0;
int maxTokens = 0;
int maxHelpers = -1; // -1 = not given
std::optional<double> temperature;
bool skipPermissions = false;
bool noWeb = false;
bool noSkills = false;
bool noMemory = false;
bool screenshots = false;
bool fullAccess = false;
bool acceptEdits = false;
std::vector<std::string> allowDirs;
bool debug = false;
bool dev = false;
bool exposeToolRoutes = false;
};
void printUsage() {
std::cout <<
"gaiacpp " GAIACPP_VERSION " — GAIA agent (native)\n\n"
"Usage:\n"
" gaiacpp [options] Interactive session\n"
" gaiacpp -p [PROMPT] [options] One headless run; PROMPT or stdin\n"
" gaiacpp serve [options] OpenAI-compatible server\n"
" gaiacpp --mcp [options] MCP server on stdin/stdout: the tools,\n"
" for another program's agent to call\n"
" gaiacpp --stdio [options] Agent child of the GAIA terminal UI:\n"
" queries in, JSON Lines events out\n"
" gaiacpp skills list|install DIR|NAME[@VER] [--allow-experimental]|remove NAME\n"
" Manage installed skills (hub or folder)\n"
" gaiacpp models list|pull NAME [--checkpoint C --recipe R]\n"
" Lemonade models; takes --base-url,\n"
" --provider, --api-key-env, --config\n\n"
"Model:\n"
" -m, --model ID Model id (env GAIA_MODEL_ID)\n"
" --base-url URL OpenAI-compatible endpoint (env GAIA_BASE_URL,\n"
" LEMONADE_BASE_URL; default Lemonade on :13305)\n"
" --provider NAME lemonade (default) or fireworks\n"
" --api-key-env VAR Variable holding the endpoint key (default\n"
" GAIA_API_KEY, then LEMONADE_API_KEY)\n"
" --native-tools MODE auto | always | never (OpenAI tool calls)\n"
" --feature-tier TIER auto | full | compact: compact offers fewer tools\n"
" for a shorter prompt (env GAIA_FEATURE_TIER)\n"
" --ctx-size N Context window to load the model with\n"
" --max-tokens N Max tokens per reply\n"
" --temperature T Sampling temperature\n"
"Run:\n"
" -p, --print [PROMPT] Headless: answer on stdout, exit 0/1\n"
" --prompt-file FILE Read the prompt from FILE\n"
" --output-format FMT text (default) or json\n"
" --cwd DIR Work in DIR\n"
" --max-steps N Step budget (default 1000)\n"
" --max-helpers N Read-only helpers delegate_task runs at once. Default:\n"
" what the model serves (its slot count up to 4 locally,\n"
" 8 on a cloud model). 0 turns the tool off\n"
" (env GAIA_MAX_HELPERS)\n"
" --mcp-config FILE Connect the MCP servers in FILE (mcp.json)\n"
" --vision-model ID Model analyze_image uses (default: the main model)\n"
" --transcribe-model ID Whisper model for transcribe_audio (e.g. Whisper-Base on Lemonade)\n"
" --image-model ID Image model for generate_image (e.g. SDXL-Turbo on Lemonade)\n"
" --embedding-model ID Embedding model for document search (default with\n"
" --provider fireworks; otherwise keyword search)\n"
" --config FILE Settings file (default $GAIACPP_CONFIG, else\n"
" $XDG_CONFIG_HOME/gaiacpp/config.json or\n"
" ~/.config/gaiacpp/config.json when present;\n"
" %APPDATA%\\gaiacpp\\config.json on Windows)\n"
" --no-web Leave out web_fetch\n"
" --no-skills Leave out installed SKILL.md skills\n"
" --no-memory Don't remember or recall facts across sessions\n"
" --screenshots Offer take_screenshot (off by default: privacy)\n"
" --allow-dir DIR Also let the tools use DIR (repeatable). By default\n"
" they are confined to the working directory\n"
" --full-access Let the tools reach any path the user can\n"
" --dangerously-skip-permissions\n"
" Run gated tools (shell, writes, web) without asking.\n"
" Without it, headless runs deny them.\n"
"Serve:\n"
" --host H Bind address (default 127.0.0.1)\n"
" --port N Port (default 8200; 0 = any free port)\n"
" --server-key-env VAR Require 'Authorization: Bearer $VAR' from clients (required)\n"
" --allow-origin ORIGIN Allow a browser origin (repeatable)\n"
" --expose-tool-routes Enable POST /v1/tools/:name (direct tool runs)\n"
"Stdio (the terminal UI passes these):\n"
" --full-access With --stdio: approval prompts off. The tools stay\n"
" inside the working directory and --allow-dir\n"
" --accept-edits File edits inside the working directory run\n"
" without asking; everything else still asks\n"
" --dev Step-by-step status events, debug lines on stderr\n"
"Other:\n"
" --debug, -v/--version, -h/--help\n\n"
"Environment: GAIA_BASE_URL, GAIA_MODEL_ID, GAIA_API_KEY, LEMONADE_BASE_URL,\n"
"LEMONADE_API_KEY, FIREWORKS_API_KEY (with --provider fireworks).\n";
}
[[noreturn]] void usageError(const std::string& msg) {
std::cerr << "gaiacpp: " << msg << "\nRun 'gaiacpp --help' for usage.\n";
std::exit(2);
}
int toInt(const std::string& flag, const std::string& v) {
try {
size_t used = 0;
const int n = std::stoi(v, &used);
if (used != v.size()) throw std::invalid_argument(v);
return n;
} catch (const std::exception&) {
usageError(flag + " needs a whole number, got '" + v + "'");
}
}
int toPositiveInt(const std::string& flag, const std::string& v) {
const int n = toInt(flag, v);
if (n <= 0) usageError(flag + " needs a whole number above 0, got '" + v + "'");
return n;
}
int toHelperCount(const std::string& flag, const std::string& v) {
const int n = toInt(flag, v);
if (n < 0 || n > 64) usageError(flag + " needs a whole number from 0 to 64, got '" + v + "'");
return n;
}
// GAIA_MAX_HELPERS, or -1 when it is not set.
int maxHelpersFromEnv() {
const std::string v = gaia::getEnvVar("GAIA_MAX_HELPERS");
return v.empty() ? -1 : toHelperCount("GAIA_MAX_HELPERS", v);
}
bool validTemperature(double t) { return std::isfinite(t) && t >= 0.0 && t <= 2.0; }
double toTemperature(const std::string& flag, const std::string& v) {
double t = std::numeric_limits<double>::quiet_NaN();
try {
size_t used = 0;
t = std::stod(v, &used);
if (used != v.size()) t = std::numeric_limits<double>::quiet_NaN();
} catch (const std::exception&) {
t = std::numeric_limits<double>::quiet_NaN();
}
if (!validTemperature(t)) usageError(flag + " needs a number from 0 to 2, got '" + v + "'");
return t;
}
Cli parseArgs(int argc, char** argv) {
Cli cli;
auto need = [&](int& i, const std::string& flag) -> std::string {
if (i + 1 >= argc) usageError(flag + " needs a value");
return argv[++i];
};
std::string modeFlag;
auto setMode = [&](Cli::Mode mode, const std::string& flag) {
if (cli.mode != Cli::Mode::Interactive && cli.mode != mode) {
usageError(modeFlag + " and " + flag + " are different ways to run gaiacpp: pick one");
}
cli.mode = mode;
modeFlag = flag;
};
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "-h" || a == "--help") { printUsage(); std::exit(0); }
else if (a == "-v" || a == "--version") { std::cout << "gaiacpp " GAIACPP_VERSION "\n"; std::exit(0); }
else if (a == "serve" && i == 1) setMode(Cli::Mode::Serve, a);
else if (a == "-p" || a == "--print") {
setMode(Cli::Mode::Print, a);
if (i + 1 < argc && argv[i + 1][0] != '-') cli.prompt = argv[++i];
}
else if (a == "--mcp") setMode(Cli::Mode::Mcp, a);
else if (a == "--stdio") setMode(Cli::Mode::Stdio, a);
else if (a == "--accept-edits") cli.acceptEdits = true;
else if (a == "--dev") cli.dev = true;
else if (a == "--use-claude" || a == "--claude-model") {
usageError(a + " isn't supported: gaiacpp has no Claude provider and runs models through "
"Lemonade only. Drop the flag and pick a model with --model, or use the "
"Python agent (gaia-agent) for Claude.");
}
else if (a == "--prompt-file") { setMode(Cli::Mode::Print, a); cli.promptFile = need(i, a); }
else if (a == "--output-format") cli.outputFormat = need(i, a);
else if (a == "-m" || a == "--model") cli.model = need(i, a);
else if (a == "--base-url") cli.baseUrl = need(i, a);
else if (a == "--provider") cli.provider = need(i, a);
else if (a == "--api-key-env") cli.apiKeyEnv = need(i, a);
else if (a == "--native-tools") cli.nativeTools = need(i, a);
else if (a == "--feature-tier") cli.featureTier = need(i, a);
else if (a == "--ctx-size") cli.ctxSize = toPositiveInt(a, need(i, a));
else if (a == "--max-tokens") cli.maxTokens = toPositiveInt(a, need(i, a));
else if (a == "--temperature") cli.temperature = toTemperature(a, need(i, a));
else if (a == "--max-steps") cli.maxSteps = toPositiveInt(a, need(i, a));
else if (a == "--max-helpers") cli.maxHelpers = toHelperCount(a, need(i, a));
else if (a == "--cwd") cli.cwd = need(i, a);
else if (a == "--mcp-config") cli.mcpConfig = need(i, a);
else if (a == "--embedding-model") cli.embeddingModel = need(i, a);
else if (a == "--vision-model") cli.visionModel = need(i, a);
else if (a == "--transcribe-model") cli.transcribeModel = need(i, a);
else if (a == "--image-model") cli.imageModel = need(i, a);
else if (a == "--config") cli.configFile = need(i, a);
else if (a == "--no-web") cli.noWeb = true;
else if (a == "--no-skills") cli.noSkills = true;
else if (a == "--no-memory") cli.noMemory = true;
else if (a == "--screenshots") cli.screenshots = true;
else if (a == "--allow-dir") cli.allowDirs.push_back(need(i, a));
else if (a == "--full-access") cli.fullAccess = true;
else if (a == "--dangerously-skip-permissions") cli.skipPermissions = true;
else if (a == "--host") cli.host = need(i, a);
else if (a == "--port") {
const std::string v = need(i, a);
cli.port = toInt(a, v);
if (cli.port < 0 || cli.port > 65535) usageError("--port needs a number from 0 to 65535, got '" + v + "'");
}
else if (a == "--server-key-env") cli.serveKeyEnv = need(i, a);
else if (a == "--allow-origin") cli.allowedOrigins.push_back(need(i, a));
else if (a == "--expose-tool-routes") cli.exposeToolRoutes = true;
else if (a == "--debug") cli.debug = true;
else usageError("unknown argument '" + a + "'");
}
if (cli.outputFormat != "text" && cli.outputFormat != "json") {
usageError("--output-format must be text or json");
}
if (cli.mode != Cli::Mode::Stdio && (cli.acceptEdits || cli.dev)) {
usageError("--accept-edits and --dev go with --stdio");
}
return cli;
}
fs::path defaultConfigPath() {
const std::string env = gaia::getEnvVar("GAIACPP_CONFIG");
if (!env.empty()) return env;
#ifdef _WIN32
const std::string base = gaia::getEnvVar("APPDATA");
return base.empty() ? fs::path() : fs::path(base) / "gaiacpp" / "config.json";
#else
std::string base = gaia::getEnvVar("XDG_CONFIG_HOME");
if (base.empty()) {
const std::string home = gaia::getEnvVar("HOME");
if (home.empty()) return {};
base = home + "/.config";
}
return fs::path(base) / "gaiacpp" / "config.json";
#endif
}
void applyProvider(gaia::json& merged, const std::string& provider, const std::string& where) {
if (provider == "fireworks") {
merged["baseUrl"] = kFireworksUrl;
merged["apiKeyEnv"] = "FIREWORKS_API_KEY";
merged["nativeToolCalls"] = "always";
merged["contextSize"] = 131072;
merged["embeddingModel"] = "nomic-ai/nomic-embed-text-v1.5";
} else if (provider != "lemonade") {
throw std::runtime_error(where + ": provider must be lemonade or fireworks, got '" +
provider + "'");
}
}
// A wrongly typed or out-of-range value is named with its key and file, not left to a JSON type error.
void checkSettingsFile(const gaia::json& j, const std::string& where) {
auto fail = [&](const std::string& key, const std::string& expected) {
throw std::runtime_error(where + ": \"" + key + "\" must be " + expected + ", got " +
j[key].dump(-1, ' ', false, gaia::json::error_handler_t::replace) +
". Fix that value in the file and run again.");
};
for (const char* key : {"baseUrl", "modelId", "apiKeyEnv", "featureTier", "responseMode",
"nativeToolCalls", "embeddingModel", "transcribeModel", "audioBaseUrl",
"imageModel", "mcpConfig", "provider"}) {
if (j.contains(key) && !j[key].is_string()) fail(key, "a string");
}
for (const char* key : {"contextSize", "maxTokens", "maxSteps"}) {
if (!j.contains(key)) continue;
const gaia::json& v = j[key];
const bool ok = v.is_number_integer() && v >= 1 && v <= (std::numeric_limits<int>::max)();
if (!ok) fail(key, "a whole number above 0");
}
for (const char* key : {"debug", "showPrompts", "streaming", "silentMode", "structuredEvents"}) {
if (j.contains(key) && !j[key].is_boolean()) fail(key, "true or false");
}
if (j.contains("maxHelpers") &&
!(j["maxHelpers"].is_number_integer() && j["maxHelpers"] >= 0 && j["maxHelpers"] <= 64)) {
fail("maxHelpers", "a whole number from 0 to 64");
}
if (j.contains("temperature") &&
!(j["temperature"].is_number() && validTemperature(j["temperature"].get<double>()))) {
fail("temperature", "a number from 0 to 2");
}
}
// Settings precedence: built-in defaults < settings file < environment < flags.
struct Settings {
gaia::AgentConfig cfg;
std::string mcpConfig;
std::string embeddingModel; // empty = keyword-only document retrieval
std::string transcribeModel, audioBaseUrl, imageModel;
int maxHelpers = -1; // -1 = sized to the model
};
Settings buildSettings(const Cli& cli) {
gaia::json merged = {{"contextSize", 32768},
{"maxTokens", 16384},
{"temperature", 0.2},
{"modelId", "Gemma-4-E4B-it-GGUF"},
{"baseUrl", gaia::defaultBaseUrl()},
{"responseMode", "conversational"},
{"maxSteps", 1000}};
std::string mcpConfig;
std::string settingsFrom = "The settings";
bool fileSetsWindow = false;
const fs::path file = cli.configFile.empty() ? defaultConfigPath() : fs::path(cli.configFile);
std::error_code ec;
if (!file.empty() && (!cli.configFile.empty() || fs::exists(file, ec))) {
std::ifstream in(file);
if (!in) throw std::runtime_error("Cannot read settings file " + file.string());
gaia::json j;
try {
in >> j;
} catch (const std::exception& e) {
throw std::runtime_error("Settings file " + file.string() +
" is not valid JSON: " + e.what());
}
if (!j.is_object()) {
throw std::runtime_error("Settings file " + file.string() + " must hold a JSON object");
}
checkSettingsFile(j, "Settings file " + file.string());
settingsFrom = "Settings file " + file.string();
if (j.contains("mcpConfig")) {
fs::path m = j["mcpConfig"].get<std::string>();
if (m.is_relative()) m = file.parent_path() / m;
mcpConfig = m.string();
j.erase("mcpConfig");
}
fileSetsWindow = j.contains("contextSize") || j.contains("provider");
if (j.contains("provider")) {
applyProvider(merged, j["provider"].get<std::string>(), "Settings file " + file.string());
j.erase("provider");
}
merged.update(j);
}
const std::string envModel = gaia::getEnvVar("GAIA_MODEL_ID");
if (!envModel.empty()) merged["modelId"] = envModel;
const std::string envTier = gaia::getEnvVar("GAIA_FEATURE_TIER");
if (!envTier.empty()) merged["featureTier"] = envTier;
const std::string envUrl = gaia::getEnvVar("GAIA_BASE_URL");
if (!envUrl.empty()) merged["baseUrl"] = envUrl;
for (const auto& [var, field] : {std::pair<const char*, const char*>{"GAIA_AGENT_MAX_STEPS", "maxSteps"},
{"GAIA_MAX_STEPS", "maxSteps"},
{"GAIA_CONTEXT_SIZE", "contextSize"},
{"GAIA_MAX_TOKENS", "maxTokens"}}) {
const std::string v = gaia::getEnvVar(var);
if (!v.empty()) merged[field] = toPositiveInt(var, v);
}
if (const int n = maxHelpersFromEnv(); n >= 0) merged["maxHelpers"] = n;
if (cli.maxHelpers >= 0) merged["maxHelpers"] = cli.maxHelpers;
if (!cli.provider.empty()) applyProvider(merged, cli.provider, "--provider");
if (!cli.baseUrl.empty()) merged["baseUrl"] = cli.baseUrl;
if (!cli.model.empty()) merged["modelId"] = cli.model;
if (!cli.apiKeyEnv.empty()) merged["apiKeyEnv"] = cli.apiKeyEnv;
if (!cli.nativeTools.empty()) merged["nativeToolCalls"] = cli.nativeTools;
if (!cli.featureTier.empty()) merged["featureTier"] = cli.featureTier;
if (cli.ctxSize > 0) merged["contextSize"] = cli.ctxSize;
if (cli.maxTokens > 0) merged["maxTokens"] = cli.maxTokens;
if (cli.maxSteps > 0) merged["maxSteps"] = cli.maxSteps;
if (cli.temperature) merged["temperature"] = *cli.temperature;
if (!cli.mcpConfig.empty()) mcpConfig = cli.mcpConfig;
if (!cli.embeddingModel.empty()) merged["embeddingModel"] = cli.embeddingModel;
if (!cli.transcribeModel.empty()) merged["transcribeModel"] = cli.transcribeModel;
if (!cli.imageModel.empty()) merged["imageModel"] = cli.imageModel;
// A hosted model reached through Lemonade has the provider's window, not a local one.
const bool windowGiven = fileSetsWindow || !gaia::getEnvVar("GAIA_CONTEXT_SIZE").empty() || cli.ctxSize > 0 ||
!cli.provider.empty();
const std::string model = merged.value("modelId", "");
if (!windowGiven && (model.rfind("fireworks.", 0) == 0 || model.rfind("amd.", 0) == 0)) {
merged["contextSize"] = 131072;
}
Settings s;
if (merged.contains("maxHelpers")) {
s.maxHelpers = merged["maxHelpers"].get<int>();
merged.erase("maxHelpers");
}
for (auto [key, field] : {std::pair<const char*, std::string*>{"embeddingModel", &s.embeddingModel},
{"transcribeModel", &s.transcribeModel},
{"audioBaseUrl", &s.audioBaseUrl},
{"imageModel", &s.imageModel}}) {
if (merged.contains(key)) {
*field = merged[key].get<std::string>();
merged.erase(key);
}
}
try {
s.cfg = gaia::AgentConfig::fromJson(merged);
} catch (const gaia::json::exception& e) {
throw std::runtime_error(settingsFrom + ": a value has the wrong type (" + e.what() +
"). Fix that value and run again.");
}
s.cfg.debug = cli.debug;
s.mcpConfig = mcpConfig;
return s;
}
// The Agent constructor lets GAIA_* variables override its config; re-apply the
// resolved settings so a flag always beats the environment.
void pinConfig(gaia::Agent& agent, const gaia::AgentConfig& cfg) {
agent.setConfig(cfg);
}
void connectMcp(gaia::Agent& agent, const std::string& path) {
std::ifstream in(path);
if (!in) throw std::runtime_error("Cannot open MCP config " + path);
gaia::json doc;
try {
in >> doc;
} catch (const std::exception& e) {
throw std::runtime_error("MCP config " + path + " is not valid JSON: " + e.what());
}
const char* key = doc.contains("mcpServers") ? "mcpServers" : "servers";
if (!doc.contains(key) || !doc[key].is_object()) {
throw std::runtime_error("MCP config " + path +
" has no \"mcpServers\" object naming the servers to connect");
}
for (auto& [name, server] : doc[key].items()) {
if (!server.is_object() || server.value("disabled", false)) continue;
// "optional" is this file's own word for "start without it"; the server never sees it.
const bool optional = server.value("optional", false);
gaia::json spec = server;
spec.erase("optional");
if (agent.connectMcpServer(name, spec)) continue;
if (!optional) {
throw std::runtime_error("Could not connect MCP server '" + name + "' from " + path +
" (details above). Fix or disable it, or mark it "
"\"optional\": true to start without it, then retry.");
}
std::cerr << "gaiacpp: MCP server '" << name << "' (" << path
<< ") could not be reached and is marked optional, so its tools are not "
"available in this session.\n";
}
}
std::string readAll(std::istream& in) {
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// The working directory first (relative paths resolve there), then --allow-dir.
gaia::GaiaAgent::Options agentOptions(const Cli& cli, const Settings& settings) {
gaia::GaiaAgent::Options o;
o.embeddingModel = settings.embeddingModel;
o.transcribeModel = settings.transcribeModel;
o.audioBaseUrl = settings.audioBaseUrl;
o.imageModel = settings.imageModel;
o.visionModel = cli.visionModel;
o.webTools = !cli.noWeb;
o.skills = !cli.noSkills;
o.memory = !cli.noMemory;
o.screenshots = cli.screenshots;
o.fullAccess = cli.fullAccess;
o.maxHelpers = settings.maxHelpers;
std::error_code ec;
o.workspaceRoots.push_back(fs::current_path(ec).u8string());
for (const auto& d : cli.allowDirs) {
if (!fs::is_directory(d, ec)) usageError("--allow-dir " + d + " is not a folder");
o.workspaceRoots.push_back(fs::absolute(d).u8string()); // argv is in the code page
}
return o;
}
std::atomic<gaia::Agent*> g_agent{nullptr};
std::atomic<gaia::ApiServer*> g_server{nullptr};
std::atomic<int> g_signals{0};
// First signal: stop gracefully. A second one exits at once, since a blocking
// model call or tool can't see the cancel flag until it returns.
extern "C" void onSignal(int) {
if (g_signals.fetch_add(1) > 0) std::_Exit(130);
if (auto* s = g_server.load()) s->stop();
if (auto* a = g_agent.load()) a->requestCancel();
}
// Tools only: the calling program brings its own model, so none is contacted.
int runMcp(const Cli& cli) {
// stdout is the transport; anything else printed goes to stderr.
std::ostream transport(std::cout.rdbuf());
std::cout.rdbuf(std::cerr.rdbuf());
const Settings settings = buildSettings(cli);
gaia::AgentConfig cfg = settings.cfg;
cfg.silentMode = true;
gaia::GaiaAgent agent(cfg, agentOptions(cli, settings));
pinConfig(agent, cfg);
agent.setToolConfirmCallback([skip = cli.skipPermissions](const std::string& tool, const gaia::json&) {
if (!skip) {
std::cerr << "[gaiacpp] denied " << tool
<< " (nobody to ask over MCP; pass --dangerously-skip-permissions to allow)\n";
}
return skip ? gaia::ToolConfirmResult::ALLOW_ONCE : gaia::ToolConfirmResult::DENY;
});
if (!settings.mcpConfig.empty()) connectMcp(agent, settings.mcpConfig);
gaia::McpStdioServer server(agent, "gaiacpp", GAIACPP_VERSION, std::cin, transport);
server.run();
return 0;
}
// False once stdout is a pipe nobody reads any more.
bool stdoutHasReader() {
#ifdef _WIN32
const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
if (out == nullptr || out == INVALID_HANDLE_VALUE) return false;
if (GetFileType(out) != FILE_TYPE_PIPE) return true;
// An empty write reaches no reader but still fails on a broken pipe.
DWORD written = 0;
if (WriteFile(out, "", 0, &written, nullptr)) return true;
const DWORD err = GetLastError();
return err != ERROR_BROKEN_PIPE && err != ERROR_NO_DATA;
#else
struct pollfd p {};
p.fd = STDOUT_FILENO;
p.events = POLLOUT;
if (poll(&p, 1, 0) < 0) return true;
return (p.revents & (POLLERR | POLLHUP | POLLNVAL)) == 0;
#endif
}
// The GAIA terminal UI's agent child: queries and controls on stdin, events on stdout.
int runStdio(const Cli& cli) {
#ifndef _WIN32
// A host that closed stdout shows up as a failed write, not as a signal that kills.
std::signal(SIGPIPE, SIG_IGN);
#endif
// stdout is the wire; anything else printed goes to stderr.
std::ostream wire(std::cout.rdbuf());
std::cout.rdbuf(std::cerr.rdbuf());
try {
const Settings settings = buildSettings(cli);
gaia::AgentConfig cfg = settings.cfg;
cfg.silentMode = true;
cfg.debug = cli.debug || cli.dev;
const gaia::NativeToolCalls launchMode = cfg.nativeToolCalls;
gaia::applyStdioModel(cfg, cfg.modelId, launchMode);
gaia::GaiaAgent::Options options = agentOptions(cli, settings);
// Here --full-access turns approval prompts off; it does not widen the folders.
options.fullAccess = false;
gaia::GaiaAgent agent(cfg, options);
pinConfig(agent, cfg);
if (!settings.mcpConfig.empty()) connectMcp(agent, settings.mcpConfig);
gaia::StdioOptions so;
so.fullAccess = cli.fullAccess || cli.skipPermissions;
so.acceptEdits = cli.acceptEdits;
so.dev = cli.dev;
so.agentVersion = GAIACPP_VERSION;
// UTF-8, as the server reads it: workspaceRoots holds the code page's spelling.
so.editRoots = {gaia::workingFolderUtf8()};
so.memory = options.memory;
so.nativeTools = launchMode;
so.hostAlive = stdoutHasReader;
so.exitWhenHostGone = true;
gaia::StdioServer server(agent, std::cin, wire, so);
g_agent = &agent;
const int code = server.run();
g_agent = nullptr;
// The reader may still be blocked on stdin, which a normal exit would wait for.
if (code != 0 || server.hostGone()) {
std::cerr.flush();
std::_Exit(code);
}
return code;
} catch (const std::exception& e) {
// The UI reads the failure off the wire; main() prints it on stderr.
wire << gaia::json{{"type", "error"}, {"detail", std::string("gaiacpp could not start: ") + e.what()}}
.dump(-1, ' ', false, gaia::json::error_handler_t::replace)
<< std::endl;
throw;
}
}
int runPrint(const Cli& cli) {
std::string prompt;
if (cli.prompt) prompt = *cli.prompt;
else if (!cli.promptFile.empty()) {
std::ifstream in(cli.promptFile, std::ios::binary);
if (!in) throw std::runtime_error("Cannot read prompt file " + cli.promptFile);
prompt = readAll(in);
} else {
prompt = readAll(std::cin);
}
if (prompt.find_first_not_of(" \t\r\n") == std::string::npos) {
usageError("-p needs a prompt: pass it as an argument, with --prompt-file, or on stdin");
}
const Settings settings = buildSettings(cli);
gaia::AgentConfig cfg = settings.cfg;
cfg.silentMode = true; // stdout carries only the answer
gaia::GaiaAgent agent(cfg, agentOptions(cli, settings));
pinConfig(agent, cfg);
agent.setOutputHandler(std::make_unique<gaia::CleanConsole>());
agent.setToolConfirmCallback([skip = cli.skipPermissions](const std::string& tool, const gaia::json&) {
if (!skip) {
std::cerr << "[gaiacpp] denied " << tool
<< " (headless run; pass --dangerously-skip-permissions to allow)\n";
}
return skip ? gaia::ToolConfirmResult::ALLOW_ONCE : gaia::ToolConfirmResult::DENY;
});
if (!settings.mcpConfig.empty()) {
std::streambuf* saved = std::cout.rdbuf(std::cerr.rdbuf());
try { connectMcp(agent, settings.mcpConfig); } catch (...) { std::cout.rdbuf(saved); throw; }
std::cout.rdbuf(saved);
}
// Opened before the run so a bad path fails before any model time is spent.
std::ofstream turnLog;
if (const char* path = std::getenv("GAIA_TURN_LOG"); path && *path) {
turnLog.open(path, std::ios::app);
if (!turnLog) {
throw std::runtime_error(std::string("Cannot write the turn log at ") + path +
". Point GAIA_TURN_LOG at a writable file, or unset it.");
}
}
// One flushed line per model or tool call, so a turn that is killed still leaves a record.
std::ofstream stepLog;
if (const char* path = std::getenv("GAIA_STEP_LOG"); path && *path) {
stepLog.open(path, std::ios::app);
if (!stepLog) {
throw std::runtime_error(std::string("Cannot write the step log at ") + path +
". Point GAIA_STEP_LOG at a writable file, or unset it.");
}
agent.setStepLogger([&stepLog](const gaia::json& step) {
gaia::json line = step;
line["schema"] = "gaiacpp.step/1";
stepLog << line.dump(-1, ' ', false, gaia::json::error_handler_t::replace) << std::endl;
});
}
g_agent = &agent;
const auto t0 = std::chrono::steady_clock::now();
// Progress goes to stderr; stdout carries only the answer.
std::streambuf* stdoutBuf = std::cout.rdbuf(std::cerr.rdbuf());
gaia::json result;
try {
result = agent.processQuery(prompt);
} catch (...) {
std::cout.rdbuf(stdoutBuf);
g_agent = nullptr;
throw;
}
std::cout.rdbuf(stdoutBuf);
const double secs =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
g_agent = nullptr;
const std::string status = result.value("status", "success");
const gaia::json usage = result.value("usage", gaia::json::object());
const gaia::json helpers = agent.helperStats();
// Same names as `gaia -p --output-format json`, so one reader takes both agents.
gaia::json out = {{"status", status},
{"is_error", status != "success"},
{"steps", result.value("steps_taken", 0)},
{"tool_errors", result.value("tool_errors", 0)},
{"model", cfg.modelId},
{"duration_s", std::round(secs * 10) / 10},
{"peak_rss_mb", std::round(selfPeakRssMb() * 10) / 10},
{"cpu_s", std::round(selfCpuSeconds() * 100) / 100},
{"num_steps", result.value("steps_taken", 0)},
{"num_llm_calls", result.value("llm_calls", 0)},
{"num_tool_calls", result.value("tool_calls", 0)},
{"error_count", result.value("tool_errors", 0)},
{"input_tokens", usage.value("prompt_tokens", 0)},
{"cached_tokens", usage.value("cached_tokens", 0)},
{"output_tokens", usage.value("completion_tokens", 0)},
{"peak_context_tokens", usage.value("peak_context_tokens", 0)}};
if (result.contains("usage")) out["usage"] = usage;
if (helpers.value("runs", 0) > 0) out["helpers"] = helpers;
if (turnLog.is_open()) {
gaia::json line = out;
line["schema"] = "gaiacpp.turn/1";
line["llm_calls"] = result["telemetry"]["llm_calls"];
line["tool_calls"] = result["telemetry"]["tool_calls"];
turnLog << line.dump(-1, ' ', false, gaia::json::error_handler_t::replace) << std::endl;
}
if (cli.outputFormat == "json") {
out["result"] = result.value("result", "");
std::cout << out.dump(-1, ' ', false, gaia::json::error_handler_t::replace) << std::endl;
} else {
std::cout << result.value("result", "") << std::endl;
}
return status == "success" ? 0 : 1;
}
int runServe(const Cli& cli) {
// Tools run unasked here, so a server anyone on this PC can reach would run their commands.
if (cli.serveKeyEnv.empty()) {
usageError("serve needs --server-key-env VAR naming a variable that holds the clients' key, "
"for example: SERVE_KEY=$(openssl rand -hex 32) gaiacpp serve --server-key-env SERVE_KEY");
}
const Settings settings = buildSettings(cli);
gaia::AgentConfig cfg = settings.cfg;
cfg.silentMode = true;
gaia::GaiaAgent agent(cfg, agentOptions(cli, settings));
pinConfig(agent, cfg);
agent.setOutputHandler(std::make_unique<gaia::CleanConsole>());
// No person at the keyboard: the client that started the server owns safety.
agent.setToolConfirmCallback([](const std::string&, const gaia::json&) {
return gaia::ToolConfirmResult::ALLOW_ONCE;
});
if (!settings.mcpConfig.empty()) connectMcp(agent, settings.mcpConfig);
gaia::ServerOptions opts;
opts.host = cli.host;
opts.port = cli.port;
opts.allowedOrigins = cli.allowedOrigins;
opts.exposeToolRoutes = cli.exposeToolRoutes;
opts.agentVersion = GAIACPP_VERSION;
if (!cli.serveKeyEnv.empty()) {
opts.apiKey = gaia::getEnvVar(cli.serveKeyEnv.c_str());
if (opts.apiKey.empty()) {
usageError("--server-key-env names " + cli.serveKeyEnv + ", which is not set");
}
}
// No session store: each request carries its conversation, and the REPL's
// saved chats must not be readable or deletable over HTTP.
gaia::ApiServer server(agent, opts);
g_server = &server;
g_agent = &agent;
// One JSON line on stdout once bound, so a supervisor learns the real port.
std::atomic<bool> failed{false};
std::thread announce([&server, &cli, &cfg, &failed] {
for (int i = 0; i < 500 && !server.isRunning() && !failed.load(); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
if (!server.isRunning()) return;
const std::string url = "http://" + cli.host + ":" + std::to_string(server.port());
std::cout << gaia::json{{"event", "ready"}, {"url", url}, {"model", cfg.modelId},
{"version", GAIACPP_VERSION}}.dump()
<< std::endl;
std::cerr << "gaiacpp " GAIACPP_VERSION " serving " << cfg.modelId << " on " << url
<< " (Ctrl+C to stop)\n";
});
try {
server.run();
} catch (...) {
failed.store(true);
announce.join();
throw;
}
announce.join();
g_server = nullptr;
g_agent = nullptr;
return 0;
}
int runInteractive(const Cli& cli) {
const Settings settings = buildSettings(cli);
gaia::GaiaAgent agent(settings.cfg, agentOptions(cli, settings));
pinConfig(agent, settings.cfg);
if (cli.skipPermissions) {
agent.setToolConfirmCallback([](const std::string&, const gaia::json&) {
return gaia::ToolConfirmResult::ALLOW_ONCE;
});
}
if (!settings.mcpConfig.empty()) connectMcp(agent, settings.mcpConfig);
gaia::ReplRunner repl(agent);
repl.setSessionStore(std::make_shared<gaia::SessionStore>());
repl.run();
return 0;
}
} // namespace
// gaiacpp skills list | install <folder>|<name>[@version] [--allow-experimental] | remove <name>
int runSkills(int argc, char** argv) {
const std::string sub = argc > 2 ? argv[2] : "list";
if (sub == "list") {
gaia::SkillLibrary lib;
if (lib.skills().empty()) std::cout << "No skills installed.\n";
for (const auto& [name, s] : lib.skills()) {
std::cout << name << " (" << s.root << ") " << s.description.substr(0, 90) << "\n";
}
for (const auto& f : lib.failures()) std::cerr << "unreadable: " << f << "\n";
for (const auto& s : lib.shadowed()) std::cerr << "shadowed: " << s << "\n";
return 0;
}
if (sub == "install" && argc > 3) {
bool allowExperimental = false;
for (int i = 4; i < argc; ++i) {
if (std::string(argv[i]) == "--allow-experimental") allowExperimental = true;
else usageError(std::string("unknown argument '") + argv[i] + "'");
}
std::string tier;
const std::string what = argv[3];
std::error_code ec;
std::string where;
if (fs::exists(what, ec)) {
where = gaia::SkillLibrary::installFromFolder(what, gaia::SkillLibrary::userRoot(),
allowExperimental, &tier);
} else {
// name or name@version from the skill hub
const size_t at = what.find('@');
where = gaia::SkillLibrary::installFromHub(
what.substr(0, at), at == std::string::npos ? "" : what.substr(at + 1),
gaia::SkillLibrary::userRoot(), allowExperimental, &tier);
}
gaia::SkillLibrary lib;
const std::string name = fs::path(where).filename().string();
std::cout << "Installed " << name << " (" << tier << ") in " << where << "\n";
const auto installed = lib.skills().find(name);
if (installed == lib.skills().end()) {
std::string why;
for (const auto& f : lib.failures()) why += "\n " + f;
throw std::runtime_error("Copied " + name + " to " + where +
", but gaiacpp can't load it from there." +
(why.empty() ? " Run 'gaiacpp skills list' to see why." : why) +
"\nFix its SKILL.md and install again, or run 'gaiacpp skills "
"remove " + name + "'.");
}
if (!installed->second.isInstructionOnly()) {
std::cout << "Note: its Python tools need the Python GAIA runtime; gaiacpp uses its "
"instructions only.\n";
}
return 0;
}
if (sub == "remove" && argc > 3) {
if (!gaia::SkillLibrary::removeInstalled(argv[3])) {
std::cerr << "gaiacpp: no installed skill named " << argv[3] << " in "
<< gaia::SkillLibrary::userRoot() << "\n";
return 1;
}
std::cout << "Removed " << argv[3] << "\n";
return 0;
}
usageError("usage: gaiacpp skills list | install <folder>|<name>[@version] "
"[--allow-experimental] | remove <name>");
}
// gaiacpp models list | pull <name> [--checkpoint C --recipe R] (Lemonade)
int runModels(int argc, char** argv) {
static const char* kUsage =
"usage: gaiacpp models list | pull <name> [--checkpoint C --recipe R] "
"[--base-url URL] [--provider NAME] [--api-key-env VAR] [--config FILE]";
Cli cli;
std::string checkpoint, recipe;
std::vector<std::string> words;
for (int i = 2; i < argc; ++i) {
const std::string a = argv[i];
std::string* target = a == "--checkpoint" ? &checkpoint
: a == "--recipe" ? &recipe
: a == "--base-url" ? &cli.baseUrl
: a == "--provider" ? &cli.provider
: a == "--api-key-env" ? &cli.apiKeyEnv
: a == "--config" ? &cli.configFile
: nullptr;
if (target) {
if (i + 1 >= argc) usageError(a + " needs a value");
*target = argv[++i];
} else if (!a.empty() && a[0] == '-') {
usageError("unknown argument '" + a + "'");
} else {
words.push_back(a);
}
}
const std::string sub = words.empty() ? "list" : words[0];
const bool isList = sub == "list" && words.size() <= 1;
const bool isPull = sub == "pull" && words.size() == 2;
if (!isList && !isPull) usageError(kUsage);
if (isList && (!checkpoint.empty() || !recipe.empty())) {
usageError("--checkpoint and --recipe go with 'models pull'");
}
// Same endpoint and key the agent itself would use.
const Settings settings = buildSettings(cli);
gaia::LemonadeClient client(gaia::LemonadeClientConfig{settings.cfg.baseUrl});
client.setApiKey(gaia::resolveApiKey(settings.cfg));
if (isList) {
const gaia::json models = client.listModels();
for (const auto& m : models.value("data", gaia::json::array())) {
std::cout << m.value("id", "") << "\n";
}
return 0;
}
const std::string& name = words[1];
std::cerr << "Downloading " << name << " through " << client.baseUrl() << " ...\n";
client.pullModel(name, checkpoint, recipe);
std::cout << "Downloaded " << name << "\n";
return 0;
}
int main(int argc, char** argv) {
try {