aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
aien-protocols-mv / crates / aien-pi-spark-task / src / lib.rs
| 1 | //! PST1, the Pi-Spark task message: reader and writer for the fixed header. |
| 2 | //! |
| 3 | //! Spec: `specs/pi-spark-task/SPEC.md` (Draft v0.3, contract 0.1.0, wire |
| 4 | //! version 1). The C reference checker is `specs/pi-spark-task/tools/pst_verify.c`; |
| 5 | //! this crate must give the same verdict on the same bytes (the test in |
| 6 | //! `tests/vectors.rs` walks the shared vectors). |
| 7 | //! |
| 8 | //! Bounds are fixed: a message is 224 header bytes plus at most 800 payload |
| 9 | //! bytes. Decoding borrows the payload from the input and allocates nothing. |
| 10 | //! There is no JSON anywhere in the decode path. |
| 11 | //! |
| 12 | //! First cut (aien-protocols-mv#31): the header only. C6 (aien-protocols-mv#33) |
| 13 | //! adds the tool-call body (SPEC.md section 11): the 36-byte head of a |
| 14 | //! `tool_call_request` is checked in [`decode`], and [`TaskBody`] joins the |
| 15 | //! `tool_call_chunk` payloads into the INTERPLANE canonical request and checks |
| 16 | //! its digest. The side of the sender and the other session rules (section 10) |
| 17 | //! are not read here. |
| 18 | #![forbid(unsafe_code)] |
| 19 | |
| 20 | use sha2::{Digest, Sha256}; |
| 21 | |
| 22 | /// Bytes in the fixed header. |
| 23 | pub const HEADER_LEN: usize = 224; |
| 24 | /// Largest payload. |
| 25 | pub const MAX_PAYLOAD: usize = 800; |
| 26 | /// Largest message (header plus payload). |
| 27 | pub const MAX_MESSAGE: usize = HEADER_LEN + MAX_PAYLOAD; |
| 28 | /// The four bytes that open every message. |
| 29 | pub const MAGIC: [u8; 4] = *b"PST1"; |
| 30 | /// The only wire version. |
| 31 | pub const VERSION: u8 = 1; |
| 32 | /// Highest message type (section 5). |
| 33 | pub const MAX_TYPE: u8 = 16; |
| 34 | /// The `request` type (an ordinary, non-tool task). |
| 35 | pub const TYPE_REQUEST: u8 = 1; |
| 36 | /// The `failed` type. |
| 37 | pub const TYPE_FAILED: u8 = 8; |
| 38 | /// The `cancelled` type. |
| 39 | pub const TYPE_CANCELLED: u8 = 9; |
| 40 | /// The `tool_call_request` type: opens a tool-call task (section 11). |
| 41 | pub const TYPE_TOOL_CALL_REQUEST: u8 = 15; |
| 42 | /// The `tool_call_chunk` type: the next piece of the canonical request. |
| 43 | pub const TYPE_TOOL_CALL_CHUNK: u8 = 16; |
| 44 | /// Bytes in a tool-call head: the INTERPLANE digest and the canonical length. |
| 45 | pub const TOOL_HEAD_LEN: usize = 36; |
| 46 | /// Longest INTERPLANE canonical request one tool-call task can carry. |
| 47 | pub const MAX_TOOL_REQUEST: u32 = 102_400; |
| 48 | |
| 49 | const O_MAGIC: usize = 0; |
| 50 | const O_VERSION: usize = 4; |
| 51 | const O_TYPE: usize = 5; |
| 52 | const O_RES0: usize = 6; |
| 53 | const O_CAUSE: usize = 8; |
| 54 | const O_ORIGIN: usize = 40; |
| 55 | const O_OBJECTIVE: usize = 72; |
| 56 | const O_SUBJECT: usize = 104; |
| 57 | const O_PARENT: usize = 136; |
| 58 | const O_TASK: usize = 152; |
| 59 | const O_IDEM: usize = 168; |
| 60 | const O_ORDINAL: usize = 184; |
| 61 | const O_EFFECT: usize = 188; |
| 62 | const O_RES1: usize = 189; |
| 63 | const O_PLEN: usize = 190; |
| 64 | const O_DIGEST: usize = 192; |
| 65 | |
| 66 | /// A refusal code from SPEC.md section 7. |
| 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 68 | pub enum Refusal { |
| 69 | BadMagic, |
| 70 | BadVersion, |
| 71 | Downgrade, |
| 72 | BadType, |
| 73 | WrongSide, |
| 74 | BadLength, |
| 75 | TrailingBytes, |
| 76 | ReservedNonzero, |
| 77 | NoCause, |
| 78 | NoTask, |
| 79 | NoObjective, |
| 80 | DigestMismatch, |
| 81 | BadEffectClass, |
| 82 | SubjectMismatch, |
| 83 | BadOrder, |
| 84 | BadToolHead, |
| 85 | ToolChunkSize, |
| 86 | ToolDigestMismatch, |
| 87 | ToolIncomplete, |
| 88 | NotToolTask, |
| 89 | } |
| 90 | |
| 91 | impl Refusal { |
| 92 | /// The code name exactly as SPEC.md section 7 and the C checker print it. |
| 93 | pub fn code(self) -> &'static str { |
| 94 | match self { |
| 95 | Refusal::BadMagic => "PST_BAD_MAGIC", |
| 96 | Refusal::BadVersion => "PST_BAD_VERSION", |
| 97 | Refusal::Downgrade => "PST_DOWNGRADE", |
| 98 | Refusal::BadType => "PST_BAD_TYPE", |
| 99 | Refusal::WrongSide => "PST_WRONG_SIDE", |
| 100 | Refusal::BadLength => "PST_BAD_LENGTH", |
| 101 | Refusal::TrailingBytes => "PST_TRAILING_BYTES", |
| 102 | Refusal::ReservedNonzero => "PST_RESERVED_NONZERO", |
| 103 | Refusal::NoCause => "PST_NO_CAUSE", |
| 104 | Refusal::NoTask => "PST_NO_TASK", |
| 105 | Refusal::NoObjective => "PST_NO_OBJECTIVE", |
| 106 | Refusal::DigestMismatch => "PST_DIGEST_MISMATCH", |
| 107 | Refusal::BadEffectClass => "PST_BAD_EFFECT_CLASS", |
| 108 | Refusal::SubjectMismatch => "PST_SUBJECT_MISMATCH", |
| 109 | Refusal::BadOrder => "PST_BAD_ORDER", |
| 110 | Refusal::BadToolHead => "PST_BAD_TOOL_HEAD", |
| 111 | Refusal::ToolChunkSize => "PST_TOOL_CHUNK_SIZE", |
| 112 | Refusal::ToolDigestMismatch => "PST_TOOL_DIGEST_MISMATCH", |
| 113 | Refusal::ToolIncomplete => "PST_TOOL_INCOMPLETE", |
| 114 | Refusal::NotToolTask => "PST_NOT_TOOL_TASK", |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// The decoded fixed header (SPEC.md section 4). Reserved bytes and the |
| 120 | /// magic are not stored: they have exactly one allowed value. |
| 121 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 122 | pub struct Header { |
| 123 | pub version: u8, |
| 124 | pub msg_type: u8, |
| 125 | pub cause_id: [u8; 32], |
| 126 | pub origin_run_id: [u8; 32], |
| 127 | pub objective_id: [u8; 32], |
| 128 | pub subject_id: [u8; 32], |
| 129 | pub parent_task_id: [u8; 16], |
| 130 | pub task_id: [u8; 16], |
| 131 | pub idempotence_key: [u8; 16], |
| 132 | pub ordinal: u32, |
| 133 | pub effect_class: u8, |
| 134 | pub payload_len: u16, |
| 135 | pub payload_digest: [u8; 32], |
| 136 | } |
| 137 | |
| 138 | /// One accepted message: the header and the payload it borrows. |
| 139 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 140 | pub struct Message<'a> { |
| 141 | pub header: Header, |
| 142 | pub payload: &'a [u8], |
| 143 | } |
| 144 | |
| 145 | /// Why `encode` could not write a message. |
| 146 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 147 | pub enum EncodeError { |
| 148 | /// The payload is longer than 800 bytes. |
| 149 | PayloadTooLong, |
| 150 | /// `payload_len` in the header differs from the payload given. |
| 151 | LengthMismatch, |
| 152 | /// The output buffer is too small. |
| 153 | BufferTooSmall, |
| 154 | } |
| 155 | |
| 156 | fn arr<const N: usize>(b: &[u8], at: usize) -> [u8; N] { |
| 157 | let mut a = [0u8; N]; |
| 158 | a.copy_from_slice(&b[at..at + N]); |
| 159 | a |
| 160 | } |
| 161 | |
| 162 | fn all_zero(b: &[u8]) -> bool { |
| 163 | b.iter().all(|&x| x == 0) |
| 164 | } |
| 165 | |
| 166 | /// Decode and check one message in the order of SPEC.md section 4.1, the |
| 167 | /// same order as the C checker, so the same bytes give the same code. |
| 168 | pub fn decode(b: &[u8]) -> Result<Message<'_>, Refusal> { |
| 169 | // 1. length bounds |
| 170 | if b.len() < HEADER_LEN || b.len() > MAX_MESSAGE { |
| 171 | return Err(Refusal::BadLength); |
| 172 | } |
| 173 | // 2. magic |
| 174 | if b[O_MAGIC..O_MAGIC + 4] != MAGIC { |
| 175 | return Err(Refusal::BadMagic); |
| 176 | } |
| 177 | // 3. version |
| 178 | if b[O_VERSION] < VERSION { |
| 179 | return Err(Refusal::Downgrade); |
| 180 | } |
| 181 | if b[O_VERSION] > VERSION { |
| 182 | return Err(Refusal::BadVersion); |
| 183 | } |
| 184 | // 4. type |
| 185 | if b[O_TYPE] == 0 || b[O_TYPE] > MAX_TYPE { |
| 186 | return Err(Refusal::BadType); |
| 187 | } |
| 188 | // 5. reserved |
| 189 | if !all_zero(&b[O_RES0..O_RES0 + 2]) || b[O_RES1] != 0 { |
| 190 | return Err(Refusal::ReservedNonzero); |
| 191 | } |
| 192 | // 6, 7. payload length against the bytes present |
| 193 | let payload_len = u16::from_be_bytes(arr(b, O_PLEN)); |
| 194 | let body = &b[HEADER_LEN..]; |
| 195 | if body.len() < usize::from(payload_len) { |
| 196 | return Err(Refusal::BadLength); |
| 197 | } |
| 198 | if body.len() > usize::from(payload_len) { |
| 199 | return Err(Refusal::TrailingBytes); |
| 200 | } |
| 201 | // 8..11. field rules |
| 202 | if b[O_EFFECT] > 2 { |
| 203 | return Err(Refusal::BadEffectClass); |
| 204 | } |
| 205 | if all_zero(&b[O_CAUSE..O_CAUSE + 32]) { |
| 206 | return Err(Refusal::NoCause); |
| 207 | } |
| 208 | if all_zero(&b[O_TASK..O_TASK + 16]) || all_zero(&b[O_IDEM..O_IDEM + 16]) { |
| 209 | return Err(Refusal::NoTask); |
| 210 | } |
| 211 | let opens_task = b[O_TYPE] == TYPE_REQUEST || b[O_TYPE] == TYPE_TOOL_CALL_REQUEST; |
| 212 | if opens_task && all_zero(&b[O_OBJECTIVE..O_OBJECTIVE + 32]) { |
| 213 | return Err(Refusal::NoObjective); |
| 214 | } |
| 215 | // 12. payload digest |
| 216 | let digest: [u8; 32] = Sha256::digest(body).into(); |
| 217 | if digest[..] != b[O_DIGEST..O_DIGEST + 32] { |
| 218 | return Err(Refusal::DigestMismatch); |
| 219 | } |
| 220 | // 13. tool-call head |
| 221 | if b[O_TYPE] == TYPE_TOOL_CALL_REQUEST { |
| 222 | ToolCallHead::parse(body)?; |
| 223 | } |
| 224 | Ok(Message { |
| 225 | header: Header { |
| 226 | version: b[O_VERSION], |
| 227 | msg_type: b[O_TYPE], |
| 228 | cause_id: arr(b, O_CAUSE), |
| 229 | origin_run_id: arr(b, O_ORIGIN), |
| 230 | objective_id: arr(b, O_OBJECTIVE), |
| 231 | subject_id: arr(b, O_SUBJECT), |
| 232 | parent_task_id: arr(b, O_PARENT), |
| 233 | task_id: arr(b, O_TASK), |
| 234 | idempotence_key: arr(b, O_IDEM), |
| 235 | ordinal: u32::from_be_bytes(arr(b, O_ORDINAL)), |
| 236 | effect_class: b[O_EFFECT], |
| 237 | payload_len, |
| 238 | payload_digest: arr(b, O_DIGEST), |
| 239 | }, |
| 240 | payload: body, |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | /// Write one message into `out` and return the byte count. Fields are written |
| 245 | /// exactly as given; the digest is not recomputed (use [`payload_digest`]). |
| 246 | pub fn encode(h: &Header, payload: &[u8], out: &mut [u8]) -> Result<usize, EncodeError> { |
| 247 | if payload.len() > MAX_PAYLOAD { |
| 248 | return Err(EncodeError::PayloadTooLong); |
| 249 | } |
| 250 | if usize::from(h.payload_len) != payload.len() { |
| 251 | return Err(EncodeError::LengthMismatch); |
| 252 | } |
| 253 | let n = HEADER_LEN + payload.len(); |
| 254 | if out.len() < n { |
| 255 | return Err(EncodeError::BufferTooSmall); |
| 256 | } |
| 257 | let o = &mut out[..n]; |
| 258 | o[..HEADER_LEN].fill(0); |
| 259 | o[O_MAGIC..O_MAGIC + 4].copy_from_slice(&MAGIC); |
| 260 | o[O_VERSION] = h.version; |
| 261 | o[O_TYPE] = h.msg_type; |
| 262 | o[O_CAUSE..O_CAUSE + 32].copy_from_slice(&h.cause_id); |
| 263 | o[O_ORIGIN..O_ORIGIN + 32].copy_from_slice(&h.origin_run_id); |
| 264 | o[O_OBJECTIVE..O_OBJECTIVE + 32].copy_from_slice(&h.objective_id); |
| 265 | o[O_SUBJECT..O_SUBJECT + 32].copy_from_slice(&h.subject_id); |
| 266 | o[O_PARENT..O_PARENT + 16].copy_from_slice(&h.parent_task_id); |
| 267 | o[O_TASK..O_TASK + 16].copy_from_slice(&h.task_id); |
| 268 | o[O_IDEM..O_IDEM + 16].copy_from_slice(&h.idempotence_key); |
| 269 | o[O_ORDINAL..O_ORDINAL + 4].copy_from_slice(&h.ordinal.to_be_bytes()); |
| 270 | o[O_EFFECT] = h.effect_class; |
| 271 | o[O_PLEN..O_PLEN + 2].copy_from_slice(&h.payload_len.to_be_bytes()); |
| 272 | o[O_DIGEST..O_DIGEST + 32].copy_from_slice(&h.payload_digest); |
| 273 | o[HEADER_LEN..].copy_from_slice(payload); |
| 274 | Ok(n) |
| 275 | } |
| 276 | |
| 277 | /// The payload of a `tool_call_request` (SPEC.md section 11.2): the digest of |
| 278 | /// the INTERPLANE canonical request and its length in bytes, and nothing else. |
| 279 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 280 | pub struct ToolCallHead { |
| 281 | /// SHA-256 of the canonical bytes; INTERPLANE writes it as `sha256:` + hex. |
| 282 | pub interplane_digest: [u8; 32], |
| 283 | /// Length of the canonical bytes, 1 to [`MAX_TOOL_REQUEST`]. |
| 284 | pub canonical_len: u32, |
| 285 | } |
| 286 | |
| 287 | impl ToolCallHead { |
| 288 | /// Read a head. Exactly 36 bytes, length 1 to 102400; anything else is |
| 289 | /// `PST_BAD_TOOL_HEAD`. |
| 290 | pub fn parse(payload: &[u8]) -> Result<Self, Refusal> { |
| 291 | if payload.len() != TOOL_HEAD_LEN { |
| 292 | return Err(Refusal::BadToolHead); |
| 293 | } |
| 294 | let canonical_len = u32::from_be_bytes(arr(payload, 32)); |
| 295 | if canonical_len == 0 || canonical_len > MAX_TOOL_REQUEST { |
| 296 | return Err(Refusal::BadToolHead); |
| 297 | } |
| 298 | Ok(ToolCallHead { |
| 299 | interplane_digest: arr(payload, 0), |
| 300 | canonical_len, |
| 301 | }) |
| 302 | } |
| 303 | |
| 304 | /// The digest as INTERPLANE prints it: `sha256:` and 64 lower-case hex digits. |
| 305 | pub fn interplane_digest_string(&self) -> String { |
| 306 | let mut s = String::with_capacity(71); |
| 307 | s.push_str("sha256:"); |
| 308 | hex(&mut s, &self.interplane_digest); |
| 309 | s |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// A tool call being received: the head and the canonical bytes so far. |
| 314 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 315 | pub struct ToolCall { |
| 316 | head: ToolCallHead, |
| 317 | bytes: Vec<u8>, |
| 318 | verified: bool, |
| 319 | } |
| 320 | |
| 321 | impl ToolCall { |
| 322 | /// Start collecting the bytes the head announces. |
| 323 | pub fn new(head: ToolCallHead) -> Self { |
| 324 | ToolCall { |
| 325 | head, |
| 326 | bytes: Vec::with_capacity(head.canonical_len as usize), |
| 327 | verified: false, |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// The head this call was opened with. |
| 332 | pub fn head(&self) -> &ToolCallHead { |
| 333 | &self.head |
| 334 | } |
| 335 | |
| 336 | /// Add one `tool_call_chunk` payload (section 11.3). Every chunk is |
| 337 | /// exactly 800 bytes except the last, which is exactly what is left. |
| 338 | /// Returns `Ok(true)` when the last chunk is in and the joined bytes match |
| 339 | /// the head's digest. |
| 340 | pub fn push_chunk(&mut self, chunk: &[u8]) -> Result<bool, Refusal> { |
| 341 | if self.verified { |
| 342 | return Err(Refusal::BadOrder); |
| 343 | } |
| 344 | let left = self.head.canonical_len as usize - self.bytes.len(); |
| 345 | if chunk.len() != left.min(MAX_PAYLOAD) { |
| 346 | return Err(Refusal::ToolChunkSize); |
| 347 | } |
| 348 | self.bytes.extend_from_slice(chunk); |
| 349 | if self.bytes.len() < self.head.canonical_len as usize { |
| 350 | return Ok(false); |
| 351 | } |
| 352 | if payload_digest(&self.bytes) != self.head.interplane_digest { |
| 353 | return Err(Refusal::ToolDigestMismatch); |
| 354 | } |
| 355 | self.verified = true; |
| 356 | Ok(true) |
| 357 | } |
| 358 | |
| 359 | /// The INTERPLANE canonical request, exactly as sent, once every chunk is |
| 360 | /// in and the digest matched. `None` before that. |
| 361 | pub fn canonical_bytes(&self) -> Option<&[u8]> { |
| 362 | self.verified.then_some(&self.bytes[..]) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// What a task carries, fixed by the message that opened it (section 11.1). |
| 367 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 368 | pub enum TaskBody { |
| 369 | /// Opened by `request`: an ordinary task. It never carries tool-call chunks. |
| 370 | Chat, |
| 371 | /// Opened by `tool_call_request`: carries one INTERPLANE canonical request. |
| 372 | ToolCall(ToolCall), |
| 373 | } |
| 374 | |
| 375 | impl TaskBody { |
| 376 | /// The body a task opened by `m` carries, or `None` if `m` opens no task. |
| 377 | pub fn open(m: &Message<'_>) -> Option<Result<Self, Refusal>> { |
| 378 | match m.header.msg_type { |
| 379 | TYPE_REQUEST => Some(Ok(TaskBody::Chat)), |
| 380 | TYPE_TOOL_CALL_REQUEST => { |
| 381 | Some(ToolCallHead::parse(m.payload).map(|h| TaskBody::ToolCall(ToolCall::new(h)))) |
| 382 | } |
| 383 | _ => None, |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | /// A `tool_call_chunk` for this task. A chunk on an ordinary task is |
| 388 | /// `PST_NOT_TOOL_TASK`. |
| 389 | pub fn chunk(&mut self, payload: &[u8]) -> Result<bool, Refusal> { |
| 390 | match self { |
| 391 | TaskBody::Chat => Err(Refusal::NotToolTask), |
| 392 | TaskBody::ToolCall(call) => call.push_chunk(payload), |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | /// May the Spark send `msg_type` for this task yet? Until the whole |
| 397 | /// request is in and verified, only `failed` and `cancelled` are allowed |
| 398 | /// (`PST_TOOL_INCOMPLETE`). |
| 399 | pub fn check_spark(&self, msg_type: u8) -> Result<(), Refusal> { |
| 400 | match self { |
| 401 | TaskBody::ToolCall(call) |
| 402 | if call.canonical_bytes().is_none() |
| 403 | && msg_type != TYPE_FAILED |
| 404 | && msg_type != TYPE_CANCELLED => |
| 405 | { |
| 406 | Err(Refusal::ToolIncomplete) |
| 407 | } |
| 408 | _ => Ok(()), |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | /// SHA-256 of a payload, for filling `Header::payload_digest`. |
| 414 | pub fn payload_digest(payload: &[u8]) -> [u8; 32] { |
| 415 | Sha256::digest(payload).into() |
| 416 | } |
| 417 | |
| 418 | fn hex(out: &mut String, bytes: &[u8]) { |
| 419 | const HX: &[u8; 16] = b"0123456789abcdef"; |
| 420 | for &x in bytes { |
| 421 | out.push(char::from(HX[usize::from(x >> 4)])); |
| 422 | out.push(char::from(HX[usize::from(x & 15)])); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | /// The verdict line in the exact format of `pst_verify FILE` and |
| 427 | /// `vectors/expected.txt`. |
| 428 | pub fn verdict_line(result: &Result<Message<'_>, Refusal>) -> String { |
| 429 | let m = match result { |
| 430 | Err(r) => return format!("refuse {}", r.code()), |
| 431 | Ok(m) => &m.header, |
| 432 | }; |
| 433 | let mut s = String::with_capacity(512); |
| 434 | s.push_str(&format!( |
| 435 | "ok type={} version={} cause=", |
| 436 | m.msg_type, m.version |
| 437 | )); |
| 438 | hex(&mut s, &m.cause_id); |
| 439 | s.push_str(" origin="); |
| 440 | hex(&mut s, &m.origin_run_id); |
| 441 | s.push_str(" objective="); |
| 442 | hex(&mut s, &m.objective_id); |
| 443 | s.push_str(" subject="); |
| 444 | hex(&mut s, &m.subject_id); |
| 445 | s.push_str(" parent="); |
| 446 | hex(&mut s, &m.parent_task_id); |
| 447 | s.push_str(" task="); |
| 448 | hex(&mut s, &m.task_id); |
| 449 | s.push_str(" idem="); |
| 450 | hex(&mut s, &m.idempotence_key); |
| 451 | s.push_str(&format!( |
| 452 | " ordinal={} effect={} len={} digest=", |
| 453 | m.ordinal, m.effect_class, m.payload_len |
| 454 | )); |
| 455 | hex(&mut s, &m.payload_digest); |
| 456 | s |
| 457 | } |
| 458 | |
| 459 | #[cfg(test)] |
| 460 | mod tests { |
| 461 | use super::*; |
| 462 | |
| 463 | fn sample() -> (Header, &'static [u8]) { |
| 464 | let payload: &'static [u8] = b"hello"; |
| 465 | let h = Header { |
| 466 | version: VERSION, |
| 467 | msg_type: TYPE_REQUEST, |
| 468 | cause_id: [1; 32], |
| 469 | origin_run_id: [2; 32], |
| 470 | objective_id: [3; 32], |
| 471 | subject_id: [4; 32], |
| 472 | parent_task_id: [0; 16], |
| 473 | task_id: [5; 16], |
| 474 | idempotence_key: [6; 16], |
| 475 | ordinal: 0, |
| 476 | effect_class: 1, |
| 477 | payload_len: 5, |
| 478 | payload_digest: payload_digest(payload), |
| 479 | }; |
| 480 | (h, payload) |
| 481 | } |
| 482 | |
| 483 | #[test] |
| 484 | fn encode_then_decode_round_trips() { |
| 485 | let (h, p) = sample(); |
| 486 | let mut out = [0u8; MAX_MESSAGE]; |
| 487 | let n = encode(&h, p, &mut out).unwrap(); |
| 488 | let m = decode(&out[..n]).unwrap(); |
| 489 | assert_eq!(m.header, h); |
| 490 | assert_eq!(m.payload, p); |
| 491 | } |
| 492 | |
| 493 | #[test] |
| 494 | fn encode_refuses_what_it_cannot_write() { |
| 495 | let (mut h, p) = sample(); |
| 496 | let mut small = [0u8; HEADER_LEN]; |
| 497 | assert_eq!(encode(&h, p, &mut small), Err(EncodeError::BufferTooSmall)); |
| 498 | h.payload_len = 4; |
| 499 | let mut out = [0u8; MAX_MESSAGE]; |
| 500 | assert_eq!(encode(&h, p, &mut out), Err(EncodeError::LengthMismatch)); |
| 501 | let long = [0u8; MAX_PAYLOAD + 1]; |
| 502 | assert_eq!( |
| 503 | encode(&h, &long, &mut [0u8; 2048]), |
| 504 | Err(EncodeError::PayloadTooLong) |
| 505 | ); |
| 506 | } |
| 507 | fn head_for(bytes: &[u8]) -> [u8; TOOL_HEAD_LEN] { |
| 508 | let mut h = [0u8; TOOL_HEAD_LEN]; |
| 509 | h[..32].copy_from_slice(&payload_digest(bytes)); |
| 510 | h[32..].copy_from_slice(&(bytes.len() as u32).to_be_bytes()); |
| 511 | h |
| 512 | } |
| 513 | |
| 514 | #[test] |
| 515 | fn tool_call_joins_chunks_and_checks_the_digest() { |
| 516 | let canonical: Vec<u8> = (0..1700u32).map(|i| b'a' + (i % 26) as u8).collect(); |
| 517 | let head = ToolCallHead::parse(&head_for(&canonical)).unwrap(); |
| 518 | let mut call = ToolCall::new(head); |
| 519 | assert_eq!(call.push_chunk(&canonical[..800]), Ok(false)); |
| 520 | assert_eq!(call.canonical_bytes(), None); |
| 521 | assert_eq!(call.push_chunk(&canonical[800..1600]), Ok(false)); |
| 522 | assert_eq!(call.push_chunk(&canonical[1600..]), Ok(true)); |
| 523 | assert_eq!(call.canonical_bytes(), Some(&canonical[..])); |
| 524 | assert_eq!(call.push_chunk(b"x"), Err(Refusal::BadOrder)); |
| 525 | |
| 526 | let mut altered = canonical.clone(); |
| 527 | altered[5] ^= 1; |
| 528 | let mut call = ToolCall::new(head); |
| 529 | call.push_chunk(&altered[..800]).unwrap(); |
| 530 | call.push_chunk(&altered[800..1600]).unwrap(); |
| 531 | assert_eq!( |
| 532 | call.push_chunk(&altered[1600..]), |
| 533 | Err(Refusal::ToolDigestMismatch) |
| 534 | ); |
| 535 | |
| 536 | let mut call = ToolCall::new(head); |
| 537 | assert_eq!( |
| 538 | call.push_chunk(&canonical[..799]), |
| 539 | Err(Refusal::ToolChunkSize) |
| 540 | ); |
| 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn tool_head_is_exactly_digest_and_length() { |
| 545 | let h = head_for(b"{}"); |
| 546 | assert!(ToolCallHead::parse(&h).is_ok()); |
| 547 | assert_eq!(ToolCallHead::parse(&h[..35]), Err(Refusal::BadToolHead)); |
| 548 | let mut extra = h.to_vec(); |
| 549 | extra.push(0); |
| 550 | assert_eq!(ToolCallHead::parse(&extra), Err(Refusal::BadToolHead)); |
| 551 | let mut zero = h; |
| 552 | zero[32..].fill(0); |
| 553 | assert_eq!(ToolCallHead::parse(&zero), Err(Refusal::BadToolHead)); |
| 554 | let mut over = h; |
| 555 | over[32..].copy_from_slice(&(MAX_TOOL_REQUEST + 1).to_be_bytes()); |
| 556 | assert_eq!(ToolCallHead::parse(&over), Err(Refusal::BadToolHead)); |
| 557 | } |
| 558 | |
| 559 | #[test] |
| 560 | fn chat_tasks_carry_no_tool_chunks_and_spark_waits_for_the_whole_call() { |
| 561 | let mut chat = TaskBody::Chat; |
| 562 | assert_eq!(chat.chunk(b"{}"), Err(Refusal::NotToolTask)); |
| 563 | let head = ToolCallHead::parse(&head_for(b"{}")).unwrap(); |
| 564 | let mut tool = TaskBody::ToolCall(ToolCall::new(head)); |
| 565 | assert_eq!(tool.check_spark(2), Err(Refusal::ToolIncomplete)); |
| 566 | assert_eq!(tool.check_spark(TYPE_FAILED), Ok(())); |
| 567 | assert_eq!(tool.chunk(b"{}"), Ok(true)); |
| 568 | assert_eq!(tool.check_spark(2), Ok(())); |
| 569 | } |
| 570 | } |