harn-vm 0.10.94

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
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::orchestration::{CapabilityPolicy, ToolApprovalPolicy};

use super::receipt::RunAuthorityReceipt;

pub const RUN_AUTHORITY_PLAN_SCHEMA: &str = "harn.run_authority_plan.v1";
pub const RUN_AUTHORITY_RECEIPT_SCHEMA: &str = "harn.run_authority.v1";
pub const RUN_AUTHORITY_PLAN_V1_SCHEMA_JSON: &str =
    include_str!("../../schemas/run-authority-plan.v1.json");

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunInteractivity {
    Interactive,
    NonInteractive,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalAvailability {
    Available,
    Unavailable,
}

/// Prepared-run receipts reuse the canonical permission activity decider
/// vocabulary rather than defining a host-specific approval taxonomy.
pub type AuthorityDecider = crate::orchestration::ToolPermissionDecider;

#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct RunBudget {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spend_microusd: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub turns: Option<u64>,
}

impl RunBudget {
    pub(crate) fn exceeds(&self, ceiling: &Self) -> Vec<&'static str> {
        let mut exceeded = Vec::new();
        if exceeds(self.spend_microusd, ceiling.spend_microusd) {
            exceeded.push("spend_microusd");
        }
        if exceeds(self.time_ms, ceiling.time_ms) {
            exceeded.push("time_ms");
        }
        if exceeds(self.turns, ceiling.turns) {
            exceeded.push("turns");
        }
        exceeded
    }

    pub(crate) fn missing_dimensions(&self) -> Vec<&'static str> {
        let mut missing = Vec::new();
        if self.spend_microusd.is_none() {
            missing.push("spend_microusd");
        }
        if self.time_ms.is_none() {
            missing.push("time_ms");
        }
        if self.turns.is_none() {
            missing.push("turns");
        }
        missing
    }
}

fn exceeds(requested: Option<u64>, ceiling: Option<u64>) -> bool {
    matches!((requested, ceiling), (Some(requested), Some(ceiling)) if requested > ceiling)
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct RuntimeContractProvenance {
    pub harn_version: String,
    pub harn_revision: String,
    pub host_name: String,
    pub host_version: String,
    pub host_revision: String,
    pub contracts_version: String,
    pub runtime_digest: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SecretSourceKind {
    ProcessLocal,
    DurableBroker,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SecretConsumerKind {
    Provider,
    Process,
    Mcp,
    Connector,
}

/// A canonical Harn secret reference. Construction rejects raw values so a
/// run authority plan cannot accidentally serialize credential material.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct SecretReference(String);

impl SecretReference {
    pub fn parse(raw: &str) -> Result<Self, String> {
        let id = crate::secrets::parse_secret_ref(raw)
            .ok()
            .flatten()
            .ok_or_else(|| {
                "secret reference must use harn-secret://<namespace>/<name>".to_string()
            })?;
        Ok(Self(format!("{}{}", crate::secrets::SECRET_REF_SCHEME, id)))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for SecretReference {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for SecretReference {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        Self::parse(&raw).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct SecretConsumerBinding {
    pub kind: SecretConsumerKind,
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment_name: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct SecretRequirement {
    pub reference: SecretReference,
    pub source: SecretSourceKind,
    pub consumer: SecretConsumerBinding,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SecretBrokerFacts {
    pub outside_sandbox: bool,
    pub supports_non_interactive: bool,
    pub may_prompt_gui: bool,
    pub zeroizing_handles: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct NetworkRequirement {
    pub destination: String,
    pub protocol: String,
    pub port: u16,
}

impl NetworkRequirement {
    pub(crate) fn url(&self) -> String {
        format!("{}://{}:{}", self.protocol, self.destination, self.port)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessSocketKind {
    Unix,
    TcpLoopback,
    Docker,
    SshAgent,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct ProcessSocketRequirement {
    pub socket_kind: ProcessSocketKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct McpRequirement {
    pub server: String,
    pub tool: String,
    pub side_effect: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AuthorityRequirement {
    FilesystemRead {
        root: String,
    },
    FilesystemWrite {
        root: String,
    },
    ProcessReadRoot {
        root: String,
    },
    ProcessWriteRoot {
        root: String,
    },
    ProcessSandbox {
        profile: String,
        preset: String,
    },
    ProcessSocket(ProcessSocketRequirement),
    Network(NetworkRequirement),
    Secret(SecretRequirement),
    Environment {
        name: String,
    },
    Tool {
        pattern: String,
    },
    HostCapability {
        capability: String,
        operation: String,
    },
    SideEffectCeiling {
        level: String,
    },
    RecursionLimit {
        depth: usize,
    },
    Mcp(McpRequirement),
    Budget {
        budget: RunBudget,
    },
    Provenance {
        provenance: RuntimeContractProvenance,
    },
    Startup {
        deadline_at_ms: u64,
        receipt_uri: String,
    },
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RunIntent {
    pub intent_id: String,
    pub capability_policy: CapabilityPolicy,
    #[serde(default)]
    pub network: Vec<NetworkRequirement>,
    #[serde(default)]
    pub secrets: Vec<SecretRequirement>,
    #[serde(default)]
    pub admitted_environment: Vec<String>,
    #[serde(default)]
    pub process_sockets: Vec<ProcessSocketRequirement>,
    #[serde(default)]
    pub mcp: Vec<McpRequirement>,
    pub budget: RunBudget,
    pub provenance: RuntimeContractProvenance,
    pub interactivity: RunInteractivity,
    pub startup_deadline_at_ms: u64,
    pub receipt_uri: String,
}

#[derive(Clone, Debug)]
pub struct HostFacts {
    pub capability_ceiling: CapabilityPolicy,
    pub approval_policy: ToolApprovalPolicy,
    pub approval_availability: ApprovalAvailability,
    pub approved_batches: BTreeMap<String, AuthorityDecider>,
    pub net_policy: crate::harness_net::NetPolicy,
    pub secret_bindings: BTreeSet<SecretRequirement>,
    pub secret_brokers: BTreeMap<SecretSourceKind, SecretBrokerFacts>,
    pub admitted_environment: BTreeSet<String>,
    pub process_sockets: BTreeSet<ProcessSocketRequirement>,
    pub mcp: BTreeSet<McpRequirement>,
    pub budget_ceiling: RunBudget,
    pub provenance: RuntimeContractProvenance,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RunAuthorityPlanV1 {
    pub schema: String,
    pub intent_id: String,
    pub capability_policy: CapabilityPolicy,
    pub requirements: Vec<AuthorityRequirement>,
    pub budget: RunBudget,
    pub provenance: RuntimeContractProvenance,
    pub interactivity: RunInteractivity,
    pub startup_deadline_at_ms: u64,
    pub receipt_uri: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthorityDiagnostic {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requirement_fingerprint: Option<String>,
    pub actionable: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ApprovalGroup {
    pub semantic_group: String,
    pub requirement_fingerprints: Vec<String>,
    pub summaries: Vec<String>,
    pub risk_labels: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ApprovalBatch {
    pub batch_fingerprint: String,
    pub plan_fingerprint: String,
    pub groups: Vec<ApprovalGroup>,
}

#[derive(Debug)]
pub enum PreparationOutcome {
    Ready {
        authority_lease: Box<AuthorityLease>,
        receipt: RunAuthorityReceipt,
    },
    NeedsApproval {
        batched_requests: ApprovalBatch,
        receipt: RunAuthorityReceipt,
    },
    Blocked {
        diagnostics: Vec<AuthorityDiagnostic>,
        receipt: Option<RunAuthorityReceipt>,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuthorityLeaseDelta {
    pub(crate) parent_lease_fingerprint: String,
    pub(crate) requirement: AuthorityRequirement,
    pub(crate) requirement_fingerprint: String,
    pub(crate) expires_at_ms: u64,
}

impl AuthorityLeaseDelta {
    pub fn parent_lease_fingerprint(&self) -> &str {
        &self.parent_lease_fingerprint
    }

    pub fn requirement(&self) -> &AuthorityRequirement {
        &self.requirement
    }

    pub fn requirement_fingerprint(&self) -> &str {
        &self.requirement_fingerprint
    }

    pub fn expires_at_ms(&self) -> u64 {
        self.expires_at_ms
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LeaseDeltaOutcome {
    Covered,
    Attenuated(AuthorityLeaseDelta),
    Blocked(AuthorityDiagnostic),
}

#[derive(Debug)]
pub struct AuthorityLease {
    pub(crate) lease_fingerprint: String,
    pub(crate) plan_fingerprint: String,
    pub(crate) plan: RunAuthorityPlanV1,
    pub(crate) requirement_fingerprints: BTreeMap<String, AuthorityRequirement>,
    pub(crate) approval_policy: ToolApprovalPolicy,
    pub(crate) net_policy: crate::harness_net::NetPolicy,
    pub(crate) deciders: BTreeMap<String, AuthorityDecider>,
    pub(crate) expires_at_ms: u64,
}

impl AuthorityLease {
    pub fn fingerprint(&self) -> &str {
        &self.lease_fingerprint
    }

    pub fn plan_fingerprint(&self) -> &str {
        &self.plan_fingerprint
    }

    pub fn expires_at_ms(&self) -> u64 {
        self.expires_at_ms
    }

    pub fn plan(&self) -> &RunAuthorityPlanV1 {
        &self.plan
    }
}