-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.cpp
More file actions
4104 lines (3751 loc) · 168 KB
/
Copy pathhost.cpp
File metadata and controls
4104 lines (3751 loc) · 168 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
#include "host.hpp"
#include "app_index.hpp"
#include "windows_locations.hpp"
#include "command_runner.hpp"
#include "reliability/command_guards.hpp"
#include "reliability/path_guards.hpp"
#include "classify/turn_decision.hpp"
#include "classify/response_templates.hpp"
#include "settings_store.hpp"
#include "tools/sync_http_client.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <sstream>
#include <thread>
#include <utility>
namespace droidcli::cli {
namespace {
// The path/content and destructive-command guards used throughout this file
// now live in src/reliability/ (portable core, unit-tested in tests/ - see
// path_guards_test.cpp/command_guards_test.cpp) rather than as local copies
// here, so a future edit can't silently regress one of them without a test
// failing.
using namespace droidcli::reliability;
// Lowercases and strips everything but letters/digits, so "Note Pad",
// "note-pad", and "NOTEPAD" all normalize to the same "notepad" key - name
// matching should be resilient to case and to spacing/punctuation variants a
// user (or a model paraphrasing the user) might type, not just case.
core::String normalize_for_match(const core::String& value)
{
core::String result;
result.reserve(value.size());
for (const unsigned char c : value)
{
if (std::isalnum(c))
{
result += static_cast<char>(std::tolower(c));
}
}
return result;
}
// A failed call to one of these has enough information in its own error
// (a bad path, a bad argument) that a fresh classification, told the real
// failure_reason, has a real shot at correcting it - see
// DroidHost::finish_turn_after_execution's one bounded auto-retry.
bool is_retriable_tool(const core::String& tool_name)
{
static const char* const kRetriableTools[] = {
"run_command", "run_ffmpeg",
"read_file", "write_file", "copy_file", "move_path", "delete_file", "create_directory",
"open_application"
};
for (const char* retriable_tool : kRetriableTools)
{
if (tool_name == retriable_tool)
{
return true;
}
}
return false;
}
// Best-effort match of `query` against the installed-apps index, insensitive
// to case and to spacing/punctuation: exact normalized match first, then a
// substring match either direction (so "chrome" matches "Google Chrome",
// "kicad" matches "KiCad 8.0", and "note pad" / "NotePad" both match
// "Notepad"). Returns an empty path if nothing plausible is found.
core::String find_installed_app_match(const core::Array<InstalledApp>& apps, const core::String& query)
{
if (query.empty())
{
return {};
}
const core::String normalized_query = normalize_for_match(query);
if (normalized_query.empty())
{
return {};
}
for (const InstalledApp& app : apps)
{
if (normalize_for_match(app.name) == normalized_query)
{
return app.path;
}
}
for (const InstalledApp& app : apps)
{
const core::String normalized_name = normalize_for_match(app.name);
if (normalized_name.find(normalized_query) != core::String::npos
|| normalized_query.find(normalized_name) != core::String::npos)
{
return app.path;
}
}
return {};
}
// Same matching rule as find_installed_app_match, but returns every
// plausible match (capped at max_results) instead of just the first - the
// deterministic quick-open flow needs to know whether a query is ambiguous
// (more than one installed app could be meant), which a single best-match
// path can't tell it.
core::Array<InstalledApp> collect_installed_app_matches(
const core::Array<InstalledApp>& apps, const core::String& query, size_t max_results)
{
core::Array<InstalledApp> matches;
const core::String normalized_query = normalize_for_match(query);
if (normalized_query.empty())
{
return matches;
}
for (const InstalledApp& app : apps)
{
if (normalize_for_match(app.name) == normalized_query)
{
// An exact normalized-name match is unambiguous regardless of
// how many substring matches also exist - return it alone.
matches.clear();
matches.push_back(app);
return matches;
}
}
for (const InstalledApp& app : apps)
{
const core::String normalized_name = normalize_for_match(app.name);
if (normalized_name.find(normalized_query) != core::String::npos
|| normalized_query.find(normalized_name) != core::String::npos)
{
matches.push_back(app);
if (matches.size() >= max_results)
{
break;
}
}
}
return matches;
}
// A real transcript showed "Sound Settings" (and, separately, "Recycle
// Bin") fail to open: neither is an installed application - neither has an
// Add/Remove Programs entry nor a discoverable .exe by that name, so
// find_installed_app_match/collect_installed_app_matches above will never
// find them, and a literal CreateProcess("Sound Settings") or
// CreateProcess("Recycle Bin") can never succeed no matter how it's spelled.
// Real Windows locations - known folders, Administrative Tools shortcuts,
// plus a small hardcoded exception list for the two categories with no
// discoverable API (see windows_locations.hpp for the full breakdown) -
// checked only after the installed-apps index comes up empty, so a real
// installed app of the same name (e.g. a third-party
// "Sound Recorder") is never shadowed by this data.
struct WellKnownWindowsTarget
{
core::String display_name;
core::String path_or_name;
core::String args;
};
// Splits `value` into lowercase, alnum-only words (any run of non-alnum
// characters is a separator) - unlike normalize_for_match, which collapses
// everything into one run-together token, this preserves word boundaries so
// two phrasings using the same words in a different order ("partition
// disk" vs. an alias written "disk partition") can still be recognized as
// equivalent. See find_known_windows_target's fallback tier below.
core::Array<core::String> split_words_for_match(const core::String& value)
{
core::Array<core::String> words;
core::String current;
for (const unsigned char c : value)
{
if (std::isalnum(c))
{
current += static_cast<char>(std::tolower(c));
}
else if (!current.empty())
{
words.push_back(current);
current.clear();
}
}
if (!current.empty())
{
words.push_back(current);
}
return words;
}
// True if every word in `query_words` appears somewhere in `alias_words` -
// order-independent. Requires at least two words in the query (not one) so
// a single common word ("disk", "settings") can't coincidentally match an
// unrelated alias on its own - every word has to line up, not just one.
bool words_all_present(const core::Array<core::String>& query_words, const core::Array<core::String>& alias_words)
{
if (query_words.size() < 2)
{
return false;
}
for (const core::String& query_word : query_words)
{
bool found = false;
for (const core::String& alias_word : alias_words)
{
if (query_word == alias_word)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
bool find_known_windows_target(
const core::String& query, const core::Array<WindowsLocationEntry>& targets, WellKnownWindowsTarget& out)
{
const core::String normalized_query = normalize_for_match(query);
if (normalized_query.empty())
{
return false;
}
for (const WindowsLocationEntry& target : targets)
{
const core::String normalized_alias = normalize_for_match(target.alias);
if (normalized_alias == normalized_query
|| normalized_alias.find(normalized_query) != core::String::npos
|| normalized_query.find(normalized_alias) != core::String::npos)
{
out.display_name = target.display_name;
out.path_or_name = target.path_or_name;
out.args = target.args;
return true;
}
}
// Fallback: word-order-independent match. A real transcript showed
// "open the partition disk" fail outright - the curated alias is
// "disk partition", and neither phrase is a substring of the other, so
// the exact/substring check above (correctly) never matches reversed
// word order. See "Search before giving up" in ARCHITECTURE.md.
const core::Array<core::String> query_words = split_words_for_match(query);
for (const WindowsLocationEntry& target : targets)
{
const core::Array<core::String> alias_words = split_words_for_match(target.alias);
if (words_all_present(query_words, alias_words))
{
out.display_name = target.display_name;
out.path_or_name = target.path_or_name;
out.args = target.args;
return true;
}
}
return false;
}
// Backs the list_windows_locations agent tool - every distinct display_name
// in `targets` (windows_locations_ - see windows_locations.hpp), deduplicated
// (several entries share one display_name across multiple aliases, e.g. all
// six Task Manager aliases). Gives the model real data to answer "what
// Windows panels/settings can you open" instead of fabricating an answer.
core::String list_well_known_windows_targets_json(const core::Array<WindowsLocationEntry>& targets)
{
core::Array<core::String> seen_names;
std::ostringstream stream;
stream << '{' << net::json_bool_field("ok", true) << ",\"locations\":[";
bool first = true;
for (const WindowsLocationEntry& target : targets)
{
const core::String display_name = target.display_name;
bool duplicate = false;
for (const core::String& existing : seen_names)
{
if (existing == display_name)
{
duplicate = true;
break;
}
}
if (duplicate)
{
continue;
}
seen_names.push_back(display_name);
if (!first)
{
stream << ',';
}
first = false;
stream << '"' << net::escape_json_string(display_name) << '"';
}
stream << "]}";
return stream.str();
}
core::Array<core::String> parse_ollama_model_names(const core::String& tags_json)
{
core::Array<core::String> names;
const size_t models_index = tags_json.find("\"models\":");
if (models_index == core::String::npos)
{
return names;
}
size_t cursor = models_index;
while (cursor < tags_json.size())
{
const size_t name_key = tags_json.find("\"name\":", cursor);
if (name_key == core::String::npos)
{
break;
}
const core::String name = net::extract_json_string_field(tags_json, "name", name_key);
if (name.empty())
{
break;
}
bool duplicate = false;
for (const core::String& existing : names)
{
if (existing == name)
{
duplicate = true;
break;
}
}
if (!duplicate)
{
names.push_back(name);
}
cursor = name_key + 6;
}
return names;
}
core::String strip_trailing_slashes(core::String value)
{
while (!value.empty() && value.back() == '/')
{
value.pop_back();
}
return value;
}
core::String join_url(const core::String& base, const core::String& path)
{
const core::String trimmed_base = strip_trailing_slashes(base);
if (path.empty())
{
return trimmed_base;
}
return path.front() == '/' ? trimmed_base + path : trimmed_base + "/" + path;
}
// int32_t-scoped field extractor for host-local uses (timeout_ms, max_bytes)
// that never need more than 32 bits. net::extract_json_int_field (added
// alongside Task::scheduled_for_ms) is the int64_t-scoped equivalent for
// fields that can hold an absolute epoch-ms value; kept separate rather than
// widening every call site here to int64_t for no benefit.
bool extract_json_int_field(const core::String& json, const core::String& field_name, int32_t& out_value)
{
const core::String needle = "\"" + field_name + "\":";
const size_t field_index = json.find(needle);
if (field_index == core::String::npos)
{
return false;
}
size_t cursor = field_index + needle.size();
while (cursor < json.size() && (json[cursor] == ' ' || json[cursor] == '\t'))
{
++cursor;
}
const size_t start = cursor;
if (cursor < json.size() && json[cursor] == '-')
{
++cursor;
}
while (cursor < json.size() && std::isdigit(static_cast<unsigned char>(json[cursor])))
{
++cursor;
}
if (cursor == start)
{
return false;
}
out_value = std::atoi(json.substr(start, cursor - start).c_str());
return true;
}
// Replaces the value of an existing top-level "field_name":"..." string
// field in `json` with `new_value`, re-escaped - returns `json` unchanged if
// the field isn't present or isn't a plain string value. Used to show a
// resolved full path in an approval prompt without touching any other part
// of the arguments JSON; see "Full paths in the approval prompt" in
// ARCHITECTURE.md.
core::String replace_json_string_field_value(const core::String& json, const core::String& field_name, const core::String& new_value)
{
const core::String needle = "\"" + field_name + "\":";
const size_t field_index = json.find(needle);
if (field_index == core::String::npos)
{
return json;
}
size_t cursor = field_index + needle.size();
while (cursor < json.size() && (json[cursor] == ' ' || json[cursor] == '\t'))
{
++cursor;
}
if (cursor >= json.size() || json[cursor] != '"')
{
return json;
}
const size_t value_start = cursor;
++cursor;
while (cursor < json.size())
{
if (json[cursor] == '\\' && cursor + 1 < json.size())
{
cursor += 2;
continue;
}
if (json[cursor] == '"')
{
++cursor;
break;
}
++cursor;
}
const size_t value_end = cursor;
return json.substr(0, value_start) + "\"" + net::escape_json_string(new_value) + "\"" + json.substr(value_end);
}
// Whether the agent-turn loop must pause and get the user's explicit
// approval before executing this tool, rather than auto-running it. Only
// side-effecting tools are gated - anything read-only (list_dir, get_cwd,
// get_system_info, which, list_connectors, list_tasks, list_open_windows,
// find_application, connector_status, read_file, stat_path, call_connector,
// read_clipboard) keeps auto-running, since gating those would only make
// the agent slower to answer plain questions for no safety benefit.
bool tool_call_requires_approval(const core::String& tool_name)
{
return tool_name == "run_command"
|| tool_name == "run_ffmpeg"
|| tool_name == "write_file"
|| tool_name == "open_application"
|| tool_name == "launch_connector"
|| tool_name == "stop_connector"
|| tool_name == "enqueue_task"
|| tool_name == "cancel_task"
|| tool_name == "copy_file"
|| tool_name == "move_path"
|| tool_name == "delete_file"
|| tool_name == "create_directory"
|| tool_name == "write_clipboard";
}
// Returns the last up to `max_lines` non-empty, \r-trimmed lines of `text`,
// joined by " | " - used to surface the actual diagnostic buried at the end
// of a verbose command's output. ffmpeg is the main offender: its real error
// always lands in the last line or two, after a wall of build-config and
// stream-probe banner noise the model has no reason to read through to find
// it (a real case: "Invalid size 'h'" - the actual problem - was buried
// under ~2KB of ffmpeg's own version/config preamble).
core::String last_nonempty_lines(const core::String& text, const size_t max_lines)
{
core::Array<core::String> lines;
size_t start = 0;
while (start <= text.size())
{
const size_t newline = text.find('\n', start);
core::String line = text.substr(start, newline == core::String::npos ? core::String::npos : newline - start);
while (!line.empty() && (line.back() == '\r' || line.back() == ' '))
{
line.pop_back();
}
if (!line.empty())
{
lines.push_back(line);
}
if (newline == core::String::npos)
{
break;
}
start = newline + 1;
}
const size_t take = lines.size() < max_lines ? lines.size() : max_lines;
core::String joined;
for (size_t index = lines.size() - take; index < lines.size(); ++index)
{
if (!joined.empty())
{
joined += " | ";
}
joined += lines[index];
}
return joined;
}
// A short, unambiguous explanation of why a command_succeeded()==false
// CommandRunResult failed - prefers error_message (spawn failure, timeout),
// then stderr's tail (where a well-behaved program puts errors), then
// stdout's tail (ffmpeg, notably, writes everything - including its actual
// error - there in this codebase's capture).
core::String summarize_command_failure(const CommandRunResult& result)
{
if (!result.error_message.empty())
{
return result.error_message;
}
const core::String stderr_tail = last_nonempty_lines(result.stderr_text, 3);
if (!stderr_tail.empty())
{
return stderr_tail;
}
return last_nonempty_lines(result.stdout_text, 3);
}
} // namespace
void DroidHost::configure(const HostConfig& config)
{
std::lock_guard<std::mutex> lock(mutex_);
config_ = config;
}
void DroidHost::initialize()
{
{
std::lock_guard<std::mutex> lock(mutex_);
droidcli::initialize_defaults();
// Queried once, up front, so every route/tool/log line that reports
// "where droidcli is running" (build_system_info_json, the
// get_system_info agent tool, the system prompt below) agrees with
// each other instead of re-querying the OS independently.
system_info_ = get_system_info();
// Hardware inventory only runs if the human opted in at startup
// (--enable-hardware-scan) - see HostConfig::enable_hardware_scan.
// Left default-constructed (empty) otherwise; build_hardware_info_json
// reports that honestly rather than presenting zeroed fields as data.
if (config_.enable_hardware_scan)
{
hardware_info_ = scan_hardware_info();
}
// Durable session log: logs/log.jsonl accumulates across restarts so
// a crash or a bug report can be diagnosed after the fact, not just
// while the process happens to still be up. Structured JSONL (one
// JSON object per line, see append_app_log()), not the bracketed
// plain-text format the console gets. Created relative to the
// working directory droidcli was launched from - if that directory
// isn't writable, log_file_ just stays closed and append_app_log()
// silently skips the file write (console/in-memory logging still
// works either way).
std::error_code log_dir_error;
std::filesystem::create_directories("logs", log_dir_error);
log_file_.open("logs/log.jsonl", std::ios::app);
if (log_file_)
{
log_file_ << "{" << net::json_string_field("event", "session_started") << ","
<< net::json_string_field("ts", make_full_log_timestamp()) << "}" << std::endl;
log_file_ << "{" << net::json_string_field("event", "system_detected") << ","
<< net::json_string_field("os_name", system_info_.os_name) << ","
<< net::json_string_field("os_version", system_info_.os_version) << ","
<< net::json_string_field("architecture", system_info_.architecture) << ","
<< net::json_string_field("hostname", system_info_.hostname) << ","
<< net::json_string_field("cwd", system_info_.cwd) << ","
<< net::json_string_field("ts", make_full_log_timestamp()) << "}" << std::endl;
}
session_.active = true;
session_.map_name = "droidcli";
session_.build_label = "daemon";
session_.http_enabled = true;
session_.http_router_bound = true;
session_.features.networking = true;
session_.features.ui = false;
session_.features.ai = config_.enable_ai;
session_.features.recording = true;
language_ai_transport_.post_json = [](
const core::String& url,
const core::String& body,
const core::Array<core::String>& headers,
int32_t& status_code_out,
core::String& response_body_out)
{
return tools::sync_http_post_json(url, body, status_code_out, response_body_out, headers);
};
if (config_.enable_ai)
{
language_ai_.set_runtime_enabled(true);
ai::OpenAICompatConfig ollama_config;
ollama_config.base_url = config_.ollama_url;
ollama_config.model = config_.ollama_model;
ollama_config.enabled = true;
ollama_config.num_ctx = config_.ollama_num_ctx;
language_ai_.set_ollama_config(ollama_config);
if (!config_.system_prompt.empty())
{
// Appended rather than baked into HostConfig::system_prompt's
// static default text, since system_info_ is only known once
// initialize() actually queries the OS.
const core::String prompt_with_system_info = config_.system_prompt
+ " You are currently running on " + system_info_.os_name
+ " " + system_info_.os_version + " (" + system_info_.architecture
+ "), hostname " + system_info_.hostname
+ ", working directory " + system_info_.cwd
+ (system_info_.desktop_path.empty()
? core::String()
: ", the user's Desktop folder is at " + system_info_.desktop_path
+ " - use this exact path when a request mentions \"the Desktop\", "
"never guess a \"C:\\Users\\<name>\\Desktop\"-style path yourself")
+ " - call get_system_info if you need these details again mid-conversation.";
language_ai_.set_system_prompt(prompt_with_system_info);
}
}
else
{
language_ai_.set_runtime_enabled(false);
}
// Scan once at startup, not per-lookup: this walks potentially
// hundreds of registry keys (Windows Uninstall/Add-Remove-Programs
// entries) and touches disk to resolve some paths. Lets
// open_application()/find_application resolve names like "Blender"
// or "KiCad" that installers never add to PATH or the App Paths
// registry key - most installers only ever register an Add/Remove
// Programs entry.
installed_apps_ = scan_installed_applications();
// Real, discoverable Windows locations (known folders, Administrative
// Tools shortcuts) plus the small hardcoded exception list for the
// two categories with no discoverable API - see windows_locations.hpp.
// Same scan-once-at-startup lifecycle as installed_apps_ above.
windows_locations_ = scan_windows_locations();
// Persistent agent-turn memory (see "Persistent memory" in
// ARCHITECTURE.md's extension plan) - a fresh session id every
// process start (no auto-resume; a caller opts in by passing a
// prior session_id explicitly, see agent_turn()). A failed open()
// (bad working directory, disk full) leaves memory_store_ closed;
// record_agent_message()/history routes degrade to in-memory-only
// behavior rather than crashing the daemon over it.
current_session_id_ = generate_session_id();
std::error_code db_dir_error;
std::filesystem::create_directories("db", db_dir_error);
if (!memory_store_.open("db/droidcli_memory.sqlite3"))
{
append_app_log("host", "event", "warning: could not open db/droidcli_memory.sqlite3 - agent history will not persist across restarts", false);
}
}
append_app_log("host", "event",
"droidcli host initialized (" + std::to_string(installed_apps_.size()) + " installed apps indexed"
+ (config_.enable_hardware_scan ? ", hardware scan enabled" : ", hardware scan disabled") + ")",
true);
}
void DroidHost::tick(const float delta_seconds)
{
(void)delta_seconds;
tick_watchdog();
tick_tasks();
}
session::RuntimeSession& DroidHost::session()
{
return session_;
}
const session::RuntimeSession& DroidHost::session() const
{
return session_;
}
net::HandlerContext DroidHost::make_handler_context()
{
net::HandlerContext context;
context.session = session_;
if (config_.enable_ai)
{
context.language_ai = &language_ai_;
context.language_ai_transport = &language_ai_transport_;
}
return context;
}
net::RouteDispatchResult DroidHost::dispatch_route(const net::HttpRequest& request)
{
std::lock_guard<std::mutex> lock(mutex_);
net::RouteDispatchResult result = routes_.dispatch(request, make_handler_context());
if (result.notify.has_notify_message)
{
on_notify(result.notify.notify_message.text);
}
return result;
}
void DroidHost::on_notify(const core::String& message)
{
notify_log_.push_back(message);
if (notify_log_.size() > 64)
{
notify_log_.erase(notify_log_.begin());
}
std::cout << "[notify] " << message << std::endl;
}
core::String DroidHost::build_notify_log_json() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::ostringstream stream;
stream << "{\"entries\":[";
for (size_t index = 0; index < notify_log_.size(); ++index)
{
if (index > 0)
{
stream << ',';
}
stream << '{';
stream << net::json_string_field("message", notify_log_[index]);
stream << '}';
}
stream << "]}";
return stream.str();
}
core::String DroidHost::build_status_json() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::ostringstream stream;
stream << '{';
stream << net::json_string_field("host", "droidcli") << ',';
stream << net::json_string_field("map", session_.map_name) << ',';
stream << net::json_string_field("build", session_.build_label) << ',';
stream << net::json_bool_field("active", session_.active) << ',';
stream << net::json_bool_field("ai_enabled", config_.enable_ai) << ',';
stream << "\"connector_count\":" << connectors_.list_connectors().size() << ',';
stream << "\"task_count\":" << tasks_.list().size();
stream << '}';
return stream.str();
}
core::String DroidHost::build_config_json() const
{
std::lock_guard<std::mutex> lock(mutex_);
std::ostringstream stream;
stream << '{';
stream << net::json_bool_field("ai_enabled", config_.enable_ai) << ',';
stream << net::json_string_field("ollama_url", config_.ollama_url) << ',';
stream << net::json_string_field("ollama_model", config_.ollama_model);
stream << '}';
return stream.str();
}
core::String DroidHost::active_model_name() const
{
std::lock_guard<std::mutex> lock(mutex_);
return config_.ollama_model;
}
core::String DroidHost::update_config(const core::String& body)
{
std::lock_guard<std::mutex> lock(mutex_);
const core::String ollama_url = net::extract_json_string_field(body, "ollama_url");
if (!ollama_url.empty())
{
config_.ollama_url = ollama_url;
}
const core::String ollama_model = net::extract_json_string_field(body, "ollama_model");
if (!ollama_model.empty())
{
config_.ollama_model = ollama_model;
}
if (config_.enable_ai)
{
ai::OpenAICompatConfig ollama_config;
ollama_config.base_url = config_.ollama_url;
ollama_config.model = config_.ollama_model;
ollama_config.enabled = true;
ollama_config.num_ctx = config_.ollama_num_ctx;
language_ai_.set_ollama_config(ollama_config);
}
persist_current_settings_locked();
std::ostringstream stream;
stream << '{';
stream << net::json_bool_field("success", true) << ',';
stream << net::json_bool_field("ai_enabled", config_.enable_ai) << ',';
stream << net::json_string_field("ollama_url", config_.ollama_url) << ',';
stream << net::json_string_field("ollama_model", config_.ollama_model);
stream << '}';
return stream.str();
}
void DroidHost::append_app_log(
const core::String& channel,
const core::String& direction,
const core::String& summary,
const bool success,
const core::String& session_id,
const core::String& extra_json_fields)
{
std::lock_guard<std::mutex> lock(mutex_);
AppLogEntry entry;
entry.timestamp = make_log_timestamp();
entry.channel = channel;
entry.direction = direction;
entry.summary = summary;
entry.success = success;
app_log_.push_back(entry);
if (app_log_.size() > 256)
{
app_log_.erase(app_log_.begin());
}
// Console/stderr output stays a human-readable line - this is for a
// person watching the terminal, not for durable structured storage.
const core::String line = "[" + entry.timestamp + "] ["
+ entry.channel + "] [" + entry.direction + "] " + entry.summary;
if (success)
{
std::cout << line << std::endl;
}
else
{
std::cerr << line << std::endl;
}
// Durable file log (logs/log.jsonl) is structured JSONL - one JSON
// object per line, no bracketed-text formatting - so any tool can parse
// it without re-deriving the console format's escaping rules. See
// "Structured JSONL logging" in ARCHITECTURE.md's extension plan.
if (log_file_)
{
core::String json_line = "{"
+ net::json_string_field("ts", make_full_log_timestamp()) + ","
+ net::json_string_field("channel", channel) + ","
+ net::json_string_field("direction", direction) + ","
+ net::json_string_field("summary", summary) + ","
+ net::json_bool_field("success", success);
if (!session_id.empty())
{
json_line += "," + net::json_string_field("session_id", session_id);
}
if (!extra_json_fields.empty())
{
json_line += "," + extra_json_fields;
}
json_line += "}";
log_file_ << json_line << std::endl;
}
}
core::String DroidHost::make_log_timestamp()
{
std::time_t raw_time = std::time(nullptr);
std::tm local_time {};
#if defined(_WIN32)
localtime_s(&local_time, &raw_time);
#else
localtime_r(&raw_time, &local_time);
#endif
char buffer[32] {};
std::strftime(buffer, sizeof(buffer), "%H:%M:%S", &local_time);
return buffer;
}
core::String DroidHost::make_full_log_timestamp()
{
std::time_t raw_time = std::time(nullptr);
std::tm local_time {};
#if defined(_WIN32)
localtime_s(&local_time, &raw_time);
#else
localtime_r(&raw_time, &local_time);
#endif
char buffer[32] {};
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &local_time);
return buffer;
}
core::String DroidHost::generate_session_id()
{
std::time_t raw_time = std::time(nullptr);
std::tm local_time {};
#if defined(_WIN32)
localtime_s(&local_time, &raw_time);
#else
localtime_r(&raw_time, &local_time);
#endif
char buffer[32] {};
std::strftime(buffer, sizeof(buffer), "%Y%m%dT%H%M%S", &local_time);
// A timestamp alone can collide if two sessions start within the same
// second (e.g. --no-ai smoke tests launched back to back); a few bits
// of the address of a stack-local disambiguate without pulling in a
// UUID/random dependency for something that only needs to be
// locally-unique, not globally-unique or unpredictable.
int disambiguator = 0;
const auto address_bits = reinterpret_cast<std::uintptr_t>(&disambiguator);
std::ostringstream stream;
stream << buffer << "-" << std::hex << (address_bits & 0xffff);
return stream.str();
}
bool DroidHost::should_emit_periodic_log(
const std::time_t now_utc,
std::time_t& last_emit_utc,
const int32_t min_interval_seconds)
{
if (now_utc <= 0)
{
return true;
}
if (last_emit_utc == 0 || (now_utc - last_emit_utc) >= min_interval_seconds)
{
last_emit_utc = now_utc;
return true;
}
return false;
}
void DroidHost::tick_watchdog()
{
if (!config_.enable_ai)
{
// --no-ai means there's nothing to watch - don't manufacture
// "Ollama unreachable" noise for a backend the operator deliberately
// turned off.
return;
}
const std::time_t now_utc = std::time(nullptr);
std::time_t last_check = watchdog_last_check_utc_;
if (!should_emit_periodic_log(now_utc, last_check, kWatchdogIntervalSeconds))
{
return;
}
watchdog_last_check_utc_ = last_check;
core::String ollama_url_copy;
{
std::lock_guard<std::mutex> lock(mutex_);
ollama_url_copy = config_.ollama_url;
}
const core::String tags_url = strip_trailing_slashes(ollama_url_copy) + "/api/tags";
int32_t status_code = 0;
core::String response_body;
const bool transport_ok = tools::sync_http_get(tags_url, status_code, response_body);
const bool reachable = transport_ok && status_code >= 200 && status_code < 300;
using namespace std::chrono;
const int64_t checked_at_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
bool was_reachable = true;
{
std::lock_guard<std::mutex> lock(mutex_);
was_reachable = ollama_reachable_;
ollama_reachable_ = reachable;