-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent_loop.hpp
More file actions
692 lines (612 loc) · 32.1 KB
/
Copy pathagent_loop.hpp
File metadata and controls
692 lines (612 loc) · 32.1 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
#pragma once
#include "provider/llm_provider.hpp"
#include "tool/tool_executor.hpp"
#include "permissions.hpp"
#include "utils/path_validator.hpp"
#include "utils/token_tracker.hpp"
#include "session/session_manager.hpp"
#include "session/event_dispatcher.hpp"
#include "session/permission_prompter.hpp"
#include "session/ask_user_question_prompter.hpp"
#include "config/config.hpp"
#include "hooks/hook_runtime.hpp"
#include <vector>
#include <string>
#include <functional>
#include <cstdint>
#include <mutex>
#include <atomic>
#include <thread>
#include <condition_variable>
#include <deque>
#include <queue>
#include <map>
#include <optional>
#include <utility>
#include <limits>
#include <memory>
#include <chrono>
namespace acecode {
struct LoopExecutionPolicy {
bool active = false;
std::string system_context;
};
// Authoritative receipt for a control task inserted into the AgentLoop worker
// queue. queued_behind_turn is computed while holding the same mutex that
// orders chat/control tasks, so a chat that has been submitted but has not yet
// flipped busy=true is still observed. Completion and success are separate: a
// callback that ran but could not commit its state must not be reported as
// applied.
struct ControlExecutionState {
mutable std::mutex mu;
std::condition_variable cv;
bool completed = false;
bool succeeded = false;
};
struct ControlEnqueueReceipt {
std::uint64_t sequence = 0;
bool accepted = false;
bool queued_behind_turn = false;
std::shared_ptr<ControlExecutionState> execution;
bool completed() const {
if (!execution) return false;
std::lock_guard<std::mutex> lock(execution->mu);
return execution->completed;
}
bool succeeded() const {
if (!execution) return false;
std::lock_guard<std::mutex> lock(execution->mu);
return execution->completed && execution->succeeded;
}
bool applied() const {
return succeeded();
}
bool wait_for_completion(std::chrono::milliseconds timeout) const {
if (!execution) return false;
std::unique_lock<std::mutex> lock(execution->mu);
return execution->cv.wait_for(
lock, timeout, [&] { return execution->completed; });
}
};
class SkillRegistry;
class MemoryRegistry;
class HookManager;
struct MemoryConfig;
struct ProjectInstructionsConfig;
struct ExpertDefinition;
struct CompactResult;
class AgentLoopDoomGuard;
// Callbacks for the TUI to observe agent loop events
struct AgentCallbacks {
// Called when a new message is added to the conversation
std::function<void(const std::string& role, const std::string& content, bool is_tool)> on_message;
// Metadata-preserving observer for persisted transcript-only messages.
// When installed, it receives those messages instead of the legacy
// three-field on_message callback so UI grouping can use stable metadata.
std::function<void(const ChatMessage& message)> on_transcript_message;
// Called after each tool execution with the structured ToolResult so the
// TUI can render a summary row. Fires in addition to on_message (not in
// place of it) so consumers that only care about the text stream continue
// to work unchanged. Receives the tool_call message too so the TUI can
// correlate summaries with their call rows.
std::function<void(const ChatMessage& call_msg,
const std::string& tool_name,
const ToolResult& result)> on_tool_result;
// Called when the agent starts/stops processing
std::function<void(bool busy)> on_busy_changed;
// Called once for a submitted agent turn immediately before its terminal
// busy=false callback. Values match persisted turn timing status:
// "completed", "error", or "aborted". Compact/background busy cycles do
// not invoke this hook.
std::function<void(const std::string& status)> on_turn_finished;
// Called to request user confirmation for a tool call.
// Returns: Allow, Deny, or AlwaysAllow
std::function<PermissionResult(const std::string& tool_name, const std::string& arguments)> on_tool_confirm;
// Called for each streaming delta token (real-time TUI update)
std::function<void(const std::string& token)> on_delta;
// Called when token usage data is received from the provider
std::function<void(const TokenUsage& usage)> on_usage;
// Called when the current thread goal status changes. Empty string means
// no goal is active for the current session.
std::function<void(const std::string& status)> on_goal_status;
// Called when TodoWrite publishes or reads the current visible checklist.
// The payload shape matches the todo_updated session event.
std::function<void(const nlohmann::json& payload)> on_todo_updated;
// Legacy display observer for replacement-style transcript updates. Normal
// compact success appends marker messages and no longer calls this hook.
std::function<void(const std::vector<ChatMessage>& messages,
const CompactResult& result)> on_transcript_replace;
// Called before a provider retry replays the current model request.
// Consumers should clear provisional live assistant output from the failed
// stream attempt; persisted history is unchanged.
std::function<void()> on_stream_retry_reset;
// Presentation-only retry lifecycle; neither callback appends transcript
// messages.
std::function<void(const ProviderErrorInfo&)> on_model_retry;
std::function<void()> on_model_retry_resume;
// Called just before a tool begins executing. `command_preview` is a short
// human-readable summary (e.g. the first 60 chars of a bash command).
std::function<void(const std::string& tool_name,
const std::string& command_preview)> on_tool_progress_start;
// Called from the tool's streaming thread with each cleaned chunk.
// `tail_snapshot` is the last-5-lines sliding window; `current_partial` is
// the in-progress line (not yet terminated by \n).
std::function<void(const std::vector<std::string>& tail_snapshot,
const std::string& current_partial,
size_t total_bytes,
int total_lines)> on_tool_progress_update;
// Called after the tool returns (or throws). Guaranteed via RAII to fire
// once for every on_tool_progress_start.
std::function<void()> on_tool_progress_end;
};
class AgentLoop {
public:
// provider_accessor: 每轮 turn 开始时调用,返回当前有效的 provider 的
// shared_ptr 快照。调用方负责在该函数内部加锁保护 main.cpp 的 provider
// 替换(见 design D4 / 任务 4.6)。这样 worker 即使跨 turn 持有 snapshot
// 也不会悬空,下一轮再拿最新的。
using ProviderAccessor = std::function<std::shared_ptr<LlmProvider>()>;
AgentLoop(ProviderAccessor provider_accessor, ToolExecutor& tools,
AgentCallbacks callbacks, const std::string& cwd,
PermissionManager& permissions);
~AgentLoop();
void set_callbacks(AgentCallbacks cb);
// Submit a user message. Non-blocking: enqueues the message and returns immediately.
// The internal worker thread will process it.
void submit(const std::string& user_message);
// Submit with separate "LLM prompt" vs "UI display" texts. `prompt` is what
// the model sees in `messages_` (and persisted JSONL);`display_text` is
// recorded in `user_msg.metadata.display_text` so UI can show the original
// user input even though the model sees an expanded form (e.g. daemon-side
// skill command expansion). Empty `display_text` falls back to `prompt`.
void submit(const std::string& prompt, const std::string& display_text);
// Submit structured user input containing text plus optional attachment or
// context parts. Existing text-only submit overloads delegate here.
void submit(const UserInput& input);
// Submit a user-initiated shell command triggered by `!` mode. Non-blocking:
// enqueues on the same worker so it serialises with LLM turns. The worker
// invokes BashTool directly (no LLM round-trip), emits tool_call + tool_result
// UI messages via callbacks, and appends a `<bash-input>/<bash-stdout>/...`
// user-role entry to messages_ for the next LLM turn.
void submit_shell(std::string command);
// Queue a manual `/compact` control task on the same worker as chat/tool
// turns so transcript mutation cannot race an active model run.
void submit_compact();
// Queue a runtime-context update on the same worker as chat turns. The
// callback runs between already-queued and subsequently-queued turns, so an
// in-flight turn keeps its current context while the next turn sees the
// update.
ControlEnqueueReceipt enqueue_control(std::function<bool()> control);
// Emit a visible system message without adding it to LLM history. Used by
// daemon-owned builtin commands for TUI-like progress and fallback output.
void emit_system_message(const std::string& content);
void emit_transcript_system_message(const std::string& content,
nlohmann::json metadata = nlohmann::json::object());
// Append a single user-role entry to messages_ representing an already-run
// shell command and its captured output. Used both by the shell worker
// branch and by --resume to rehydrate LLM context from persisted session
// messages (`!cmd` user + tool_result pair).
void inject_shell_turn(const std::string& cmd,
const std::string& stdout_text,
const std::string& stderr_text,
int exit_code);
// Abort the current inference. Safe to call from any thread.
void abort();
void clear_stale_abort_request();
// Signal the worker thread to exit and wait for it to finish.
void shutdown();
// Returns true if abort has been requested. Useful for confirm callbacks.
bool is_aborting() const { return abort_requested_.load(); }
// Returns true while the worker is processing a submitted turn.
bool is_busy() const { return busy_.load(); }
// Append input to the active regular turn. The expected id check and FIFO
// append happen under one lock, matching Codex turn/steer race semantics.
TurnSteerResult steer_input(const std::string& expected_turn_id,
const UserInput& input);
// Atomically promise a new high-priority user turn and abort the matching
// active turn. Unlike steer_input(), this does not wait for the current
// provider response to reach its next model boundary.
TurnSteerResult interrupt_turn(const std::string& expected_turn_id,
const UserInput& input);
std::string active_turn_id() const;
// Legacy cancel alias
void cancel() { abort(); }
// Clear all messages (for /clear command)
void clear_messages() {
messages_.clear();
last_api_total_tokens_.store(0, std::memory_order_relaxed);
compact_window_initialized_ = false;
compact_window_number_ = 0;
compact_first_window_id_.clear();
compact_current_window_id_.clear();
}
// Push a message (for session restore)
void push_message(const ChatMessage& msg) { messages_.push_back(msg); }
const std::vector<ChatMessage>& messages() const { return messages_; }
std::vector<ChatMessage>& messages_mut() { return messages_; }
// Copy of the latest complete provider-facing prompt built by the worker.
// `/btw` callers use this instead of reading messages_ from an HTTP thread,
// which would race the active turn. The snapshot is intentionally detached
// from transcript/session persistence.
std::vector<ChatMessage> side_question_context_snapshot() const;
SideQuestionResult ask_side_question(const std::string& question);
using SideQuestionCallback =
std::function<void(SideQuestionResult)>;
// Runs the detached provider call without blocking the TUI thread. Worker
// lifetime is owned by AgentLoop and callbacks are suppressed on shutdown.
bool ask_side_question_async(std::string question,
SideQuestionCallback callback);
const std::string& cwd() const { return cwd_; }
// 切换会话工作目录(enter_worktree / exit_worktree / worktree resume 恢复)。
// 更新 cwd_ 并以新根重建 PathValidator;会话存储位置(SessionManager 的
// project dir)不动 —— worktree 是同一个项目会话的临时工作区,不是新项目。
// 只应在工具执行线程(turn 内)或会话未运行时调用。
void set_cwd(const std::string& new_cwd);
void set_context_window(int cw) {
context_window_.store(cw, std::memory_order_relaxed);
}
int context_window() const {
return context_window_.load(std::memory_order_relaxed);
}
void set_no_model_config_prompt(std::string prompt) {
no_model_config_prompt_ = std::move(prompt);
}
// Install / update the agent-loop termination policy. Called once from
// main.cpp at startup (and could be called again if config reloads).
// A fresh-default AgentLoopConfig is used when this setter is never called.
void set_agent_loop_config(AgentLoopConfig cfg) { loop_cfg_ = cfg; }
// Per-session policy used only by daemon-owned LOOP runs. It is installed
// before the first submit and may be updated once worktree creation adds
// final branch/path context.
void set_loop_execution_policy(LoopExecutionPolicy policy) {
loop_execution_policy_ = std::move(policy);
}
const LoopExecutionPolicy& loop_execution_policy() const {
return loop_execution_policy_;
}
ResolvedQuestionPolicy resolved_question_policy() const;
void set_session_manager(SessionManager* sm);
void set_hook_manager(HookManager* hm) { hook_manager_ = hm; }
void dispatch_session_start_hook(const std::string& source);
void dispatch_session_title_changed_hook(const std::string& title,
const std::string& source,
const std::string& title_source);
void restore_goal_runtime();
void publish_current_goal_state();
void maybe_continue_goal();
// Goal 无人值守模式:当前会话(或子代理的父会话)存在 Active goal 且不在
// Plan mode 时为 true。工具权限确认自动放行;
// AskUserQuestion 正常弹 UI,30 秒未回答则自动采纳推荐项。
bool goal_unattended_active();
// /goal edit 修改了 active goal 的 objective 时调用。回合运行中则在下一次
// 模型请求前注入 objective_updated steering(对齐 Codex ext/goal 的
// inject_active_turn_steering);空闲时为 no-op(下一次 continuation 自然
// 带新 objective)。
void notify_goal_objective_updated();
void set_skill_registry(const SkillRegistry* sr) { skill_registry_ = sr; }
void set_memory_registry(const MemoryRegistry* mr) { memory_registry_ = mr; }
void set_memory_config(const MemoryConfig* cfg) { memory_cfg_ = cfg; }
void set_project_instructions_config(const ProjectInstructionsConfig* cfg) {
project_instructions_cfg_ = cfg;
}
void set_custom_instructions_config(const CustomInstructionsConfig* cfg) {
custom_instructions_cfg_ = cfg;
}
void set_expert_context(const ExpertDefinition* expert,
std::string member_id = {}) {
expert_ = expert;
expert_member_id_ = std::move(member_id);
}
void set_tool_capability_policy(ToolCapabilityPolicy policy) {
tool_capability_policy_ = std::move(policy);
}
void set_git_context_config(const GitContextConfig* cfg) {
git_context_cfg_ = cfg;
}
// 外部 git 状态变更(如 Web UI checkout 分支)后标记快照过期。线程安全:
// 任意线程可调;worker 在下一次模型请求前消费标记并重采。正在跑的 turn
// 继续用旧快照 —— 快照本身声明为 point-in-time,一回合的陈旧无害。
void invalidate_git_snapshot() { git_snapshot_stale_.store(true); }
// ---- 事件流(Section 7 SessionClient)----
// 老的 AgentCallbacks 路径**完全不动**:TUI 仍然用 callbacks。
// SessionClient 走 events_,daemon HTTP/WebSocket handler 在 subscribe 上
// 拿事件流。两者并行,不互相影响。
EventDispatcher& events() { return events_; }
// 注入异步 PermissionPrompter(daemon 模式)。不调用此 setter 时,AgentLoop
// 默认走 callbacks_.on_tool_confirm 同步路径(TUI 模式)。线程安全要求:
// 不在 worker 跑工具时调用 — 通常 SessionRegistry 创建 AgentLoop 后立刻
// 调,然后才 submit 第一条消息。
void set_permission_prompter(std::unique_ptr<PermissionPrompter> p) {
prompter_ = std::move(p);
}
// 注入异步 AskUserQuestionPrompter(daemon 模式)。raw 指针;生命周期由
// 调用方(典型是 SessionEntry)保证。AgentLoop 在每次工具调用前把它包成
// ToolContext::ask_user_questions 回调注入。
void set_ask_question_prompter(AskUserQuestionPrompter* p) {
ask_prompter_ = p;
}
private:
void worker_main();
void join_side_question_threads();
void run_agent(const std::string& user_message);
void run_agent_with_input(const UserInput& input,
bool hidden_goal_context = false);
// Variant that records `display_text` into the user message's metadata.display_text
// so UI can show the original input while the LLM sees an expanded `prompt`.
// When `display_text` is empty, behaves identically to run_agent(prompt).
void run_agent_with_display(const std::string& prompt,
const std::string& display_text,
bool hidden_goal_context = false);
void run_shell(std::string command);
void run_compact();
void account_goal_usage(std::int64_t token_delta = 0, bool allow_complete = false);
void emit_goal_updated(const ThreadGoal& goal);
void emit_goal_cleared(const std::string& session_id);
void emit_todo_updated(const nlohmann::json& payload);
std::string build_goal_context_prompt(const ThreadGoal& goal) const;
std::string build_goal_budget_limit_prompt(const ThreadGoal& goal) const;
std::string build_goal_objective_updated_prompt(const ThreadGoal& goal) const;
// 回合失败(provider 终止错误 / 连续空回复 / provider 缺失)时停止 Active
// goal:HTTP 429 → usage_limited,其余 → blocked。对齐 Codex ext/goal 的
// on_turn_error,防止 maybe_continue_goal 对着同一个错误无限重试烧 token。
void stop_active_goal_after_turn_error(const ProviderErrorInfo& info);
void set_active_provider_for_retry(
const std::shared_ptr<LlmProvider>& provider);
void clear_active_provider_for_retry(
const std::shared_ptr<LlmProvider>& provider);
void wake_active_provider_retry();
// 在每次模型请求前消费 pending steering 标记,把 budget_limit /
// objective_updated 提示以 hidden_goal_context user 消息注入。
void maybe_inject_goal_steering();
void begin_active_turn(const std::string& turn_id);
void commit_turn_steering_input(UserInput input,
const std::string& turn_id);
// Worker-only. Drains pending input and returns true when at least one
// message was committed. When close_if_empty is true, an empty queue closes
// acceptance under the same lock, eliminating the final-response race.
bool drain_active_turn_inputs(bool close_if_empty);
void append_interrupted_turn_context(const std::string& turn_id);
// Visible abort notice: manual stop keeps [Interrupted]; interjection
// uses a dedicated [Interjected] system marker so the transcript does
// not look like a user stop.
std::string abort_notice_text() const;
nlohmann::json abort_notice_metadata() const;
std::size_t close_active_turn_and_discard();
bool maybe_run_auto_compact();
bool active_estimate_exceeds_auto_threshold(
const UserInput* pending_input = nullptr) const;
std::vector<ChatMessage> build_compaction_initial_context() const;
void initialize_compact_window_state();
void apply_compact_result(const CompactResult& result,
const std::string& trigger,
const std::string& compact_notice_id);
// Section 7: 同时调老 on_message callback(若 TUI 挂了)和新事件流
// (events_)。所有 on_message 触发点都该走这个 helper,确保 daemon
// 模式下没装 callbacks 也能拿到事件。
void dispatch_message(const std::string& role,
const std::string& content,
bool is_tool,
nlohmann::json metadata = nlohmann::json::object(),
nlohmann::json content_parts = nlohmann::json::array());
void append_turn_timing_record(const std::string& user_message_uuid,
std::int64_t started_at_ms,
std::int64_t completed_at_ms,
const std::string& status);
void append_tool_user_prompt(const std::string& content,
const std::string& display_text,
const std::string& source_tool);
void dispatch_assistant_completed_hook(const ChatMessage& assistant_msg,
const std::shared_ptr<LlmProvider>& provider_snapshot);
HookCommonPayloadFields build_hook_common_fields(const std::string& event_name) const;
void apply_hook_side_effects(const HookAggregateOutcome& outcome,
bool include_additional_context = true);
std::string drain_hook_request_context();
HookAggregateOutcome dispatch_codex_hook(const std::string& event_name,
const std::string& matcher_value,
const nlohmann::json& payload);
// ---- Refactored sub-methods of run_agent_with_input ----
// These decompose the monolithic turn function into focused phases.
// Return types are defined in the .cpp anonymous namespace.
// Type alias for the progress emission callback used across sub-methods.
using ProgressEmitter = std::function<void(
const std::string& phase, const std::string& label,
const std::string& detail, const std::string& tool,
const std::string& tool_call_id, int tool_index, bool force)>;
// Phase 1: Build user message from input, persist, emit events.
// Returns turn timing metadata for the orchestrator.
struct UserTurnInfo {
ChatMessage user_msg;
bool visible_timed_turn = false;
std::string turn_user_uuid;
std::string active_turn_id;
std::int64_t turn_started_at_ms = 0;
};
UserTurnInfo prepare_user_turn(const UserInput& input, bool hidden_goal_context);
// Phase 2: Build the full message list for the LLM provider.
struct ApiRequestBundle {
std::vector<ChatMessage> messages_with_system;
std::vector<ToolDef> tool_defs;
ContextUsageBreakdown context_usage_estimate;
nlohmann::json prompt_diag; // simplified: store as raw json
};
ApiRequestBundle build_api_request_messages(bool emergency_profile = false);
void publish_side_question_context(
const std::vector<ChatMessage>& messages_with_system);
// Phase 3: Stream provider response and accumulate.
struct ProviderCallResult {
ChatResponse accumulated;
bool provider_error_seen = false;
ProviderErrorInfo provider_error_info;
std::shared_ptr<LlmProvider> provider_snapshot;
int provider_attempt = 1;
};
ProviderCallResult call_provider_and_collect(
const std::shared_ptr<LlmProvider>& provider,
const ApiRequestBundle& bundle,
const ProgressEmitter& emit_progress,
int model_step_index);
void emit_retry_lifecycle(
const ProviderErrorInfo& info,
bool waiting,
bool compaction);
void record_terminal_trajectory_events(
nlohmann::json busy_payload,
nlohmann::json done_payload);
// Phase 4: Classify terminal provider errors.
enum class HandleErrorResult { Continue, Break, Proceed };
enum class ContextRecoveryStage {
Normal,
HistoryRepaired,
EmergencyProfile,
};
HandleErrorResult handle_provider_error(
ProviderCallResult& result,
const std::vector<ChatMessage>& messages_with_system,
std::string& turn_timing_status,
ContextRecoveryStage& recovery_stage,
bool& emergency_request_profile);
// Phase 5: Execute tool calls (parallel read + serial write).
// Returns true if task_complete terminator fired.
bool execute_tool_calls(
const ChatResponse& accumulated,
const std::shared_ptr<LlmProvider>& provider_snapshot,
const ProgressEmitter& emit_progress,
// Mutable state from the orchestrator:
AgentLoopDoomGuard& doom_guard,
std::mutex& doom_guard_mu,
std::string& turn_timing_status);
// Helper: construct a ToolContext with all callbacks wired up.
ToolContext build_tool_context(
const ProgressEmitter& emit_progress,
AgentLoopDoomGuard& doom_guard,
std::mutex& doom_guard_mu);
// Helper: emit agent progress with rate-limiting and coalescing.
// Uses the progress state passed by reference.
void emit_progress_tick(
const ProgressEmitter& emit_progress,
const std::string& phase, const std::string& label,
const std::string& detail, const std::string& tool,
const std::string& tool_call_id, int tool_index, bool force,
// Mutable progress state:
std::mutex& progress_mu,
std::string& active_progress_key,
std::int64_t& active_progress_started_at_ms,
std::chrono::steady_clock::time_point& last_progress_emit_at);
struct WorkerTask {
enum class Kind { Chat, Shell, Compact, Control };
Kind kind = Kind::Chat;
std::string payload;
UserInput input;
// 仅 Chat 用:UI 渲染时希望显示的"原文",而 payload(发给 LLM)可能
// 是被 daemon expander 展开过的字符串(skill 调用提示等)。空 = UI 与
// LLM 看到同一份(payload)。
std::string display_text;
bool hidden_goal_context = false;
std::function<void()> control;
};
ProviderAccessor provider_accessor_;
ToolExecutor& tools_;
AgentCallbacks callbacks_;
std::vector<ChatMessage> messages_;
mutable std::mutex side_question_context_mu_;
std::vector<ChatMessage> side_question_context_;
std::mutex side_question_threads_mu_;
std::vector<std::thread> side_question_threads_;
std::atomic<bool> side_question_shutdown_{false};
std::atomic<bool> abort_requested_{false};
// Distinguishes a steering interrupt from a manual stop. The former
// immediately continues with a promised turn and must not pause goals.
std::atomic<bool> turn_interrupt_requested_{false};
std::atomic<bool> busy_{false};
std::mutex active_provider_mu_;
std::weak_ptr<LlmProvider> active_provider_;
std::string cwd_;
PermissionManager& permissions_;
PathValidator path_validator_;
std::atomic<int> context_window_{128000};
std::string no_model_config_prompt_;
// agent_loop termination policy. Fresh defaults come from AgentLoopConfig
// until set_agent_loop_config is called from main.cpp.
AgentLoopConfig loop_cfg_;
LoopExecutionPolicy loop_execution_policy_;
// Latest server-reported total active-context usage. For providers that do
// not return total_tokens, prompt_tokens is used as the fallback.
std::atomic<int> last_api_total_tokens_{0};
std::atomic<int> compact_generation_{0};
bool compact_window_initialized_ = false;
std::uint64_t compact_window_number_ = 0;
std::string compact_first_window_id_;
std::string compact_current_window_id_;
SessionManager* session_manager_ = nullptr;
HookManager* hook_manager_ = nullptr;
std::vector<std::string> hook_request_context_;
bool stop_hook_active_ = false;
const SkillRegistry* skill_registry_ = nullptr;
const MemoryRegistry* memory_registry_ = nullptr;
const MemoryConfig* memory_cfg_ = nullptr;
const ProjectInstructionsConfig* project_instructions_cfg_ = nullptr;
const CustomInstructionsConfig* custom_instructions_cfg_ = nullptr;
const ExpertDefinition* expert_ = nullptr;
std::string expert_member_id_;
ToolCapabilityPolicy tool_capability_policy_;
const GitContextConfig* git_context_cfg_ = nullptr;
// gitStatus 快照缓存(openspec add-git-context):nullopt = 尚未采集,
// 空串 = 已采集但非仓库/失败/disabled(不注入)。只在 worker 线程读写
// (build_api_request_messages 惰性采集,set_cwd 经工具回调在同线程重置),
// 与 cwd_ 本身的线程假设一致。
std::optional<std::string> git_snapshot_cache_;
// 跨线程失效信号(invalidate_git_snapshot):worker 在模型请求前 exchange
// 消费,避免 HTTP 线程直接 reset optional 造成数据竞争。
std::atomic<bool> git_snapshot_stale_{false};
std::string session_context_cache_key_;
std::string session_context_cache_content_;
std::string skill_context_cache_key_;
std::string skill_context_cache_content_;
// Worker-thread-only flag derived from the current root UserInput. It
// remains active across all provider iterations in that turn.
bool active_turn_swarm_mode_ = false;
// Worker-only control populated by terminal tool results. Actions run only
// after canonical tool results, turn timing, BusyChanged and Done have all
// been emitted/persisted.
bool terminate_session_after_turn_ = false;
std::vector<std::function<void()>> post_turn_actions_;
std::string goal_accounting_thread_id_;
std::string goal_accounting_goal_id_;
std::string budget_notice_goal_id_;
std::chrono::steady_clock::time_point goal_time_checkpoint_{};
// Goal steering pending 标记。atomic:budget 标记可能从并行读工具批次的
// 线程置位,objective 标记从 TUI/daemon 命令线程置位;消费固定在 worker
// 线程的模型请求前。回合开始时清零 = Codex inject_if_running 失败即丢弃。
std::atomic<bool> pending_goal_budget_limit_steering_{false};
std::atomic<bool> pending_goal_objective_steering_{false};
std::map<std::string, std::chrono::steady_clock::time_point> recent_safe_edit_failures_;
static constexpr std::size_t kMaxPendingTurnSteers = 128;
mutable std::mutex active_turn_mu_;
std::string active_turn_id_;
bool active_turn_accepting_ = false;
std::deque<UserInput> pending_turn_inputs_;
// Worker thread and task queue
std::thread worker_thread_;
std::mutex queue_mu_;
std::condition_variable queue_cv_;
// Immediate steering follow-ups run before ordinary queued work. Separate
// FIFOs preserve both urgent and ordinary relative ordering.
std::queue<WorkerTask> priority_task_queue_;
std::queue<WorkerTask> task_queue_;
bool shutdown_requested_ = false;
bool worker_task_active_ = false;
WorkerTask::Kind worker_task_kind_ = WorkerTask::Kind::Control;
std::uint64_t next_control_sequence_ = 0;
// Section 7: 事件分发器。EventDispatcher 自己内部加锁,所以这里不需要
// 额外的同步;emit 由 worker_main 线程调用,subscribe/unsubscribe 由
// HTTP handler 线程并发调用。
EventDispatcher events_;
// Section 7.6: PermissionPrompter。null 时走 callbacks_.on_tool_confirm
// 老路径(TUI);非 null 时(daemon 模式)走 prompter_->prompt。
std::unique_ptr<PermissionPrompter> prompter_;
// AskUserQuestionPrompter: daemon 模式下走 WS。raw 指针,生命周期由
// SessionEntry 持有。null 时 ToolContext::ask_user_questions 不注入,
// 此时 AskUserQuestion 工具(daemon 工厂版)会返回 rejected。
AskUserQuestionPrompter* ask_prompter_ = nullptr;
};
} // namespace acecode