1use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
7pub mod bridge;
8pub mod cl;
9pub mod batch;
10pub mod cnp;
11pub mod did;
12pub mod dialogue;
13pub mod idl;
14pub mod protocol;
15pub mod codegen;
16pub mod runtime;
17pub mod session;
18pub mod scenario;
19pub mod stdlib;
20pub mod schema;
21pub mod semantics;
22pub mod sealed;
23pub mod idempotency;
24pub mod registry;
25pub mod registry_protocols;
26pub mod replay;
27pub mod rdf;
28use serde::{Deserialize, Serialize};
29use serde_repr::{Deserialize_repr, Serialize_repr};
30use std::io::Read;
31
32pub const ACL_VERSION: u8 = 1;
33pub const MAX_HOP_COUNT: u8 = 8;
34pub const DEFAULT_TTL_MS: u32 = 300_000;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]
40#[repr(u8)]
41pub enum Performative {
42 Request = 1,
43 Inform = 2,
44 Query = 3,
45 Propose = 4,
46 Accept = 5,
47 Reject = 6,
48 Cancel = 7,
49 Progress = 8,
50 InputRequired = 9,
51 Failure = 10,
52 Delegate = 11,
53 Error = 12,
54 Hello = 13,
55 Bye = 14,
56 Retract = 15,
58 Subscribe = 16,
60 Unsubscribe = 17,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
66pub struct Artifact {
67 pub name: String,
68 pub mime: String,
69 #[serde(with = "serde_bytes")]
71 pub bytes: Vec<u8>,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ErrorKind {
78 UnknownPredicate,
79 SchemaViolation,
80 MailboxFull,
81 RateLimited,
82 Unauthorized,
83 UnknownAgent,
84 DecodeFailed,
85 Expired,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
90#[serde(tag = "t", content = "v")]
91pub enum Body {
92 Task {
93 description: String,
94 input: serde_json::Value,
95 #[serde(skip_serializing_if = "Option::is_none")]
96 deadline_ms: Option<u32>,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 priority: Option<u8>,
99 },
100 Result {
101 output: serde_json::Value,
102 #[serde(default)]
103 artifacts: Vec<Artifact>,
104 },
105 Text {
106 text: String,
107 },
108 Query {
109 subject: String,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 parameters: Option<serde_json::Value>,
112 },
113 Proposal {
114 terms: serde_json::Value,
115 #[serde(skip_serializing_if = "Option::is_none")]
116 price: Option<String>,
117 #[serde(skip_serializing_if = "Option::is_none")]
118 valid_until: Option<i64>,
119 },
120 Ref {
121 target_msg_id: String,
122 },
123 Progress {
124 target_msg_id: String,
125 #[serde(skip_serializing_if = "Option::is_none")]
126 percent: Option<u8>,
127 #[serde(skip_serializing_if = "Option::is_none")]
128 note: Option<String>,
129 },
130 InputNeeded {
131 target_msg_id: String,
132 what: String,
133 #[serde(skip_serializing_if = "Option::is_none")]
134 schema: Option<serde_json::Value>,
135 },
136 Failure {
137 target_msg_id: String,
138 code: u16,
139 reason: String,
140 recoverable: bool,
141 },
142 Error {
143 code: u16,
144 message: String,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
147 taxonomy: Option<ErrorKind>,
148 #[serde(skip_serializing_if = "Option::is_none")]
149 details: Option<serde_json::Value>,
150 },
151 Hello {
152 agent_card: Option<AgentCard>,
153 card_hash: Option<String>,
154 nonce: Vec<u8>,
155 },
156 Delegate {
157 task: Box<Body>, chain: Vec<String>,
159 },
160 Sealed {
162 sender_pub: Vec<u8>,
163 salt: Vec<u8>,
164 ciphertext: Vec<u8>,
165 },
166 Cl {
169 expressions: Vec<crate::cl::ClExpr>,
170 },
171 #[serde(rename = "subscribe")]
173 Subscribe { watch: Box<crate::Matcher>, until_ms: Option<i64> },
174 #[serde(rename = "unsubscribe")]
176 Unsubscribe { target_msg_id: String },
177 #[serde(rename = "key_rotation")]
181 KeyRotation {
182 new_did: String,
183 valid_from_ms: i64,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 reason: Option<String>,
186 },
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
192pub struct Matcher {
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub performative: Option<Performative>,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub from: Option<String>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub predicate: Option<String>,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
206pub struct Aid(pub String);
207
208impl Aid {
209 pub fn new(s: impl Into<String>) -> Self {
210 Aid(s.into())
211 }
212 pub fn scheme(&self) -> Option<&str> {
213 self.0.split(':').next()
214 }
215 pub fn local(pid: u32, session: &str) -> Self {
216 Aid(format!("local:{pid}:{session}"))
217 }
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct Envelope {
225 pub acl: u8,
226 pub msg_id: String,
228 #[serde(skip_serializing_if = "Option::is_none")]
229 pub in_reply_to: Option<String>,
230 pub from: Aid,
231 pub to: Aid,
232 pub ts: i64,
234 #[serde(default = "default_ttl")]
235 pub ttl: u32,
236 #[serde(skip_serializing_if = "Option::is_none")]
237 pub reply_with: Option<String>,
238 #[serde(default, skip_serializing_if = "is_zero")]
239 pub hop_count: u8,
240 pub performative: Performative,
241 pub body: Body,
242 #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
244 pub sig: Option<Vec<u8>>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub rational_effect: Option<String>,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub feasibility_precondition: Option<String>,
254}
255
256fn default_ttl() -> u32 {
257 DEFAULT_TTL_MS
258}
259
260fn is_zero(v: &u8) -> bool {
261 *v == 0
262}
263
264pub fn new_msg_id() -> String {
266 use rand::Rng;
267 let mut b = [0u8; 16];
268 rand::rng().fill_bytes(&mut b);
269 hex(&b)
270}
271
272fn hex(b: &[u8]) -> String {
273 b.iter().map(|x| format!("{x:02x}")).collect()
274}
275
276mod opt_serde_bytes {
277 use serde::{Deserializer, Serializer};
278
279 pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
280 match v {
281 Some(b) => serde_bytes::serialize(b, s),
282 None => s.serialize_none(),
283 }
284 }
285 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
286 let opt: Option<serde_bytes::ByteBuf> = serde_bytes::deserialize(d)?;
287 Ok(opt.map(|b| b.into_vec()))
288 }
289}
290
291impl Envelope {
292 pub fn new(from: Aid, to: Aid, performative: Performative, body: Body) -> Self {
293 Envelope {
294 acl: ACL_VERSION,
295 msg_id: new_msg_id(),
296 in_reply_to: None,
297 from,
298 to,
299 ts: now_ms(),
300 ttl: DEFAULT_TTL_MS,
301 reply_with: None,
302 hop_count: 0,
303 performative,
304 body,
305 sig: None,
306 rational_effect: None,
307 feasibility_precondition: None,
308 }
309 }
310
311 pub fn with_intent(mut self, fp: &str, re: &str) -> Self {
313 self.feasibility_precondition = Some(fp.into());
314 self.rational_effect = Some(re.into());
315 self
316 }
317
318 pub fn encode_unsigned(&self) -> Result<Vec<u8>, AclError> {
320 let mut copy = self.clone();
321 copy.sig = None;
322 rmp_serde::to_vec_named(©).map_err(AclError::Encode)
323 }
324
325 pub fn encode(&self) -> Result<Vec<u8>, AclError> {
327 rmp_serde::to_vec_named(self).map_err(AclError::Encode)
328 }
329
330 pub fn decode(bytes: &[u8]) -> Result<Self, AclError> {
331 let env: Envelope = rmp_serde::from_slice(bytes).map_err(AclError::Decode)?;
332 if env.acl != ACL_VERSION {
333 return Err(AclError::Version(env.acl));
334 }
335 Ok(env)
336 }
337
338 pub fn sign(&mut self, key: &SigningKey) -> Result<(), AclError> {
340 let unsigned = self.encode_unsigned()?;
341 self.sig = Some(key.sign(&unsigned).to_bytes().to_vec());
342 Ok(())
343 }
344
345 pub fn verify(&self, vk: &VerifyingKey) -> Result<bool, AclError> {
347 let Some(sig_bytes) = self.sig.clone() else {
348 return Ok(false);
349 };
350 let sig = Signature::from_bytes(
351 <&[u8; 64]>::try_from(&sig_bytes[..]).map_err(|_| AclError::BadKey)?,
352 );
353 let unsigned = self.encode_unsigned()?;
354 Ok(vk.verify(&unsigned, &sig).is_ok())
355 }
356
357 pub fn is_expired(&self, now_ms: i64) -> bool {
358 now_ms.saturating_sub(self.ts) > self.ttl as i64
359 }
360}
361
362fn now_ms() -> i64 {
363 std::time::SystemTime::now()
364 .duration_since(std::time::UNIX_EPOCH)
365 .map(|d| d.as_millis() as i64)
366 .unwrap_or(0)
367}
368
369#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
373pub struct AgentCard {
374 pub name: String,
375 pub version: String,
376 pub description: String,
377 pub endpoint: Aid,
378 pub capabilities: Vec<Capability>,
379 pub auth_scheme: String, #[serde(skip_serializing_if = "Option::is_none")]
381 pub key_id: Option<String>,
382 #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
384 pub public_key: Option<Vec<u8>>,
385 #[serde(skip_serializing_if = "Option::is_none")]
386 pub rate_hint: Option<u32>,
387 #[serde(skip_serializing_if = "Option::is_none")]
388 pub valid_until: Option<i64>,
389 #[serde(default, skip_serializing_if = "Option::is_none", with = "opt_serde_bytes")]
391 pub sig: Option<Vec<u8>>,
392}
393
394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
395pub struct Capability {
396 pub name: String,
397 #[serde(skip_serializing_if = "Option::is_none")]
398 pub input_schema: Option<serde_json::Value>,
399 #[serde(skip_serializing_if = "Option::is_none")]
400 pub output_schema: Option<serde_json::Value>,
401 #[serde(skip_serializing_if = "Option::is_none")]
402 pub examples: Option<Vec<String>>,
403}
404
405impl AgentCard {
406 pub fn encode_unsigned(&self) -> Result<Vec<u8>, AclError> {
407 let mut copy = self.clone();
408 copy.sig = None;
409 rmp_serde::to_vec_named(©).map_err(AclError::Encode)
410 }
411
412 pub fn sign(&mut self, key: &SigningKey) -> Result<(), AclError> {
413 self.public_key = Some(key.verifying_key().to_bytes().to_vec());
414 let unsigned = self.encode_unsigned()?;
415 self.sig = Some(key.sign(&unsigned).to_bytes().to_vec());
416 Ok(())
417 }
418
419 pub fn verify(&self) -> Result<bool, AclError> {
420 let (Some(sig_bytes), Some(pk)) = (self.sig.clone(), self.public_key.clone()) else {
421 return Ok(false);
422 };
423 let vk = VerifyingKey::from_bytes(
424 <&[u8; 32]>::try_from(&pk[..]).map_err(|_| AclError::BadKey)?,
425 )
426 .map_err(|_| AclError::BadKey)?;
427 let sig = Signature::from_bytes(
428 <&[u8; 64]>::try_from(&sig_bytes[..]).map_err(|_| AclError::BadKey)?,
429 );
430 Ok(vk.verify(&self.encode_unsigned()?, &sig).is_ok())
431 }
432}
433
434pub fn read_frame<R: Read>(mut r: R) -> std::io::Result<Option<Vec<u8>>> {
439 let mut len_buf = [0u8; 4];
440 match r.read_exact(&mut len_buf) {
441 Ok(()) => {}
442 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
443 Err(e) => return Err(e),
444 }
445 let len = u32::from_be_bytes(len_buf) as usize;
446 if len > 16 * 1024 * 1024 {
447 return Err(std::io::Error::new(
448 std::io::ErrorKind::InvalidData,
449 "frame too large",
450 ));
451 }
452 let mut buf = vec![0u8; len];
453 r.read_exact(&mut buf)?;
454 Ok(Some(buf))
455}
456
457pub fn write_frame(buf: &mut Vec<u8>, payload: &[u8]) {
458 buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
459 buf.extend_from_slice(payload);
460}
461
462#[derive(Debug)]
465pub enum AclError {
466 Encode(rmp_serde::encode::Error),
467 Decode(rmp_serde::decode::Error),
468 Version(u8),
469 BadKey,
470}
471
472impl std::fmt::Display for AclError {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 match self {
475 AclError::Encode(e) => write!(f, "encode: {e}"),
476 AclError::Decode(e) => write!(f, "decode: {e}"),
477 AclError::Version(v) => write!(f, "unsupported ACL version {v}"),
478 AclError::BadKey => write!(f, "bad ed25519 key"),
479 }
480 }
481}
482impl std::error::Error for AclError {}
483
484#[cfg(test)]
487mod tests {
488 use super::*;
489 use rand::Rng;
490
491 fn key() -> SigningKey {
492 let mut seed = [0u8; 32];
493 rand::rng().fill_bytes(&mut seed);
494 SigningKey::from_bytes(&seed)
495 }
496
497 fn sample() -> Envelope {
498 Envelope::new(
499 Aid::local(4211, "a1"),
500 Aid::new("did:example:agent-b"),
501 Performative::Request,
502 Body::Task {
503 description: "summarize report".into(),
504 input: serde_json::json!({"file": "q3.pdf", "lang": "pt"}),
505 deadline_ms: Some(60_000),
506 priority: Some(5),
507 },
508 )
509 }
510
511 #[test]
512 fn roundtrip_all_performatives() {
513 let bodies = vec![
514 (Performative::Request, Body::Task { description: "t".into(), input: serde_json::json!({"x": 1}), deadline_ms: None, priority: None }),
515 (Performative::Inform, Body::Result { output: serde_json::json!("done"), artifacts: vec![Artifact { name: "a.txt".into(), mime: "text/plain".into(), bytes: b"hi".to_vec() }] }),
516 (Performative::Inform, Body::Text { text: "hello".into() }),
517 (Performative::Query, Body::Query { subject: "agent.card".into(), parameters: None }),
518 (Performative::Propose, Body::Proposal { terms: serde_json::json!({"split": "50/50"}), price: Some("2 credits".into()), valid_until: None }),
519 (Performative::Accept, Body::Ref { target_msg_id: "abc".into() }),
520 (Performative::Reject, Body::Ref { target_msg_id: "abc".into() }),
521 (Performative::Cancel, Body::Ref { target_msg_id: "abc".into() }),
522 (Performative::Progress, Body::Progress { target_msg_id: "abc".into(), percent: Some(50), note: Some("halfway".into()) }),
523 (Performative::InputRequired, Body::InputNeeded { target_msg_id: "abc".into(), what: "missing column".into(), schema: None }),
524 (Performative::Failure, Body::Failure { target_msg_id: "abc".into(), code: 500, reason: "no data".into(), recoverable: false }),
525 (Performative::Error, Body::Error {
526 code: 400, message: "bad".into(), taxonomy: None, details: None }),
527 (Performative::Hello, Body::Hello { agent_card: None, card_hash: None, nonce: vec![7u8; 16] }),
528 (Performative::Bye, Body::Ref { target_msg_id: "abc".into() }),
529 (Performative::Delegate, Body::Delegate { task: Box::new(Body::Task { description: "sub".into(), input: serde_json::json!(null), deadline_ms: None, priority: None }), chain: vec!["did:example:a".into(), "did:example:b".into()] }),
530 ];
531 for (perf, body) in bodies {
532 let env = Envelope::new(Aid::local(1, "s"), Aid::new("did:x:y"), perf, body);
533 let bytes = env.encode().expect("encode");
534 let back = Envelope::decode(&bytes).expect("decode");
535 assert_eq!(back.performative, perf);
536 assert_eq!(back.msg_id, env.msg_id);
537 }
538 }
539
540 #[test]
541 fn sign_verify() {
542 let key = key();
543 let mut env = sample();
544 env.sign(&key).unwrap();
545 assert!(env.verify(&key.verifying_key()).unwrap());
546 env.ttl = 1;
548 assert!(!env.verify(&key.verifying_key()).unwrap());
549 }
550
551 #[test]
552 fn wrong_key_fails() {
553 let mut env = sample();
554 env.sign(&key()).unwrap();
555 assert!(!env.verify(&key().verifying_key()).unwrap());
556 }
557
558 #[test]
559 fn framing_roundtrip() {
560 let env = sample();
561 let payload = env.encode().unwrap();
562 let mut stream = Vec::new();
563 write_frame(&mut stream, &payload);
564 write_frame(&mut stream, &payload);
565 let mut cursor = &stream[..];
566 let f1 = read_frame(&mut cursor).unwrap().unwrap();
567 let f2 = read_frame(&mut cursor).unwrap().unwrap();
568 let eof = read_frame(&mut cursor).unwrap();
569 assert_eq!(f1, payload);
570 assert_eq!(f2, payload);
571 assert!(eof.is_none());
572 }
573
574 #[test]
575 fn agent_card_sign_verify() {
576 let key = key();
577 let mut card = AgentCard {
578 name: "argus".into(),
579 version: "1.0".into(),
580 description: "watchdog agent".into(),
581 endpoint: Aid::local(4211, "a1"),
582 capabilities: vec![Capability {
583 name: "log.watch".into(),
584 input_schema: None,
585 output_schema: None,
586 examples: None,
587 }],
588 auth_scheme: "ed25519".into(),
589 key_id: None,
590 public_key: None,
591 rate_hint: Some(60),
592 valid_until: None,
593 sig: None,
594 };
595 card.sign(&key).unwrap();
596 assert!(card.verify().unwrap());
597 card.name = "tampered".into();
598 assert!(!card.verify().unwrap());
599 }
600
601 #[test]
602 fn compactness() {
603 let env = sample();
604 let mp = env.encode().unwrap();
605 let js = serde_json::to_vec(&env).unwrap();
606 println!("msgpack {} bytes vs json {} bytes", mp.len(), js.len());
607 assert!(mp.len() < js.len());
608 }
609}
610
611
612pub fn rotate_identity(
616 from: &Aid,
617 old_key: &ed25519_dalek::SigningKey,
618 new_key: &ed25519_dalek::SigningKey,
619 reason: Option<&str>,
620 now_ms: i64,
621) -> Result<Envelope, AclError> {
622 let new_did = crate::did::verifying_key_to_did_key(&new_key.verifying_key());
623 let mut env = Envelope::new(
624 from.clone(),
625 Aid::new("local:registry:identity"),
626 Performative::Inform,
627 Body::KeyRotation {
628 new_did: new_did.to_string(),
629 valid_from_ms: now_ms,
630 reason: reason.map(|r| r.to_string()),
631 },
632 );
633 env.msg_id = new_msg_id();
634 env.ts = now_ms;
635 env.sign(old_key)?;
636 Ok(env)
637}
638
639
640#[cfg(test)]
641mod rotation_tests {
642 use super::*;
643 use ed25519_dalek::SigningKey;
644 use rand::Rng;
645
646 #[test]
647 fn key_rotation_verifies_with_old_key_and_announces_new_did() {
648 let mut old_seed = [0u8; 32];
649 rand::rng().fill_bytes(&mut old_seed);
650 let mut new_seed = [0u8; 32];
651 rand::rng().fill_bytes(&mut new_seed);
652 let old_key = SigningKey::from_bytes(&old_seed);
653 let new_key = SigningKey::from_bytes(&new_seed);
654
655 let from = Aid::new("did:key:z6old");
656 let env = rotate_identity(&from, &old_key, &new_key, Some("scheduled rotation"), 1_700_000_000_000)
657 .expect("rotation envelope");
658
659 env.verify(&old_key.verifying_key()).expect("rotation must verify with old key");
661 match &env.body {
663 Body::KeyRotation { new_did, .. } => {
664 let expected = crate::did::verifying_key_to_did_key(&new_key.verifying_key());
665 assert_eq!(new_did, &expected);
666 }
667 other => panic!("expected KeyRotation, got {other:?}"),
668 }
669 let decoded = Envelope::decode(&env.encode().unwrap()).unwrap();
671 decoded.verify(&old_key.verifying_key()).unwrap();
672 }
673}