interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / rust / crates / interplane-conformance / tests / hosts / mod.rs

486 lines · 15809 bytes Raw Blame History
1//! The two hosts whose adapter runs are recorded under bench/runs, as [`AdapterHost`]s:
2//!
3//! * `toy`: the to-do host of the independent reproduction (bench/runs/adapter-repro-20261005T1215Z).
4//! * `home`: the maintainer's smart-home check (bench/runs/home-check-20261005T1320Z).
5//!
6//! Each is a line-for-line port of the recorded host; `tests/adapter_runner.rs` proves it against
7//! the recorded verdict files.
8#![allow(dead_code)]
9use interplane_conformance::adapter_runner::AdapterHost;
10use interplane_core::{
11 CapabilityDescriptor, CapabilityRequest, Catalog, Decision, Limits, RequestLedger,
12 ResultProvenance, ToolResult, TrustLevel,
13};
14use interplane_crossaxis::MappingTable;
15use interplane_crossveil::{CallContext, Pipeline, RuntimeAuthority};
16use interplane_lenshift::DialectRegistry;
17use serde_json::{json, Map, Value};
18
19const TRUSTED_FLOORS: [&str; 2] = ["user_supplied", "trusted_runtime"];
20
21/// `{"type": "object", "properties": {k: {"type": "string"}}, "required": [...]}`
22fn params(required: &[&str], optional: &[&str]) -> Map<String, Value> {
23 let props: Map<String, Value> = required
24 .iter()
25 .chain(optional)
26 .map(|k| (k.to_string(), json!({"type": "string"})))
27 .collect();
28 json!({"type": "object", "properties": props, "required": required})
29 .as_object()
30 .unwrap()
31 .clone()
32}
33
34fn descriptor(
35 name: &str,
36 desc: &str,
37 ns: &str,
38 canonical: &str,
39 p: Map<String, Value>,
40 domains: &[&str],
41) -> CapabilityDescriptor {
42 serde_json::from_value(json!({
43 "name": name, "description": desc, "parameters": p, "domains": domains,
44 "canonical": {"namespace": ns, "name": canonical},
45 }))
46 .unwrap()
47}
48
49fn catalog(runtime: &str, caps: Vec<CapabilityDescriptor>) -> Catalog {
50 serde_json::from_value(json!({"kind": "catalog", "runtime": runtime, "catalog_version": "1", "capabilities": caps}))
51 .unwrap()
52}
53
54/// A mapping table: one passthrough rule per name, then `(namespace, alias, target)` alias rules.
55fn table(
56 runtime: &str,
57 cat: &Catalog,
58 names: &[&str],
59 aliases: &[(&str, &str, &str)],
60) -> MappingTable {
61 let mut rules: Vec<Value> = names
62 .iter()
63 .map(|n| json!({"id": format!("passthrough:{n}"), "kind": "passthrough", "from": {"namespace": null, "name": n}, "to": n}))
64 .collect();
65 rules.extend(aliases.iter().map(|(ns, a, t)| {
66 json!({"id": format!("alias:{ns}.{a}"), "kind": "alias", "from": {"namespace": ns, "name": a}, "to": t})
67 }));
68 serde_json::from_value(json!({"runtime": runtime, "table_version": "1",
69 "catalog_digest": cat.compute_digest(), "rules": rules}))
70 .unwrap()
71}
72
73fn pipeline<'a>(table: MappingTable, authority: &'a mut dyn RuntimeAuthority) -> Pipeline<'a> {
74 Pipeline::new(
75 DialectRegistry::with_defaults(),
76 table,
77 authority,
78 Limits::default(),
79 RequestLedger::new(),
80 )
81}
82
83/// The decision a host returns: its own runtime, policy and decision id.
84#[allow(clippy::too_many_arguments)]
85fn decision(
86 rid: &str,
87 value: &str,
88 runtime: &str,
89 policy: &str,
90 decision_id: &str,
91 cap: &str,
92 reason: &str,
93 approval: Value,
94) -> Decision {
95 serde_json::from_value(json!({
96 "kind": "decision", "request_id": rid, "decision": value, "capability": cap,
97 "authority": {"runtime": runtime, "policy_engine": policy, "decision_id": decision_id},
98 "reason": reason, "approval": approval,
99 }))
100 .unwrap()
101}
102
103fn approval(id: String, expires_at: &Option<String>) -> Value {
104 json!({"approval_id": id, "scope": "single_action", "expires_at": expires_at})
105}
106
107/// An `ok` result labelled by the host (`trusted` follows `trust`).
108fn labelled(
109 rid: &str,
110 runtime: &str,
111 cap: &str,
112 data: Value,
113 kind: &str,
114 trust: &str,
115) -> ToolResult {
116 let mut r = ToolResult::ok(rid, data);
117 let trust: TrustLevel = serde_json::from_value(json!(trust)).unwrap();
118 r.provenance = Some(ResultProvenance {
119 capability: Some(cap.into()),
120 content_kind: serde_json::from_value(json!(kind)).unwrap(),
121 duration_ms: None,
122 runtime: Some(runtime.into()),
123 trusted: trust.trusted_flag(),
124 trust: Some(trust),
125 extensions: Map::new(),
126 });
127 r
128}
129
130fn floor(ctx: &CallContext) -> Option<String> {
131 ctx.exposure
132 .as_ref()
133 .and_then(|e| serde_json::to_value(&e.floor).ok())
134 .and_then(|v| v.as_str().map(String::from))
135}
136
137fn text_args(args: &Map<String, Value>, keys: &[&str]) -> bool {
138 keys.iter()
139 .all(|k| args.get(*k).is_some_and(Value::is_string))
140}
141
142fn arg(args: &Map<String, Value>, k: &str) -> String {
143 args.get(k)
144 .and_then(Value::as_str)
145 .unwrap_or("")
146 .to_string()
147}
148
149// ---- smart-home host (bench/runs/home-check-20261005T1320Z)
150
151pub struct Home;
152
153const HOME_NAMES: [&str; 4] = ["read_sensors", "set_light", "send_alert", "unlock_door"];
154
155fn home_catalog() -> Catalog {
156 let cap = |n: &str, d: &str, req: &[&str], opt: &[&str]| {
157 descriptor(n, d, "home", n, params(req, opt), &["home"])
158 };
159 catalog(
160 "home",
161 vec![
162 cap("read_sensors", "Read the home's sensors.", &[], &["room"]),
163 cap("set_light", "Set a room's light.", &["room", "level"], &[]),
164 cap(
165 "send_alert",
166 "Send an alert message out of the home.",
167 &["to", "message"],
168 &[],
169 ),
170 cap("unlock_door", "Unlock a door.", &["door"], &[]),
171 ],
172 )
173}
174
175pub struct HomeAuthority {
176 no_exposure_check: bool,
177 expires_at: Option<String>,
178 catalog: Catalog,
179 pub lights: Vec<(String, String)>,
180 pub alerts: Vec<(String, String)>,
181 pub unlocked: Vec<String>,
182}
183
184impl RuntimeAuthority for HomeAuthority {
185 fn runtime_id(&self) -> &str {
186 "home"
187 }
188 fn catalog(&self) -> Catalog {
189 self.catalog.clone()
190 }
191 fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision {
192 let trusted = self.no_exposure_check
193 || floor(ctx).is_some_and(|f| TRUSTED_FLOORS.contains(&f.as_str()));
194 let required: &[&str] = match req.capability.as_str() {
195 "read_sensors" => &[],
196 "set_light" => &["room", "level"],
197 "send_alert" => &["to", "message"],
198 "unlock_door" => &["door"],
199 _ => &["\u{0}unknown"],
200 };
201 let (value, reason) = if !HOME_NAMES.contains(&req.capability.as_str()) {
202 ("not_found", "no such home capability")
203 } else if !text_args(&req.arguments, required) {
204 ("invalid", "missing or non-text argument")
205 } else if req.capability == "read_sensors" {
206 ("authorized", "reads are allowed")
207 } else if req.capability == "unlock_door" {
208 (
209 "requires_approval",
210 "unlocking a door always needs a person",
211 )
212 } else if req.capability == "set_light" {
213 if trusted {
214 ("authorized", "allowed")
215 } else {
216 ("requires_approval", "untrusted content in view")
217 }
218 } else if trusted {
219 // send_alert: data leaving the home is refused after untrusted input
220 ("authorized", "allowed")
221 } else {
222 ("denied", "no outbound alerts after untrusted input")
223 };
224 let ap = if value == "requires_approval" {
225 approval(
226 format!("home-approval-{}", req.request_id),
227 &self.expires_at,
228 )
229 } else {
230 Value::Null
231 };
232 let did = format!("home-{}", req.request_id);
233 decision(
234 &req.request_id,
235 value,
236 "home",
237 "home.policy",
238 &did,
239 &req.capability,
240 reason,
241 ap,
242 )
243 }
244 fn execute(
245 &mut self,
246 req: &CapabilityRequest,
247 _d: &Decision,
248 _ctx: &CallContext,
249 ) -> ToolResult {
250 let a = &req.arguments;
251 let rid = &req.request_id;
252 match req.capability.as_str() {
253 "read_sensors" => {
254 let lights: Map<String, Value> = self
255 .lights
256 .iter()
257 .map(|(k, v)| (k.clone(), json!(v)))
258 .collect();
259 // room names are user-set
260 return labelled(
261 rid,
262 "home",
263 &req.capability,
264 json!({"lights": lights, "temperature_c": 21}),
265 "workspace_content",
266 "workspace_untrusted",
267 );
268 }
269 "set_light" => {
270 let (room, level) = (arg(a, "room"), arg(a, "level"));
271 match self.lights.iter_mut().find(|(k, _)| *k == room) {
272 Some(slot) => slot.1 = level,
273 None => self.lights.push((room, level)),
274 }
275 }
276 "send_alert" => self.alerts.push((arg(a, "to"), arg(a, "message"))),
277 _ => self.unlocked.push(arg(a, "door")),
278 }
279 labelled(
280 rid,
281 "home",
282 &req.capability,
283 json!({"done": req.capability}),
284 "tool_result",
285 "trusted_runtime",
286 )
287 }
288}
289
290impl AdapterHost for Home {
291 fn runtime(&self) -> &str {
292 "home"
293 }
294 fn policy(&self) -> &str {
295 "home.policy"
296 }
297 fn make_authority(
298 &self,
299 no_exposure_check: bool,
300 expires_at: Option<&str>,
301 ) -> Box<dyn RuntimeAuthority> {
302 Box::new(HomeAuthority {
303 no_exposure_check,
304 expires_at: expires_at.map(String::from),
305 catalog: home_catalog(),
306 lights: vec![("hall".into(), "off".into())],
307 alerts: vec![],
308 unlocked: vec![],
309 })
310 }
311 fn make_pipeline<'a>(&self, authority: &'a mut dyn RuntimeAuthority) -> Pipeline<'a> {
312 let t = table("home", &authority.catalog(), &HOME_NAMES, &[]);
313 pipeline(t, authority)
314 }
315}
316
317// ---- to-do host of the independent reproduction (bench/runs/adapter-repro-20261005T1215Z)
318
319pub struct Toy;
320
321fn toy_catalog() -> Catalog {
322 catalog(
323 "toy",
324 vec![
325 descriptor(
326 "list_items",
327 "List to-do items.",
328 "todo",
329 "list",
330 params(&[], &["scope"]),
331 &["todo"],
332 ),
333 descriptor(
334 "add_item",
335 "Add a to-do item.",
336 "todo",
337 "add",
338 params(&["text"], &["list"]),
339 &["todo"],
340 ),
341 descriptor(
342 "delete_item",
343 "Delete a to-do item.",
344 "todo",
345 "delete",
346 params(&["item_id"], &[]),
347 &["todo"],
348 ),
349 ],
350 )
351}
352
353pub struct TodoAuthority {
354 no_exposure_check: bool,
355 expires_at: Option<String>,
356 catalog: Catalog,
357 pub items: Vec<(String, Value)>,
358 next_id: u64,
359}
360
361impl RuntimeAuthority for TodoAuthority {
362 fn runtime_id(&self) -> &str {
363 "toy"
364 }
365 fn catalog(&self) -> Catalog {
366 self.catalog.clone()
367 }
368 fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision {
369 let name = req.capability.as_str();
370 let args = &req.arguments;
371 let (required, optional): (&[&str], &[&str]) = match name {
372 "list_items" => (&[], &["scope"]),
373 "add_item" => (&["text"], &["list"]),
374 "delete_item" => (&["item_id"], &[]),
375 _ => (&[], &[]),
376 };
377 let trusted_floor = floor(ctx).is_some_and(|f| TRUSTED_FLOORS.contains(&f.as_str()));
378 let (value, reason) = if !["list_items", "add_item", "delete_item"].contains(&name) {
379 ("not_found", "unknown to-do capability")
380 } else if !text_args(args, required)
381 || optional
382 .iter()
383 .any(|k| args.get(*k).is_some_and(|v| !v.is_string()))
384 {
385 ("invalid", "required to-do argument missing or not text")
386 } else if name == "delete_item" {
387 ("requires_approval", "toy policy: deletion needs approval")
388 } else if name == "add_item" && !self.no_exposure_check && !trusted_floor {
389 (
390 "requires_approval",
391 "toy policy: effects after untrusted input need approval",
392 )
393 } else {
394 ("authorized", "toy policy permits this action")
395 };
396 let ap = if value == "requires_approval" {
397 approval(format!("toy-approval-{}", req.request_id), &self.expires_at)
398 } else {
399 Value::Null
400 };
401 let did = format!("toy-decision-{}", req.request_id);
402 decision(
403 &req.request_id,
404 value,
405 "toy",
406 "toy.todo.policy",
407 &did,
408 name,
409 reason,
410 ap,
411 )
412 }
413 fn execute(
414 &mut self,
415 req: &CapabilityRequest,
416 _d: &Decision,
417 _ctx: &CallContext,
418 ) -> ToolResult {
419 let (name, args, rid) = (req.capability.as_str(), &req.arguments, &req.request_id);
420 let (data, kind) = match name {
421 "list_items" => {
422 let items: Vec<Value> = self.items.iter().map(|(_, v)| v.clone()).collect();
423 (json!({"items": items}), "workspace_content")
424 }
425 "add_item" => {
426 let id = format!("item-{}", self.next_id);
427 self.next_id += 1;
428 let list = args.get("list").cloned().unwrap_or(json!("inbox"));
429 let item = json!({"id": id, "text": args.get("text").cloned().unwrap_or(Value::Null), "list": list});
430 self.items.push((id, item.clone()));
431 (json!({"item": item}), "tool_result")
432 }
433 _ => {
434 let id = arg(args, "item_id");
435 let before = self.items.len();
436 self.items.retain(|(k, _)| *k != id);
437 (
438 json!({"item_id": id, "deleted": self.items.len() != before}),
439 "tool_result",
440 )
441 }
442 };
443 labelled(rid, "toy", name, data, kind, "workspace_untrusted")
444 }
445}
446
447impl AdapterHost for Toy {
448 fn runtime(&self) -> &str {
449 "toy"
450 }
451 fn policy(&self) -> &str {
452 "toy.todo.policy"
453 }
454 fn make_authority(
455 &self,
456 no_exposure_check: bool,
457 expires_at: Option<&str>,
458 ) -> Box<dyn RuntimeAuthority> {
459 let items = ["old.txt", "a.txt", "b.txt"]
460 .iter()
461 .map(|k| {
462 (
463 k.to_string(),
464 json!({"id": k, "text": "Existing item", "list": "inbox"}),
465 )
466 })
467 .collect();
468 Box::new(TodoAuthority {
469 no_exposure_check,
470 expires_at: expires_at.map(String::from),
471 catalog: toy_catalog(),
472 items,
473 next_id: 1,
474 })
475 }
476 fn make_pipeline<'a>(&self, authority: &'a mut dyn RuntimeAuthority) -> Pipeline<'a> {
477 let names = ["list_items", "add_item", "delete_item"];
478 let aliases = [
479 ("todo", "list", "list_items"),
480 ("todo", "add", "add_item"),
481 ("todo", "delete", "delete_item"),
482 ];
483 let t = table("toy", &authority.catalog(), &names, &aliases);
484 pipeline(t, authority)
485 }
486}