aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-reflex / src / route.rs
| 1 | //! Interactive routing (aienos#399): one typed [`DecisionProposal`] per live conversational turn. |
| 2 | //! |
| 3 | //! This is a separate layer on top of the unchanged 15-way decision core. The exam labels in |
| 4 | //! [`crate::action`] keep their meaning, and the held-out exam and its receipts are not touched. |
| 5 | //! The core's label is one input here; the proposal says where the turn should go: |
| 6 | //! |
| 7 | //! | route | meaning | |
| 8 | //! |---|---| |
| 9 | //! | `local_deterministic` | answered on the Pi by fixed code (status, help, evidence, "I cannot do that") | |
| 10 | //! | `memory` | read of approved owner memory (recall, facts) | |
| 11 | //! | `clarify` | the explicit unknown: ALLEN asks instead of guessing | |
| 12 | //! | `refuse` | the request breaks a rule or a bound | |
| 13 | //! | `local_model` | generation by the model resident on the Pi | |
| 14 | //! | `spark_inference` | generation on the Spark (a PST1 `request` is built, never sent here) | |
| 15 | //! | `spark_omegese` | a bounded Spark task (PST1 `request`, approval required before it may be sent) | |
| 16 | //! | `approval_needed` | the turn asks for an owner decision or a Store write: forwarded to the owner desk of aienos#396 | |
| 17 | //! |
| 18 | //! Authority. A proposal is data. It carries no capability, no grant and no approval: the |
| 19 | //! [`DecisionProposal`] type has no field that could hold one, and [`DecisionProposal::json`] |
| 20 | //! always prints `"grants":"none"`. Approve, deny, cancel, remember, prefer and task phrases |
| 21 | //! become `approval_needed` and go to the one owner desk (aienos#396); this module never |
| 22 | //! decides them. Pending state and memory consent come from the caller's authoritative |
| 23 | //! records ([`RouteCtx`]), never from words in the conversation: an earlier turn that looks |
| 24 | //! like a decision (for example recalled text carrying `"action":"task"`) cannot create a |
| 25 | //! pending item here. |
| 26 | //! |
| 27 | //! Readiness. Every route says whether what it needs is there ([`NotReady`]), and when it is |
| 28 | //! not, names a deterministic fallback that is (always `local_deterministic`, which needs |
| 29 | //! nothing). The proposal never claims a link, a model or a Store the caller did not declare. |
| 30 | //! |
| 31 | //! Abstention. Out-of-distribution turns become `clarify` before any route is chosen: input |
| 32 | //! bounds, non-ASCII bytes, no words, a named model that is not installed, and a learned score |
| 33 | //! that is too far from everything the core knows ([`Calibration`], frozen on the route dev |
| 34 | //! family, see `docs/native/pi5-8/route/`). |
| 35 | |
| 36 | use crate::action::Action; |
| 37 | use crate::dialog::{Role, Turn}; |
| 38 | use crate::policy::RefuseRule; |
| 39 | use crate::{Decision, Explanation, Mode, Reflex, Why}; |
| 40 | use aienos_crypto::sha256::{self, Sha256}; |
| 41 | use alloc::string::String; |
| 42 | use alloc::vec::Vec; |
| 43 | |
| 44 | /// Longest scored user turn accepted for interactive routing (bytes). Longer is refused whole. |
| 45 | pub const INTERACTIVE_MAX: usize = 512; |
| 46 | /// PST1 fixed header bytes (aien-protocols `specs/pi-spark-task/SPEC.md` section 4, Draft v0). |
| 47 | pub const PST1_HEADER: usize = 224; |
| 48 | /// PST1 payload bound (section 4: `payload_len` 0..800). |
| 49 | pub const PST1_PAYLOAD_MAX: usize = 800; |
| 50 | /// Domain prefix of the objective id (aien-sovereign-core `objective.rs`, PST1 section 2). |
| 51 | pub const OBJECTIVE_DOMAIN: &[u8] = b"AIEN_E2E_OBJECTIVE_V1\n"; |
| 52 | |
| 53 | /// Where a turn should go. |
| 54 | #[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)] |
| 55 | #[repr(u8)] |
| 56 | pub enum Route { |
| 57 | LocalDeterministic = 0, |
| 58 | Memory, |
| 59 | Clarify, |
| 60 | Refuse, |
| 61 | LocalModel, |
| 62 | SparkInference, |
| 63 | SparkOmegese, |
| 64 | ApprovalNeeded, |
| 65 | } |
| 66 | |
| 67 | impl Route { |
| 68 | /// All routes in index order. |
| 69 | pub const ALL: [Route; 8] = [ |
| 70 | Route::LocalDeterministic, |
| 71 | Route::Memory, |
| 72 | Route::Clarify, |
| 73 | Route::Refuse, |
| 74 | Route::LocalModel, |
| 75 | Route::SparkInference, |
| 76 | Route::SparkOmegese, |
| 77 | Route::ApprovalNeeded, |
| 78 | ]; |
| 79 | |
| 80 | /// Name used in the proposal line and the route families. |
| 81 | pub fn name(self) -> &'static str { |
| 82 | match self { |
| 83 | Route::LocalDeterministic => "local_deterministic", |
| 84 | Route::Memory => "memory", |
| 85 | Route::Clarify => "clarify", |
| 86 | Route::Refuse => "refuse", |
| 87 | Route::LocalModel => "local_model", |
| 88 | Route::SparkInference => "spark_inference", |
| 89 | Route::SparkOmegese => "spark_omegese", |
| 90 | Route::ApprovalNeeded => "approval_needed", |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// Parse a route name (exact). |
| 95 | pub fn from_name(s: &str) -> Option<Route> { |
| 96 | Route::ALL.iter().copied().find(|r| r.name() == s) |
| 97 | } |
| 98 | |
| 99 | /// Routes that may run without an owner decision once ready. `approval_needed` and |
| 100 | /// `spark_omegese` always wait for the owner desk; `clarify` and `refuse` run nothing. |
| 101 | pub fn runs_without_owner(self) -> bool { |
| 102 | matches!( |
| 103 | self, |
| 104 | Route::LocalDeterministic | Route::Memory | Route::LocalModel | Route::SparkInference |
| 105 | ) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// The owner decision an `approval_needed` (or `spark_omegese`) proposal waits for. |
| 110 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 111 | pub enum Then { |
| 112 | Approve, |
| 113 | Deny, |
| 114 | Cancel, |
| 115 | Remember, |
| 116 | Prefer, |
| 117 | NoteTask, |
| 118 | SparkTask, |
| 119 | } |
| 120 | |
| 121 | impl Then { |
| 122 | /// Name used in the proposal line. |
| 123 | pub fn name(self) -> &'static str { |
| 124 | match self { |
| 125 | Then::Approve => "approve", |
| 126 | Then::Deny => "deny", |
| 127 | Then::Cancel => "cancel", |
| 128 | Then::Remember => "remember", |
| 129 | Then::Prefer => "prefer", |
| 130 | Then::NoteTask => "note_task", |
| 131 | Then::SparkTask => "spark_task", |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// Parse (exact). |
| 136 | pub fn from_name(s: &str) -> Option<Then> { |
| 137 | [ |
| 138 | Then::Approve, |
| 139 | Then::Deny, |
| 140 | Then::Cancel, |
| 141 | Then::Remember, |
| 142 | Then::Prefer, |
| 143 | Then::NoteTask, |
| 144 | Then::SparkTask, |
| 145 | ] |
| 146 | .into_iter() |
| 147 | .find(|t| t.name() == s) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// Who is speaking, as established by the owner-access path of aienos#396. |
| 152 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 153 | pub enum Speaker { |
| 154 | /// owner access established for this session |
| 155 | Owner, |
| 156 | /// skip/guest mode: no named profile, no owner memory, no Store writes |
| 157 | Guest, |
| 158 | } |
| 159 | |
| 160 | impl Speaker { |
| 161 | /// Name used in the proposal line. |
| 162 | pub fn name(self) -> &'static str { |
| 163 | match self { |
| 164 | Speaker::Owner => "owner", |
| 165 | Speaker::Guest => "guest", |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// What the running image really has. Only the caller knows; the proposal never assumes more. |
| 171 | #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] |
| 172 | pub struct Caps { |
| 173 | /// sealed Store open (memory reads, approved writes) |
| 174 | pub store: bool, |
| 175 | /// the owner desk of aienos#396 is present to take approvals |
| 176 | pub desk: bool, |
| 177 | /// a local model is resident |
| 178 | pub local_model: bool, |
| 179 | /// an authenticated Spark session (M6-B) is up |
| 180 | pub spark_link: bool, |
| 181 | } |
| 182 | |
| 183 | impl Caps { |
| 184 | /// Bit form for the C side: 1 store, 2 desk, 4 local model, 8 Spark link. |
| 185 | pub fn from_bits(b: u32) -> Caps { |
| 186 | Caps { |
| 187 | store: b & 1 != 0, |
| 188 | desk: b & 2 != 0, |
| 189 | local_model: b & 4 != 0, |
| 190 | spark_link: b & 8 != 0, |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// Learned-score abstention thresholds. Frozen per mode on the route dev family. |
| 196 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 197 | pub struct Calibration { |
| 198 | /// below this similarity to the nearest stored example: `clarify` (unfamiliar) |
| 199 | pub min_sim: f32, |
| 200 | /// below this score margin between the top two labels: `clarify` (unsure) |
| 201 | pub min_margin: f32, |
| 202 | } |
| 203 | |
| 204 | impl Calibration { |
| 205 | /// Off: never abstain on score (the exam setting). |
| 206 | pub const OFF: Calibration = Calibration { |
| 207 | min_sim: -1.0, |
| 208 | min_margin: f32::MIN, |
| 209 | }; |
| 210 | |
| 211 | /// The frozen route calibration for `mode` (chosen on `route-dev.psv` only; see |
| 212 | /// `docs/native/pi5-8/route/README.md`). The perceptron has no similarity, only a margin. |
| 213 | pub fn frozen(mode: Mode) -> Calibration { |
| 214 | match mode { |
| 215 | Mode::Reflex => Calibration { |
| 216 | min_sim: 0.20, |
| 217 | min_margin: f32::MIN, |
| 218 | }, |
| 219 | Mode::Nearest => Calibration { |
| 220 | min_sim: 0.35, |
| 221 | min_margin: f32::MIN, |
| 222 | }, |
| 223 | Mode::Perceptron => Calibration { |
| 224 | min_sim: -1.0, |
| 225 | min_margin: 0.15, |
| 226 | }, |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// Authoritative context of one turn, from the caller's own records. |
| 232 | #[derive(Clone, Copy, Debug)] |
| 233 | pub struct RouteCtx<'a> { |
| 234 | /// who is speaking |
| 235 | pub speaker: Speaker, |
| 236 | /// the owner consented (through aienos#396) to memory use in this profile revision |
| 237 | pub memory_consent: bool, |
| 238 | /// the lifecycle has a pending item right now |
| 239 | pub pending: bool, |
| 240 | /// what the image has |
| 241 | pub caps: Caps, |
| 242 | /// the installed local model's short name, if any (lower case) |
| 243 | pub installed_model: Option<&'a str>, |
| 244 | /// ALLEN subject reference for PST1 `subject_id` (all zero when unknown) |
| 245 | pub subject_id: [u8; 32], |
| 246 | /// score abstention |
| 247 | pub cal: Calibration, |
| 248 | } |
| 249 | |
| 250 | /// One interactive request with its references. |
| 251 | #[derive(Clone, Copy, Debug)] |
| 252 | pub struct RouteRequest<'a> { |
| 253 | /// request id given by the input path (aienos#396), unique per session |
| 254 | pub request_id: u64, |
| 255 | /// session id given by the input path |
| 256 | pub session_id: u64, |
| 257 | /// the conversation; the last user turn is the request |
| 258 | pub turns: &'a [Turn<'a>], |
| 259 | } |
| 260 | |
| 261 | /// Why a route cannot run now. |
| 262 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 263 | pub enum NotReady { |
| 264 | /// no sealed Store open in this image |
| 265 | StoreAbsent, |
| 266 | /// the owner has not consented to memory use |
| 267 | NoConsent, |
| 268 | /// no owner desk to take the decision |
| 269 | DeskAbsent, |
| 270 | /// no local model resident |
| 271 | NoLocalModel, |
| 272 | /// no authenticated Spark session |
| 273 | SparkLinkDown, |
| 274 | } |
| 275 | |
| 276 | impl NotReady { |
| 277 | /// Name used in the proposal line. |
| 278 | pub fn name(self) -> &'static str { |
| 279 | match self { |
| 280 | NotReady::StoreAbsent => "store_absent", |
| 281 | NotReady::NoConsent => "no_memory_consent", |
| 282 | NotReady::DeskAbsent => "owner_desk_absent", |
| 283 | NotReady::NoLocalModel => "no_local_model", |
| 284 | NotReady::SparkLinkDown => "spark_link_down", |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | /// Why the route came out as it did. |
| 290 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 291 | pub enum RouteWhy { |
| 292 | /// the core's label, mapped |
| 293 | Scored, |
| 294 | /// the core recalled an (almost) identical stored example |
| 295 | ExactRecall, |
| 296 | /// the core's policy layer refused |
| 297 | Policy(RefuseRule), |
| 298 | /// no user turn |
| 299 | NoUserTurn, |
| 300 | /// scored turn longer than [`INTERACTIVE_MAX`] |
| 301 | InputTooLong, |
| 302 | /// a byte outside printable ASCII |
| 303 | NonAscii, |
| 304 | /// no words |
| 305 | NoWords, |
| 306 | /// the core abstained or asked (its own clarify) |
| 307 | CoreClarify, |
| 308 | /// a text verb without a usable subject |
| 309 | MissingSubject, |
| 310 | /// too far from every stored example |
| 311 | Unfamiliar, |
| 312 | /// top labels too close |
| 313 | Unsure, |
| 314 | /// approve/deny/cancel with nothing pending in the lifecycle |
| 315 | NothingPending, |
| 316 | /// the turn names a model that is not installed |
| 317 | ModelUnavailable, |
| 318 | /// a guest asked for owner memory or a Store write |
| 319 | GuestScope, |
| 320 | /// a request the agent has no capability for |
| 321 | OutOfCapability, |
| 322 | /// explicit Spark task cue |
| 323 | SparkCue, |
| 324 | } |
| 325 | |
| 326 | impl RouteWhy { |
| 327 | /// Name used in the proposal line. |
| 328 | pub fn name(self) -> &'static str { |
| 329 | match self { |
| 330 | RouteWhy::Scored => "scored", |
| 331 | RouteWhy::ExactRecall => "exact_recall", |
| 332 | RouteWhy::Policy(_) => "policy", |
| 333 | RouteWhy::NoUserTurn => "no_user_turn", |
| 334 | RouteWhy::InputTooLong => "input_too_long", |
| 335 | RouteWhy::NonAscii => "non_ascii", |
| 336 | RouteWhy::NoWords => "no_words", |
| 337 | RouteWhy::CoreClarify => "core_clarify", |
| 338 | RouteWhy::MissingSubject => "missing_subject", |
| 339 | RouteWhy::Unfamiliar => "unfamiliar", |
| 340 | RouteWhy::Unsure => "unsure", |
| 341 | RouteWhy::NothingPending => "nothing_pending", |
| 342 | RouteWhy::ModelUnavailable => "model_unavailable", |
| 343 | RouteWhy::GuestScope => "guest_scope", |
| 344 | RouteWhy::OutOfCapability => "out_of_capability", |
| 345 | RouteWhy::SparkCue => "spark_cue", |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /// The typed proposal for one interactive turn. Data only: it grants nothing. |
| 351 | #[derive(Clone, Debug, PartialEq)] |
| 352 | pub struct DecisionProposal { |
| 353 | /// request id as given |
| 354 | pub request_id: u64, |
| 355 | /// session id as given |
| 356 | pub session_id: u64, |
| 357 | /// who spoke |
| 358 | pub speaker: Speaker, |
| 359 | /// SHA-256 of [`OBJECTIVE_DOMAIN`] and the exact bytes of the scored user turn |
| 360 | /// (all zero when there is no user turn) |
| 361 | pub objective_id: [u8; 32], |
| 362 | /// where the turn should go |
| 363 | pub route: Route, |
| 364 | /// the owner decision it waits for (approval_needed, spark_omegese) |
| 365 | pub then: Option<Then>, |
| 366 | /// `None`: ready; `Some`: the first missing piece |
| 367 | pub not_ready: Option<NotReady>, |
| 368 | /// what runs instead while not ready (always `local_deterministic`) |
| 369 | pub fallback: Option<Route>, |
| 370 | /// reason |
| 371 | pub why: RouteWhy, |
| 372 | /// the core's label (input to the routing, kept for the record) |
| 373 | pub label: Action, |
| 374 | /// the core's copied argument text, if any |
| 375 | pub text: Option<String>, |
| 376 | /// SHA-256 of the PST1 `request` message built for a Spark route (never sent here) |
| 377 | pub pst1_digest: Option<[u8; 32]>, |
| 378 | } |
| 379 | |
| 380 | fn hex(out: &mut String, b: &[u8]) { |
| 381 | const H: &[u8; 16] = b"0123456789abcdef"; |
| 382 | for &x in b { |
| 383 | out.push(H[(x >> 4) as usize] as char); |
| 384 | out.push(H[(x & 15) as usize] as char); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | fn push_u64(out: &mut String, mut v: u64) { |
| 389 | let mut b = [0u8; 20]; |
| 390 | let mut i = b.len(); |
| 391 | loop { |
| 392 | i -= 1; |
| 393 | b[i] = b'0' + (v % 10) as u8; |
| 394 | v /= 10; |
| 395 | if v == 0 { |
| 396 | break; |
| 397 | } |
| 398 | } |
| 399 | for &c in &b[i..] { |
| 400 | out.push(c as char); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | impl DecisionProposal { |
| 405 | /// One JSON line. Field order is fixed so the Pi and the host print the same bytes. |
| 406 | /// Every string is printable ASCII without `"` or `\` (names, hex, and the core's text, |
| 407 | /// which [`crate::span`] already restricts). |
| 408 | pub fn json(&self) -> String { |
| 409 | let mut s = String::with_capacity(320); |
| 410 | s.push_str("{\"req\":"); |
| 411 | push_u64(&mut s, self.request_id); |
| 412 | s.push_str(",\"session\":"); |
| 413 | push_u64(&mut s, self.session_id); |
| 414 | s.push_str(",\"speaker\":\""); |
| 415 | s.push_str(self.speaker.name()); |
| 416 | s.push_str("\",\"objective\":\""); |
| 417 | hex(&mut s, &self.objective_id); |
| 418 | s.push_str("\",\"route\":\""); |
| 419 | s.push_str(self.route.name()); |
| 420 | s.push_str("\",\"then\":\""); |
| 421 | s.push_str(self.then.map(|t| t.name()).unwrap_or("-")); |
| 422 | s.push_str("\",\"ready\":\""); |
| 423 | match self.not_ready { |
| 424 | None => s.push_str("yes"), |
| 425 | Some(n) => { |
| 426 | s.push_str("no:"); |
| 427 | s.push_str(n.name()); |
| 428 | } |
| 429 | } |
| 430 | s.push_str("\",\"fallback\":\""); |
| 431 | s.push_str(self.fallback.map(|r| r.name()).unwrap_or("-")); |
| 432 | s.push_str("\",\"why\":\""); |
| 433 | s.push_str(self.why.name()); |
| 434 | if let RouteWhy::Policy(r) = self.why { |
| 435 | s.push(':'); |
| 436 | s.push_str(r.name()); |
| 437 | } |
| 438 | s.push_str("\",\"label\":\""); |
| 439 | s.push_str(self.label.name()); |
| 440 | s.push_str("\",\"text\":\""); |
| 441 | if let Some(t) = &self.text { |
| 442 | s.push_str(t); |
| 443 | } |
| 444 | s.push_str("\",\"pst1\":\""); |
| 445 | match &self.pst1_digest { |
| 446 | Some(d) => hex(&mut s, d), |
| 447 | None => s.push('-'), |
| 448 | } |
| 449 | s.push_str("\",\"grants\":\"none\"}"); |
| 450 | s |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | /// Objective id of a request text (PST1 `objective_id`). |
| 455 | pub fn objective_id(text: &[u8]) -> [u8; 32] { |
| 456 | let mut h = Sha256::new(); |
| 457 | h.update(OBJECTIVE_DOMAIN); |
| 458 | h.update(text); |
| 459 | h.finalize() |
| 460 | } |
| 461 | |
| 462 | fn take16(d: &[u8; 32]) -> [u8; 16] { |
| 463 | let mut o = [0u8; 16]; |
| 464 | o.copy_from_slice(&d[..16]); |
| 465 | o |
| 466 | } |
| 467 | |
| 468 | /// Build the PST1 `request` message (header + payload) for a Spark route. Draft v0 layout of |
| 469 | /// aien-protocols `specs/pi-spark-task/SPEC.md`; big-endian; reserved bytes zero. It is built |
| 470 | /// so its exact bytes are on record; nothing here sends it, and a Spark task still needs the |
| 471 | /// owner desk before any sender may take it. `None` when the payload exceeds the bound or |
| 472 | /// the route is not a Spark route. |
| 473 | pub fn pst1_request( |
| 474 | p: &DecisionProposal, |
| 475 | payload: &[u8], |
| 476 | subject_id: &[u8; 32], |
| 477 | ) -> Option<Vec<u8>> { |
| 478 | let effect_class: u8 = match p.route { |
| 479 | Route::SparkInference | Route::SparkOmegese => 1, // COMPUTE: a claim, never a permission |
| 480 | _ => return None, |
| 481 | }; |
| 482 | if payload.len() > PST1_PAYLOAD_MAX { |
| 483 | return None; |
| 484 | } |
| 485 | let mut cause = Sha256::new(); |
| 486 | cause.update(b"AIENOS_PST1_CAUSE_V1\n"); |
| 487 | cause.update(&p.session_id.to_be_bytes()); |
| 488 | cause.update(&p.request_id.to_be_bytes()); |
| 489 | cause.update(&p.objective_id); |
| 490 | let cause_id = cause.finalize(); |
| 491 | let mut t = Sha256::new(); |
| 492 | t.update(b"AIENOS_PST1_TASK_V1\n"); |
| 493 | t.update(&cause_id); |
| 494 | let task_id = take16(&t.finalize()); |
| 495 | let mut k = Sha256::new(); |
| 496 | k.update(b"AIENOS_PST1_IDEMPOTENCE_V1\n"); |
| 497 | k.update(&cause_id); |
| 498 | let idem = take16(&k.finalize()); |
| 499 | let mut m = Vec::with_capacity(PST1_HEADER + payload.len()); |
| 500 | m.push(1); // version |
| 501 | m.push(1); // type: request (Pi side) |
| 502 | m.extend_from_slice(&[0, 0]); // reserved0 |
| 503 | m.extend_from_slice(&cause_id); // cause_id |
| 504 | m.extend_from_slice(&[0u8; 32]); // origin_run_id: opaque, none on the Pi |
| 505 | m.extend_from_slice(&p.objective_id); // objective_id |
| 506 | m.extend_from_slice(subject_id); // subject_id |
| 507 | m.extend_from_slice(&[0u8; 16]); // parent_task_id: no parent |
| 508 | m.extend_from_slice(&task_id); |
| 509 | m.extend_from_slice(&idem); |
| 510 | m.extend_from_slice(&0u32.to_be_bytes()); // ordinal 0 |
| 511 | m.push(effect_class); |
| 512 | m.extend_from_slice(&[0, 0, 0]); // reserved1 |
| 513 | m.extend_from_slice(&(payload.len() as u16).to_be_bytes()); |
| 514 | m.extend_from_slice(&[0, 0]); // reserved2 |
| 515 | m.extend_from_slice(&sha256::hash(payload)); |
| 516 | debug_assert_eq!(m.len(), PST1_HEADER); |
| 517 | m.extend_from_slice(payload); |
| 518 | Some(m) |
| 519 | } |
| 520 | |
| 521 | /// Model family words a request may name. A named family that is not the installed model |
| 522 | /// makes the turn `clarify` (`model_unavailable`) instead of silently using another model. |
| 523 | const MODEL_WORDS: [&str; 14] = [ |
| 524 | "gpt", |
| 525 | "chatgpt", |
| 526 | "claude", |
| 527 | "gemini", |
| 528 | "llama", |
| 529 | "tinyllama", |
| 530 | "mistral", |
| 531 | "qwen", |
| 532 | "danube", |
| 533 | "phi", |
| 534 | "grok", |
| 535 | "deepseek", |
| 536 | "gemma", |
| 537 | "copilot", |
| 538 | ]; |
| 539 | |
| 540 | /// Words that mark an explicit Spark task ("run the benchmark on the spark"). |
| 541 | const SPARK_TASK_VERBS: [&str; 10] = [ |
| 542 | "run", |
| 543 | "compile", |
| 544 | "build", |
| 545 | "benchmark", |
| 546 | "train", |
| 547 | "test", |
| 548 | "verify", |
| 549 | "execute", |
| 550 | "measure", |
| 551 | "compute", |
| 552 | ]; |
| 553 | |
| 554 | fn lower_words(msg: &str) -> impl Iterator<Item = &str> { |
| 555 | msg.split(|c: char| !c.is_ascii_alphanumeric()) |
| 556 | .filter(|w| !w.is_empty()) |
| 557 | } |
| 558 | |
| 559 | fn eq_ci(a: &str, b: &str) -> bool { |
| 560 | a.eq_ignore_ascii_case(b) |
| 561 | } |
| 562 | |
| 563 | fn named_model(msg: &str) -> Option<&str> { |
| 564 | lower_words(msg).find(|w| MODEL_WORDS.iter().any(|m| eq_ci(w, m))) |
| 565 | } |
| 566 | |
| 567 | fn spark_cue(msg: &str) -> bool { |
| 568 | let mut spark = false; |
| 569 | let mut verb = false; |
| 570 | for w in lower_words(msg) { |
| 571 | spark |= eq_ci(w, "spark") || eq_ci(w, "gb10"); |
| 572 | verb |= SPARK_TASK_VERBS.iter().any(|v| eq_ci(w, v)); |
| 573 | } |
| 574 | spark && verb |
| 575 | } |
| 576 | |
| 577 | /// Decide one interactive turn. Never fails: every outcome is one proposal. |
| 578 | pub fn propose(core: &Reflex, req: &RouteRequest, ctx: &RouteCtx) -> DecisionProposal { |
| 579 | let last = req.turns.iter().rposition(|t| t.role == Role::User); |
| 580 | let msg: &str = last.map(|i| req.turns[i].text).unwrap_or(""); |
| 581 | let mut p = DecisionProposal { |
| 582 | request_id: req.request_id, |
| 583 | session_id: req.session_id, |
| 584 | speaker: ctx.speaker, |
| 585 | objective_id: if last.is_some() { |
| 586 | objective_id(msg.as_bytes()) |
| 587 | } else { |
| 588 | [0u8; 32] |
| 589 | }, |
| 590 | route: Route::Clarify, |
| 591 | then: None, |
| 592 | not_ready: None, |
| 593 | fallback: None, |
| 594 | why: RouteWhy::NoUserTurn, |
| 595 | label: Action::Clarify, |
| 596 | text: None, |
| 597 | pst1_digest: None, |
| 598 | }; |
| 599 | if last.is_none() { |
| 600 | return p; |
| 601 | } |
| 602 | // Bounds and byte checks before the core sees anything. |
| 603 | if msg.len() > INTERACTIVE_MAX { |
| 604 | p.route = Route::Refuse; |
| 605 | p.why = RouteWhy::InputTooLong; |
| 606 | return p; |
| 607 | } |
| 608 | if !msg.bytes().all(|b| (0x20..=0x7e).contains(&b)) { |
| 609 | p.why = RouteWhy::NonAscii; |
| 610 | return p; |
| 611 | } |
| 612 | let (d, e): (Decision, Explanation) = core.decide(req.turns); |
| 613 | p.label = d.action; |
| 614 | p.text = d.text; |
| 615 | // The core's own refusals and abstentions. |
| 616 | match e.why { |
| 617 | Why::Policy(r) => { |
| 618 | p.route = Route::Refuse; |
| 619 | p.why = RouteWhy::Policy(r); |
| 620 | p.text = None; |
| 621 | return p; |
| 622 | } |
| 623 | Why::NoUserTurn => { |
| 624 | p.why = RouteWhy::NoUserTurn; |
| 625 | return p; |
| 626 | } |
| 627 | Why::InputTooLong => { |
| 628 | p.route = Route::Refuse; |
| 629 | p.why = RouteWhy::InputTooLong; |
| 630 | return p; |
| 631 | } |
| 632 | Why::NoWords => { |
| 633 | p.why = RouteWhy::NoWords; |
| 634 | return p; |
| 635 | } |
| 636 | Why::Span(_) => { |
| 637 | p.why = RouteWhy::MissingSubject; |
| 638 | return p; |
| 639 | } |
| 640 | _ => {} |
| 641 | } |
| 642 | // Score abstention (explicit unknown). An exact recall is a known message. A scored `refuse` |
| 643 | // far from every example also becomes `clarify` (dev: unfamiliar words otherwise scored as |
| 644 | // refuse); policy refusals returned above are never softened. |
| 645 | if e.why != Why::ExactRecall { |
| 646 | if e.best_sim < ctx.cal.min_sim { |
| 647 | p.route = Route::Clarify; |
| 648 | p.why = RouteWhy::Unfamiliar; |
| 649 | p.text = None; |
| 650 | return p; |
| 651 | } |
| 652 | if e.margin < ctx.cal.min_margin { |
| 653 | p.route = Route::Clarify; |
| 654 | p.why = RouteWhy::Unsure; |
| 655 | p.text = None; |
| 656 | return p; |
| 657 | } |
| 658 | } |
| 659 | let why = if e.why == Why::ExactRecall { |
| 660 | RouteWhy::ExactRecall |
| 661 | } else { |
| 662 | RouteWhy::Scored |
| 663 | }; |
| 664 | p.why = why; |
| 665 | // A named model that is not installed: ask, never substitute. |
| 666 | if let Some(m) = named_model(msg) { |
| 667 | if !ctx.installed_model.is_some_and(|im| eq_ci(im, m)) { |
| 668 | p.route = Route::Clarify; |
| 669 | p.why = RouteWhy::ModelUnavailable; |
| 670 | p.text = None; |
| 671 | return p; |
| 672 | } |
| 673 | } |
| 674 | let owner = ctx.speaker == Speaker::Owner; |
| 675 | match d.action { |
| 676 | Action::Status | Action::Help | Action::Evidence => { |
| 677 | p.route = Route::LocalDeterministic; |
| 678 | } |
| 679 | Action::None => { |
| 680 | p.route = Route::LocalDeterministic; |
| 681 | p.why = RouteWhy::OutOfCapability; |
| 682 | } |
| 683 | Action::Recall | Action::Facts => { |
| 684 | // MUTANT: a guest reads owner memory. |
| 685 | #[cfg(feature = "route-mutant-guest-memory")] |
| 686 | let owner = true; |
| 687 | if !owner { |
| 688 | p.route = Route::Refuse; |
| 689 | p.why = RouteWhy::GuestScope; |
| 690 | return p; |
| 691 | } |
| 692 | p.route = Route::Memory; |
| 693 | p.not_ready = if !ctx.memory_consent { |
| 694 | Some(NotReady::NoConsent) |
| 695 | } else if !ctx.caps.store { |
| 696 | Some(NotReady::StoreAbsent) |
| 697 | } else { |
| 698 | None |
| 699 | }; |
| 700 | } |
| 701 | Action::Remember | Action::Prefer | Action::Task => { |
| 702 | if !owner { |
| 703 | p.route = Route::Refuse; |
| 704 | p.why = RouteWhy::GuestScope; |
| 705 | return p; |
| 706 | } |
| 707 | if d.action == Action::Task && spark_cue(msg) { |
| 708 | p.route = Route::SparkOmegese; |
| 709 | p.why = RouteWhy::SparkCue; |
| 710 | p.then = Some(Then::SparkTask); |
| 711 | p.not_ready = if !ctx.caps.desk { |
| 712 | Some(NotReady::DeskAbsent) |
| 713 | } else if !ctx.caps.spark_link { |
| 714 | Some(NotReady::SparkLinkDown) |
| 715 | } else { |
| 716 | None |
| 717 | }; |
| 718 | } else { |
| 719 | p.route = Route::ApprovalNeeded; |
| 720 | p.then = Some(match d.action { |
| 721 | Action::Remember => Then::Remember, |
| 722 | Action::Prefer => Then::Prefer, |
| 723 | _ => Then::NoteTask, |
| 724 | }); |
| 725 | p.not_ready = if d.action != Action::Task && !ctx.memory_consent { |
| 726 | Some(NotReady::NoConsent) |
| 727 | } else if !ctx.caps.desk { |
| 728 | Some(NotReady::DeskAbsent) |
| 729 | } else if !ctx.caps.store { |
| 730 | Some(NotReady::StoreAbsent) |
| 731 | } else { |
| 732 | None |
| 733 | }; |
| 734 | } |
| 735 | } |
| 736 | Action::Prompt => { |
| 737 | if spark_cue(msg) && owner { |
| 738 | p.route = Route::SparkOmegese; |
| 739 | p.why = RouteWhy::SparkCue; |
| 740 | p.then = Some(Then::SparkTask); |
| 741 | p.not_ready = if !ctx.caps.desk { |
| 742 | Some(NotReady::DeskAbsent) |
| 743 | } else if !ctx.caps.spark_link { |
| 744 | Some(NotReady::SparkLinkDown) |
| 745 | } else { |
| 746 | None |
| 747 | }; |
| 748 | } else if ctx.caps.local_model { |
| 749 | p.route = Route::LocalModel; |
| 750 | } else { |
| 751 | p.route = Route::SparkInference; |
| 752 | if !ctx.caps.spark_link { |
| 753 | p.not_ready = Some(NotReady::SparkLinkDown); |
| 754 | } |
| 755 | } |
| 756 | } |
| 757 | Action::Approve | Action::Deny | Action::Cancel => { |
| 758 | #[cfg(not(feature = "route-mutant-dialog-pending"))] |
| 759 | let pending = ctx.pending; |
| 760 | // MUTANT: believe the conversation (an earlier turn that looks like a decision) about pending state. |
| 761 | #[cfg(feature = "route-mutant-dialog-pending")] |
| 762 | let pending = ctx.pending |
| 763 | || crate::dialog::state(req.turns).pending == crate::dialog::Pending::Yes; |
| 764 | if !pending { |
| 765 | p.route = Route::Clarify; |
| 766 | p.why = RouteWhy::NothingPending; |
| 767 | return p; |
| 768 | } |
| 769 | // MUTANT: an approval phrase runs directly instead of going to the owner desk. |
| 770 | #[cfg(feature = "route-mutant-grant")] |
| 771 | if pending { |
| 772 | p.route = Route::LocalDeterministic; |
| 773 | return p; |
| 774 | } |
| 775 | if !owner { |
| 776 | p.route = Route::Refuse; |
| 777 | p.why = RouteWhy::GuestScope; |
| 778 | return p; |
| 779 | } |
| 780 | p.route = Route::ApprovalNeeded; |
| 781 | p.then = Some(match d.action { |
| 782 | Action::Approve => Then::Approve, |
| 783 | Action::Deny => Then::Deny, |
| 784 | _ => Then::Cancel, |
| 785 | }); |
| 786 | if !ctx.caps.desk { |
| 787 | p.not_ready = Some(NotReady::DeskAbsent); |
| 788 | } |
| 789 | } |
| 790 | Action::Clarify => { |
| 791 | p.route = Route::Clarify; |
| 792 | p.why = RouteWhy::CoreClarify; |
| 793 | } |
| 794 | Action::Refuse => { |
| 795 | p.route = Route::Refuse; |
| 796 | } |
| 797 | } |
| 798 | if p.not_ready.is_some() { |
| 799 | p.fallback = Some(Route::LocalDeterministic); |
| 800 | } |
| 801 | if matches!(p.route, Route::SparkInference | Route::SparkOmegese) { |
| 802 | p.pst1_digest = pst1_request(&p, msg.as_bytes(), &ctx.subject_id).map(|m| sha256::hash(&m)); |
| 803 | } |
| 804 | p |
| 805 | } |
| 806 | |
| 807 | /// Decode the `%HH` escapes of a route card or route family turns field (`%25` is `%`). |
| 808 | /// `None` on a malformed escape. Bytes that are not UTF-8 are replaced by U+FFFD, which the |
| 809 | /// router then treats as non-ASCII (`clarify`). |
| 810 | pub fn pct_decode(s: &str) -> Option<String> { |
| 811 | let b = s.as_bytes(); |
| 812 | let mut out: Vec<u8> = Vec::with_capacity(b.len()); |
| 813 | let mut i = 0; |
| 814 | while i < b.len() { |
| 815 | if b[i] == b'%' { |
| 816 | let h = |c: u8| match c { |
| 817 | b'0'..=b'9' => Some(c - b'0'), |
| 818 | b'a'..=b'f' => Some(c - b'a' + 10), |
| 819 | b'A'..=b'F' => Some(c - b'A' + 10), |
| 820 | _ => None, |
| 821 | }; |
| 822 | if i + 2 >= b.len() { |
| 823 | return None; |
| 824 | } |
| 825 | let (Some(hi), Some(lo)) = (h(b[i + 1]), h(b[i + 2])) else { |
| 826 | return None; |
| 827 | }; |
| 828 | out.push(hi << 4 | lo); |
| 829 | i += 3; |
| 830 | } else { |
| 831 | out.push(b[i]); |
| 832 | i += 1; |
| 833 | } |
| 834 | } |
| 835 | Some(String::from_utf8_lossy(&out).into_owned()) |
| 836 | } |