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 / adapters / aien / src / bin / aien-authority-bridge.rs

237 lines · 9909 bytes Raw Blame History
1//! Line-delimited JSON bridge over the real [`AienAuthority`].
2//!
3//! `aien-authority-bridge <workspace>` reads one JSON request per line on stdin and writes
4//! exactly one JSON line per request on stdout. It adds no authority: `decide`, `execute`
5//! and the approval calls go straight to `AienAuthority`, and every answer is the serde JSON of the
6//! real `interplane-core` type (`Catalog`, `Decision`, `ToolResult`). It decides nothing itself.
7//!
8//! Requests (`op`):
9//! `catalog` -> `{"ok":true,"catalog":Catalog}`
10//! `mapping_table` -> `{"ok":true,"mapping_table":MappingTable}` (pinned)
11//! `decide` `request`, `ctx` -> `{"ok":true,"decision":Decision}`
12//! `execute` `request`, `decision`, `ctx` -> `{"ok":true,"result":ToolResult}` (only for a request this
13//! bridge decided `authorized` itself, once; the supplied `decision` is never trusted)
14//! `approve` `request`, optional `ttl_secs` -> `{"ok":true,"decision":Decision}` (host-only
15//! approver channel: AIEN's own desk issues one single-use grant for exactly this
16//! request and `present_approval` spends it; the continuation decision is AIEN's)
17//! `discard` `request_id` -> `{"ok":true,"discarded":bool}`
18//! Anything else (unknown op, malformed JSON, wrong shape, bad trace id) is `{"ok":false,"error":..}`
19//! and never a decision.
20use std::collections::{HashMap, HashSet};
21use std::io::{BufRead, Write};
22
23use interplane_adapter_aien::{host_clock, AienAuthority};
24use interplane_core::{CapabilityRequest, Decision, Exposure, Party};
25use interplane_crossveil::{CallContext, RuntimeAuthority};
26use serde_json::{json, Map, Value};
27
28const DEFAULT_TTL_SECS: u64 = 300;
29const MAX_TTL_SECS: u64 = 3600;
30
31fn err(msg: impl Into<String>) -> Value {
32 json!({"ok": false, "error": msg.into()})
33}
34
35fn field<T: serde::de::DeserializeOwned>(obj: &Map<String, Value>, key: &str) -> Result<T, String> {
36 let v = obj
37 .get(key)
38 .ok_or_else(|| format!("missing field: {key}"))?;
39 serde_json::from_value(v.clone()).map_err(|e| format!("bad {key}: {e}"))
40}
41
42fn is_trace_id(s: &str) -> bool {
43 s.len() == 32
44 && s.bytes()
45 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
46}
47
48fn context(obj: &Map<String, Value>) -> Result<CallContext, String> {
49 let ctx = obj
50 .get("ctx")
51 .and_then(Value::as_object)
52 .ok_or("missing field: ctx")?;
53 let text = |k: &str| -> Result<String, String> {
54 ctx.get(k)
55 .and_then(Value::as_str)
56 .map(str::to_string)
57 .ok_or_else(|| format!("ctx.{k} must be a string"))
58 };
59 let trace_id = text("trace_id")?;
60 if !is_trace_id(&trace_id) {
61 return Err("ctx.trace_id must be 32 lowercase hex characters".into());
62 }
63 let parent_id = match ctx.get("parent_id") {
64 None | Some(Value::Null) => None,
65 Some(Value::String(s)) => Some(s.clone()),
66 Some(_) => return Err("ctx.parent_id must be a string or null".into()),
67 };
68 let model = match ctx.get("model") {
69 None | Some(Value::Null) => Party::new("model", "unknown"),
70 Some(v) => serde_json::from_value(v.clone()).map_err(|e| format!("bad ctx.model: {e}"))?,
71 };
72 let exposure = match ctx.get("exposure") {
73 None | Some(Value::Null) => None,
74 Some(v) => Some(
75 serde_json::from_value::<Exposure>(v.clone())
76 .map_err(|e| format!("bad ctx.exposure: {e}"))?,
77 ),
78 };
79 Ok(CallContext {
80 trace_id,
81 message_id: text("message_id")?,
82 parent_id,
83 model,
84 session: ctx.get("runtime_session").filter(|v| !v.is_null()).cloned(),
85 exposure,
86 })
87}
88
89fn to_value<T: serde::Serialize>(key: &str, v: &T) -> Value {
90 match serde_json::to_value(v) {
91 Ok(x) => json!({"ok": true, key: x}),
92 Err(e) => err(format!("cannot serialize {key}: {e}")),
93 }
94}
95
96/// What this bridge itself recorded for one request id. Restriction only: it never grants anything.
97struct Seen {
98 request: CapabilityRequest,
99 decision: Decision,
100 executed: bool,
101}
102
103#[derive(Default)]
104struct State {
105 /// Request ids for which an approve was attempted (any outcome).
106 approved: HashSet<String>,
107 /// Request ids decided by AIEN through this bridge, with AIEN's own decision.
108 seen: HashMap<String, Seen>,
109}
110
111fn handle(aien: &mut AienAuthority, state: &mut State, line: &str) -> Value {
112 let parsed: Value = match serde_json::from_str(line) {
113 Ok(v) => v,
114 Err(e) => return err(format!("malformed json: {e}")),
115 };
116 let Some(obj) = parsed.as_object() else {
117 return err("request must be a json object");
118 };
119 let Some(op) = obj.get("op").and_then(Value::as_str) else {
120 return err("missing field: op");
121 };
122 let mut run = || -> Result<Value, String> {
123 match op {
124 "catalog" => Ok(to_value("catalog", &aien.catalog())),
125 "mapping_table" => Ok(to_value("mapping_table", &aien.mapping_table(true))),
126 "decide" => {
127 let req: CapabilityRequest = field(obj, "request")?;
128 let ctx = context(obj)?;
129 if state.seen.contains_key(&req.request_id) {
130 return Err(format!("request {} was already decided", req.request_id));
131 }
132 let decision = aien.decide(&req, &ctx);
133 state.seen.insert(
134 req.request_id.clone(),
135 Seen {
136 request: req,
137 decision: decision.clone(),
138 executed: false,
139 },
140 );
141 Ok(to_value("decision", &decision))
142 }
143 "execute" => {
144 let req: CapabilityRequest = field(obj, "request")?;
145 // A client-supplied decision is parsed for shape only; it is never authority.
146 let _: Decision = field(obj, "decision")?;
147 let ctx = context(obj)?;
148 let Some(seen) = state.seen.get_mut(&req.request_id) else {
149 return Err(format!("request {} was never decided here", req.request_id));
150 };
151 if seen.request != req {
152 return Err(format!(
153 "request {} differs from the decided one",
154 req.request_id
155 ));
156 }
157 if !seen.decision.is_authorized() {
158 return Err(format!(
159 "request {} has no authorized decision",
160 req.request_id
161 ));
162 }
163 if seen.executed {
164 return Err(format!("request {} was already executed", req.request_id));
165 }
166 seen.executed = true;
167 let own = seen.decision.clone();
168 Ok(to_value("result", &aien.execute(&req, &own, &ctx)))
169 }
170 "approve" => {
171 let req: CapabilityRequest = field(obj, "request")?;
172 let ttl = match obj.get("ttl_secs") {
173 None | Some(Value::Null) => DEFAULT_TTL_SECS,
174 Some(v) => v
175 .as_u64()
176 .filter(|t| (1..=MAX_TTL_SECS).contains(t))
177 .ok_or("ttl_secs must be an integer from 1 to 3600")?,
178 };
179 // Restriction only: one approval attempt per request id, recorded on any attempt. AIEN's desk would issue another grant.
180 if state.approved.contains(&req.request_id) {
181 return Err(format!("approval already requested for {}", req.request_id));
182 }
183 // Recorded before AIEN is asked, whatever the outcome: a failed attempt is not retried.
184 state.approved.insert(req.request_id.clone());
185 match state.seen.get(&req.request_id) {
186 Some(seen) if seen.request == req && !seen.executed => {}
187 _ => return Err(format!("request {} was not decided here", req.request_id)),
188 }
189 let now = (host_clock())();
190 let grant = aien.issue_approval(&req, now + ttl)?;
191 let decision = aien.present_approval(&req, &grant, now);
192 if decision.is_authorized() {
193 if let Some(seen) = state.seen.get_mut(&req.request_id) {
194 seen.decision = decision.clone();
195 }
196 }
197 Ok(to_value("decision", &decision))
198 }
199 "discard" => {
200 let rid: String = field(obj, "request_id")?;
201 Ok(json!({"ok": true, "discarded": aien.discard_unexecuted(&rid)}))
202 }
203 other => Err(format!("unknown op: {other}")),
204 }
205 };
206 run().unwrap_or_else(err)
207}
208
209fn main() {
210 let Some(workspace) = std::env::args().nth(1) else {
211 eprintln!("usage: aien-authority-bridge <workspace>");
212 std::process::exit(2);
213 };
214 let mut aien = match AienAuthority::new(&workspace) {
215 Ok(a) => a,
216 Err(e) => {
217 eprintln!("aien-authority-bridge: {e}");
218 std::process::exit(2);
219 }
220 };
221 let mut state = State::default();
222 let stdin = std::io::stdin();
223 let mut out = std::io::stdout().lock();
224 for line in stdin.lock().lines() {
225 let Ok(line) = line else { break };
226 if line.trim().is_empty() {
227 continue;
228 }
229 let answer = handle(&mut aien, &mut state, &line);
230 if writeln!(out, "{answer}")
231 .and_then(|()| out.flush())
232 .is_err()
233 {
234 break;
235 }
236 }
237}