-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsession_registry.cpp
More file actions
2208 lines (2041 loc) · 85 KB
/
Copy pathsession_registry.cpp
File metadata and controls
2208 lines (2041 loc) · 85 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 "session_registry.hpp"
#include "compact_checkpoint.hpp"
#include "session_rewind.hpp"
#include "session_resume_restore.hpp"
#include "session_storage.hpp"
#include "session_auto_title.hpp"
#include "thread_goal_store.hpp"
#include "tool_result_storage.hpp"
#include "turn_timing.hpp"
#include "../commands/init_command.hpp"
#include "../commands/lsp_command.hpp"
#include "../provider/apply_model_to_session.hpp"
#include "../provider/cwd_model_override.hpp"
#include "../provider/model_context_resolver.hpp"
#include "../provider/model_pool_status.hpp"
#include "../provider/model_resolver.hpp"
#include "../config/saved_models_revision.hpp"
#include "../skills/skill_init.hpp"
#include "../gitinfo/git_context_core.hpp"
#include "../tool/mcp_manager.hpp"
#include "../tool/question_policy.hpp"
#include "../worktree/worktree_core.hpp"
#include "../worktree/worktree_manager.hpp"
#include "../utils/logger.hpp"
#include "../utils/cwd_hash.hpp"
#include "../utils/power_inhibitor.hpp"
#include "../utils/utf8_path.hpp"
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <system_error>
#include <thread>
#include <unordered_set>
#include <utility>
namespace acecode {
namespace {
std::string session_dir_name_from_id(const std::string& session_id) {
std::string out;
out.reserve(session_id.size());
for (unsigned char ch : session_id) {
if (std::isalnum(ch) || ch == '-' || ch == '_') {
out.push_back(static_cast<char>(ch));
} else {
out.push_back('_');
}
}
return out.empty() ? "session" : out;
}
bool is_llm_role(const std::string& role) {
return role == "user" || role == "assistant" ||
role == "system" || role == "tool";
}
std::string trim_copy(const std::string& value) {
std::size_t first = 0;
while (first < value.size() &&
std::isspace(static_cast<unsigned char>(value[first])) != 0) {
++first;
}
std::size_t last = value.size();
while (last > first &&
std::isspace(static_cast<unsigned char>(value[last - 1])) != 0) {
--last;
}
return value.substr(first, last - first);
}
ToolCapabilityPolicy tool_policy_from_expert_scopes(
const ExpertCapabilityScopes& scopes,
const AppConfig* config) {
ToolCapabilityPolicy policy;
if (scopes.tools) {
policy.builtin_tools = std::unordered_set<std::string>(
scopes.tools->begin(), scopes.tools->end());
}
if (scopes.mcp_servers) {
policy.mcp_servers = std::unordered_set<std::string>(
scopes.mcp_servers->begin(), scopes.mcp_servers->end());
} else if (config) {
// A shared MCP runtime may contain servers started for another
// expert. Inheriting sessions only see daemon-global enabled servers.
std::unordered_set<std::string> globally_enabled;
for (const auto& [name, server] : config->mcp_servers) {
if (!server.disabled) globally_enabled.insert(name);
}
policy.mcp_servers = std::move(globally_enabled);
}
return policy;
}
void ensure_expert_mcp_servers_available(
const ExpertCapabilityScopes& scopes,
McpManager* manager,
ToolExecutor* tools) {
if (!scopes.mcp_servers || !manager || !tools) return;
for (const auto& name : *scopes.mcp_servers) {
if (!manager->has_server(name)) continue;
// enable() is idempotent for Connected/Starting entries and does not
// mutate AppConfig, so the global default remains disabled.
(void)manager->enable(name, *tools);
}
}
ExpertCapabilityScopes fail_closed_expert_scopes() {
ExpertCapabilityScopes scopes;
scopes.skills = std::vector<std::string>{};
scopes.mcp_servers = std::vector<std::string>{};
scopes.tools = std::vector<std::string>{};
return scopes;
}
bool is_transcript_only_message(const ChatMessage& msg) {
return msg.metadata.is_object() &&
msg.metadata.value("transcript_only", false);
}
std::optional<std::pair<std::size_t, CompactCheckpoint>>
latest_valid_compact_checkpoint(const std::vector<ChatMessage>& messages) {
for (std::size_t i = messages.size(); i > 0; --i) {
auto checkpoint = decode_compact_checkpoint(messages[i - 1]);
if (checkpoint.has_value()) {
return std::make_pair(i - 1, std::move(*checkpoint));
}
}
return std::nullopt;
}
void append_model_messages_to_loop(AgentLoop& loop,
const std::vector<ChatMessage>& messages) {
for (std::size_t i = 0; i < messages.size(); ++i) {
const auto& msg = messages[i];
if (is_file_checkpoint_message(msg)) continue;
if (is_content_replacement_message(msg)) continue;
if (is_turn_timing_message(msg)) continue;
if (is_compact_checkpoint_message(msg)) continue;
const bool is_shell_user =
(msg.role == "user" && !msg.content.empty() && msg.content[0] == '!');
const bool next_is_result =
(i + 1 < messages.size() && messages[i + 1].role == "tool_result");
if (is_shell_user && next_is_result) {
loop.inject_shell_turn(msg.content.substr(1),
messages[i + 1].content,
"",
0);
++i;
continue;
}
if (is_llm_role(msg.role) && !is_transcript_only_message(msg)) {
loop.push_message(msg);
}
}
}
std::pair<std::string, std::string>
current_provider_model(const SessionRegistryDeps& deps,
const std::string& fallback_model) {
(void)fallback_model;
if (deps.provider_accessor) {
auto provider = deps.provider_accessor();
if (provider) {
return {provider->name(), provider->model()};
}
}
return {"", ""};
}
const ModelProfile* find_profile_by_name(const AppConfig& cfg,
const std::string& name) {
if (name.empty()) return nullptr;
for (const auto& entry : cfg.saved_models) {
if (entry.name == name) return &entry;
}
return nullptr;
}
std::optional<ModelProfile> explicit_profile(const AppConfig& cfg,
const std::string& name) {
if (name.empty()) return std::nullopt;
if (const auto* entry = find_profile_by_name(cfg, name)) {
ModelProfile profile = *entry;
if (profile.provider == "openai" && !profile.stream_timeout_ms.has_value()) {
profile.stream_timeout_ms = cfg.openai.stream_timeout_ms;
}
return profile;
}
return std::nullopt;
}
SessionModelState state_from_profile(const AppConfig& cfg,
const ModelProfile& profile) {
return session_model_state_from_profile(cfg, profile);
}
SessionModelState deleted_state_from_name(const std::string& name) {
SessionModelState state;
state.name = name;
state.deleted = true;
return state;
}
void mark_deleted_if_model_name_missing(const AppConfig& cfg, SessionModelState& state) {
if (state.name.empty() || state.name.rfind("(session:", 0) == 0) return;
if (find_profile_by_name(cfg, state.name) != nullptr) return;
state.provider.clear();
state.model.clear();
state.context_window = 0;
state.deleted = true;
}
struct ResolvedSessionModel {
SessionModelState state;
std::optional<ModelProfile> profile;
std::shared_ptr<const AppConfig> config;
std::shared_ptr<LlmProvider> runtime_provider;
SavedModelsRevision revision = 0;
};
struct ModelConfigSnapshot {
std::shared_ptr<const AppConfig> config;
SavedModelsRevision revision = 0;
};
ModelConfigSnapshot snapshot_model_config(const SessionRegistryDeps& deps) {
if (!deps.config) return {};
if (deps.config_mutex) {
std::shared_lock<std::shared_mutex> lock(*deps.config_mutex);
return {
std::make_shared<AppConfig>(*deps.config),
current_saved_models_revision(),
};
}
return {
std::make_shared<AppConfig>(*deps.config),
current_saved_models_revision(),
};
}
SessionModelResolvedTarget resolve_target_for_name(
const SessionRegistryDeps& deps,
const std::string& name) {
auto snapshot = snapshot_model_config(deps);
SessionModelResolvedTarget target;
target.revision = snapshot.revision;
target.config = snapshot.config;
if (!snapshot.config) return target;
const auto found = std::find_if(
snapshot.config->saved_models.begin(),
snapshot.config->saved_models.end(),
[&name](const ModelProfile& candidate) {
return candidate.name == name;
});
if (found != snapshot.config->saved_models.end()) {
target.profile = *found;
target.state = session_model_state_from_profile(*snapshot.config, *found);
}
return target;
}
ResolvedSessionModel resolve_from_profile(
std::shared_ptr<const AppConfig> config,
SavedModelsRevision revision,
const ModelProfile& profile) {
ResolvedSessionModel resolved;
resolved.state = state_from_profile(*config, profile);
resolved.profile = profile;
resolved.config = std::move(config);
resolved.revision = revision;
LOG_INFO("[registry] resolve_from_profile name='" + profile.name +
"' provider='" + profile.provider + "' model='" + profile.model + "'");
return resolved;
}
ResolvedSessionModel resolve_session_model(const SessionRegistryDeps& deps,
const SessionOptions& opts,
const SessionMeta* resumed_meta) {
auto snapshot = snapshot_model_config(deps);
if (snapshot.config) {
const AppConfig& config = *snapshot.config;
ModelProfile profile;
std::optional<std::string> cwd_override;
if (!opts.cwd.empty()) {
cwd_override = load_cwd_model_override(opts.cwd);
}
if (!opts.model_name.empty()) {
auto explicit_match = explicit_profile(config, opts.model_name);
if (explicit_match.has_value()) {
profile = *explicit_match;
} else {
LOG_WARN("[registry] requested model preset '" + opts.model_name +
"' not found; falling back to default saved model");
profile = resolve_effective_model(config, std::nullopt, std::nullopt);
}
} else if (resumed_meta) {
if (!resumed_meta->model_preset.empty() &&
find_profile_by_name(config, resumed_meta->model_preset) == nullptr) {
LOG_WARN("[registry] session model preset '" + resumed_meta->model_preset +
"' was deleted from saved_models");
ResolvedSessionModel deleted;
deleted.state = deleted_state_from_name(resumed_meta->model_preset);
deleted.config = snapshot.config;
deleted.revision = snapshot.revision;
return deleted;
}
profile = resolve_effective_model(
config, cwd_override, std::optional<SessionMeta>{*resumed_meta});
} else {
profile = resolve_effective_model(config, cwd_override, std::nullopt);
}
return resolve_from_profile(
std::move(snapshot.config), snapshot.revision, profile);
}
auto [provider, model] = current_provider_model(deps, opts.model_name);
ResolvedSessionModel resolved;
resolved.runtime_provider =
deps.provider_accessor ? deps.provider_accessor() : nullptr;
resolved.state.name = opts.model_name;
resolved.state.provider = provider;
resolved.state.model = model;
resolved.state.context_window = 0;
resolved.revision = current_saved_models_revision();
return resolved;
}
SessionModelTransitionCallback transition_for_entry(
const std::shared_ptr<SessionEntry>& entry) {
return [weak = std::weak_ptr<SessionEntry>(entry)](
const SessionModelState& state,
const SessionModelTransition& transition) {
auto active = weak.lock();
if (!active) return true;
if (active->loop && state.context_window > 0) {
active->loop->set_context_window(state.context_window);
}
if (!active->sm || (!transition.provider_published &&
!transition.selection_changed)) {
return true;
}
try {
return active->sm->set_active_provider(
state.provider, state.model, state.name);
} catch (...) {
LOG_WARN("[session_model_binding] session metadata persistence failed");
return false;
}
};
}
SessionOptions with_resolved_workspace(const SessionRegistryDeps& deps,
const SessionOptions& in,
const std::string& session_id = {}) {
SessionOptions out = in;
if (out.no_workspace) {
if (out.cwd.empty()) {
out.cwd = no_workspace_session_cwd(session_id, deps.no_workspace_cache_root);
}
out.workspace_hash.clear();
return out;
}
if (out.cwd.empty()) {
out.cwd = deps.cwd;
}
if (out.workspace_hash.empty() && !out.cwd.empty()) {
out.workspace_hash = compute_cwd_hash(out.cwd);
}
return out;
}
std::string trim_ascii(std::string s) {
auto is_space = [](unsigned char c) { return std::isspace(c) != 0; };
while (!s.empty() && is_space(static_cast<unsigned char>(s.front()))) s.erase(s.begin());
while (!s.empty() && is_space(static_cast<unsigned char>(s.back()))) s.pop_back();
return s;
}
std::string lower_ascii(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
}
bool parse_goal_budget_value(const std::string& text, std::int64_t* out) {
if (!out || text.empty()) return false;
std::string s = lower_ascii(text);
std::int64_t multiplier = 1;
if (!s.empty() && (s.back() == 'k' || s.back() == 'm')) {
multiplier = s.back() == 'k' ? 1000 : 1000000;
s.pop_back();
}
if (s.empty()) return false;
std::int64_t value = 0;
for (char c : s) {
if (!std::isdigit(static_cast<unsigned char>(c))) return false;
value = value * 10 + (c - '0');
}
*out = value * multiplier;
return *out > 0;
}
PermissionMode permission_mode_from_name(std::string mode) {
if (mode == "acceptEdits") mode = "accept-edits";
if (mode == "accept-edits") return PermissionMode::AcceptEdits;
if (mode == "yolo") return PermissionMode::Yolo;
if (mode == "plan") return PermissionMode::Plan;
return PermissionMode::Default;
}
void emit_session_title_updated(SessionEntry& entry) {
if (!entry.loop || !entry.sm) return;
entry.loop->events().emit(SessionEventKind::SessionUpdated, nlohmann::json{
{"session_id", entry.id},
{"workspace_hash", entry.workspace_hash},
{"cwd", entry.cwd},
{"title", entry.sm->current_title()},
{"title_source", entry.sm->current_title_source()},
});
}
struct RegistryGoalArgs {
std::optional<std::int64_t> token_budget;
std::string remainder;
std::string error;
};
RegistryGoalArgs parse_registry_goal_args(std::string args) {
RegistryGoalArgs parsed;
args = trim_ascii(std::move(args));
if (args.rfind("--tokens", 0) != 0) {
parsed.remainder = args;
return parsed;
}
std::string rest = trim_ascii(args.substr(std::string("--tokens").size()));
const auto split = rest.find_first_of(" \t\r\n");
const std::string budget_text = split == std::string::npos ? rest : rest.substr(0, split);
std::int64_t budget = 0;
if (!parse_goal_budget_value(budget_text, &budget)) {
parsed.error = "Goal token budget must be a positive integer, optionally suffixed with K or M.";
return parsed;
}
parsed.token_budget = budget;
parsed.remainder = split == std::string::npos ? std::string{} : trim_ascii(rest.substr(split + 1));
return parsed;
}
std::string format_registry_goal_summary(const ThreadGoal& goal) {
std::ostringstream oss;
oss << "Goal:\n"
<< " objective: " << goal.objective << "\n"
<< " status: " << to_string(goal.status) << "\n"
<< " tokens: " << goal.tokens_used;
if (goal.token_budget.has_value()) {
oss << " / " << *goal.token_budget
<< " (" << std::max<std::int64_t>(0, *goal.token_budget - goal.tokens_used)
<< " remaining)";
}
oss << "\n elapsed: " << goal.time_used_seconds << "s";
return oss.str();
}
void emit_goal_audit_message(SessionEntry& entry,
const ThreadGoal& goal,
const std::string& action,
const std::string& label) {
if (!entry.loop) return;
entry.loop->emit_transcript_system_message(
"[Goal] " + label + ": " + goal.objective,
nlohmann::json{
{"goal_audit", true},
{"goal_action", action},
{"goal_id", goal.goal_id},
{"thread_id", goal.thread_id},
});
}
std::optional<ThreadGoal> current_active_goal(SessionEntry& entry) {
if (!entry.sm) return std::nullopt;
const std::string sid = entry.sm->current_session_id();
ThreadGoalStore* store = entry.sm->existing_goal_store();
if (!store || sid.empty()) return std::nullopt;
std::string error;
auto goal = store->get_thread_goal(sid, &error);
if (!error.empty() || !goal.has_value() || goal->status != ThreadGoalStatus::Active) {
return std::nullopt;
}
return goal;
}
BuiltinCommandResult execute_goal_builtin(SessionEntry& entry,
const BuiltinCommandRequest& request) {
if (!entry.sm || !entry.loop) return {BuiltinCommandStatus::Failed, "session unavailable"};
ThreadGoalStore* store = entry.sm->goal_store();
if (!store) {
entry.loop->emit_system_message("Goal storage is not available.");
return {BuiltinCommandStatus::Failed, "goal storage unavailable"};
}
const std::string args = trim_ascii(request.args);
const std::string lower = lower_ascii(args);
std::string sid = entry.sm->current_session_id();
std::string error;
auto emit_updated = [&entry](const ThreadGoal& goal) {
entry.loop->events().emit(SessionEventKind::GoalUpdated,
nlohmann::json{{"session_id", goal.thread_id}, {"goal", thread_goal_to_json(goal)}});
entry.loop->restore_goal_runtime();
};
auto emit_cleared = [&entry](const std::string& session_id) {
entry.loop->events().emit(SessionEventKind::GoalCleared,
nlohmann::json{{"session_id", session_id}});
entry.loop->restore_goal_runtime();
};
if (args.empty() || lower == "view") {
if (sid.empty()) {
entry.loop->emit_system_message("No goal set. Use /goal <objective> to create one.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
auto goal = store->get_thread_goal(sid, &error);
if (!error.empty()) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
entry.loop->emit_system_message(goal.has_value()
? format_registry_goal_summary(*goal)
: "No goal set. Use /goal <objective> to create one.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
const auto first_space = args.find_first_of(" \t\r\n");
const std::string sub = lower_ascii(first_space == std::string::npos
? args
: args.substr(0, first_space));
const std::string tail = first_space == std::string::npos
? std::string{}
: trim_ascii(args.substr(first_space + 1));
const bool state_only = sub == "clear" || sub == "pause" || sub == "resume" || sub == "edit";
if (!state_only) sid = entry.sm->ensure_active_session_id();
if (sid.empty()) {
entry.loop->emit_system_message("No active session is available for /goal.");
return {BuiltinCommandStatus::Failed, "no active session"};
}
auto current = store->get_thread_goal(sid, &error);
if (!error.empty()) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
if (sub == "clear") {
if (!current.has_value()) {
entry.loop->emit_system_message("No goal to clear.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (!store->delete_thread_goal(sid, &error)) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
emit_cleared(sid);
entry.loop->emit_system_message("Goal cleared.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (sub == "pause") {
if (!current.has_value() || current->status != ThreadGoalStatus::Active) {
entry.loop->emit_system_message("Goal is not active.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (!store->update_thread_goal_status(sid, current->goal_id, ThreadGoalStatus::Paused, &error)) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
auto goal = store->get_thread_goal(sid);
if (goal.has_value()) emit_updated(*goal);
entry.loop->emit_system_message("Goal paused.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (sub == "resume") {
if (!current.has_value()) {
entry.loop->emit_system_message("No goal to resume.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (current->status == ThreadGoalStatus::Complete) {
entry.loop->emit_system_message("Goal is already complete.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (current->token_budget.has_value() && current->tokens_used >= *current->token_budget) {
entry.loop->emit_system_message("Goal is over its token budget. Create a replacement goal with a larger budget.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (!store->update_thread_goal_status(sid, current->goal_id, ThreadGoalStatus::Active, &error)) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
auto goal = store->get_thread_goal(sid);
if (goal.has_value()) emit_updated(*goal);
entry.loop->emit_system_message("Goal resumed.");
if (goal.has_value()) {
emit_goal_audit_message(entry, *goal, "resume", "Resumed");
}
entry.loop->clear_stale_abort_request();
entry.loop->maybe_continue_goal();
return {BuiltinCommandStatus::Accepted, "completed"};
}
if (sub == "edit") {
if (!current.has_value()) {
entry.loop->emit_system_message("No goal to edit.");
return {BuiltinCommandStatus::Accepted, "completed"};
}
auto parsed = parse_registry_goal_args(tail);
if (!parsed.error.empty()) {
entry.loop->emit_system_message(parsed.error);
return {BuiltinCommandStatus::Failed, parsed.error};
}
const std::string objective = trim_goal_objective(parsed.remainder);
if (!validate_goal_objective(objective, &error)) {
entry.loop->emit_system_message(error);
return {BuiltinCommandStatus::Failed, error};
}
auto budget = parsed.token_budget.has_value() ? parsed.token_budget : current->token_budget;
if (!store->update_thread_goal_objective(sid, current->goal_id, objective, budget, &error)) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
auto goal = store->get_thread_goal(sid);
if (goal.has_value()) emit_updated(*goal);
entry.loop->emit_system_message(goal.has_value() ? format_registry_goal_summary(*goal) : "Goal updated.");
// 回合运行中时把新 objective 通知给正在跑的模型(objective_updated
// steering);空闲时 no-op,下一次 continuation 自然携带新 objective。
entry.loop->notify_goal_objective_updated();
return {BuiltinCommandStatus::Accepted, "completed"};
}
auto parsed = parse_registry_goal_args(args);
if (!parsed.error.empty()) {
entry.loop->emit_system_message(parsed.error);
return {BuiltinCommandStatus::Failed, parsed.error};
}
const std::string objective = trim_goal_objective(parsed.remainder);
if (!validate_goal_objective(objective, &error)) {
entry.loop->emit_system_message(error);
return {BuiltinCommandStatus::Failed, error};
}
if (!store->replace_thread_goal(sid, objective, parsed.token_budget, ThreadGoalStatus::Active, &error)) {
entry.loop->emit_system_message("Goal error: " + error);
return {BuiltinCommandStatus::Failed, error};
}
auto goal = store->get_thread_goal(sid);
if (goal.has_value()) emit_updated(*goal);
entry.loop->emit_system_message(goal.has_value() ? format_registry_goal_summary(*goal) : "Goal created.");
if (goal.has_value()) {
emit_goal_audit_message(entry, *goal, "create", "Started");
}
entry.loop->maybe_continue_goal();
return {BuiltinCommandStatus::Accepted, "completed"};
}
BuiltinCommandResult execute_plan_builtin(SessionEntry& entry,
const BuiltinCommandRequest& request) {
if (!entry.sm || !entry.loop || !entry.perm) {
return {BuiltinCommandStatus::Failed, "session unavailable"};
}
const PermissionMode before = entry.perm->mode();
entry.perm->set_mode(PermissionMode::Plan);
entry.perm->clear_session_allows();
entry.sm->set_permission_mode("plan");
entry.sm->set_pre_plan_permission_mode(PermissionManager::mode_name(
before == PermissionMode::Plan ? entry.perm->pre_plan_mode() : before));
const std::string plan_file = entry.sm->ensure_plan_file_path();
std::ostringstream oss;
oss << "Plan mode enabled.";
if (!plan_file.empty()) {
oss << "\nPlan file: " << plan_file;
}
oss << "\nExplore and update only the plan file, then call ExitPlanMode for approval.";
entry.loop->emit_system_message(oss.str());
const std::string args = trim_ascii(request.args);
if (!args.empty()) {
const std::string display = request.display_text.empty()
? "/plan " + args
: request.display_text;
entry.loop->submit(args, display);
return {BuiltinCommandStatus::Accepted, "queued"};
}
return {BuiltinCommandStatus::Accepted, "completed"};
}
} // namespace
std::string default_no_workspace_cache_root() {
return path_to_utf8(path_from_utf8(get_acecode_dir()) / "cache" / "no-workspace");
}
std::string no_workspace_session_cwd(const std::string& session_id,
const std::string& cache_root) {
const std::string root = cache_root.empty() ? default_no_workspace_cache_root() : cache_root;
return path_to_utf8(path_from_utf8(root) / session_dir_name_from_id(session_id));
}
std::vector<std::string> list_no_workspace_session_cwds(const std::string& cache_root) {
namespace fs = std::filesystem;
std::vector<std::string> out;
const fs::path root = path_from_utf8(cache_root.empty()
? default_no_workspace_cache_root()
: cache_root);
std::error_code ec;
if (!fs::exists(root, ec) || !fs::is_directory(root, ec)) return out;
for (fs::directory_iterator it(root, ec), end; !ec && it != end; it.increment(ec)) {
std::error_code item_ec;
if (!it->is_directory(item_ec) || item_ec) continue;
out.push_back(path_to_utf8(it->path()));
}
std::sort(out.begin(), out.end());
return out;
}
std::optional<SessionMeta> find_no_workspace_session_meta(const std::string& id,
const std::string& cache_root) {
if (id.empty()) return std::nullopt;
const auto direct_cwd = no_workspace_session_cwd(id, cache_root);
auto direct_meta = SessionStorage::read_meta(
SessionStorage::meta_path(SessionStorage::get_project_dir(direct_cwd), id));
if (!direct_meta.id.empty() && direct_meta.no_workspace) return direct_meta;
for (const auto& cwd : list_no_workspace_session_cwds(cache_root)) {
if (cwd == direct_cwd) continue;
auto meta = SessionStorage::read_meta(
SessionStorage::meta_path(SessionStorage::get_project_dir(cwd), id));
if (!meta.id.empty() && meta.no_workspace) return meta;
}
return std::nullopt;
}
SessionRegistry::SessionRegistry(SessionRegistryDeps deps)
: deps_(std::move(deps)) {}
SessionRegistry::~SessionRegistry() {
shutting_down_.store(true);
if (deps_.power_guard) {
std::lock_guard<std::mutex> lk(mu_);
for (const auto& [id, _entry] : entries_) {
deps_.power_guard->release_session(id);
}
}
std::vector<std::thread> threads;
{
std::lock_guard<std::mutex> lk(title_threads_mu_);
threads.swap(title_threads_);
}
for (auto& t : threads) {
if (t.joinable()) t.join();
}
threads.clear();
{
std::lock_guard<std::mutex> lk(lifecycle_threads_mu_);
threads.swap(lifecycle_threads_);
}
for (auto& t : threads) {
if (t.joinable()) t.join();
}
// entries_ 析构会触发每个 SessionEntry 析构 → AgentLoop::shutdown 等等
// worker thread join。锁不需要 — 此时没人再调 lookup/destroy(daemon
// 退出路径)。
}
std::string SessionRegistry::create(const SessionOptions& opts) {
std::string id = opts.preset_session_id.empty()
? SessionStorage::generate_session_id()
: opts.preset_session_id;
SessionOptions create_opts = opts;
if (create_opts.no_workspace) create_opts.cwd.clear();
SessionOptions resolved = with_resolved_workspace(deps_, create_opts, id);
auto entry = make_entry_locked(id, resolved, nullptr);
{
std::lock_guard<std::mutex> lk(mu_);
entries_.emplace(id, std::move(entry));
}
if (auto active = acquire(id)) {
if (active->loop) active->loop->dispatch_session_start_hook("startup");
}
if (resolved.auto_start && !resolved.initial_user_message.empty()) {
UserInput input;
input.text = resolved.initial_user_message;
maybe_start_auto_title(id, input);
if (auto active = acquire(id)) {
if (active->loop) active->loop->submit(input);
}
}
LOG_INFO("[registry] created session " + id);
return id;
}
std::shared_ptr<SessionEntry>
SessionRegistry::make_entry_locked(const std::string& id,
const SessionOptions& opts,
const SessionMeta* resumed_meta) {
auto resolved_model = resolve_session_model(deps_, opts, resumed_meta);
auto entry = std::make_shared<SessionEntry>();
entry->id = id;
entry->cwd = opts.cwd.empty() ? deps_.cwd : opts.cwd;
entry->subagent_depth = opts.subagent_depth;
entry->parent_session_id = opts.parent_session_id;
entry->expert_id = opts.expert_id;
entry->expert_member_id = opts.expert_member_id;
entry->loop_execution = opts.loop_execution;
entry->loop_id = opts.loop_id;
entry->loop_run_id = opts.loop_run_id;
if (resumed_meta && !resumed_meta->parent_session_id.empty()) {
// resume 路径:子会话身份从持久化 meta 恢复,深度限制随之生效。
entry->parent_session_id = resumed_meta->parent_session_id;
}
if (resumed_meta) {
if (entry->expert_id.empty()) entry->expert_id = resumed_meta->expert_id;
if (entry->expert_member_id.empty()) {
entry->expert_member_id = resumed_meta->expert_member_id;
}
}
if (!entry->parent_session_id.empty() && entry->subagent_depth < 1) {
entry->subagent_depth = 1;
}
entry->no_workspace = opts.no_workspace || (resumed_meta && resumed_meta->no_workspace);
if (entry->no_workspace && !entry->cwd.empty()) {
std::error_code ec;
std::filesystem::create_directories(path_from_utf8(entry->cwd), ec);
if (ec) {
LOG_WARN("[registry] failed to create no-workspace cwd " +
entry->cwd + ": " + ec.message());
}
}
entry->workspace_hash = entry->no_workspace
? std::string{}
: (opts.workspace_hash.empty()
? compute_cwd_hash(entry->cwd)
: opts.workspace_hash);
entry->model_binding = std::make_shared<SessionModelBinding>();
if (resolved_model.profile.has_value() && resolved_model.config) {
SessionModelResolvedTarget target;
target.revision = resolved_model.revision;
target.profile = resolved_model.profile;
target.config = resolved_model.config;
target.state = resolved_model.state;
// Saved profiles must revalidate against the live config immediately
// before publication, including during initial create/resume. Ad-hoc
// `(session:<id>)` profiles stay on the explicit target inside the
// binding and never enter this saved-model resolver.
auto initial_resolver = [this](const std::string& name) {
return resolve_target_for_name(deps_, name);
};
const auto installed = entry->model_binding->install_explicit(
std::move(target), initial_resolver);
if (!installed.ok) {
LOG_WARN("[registry] initial session provider construction failed");
entry->model_binding->install_runtime_snapshot(
nullptr, resolved_model.state, resolved_model.revision);
} else if (!installed.warning.empty()) {
LOG_WARN("[registry] " + installed.warning);
}
} else {
entry->model_binding->install_runtime_snapshot(
std::move(resolved_model.runtime_provider),
resolved_model.state,
resolved_model.revision);
}
const auto initial_model_state = entry->model_binding->state_snapshot();
const AppConfig* entry_config = resolved_model.config
? resolved_model.config.get()
: deps_.config;
if (!entry->expert_id.empty()) {
if (deps_.expert_registry) {
entry->expert = deps_.expert_registry->find(entry->cwd, entry->expert_id);
}
if (!entry->expert_member_id.empty() &&
(!entry->expert ||
!entry->expert->is_declared_member(entry->expert_member_id))) {
entry->expert.reset();
}
if (!entry->expert) {
entry->expert_missing = true;
if (!resumed_meta) {
throw std::invalid_argument("unknown or invalid expert component: " +
entry->expert_id);
}
}
} else if (!entry->expert_member_id.empty()) {
entry->expert_missing = true;
if (!resumed_meta) {
throw std::invalid_argument(
"expert member requires a team expert binding");
}
}
const ExpertCapabilityScopes expert_scopes =
entry->expert
? entry->expert->selected_capabilities(entry->expert_member_id)
: (entry->expert_missing
? fail_closed_expert_scopes()
: ExpertCapabilityScopes{});
entry->expert_skill_roots =
entry->expert
? entry->expert->selected_skill_roots(entry->expert_member_id)
: std::vector<std::filesystem::path>{};
entry->expert_skill_allowlist = expert_scopes.skills;
ensure_expert_mcp_servers_available(
expert_scopes, deps_.mcp_manager, deps_.tools);
entry->tool_capability_policy =
tool_policy_from_expert_scopes(expert_scopes, entry_config);
if (entry_config) {
entry->skill_registry = std::make_shared<SkillRegistry>();
initialize_skill_registry(*entry->skill_registry, *entry_config,
entry->cwd, entry->expert_skill_roots,
entry->expert_skill_allowlist);
}
// SessionManager
entry->sm = std::make_unique<SessionManager>();
entry->sm->start_session(entry->cwd,
initial_model_state.provider,
initial_model_state.model,
id,
initial_model_state.name,
"daemon",
entry->no_workspace);
if (!entry->parent_session_id.empty()) {
// 子会话身份写进 meta(lazy:首条消息落盘时随初始 meta 一起写)。
entry->sm->set_parent_session_id(entry->parent_session_id);
}
if (!entry->expert_id.empty()) {
entry->sm->set_expert_binding(entry->expert_id,
entry->expert_member_id);
}
if (opts.loop_execution) {
entry->sm->set_loop_origin(opts.loop_id, opts.loop_run_id);
}
// PermissionManager: 复制 mode + dangerous flag,rules 由调用方在初始化
// template_permissions 时设好。session_allowed_ 不复制,各 session 独立。
entry->perm = std::make_unique<PermissionManager>();
if (deps_.template_permissions) {
entry->perm->set_mode(deps_.template_permissions->mode());
entry->perm->set_dangerous(deps_.template_permissions->is_dangerous());
// 注意: rules 当前没有 copy 接口 — v1 暂不复制 rules,daemon 路径
// 自己装(后续 Section 9 落 HTTP 时一起补)。TUI 路径不受影响。
}
// LOOP permission is definition-scoped. A daemon-wide --dangerous flag
// must not silently turn a LOOP configured as Default into Yolo.
if (opts.loop_execution) entry->perm->set_dangerous(false);
// 显式传入的 permission_mode 优先于 resume meta 恢复值:headless
// `-p --resume <id> --permission-mode accept-edits` 若被静默忽略,脚本
// 会在 default 模式下被写权限门自动拒绝,极难排查。web resume 不传该
// 字段(entry_opts 为空串),仍走 meta 恢复分支。
if (!opts.permission_mode.empty()) {
const PermissionMode requested_mode =
permission_mode_from_name(opts.permission_mode);
if (requested_mode == PermissionMode::Plan) {
entry->perm->set_mode(PermissionMode::Default);
entry->perm->set_mode(PermissionMode::Plan);
} else {
entry->perm->set_mode(requested_mode);
}
} else if (resumed_meta) {
const PermissionMode restored_mode =
permission_mode_from_name(resumed_meta->permission_mode);
if (restored_mode == PermissionMode::Plan) {
entry->perm->set_mode(permission_mode_from_name(
resumed_meta->pre_plan_permission_mode.empty()
? std::string{"default"}
: resumed_meta->pre_plan_permission_mode));
entry->perm->set_mode(PermissionMode::Plan);
} else {
entry->perm->set_mode(restored_mode);
}
}
entry->sm->set_permission_mode(
PermissionManager::mode_name(entry->perm->mode()),
/*persist_immediately=*/false);
if (entry->perm->mode() == PermissionMode::Plan) {
entry->sm->set_pre_plan_permission_mode(
PermissionManager::mode_name(entry->perm->pre_plan_mode()),
/*persist_immediately=*/false);