microclaw-engine 0.10.1

Channel-independent Agent Engine and default services for MicroClaw
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! Parallel tool execution within a single agent turn.
//!
//! When the LLM returns multiple tool_use blocks, this module partitions them into
//! execution "waves" based on their concurrency class and runs safe subsets in parallel
//! via `tokio::JoinSet`.

use std::collections::HashMap;
use std::sync::Arc;

use serde_json::Value;
use tracing::{info, warn};

use crate::hooks::HookOutcome;
use crate::internal::observability::traces::{kv, new_span_id, now_unix_nano, SpanData};
use crate::internal::tool_runtime::runtime::{
    parse_concurrency_class, tool_concurrency_class, ToolConcurrencyClass, ToolResult,
};
use crate::runtime::AppState;
use crate::tools::ToolAuthContext;
use microclaw_core::llm_types::ContentBlock;
use opentelemetry_proto::tonic::trace::v1::Status;

use crate::agent_engine::AgentEvent;
use crate::internal::observability::traces::OtlpTraceExporter;
use microclaw_core::runtime_event::{RuntimePlanStep, RuntimePlanStepStatus, RuntimeProcessKind};
use tokio::sync::mpsc::UnboundedSender;

/// A single pending tool call extracted from the LLM response.
#[derive(Clone, Debug)]
pub struct PendingToolCall {
    pub id: String,
    pub name: String,
    pub input: Value,
}

/// Mutable context accumulated across tool executions within a turn.
pub struct ToolBatchContext {
    pub failed_tools: std::collections::BTreeSet<String>,
    pub failed_tool_details: Vec<String>,
    pub seen_failed_tool_details: std::collections::HashSet<String>,
    pub consecutive_send_message_calls: usize,
    pub skill_env_files: Vec<String>,
    pub tool_auth: ToolAuthContext,
    pub waiting_for_user_approval: bool,
    pub waiting_approval_tool: Option<String>,
    /// Human-readable preview of the operation requesting approval (e.g., the
    /// exact bash command). Surfaced to the operator so they can confirm
    /// without having to scroll back through tool-call JSON.
    pub waiting_approval_preview: Option<String>,
}

/// Metrics counters for tool execution.
pub struct ToolMetrics {
    pub tool_calls: i64,
    pub tool_errors: i64,
}

/// Resolve the effective concurrency class for a tool, respecting config overrides.
fn resolve_concurrency_class(
    name: &str,
    overrides: &HashMap<String, String>,
) -> ToolConcurrencyClass {
    if let Some(override_str) = overrides.get(name) {
        if let Some(class) = parse_concurrency_class(override_str) {
            return class;
        }
        warn!(
            "Invalid tool_concurrency_override for '{}': '{}'; using default",
            name, override_str
        );
    }
    tool_concurrency_class(name)
}

/// Partition tool calls into execution waves based on concurrency classes.
///
/// Rules:
/// 1. All ReadOnly -> single wave, all parallel
/// 2. Mixed ReadOnly + others -> wave 1 = ReadOnly parallel, then rest sequentially
/// 3. Exclusive -> runs alone in its own wave
fn partition_into_waves(
    calls: &[PendingToolCall],
    overrides: &HashMap<String, String>,
) -> Vec<Vec<usize>> {
    if calls.is_empty() {
        return Vec::new();
    }
    if calls.len() == 1 {
        return vec![vec![0]];
    }

    let classes: Vec<ToolConcurrencyClass> = calls
        .iter()
        .map(|c| resolve_concurrency_class(&c.name, overrides))
        .collect();

    let mut readonly_indices = Vec::new();
    let mut sideeffect_indices = Vec::new();
    let mut exclusive_indices = Vec::new();

    for (i, class) in classes.iter().enumerate() {
        match class {
            ToolConcurrencyClass::ReadOnly => readonly_indices.push(i),
            ToolConcurrencyClass::SideEffect => sideeffect_indices.push(i),
            ToolConcurrencyClass::Exclusive => exclusive_indices.push(i),
        }
    }

    let mut waves = Vec::new();

    // Wave 1: all ReadOnly tools in parallel
    if !readonly_indices.is_empty() {
        waves.push(readonly_indices);
    }

    // Then: SideEffect tools, one per wave (sequential)
    for idx in sideeffect_indices {
        waves.push(vec![idx]);
    }

    // Then: Exclusive tools, one per wave
    for idx in exclusive_indices {
        waves.push(vec![idx]);
    }

    waves
}

/// Execute a batch of tool calls, optionally in parallel.
///
/// When `parallel_enabled` is false, all tools execute sequentially (existing behavior).
/// When true, tools are partitioned into waves and ReadOnly tools within a wave run concurrently.
#[expect(clippy::too_many_arguments)]
pub async fn execute_tool_batch(
    state: &AppState,
    calls: &[PendingToolCall],
    ctx: &mut ToolBatchContext,
    metrics: &mut ToolMetrics,
    event_tx: Option<&UnboundedSender<AgentEvent>>,
    chat_id: i64,
    iteration: usize,
    caller_channel: &str,
    explicit_user_approval: bool,
    trace_id: &[u8],
    parent_span_id: &[u8],
) -> Vec<ContentBlock> {
    let max_concurrency = state.config.parallel_tool_max_concurrency;

    if calls.len() <= 1 {
        // Sequential execution (original behavior)
        return execute_sequentially(
            state,
            calls,
            ctx,
            metrics,
            event_tx,
            chat_id,
            iteration,
            caller_channel,
            explicit_user_approval,
            trace_id,
            parent_span_id,
        )
        .await;
    }

    let waves = partition_into_waves(calls, &state.config.tool_concurrency_overrides);
    let mut all_results: Vec<(usize, ContentBlock)> = Vec::with_capacity(calls.len());

    for (wave_idx, wave) in waves.iter().enumerate() {
        if let Some(tx) = event_tx {
            let _ = tx.send(AgentEvent::ToolWaveStart {
                wave: wave_idx + 1,
                tool_count: wave.len(),
            });
        }

        if wave.len() == 1 {
            // Single tool in wave — execute inline (no spawn overhead)
            let idx = wave[0];
            let result = execute_single_tool(
                state,
                &calls[idx],
                ctx,
                metrics,
                event_tx,
                chat_id,
                iteration,
                caller_channel,
                explicit_user_approval,
                trace_id,
                parent_span_id,
            )
            .await;
            all_results.push((idx, result));
        } else {
            // Multiple tools — run in parallel with JoinSet
            let results = execute_wave_parallel(
                state,
                calls,
                wave,
                ctx,
                metrics,
                event_tx,
                chat_id,
                iteration,
                caller_channel,
                explicit_user_approval,
                trace_id,
                parent_span_id,
                max_concurrency,
            )
            .await;
            all_results.extend(results);
        }

        if let Some(tx) = event_tx {
            let _ = tx.send(AgentEvent::ToolWaveComplete { wave: wave_idx + 1 });
        }
    }

    // Sort by original index to preserve order
    all_results.sort_by_key(|(idx, _)| *idx);
    all_results.into_iter().map(|(_, block)| block).collect()
}

/// Execute all tools sequentially (the original behavior).
#[expect(clippy::too_many_arguments)]
async fn execute_sequentially(
    state: &AppState,
    calls: &[PendingToolCall],
    ctx: &mut ToolBatchContext,
    metrics: &mut ToolMetrics,
    event_tx: Option<&UnboundedSender<AgentEvent>>,
    chat_id: i64,
    iteration: usize,
    caller_channel: &str,
    explicit_user_approval: bool,
    trace_id: &[u8],
    parent_span_id: &[u8],
) -> Vec<ContentBlock> {
    let mut results = Vec::with_capacity(calls.len());
    for call in calls {
        let block = execute_single_tool(
            state,
            call,
            ctx,
            metrics,
            event_tx,
            chat_id,
            iteration,
            caller_channel,
            explicit_user_approval,
            trace_id,
            parent_span_id,
        )
        .await;
        results.push(block);
    }
    results
}

/// Execute a single tool call with all the hooks, tracing, and guardrail logic.
#[expect(clippy::too_many_arguments)]
async fn execute_single_tool(
    state: &AppState,
    call: &PendingToolCall,
    ctx: &mut ToolBatchContext,
    metrics: &mut ToolMetrics,
    event_tx: Option<&UnboundedSender<AgentEvent>>,
    chat_id: i64,
    iteration: usize,
    caller_channel: &str,
    explicit_user_approval: bool,
    trace_id: &[u8],
    parent_span_id: &[u8],
) -> ContentBlock {
    let id = &call.id;
    let name = &call.name;
    let input = &call.input;

    // Malformed tool name check
    if name.trim().is_empty() {
        warn!(
            chat_id,
            iteration,
            tool_use_id = %id,
            "Skipping malformed tool call with empty tool name"
        );
        return ContentBlock::ToolResult {
            tool_use_id: id.clone(),
            content: "Malformed tool call: missing tool name. Retry with a valid registered tool."
                .to_string(),
            is_error: Some(true),
        };
    }

    // send_message consecutive call guardrail
    if name != "send_message" {
        ctx.consecutive_send_message_calls = 0;
    } else if ctx.consecutive_send_message_calls >= 3 {
        warn!(
            chat_id,
            iteration, "Guardrail: blocking repeated send_message loop"
        );
        let content = "send_message blocked: too many consecutive send_message calls in one request. Use normal assistant reply for final output instead of repeatedly calling send_message.".to_string();
        ctx.failed_tools.insert(name.clone());
        let detail = format!("send_message: {content}");
        if ctx.seen_failed_tool_details.insert(detail.clone()) {
            ctx.failed_tool_details.push(detail);
        }
        return ContentBlock::ToolResult {
            tool_use_id: id.clone(),
            content,
            is_error: Some(true),
        };
    }

    // Feishu send_message text restriction
    let is_feishu_turn = caller_channel.starts_with("feishu") || caller_channel.starts_with("lark");
    let send_message_has_attachment = input
        .get("attachment_path")
        .and_then(|v| v.as_str())
        .map(|v| !v.trim().is_empty())
        .unwrap_or(false);
    if name == "send_message" && is_feishu_turn && !send_message_has_attachment {
        return ContentBlock::ToolResult {
            tool_use_id: id.clone(),
            content: "send_message text replies are disabled for Feishu runtime turns; return the final assistant text directly so channel reaction/text delivery can be handled correctly. If you need to send a file, call send_message with attachment_path.".to_string(),
            is_error: Some(true),
        };
    }

    // Before-tool hook
    let mut effective_input = input.clone();
    if let Ok(hook_outcome) = state
        .hooks
        .run_before_tool(chat_id, caller_channel, iteration, name, &effective_input)
        .await
    {
        match hook_outcome {
            HookOutcome::Block { reason } => {
                return ContentBlock::ToolResult {
                    tool_use_id: id.clone(),
                    content: if reason.trim().is_empty() {
                        format!("tool '{}' blocked by policy hook", name)
                    } else {
                        reason
                    },
                    is_error: Some(true),
                };
            }
            HookOutcome::Allow { patches } => {
                for patch in patches {
                    if let Some(v) = patch.get("tool_input") {
                        effective_input = v.clone();
                    }
                }
            }
        }
    }

    // Emit ToolStart event
    if let Some(tx) = event_tx {
        let _ = tx.send(AgentEvent::ToolStart {
            call_id: id.clone(),
            name: name.clone(),
            input: effective_input.clone(),
        });
    }
    info!(chat_id, tool = %name, iteration, "Executing tool");

    let started = std::time::Instant::now();
    let mut executed_input = effective_input.clone();
    let tool_span_id = new_span_id();
    let tool_start = now_unix_nano();
    metrics.tool_calls += 1;

    // Execute tool
    let mut result = state
        .tools
        .execute_with_auth(name, executed_input.clone(), &ctx.tool_auth)
        .await;

    // Trace span
    if let Some(exp) = &state.trace_exporter {
        emit_tool_span(
            exp,
            trace_id,
            tool_span_id,
            parent_span_id,
            name,
            &executed_input,
            &result,
            tool_start,
            "tool_execution",
        );
    }

    // Auto-retry on approval_required
    if result.is_error && result.error_type.as_deref() == Some("approval_required") {
        let can_retry_with_approval = if state.config.high_risk_tool_user_confirmation_required {
            explicit_user_approval
        } else {
            true
        };
        if can_retry_with_approval {
            executed_input = with_high_risk_approval_marker(&effective_input);
            if state.config.high_risk_tool_user_confirmation_required {
                info!("Retrying tool '{}' after explicit user approval", name);
            } else {
                info!("Auto-retrying tool '{}' after approval gate", name);
            }
            let retry_span_id = new_span_id();
            let retry_start = now_unix_nano();
            metrics.tool_calls += 1;

            result = state
                .tools
                .execute_with_auth(name, executed_input.clone(), &ctx.tool_auth)
                .await;

            if let Some(exp) = &state.trace_exporter {
                emit_tool_span(
                    exp,
                    trace_id,
                    retry_span_id,
                    parent_span_id,
                    name,
                    &executed_input,
                    &result,
                    retry_start,
                    "tool_execution_retry",
                );
            }
        } else if state.config.high_risk_tool_user_confirmation_required {
            ctx.waiting_for_user_approval = true;
            ctx.waiting_approval_tool = Some(name.clone());
            ctx.waiting_approval_preview = approval_preview(name, &executed_input);
        }
    }

    // activate_skill metadata handling
    if name == "activate_skill" && !result.is_error {
        if let Some(meta) = &result.metadata {
            if let Some(path) = meta.get("skill_env_file").and_then(|v| v.as_str()) {
                let path_str = path.to_string();
                if !ctx.skill_env_files.contains(&path_str) {
                    ctx.skill_env_files.push(path_str);
                    ctx.tool_auth.env_files = ctx.skill_env_files.clone();
                }
                if let Ok(files_json) = serde_json::to_string(&ctx.skill_env_files) {
                    let db = state.db.clone();
                    let _ = crate::internal::storage::db::call_blocking(db, move |db| {
                        db.save_session_skill_envs(chat_id, &files_json)
                    })
                    .await;
                }
            }
        }
    }

    // After-tool hook
    if let Ok(hook_outcome) = state
        .hooks
        .run_after_tool(
            chat_id,
            caller_channel,
            iteration,
            name,
            &executed_input,
            &result,
        )
        .await
    {
        match hook_outcome {
            HookOutcome::Block { reason } => {
                result.is_error = true;
                if !reason.trim().is_empty() {
                    result.content = reason;
                }
                if result.error_type.is_none() {
                    result.error_type = Some("hook_blocked".to_string());
                }
            }
            HookOutcome::Allow { patches } => {
                for patch in patches {
                    if let Some(v) = patch.get("content").and_then(|v| v.as_str()) {
                        result.content = v.to_string();
                    }
                    if let Some(v) = patch.get("is_error").and_then(|v| v.as_bool()) {
                        result.is_error = v;
                    }
                    if let Some(v) = patch
                        .get("error_type")
                        .and_then(|v| v.as_str())
                        .map(str::to_string)
                    {
                        result.error_type = Some(v);
                    }
                    if let Some(v) = patch
                        .get("status_code")
                        .and_then(|v| v.as_i64())
                        .map(|x| x as i32)
                    {
                        result.status_code = Some(v);
                    }
                }
            }
        }
    }

    // Error tracking
    if result.is_error && result.error_type.as_deref() != Some("approval_required") {
        let suppress = result
            .error_type
            .as_deref()
            .map(|t| t == "feishu_reaction_protocol_text" || t == "feishu_send_message_disabled")
            .unwrap_or(false);
        if !suppress {
            ctx.failed_tools.insert(name.clone());
            let detail = format_failed_action_for_user(name, &executed_input, &result.content);
            if ctx.seen_failed_tool_details.insert(detail.clone()) {
                ctx.failed_tool_details.push(detail);
            }
        }
        let preview = truncate_for_log(&result.content, 300);
        warn!(
            chat_id,
            tool = %name,
            iteration,
            error_type = ?result.error_type,
            "Tool execution failed: {}",
            preview
        );
    }

    // Emit ToolResult event
    if let Some(tx) = event_tx {
        let preview = truncate_for_log(&result.content, 160);
        let duration_ms = result
            .duration_ms
            .unwrap_or_else(|| started.elapsed().as_millis());
        let transport_duration_ms = u64::try_from(duration_ms).unwrap_or(u64::MAX);
        let _ = tx.send(AgentEvent::ToolResult {
            call_id: id.clone(),
            name: name.clone(),
            is_error: result.is_error,
            preview,
            duration_ms: transport_duration_ms,
            status_code: result.status_code,
            bytes: result.bytes,
            error_type: result.error_type.clone(),
        });
        emit_file_diff_event(tx, &result);
        emit_plan_update_event(tx, name, &executed_input, result.is_error);
        emit_process_output_event(tx, id, name, &executed_input, &result, duration_ms);
    }
    if result.is_error {
        metrics.tool_errors += 1;
    }
    if name == "send_message" {
        ctx.consecutive_send_message_calls += 1;
    }

    // Spill oversized tool results to an artifact and truncate the inline copy
    // so the message history stays cheap to replay. The agent can fetch the
    // full body via `fetch_artifact`. `fetch_artifact` itself is exempted to
    // avoid recursive truncation when the agent reads a slice.
    let content = if name == "fetch_artifact" {
        result.content
    } else {
        maybe_spill_to_artifact(state, chat_id, name, result.content).await
    };

    ContentBlock::ToolResult {
        tool_use_id: id.clone(),
        content,
        is_error: if result.is_error { Some(true) } else { None },
    }
}

/// Spill `content` to a `tool_result_artifacts` row when it exceeds the
/// configured threshold; the returned string keeps the head + tail and a
/// pointer the agent can pass to `fetch_artifact`. Falls back to the
/// untouched content on any storage error so a transient DB failure never
/// drops a tool result.
async fn maybe_spill_to_artifact(
    state: &AppState,
    chat_id: i64,
    tool_name: &str,
    content: String,
) -> String {
    let threshold = state.config.tool_result_truncation_threshold_chars;
    if threshold == 0 {
        return content;
    }
    let total_chars = content.chars().count();
    if total_chars <= threshold {
        return content;
    }

    let head_chars = state.config.tool_result_truncation_head_chars;
    let tail_chars = state.config.tool_result_truncation_tail_chars;
    let ttl_hours = state.config.tool_result_artifact_ttl_hours;

    // Guard against pathological config: head + tail must still leave room
    // for the truncation marker, otherwise truncation is pointless.
    if head_chars + tail_chars >= total_chars {
        return content;
    }

    let artifact_id = format!("art_{}", uuid::Uuid::new_v4().simple());
    let expires_at = (chrono::Utc::now() + chrono::Duration::hours(ttl_hours as i64)).to_rfc3339();

    let db = state.db.clone();
    let artifact_id_for_save = artifact_id.clone();
    let tool_name_for_save = tool_name.to_string();
    let content_for_save = content.clone();
    let saved = crate::internal::storage::db::call_blocking(db, move |db| {
        db.save_tool_artifact(
            &artifact_id_for_save,
            chat_id,
            &tool_name_for_save,
            &content_for_save,
            &expires_at,
        )
    })
    .await;

    if let Err(e) = saved {
        warn!(
            chat_id,
            tool = %tool_name,
            "Failed to persist tool artifact; returning untruncated content: {}",
            e
        );
        return content;
    }

    let head: String = content.chars().take(head_chars).collect();
    let tail: String = content.chars().skip(total_chars - tail_chars).collect();
    let hidden = total_chars - head_chars - tail_chars;
    format!(
        "{head}\n\n[--- {hidden} of {total_chars} characters truncated. \
         Full result saved as artifact `{artifact_id}` for {ttl_hours}h. \
         Call fetch_artifact(artifact_id=\"{artifact_id}\", offset=N, length=N) \
         to read more. ---]\n\n{tail}"
    )
}

/// Execute a wave of tools in parallel using futures::join_all.
///
/// Before-tool hooks run sequentially first, then tools execute concurrently,
/// then after-tool hooks are handled per-tool. This preserves hook ordering.
#[expect(clippy::too_many_arguments)]
async fn execute_wave_parallel(
    state: &AppState,
    calls: &[PendingToolCall],
    wave_indices: &[usize],
    ctx: &mut ToolBatchContext,
    metrics: &mut ToolMetrics,
    event_tx: Option<&UnboundedSender<AgentEvent>>,
    chat_id: i64,
    iteration: usize,
    caller_channel: &str,
    _explicit_user_approval: bool,
    _trace_id: &[u8],
    _parent_span_id: &[u8],
    _max_concurrency: usize,
) -> Vec<(usize, ContentBlock)> {
    info!(
        chat_id,
        wave_size = wave_indices.len(),
        "Executing tool wave in parallel"
    );

    // Pre-process: run before_tool hooks sequentially and prepare inputs.
    struct PreparedCall {
        idx: usize,
        name: String,
        effective_input: Value,
        skipped: Option<ContentBlock>,
    }

    let mut prepared = Vec::with_capacity(wave_indices.len());
    for &idx in wave_indices {
        let call = &calls[idx];
        let name = &call.name;
        let mut effective_input = call.input.clone();

        if let Some(tx) = event_tx {
            let _ = tx.send(AgentEvent::ToolStart {
                call_id: call.id.clone(),
                name: name.clone(),
                input: effective_input.clone(),
            });
        }

        let mut skipped = None;
        if let Ok(hook_outcome) = state
            .hooks
            .run_before_tool(chat_id, caller_channel, iteration, name, &effective_input)
            .await
        {
            match hook_outcome {
                HookOutcome::Block { reason } => {
                    skipped = Some(ContentBlock::ToolResult {
                        tool_use_id: call.id.clone(),
                        content: if reason.trim().is_empty() {
                            format!("tool '{}' blocked by policy hook", name)
                        } else {
                            reason
                        },
                        is_error: Some(true),
                    });
                }
                HookOutcome::Allow { patches } => {
                    for patch in patches {
                        if let Some(v) = patch.get("tool_input") {
                            effective_input = v.clone();
                        }
                    }
                }
            }
        }

        prepared.push(PreparedCall {
            idx,
            name: name.clone(),
            effective_input,
            skipped,
        });
    }

    // Execute non-skipped tools in parallel using futures::join_all.
    // This borrows state rather than requiring 'static, which avoids the Clone issue.
    let tool_auth = ctx.tool_auth.clone();
    let futures: Vec<_> = prepared
        .iter()
        .filter(|p| p.skipped.is_none())
        .map(|prep| {
            let tool_auth = tool_auth.clone();
            let name = prep.name.clone();
            let input = prep.effective_input.clone();
            let idx = prep.idx;
            async move {
                let started = std::time::Instant::now();
                let result = state
                    .tools
                    .execute_with_auth(&name, input.clone(), &tool_auth)
                    .await;
                let duration = started.elapsed().as_millis();
                (idx, name, input, result, duration)
            }
        })
        .collect();

    let parallel_results = futures_util::future::join_all(futures).await;

    let mut results: Vec<(usize, ContentBlock)> = Vec::with_capacity(prepared.len());

    // Add skipped results first
    for prep in &prepared {
        if let Some(block) = &prep.skipped {
            results.push((prep.idx, block.clone()));
        }
    }

    // Process parallel results
    for (idx, name, input, result, _duration) in parallel_results {
        let call_id = &calls[idx].id;
        metrics.tool_calls += 1;
        if result.is_error {
            metrics.tool_errors += 1;
            ctx.failed_tools.insert(name.clone());
        }
        if name == "send_message" {
            ctx.consecutive_send_message_calls += 1;
        }

        // Emit ToolResult event
        if let Some(tx) = event_tx {
            let preview = truncate_for_log(&result.content, 160);
            let duration_ms = result.duration_ms.unwrap_or(_duration);
            let transport_duration_ms = u64::try_from(duration_ms).unwrap_or(u64::MAX);
            let _ = tx.send(AgentEvent::ToolResult {
                call_id: call_id.clone(),
                name: name.clone(),
                is_error: result.is_error,
                preview,
                duration_ms: transport_duration_ms,
                status_code: result.status_code,
                bytes: result.bytes,
                error_type: result.error_type.clone(),
            });
            emit_file_diff_event(tx, &result);
            emit_plan_update_event(tx, &name, &input, result.is_error);
            emit_process_output_event(tx, call_id, &name, &input, &result, duration_ms);
        }

        results.push((
            idx,
            ContentBlock::ToolResult {
                tool_use_id: call_id.clone(),
                content: result.content,
                is_error: if result.is_error { Some(true) } else { None },
            },
        ));
    }

    results
}

fn emit_plan_update_event(
    tx: &UnboundedSender<AgentEvent>,
    tool_name: &str,
    input: &Value,
    is_error: bool,
) {
    if tool_name != "todo_write" || is_error {
        return;
    }
    let Some(todos) = input.get("todos").and_then(Value::as_array) else {
        return;
    };
    let steps = todos
        .iter()
        .filter_map(|todo| {
            let title = todo.get("task")?.as_str()?.trim();
            if title.is_empty() {
                return None;
            }
            let status = match todo.get("status")?.as_str()? {
                "pending" => RuntimePlanStepStatus::Pending,
                "in_progress" => RuntimePlanStepStatus::InProgress,
                "completed" => RuntimePlanStepStatus::Completed,
                _ => return None,
            };
            Some(RuntimePlanStep {
                title: title.to_string(),
                status,
            })
        })
        .collect();
    let _ = tx.send(AgentEvent::PlanUpdated { steps });
}

const MAX_PROCESS_OUTPUT_BYTES: usize = 16 * 1024;

fn emit_process_output_event(
    tx: &UnboundedSender<AgentEvent>,
    call_id: &str,
    tool_name: &str,
    input: &Value,
    result: &ToolResult,
    duration_ms: u128,
) {
    if tool_name != "bash" {
        return;
    }
    let Some(command) = input.get("command").and_then(Value::as_str) else {
        return;
    };
    let command = microclaw_core::redact::redact_secrets(command);
    let command = bounded_text(&command, 2_000).0;
    let output = microclaw_core::redact::redact_secrets(&result.content);
    let (output, truncated) = bounded_text(&output, MAX_PROCESS_OUTPUT_BYTES);
    let kind = if is_verification_command(&command) {
        RuntimeProcessKind::Verification
    } else {
        RuntimeProcessKind::Command
    };
    let _ = tx.send(AgentEvent::ProcessOutput {
        call_id: call_id.to_string(),
        command,
        output,
        exit_code: result.status_code,
        duration_ms: u64::try_from(duration_ms).unwrap_or(u64::MAX),
        truncated,
        kind,
    });
}

fn is_verification_command(command: &str) -> bool {
    let normalized = command.to_ascii_lowercase();
    [
        "cargo test",
        "cargo check",
        "cargo clippy",
        "npm test",
        "npm run test",
        "npm run build",
        "pnpm test",
        "pnpm build",
        "yarn test",
        "yarn build",
        "pytest",
        "go test",
        "swift test",
        "dotnet test",
        "mvn test",
        "gradle test",
    ]
    .iter()
    .any(|marker| normalized.contains(marker))
}

fn bounded_text(text: &str, limit: usize) -> (String, bool) {
    if text.len() <= limit {
        return (text.to_string(), false);
    }
    let half = limit / 2;
    let head_end = microclaw_core::text::floor_char_boundary(text, half);
    let mut tail_start = text.len() - half;
    while tail_start < text.len() && !text.is_char_boundary(tail_start) {
        tail_start += 1;
    }
    (
        format!(
            "{}\n\n[… {} bytes omitted …]\n\n{}",
            &text[..head_end],
            tail_start.saturating_sub(head_end),
            &text[tail_start..]
        ),
        true,
    )
}

/// Forward a `file_diff` metadata payload (attached by edit_file/write_file)
/// as an `AgentEvent::FileDiff` so channels and the web UI can render what
/// changed. Successful edits only — error results never carry the payload.
fn emit_file_diff_event(
    tx: &tokio::sync::mpsc::UnboundedSender<AgentEvent>,
    result: &crate::internal::tool_runtime::runtime::ToolResult,
) {
    let Some(fd) = result
        .metadata
        .as_ref()
        .and_then(|m| m.get(microclaw_core::diff::FILE_DIFF_METADATA_KEY))
    else {
        return;
    };
    let (Some(path), Some(diff)) = (
        fd.get("path").and_then(|v| v.as_str()),
        fd.get("diff").and_then(|v| v.as_str()),
    ) else {
        return;
    };
    let _ = tx.send(AgentEvent::FileDiff {
        path: path.to_string(),
        diff: diff.to_string(),
        added: fd.get("added").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
        removed: fd.get("removed").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
        truncated: fd
            .get("truncated")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
    });
}

/// Build a short, operator-readable preview of the action awaiting approval.
/// For bash this is the actual command; for any other future high-risk tool
/// we fall back to a truncated JSON dump so the operator can still see what
/// is queued instead of just the tool name.
fn approval_preview(name: &str, input: &Value) -> Option<String> {
    if name == "bash" {
        if let Some(cmd) = input
            .get("command")
            .or_else(|| input.get("cmd"))
            .and_then(|v| v.as_str())
        {
            let trimmed = cmd.trim();
            if trimmed.is_empty() {
                return None;
            }
            return Some(truncate_for_log(trimmed, 400));
        }
    }
    let dump = input.to_string();
    if dump == "{}" || dump == "null" {
        None
    } else {
        Some(truncate_for_log(&dump, 400))
    }
}

fn with_high_risk_approval_marker(input: &Value) -> Value {
    let mut approved_input = input.clone();
    if let Some(obj) = approved_input.as_object_mut() {
        obj.insert(
            "__microclaw_high_risk_approved".to_string(),
            Value::Bool(true),
        );
        return approved_input;
    }
    serde_json::json!({
        "__microclaw_high_risk_approved": true,
        "__microclaw_original_input": input,
    })
}

fn format_failed_action_for_user(tool_name: &str, input: &Value, result_content: &str) -> String {
    let error_summary = truncate_for_log(result_content, 140);
    if tool_name == "bash" {
        if let Some(command) = input
            .get("command")
            .or_else(|| input.get("cmd"))
            .and_then(|v| v.as_str())
        {
            let command_summary = truncate_for_log(command, 140);
            return format!("bash `{command_summary}` failed: {error_summary}");
        }
    }
    let input_summary = truncate_for_log(&input.to_string(), 100);
    format!("{tool_name} input `{input_summary}` failed: {error_summary}")
}

fn truncate_for_log(text: &str, max_chars: usize) -> String {
    let count = text.chars().count();
    if count <= max_chars {
        text.to_string()
    } else {
        let clipped = text.chars().take(max_chars).collect::<String>();
        format!("{clipped}...")
    }
}

#[expect(clippy::too_many_arguments)]
fn emit_tool_span(
    exp: &Arc<OtlpTraceExporter>,
    trace_id: &[u8],
    span_id: Vec<u8>,
    parent_span_id: &[u8],
    name: &str,
    input: &Value,
    result: &ToolResult,
    start_time: u64,
    span_name: &str,
) {
    let mut attrs = vec![kv("tool.name", name), kv("input", &input.to_string())];
    if result.is_error {
        attrs.push(kv(
            "error.type",
            result.error_type.as_deref().unwrap_or("unknown"),
        ));
        attrs.push(kv("output", &result.content));
    } else {
        attrs.push(kv("output", &truncate_for_log(&result.content, 1000)));
    }
    exp.send_span(SpanData {
        trace_id: trace_id.to_vec(),
        span_id,
        parent_span_id: parent_span_id.to_vec(),
        name: span_name.to_string(),
        start_time_unix_nano: start_time,
        end_time_unix_nano: now_unix_nano(),
        attributes: attrs,
        status: if result.is_error {
            Some(Status {
                message: result.content.clone(),
                code: 2,
            })
        } else {
            Some(Status {
                message: "".to_string(),
                code: 1,
            })
        },
        kind: 1,
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_partition_single_readonly() {
        let calls = vec![PendingToolCall {
            id: "1".into(),
            name: "read_file".into(),
            input: Value::Null,
        }];
        let waves = partition_into_waves(&calls, &HashMap::new());
        assert_eq!(waves, vec![vec![0]]);
    }

    #[test]
    fn test_partition_all_readonly_parallel() {
        let calls = vec![
            PendingToolCall {
                id: "1".into(),
                name: "read_file".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "2".into(),
                name: "glob".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "3".into(),
                name: "web_search".into(),
                input: Value::Null,
            },
        ];
        let waves = partition_into_waves(&calls, &HashMap::new());
        assert_eq!(waves, vec![vec![0, 1, 2]]);
    }

    #[test]
    fn test_partition_mixed_readonly_sideeffect() {
        let calls = vec![
            PendingToolCall {
                id: "1".into(),
                name: "read_file".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "2".into(),
                name: "write_file".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "3".into(),
                name: "glob".into(),
                input: Value::Null,
            },
        ];
        let waves = partition_into_waves(&calls, &HashMap::new());
        // Wave 1: readonly [0, 2], Wave 2: sideeffect [1]
        assert_eq!(waves, vec![vec![0, 2], vec![1]]);
    }

    #[test]
    fn test_partition_exclusive_alone() {
        let calls = vec![
            PendingToolCall {
                id: "1".into(),
                name: "read_file".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "2".into(),
                name: "bash".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "3".into(),
                name: "glob".into(),
                input: Value::Null,
            },
        ];
        let waves = partition_into_waves(&calls, &HashMap::new());
        // Wave 1: readonly [0, 2], Wave 2: exclusive [1]
        assert_eq!(waves, vec![vec![0, 2], vec![1]]);
    }

    #[test]
    fn test_partition_config_override() {
        let mut overrides = HashMap::new();
        overrides.insert("mcp_custom_search".to_string(), "read_only".to_string());

        let calls = vec![
            PendingToolCall {
                id: "1".into(),
                name: "read_file".into(),
                input: Value::Null,
            },
            PendingToolCall {
                id: "2".into(),
                name: "mcp_custom_search".into(),
                input: Value::Null,
            },
        ];
        let waves = partition_into_waves(&calls, &overrides);
        // Both should be in single parallel wave (mcp_custom_search overridden to ReadOnly)
        assert_eq!(waves, vec![vec![0, 1]]);
    }

    #[test]
    fn test_partition_empty() {
        let calls: Vec<PendingToolCall> = vec![];
        let waves = partition_into_waves(&calls, &HashMap::new());
        assert!(waves.is_empty());
    }

    #[test]
    fn successful_todo_write_emits_structured_plan() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        emit_plan_update_event(
            &tx,
            "todo_write",
            &serde_json::json!({
                "chat_id": 42,
                "todos": [
                    {"task": "Inspect", "status": "completed"},
                    {"task": "Implement", "status": "in_progress"},
                    {"task": "Verify", "status": "pending"}
                ]
            }),
            false,
        );

        assert_eq!(
            rx.try_recv().unwrap(),
            AgentEvent::PlanUpdated {
                steps: vec![
                    RuntimePlanStep {
                        title: "Inspect".into(),
                        status: RuntimePlanStepStatus::Completed,
                    },
                    RuntimePlanStep {
                        title: "Implement".into(),
                        status: RuntimePlanStepStatus::InProgress,
                    },
                    RuntimePlanStep {
                        title: "Verify".into(),
                        status: RuntimePlanStepStatus::Pending,
                    },
                ],
            }
        );
    }

    #[test]
    fn failed_todo_write_does_not_publish_a_plan() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        emit_plan_update_event(
            &tx,
            "todo_write",
            &serde_json::json!({"todos": [{"task": "Nope", "status": "pending"}]}),
            true,
        );
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn bash_result_emits_bounded_redacted_verification_evidence() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let secret = "sk-proj-abcdefghijklmnopqrstuvwxyz0123456789";
        let output = format!(
            "{secret}\n{}\nTAIL",
            "x".repeat(MAX_PROCESS_OUTPUT_BYTES + 100)
        );
        let result = ToolResult::success(output).with_status_code(0);

        emit_process_output_event(
            &tx,
            "call-check",
            "bash",
            &serde_json::json!({"command": "cargo test -p microclaw-core"}),
            &result,
            321,
        );

        let event = rx.try_recv().unwrap();
        let AgentEvent::ProcessOutput {
            call_id,
            output,
            exit_code,
            duration_ms,
            truncated,
            kind,
            ..
        } = event
        else {
            panic!("expected process output event");
        };
        assert_eq!(call_id, "call-check");
        assert_eq!(exit_code, Some(0));
        assert_eq!(duration_ms, 321);
        assert!(truncated);
        assert_eq!(kind, RuntimeProcessKind::Verification);
        assert!(!output.contains(secret));
        assert!(output.to_ascii_lowercase().contains("redacted"));
        assert!(output.ends_with("TAIL"));
    }

    #[test]
    fn non_process_tool_does_not_emit_process_output() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        emit_process_output_event(
            &tx,
            "call-read",
            "read_file",
            &serde_json::json!({"path": "README.md"}),
            &ToolResult::success("contents".into()),
            1,
        );
        assert!(rx.try_recv().is_err());
    }
}