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
// lc-agents/src/executor/agent_loop.rs
//! `AgentExecutor`'s decision loop: the main agent loop plus sequential/parallel tool
//! execution.
//!
//! Works alongside `executor.rs` (struct + builder + invoke/stream entry points) and
//! `plan.rs` (cached planning).
use super::budget::{budget_iteration_gate, budget_token_gate, budget_tool_gate};
use super::engine::{AgentExecutor, MaxIterationsPolicy};
use super::tools::{run_tool_with_timeout, tool_error_observation};
use super::AgentError;
use crate::approval::ApprovalDecision;
use crate::hooks::{ToolCallAction, ToolCallContext, ToolResultContext};
use crate::metrics::AgentMetrics;
use crate::resume::{PendingApproval, ResumeStore};
use crate::types::{AgentAction, AgentOutput, AgentStep, ToolInput};
use lc_callbacks::{RunTree, RunType};
use lc_core::tools::ToolError;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
/// Cross-process resume (§4.2): the checkpoint context needed for a single tool call.
///
/// Constructed by the agent loop in the Action branch: `tool_name` / `arguments` /
/// `tool_id` start as placeholders, then `execute_tool_inner` fills in the **final values**
/// the approval saw once the synchronous hooks finish, and persists them; the checkpoint
/// is cleared once the approval decision lands. The parallel tool path
/// (`execute_tools_parallel`) does not build one — concurrent multi-tool approvals never
/// persist, so checkpoints cannot overwrite each other.
pub(crate) struct ResumeContext<'a> {
/// Checkpoint template pre-filled with loop context (inputs / steps / iteration /
/// budget accumulation / trace).
pending: &'a PendingApproval,
/// Checkpoint storage (persist before / clear after approval).
store: &'a Arc<dyn ResumeStore>,
}
/// Applies an approval decision to `tool_ctx`.
///
/// Returns `Some(reason)` for **Deny** (aborts execution; the rejection observation is fed
/// back to the loop); `None` for Allow / Modify (execution continues). Modify overwrites
/// `tool_ctx.arguments`.
fn apply_approval_decision(
decision: ApprovalDecision,
tool_ctx: &mut ToolCallContext,
) -> Option<String> {
match decision {
ApprovalDecision::Allow => None,
ApprovalDecision::Deny { reason } => {
log::info!(
target: "lc_agents::approval",
"tool_call denied by approval handler name={} reason={}",
tool_ctx.name,
reason
);
Some(reason)
}
ApprovalDecision::Modify { arguments, note } => {
log::info!(
target: "lc_agents::approval",
"tool_call arguments modified by approval handler name={} note={}",
tool_ctx.name,
note
);
tool_ctx.arguments = arguments;
None
}
}
}
impl AgentExecutor {
/// Runs the agent loop from scratch.
///
/// Accumulates `metrics` (LLM calls, tool calls, token usage) as it goes.
pub(crate) async fn run_agent_loop(
&self,
inputs: HashMap<String, String>,
intermediate_steps: Vec<AgentStep>,
root_run: &mut RunTree,
metrics: &mut AgentMetrics,
) -> Result<String, AgentError> {
self.run_agent_loop_from(inputs, intermediate_steps, 0, root_run, metrics)
.await
}
/// Runs the agent loop starting at a given iteration.
///
/// Cross-process resume (§4.2) uses this to continue from a pending iteration: the
/// iteration / tool-call budgets keep counting from the checkpoint's accumulated
/// amounts, and already-completed intermediate steps are not replayed.
pub(crate) async fn run_agent_loop_from(
&self,
inputs: HashMap<String, String>,
mut intermediate_steps: Vec<AgentStep>,
start_iteration: usize,
root_run: &mut RunTree,
metrics: &mut AgentMetrics,
) -> Result<String, AgentError> {
// Budget gate (§4.2): start the loop timer, used by the max_duration /
// max_iterations checks.
let loop_start = Instant::now();
for iteration in start_iteration..self.max_iterations {
// Budget gate: iteration-level (iteration count + wall-clock). Off by default
// (returns None immediately when the config is None).
if let Some(err) = budget_iteration_gate(
self.budget.as_ref(),
self.max_iterations,
iteration,
loop_start,
) {
return Err(err);
}
if self.verbose {
log::info!("=== Iteration {} ===", iteration + 1);
}
// 0.21.0 S6.1: context compaction (off by default). Checked before
// every plan round; drops the oldest whole steps (action + pair
// observation stay together) when the trigger fires. The same
// semantics run in the streaming path — the two paths cannot diverge.
if let Some(config) = &self.compaction {
let tokens = metrics.total_tokens.unwrap_or(0);
let (kept, dropped) = config.compact(&intermediate_steps, tokens);
if dropped > 0 {
log::info!(
target: "lc_agents::compaction",
"compacted {} of {} steps ({} remain)",
dropped,
dropped + kept.len(),
kept.len()
);
intermediate_steps = kept;
metrics.compactions += 1;
}
}
let output = self
.plan_cached(&intermediate_steps, &inputs, metrics)
.await?;
// Budget gate: cumulative tokens after an LLM call; hard-stops when the limit
// is exceeded.
if let Some(err) = budget_token_gate(self.budget.as_ref(), metrics) {
return Err(err);
}
match output {
AgentOutput::Finish(finish) => {
if self.verbose {
log::info!("Final answer: {:?}", finish.return_values);
}
return Ok(finish.output().unwrap_or("").to_string());
}
AgentOutput::Action(action) => {
// 0.22.0 audit fix (H-A5): the ReAct parse-repair pseudo-tool is
// not a real tool — never executed. Its input is fed back as the
// observation so the model can re-emit in the correct format;
// the agent hard-fails if it fails to parse twice in a row.
if action.tool == crate::react::agent::PARSE_ERROR_TOOL {
let observation = match &action.tool_input {
ToolInput::String { value } => value.clone(),
ToolInput::Object { value } => value.to_string(),
};
if self.verbose {
log::info!("Parse repair observation: {}", observation);
}
intermediate_steps.push(AgentStep::new(action, observation));
continue;
}
metrics.tool_calls += 1;
if self.verbose {
log::info!("Action: {}({})", action.tool, action.tool_input);
}
// Budget gate: check cumulative call count and wall-clock before the
// tool runs.
if let Some(err) = budget_tool_gate(self.budget.as_ref(), metrics, loop_start) {
return Err(err);
}
// Cross-process resume (§4.2): build the checkpoint context (only when
// a store is configured). Carries a snapshot of the loop context only;
// tool_name / arguments / tool_id are filled in by execute_tool_inner
// with the final values the approval sees, once the sync hooks finish.
// `inputs` / `intermediate_steps` are cloned as snapshots so resume
// continues from this batch of intermediate steps without replaying
// already-completed tool calls.
let pending = PendingApproval {
tool_name: action.tool.clone(),
arguments: serde_json::Value::Null,
tool_id: String::new(),
inputs: inputs.clone(),
steps: intermediate_steps.clone(),
iteration,
tool_calls_consumed: metrics.tool_calls,
tokens_consumed: metrics.total_tokens,
trace_id: root_run.trace_id.map(|id| id.to_string()),
};
let resume_ctx = self.resume_store.as_ref().map(|store| ResumeContext {
pending: &pending,
store,
});
// 0.20.0 S3.1:工具**执行**错误(工具真的跑了、失败返回 ToolError)
// 转 observation 喂回循环,agent 可自救——四条执行路径(顺序/并行 ×
// invoke/stream)一致。框架级守卫拒绝(权限策略 / hook 拒绝 /
// ControlAbort 交接环与深度中止 / ToolNotFound)不是执行失败,仍
// 硬失败上抛:agent 无法靠重规划绕过它们,软化成 observation 会让
// 策略拒绝、预算配额与交接环检测形同虚设。
let observation = match self
.execute_tool_inner(&action, root_run, resume_ctx.as_ref(), None)
.await
{
Ok(obs) => obs,
Err(e @ AgentError::ToolExecutionError(_)) => tool_error_observation(&e),
Err(e) => return Err(e),
};
if self.verbose {
log::info!("Observation: {}", observation);
}
intermediate_steps.push(AgentStep::new(action, observation));
}
AgentOutput::Actions(actions) => {
metrics.tool_calls += actions.len();
if self.verbose {
log::info!("Parallel actions: {} count", actions.len());
for action in &actions {
log::info!(" - {}({})", action.tool, action.tool_input);
}
}
// Budget gate: check cumulative call count and wall-clock before the
// tool runs.
if let Some(err) = budget_tool_gate(self.budget.as_ref(), metrics, loop_start) {
return Err(err);
}
let observations = self.execute_tools_parallel(&actions, root_run).await?;
if self.verbose {
for (i, obs) in observations.iter().enumerate() {
log::info!("Observation {}: {}", i + 1, obs);
}
}
for (action, observation) in actions.into_iter().zip(observations.into_iter()) {
intermediate_steps.push(AgentStep::new(action, observation));
}
}
}
}
// 0.22.0 C4 fix: the iteration cap is a failure, not a silent
// placeholder. Default policy fails the run with `MaxIterationsReached`
// so callers (PlanExecute included) can distinguish "did not converge"
// from a real answer; `MaxIterationsPolicy::Placeholder` restores the
// legacy ≤ 0.21.x behavior.
log::warn!(
"agent reached max iterations {} without returning a final answer (policy: {:?})",
self.max_iterations,
self.on_max_iterations
);
if self.on_max_iterations == MaxIterationsPolicy::Error {
return Err(AgentError::MaxIterationsReached);
}
let finish = self.agent.return_stopped_response(&intermediate_steps);
Ok(finish.output().unwrap_or("").to_string())
}
/// Executes multiple tools in parallel.
///
/// Collects successful results and reports failures as error observations
/// rather than discarding partial results when one tool fails. A tool that
/// ran and failed (`ToolExecutionError`) or that was never registered
/// (`ToolNotFound` — e.g. an LLM hallucinated name, 0.20.0 A-H3) becomes an
/// observation, so the batch's other results survive and the loop can
/// recover. Non-recoverable framework guardrails (`ControlAbort`, permission
/// policy, hook `Reject`) still abort the whole batch hard.
/// Concurrency is capped by the executor's global `concurrency_sem`.
async fn execute_tools_parallel(
&self,
actions: &[AgentAction],
root_run: &RunTree,
) -> Result<Vec<String>, AgentError> {
use futures_util::future::join_all;
let sem = self.concurrency_sem.clone();
let futures = actions.iter().map(|action| {
let sem = sem.clone();
async move {
let _permit = sem
.acquire_owned()
.await
.map_err(|e| AgentError::Other(format!("concurrency semaphore closed: {e}")))?;
self.execute_tool(action, root_run).await
}
});
let results = join_all(futures).await;
let mut observations = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(output) => observations.push(output),
// 0.20.0 S3.1:工具**执行**错误(工具真的跑了、失败返回 ToolError)
// 转 observation。
Err(e @ AgentError::ToolExecutionError(_)) => {
observations.push(tool_error_observation(&e))
}
// 0.20.0 A-H3:并行 batch 中单个未注册工具名(LLM 幻觉)也转
// observation——同批其余工具的真实结果得以保留,agent 可自救。
// 这是并行路径独有的宽松:顺序路径引用一个不存在的工具没有任何
// 部分结果可保留,仍硬失败(P2-2 锁存)。
Err(AgentError::ToolNotFound(name)) => {
observations.push(format!("[Tool not found: {name}]"))
}
// 框架级守卫拒绝(ControlAbort 交接环与深度中止 / 权限策略 /
// hook 拒绝)仍硬失败上抛:agent 无法靠重规划绕过它们。
Err(e) => return Err(e),
}
}
Ok(observations)
}
/// Executes a single tool (no resume context, no pre-decided approval).
async fn execute_tool(
&self,
action: &AgentAction,
root_run: &RunTree,
) -> Result<String, AgentError> {
self.execute_tool_inner(action, root_run, None, None).await
}
/// Executes a single tool with optional cross-process resume integration.
///
/// - `resume_ctx`: when non-None, the checkpoint (including the final
/// `tool_name` / `arguments` after synchronous-hook mutation) is persisted
/// **before** entering the approval gate to await approval, and cleared once the
/// decision **lands**. The parallel tool path (`execute_tools_parallel`) passes
/// `None` so concurrent multi-tool approvals never persist and cannot overwrite
/// each other's checkpoints.
/// - `pre_decided`: when non-None, the approval handler is skipped and the given
/// decision is used directly (cross-process resume injects the decision without
/// re-running approval; `resume_ctx` should then be `None` — the checkpoint was
/// already claimed in [`AgentExecutor::resume`](crate::executor::AgentExecutor::resume)).
pub(crate) async fn execute_tool_inner(
&self,
action: &AgentAction,
root_run: &RunTree,
resume_ctx: Option<&ResumeContext<'_>>,
pre_decided: Option<ApprovalDecision>,
) -> Result<String, AgentError> {
let tool = self
.tools
.iter()
.find(|t| t.name() == action.tool)
.ok_or_else(|| AgentError::ToolNotFound(action.tool.clone()))?;
let _input_str = match &action.tool_input {
ToolInput::String { value: s } => s.clone(),
ToolInput::Object { value: v } => serde_json::to_string(v)
.map_err(|e| AgentError::Other(format!("Failed to serialize tool input: {}", e)))?,
};
// Run hooks: on_before_tool_call
let mut tool_ctx = ToolCallContext {
name: action.tool.clone(),
arguments: match &action.tool_input {
ToolInput::String { value: s } => {
// If the string is valid JSON, parse it as a Value to avoid
// double-encoding when serde_json::to_string() is called later.
// Otherwise wrap it as Value::String.
serde_json::from_str::<serde_json::Value>(s)
.unwrap_or(serde_json::Value::String(s.clone()))
}
ToolInput::Object { value: v } => v.clone(),
},
tool_id: String::new(),
};
for hook in &self.hooks {
match hook.on_before_tool_call(&mut tool_ctx) {
ToolCallAction::Continue => {}
ToolCallAction::Modify { name, arguments } => {
tool_ctx.name = name;
tool_ctx.arguments = arguments;
}
ToolCallAction::Reject { reason } => {
return Err(AgentError::Other(format!(
"Tool call rejected by hook: {}",
reason
)));
}
ToolCallAction::Skip => {
return Ok("[Skipped by hook]".to_string());
}
}
}
// Approval gate (§4.2) + cross-process resume (§4.2): after the sync hooks,
// before the actual execution.
// - Normal invoke: no pre_decided, goes through the handler; persists the
// checkpoint before approval, clears it once the decision lands.
// - Resume: injects pre_decided, no persist/clear (the checkpoint was already
// claimed in resume()).
// Deny is isomorphic with ToolCallAction::Skip — the rejection is fed back as an
// observation; the tool does not run and the loop is not interrupted; the next
// plan round sees the rejection observation and adjusts on its own.
let deny_reason: Option<String> = if let Some(pre) = pre_decided {
apply_approval_decision(pre, &mut tool_ctx)
} else if let Some(handler) = &self.approval {
// Cross-process resume: persist before approval. The sync hooks have already
// run, so this is the final value the approval sees.
if let Some(ctx) = resume_ctx {
let mut pending = ctx.pending.clone();
pending.tool_name = tool_ctx.name.clone();
pending.arguments = tool_ctx.arguments.clone();
pending.tool_id = tool_ctx.tool_id.clone();
if let Err(e) = ctx.store.save_pending(&pending).await {
log::warn!(
target: "lc_agents::resume",
"failed to persist pending approval: {}",
e
);
}
}
apply_approval_decision(handler.approve(&tool_ctx).await, &mut tool_ctx)
} else {
None
};
// The approval decision has landed: clear the checkpoint (Allow / Modify continue
// execution; Deny returns the rejection observation).
if let Some(ctx) = resume_ctx {
if let Err(e) = ctx.store.clear_pending().await {
log::warn!(
target: "lc_agents::resume",
"failed to clear pending approval: {}",
e
);
}
}
if let Some(reason) = deny_reason {
return Ok(format!("[DENIED by approval: {reason}]"));
}
let tool_name = tool_ctx.name.clone();
// P2-9: tool permission policy (permission tiering + sandbox gate). Allows when
// unconfigured.
if let Some(policy) = &self.tool_policy {
policy.check(&tool_name)?;
}
// A2 Rule of Two (v0.22.1 §S8): a tool that arms all three risk properties
// (untrusted-input + sensitive-access + state-changing) is blocked before
// execution; the loop gets a rejection observation it can re-plan around.
// Default off — an undeclared tool has an all-false profile (count 0) and is
// never intercepted.
if self.rule_of_two && tool.risk().count_armed() >= 3 {
log::warn!(
target: "lc_agents::rule_of_two",
"blocked high-risk tool '{}' (risk={}/3)",
tool_name,
tool.risk().count_armed()
);
return Ok(
"[BLOCKED by Rule of Two: tool declares untrusted-input + sensitive-access + state-changing]"
.to_string(),
);
}
let input_for_tool = serde_json::to_string(&tool_ctx.arguments)
.unwrap_or_else(|_| tool_ctx.arguments.to_string());
let mut tool_run = root_run.create_child(
&tool_name,
RunType::Tool,
json!({"input": input_for_tool.clone()}),
);
if let Some(ref callbacks) = self.callbacks {
for handler in callbacks.handlers() {
handler
.on_tool_start(&tool_run, &tool_name, &input_for_tool)
.await;
}
}
let tool_started = std::time::Instant::now();
let result = run_tool_with_timeout(tool, input_for_tool.clone(), self.tool_timeout).await;
let tool_duration_ms = tool_started.elapsed().as_millis();
let trace = root_run
.trace_id
.map(|id| id.to_string())
.unwrap_or_default();
match result {
Ok(output) => {
// P1-6: tool call audit log with trace/input/duration/outcome.
log::info!(
target: "lc_agents::audit",
"tool_call trace_id={} name={} input={} duration_ms={} outcome=ok",
trace,
tool_name,
input_for_tool,
tool_duration_ms
);
tool_run.end(json!({"output": output.clone()}));
if let Some(ref callbacks) = self.callbacks {
for handler in callbacks.handlers() {
handler.on_tool_end(&tool_run, &output).await;
}
}
// Run hooks: on_after_tool_call
let mut result_ctx = ToolResultContext {
name: tool_name,
result: output.clone(),
tool_id: String::new(),
};
for hook in &self.hooks {
if let Err(e) = hook.on_after_tool_call(&mut result_ctx) {
log::warn!("Hook on_after_tool_call error: {}", e);
}
}
// A1 (v0.22.1 §S8): when spotlighting is on, wrap the observation so the
// model reads untrusted tool output as delimited data.
let observed = if self.spotlight_tool_output {
super::tools::wrap_tool_output(&result_ctx.result)
} else {
result_ctx.result
};
Ok(observed)
}
Err(e) => {
log::info!(
target: "lc_agents::audit",
"tool_call trace_id={} name={} input={} duration_ms={} outcome=error:{}",
trace,
tool_name,
input_for_tool,
tool_duration_ms,
e
);
tool_run.end_with_error(e.to_string());
if let Some(ref callbacks) = self.callbacks {
for handler in callbacks.handlers() {
handler.on_tool_error(&tool_run, &e.to_string()).await;
}
}
// 0.20.0 S3.1:框架级控制中止(如交接环/深度守卫,见 ToolError::ControlAbort)
// 是「拒绝执行」而非「执行失败」,走 Other 硬失败上抛;其余 ToolError
// (ExecutionFailed/Timeout/McpError/InvalidInput/ToolNotFound)才包装成
// ToolExecutionError,由循环软化成 observation。两者在调用方必须可区分。
match e {
ToolError::ControlAbort(msg) => {
Err(AgentError::Other(format!("Tool call aborted: {msg}")))
}
other => Err(AgentError::ToolExecutionError(other.to_string())),
}
}
}
}
}