harn-vm 0.8.59

Async bytecode virtual machine for the Harn programming language
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
//! Language-neutral executable tool-composition contract.
//!
//! A composition run is a tiny program over already-typed tool bindings. The
//! runtime must expose it as a parent run with child tool operations, not as an
//! opaque "execute code" blob, so policy, transcript, replay, and host approval
//! surfaces can keep reasoning about each child call normally.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use std::time::Duration;

use futures::stream::{FuturesUnordered, StreamExt};
use serde_json::Value;
use sha2::{Digest, Sha256};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

use crate::agent_events::{ToolCallErrorCategory, ToolCallStatus};
use crate::tool_annotations::SideEffectLevel;
use crate::value::{VmError, VmValue};
use crate::vm::Vm;

mod crystallization;
mod events;
mod harn_api;
mod hosts;
mod manifest;
mod types;
mod typescript;

#[cfg(test)]
mod tests;

pub use crystallization::composition_crystallization_trace;
pub use events::composition_report_events;
pub use harn_api::composition_harn_api;
pub use hosts::{ClosureCompositionToolHost, StaticCompositionToolHost};
pub use manifest::{
    binding_manifest_from_tool_surface, binding_manifest_hash, BindingManifest,
    BindingManifestEntry, BindingManifestOptions, BindingPolicyDisposition, BindingPolicyStatus,
    BINDING_MANIFEST_SCHEMA_VERSION,
};
pub use types::{
    CompositionChildCall, CompositionChildResult, CompositionExecutionLimits,
    CompositionExecutionReport, CompositionExecutionRequest, CompositionFailureCategory,
    CompositionMcpPolicy, CompositionRetryPolicy, CompositionRunEnvelope, CompositionToolHost,
    CompositionToolOutput, COMPOSITION_EXECUTION_SCHEMA_VERSION,
};
pub use typescript::composition_typescript_declarations;

/// Stable digest for the prompt-visible snippet body.
pub fn composition_snippet_hash(language: &str, snippet: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(b"harn.composition.snippet.v1\0");
    hasher.update(language.as_bytes());
    hasher.update(b"\0");
    hasher.update(snippet.as_bytes());
    format!("sha256:{}", hex::encode(hasher.finalize()))
}

struct ExecutionState {
    request: CompositionExecutionRequest,
    calls: Vec<CompositionChildCall>,
    results: Vec<CompositionChildResult>,
    clock: Arc<dyn harn_clock::Clock>,
    started_ms: i64,
}

impl ExecutionState {
    fn next_call(
        &mut self,
        tool_name: &str,
        input: Value,
    ) -> Result<(BindingManifestEntry, CompositionChildCall), VmError> {
        if self.results.len() as u64 >= self.request.limits.max_operations {
            return Err(VmError::Runtime(format!(
                "composition exceeded max_operations={}",
                self.request.limits.max_operations
            )));
        }
        if let Some(timeout_ms) = self.request.limits.timeout_ms {
            if elapsed_ms(&*self.clock, self.started_ms) > timeout_ms {
                return Err(VmError::Runtime(format!(
                    "composition exceeded timeout_ms={timeout_ms}"
                )));
            }
        }
        let binding = self
            .request
            .manifest
            .find_by_name(tool_name)
            .or_else(|| self.request.manifest.find_by_binding(tool_name))
            .cloned()
            .ok_or_else(|| {
                VmError::Runtime(format!("composition binding '{tool_name}' not found"))
            })?;
        let call = self.push_call(&binding, input);
        if binding.policy.disposition == BindingPolicyDisposition::Denied {
            let message = format!(
                "composition binding '{}' denied{}",
                binding.name,
                binding
                    .policy
                    .reason
                    .as_deref()
                    .map(|reason| format!(": {reason}"))
                    .unwrap_or_default()
            );
            self.push_failed_result(&call, &message, ToolCallErrorCategory::PermissionDenied);
            return Err(VmError::Runtime(message));
        }
        if binding.policy.disposition == BindingPolicyDisposition::Gated {
            let message = format!(
                "composition binding '{}' requires approval and cannot run in read-only mode",
                binding.name
            );
            self.push_failed_result(&call, &message, ToolCallErrorCategory::PermissionDenied);
            return Err(VmError::Runtime(message));
        }
        if binding.side_effect_level.rank() > self.request.requested_side_effect_ceiling.rank() {
            let message = format!(
                "composition binding '{}' requires side-effect level '{}' above requested ceiling '{}'",
                binding.name,
                binding.side_effect_level.as_str(),
                self.request.requested_side_effect_ceiling.as_str()
            );
            self.push_failed_result(&call, &message, ToolCallErrorCategory::PermissionDenied);
            return Err(VmError::Runtime(message));
        }
        Ok((binding, call))
    }

    fn push_call(&mut self, binding: &BindingManifestEntry, input: Value) -> CompositionChildCall {
        let operation_index = self.calls.len() as u64;
        let call = CompositionChildCall {
            run_id: self.request.run_id.clone(),
            tool_call_id: format!("{}:{operation_index}", self.request.run_id),
            tool_name: binding.name.clone(),
            operation_index,
            annotations: Some(binding.annotations.clone()),
            requested_side_effect_level: binding.side_effect_level,
            policy_context: serde_json::json!({
                "disposition": binding.policy.disposition,
                "reason": binding.policy.reason,
                "ceiling": self.request.requested_side_effect_ceiling,
            }),
            raw_input: input,
        };
        self.calls.push(call.clone());
        call
    }

    fn push_failed_result(
        &mut self,
        call: &CompositionChildCall,
        message: &str,
        category: ToolCallErrorCategory,
    ) {
        self.results.push(CompositionChildResult {
            run_id: call.run_id.clone(),
            tool_call_id: call.tool_call_id.clone(),
            tool_name: call.tool_name.clone(),
            operation_index: call.operation_index,
            status: ToolCallStatus::Failed,
            raw_output: None,
            error: Some(message.to_string()),
            error_category: Some(category),
            executor: Some(crate::agent_events::ToolExecutor::HarnBuiltin),
            duration_ms: Some(0),
            execution_duration_ms: Some(0),
            attempt: 1,
            retry_attempts: 0,
            retry_errors: Vec::new(),
            retry_delays_ms: Vec::new(),
        });
    }

    fn push_result(
        &mut self,
        call: &CompositionChildCall,
        outcome: &CompositionDispatchOutcome,
        elapsed_ms: u64,
    ) {
        if self
            .results
            .iter()
            .any(|result| result.tool_call_id == call.tool_call_id)
        {
            return;
        }
        self.results.push(CompositionChildResult {
            run_id: call.run_id.clone(),
            tool_call_id: call.tool_call_id.clone(),
            tool_name: call.tool_name.clone(),
            operation_index: call.operation_index,
            status: if outcome.output.error.is_some() {
                ToolCallStatus::Failed
            } else {
                ToolCallStatus::Completed
            },
            raw_output: outcome.output.value.clone(),
            error: outcome.output.error.clone(),
            error_category: outcome.output.error_category,
            executor: outcome.output.executor.clone(),
            duration_ms: Some(elapsed_ms),
            execution_duration_ms: Some(elapsed_ms),
            attempt: outcome.attempt,
            retry_attempts: outcome.retry_attempts,
            retry_errors: outcome.retry_errors.clone(),
            retry_delays_ms: outcome.retry_delays_ms.clone(),
        });
    }
}

#[derive(Clone)]
struct CompositionRuntime {
    state: Arc<parking_lot::Mutex<ExecutionState>>,
    host: Arc<dyn CompositionToolHost>,
    bulkheads: Arc<CompositionBulkheads>,
}

struct CompositionBulkheads {
    global: Arc<Semaphore>,
    per_server: parking_lot::Mutex<HashMap<String, Arc<Semaphore>>>,
    per_server_limit: usize,
}

impl CompositionBulkheads {
    fn new(limits: &CompositionExecutionLimits) -> Self {
        Self {
            global: Arc::new(Semaphore::new(
                limits
                    .max_concurrent_operations
                    .clamp(1, Semaphore::MAX_PERMITS),
            )),
            per_server: parking_lot::Mutex::new(HashMap::new()),
            per_server_limit: limits
                .max_concurrent_per_server
                .clamp(1, Semaphore::MAX_PERMITS),
        }
    }

    async fn acquire(
        &self,
        binding: &BindingManifestEntry,
    ) -> Result<(OwnedSemaphorePermit, Option<OwnedSemaphorePermit>), VmError> {
        let global = self
            .global
            .clone()
            .acquire_owned()
            .await
            .map_err(|_| VmError::Runtime("composition bulkhead closed".to_string()))?;
        let server = mcp_server_name(binding);
        let per_server = match server {
            Some(server) => {
                let semaphore = {
                    let mut semaphores = self.per_server.lock();
                    semaphores
                        .entry(server)
                        .or_insert_with(|| Arc::new(Semaphore::new(self.per_server_limit)))
                        .clone()
                };
                Some(semaphore.acquire_owned().await.map_err(|_| {
                    VmError::Runtime("composition per-server bulkhead closed".to_string())
                })?)
            }
            None => None,
        };
        Ok((global, per_server))
    }
}

struct CompositionDispatchOutcome {
    output: CompositionToolOutput,
    attempt: u32,
    retry_attempts: u32,
    retry_errors: Vec<String>,
    retry_delays_ms: Vec<u64>,
}

/// Execute a read-only Harn-native composition snippet against a manifest.
pub async fn execute_harn_composition(
    mut request: CompositionExecutionRequest,
    host: Arc<dyn CompositionToolHost>,
) -> CompositionExecutionReport {
    if request.run_id.trim().is_empty() {
        request.run_id = uuid::Uuid::now_v7().to_string();
    }
    if request.language.trim().is_empty() {
        request.language = "harn".to_string();
    }
    let manifest_hash = request
        .manifest
        .hash()
        .unwrap_or_else(|_| "sha256:manifest_hash_error".to_string());
    let snippet_hash = composition_snippet_hash(&request.language, &request.snippet);
    let mut run = CompositionRunEnvelope::read_only(
        request.run_id.clone(),
        request.language.clone(),
        snippet_hash,
        manifest_hash,
    );
    let session_id = request.session_id.clone();
    run.requested_side_effect_ceiling = request.requested_side_effect_ceiling;
    run.metadata = request.metadata.clone();
    if !run.metadata.is_object() {
        run.metadata = Value::Object(serde_json::Map::new());
    }
    if let Some(session_id) = &session_id {
        run.metadata["session_id"] = Value::String(session_id.clone());
    }
    let clock = harn_clock::RealClock::arc();
    let started_ms = clock.monotonic_ms();

    let result = if request.language != "harn" {
        Err((
            CompositionFailureCategory::UnsupportedLanguage,
            format!("unsupported composition language '{}'", request.language),
            Vec::new(),
            Vec::new(),
        ))
    } else if request.requested_side_effect_ceiling.rank() > SideEffectLevel::ReadOnly.rank() {
        Err((
            CompositionFailureCategory::PolicyDenied,
            "read-only composition executor refuses side-effect ceilings above read_only"
                .to_string(),
            Vec::new(),
            Vec::new(),
        ))
    } else {
        execute_harn_composition_inner(request, host).await
    };

    let report = match result {
        Ok((value, stdout, calls, results)) => {
            run.result = Some(value);
            run.stdout = (!stdout.is_empty()).then_some(stdout);
            run.duration_ms = Some(elapsed_ms(&*clock, started_ms));
            CompositionExecutionReport {
                schema_version: COMPOSITION_EXECUTION_SCHEMA_VERSION,
                ok: true,
                summary: format!(
                    "composition completed with {} child operation(s)",
                    results.len()
                ),
                run,
                child_calls: calls,
                child_results: results,
            }
        }
        Err((category, error, calls, results)) => {
            run.failure_category = Some(category);
            run.error = Some(error.clone());
            run.duration_ms = Some(elapsed_ms(&*clock, started_ms));
            CompositionExecutionReport {
                schema_version: COMPOSITION_EXECUTION_SCHEMA_VERSION,
                ok: false,
                summary: error,
                run,
                child_calls: calls,
                child_results: results,
            }
        }
    };
    if let Some(session_id) = session_id {
        events::emit_composition_report_events(&session_id, &report);
    }
    report
}

async fn execute_harn_composition_inner(
    request: CompositionExecutionRequest,
    host: Arc<dyn CompositionToolHost>,
) -> Result<
    (
        Value,
        String,
        Vec<CompositionChildCall>,
        Vec<CompositionChildResult>,
    ),
    (
        CompositionFailureCategory,
        String,
        Vec<CompositionChildCall>,
        Vec<CompositionChildResult>,
    ),
> {
    let validation_source = composition_validation_source(&request.snippet);
    let validation_program = harn_parser::parse_source(&validation_source).map_err(|error| {
        (
            CompositionFailureCategory::SchemaValidation,
            format!("composition parse error: {error}"),
            Vec::new(),
            Vec::new(),
        )
    })?;
    validate_composition_program(&validation_program, &request.manifest).map_err(|error| {
        (
            CompositionFailureCategory::PolicyDenied,
            error,
            Vec::new(),
            Vec::new(),
        )
    })?;

    let source = composition_source(&request.manifest, &request.snippet);
    let program = harn_parser::parse_source(&source).map_err(|error| {
        (
            CompositionFailureCategory::SchemaValidation,
            format!("composition parse error: {error}"),
            Vec::new(),
            Vec::new(),
        )
    })?;
    let chunk = crate::Compiler::new()
        .compile_named(&program, "main")
        .map_err(|error| {
            (
                CompositionFailureCategory::SchemaValidation,
                format!("composition compile error: {error}"),
                Vec::new(),
                Vec::new(),
            )
        })?;

    let execution_clock = harn_clock::RealClock::arc();
    let execution_started_ms = execution_clock.monotonic_ms();
    let state = Arc::new(parking_lot::Mutex::new(ExecutionState {
        request,
        calls: Vec::new(),
        results: Vec::new(),
        clock: execution_clock,
        started_ms: execution_started_ms,
    }));
    let mut vm = Vm::new();
    crate::register_core_stdlib(&mut vm);
    let limits = state.lock().request.limits.clone();
    let runtime = CompositionRuntime {
        state: state.clone(),
        host,
        bulkheads: Arc::new(CompositionBulkheads::new(&limits)),
    };
    register_composition_call_builtin(&mut vm, runtime.clone());
    register_composition_map_bounded_builtin(&mut vm, runtime);
    if let Some(timeout_ms) = state.lock().request.limits.timeout_ms {
        vm.push_deadline_after(std::time::Duration::from_millis(timeout_ms));
    }
    vm.set_source_info("composition://snippet.harn", &source);
    match vm.execute(&chunk).await {
        Ok(value) => {
            let json = crate::llm::vm_value_to_json(&value);
            let stdout = vm.output().to_string();
            let state = state.lock();
            let result_size = serde_json::to_vec(&json)
                .map(|bytes| bytes.len())
                .unwrap_or(0);
            let output_size = result_size.saturating_add(stdout.len());
            if output_size as u64 > state.request.limits.max_output_bytes {
                return Err((
                    CompositionFailureCategory::ExecutionError,
                    format!(
                        "composition output exceeded max_output_bytes={}",
                        state.request.limits.max_output_bytes
                    ),
                    state.calls.clone(),
                    state.results.clone(),
                ));
            }
            Ok((json, stdout, state.calls.clone(), state.results.clone()))
        }
        Err(error) => {
            let state = state.lock();
            let category = if error.to_string().contains("denied")
                || error.to_string().contains("side-effect")
                || error.to_string().contains("approval")
            {
                CompositionFailureCategory::PolicyDenied
            } else if error.to_string().contains("Deadline exceeded")
                || error.to_string().contains("max_operations")
                || error.to_string().contains("timeout_ms")
                || error.to_string().contains("max_output_bytes")
            {
                CompositionFailureCategory::Timeout
            } else if state
                .results
                .iter()
                .any(|result| result.status == ToolCallStatus::Failed)
            {
                CompositionFailureCategory::ChildToolError
            } else {
                CompositionFailureCategory::ExecutionError
            };
            Err((
                category,
                error.to_string(),
                state.calls.clone(),
                state.results.clone(),
            ))
        }
    }
}

fn register_composition_call_builtin(vm: &mut Vm, runtime: CompositionRuntime) {
    vm.register_async_builtin("__composition_call", move |_ctx, args| {
        let runtime = runtime.clone();
        async move {
            let tool_name = args
                .first()
                .map(VmValue::display)
                .ok_or_else(|| VmError::Runtime("__composition_call: missing tool name".into()))?;
            let input = args
                .get(1)
                .map(crate::llm::vm_value_to_json)
                .unwrap_or_else(|| serde_json::json!({}));
            let (binding, call, clock) = {
                let mut state = runtime.state.lock();
                let (binding, call) = state.next_call(&tool_name, input.clone())?;
                (binding, call, state.clock.clone())
            };
            let started_ms = clock.monotonic_ms();
            let outcome = dispatch_binding_with_policy(&runtime, &binding, input).await?;
            {
                let mut state = runtime.state.lock();
                state.push_result(&call, &outcome, elapsed_ms(&*clock, started_ms));
            }
            if let Some(error) = outcome.output.error {
                return Err(VmError::Runtime(error));
            }
            Ok(crate::json_to_vm_value(
                &outcome.output.value.unwrap_or(Value::Null),
            ))
        }
    });
}

async fn dispatch_binding_with_policy(
    runtime: &CompositionRuntime,
    binding: &BindingManifestEntry,
    input: Value,
) -> Result<CompositionDispatchOutcome, VmError> {
    let policy = runtime.state.lock().request.mcp_policy.clone();
    let retry = policy.retry.clone();
    let max_attempts = retry.max_attempts.max(1);
    let can_retry = retry_allowed(binding, &input, &policy);
    let mut attempt = 1u32;
    let mut retry_errors = Vec::new();
    let mut retry_delays_ms = Vec::new();

    loop {
        let (_global_permit, _server_permit) = runtime.bulkheads.acquire(binding).await?;
        let call = runtime.host.call(binding, input.clone());
        let mut output = if let Some(timeout_ms) = policy.call_timeout_ms.filter(|ms| *ms > 0) {
            match tokio::time::timeout(Duration::from_millis(timeout_ms), call).await {
                Ok(output) => output,
                Err(_) => CompositionToolOutput::error(
                    format!(
                        "composition binding '{}' timed out after {timeout_ms}ms",
                        binding.name
                    ),
                    ToolCallErrorCategory::Timeout,
                ),
            }
        } else {
            call.await
        };
        drop((_global_permit, _server_permit));

        if output.error.is_none() {
            if let Some(value) = output.value.take() {
                match validate_binding_output(binding, value) {
                    Ok(value) => output.value = Some(value),
                    Err(message) => {
                        output = CompositionToolOutput::error(
                            message,
                            ToolCallErrorCategory::SchemaValidation,
                        );
                    }
                }
            }
        }

        if output.error.is_none()
            || attempt >= max_attempts
            || !can_retry
            || !is_retryable_child_error(&output)
        {
            return Ok(CompositionDispatchOutcome {
                output,
                attempt,
                retry_attempts: attempt.saturating_sub(1),
                retry_errors,
                retry_delays_ms,
            });
        }

        let error = output
            .error
            .clone()
            .unwrap_or_else(|| "composition child call failed".to_string());
        let delay_ms = compute_retry_delay_ms(binding, &input, attempt, &retry, &error);
        retry_errors.push(error);
        retry_delays_ms.push(delay_ms);
        if delay_ms > 0 {
            tokio::time::sleep(Duration::from_millis(delay_ms)).await;
        }
        attempt = attempt.saturating_add(1);
    }
}

fn validate_binding_output(binding: &BindingManifestEntry, value: Value) -> Result<Value, String> {
    let Some(schema) = &binding.output_schema else {
        return Ok(value);
    };
    let value_vm = crate::json_to_vm_value(&value);
    let schema_vm = crate::json_to_vm_value(schema);
    crate::schema::schema_expect_value(&value_vm, &schema_vm, false)
        .map(|value| crate::llm::vm_value_to_json(&value))
        .map_err(|error| {
            format!(
                "composition binding '{}' outputSchema validation failed: {error}",
                binding.name
            )
        })
}

fn retry_allowed(
    binding: &BindingManifestEntry,
    input: &Value,
    policy: &CompositionMcpPolicy,
) -> bool {
    if idempotency_key_present(input) {
        return true;
    }
    if binding.source == "mcp_server" {
        if !mcp_binding_trusted(binding, policy) {
            return false;
        }
        return binding.annotations.destructive_hint != Some(true)
            && (binding.annotations.read_only_hint == Some(true)
                || binding.annotations.idempotent_hint == Some(true));
    }
    binding.side_effect_level == SideEffectLevel::ReadOnly
        && binding.annotations.kind.is_read_only()
}

fn mcp_binding_trusted(binding: &BindingManifestEntry, policy: &CompositionMcpPolicy) -> bool {
    policy.trust_annotations
        || mcp_server_name(binding)
            .as_ref()
            .is_some_and(|server| policy.trusted_servers.contains(server))
}

fn mcp_server_name(binding: &BindingManifestEntry) -> Option<String> {
    binding
        .metadata
        .get("_mcp_server")
        .or_else(|| binding.metadata.get("mcp_server"))
        .or_else(|| binding.metadata.pointer("/server/name"))
        .and_then(Value::as_str)
        .filter(|server| !server.is_empty())
        .map(ToOwned::to_owned)
}

fn idempotency_key_present(input: &Value) -> bool {
    for pointer in [
        "/idempotency_key",
        "/idempotencyKey",
        "/_idempotency_key",
        "/_meta/idempotencyKey",
        "/_meta/harn/idempotencyKey",
    ] {
        if input.pointer(pointer).is_some_and(|value| match value {
            Value::String(value) => !value.trim().is_empty(),
            Value::Null => false,
            _ => true,
        }) {
            return true;
        }
    }
    false
}

fn is_retryable_child_error(output: &CompositionToolOutput) -> bool {
    if matches!(
        output.error_category,
        Some(
            ToolCallErrorCategory::Network
                | ToolCallErrorCategory::Timeout
                | ToolCallErrorCategory::McpServerError
        )
    ) {
        return true;
    }
    let Some(error) = &output.error else {
        return false;
    };
    let error = error.to_ascii_lowercase();
    [
        "429",
        "503",
        "retry-after",
        "rate limit",
        "rate-limit",
        "timeout",
        "timed out",
        "transient",
        "overloaded",
        "server closed connection",
        "disconnected",
        "mcp read error",
        "mcp write error",
        "connection reset",
    ]
    .iter()
    .any(|needle| error.contains(needle))
}

fn compute_retry_delay_ms(
    binding: &BindingManifestEntry,
    input: &Value,
    attempt: u32,
    retry: &CompositionRetryPolicy,
    error: &str,
) -> u64 {
    if retry.max_delay_ms == 0 {
        return 0;
    }
    if retry.honor_retry_after {
        if let Some(delay) = retry_after_ms_from_error(error) {
            return delay.min(retry.max_delay_ms);
        }
    }
    let shift = attempt.saturating_sub(1).min(20);
    let multiplier = 1u64.checked_shl(shift).unwrap_or(u64::MAX);
    let base = retry.base_delay_ms.saturating_mul(multiplier);
    if base == 0 {
        return 0;
    }
    let jitter_span = (base / 2).max(1);
    let mut hasher = Sha256::new();
    hasher.update(binding.name.as_bytes());
    hasher.update(b"\0");
    hasher.update(attempt.to_le_bytes());
    hasher.update(b"\0");
    if let Ok(bytes) = serde_json::to_vec(input) {
        hasher.update(bytes);
    }
    let digest = hasher.finalize();
    let jitter = u64::from_le_bytes(digest[..8].try_into().unwrap_or([0; 8])) % (jitter_span + 1);
    base.saturating_add(jitter).min(retry.max_delay_ms)
}

fn retry_after_ms_from_error(error: &str) -> Option<u64> {
    let lower = error.to_ascii_lowercase();
    let (_, tail) = lower.split_once("retry-after")?;
    let value = tail
        .trim_start_matches(|c: char| c == ':' || c == '=' || c.is_whitespace())
        .split(|c: char| !c.is_ascii_digit())
        .next()
        .filter(|value| !value.is_empty())?;
    value
        .parse::<u64>()
        .ok()
        .map(|seconds| seconds.saturating_mul(1000))
}

fn register_composition_map_bounded_builtin(vm: &mut Vm, runtime: CompositionRuntime) {
    vm.register_async_builtin("map_bounded", move |ctx, args| {
        let runtime = runtime.clone();
        async move {
            let items = match args.first() {
                Some(VmValue::List(items)) => items.as_ref().clone(),
                Some(other) => {
                    return Err(VmError::TypeError(format!(
                        "map_bounded: first argument must be a list, got {}",
                        other.type_name()
                    )))
                }
                None => {
                    return Err(VmError::Runtime(
                        "map_bounded: first argument must be a list".to_string(),
                    ))
                }
            };
            let closure = match args.get(1) {
                Some(VmValue::Closure(closure)) => closure.clone(),
                Some(other) => {
                    return Err(VmError::TypeError(format!(
                        "map_bounded: second argument must be a closure, got {}",
                        other.type_name()
                    )))
                }
                None => {
                    return Err(VmError::Runtime(
                        "map_bounded: second argument must be a closure".to_string(),
                    ))
                }
            };
            let options = args
                .get(2)
                .map(crate::llm::vm_value_to_json)
                .unwrap_or_else(|| serde_json::json!({}));
            let default_cap = runtime
                .state
                .lock()
                .request
                .limits
                .max_concurrent_operations
                .max(1);
            let cap = options
                .get("concurrency")
                .or_else(|| options.get("max_concurrent"))
                .and_then(Value::as_u64)
                .map(|value| value.max(1) as usize)
                .unwrap_or(default_cap)
                .min(items.len().max(1));

            let total = items.len();
            let mut pending = items.into_iter().enumerate();
            let mut in_flight = FuturesUnordered::new();
            let mut results: Vec<Option<VmValue>> = vec![None; total];
            let mut succeeded = 0i64;
            let mut failed = 0i64;

            while in_flight.len() < cap {
                let Some((index, item)) = pending.next() else {
                    break;
                };
                in_flight.push(run_map_bounded_item(
                    ctx.clone(),
                    closure.clone(),
                    index,
                    item,
                ));
            }
            while let Some((index, output, result)) = in_flight.next().await {
                ctx.forward_output(&output);
                match result {
                    Ok(value) => {
                        succeeded += 1;
                        results[index] = Some(VmValue::enum_variant("Result", "Ok", vec![value]));
                    }
                    Err(error) => {
                        failed += 1;
                        results[index] = Some(VmValue::enum_variant(
                            "Result",
                            "Err",
                            vec![VmValue::String(std::sync::Arc::from(error.to_string()))],
                        ));
                    }
                }
                if let Some((next_index, next_item)) = pending.next() {
                    in_flight.push(run_map_bounded_item(
                        ctx.clone(),
                        closure.clone(),
                        next_index,
                        next_item,
                    ));
                }
            }

            let mut dict = BTreeMap::new();
            dict.insert(
                "results".to_string(),
                VmValue::List(std::sync::Arc::new(
                    results
                        .into_iter()
                        .map(|value| {
                            value.unwrap_or_else(|| {
                                VmValue::enum_variant(
                                    "Result",
                                    "Err",
                                    vec![VmValue::String(std::sync::Arc::from(
                                        "map_bounded: task did not produce a result",
                                    ))],
                                )
                            })
                        })
                        .collect(),
                )),
            );
            dict.insert("succeeded".to_string(), VmValue::Int(succeeded));
            dict.insert("failed".to_string(), VmValue::Int(failed));
            Ok(VmValue::Dict(std::sync::Arc::new(dict)))
        }
    });
}

async fn run_map_bounded_item(
    ctx: crate::vm::AsyncBuiltinCtx,
    closure: std::sync::Arc<crate::VmClosure>,
    index: usize,
    item: VmValue,
) -> (usize, String, Result<VmValue, VmError>) {
    let mut vm = ctx.child_vm();
    let result = vm.call_closure_pub(&closure, &[item]).await;
    let output = vm.take_output();
    (index, output, result)
}

fn elapsed_ms(clock: &dyn harn_clock::Clock, started_ms: i64) -> u64 {
    clock.monotonic_ms().saturating_sub(started_ms).max(0) as u64
}

fn composition_validation_source(snippet: &str) -> String {
    let mut source = String::from("pipeline main() {\n");
    source.push_str(snippet);
    if !snippet.ends_with('\n') {
        source.push('\n');
    }
    source.push_str("}\n");
    source
}

fn composition_source(manifest: &BindingManifest, snippet: &str) -> String {
    let mut source = String::new();
    for binding in &manifest.bindings {
        source.push_str(&format!(
            "fn {}(args = {{}}) {{ return __composition_call(\"{}\", args) }}\n",
            binding.binding,
            escape_harn_string(&binding.name)
        ));
    }
    source.push_str("pipeline main() {\n");
    source.push_str(snippet);
    if !snippet.ends_with('\n') {
        source.push('\n');
    }
    source.push_str("}\n");
    source
}

fn escape_harn_string(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

fn validate_composition_program(
    program: &[harn_parser::SNode],
    manifest: &BindingManifest,
) -> Result<(), String> {
    use harn_parser::visit::walk_program;
    use harn_parser::Node;

    let bindings = manifest
        .bindings
        .iter()
        .map(|entry| entry.binding.clone())
        .collect::<BTreeSet<_>>();
    let mut local_functions = BTreeSet::from(["__composition_call".to_string()]);
    walk_program(program, &mut |node| {
        if let Node::FnDecl { name, .. } = &node.node {
            local_functions.insert(name.clone());
        }
    });

    let mut error = None;
    walk_program(program, &mut |node| {
        if error.is_some() {
            return;
        }
        match &node.node {
            Node::ImportDecl { .. } | Node::SelectiveImport { .. } => {
                error = Some("composition snippets cannot import modules".to_string());
            }
            Node::SpawnExpr { .. } | Node::Parallel { .. } => {
                error = Some("composition snippets cannot spawn or parallelize work".to_string());
            }
            Node::HitlExpr { .. } => {
                error = Some("composition snippets cannot request HITL directly".to_string());
            }
            Node::CostRoute { .. } => {
                error = Some("composition snippets cannot open LLM routing blocks".to_string());
            }
            Node::FunctionCall { name, .. } => {
                if DENIED_COMPOSITION_CALLS.contains(&name.as_str()) && !bindings.contains(name) {
                    error = Some(format!("composition snippets cannot call `{name}`"));
                } else if !bindings.contains(name)
                    && !local_functions.contains(name)
                    && !PURE_COMPOSITION_CALLS.contains(&name.as_str())
                {
                    error = Some(format!(
                        "composition call target `{name}` is not a manifest binding or pure helper"
                    ));
                }
            }
            _ => {}
        }
    });
    error.map_or(Ok(()), Err)
}

const DENIED_COMPOSITION_CALLS: &[&str] = &[
    "append_file",
    "ask_user",
    "connector_call",
    "copy_file",
    "delete_file",
    "dual_control",
    "escalate_to",
    "event_log_emit",
    "event_log.emit",
    "exec",
    "host_call",
    "host_tool_call",
    "http_delete",
    "http_download",
    "http_get",
    "http_patch",
    "http_post",
    "http_put",
    "http_request",
    "llm_call",
    "mcp_call",
    "mcp_connect",
    "pg_execute",
    "pg_query",
    "request_approval",
    "secret_get",
    "write_file",
];

const PURE_COMPOSITION_CALLS: &[&str] = &[
    "Ok",
    "Err",
    "abs",
    "assert",
    "assert_eq",
    "assert_ne",
    "base64_decode",
    "base64_encode",
    "ceil",
    "contains",
    "dedup_by",
    "dirname",
    "entries",
    "ends_with",
    "flat_map",
    "floor",
    "format",
    "group_by",
    "hash_value",
    "hex_decode",
    "hex_encode",
    "is_err",
    "is_ok",
    "join",
    "jq",
    "jq_first",
    "json_extract",
    "json_parse",
    "json_pointer",
    "json_stringify",
    "keys",
    "len",
    "lower",
    "map_bounded",
    "parse_float_or",
    "parse_int_or",
    "split",
    "starts_with",
    "to_float",
    "to_int",
    "to_string",
    "trim",
    "upper",
    "values",
];

pub fn composition_search_examples(query: &str, limit: usize) -> Value {
    let mut examples = vec![
        serde_json::json!({
            "id": "read-summarize",
            "title": "Read two files and return a compact summary",
            "language": "harn",
            "snippet": "let readme = read_file({path: \"README.md\"})\nlet spec = read_file({path: \"spec/HARN_SPEC.md\", limit: 80})\nreturn {readme: readme, spec_excerpt: spec}",
            "required_side_effect_level": "read_only",
            "tools": ["read_file"]
        }),
        serde_json::json!({
            "id": "search-then-read",
            "title": "Search first, then read the best candidate",
            "language": "harn",
            "snippet": "let hits = search({query: \"CompositionRunEnvelope\"})\nreturn hits",
            "required_side_effect_level": "read_only",
            "tools": ["search"]
        }),
    ];
    if !query.trim().is_empty() {
        let q = query.to_ascii_lowercase();
        examples.retain(|example| {
            example
                .to_string()
                .to_ascii_lowercase()
                .contains(q.as_str())
        });
    }
    examples.truncate(limit.max(1));
    Value::Array(examples)
}

pub fn register_composition_builtins(vm: &mut Vm) {
    vm.register_builtin("composition_binding_manifest", |args, _out| {
        let tools = args
            .first()
            .map(crate::llm::vm_value_to_json)
            .unwrap_or(Value::Null);
        let options_json = args
            .get(1)
            .map(crate::llm::vm_value_to_json)
            .unwrap_or(Value::Null);
        let mut options = BindingManifestOptions::default();
        if let Some(ceiling) = options_json
            .get("side_effect_ceiling")
            .and_then(Value::as_str)
        {
            options.side_effect_ceiling = SideEffectLevel::parse(ceiling);
        }
        if let Some(include_denied) = options_json.get("include_denied").and_then(Value::as_bool) {
            options.include_denied = include_denied;
        }
        options.denied_tools = string_set_option(&options_json, "denied_tools");
        options.gated_tools = string_set_option(&options_json, "gated_tools");
        let manifest = binding_manifest_from_tool_surface(&tools, options);
        let value = if options_json.get("form").and_then(Value::as_str) == Some("compact") {
            manifest.to_compact_value()
        } else {
            manifest.to_value()
        };
        Ok(crate::json_to_vm_value(&value))
    });

    vm.register_builtin("composition_search_examples", |args, _out| {
        let query = args.first().map(VmValue::display).unwrap_or_default();
        let limit = args
            .get(1)
            .and_then(|value| match value {
                VmValue::Int(n) => Some((*n).max(1) as usize),
                _ => None,
            })
            .unwrap_or(10);
        Ok(crate::json_to_vm_value(&composition_search_examples(
            &query, limit,
        )))
    });

    vm.register_builtin("composition_typescript_declarations", |args, _out| {
        let manifest_value = args
            .first()
            .map(crate::llm::vm_value_to_json)
            .ok_or_else(|| {
                VmError::Runtime("composition_typescript_declarations: manifest is required".into())
            })?;
        let manifest: BindingManifest =
            serde_json::from_value(manifest_value).map_err(|error| {
                VmError::Runtime(format!(
                    "composition_typescript_declarations: invalid manifest: {error}"
                ))
            })?;
        Ok(VmValue::String(std::sync::Arc::from(
            composition_typescript_declarations(&manifest),
        )))
    });

    vm.register_builtin("composition_harn_api", |args, _out| {
        let manifest_value = args
            .first()
            .map(crate::llm::vm_value_to_json)
            .ok_or_else(|| VmError::Runtime("composition_harn_api: manifest is required".into()))?;
        let manifest: BindingManifest =
            serde_json::from_value(manifest_value).map_err(|error| {
                VmError::Runtime(format!("composition_harn_api: invalid manifest: {error}"))
            })?;
        Ok(VmValue::String(std::sync::Arc::from(composition_harn_api(
            &manifest,
        ))))
    });

    vm.register_builtin("composition_crystallization_trace", |args, _out| {
        let report_value = args
            .first()
            .map(crate::llm::vm_value_to_json)
            .ok_or_else(|| {
                VmError::Runtime("composition_crystallization_trace: report is required".into())
            })?;
        let report: CompositionExecutionReport =
            serde_json::from_value(report_value).map_err(|error| {
                VmError::Runtime(format!(
                    "composition_crystallization_trace: invalid report: {error}"
                ))
            })?;
        let options = args
            .get(1)
            .map(crate::llm::vm_value_to_json)
            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
        Ok(crate::json_to_vm_value(&composition_crystallization_trace(
            &report, &options,
        )))
    });

    vm.register_async_builtin("composition_execute", |ctx, args| async move {
        let snippet = args
            .first()
            .map(VmValue::display)
            .ok_or_else(|| VmError::Runtime("composition_execute: snippet is required".into()))?;
        let manifest_value = args
            .get(1)
            .map(crate::llm::vm_value_to_json)
            .ok_or_else(|| VmError::Runtime("composition_execute: manifest is required".into()))?;
        let dispatcher = args.get(2).and_then(|value| match value {
            VmValue::Closure(closure) => Some((**closure).clone()),
            VmValue::Dict(dict) => match dict.get("dispatcher") {
                Some(VmValue::Closure(closure)) => Some((**closure).clone()),
                _ => None,
            },
            _ => None,
        });
        let mut request = CompositionExecutionRequest {
            snippet,
            manifest: serde_json::from_value(manifest_value).map_err(|error| {
                VmError::Runtime(format!("composition_execute: invalid manifest: {error}"))
            })?,
            ..CompositionExecutionRequest::default()
        };
        if let Some(options) = args.get(2).map(crate::llm::vm_value_to_json) {
            if let Some(session_id) = options.get("session_id").and_then(Value::as_str) {
                request.session_id = Some(session_id.to_string());
            }
            if let Some(run_id) = options.get("run_id").and_then(Value::as_str) {
                request.run_id = run_id.to_string();
            }
            if let Some(max_operations) = options.get("max_operations").and_then(Value::as_u64) {
                request.limits.max_operations = max_operations;
            }
            if let Some(timeout_ms) = options.get("timeout_ms").and_then(Value::as_u64) {
                request.limits.timeout_ms = Some(timeout_ms);
            }
            if let Some(max_output_bytes) = options.get("max_output_bytes").and_then(Value::as_u64)
            {
                request.limits.max_output_bytes = max_output_bytes;
            }
            if let Some(max_concurrent) = options
                .get("max_concurrent_operations")
                .or_else(|| options.get("max_concurrent"))
                .and_then(Value::as_u64)
            {
                request.limits.max_concurrent_operations =
                    usize::try_from(max_concurrent).unwrap_or(usize::MAX).max(1);
            }
            if let Some(per_server) = options
                .get("max_concurrent_per_server")
                .or_else(|| options.get("per_server_concurrency"))
                .and_then(Value::as_u64)
            {
                request.limits.max_concurrent_per_server =
                    usize::try_from(per_server).unwrap_or(usize::MAX).max(1);
            }
            let trusted_servers = string_set_option(&options, "trusted_servers");
            let trusted_mcp_servers = string_set_option(&options, "trusted_mcp_servers");
            if !trusted_servers.is_empty() || !trusted_mcp_servers.is_empty() {
                request
                    .mcp_policy
                    .trusted_servers
                    .extend(trusted_servers.into_iter().chain(trusted_mcp_servers));
            }
            if let Some(trust_annotations) = options
                .get("trust_annotations")
                .or_else(|| options.get("trust_mcp_annotations"))
                .and_then(Value::as_bool)
            {
                request.mcp_policy.trust_annotations = trust_annotations;
            }
            if let Some(call_timeout_ms) = options.get("call_timeout_ms").and_then(Value::as_u64) {
                request.mcp_policy.call_timeout_ms = Some(call_timeout_ms);
            }
            if let Some(retry_options) = options.get("retry") {
                if let Some(max_attempts) =
                    retry_options.get("max_attempts").and_then(Value::as_u64)
                {
                    request.mcp_policy.retry.max_attempts =
                        u32::try_from(max_attempts).unwrap_or(u32::MAX).max(1);
                }
                if let Some(base_delay_ms) =
                    retry_options.get("base_delay_ms").and_then(Value::as_u64)
                {
                    request.mcp_policy.retry.base_delay_ms = base_delay_ms;
                }
                if let Some(max_delay_ms) =
                    retry_options.get("max_delay_ms").and_then(Value::as_u64)
                {
                    request.mcp_policy.retry.max_delay_ms = max_delay_ms;
                }
                if let Some(honor_retry_after) = retry_options
                    .get("honor_retry_after")
                    .and_then(Value::as_bool)
                {
                    request.mcp_policy.retry.honor_retry_after = honor_retry_after;
                }
            }
        }
        let host: Arc<dyn CompositionToolHost> = match dispatcher {
            Some(closure) => Arc::new(ClosureCompositionToolHost::new(closure, ctx.clone())),
            None => Arc::new(StaticCompositionToolHost::new(BTreeMap::new())),
        };
        let report = execute_harn_composition(request, host).await;
        Ok(crate::json_to_vm_value(
            &serde_json::to_value(report).unwrap_or_else(|_| serde_json::json!({"ok": false})),
        ))
    });
}

fn string_set_option(value: &Value, key: &str) -> BTreeSet<String> {
    value
        .get(key)
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_str)
                .map(ToOwned::to_owned)
                .collect()
        })
        .unwrap_or_default()
}