-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathlib.rs
More file actions
1038 lines (938 loc) · 34.6 KB
/
Copy pathlib.rs
File metadata and controls
1038 lines (938 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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
//! Host runtime facade for IronClaw Reborn.
//!
//! `ironclaw_host_runtime` is the narrow boundary upper Reborn services build
//! against. It surfaces both:
//!
//! - the [`HostRuntime`] trait — the stable contract upper turn/loop services
//! depend on;
//! - [`DefaultHostRuntime`] — the production composition that wraps
//! [`ironclaw_capabilities::CapabilityHost`] (which itself coordinates
//! authorization, approvals, run-state lifecycle, and process spawn) behind
//! that contract.
//!
//! The facade preserves three important boundaries:
//!
//! - callers see structured capability outcomes instead of lower substrate
//! handles;
//! - approval/auth/resource waits are suspension states, not errors;
//! - caller/workflow origin taxonomy is intentionally kept outside this lower
//! facade. Authority remains in [`ExecutionContext`] (principals, grants,
//! leases, policy); projection selection is an opaque [`SurfaceKind`] label
//! the host treats as a cache/version dimension only. Caller-authority
//! filtering of which surface a particular UI or upper service is allowed to
//! render is intentionally an upper-layer concern — the host does not bake
//! in upper-stack vocabulary (e.g. agent loop / adapter / admin).
#![warn(unreachable_pub)]
use async_trait::async_trait;
use ironclaw_host_api::{
ApprovalRequestId, CapabilityDisplayOutputPreview, CapabilityId, CorrelationId,
DispatchFailureDetail, ExecutionContext, ExtensionId, ProcessId, ResourceEstimate,
ResourceScope, ResourceUsage, RuntimeCredentialAuthRequirement, RuntimeKind, SecretHandle,
runtime_policy::{DeploymentMode, EffectiveRuntimePolicy, RuntimeProfile},
};
use ironclaw_trust::TrustDecision;
use serde_json::Value;
use std::{collections::BTreeMap, env, fmt};
use thiserror::Error;
mod capability_catalog;
mod egress;
mod extension_contracts;
mod first_party;
mod first_party_tools;
mod http_body;
mod invocation_services;
pub mod memory_context;
mod obligations;
mod planner;
mod process_aliases;
mod process_output;
mod process_port;
mod production;
mod sandbox_process;
mod services;
mod surface;
mod turn_scheduler;
mod user_profile_source;
mod wasm_credentials;
pub use user_profile_source::{MemoryBackedUserProfileSource, PROFILE_DOCUMENT_PATH};
pub use capability_catalog::{
HotCapabilityCatalog, HotCapabilityRecord, MAX_HOT_PROMPT_BYTES, MAX_HOT_SCHEMA_BYTES,
publish_hot_capability_catalog,
};
pub use egress::{
HostHttpEgressService, HostRuntimeCredentialMaterial, HostRuntimeHttpEgressPort,
HostRuntimeHttpEgressRequest, RuntimeSecretMaterialStager, RuntimeSecretStageError,
};
pub use extension_contracts::{
default_host_api_contract_registry, default_host_port_catalog,
discover_extensions_tolerant_bounded, discover_extensions_with_default_host_api_contracts,
discover_extensions_with_default_host_api_contracts_and_catalog,
};
pub use first_party::{
FirstPartyCapabilityError, FirstPartyCapabilityHandler, FirstPartyCapabilityRegistry,
FirstPartyCapabilityRequest, FirstPartyCapabilityResult,
};
pub use first_party_tools::{
APPLY_PATCH_CAPABILITY_ID, BUILTIN_FIRST_PARTY_PROVIDER, BuiltinFirstPartyTools,
ECHO_CAPABILITY_ID, GLOB_CAPABILITY_ID, GREP_CAPABILITY_ID, HTTP_CAPABILITY_ID,
HTTP_SAVE_CAPABILITY_ID, JSON_CAPABILITY_ID, LIST_DIR_CAPABILITY_ID, MEMORY_READ_CAPABILITY_ID,
MEMORY_SEARCH_CAPABILITY_ID, MEMORY_TREE_CAPABILITY_ID, MEMORY_WRITE_CAPABILITY_ID,
PROFILE_SET_CAPABILITY_ID, READ_FILE_CAPABILITY_ID, SHELL_CAPABILITY_ID,
SKILL_INSTALL_CAPABILITY_ID, SKILL_LIST_CAPABILITY_ID, SKILL_REMOVE_CAPABILITY_ID,
SPAWN_SUBAGENT_CAPABILITY_ID, TIME_CAPABILITY_ID, TRACE_COMMONS_CREDITS_CAPABILITY_ID,
TRACE_COMMONS_ONBOARD_CAPABILITY_ID, TRACE_COMMONS_PROFILE_SET_CAPABILITY_ID,
TRACE_COMMONS_PROFILE_TOKEN_CAPABILITY_ID, TRACE_COMMONS_STATUS_CAPABILITY_ID,
TRIGGER_CREATE_CAPABILITY_ID, TRIGGER_LIST_CAPABILITY_ID, TRIGGER_PAUSE_CAPABILITY_ID,
TRIGGER_REMOVE_CAPABILITY_ID, TRIGGER_RESUME_CAPABILITY_ID, TriggerCreateHook,
WRITE_FILE_CAPABILITY_ID, builtin_first_party_handlers,
builtin_first_party_handlers_for_process_backend,
builtin_first_party_handlers_with_trigger_create_hook,
builtin_first_party_handlers_with_trigger_create_hook_for_process_backend,
builtin_first_party_package, builtin_first_party_package_for_process_backend,
};
#[cfg(any(test, feature = "test-support"))]
pub use first_party_tools::{
TriggerManagementClock, builtin_first_party_handlers_with_trigger_clock,
};
pub use http_body::{RuntimeHttpBodyStore, RuntimeHttpBodyStoreError};
pub use invocation_services::{
InvocationServices, InvocationServicesError, InvocationServicesResolutionRequest,
InvocationServicesResolver, LocalInvocationServicesResolver, ToolCallHttpEgress,
};
pub use obligations::{
BuiltinObligationHandler, BuiltinObligationServices, LEAK_REDACT_FAILED_CODE,
ProcessObligationLifecycleStore, RuntimeCredentialAccessSecret,
RuntimeCredentialAccountRequest, RuntimeCredentialAccountResolver,
};
pub use planner::{ExecutionPlan, PlannerError, plan_capability};
pub use process_output::{SavedCommandOutput, SavedCommandOutputSanitization};
pub use process_port::{
CommandExecutionOutput, CommandExecutionRequest, LocalHostProcessPort, RuntimeProcessError,
RuntimeProcessPort, SandboxCommandTransport, TenantSandboxProcessPort,
};
pub use production::DefaultHostRuntime;
pub use sandbox_process::{
RebornSandboxConfig, RebornSandboxContainerIdentity, RebornSandboxNetworkBroker,
RebornSandboxScopeKey, RebornSandboxSecretBroker, RebornSandboxWorkspaceMode,
RebornScopedSandboxCommandTransport,
};
pub use services::{
HostRuntimeServices, ProductAuthCredentialStageError, ProductAuthProviderRuntimePorts,
ProductionEventStoreWiringError, ProductionWiringComponent, ProductionWiringConfig,
ProductionWiringIssue, ProductionWiringIssueKind, ProductionWiringReport,
RegisteredRuntimeHealth,
};
pub use surface::{CapabilitySurfacePolicy, VisibleCapability, VisibleCapabilityAccess};
pub use turn_scheduler::{
DEFAULT_MAX_CONCURRENT_RUNS, SchedulerTurnRunWakeNotifier, TurnRunExecutor,
TurnRunExecutorError, TurnRunScheduler, TurnRunSchedulerConfig, TurnRunSchedulerHandle,
TurnRunWakeChannel,
};
/// Stable, validated idempotency key supplied by upper turn/loop services.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IdempotencyKey(String);
impl IdempotencyKey {
pub fn new(value: impl Into<String>) -> Result<Self, HostRuntimeError> {
validate_bounded_contract_string(value.into(), "idempotency key", 256).map(Self)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for IdempotencyKey {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl From<IdempotencyKey> for String {
fn from(value: IdempotencyKey) -> Self {
value.into_string()
}
}
impl fmt::Display for IdempotencyKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
fn validate_bounded_contract_string(
value: String,
label: &'static str,
max_bytes: usize,
) -> Result<String, HostRuntimeError> {
if value.is_empty() {
return Err(HostRuntimeError::invalid_request(format!(
"{label} must not be empty"
)));
}
if value.len() > max_bytes {
return Err(HostRuntimeError::invalid_request(format!(
"{label} must be at most {max_bytes} bytes"
)));
}
if value.chars().any(|c| c == '\0' || c.is_control()) {
return Err(HostRuntimeError::invalid_request(format!(
"{label} must not contain NUL/control characters"
)));
}
Ok(value)
}
/// Host-runtime-local gate id for non-approval suspension states.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RuntimeGateId(String);
impl RuntimeGateId {
pub fn new() -> Self {
Self(CorrelationId::new().to_string())
}
pub fn from_stable_suffix(suffix: &str) -> Result<Self, HostRuntimeError> {
Ok(Self(validate_bounded_contract_string(
suffix.to_string(),
"runtime gate id",
128,
)?))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Default for RuntimeGateId {
fn default() -> Self {
Self::new()
}
}
impl AsRef<str> for RuntimeGateId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl From<RuntimeGateId> for String {
fn from(value: RuntimeGateId) -> Self {
value.0
}
}
impl fmt::Display for RuntimeGateId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
/// Version token for the host-filtered visible capability surface.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CapabilitySurfaceVersion(String);
impl CapabilitySurfaceVersion {
pub fn new(value: impl Into<String>) -> Result<Self, HostRuntimeError> {
validate_bounded_contract_string(value.into(), "capability surface version", 128).map(Self)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for CapabilitySurfaceVersion {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl From<CapabilitySurfaceVersion> for String {
fn from(value: CapabilitySurfaceVersion) -> Self {
value.0
}
}
impl fmt::Display for CapabilitySurfaceVersion {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
/// Opaque projection-surface label supplied by the caller.
///
/// The host treats this as a cache/version dimension only — it must not bake
/// in upper-stack vocabulary (agent loop, adapter, admin, …) and must not
/// derive authority or filtering decisions from the label. Upper layers are
/// responsible for deciding which surface label a given caller is allowed to
/// render; this lower facade simply returns the projection associated with
/// whatever label is presented.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SurfaceKind(String);
impl SurfaceKind {
pub fn new(value: impl Into<String>) -> Result<Self, HostRuntimeError> {
validate_bounded_contract_string(value.into(), "surface kind", 64).map(Self)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for SurfaceKind {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl From<SurfaceKind> for String {
fn from(value: SurfaceKind) -> Self {
value.into_string()
}
}
impl fmt::Display for SurfaceKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
/// Request to invoke one capability through the composed host runtime.
///
/// Caller/workflow origin is intentionally not part of this lower contract.
/// Host runtime authorization must be derived from [`ExecutionContext`],
/// principals, grants, leases, and policy; upper workflow services can attach
/// audit labels outside this facade when they need product-specific origin
/// vocabulary.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RuntimeCapabilityRequest {
pub context: ExecutionContext,
pub capability_id: CapabilityId,
/// Advisory pre-flight estimate supplied by the caller.
///
/// Production host-runtime implementations must treat this as a hint only:
/// resource authorization, reservation, and reconciliation remain host-owned
/// and must not trust caller estimates as binding limits or actual usage.
pub estimate: ResourceEstimate,
pub input: Value,
/// Caller-supplied dedup hint.
///
/// **This field is currently advisory at this layer.** The composed
/// capability host does not yet implement caller-driven idempotent
/// retries, so two `invoke_capability` calls carrying the same key will
/// both execute. Upper turn/loop services that need at-most-once
/// semantics must dedupe themselves until idempotency lands in the
/// capability host. The field is kept on the contract surface so that
/// shape doesn't break when dedup is wired through downstream.
///
/// The host runtime still validates and forwards the key into
/// observability spans for audit/tracing.
pub idempotency_key: Option<IdempotencyKey>,
/// Legacy caller-supplied trust decision kept for transitional request-shape
/// compatibility.
///
/// [`DefaultHostRuntime`](crate::DefaultHostRuntime) ignores this value: it
/// resolves the capability provider's package identity, evaluates the
/// host-owned policy, stamps the resulting effective trust onto the
/// execution context, and passes that host-owned decision to the capability
/// host. Callers must not rely on this field to widen or narrow authority.
pub trust_decision: TrustDecision,
}
impl RuntimeCapabilityRequest {
pub fn new(
context: ExecutionContext,
capability_id: CapabilityId,
estimate: ResourceEstimate,
input: Value,
trust_decision: TrustDecision,
) -> Self {
Self {
context,
capability_id,
estimate,
input,
idempotency_key: None,
trust_decision,
}
}
pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
self.idempotency_key = Some(key);
self
}
}
/// Request to resume one approval-blocked capability through the composed host runtime.
///
/// The shape mirrors [`RuntimeCapabilityRequest`] but additionally carries the
/// approval request selected by an upper approval workflow. Like invoke requests,
/// `trust_decision` is transitional compatibility data: the default host runtime
/// evaluates provider trust itself before delegating to `CapabilityHost`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RuntimeCapabilityResumeRequest {
pub context: ExecutionContext,
pub approval_request_id: ApprovalRequestId,
pub capability_id: CapabilityId,
pub estimate: ResourceEstimate,
pub input: Value,
pub idempotency_key: Option<IdempotencyKey>,
pub trust_decision: TrustDecision,
}
impl RuntimeCapabilityResumeRequest {
pub fn new(
context: ExecutionContext,
approval_request_id: ApprovalRequestId,
capability_id: CapabilityId,
estimate: ResourceEstimate,
input: Value,
trust_decision: TrustDecision,
) -> Self {
Self {
context,
approval_request_id,
capability_id,
estimate,
input,
idempotency_key: None,
trust_decision,
}
}
pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
self.idempotency_key = Some(key);
self
}
}
/// Auth-gate resume request.
///
/// Re-dispatches a capability that was previously blocked by an auth gate,
/// reusing the original `invocation_id` encoded in the `context`. When the
/// invocation also passed a prior approval gate, `approval_request_id` is set
/// so the host can locate and claim the matching fingerprinted lease.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RuntimeCapabilityAuthResumeRequest {
pub context: ExecutionContext,
pub capability_id: CapabilityId,
pub estimate: ResourceEstimate,
pub input: Value,
pub idempotency_key: Option<IdempotencyKey>,
pub trust_decision: TrustDecision,
/// Present when the invocation previously passed an approval gate.
/// Used to locate and claim the matching fingerprinted approval lease
/// so the re-dispatch does not require a second approval.
pub approval_request_id: Option<ApprovalRequestId>,
}
impl RuntimeCapabilityAuthResumeRequest {
pub fn new(
context: ExecutionContext,
capability_id: CapabilityId,
estimate: ResourceEstimate,
input: Value,
trust_decision: TrustDecision,
approval_request_id: Option<ApprovalRequestId>,
) -> Self {
Self {
context,
capability_id,
estimate,
input,
idempotency_key: None,
trust_decision,
approval_request_id,
}
}
pub fn with_idempotency_key(mut self, key: IdempotencyKey) -> Self {
self.idempotency_key = Some(key);
self
}
}
/// Request to list host-filtered visible capabilities.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VisibleCapabilityRequest {
/// Authority envelope used for the same grant/trust checks as invocation.
pub context: ExecutionContext,
/// Projection surface selection only; this is not authority and must not
/// grant or bypass authorization. The host treats this as an opaque
/// cache/version dimension; deciding which surface labels a given caller
/// may request is an upper-layer concern.
pub surface_kind: SurfaceKind,
/// Caller/host-supplied trust decisions keyed by capability provider.
///
/// `DefaultHostRuntime` does not evaluate trust while computing visibility;
/// missing provider trust fails closed by omitting that provider's
/// capabilities from the surface.
pub provider_trust: BTreeMap<ExtensionId, TrustDecision>,
/// Upper/profile-supplied visibility ceiling. This only narrows what is
/// shown; it never grants authority or bypasses invocation authorization.
pub policy: CapabilitySurfacePolicy,
}
impl VisibleCapabilityRequest {
pub fn new(context: ExecutionContext, surface_kind: SurfaceKind) -> Self {
Self {
context,
surface_kind,
provider_trust: BTreeMap::new(),
policy: CapabilitySurfacePolicy::default(),
}
}
pub fn with_provider_trust(
mut self,
provider_trust: BTreeMap<ExtensionId, TrustDecision>,
) -> Self {
self.provider_trust = provider_trust;
self
}
pub fn with_policy(mut self, policy: CapabilitySurfacePolicy) -> Self {
self.policy = policy;
self
}
}
/// Host-filtered visible capability surface.
///
/// Entries are returned in filtered registry order for deterministic rendering.
/// The version fingerprint canonicalizes unordered inputs (policy allow-lists
/// and visible capability set) so semantically equivalent projections do not
/// churn when callers permute allow-list values or registry insertion order
/// changes. Visibility remains informational only; invocation authority is
/// re-checked by [`HostRuntime::invoke_capability`].
#[derive(Debug, Clone, PartialEq)]
pub struct VisibleCapabilitySurface {
/// Stable token for the semantic visible surface under this request policy.
pub version: CapabilitySurfaceVersion,
/// Typed visible capabilities, including access status and selected
/// resource estimate.
pub capabilities: Vec<VisibleCapability>,
}
/// Successful capability completion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeCapabilityCompleted {
pub capability_id: CapabilityId,
pub output: Value,
pub display_preview: Option<CapabilityDisplayOutputPreview>,
pub usage: ResourceUsage,
}
/// Approval suspension state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeApprovalGate {
pub approval_request_id: ApprovalRequestId,
pub capability_id: CapabilityId,
pub reason: RuntimeBlockedReason,
}
/// Auth/credential suspension state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeAuthGate {
pub gate_id: RuntimeGateId,
pub capability_id: CapabilityId,
pub reason: RuntimeBlockedReason,
pub required_secrets: Vec<SecretHandle>,
pub credential_requirements: Vec<RuntimeCredentialAuthRequirement>,
}
/// Resource suspension state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeResourceGate {
pub gate_id: RuntimeGateId,
pub capability_id: CapabilityId,
pub reason: RuntimeBlockedReason,
pub estimate: ResourceEstimate,
}
/// Spawned/background process summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeProcessHandle {
pub process_id: ProcessId,
pub capability_id: CapabilityId,
}
/// Sanitized capability failure outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeCapabilityFailure {
pub capability_id: CapabilityId,
pub kind: RuntimeFailureKind,
pub message: Option<String>,
pub detail: Option<DispatchFailureDetail>,
}
/// Explicit fallback for outcome categories that the loop adapter cannot handle
/// yet. New first-class outcome variants should be added to
/// [`RuntimeCapabilityOutcome`] and exhaustively mapped by consumers instead of
/// being hidden behind wildcard matches.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeCapabilityUnknown {
pub capability_id: CapabilityId,
pub kind: String,
pub message: Option<String>,
}
/// Outcomes returned by capability invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeCapabilityOutcome {
Completed(Box<RuntimeCapabilityCompleted>),
ApprovalRequired(RuntimeApprovalGate),
AuthRequired(RuntimeAuthGate),
ResourceBlocked(RuntimeResourceGate),
SpawnedProcess(RuntimeProcessHandle),
Failed(RuntimeCapabilityFailure),
Unknown(RuntimeCapabilityUnknown),
}
impl RuntimeCapabilityOutcome {
pub const fn kind(&self) -> &'static str {
match self {
Self::Completed(_) => "completed",
Self::ApprovalRequired(_) => "approval_required",
Self::AuthRequired(_) => "auth_required",
Self::ResourceBlocked(_) => "resource_blocked",
Self::SpawnedProcess(_) => "spawned_process",
Self::Failed(_) => "failed",
Self::Unknown(_) => "unknown",
}
}
}
/// Stable reasons for capability suspension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RuntimeBlockedReason {
ApprovalRequired,
AuthRequired,
ResourceLimit,
ResourceUnavailable,
}
/// Opt-in local diagnostic switch for raw HTTP egress failures.
///
/// Raw transport errors can contain URLs, query strings, host paths, proxy
/// details, or credential-shaped text. Keep this disabled unless debugging a
/// trusted `LocalDev` or `LocalYolo` run. Hosted and enterprise deployments
/// never enable raw diagnostics from this environment variable alone.
pub(crate) const UNSAFE_RAW_HTTP_EGRESS_ERRORS_ENV: &str = "IRONCLAW_UNSAFE_RAW_HTTP_EGRESS_ERRORS";
pub(crate) fn runtime_policy_allows_unsafe_raw_http_diagnostics(
policy: Option<&EffectiveRuntimePolicy>,
) -> bool {
policy.is_some_and(|policy| {
local_runtime_allows_unsafe_raw_http_diagnostics(policy.deployment, policy.resolved_profile)
})
}
pub(crate) fn local_runtime_allows_unsafe_raw_http_diagnostics(
deployment: DeploymentMode,
profile: RuntimeProfile,
) -> bool {
matches!(deployment, DeploymentMode::LocalSingleUser)
&& matches!(
profile,
RuntimeProfile::LocalDev | RuntimeProfile::LocalYolo
)
}
pub(crate) fn unsafe_raw_http_diagnostics_enabled(runtime_allows_raw: bool) -> bool {
runtime_allows_raw && env::var(UNSAFE_RAW_HTTP_EGRESS_ERRORS_ENV).as_deref() == Ok("1")
}
#[cfg(test)]
mod raw_http_diagnostic_policy_tests {
use super::*;
#[test]
fn raw_http_diagnostics_are_limited_to_local_dev_and_yolo_profiles() {
assert!(local_runtime_allows_unsafe_raw_http_diagnostics(
DeploymentMode::LocalSingleUser,
RuntimeProfile::LocalDev,
));
assert!(local_runtime_allows_unsafe_raw_http_diagnostics(
DeploymentMode::LocalSingleUser,
RuntimeProfile::LocalYolo,
));
assert!(!local_runtime_allows_unsafe_raw_http_diagnostics(
DeploymentMode::LocalSingleUser,
RuntimeProfile::LocalSafe,
));
assert!(!local_runtime_allows_unsafe_raw_http_diagnostics(
DeploymentMode::HostedMultiTenant,
RuntimeProfile::HostedYoloTenantScoped,
));
assert!(!local_runtime_allows_unsafe_raw_http_diagnostics(
DeploymentMode::EnterpriseDedicated,
RuntimeProfile::EnterpriseYoloDedicated,
));
}
}
/// Stable, sanitized failure categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RuntimeFailureKind {
Authorization,
Backend,
Cancelled,
Dispatcher,
Internal,
InvalidInput,
InvalidOutput,
MissingRuntime,
Network,
OperationFailed,
OutputTooLarge,
PolicyDenied,
Process,
Resource,
Transient,
Unavailable,
Unknown,
}
impl RuntimeFailureKind {
/// Returns a stable, snake_case identifier for use in metrics/tracing.
pub const fn as_str(self) -> &'static str {
match self {
Self::Authorization => "authorization",
Self::Backend => "backend",
Self::Cancelled => "cancelled",
Self::Dispatcher => "dispatcher",
Self::Internal => "internal",
Self::InvalidInput => "invalid_input",
Self::InvalidOutput => "invalid_output",
Self::MissingRuntime => "missing_runtime",
Self::Network => "network",
Self::OperationFailed => "operation_failed",
Self::OutputTooLarge => "output_too_large",
Self::PolicyDenied => "policy_denied",
Self::Process => "process",
Self::Resource => "resource",
Self::Transient => "transient",
Self::Unavailable => "unavailable",
Self::Unknown => "unknown",
}
}
}
/// Agent-loop handling decision for a sanitized runtime capability failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CapabilityFailureDisposition {
/// Return a normal tool error observation to the model in the same loop.
ModelVisibleToolError,
/// Retry the same runtime invocation before exposing anything to the model.
/// The loop recovery strategy owns the retry budget and post-exhaustion
/// fallback; the host-runtime disposition only classifies the first outcome.
RetrySameCall,
}
const MAX_RUNTIME_FAILURE_SUMMARY_CHARS: usize = 512;
impl RuntimeCapabilityFailure {
pub fn new(
capability_id: CapabilityId,
kind: RuntimeFailureKind,
message: Option<String>,
) -> Self {
Self {
capability_id,
kind,
message,
detail: None,
}
}
pub fn with_detail(mut self, detail: DispatchFailureDetail) -> Self {
self.detail = Some(detail);
self
}
pub fn safe_summary(&self) -> Option<String> {
let summary = self.message.as_deref()?.trim();
if summary.is_empty() {
return None;
}
Some(bounded_runtime_failure_summary(summary))
}
pub fn disposition(&self) -> CapabilityFailureDisposition {
capability_failure_disposition(self.kind)
}
}
fn bounded_runtime_failure_summary(summary: &str) -> String {
const ELLIPSIS: &str = "...";
let mut chars = summary.chars();
let bounded: String = chars
.by_ref()
.take(MAX_RUNTIME_FAILURE_SUMMARY_CHARS)
.collect();
if chars.next().is_some() {
let truncated_limit = MAX_RUNTIME_FAILURE_SUMMARY_CHARS - ELLIPSIS.chars().count();
let bounded: String = bounded.chars().take(truncated_limit).collect();
format!("{bounded}{ELLIPSIS}")
} else {
bounded
}
}
/// Central disposition policy for runtime capability failures.
///
/// Runtime failures should be surfaced through normal model-visible tool-error
/// handling whenever they are not retryable infrastructure outages. Security
/// isolation failures must use a separate quarantine path instead of this
/// generic failure disposition.
pub const fn capability_failure_disposition(
kind: RuntimeFailureKind,
) -> CapabilityFailureDisposition {
if matches!(kind, RuntimeFailureKind::InvalidInput) {
return CapabilityFailureDisposition::ModelVisibleToolError;
}
if runtime_failure_is_retryable(kind) {
return CapabilityFailureDisposition::RetrySameCall;
}
CapabilityFailureDisposition::ModelVisibleToolError
}
const fn runtime_failure_is_retryable(kind: RuntimeFailureKind) -> bool {
matches!(
kind,
RuntimeFailureKind::Internal
| RuntimeFailureKind::Backend
| RuntimeFailureKind::Network
| RuntimeFailureKind::Transient
| RuntimeFailureKind::Unavailable
)
}
/// Work ids tracked by the host runtime for status/cancellation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RuntimeWorkId {
Invocation(ironclaw_host_api::InvocationId),
Process(ProcessId),
Gate(RuntimeGateId),
}
/// Cancellation reason supplied by upper turn/loop services.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CancelReason {
UserRequested,
TurnCancelled,
Shutdown,
Timeout,
}
/// Request to cancel active work in one scope.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CancelRuntimeWorkRequest {
pub scope: ResourceScope,
pub correlation_id: CorrelationId,
pub reason: CancelReason,
}
impl CancelRuntimeWorkRequest {
pub fn new(scope: ResourceScope, correlation_id: CorrelationId, reason: CancelReason) -> Self {
Self {
scope,
correlation_id,
reason,
}
}
}
/// Result of best-effort cancellation fanout.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CancelRuntimeWorkOutcome {
pub cancelled: Vec<RuntimeWorkId>,
pub already_terminal: Vec<RuntimeWorkId>,
pub unsupported: Vec<RuntimeWorkId>,
}
/// Request to inspect active work for a scope.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RuntimeStatusRequest {
pub scope: ResourceScope,
pub correlation_id: CorrelationId,
}
impl RuntimeStatusRequest {
pub fn new(scope: ResourceScope, correlation_id: CorrelationId) -> Self {
Self {
scope,
correlation_id,
}
}
}
/// Redacted summary for active host runtime work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeWorkSummary {
pub work_id: RuntimeWorkId,
pub capability_id: Option<CapabilityId>,
pub runtime: Option<RuntimeKind>,
}
/// Redacted host runtime status.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HostRuntimeStatus {
pub active_work: Vec<RuntimeWorkSummary>,
}
/// Host runtime readiness information.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HostRuntimeHealth {
pub ready: bool,
pub missing_runtime_backends: Vec<RuntimeKind>,
}
/// Backend health probe for concrete runtime implementations.
///
/// The host runtime asks this port about the runtime kinds required by the
/// current visible capability registry. Implementations should return the
/// subset of `required` that is not currently available. Callers must treat a
/// missing probe as "unknown/unready" whenever the registry requires at least
/// one runtime backend.
#[async_trait]
pub trait RuntimeBackendHealth: Send + Sync {
async fn missing_runtime_backends(
&self,
required: &[RuntimeKind],
) -> Result<Vec<RuntimeKind>, HostRuntimeError>;
}
/// Contract for the Reborn host runtime facade.
#[async_trait]
pub trait HostRuntime: Send + Sync {
async fn invoke_capability(
&self,
request: RuntimeCapabilityRequest,
) -> Result<RuntimeCapabilityOutcome, HostRuntimeError>;
async fn spawn_capability(
&self,
request: RuntimeCapabilityRequest,
) -> Result<RuntimeCapabilityOutcome, HostRuntimeError> {
Ok(RuntimeCapabilityOutcome::Failed(
RuntimeCapabilityFailure::new(
request.capability_id,
RuntimeFailureKind::Unavailable,
Some("capability spawn is unsupported by this host runtime".to_string()),
),
))
}
async fn resume_capability(
&self,
request: RuntimeCapabilityResumeRequest,
) -> Result<RuntimeCapabilityOutcome, HostRuntimeError>;
/// Re-dispatch after an auth gate has been resolved.
///
/// Production hosts override this to route through
/// `CapabilityHost::auth_resume_json` which handles the `BlockedAuth`
/// run-state and optionally claims the prior approval lease.
///
/// The default implementation returns an explicit `Failed` outcome so that
/// test stubs that do not override this method fail loudly instead of
/// silently falling back to a fresh `invoke_capability` call (which would
/// bypass run-state validation and the approval-lease-claim path). Any
/// `HostRuntime` implementation that participates in auth-resume flows must
/// provide an explicit override.
async fn auth_resume_capability(
&self,
request: RuntimeCapabilityAuthResumeRequest,
) -> Result<RuntimeCapabilityOutcome, HostRuntimeError> {
Ok(RuntimeCapabilityOutcome::Failed(
RuntimeCapabilityFailure::new(
request.capability_id,
RuntimeFailureKind::Unavailable,
Some("capability auth-resume is unsupported by this host runtime".to_string()),
),
))
}
async fn resume_spawn_capability(
&self,
request: RuntimeCapabilityResumeRequest,
) -> Result<RuntimeCapabilityOutcome, HostRuntimeError> {
Ok(RuntimeCapabilityOutcome::Failed(
RuntimeCapabilityFailure::new(
request.capability_id,
RuntimeFailureKind::Unavailable,
Some("capability spawn resume is unsupported by this host runtime".to_string()),
),
))
}
async fn visible_capabilities(
&self,