rucora 0.1.5

High-performance, type-safe LLM agent framework with built-in tools and multi-provider support
Documentation
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
//! 工具执行模块
//!
//! 负责执行工具调用,包括策略检查、观测器通知、重试、超时、熔断、缓存等。

use std::sync::{Arc, LazyLock};

use regex::Regex;
use rucora_core::channel::ChannelObserver;
use rucora_core::error::{AgentError, ToolError};
use rucora_core::provider::types::{ChatMessage, Role};
use rucora_core::tool::types::{DEFAULT_TOOL_OUTPUT_MAX_BYTES, ToolCall, ToolResult};
use serde_json::{Value, json};
use tracing::{debug, info, warn};

// ========== Credential 清洗 ==========

/// 敏感凭据匹配正则(参考 zeroclaw scrub_credentials)
static SENSITIVE_KV_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(?i)(token|api[_-]?key|password|secret|user[_-]?key|bearer|credential)["']?\s*[:=]\s*(?:"([^"]{8,})"|'([^']{8,})'|([a-zA-Z0-9_\-\.]{8,}))"#,
    )
    .expect("credential regex must compile")
});

/// 清洗工具输出中的敏感凭据,防止 API key、token 等通过 LLM 上下文泄露。
///
/// 保留凭据值前 4 个字符作为调试上下文,剩余部分替换为 `[REDACTED]`。
pub(crate) fn scrub_credentials(input: &str) -> String {
    SENSITIVE_KV_REGEX
        .replace_all(input, |caps: &regex::Captures| {
            let full_match = &caps[0];
            let key = &caps[1];
            let val = caps
                .get(2)
                .or_else(|| caps.get(3))
                .or_else(|| caps.get(4))
                .map_or("", |m| m.as_str());

            // 保留前 4 个字符作为调试上下文,截断时不破坏 UTF-8 边界
            let prefix = if val.len() > 4 {
                val.char_indices()
                    .nth(4)
                    .map_or(val, |(byte_idx, _)| &val[..byte_idx])
            } else {
                ""
            };

            if full_match.contains(':') {
                if full_match.contains('"') {
                    format!("\"{key}\": \"{prefix}*[REDACTED]\"")
                } else {
                    format!("{key}: {prefix}*[REDACTED]")
                }
            } else if full_match.contains('=') {
                if full_match.contains('"') {
                    format!("{key}=\"{prefix}*[REDACTED]\"")
                } else {
                    format!("{key}={prefix}*[REDACTED]")
                }
            } else {
                format!("{key}: {prefix}*[REDACTED]")
            }
        })
        .to_string()
}

use crate::agent::policy::{ToolCallContext, ToolPolicy};
use crate::agent::tool_call_config::{
    TimeoutConfig, ToolCallEnhancedConfig, ToolCallEnhancedRuntime,
};
use crate::agent::tool_registry::ToolRegistry;
use crate::middleware::MiddlewareChain;

// ========== 工具函数 ==========

fn truncate_utf8_to_bytes(s: &str, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s.to_string();
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    let mut out = s[..end].to_string();
    out.push_str("\n... [output truncated]");
    out
}

fn apply_output_limit(payload: Value, max_bytes: usize) -> Value {
    let serialized = payload.to_string();
    let truncated = serialized.len() > max_bytes;
    let limited_payload = if truncated {
        Value::String(truncate_utf8_to_bytes(&serialized, max_bytes))
    } else {
        payload
    };

    let mut obj = match limited_payload {
        Value::Object(map) => Value::Object(map),
        other => json!({"value": other}),
    };

    if let Some(map) = obj.as_object_mut() {
        map.insert("truncated".to_string(), Value::Bool(truncated));
        map.insert("max_bytes".to_string(), json!(max_bytes));
    }
    obj
}

pub(crate) async fn execute_tool_call_with_policy_and_observer(
    tools: &ToolRegistry,
    policy: &Arc<dyn ToolPolicy>,
    observer: &Arc<dyn ChannelObserver>,
    call: &ToolCall,
) -> Result<ToolResult, AgentError> {
    // 调用带中间件的版本(无中间件)
    execute_tool_call_with_middleware(tools, policy, observer, call, &MiddlewareChain::new()).await
}

pub(crate) async fn execute_tool_call_with_middleware(
    tools: &ToolRegistry,
    policy: &Arc<dyn ToolPolicy>,
    observer: &Arc<dyn ChannelObserver>,
    call: &ToolCall,
    middleware_chain: &MiddlewareChain,
) -> Result<ToolResult, AgentError> {
    // 创建可变副本用于中间件处理
    let mut call_mut = call.clone();

    // 执行工具调用前中间件钩子
    middleware_chain
        .process_tool_call_before(&mut call_mut)
        .await
        .map_err(|e| AgentError::Message(format!("工具调用前中间件处理失败:{e}")))?;

    let input_str = call_mut.input.to_string();
    let input_len = input_str.len();
    let input_preview = if input_len <= 800 {
        input_str.clone()
    } else {
        format!("{}...<truncated:{}>", &input_str[..800], input_len)
    };

    observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
        rucora_core::channel::types::DebugEvent {
            message: "tool_call.start".to_string(),
            data: Some(json!({
                "tool_name": call_mut.name.clone(),
                "tool_call_id": call_mut.id.clone(),
                "input_len": input_len
            })),
        },
    ));

    info!(
        tool.name = %call_mut.name,
        tool.call_id = %call_mut.id,
        tool.input_len = input_len,
        "tool_call.execute.start"
    );
    debug!(
        tool.name = %call_mut.name,
        tool.call_id = %call_mut.id,
        tool.input = %input_preview,
        "tool_call.execute.input"
    );

    let ctx = ToolCallContext {
        tool_call: call_mut.clone(),
    };

    if let Err(e) = policy.check(&ctx).await {
        match &e {
            ToolError::PolicyDenied { rule_id, reason } => {
                observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
                    rucora_core::channel::types::DebugEvent {
                        message: "tool_call.denied".to_string(),
                        data: Some(json!({
                            "tool_name": call.name.clone(),
                            "tool_call_id": call.id.clone(),
                            "rule_id": rule_id,
                            "reason": reason
                        })),
                    },
                ));
                let out = apply_output_limit(
                    json!({
                        "ok": false,
                        "error": {
                            "kind": "policy_denied",
                            "rule_id": rule_id,
                            "reason": reason
                        }
                    }),
                    DEFAULT_TOOL_OUTPUT_MAX_BYTES,
                );
                debug!(
                    tool.name = %call.name,
                    tool.call_id = %call.id,
                    policy.rule_id = %rule_id,
                    "tool_call.execute.denied"
                );
                return Ok(ToolResult {
                    tool_call_id: call.id.clone(),
                    output: out,
                });
            }
            _ => {
                observer.on_event(rucora_core::channel::types::ChannelEvent::Error(
                    rucora_core::channel::types::ErrorEvent {
                        kind: "policy".to_string(),
                        message: e.to_string(),
                        data: Some(json!({
                            "tool_name": call.name.clone(),
                            "tool_call_id": call.id.clone()
                        })),
                    },
                ));
                let out = apply_output_limit(
                    json!({
                        "ok": false,
                        "error": {
                            "kind": "policy_error",
                            "message": e.to_string()
                        }
                    }),
                    DEFAULT_TOOL_OUTPUT_MAX_BYTES,
                );
                debug!(
                    tool.name = %call.name,
                    tool.call_id = %call.id,
                    error = %e.to_string(),
                    "tool_call.execute.policy_error"
                );
                return Ok(ToolResult {
                    tool_call_id: call.id.clone(),
                    output: out,
                });
            }
        }
    }

    let start = std::time::Instant::now();

    let tool = tools.get(&call.name).ok_or_else(|| {
        AgentError::Message(format!(
            "未找到工具:{} (tool_call_id={})",
            call.name, call.id
        ))
    })?;

    let tool_output = match tool.call(call.input.clone()).await {
        Ok(v) => {
            // 对字符串输出进行凭据清洗
            let cleaned_v = match &v {
                Value::String(s) => Value::String(scrub_credentials(s)),
                other => {
                    // 对序列化后的 JSON 字符串清洗,再反序列化回来
                    let serialized = other.to_string();
                    let cleaned = scrub_credentials(&serialized);
                    serde_json::from_str::<Value>(&cleaned).unwrap_or(Value::String(cleaned))
                }
            };
            json!({"ok": true, "output": cleaned_v})
        }
        Err(ToolError::PolicyDenied { rule_id, reason }) => {
            observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
                rucora_core::channel::types::DebugEvent {
                    message: "tool_call.denied".to_string(),
                    data: Some(json!({
                        "tool_name": call.name.clone(),
                        "tool_call_id": call.id.clone(),
                        "rule_id": rule_id,
                        "reason": reason
                    })),
                },
            ));
            json!({
                "ok": false,
                "error": {"kind": "policy_denied", "rule_id": rule_id, "reason": reason}
            })
        }
        Err(e) => {
            observer.on_event(rucora_core::channel::types::ChannelEvent::Error(
                rucora_core::channel::types::ErrorEvent {
                    kind: "tool".to_string(),
                    message: e.to_string(),
                    data: Some(json!({
                        "tool_name": call.name.clone(),
                        "tool_call_id": call.id.clone()
                    })),
                },
            ));
            json!({
                "ok": false,
                "error": {"kind": "tool_error", "message": e.to_string()}
            })
        }
    };

    let tool_output = apply_output_limit(tool_output, DEFAULT_TOOL_OUTPUT_MAX_BYTES);

    let output_preview = {
        const MAX: usize = 1200;
        let s = tool_output.to_string();
        if s.len() <= MAX {
            s
        } else {
            // 在字符边界处截断,避免 UTF-8 错误
            // 找到第一个超过 MAX 字节的位置的前一个字符边界
            let truncation_point = s
                .char_indices()
                .find(|(idx, _)| *idx >= MAX)
                .map_or(s.len(), |(idx, _)| idx);

            format!("{}...<truncated:{}>", &s[..truncation_point], s.len())
        }
    };

    let elapsed_ms = start.elapsed().as_millis() as u64;
    let output_len = tool_output.to_string().len();

    observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
        rucora_core::channel::types::DebugEvent {
            message: "tool_call.done".to_string(),
            data: Some(json!({
                "tool_name": call.name.clone(),
                "tool_call_id": call.id.clone(),
                "output_len": output_len,
                "elapsed_ms": elapsed_ms
            })),
        },
    ));

    info!(
        tool.name = %call.name,
        tool.call_id = %call.id,
        tool.output_len = output_len,
        tool.elapsed_ms = elapsed_ms,
        "tool_call.execute.done"
    );

    debug!(
        tool.name = %call.name,
        tool.call_id = %call.id,
        tool.output = %output_preview,
        "tool_call.execute.output"
    );

    // 构建结果
    let mut result = ToolResult {
        tool_call_id: call.id.clone(),
        output: tool_output,
    };

    // 执行工具调用后中间件钩子
    middleware_chain
        .process_tool_call_after(&mut result)
        .await
        .map_err(|e| AgentError::Message(format!("工具调用后中间件处理失败:{e}")))?;

    Ok(result)
}

/// 带增强配置(重试 + 超时 + 熔断 + 缓存)的工具执行函数。
///
/// 在现有 `execute_tool_call_with_middleware` 基础上增加可靠性增强。
/// 所有增强特性默认关闭,通过 `ToolCallEnhancedConfig` 启用。
pub(crate) async fn execute_tool_call_enhanced(
    tools: &ToolRegistry,
    policy: &Arc<dyn ToolPolicy>,
    observer: &Arc<dyn ChannelObserver>,
    call: &ToolCall,
    middleware_chain: &MiddlewareChain,
    enhanced_config: &ToolCallEnhancedConfig,
    runtime: &ToolCallEnhancedRuntime,
) -> Result<ToolResult, AgentError> {
    let tool_name = call.name.as_str();

    // --- 缓存命中检查 ---
    if enhanced_config.cache.enabled
        && let Some(cached) = runtime.cache.get(tool_name, &call.input).await
    {
        observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
            rucora_core::channel::types::DebugEvent {
                message: "tool_call.cache_hit".to_string(),
                data: Some(json!({
                    "tool_name": tool_name,
                    "tool_call_id": call.id,
                })),
            },
        ));
        debug!(tool.name = %tool_name, tool.call_id = %call.id, "tool_call.cache_hit");
        return Ok(ToolResult {
            tool_call_id: call.id.clone(),
            output: cached,
        });
    }

    // --- 熔断器检查 ---
    if enhanced_config.circuit_breaker.enabled
        && !runtime
            .circuit_breaker
            .can_pass(tool_name, &enhanced_config.circuit_breaker)
            .await
    {
        let state = runtime.circuit_breaker.get_state(tool_name).await;
        observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
            rucora_core::channel::types::DebugEvent {
                message: "tool_call.circuit_breaker_open".to_string(),
                data: Some(json!({
                    "tool_name": tool_name,
                    "tool_call_id": call.id,
                    "circuit_state": format!("{:?}", state),
                })),
            },
        ));
        warn!(
            tool.name = %tool_name,
            tool.call_id = %call.id,
            "tool_call.circuit_breaker_open"
        );
        let out = apply_output_limit(
            json!({
                "ok": false,
                "error": {
                    "kind": "circuit_breaker_open",
                    "message": format!("工具 '{tool_name}' 熔断器已开启,调用被拒绝"),
                    "circuit_state": format!("{:?}", state),
                }
            }),
            DEFAULT_TOOL_OUTPUT_MAX_BYTES,
        );
        return Ok(ToolResult {
            tool_call_id: call.id.clone(),
            output: out,
        });
    }

    // --- 重试循环 ---
    let max_retries = enhanced_config.retry.max_retries;
    let mut attempt = 0u32;

    loop {
        let result = execute_single_with_timeout(
            tools,
            policy,
            observer,
            call,
            middleware_chain,
            &enhanced_config.timeout,
        )
        .await;

        match result {
            Ok(ref tool_result) => {
                // 判断是否是逻辑上的失败(ok=false)
                let is_error = !tool_result
                    .output
                    .get("ok")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(true);

                if is_error
                    && attempt < max_retries
                    && enhanced_config.retry.should_retry(&tool_result.output)
                {
                    let delay = enhanced_config.retry.delay_for(attempt);
                    observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
                        rucora_core::channel::types::DebugEvent {
                            message: "tool_call.retry".to_string(),
                            data: Some(json!({
                                "tool_name": tool_name,
                                "tool_call_id": call.id,
                                "attempt": attempt + 1,
                                "max_retries": max_retries,
                                "delay_ms": delay.as_millis(),
                            })),
                        },
                    ));
                    warn!(
                        tool.name = %tool_name,
                        attempt = attempt + 1,
                        max_retries,
                        delay_ms = delay.as_millis(),
                        "tool_call.retry"
                    );
                    tokio::time::sleep(delay).await;
                    attempt += 1;
                    continue;
                }

                // 记录熔断器结果
                if enhanced_config.circuit_breaker.enabled {
                    if is_error {
                        runtime
                            .circuit_breaker
                            .record_failure(tool_name, &enhanced_config.circuit_breaker)
                            .await;
                    } else {
                        runtime.circuit_breaker.record_success(tool_name).await;
                    }
                }

                // 写入缓存(仅成功结果)
                if enhanced_config.cache.enabled && !is_error {
                    let ttl = enhanced_config.cache.get_ttl(tool_name);
                    runtime
                        .cache
                        .set(
                            tool_name,
                            &call.input,
                            tool_result.output.clone(),
                            ttl,
                            enhanced_config.cache.max_entries,
                        )
                        .await;
                }

                return result;
            }
            Err(ref e) => {
                // 执行框架错误的重试
                if attempt < max_retries {
                    let delay = enhanced_config.retry.delay_for(attempt);
                    observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
                        rucora_core::channel::types::DebugEvent {
                            message: "tool_call.retry".to_string(),
                            data: Some(json!({
                                "tool_name": tool_name,
                                "tool_call_id": call.id,
                                "attempt": attempt + 1,
                                "max_retries": max_retries,
                                "delay_ms": delay.as_millis(),
                                "error": e.to_string(),
                            })),
                        },
                    ));
                    warn!(
                        tool.name = %tool_name,
                        attempt = attempt + 1,
                        max_retries,
                        delay_ms = delay.as_millis(),
                        error = %e,
                        "tool_call.retry"
                    );
                    tokio::time::sleep(delay).await;
                    attempt += 1;

                    // 记录熔断器失败
                    if enhanced_config.circuit_breaker.enabled {
                        runtime
                            .circuit_breaker
                            .record_failure(tool_name, &enhanced_config.circuit_breaker)
                            .await;
                    }

                    continue;
                }

                // 记录最终失败到熔断器
                if enhanced_config.circuit_breaker.enabled {
                    runtime
                        .circuit_breaker
                        .record_failure(tool_name, &enhanced_config.circuit_breaker)
                        .await;
                }

                return result;
            }
        }
    }
}

/// 执行单次工具调用(含超时控制)
async fn execute_single_with_timeout(
    tools: &ToolRegistry,
    policy: &Arc<dyn ToolPolicy>,
    observer: &Arc<dyn ChannelObserver>,
    call: &ToolCall,
    middleware_chain: &MiddlewareChain,
    timeout_config: &TimeoutConfig,
) -> Result<ToolResult, AgentError> {
    let timeout = timeout_config.get_timeout(call.name.as_str());

    match timeout {
        Some(duration) => {
            match tokio::time::timeout(
                duration,
                execute_tool_call_with_middleware(tools, policy, observer, call, middleware_chain),
            )
            .await
            {
                Ok(result) => result,
                Err(_) => {
                    let tool_name = call.name.as_str();
                    observer.on_event(rucora_core::channel::types::ChannelEvent::Debug(
                        rucora_core::channel::types::DebugEvent {
                            message: "tool_call.timeout".to_string(),
                            data: Some(json!({
                                "tool_name": tool_name,
                                "tool_call_id": call.id,
                                "timeout_ms": duration.as_millis(),
                            })),
                        },
                    ));
                    warn!(
                        tool.name = %tool_name,
                        tool.call_id = %call.id,
                        timeout_ms = duration.as_millis(),
                        "tool_call.timeout"
                    );
                    let out = apply_output_limit(
                        json!({
                            "ok": false,
                            "error": {
                                "kind": "timeout",
                                "message": format!("工具 '{tool_name}' 执行超时({}ms)", duration.as_millis()),
                                "transient": true,
                            }
                        }),
                        DEFAULT_TOOL_OUTPUT_MAX_BYTES,
                    );
                    Ok(ToolResult {
                        tool_call_id: call.id.clone(),
                        output: out,
                    })
                }
            }
        }
        None => {
            execute_tool_call_with_middleware(tools, policy, observer, call, middleware_chain).await
        }
    }
}

pub(crate) fn tool_result_to_message(result: &ToolResult, tool_name: &str) -> ChatMessage {
    let payload = Value::Object(
        [
            (
                "tool_call_id".to_string(),
                Value::String(result.tool_call_id.clone()),
            ),
            ("output".to_string(), result.output.clone()),
        ]
        .into_iter()
        .collect(),
    );

    ChatMessage {
        role: Role::Tool,
        content: payload.to_string(),
        name: Some(tool_name.to_string()),
    }
}