1mod types;
19
20pub use types::*;
21
22use reqwest::{Client, Method, StatusCode};
23use std::time::Duration;
24
25#[derive(Debug, thiserror::Error)]
27pub enum NSRError {
28 #[error("HTTP error: {0}")]
29 Http(#[from] reqwest::Error),
30 #[error("API error ({status}): {body}")]
31 Api { status: u16, body: String },
32 #[error("Rate limited (retry after {retry_after}s)")]
33 RateLimit { retry_after: f64 },
34 #[error("JSON error: {0}")]
35 Json(#[from] serde_json::Error),
36 #[error("overall deadline of {deadline:?} exceeded before the call could complete")]
37 DeadlineExceeded { deadline: std::time::Duration },
38}
39
40impl NSRError {
41 pub fn api_code(&self) -> Option<String> {
44 self.envelope_field("code")
45 }
46
47 pub fn api_message(&self) -> Option<String> {
49 self.envelope_field("message")
50 }
51
52 fn envelope_field(&self, key: &str) -> Option<String> {
53 let NSRError::Api { body, .. } = self else {
54 return None;
55 };
56 let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
57 parsed.get(key)?.as_str().map(str::to_owned)
58 }
59}
60
61fn generate_idempotency_key() -> String {
65 use std::sync::atomic::{AtomicU64, Ordering};
66 static COUNTER: AtomicU64 = AtomicU64::new(0);
67 let count = COUNTER.fetch_add(1, Ordering::Relaxed);
68 let nanos = std::time::SystemTime::now()
69 .duration_since(std::time::UNIX_EPOCH)
70 .map(|d| d.as_nanos())
71 .unwrap_or(0);
72 format!("nsr-{nanos:x}-{:x}-{count:x}", std::process::id())
73}
74
75pub struct NSRClient {
79 http: Client,
80 base_url: String,
81 api_key: String,
82 org_id: String,
83 max_retries: u32,
84 max_backoff: Duration,
85 overall_deadline: Duration,
86}
87
88const RETRY_AFTER_CAP_SECS: f64 = 60.0;
90
91const PER_REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
94
95impl NSRClient {
96 pub fn new(api_key: impl Into<String>, org_id: impl Into<String>) -> Self {
98 Self {
99 http: Client::builder()
100 .timeout(PER_REQUEST_TIMEOUT)
101 .user_agent(concat!("stateset-nsr-rust/", env!("CARGO_PKG_VERSION")))
102 .build()
103 .unwrap_or_default(),
104 base_url: "https://api.nsr.stateset.com".to_string(),
105 api_key: api_key.into(),
106 org_id: org_id.into(),
107 max_retries: 3,
108 max_backoff: Duration::from_secs(10),
109 overall_deadline: Duration::from_secs(120),
110 }
111 }
112
113 pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
115 self.base_url = url.into().trim_end_matches('/').to_string();
116 self
117 }
118
119 pub fn with_max_retries(mut self, n: u32) -> Self {
121 self.max_retries = n;
122 self
123 }
124
125 pub fn with_max_backoff(mut self, d: Duration) -> Self {
127 self.max_backoff = d;
128 self
129 }
130
131 pub fn with_overall_deadline(mut self, d: Duration) -> Self {
138 self.overall_deadline = d;
139 self
140 }
141
142 fn backoff_delay(&self, attempt: u32) -> Duration {
145 let base = Duration::from_millis(500_u64.saturating_mul(2_u64.saturating_pow(attempt)))
146 .min(self.max_backoff);
147 let nanos = std::time::SystemTime::now()
149 .duration_since(std::time::UNIX_EPOCH)
150 .map(|d| d.subsec_nanos() as u64)
151 .unwrap_or(0);
152 let half = base / 2;
153 let jitter_ms = if half.as_millis() == 0 {
154 0
155 } else {
156 nanos % (half.as_millis() as u64 + 1)
157 };
158 (half + Duration::from_millis(jitter_ms)).min(self.max_backoff)
159 }
160
161 fn within_deadline(&self, started: std::time::Instant, delay: Duration) -> bool {
163 started.elapsed() + delay < self.overall_deadline
164 }
165
166 async fn request<T: serde::de::DeserializeOwned>(
167 &self,
168 method: Method,
169 path: &str,
170 body: Option<serde_json::Value>,
171 ) -> Result<T, NSRError> {
172 self.request_with_headers(method, path, body, &[]).await
173 }
174
175 async fn request_with_headers<T: serde::de::DeserializeOwned>(
176 &self,
177 method: Method,
178 path: &str,
179 body: Option<serde_json::Value>,
180 extra_headers: &[(&str, String)],
181 ) -> Result<T, NSRError> {
182 let url = format!("{}{}", self.base_url, path);
183 let started = std::time::Instant::now();
184
185 let is_mutating = matches!(
190 method,
191 Method::POST | Method::PUT | Method::PATCH | Method::DELETE
192 );
193 let has_explicit_key = extra_headers
194 .iter()
195 .any(|(name, _)| name.eq_ignore_ascii_case("Idempotency-Key"));
196 let auto_key = (is_mutating && !has_explicit_key).then(generate_idempotency_key);
197
198 for attempt in 0..=self.max_retries {
199 let remaining = self.overall_deadline.saturating_sub(started.elapsed());
203 if remaining.is_zero() {
204 return Err(NSRError::DeadlineExceeded {
205 deadline: self.overall_deadline,
206 });
207 }
208 let attempt_timeout = remaining.min(PER_REQUEST_TIMEOUT);
209 let mut req = self
210 .http
211 .request(method.clone(), &url)
212 .timeout(attempt_timeout)
213 .header("Content-Type", "application/json")
214 .header("X-API-Key", &self.api_key)
215 .header("X-Org-ID", &self.org_id);
216 for (name, value) in extra_headers {
219 req = req.header(*name, value);
220 }
221 if let Some(ref key) = auto_key {
222 req = req.header("Idempotency-Key", key);
223 }
224
225 if let Some(ref b) = body {
226 req = req.json(b);
227 }
228
229 let resp = match req.send().await {
232 Ok(resp) => resp,
233 Err(err) => {
234 let delay = self.backoff_delay(attempt);
235 if attempt < self.max_retries && self.within_deadline(started, delay) {
236 tokio::time::sleep(delay).await;
237 continue;
238 }
239 return Err(err.into());
240 }
241 };
242 let status = resp.status();
243
244 if status == StatusCode::TOO_MANY_REQUESTS {
246 let retry_after = resp
247 .headers()
248 .get("Retry-After")
249 .and_then(|v| v.to_str().ok())
250 .and_then(|v| v.parse::<f64>().ok())
251 .unwrap_or(1.0)
252 .clamp(0.0, RETRY_AFTER_CAP_SECS);
253 let delay = Duration::from_secs_f64(retry_after);
254 if attempt < self.max_retries && self.within_deadline(started, delay) {
255 tokio::time::sleep(delay).await;
256 continue;
257 }
258 return Err(NSRError::RateLimit { retry_after });
259 }
260
261 if status.is_server_error() && attempt < self.max_retries {
263 let delay = self.backoff_delay(attempt);
264 if self.within_deadline(started, delay) {
265 tokio::time::sleep(delay).await;
266 continue;
267 }
268 }
269
270 if !status.is_success() {
271 let body = resp.text().await.unwrap_or_default();
272 return Err(NSRError::Api {
273 status: status.as_u16(),
274 body,
275 });
276 }
277
278 return Ok(resp.json().await?);
279 }
280
281 Err(NSRError::Api {
282 status: 0,
283 body: "max retries exceeded".to_string(),
284 })
285 }
286
287 async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T, NSRError> {
288 self.request(Method::GET, path, None).await
289 }
290
291 async fn post<T: serde::de::DeserializeOwned>(
292 &self,
293 path: &str,
294 body: serde_json::Value,
295 ) -> Result<T, NSRError> {
296 self.request(Method::POST, path, Some(body)).await
297 }
298
299 async fn delete(&self, path: &str) -> Result<serde_json::Value, NSRError> {
300 self.request(Method::DELETE, path, None).await
301 }
302
303 async fn delete_as<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T, NSRError> {
304 self.request(Method::DELETE, path, None).await
305 }
306
307 async fn patch<T: serde::de::DeserializeOwned>(
308 &self,
309 path: &str,
310 body: serde_json::Value,
311 ) -> Result<T, NSRError> {
312 self.request(Method::PATCH, path, Some(body)).await
313 }
314
315 pub async fn chat(&self, message: &str) -> Result<ChatResponse, NSRError> {
319 self.post(
320 "/api/v1/nsr/chat",
321 serde_json::json!({"message": message, "max_recursive_steps": 4}),
322 )
323 .await
324 }
325
326 pub async fn chat_with_options(
328 &self,
329 message: &str,
330 session_id: Option<&str>,
331 history: Option<Vec<ChatMessage>>,
332 max_steps: u8,
333 ) -> Result<ChatResponse, NSRError> {
334 let mut body = serde_json::json!({
335 "message": message,
336 "max_recursive_steps": max_steps,
337 });
338 if let Some(sid) = session_id {
339 body["session_id"] = serde_json::json!(sid);
340 }
341 if let Some(h) = history {
342 body["history"] = serde_json::to_value(h)?;
343 }
344 self.post("/api/v1/nsr/chat", body).await
345 }
346
347 pub async fn completions(
349 &self,
350 messages: Vec<serde_json::Value>,
351 tools: Option<Vec<serde_json::Value>>,
352 ) -> Result<serde_json::Value, NSRError> {
353 let mut body = serde_json::json!({
354 "model": "nsr-v1",
355 "messages": messages,
356 });
357 if let Some(t) = tools {
358 body["tools"] = serde_json::json!(t);
359 }
360 self.post("/v1/chat/completions", body).await
361 }
362
363 pub async fn messages(
365 &self,
366 messages: Vec<serde_json::Value>,
367 max_tokens: u32,
368 system: Option<&str>,
369 ) -> Result<serde_json::Value, NSRError> {
370 let mut body = serde_json::json!({
371 "model": "nsr-v2-accurate",
372 "max_tokens": max_tokens,
373 "messages": messages,
374 });
375 if let Some(s) = system {
376 body["system"] = serde_json::json!(s);
377 }
378 self.post("/v1/messages", body).await
379 }
380
381 pub async fn decide(
389 &self,
390 query: &str,
391 action: Option<&str>,
392 mode: &str,
393 facts: Option<Vec<serde_json::Value>>,
394 rules: Option<Vec<serde_json::Value>>,
395 ) -> Result<DecisionResponse, NSRError> {
396 let mut body = serde_json::json!({
397 "query": query,
398 "mode": mode,
399 "hydrate_org_context": true,
400 });
401 if let Some(a) = action {
402 body["action"] = serde_json::json!(a);
403 }
404 if let Some(f) = facts {
405 body["facts"] = serde_json::json!(f);
406 }
407 if let Some(r) = rules {
408 body["rules"] = serde_json::json!(r);
409 }
410 let key = generate_idempotency_key();
411 self.request_with_headers(
412 Method::POST,
413 "/v1/decisions",
414 Some(body),
415 &[("Idempotency-Key", key)],
416 )
417 .await
418 }
419
420 pub async fn decide_batch(
430 &self,
431 items: Vec<serde_json::Value>,
432 ) -> Result<BatchDecisionResponse, NSRError> {
433 self.decide_batch_with_idempotency_key(&generate_idempotency_key(), items)
434 .await
435 }
436
437 pub async fn decide_batch_with_idempotency_key(
443 &self,
444 key: &str,
445 items: Vec<serde_json::Value>,
446 ) -> Result<BatchDecisionResponse, NSRError> {
447 self.request_with_headers(
448 Method::POST,
449 "/v1/decisions/batch",
450 Some(serde_json::json!({ "items": items })),
451 &[("Idempotency-Key", key.to_string())],
452 )
453 .await
454 }
455
456 pub async fn recent_decisions(&self, limit: usize) -> Result<RecentDecisionsResponse, NSRError> {
460 self.get(&format!("/v1/decisions/recent?limit={limit}")).await
461 }
462
463 pub async fn decision_stats(&self, window_secs: u64) -> Result<serde_json::Value, NSRError> {
466 self.get(&format!("/v1/decisions/stats?window_secs={window_secs}"))
467 .await
468 }
469
470 pub async fn rule_stats(&self, window_secs: u64) -> Result<serde_json::Value, NSRError> {
474 self.get(&format!("/v1/decisions/rule-stats?window_secs={window_secs}"))
475 .await
476 }
477
478 pub async fn refusal_gaps(&self, window_secs: u64) -> Result<serde_json::Value, NSRError> {
483 self.get(&format!("/v1/decisions/refusal-gaps?window_secs={window_secs}"))
484 .await
485 }
486
487 pub async fn demote_noisy(&self, options: serde_json::Value) -> Result<serde_json::Value, NSRError> {
492 self.post("/api/v1/flywheel/demote-noisy", options).await
493 }
494
495 pub async fn get_decision(&self, decision_id: &str) -> Result<DecisionRecord, NSRError> {
500 self.get(&format!("/v1/decisions/{decision_id}")).await
501 }
502
503 pub async fn gss_seed_info(&self) -> Result<serde_json::Value, NSRError> {
508 self.get("/api/v1/gss/seed").await
509 }
510
511 pub async fn add_entity(
514 &self,
515 name: &str,
516 entity_type: &str,
517 properties: Option<serde_json::Value>,
518 ) -> Result<Entity, NSRError> {
519 let mut body = serde_json::json!({"name": name, "entity_type": entity_type});
520 if let Some(props) = properties {
521 body["properties"] = props;
522 }
523 self.post("/api/v1/entities", body).await
524 }
525
526 pub async fn get_entity(&self, id: &str) -> Result<serde_json::Value, NSRError> {
527 self.get(&format!("/api/v1/entities/{id}")).await
528 }
529
530 pub async fn delete_entity(&self, id: &str) -> Result<serde_json::Value, NSRError> {
531 self.delete(&format!("/api/v1/entities/{id}")).await
532 }
533
534 pub async fn list_entities(&self) -> Result<serde_json::Value, NSRError> {
535 self.list_entities_with(&ListParams::default()).await
536 }
537
538 pub async fn list_entities_with(
540 &self,
541 params: &ListParams,
542 ) -> Result<serde_json::Value, NSRError> {
543 self.get(&format!("/api/v1/entities{}", params.to_query()))
544 .await
545 }
546
547 pub async fn search_entities(
549 &self,
550 q: &str,
551 limit: Option<usize>,
552 ) -> Result<Vec<Entity>, NSRError> {
553 let mut path = format!("/api/v1/entities/search?q={}", urlencode(q));
554 if let Some(l) = limit {
555 path.push_str(&format!("&limit={l}"));
556 }
557 self.get(&path).await
558 }
559
560 pub async fn add_rule(
561 &self,
562 name: &str,
563 head_predicate: &str,
564 head_args: &[&str],
565 body_clauses: Vec<serde_json::Value>,
566 confidence: f32,
567 ) -> Result<Rule, NSRError> {
568 self.post(
569 "/api/v1/rules",
570 serde_json::json!({
571 "name": name, "head_predicate": head_predicate, "head_args": head_args,
572 "body": body_clauses, "confidence": confidence,
573 }),
574 )
575 .await
576 }
577
578 pub async fn list_rules(&self) -> Result<serde_json::Value, NSRError> {
579 self.list_rules_with(&ListParams::default()).await
580 }
581
582 pub async fn list_rules_with(
584 &self,
585 params: &ListParams,
586 ) -> Result<serde_json::Value, NSRError> {
587 self.get(&format!("/api/v1/rules{}", params.to_query())).await
588 }
589
590 pub async fn get_rule(&self, id: &str) -> Result<serde_json::Value, NSRError> {
592 self.get(&format!("/api/v1/rules/{id}")).await
593 }
594
595 pub async fn update_rule(
597 &self,
598 id: &str,
599 update: &RuleUpdate,
600 ) -> Result<serde_json::Value, NSRError> {
601 self.patch(&format!("/api/v1/rules/{id}"), serde_json::to_value(update)?)
602 .await
603 }
604
605 pub async fn delete_rule(&self, id: &str) -> Result<serde_json::Value, NSRError> {
607 self.delete(&format!("/api/v1/rules/{id}")).await
608 }
609
610 pub async fn lint_rule(&self, rule: &RuleSpec) -> Result<RuleLintResponse, NSRError> {
612 self.post("/api/v1/rules/lint", serde_json::to_value(rule)?)
613 .await
614 }
615
616 pub async fn batch_create_rules(
618 &self,
619 rules: &[RuleSpec],
620 ) -> Result<BatchCreateRulesResponse, NSRError> {
621 self.post(
622 "/api/v1/rules/batch",
623 serde_json::json!({ "rules": rules }),
624 )
625 .await
626 }
627
628 pub async fn add_triple(
629 &self,
630 subject_id: &str,
631 predicate: &str,
632 object_id: &str,
633 confidence: f32,
634 ) -> Result<serde_json::Value, NSRError> {
635 self.post(
636 "/api/v1/triples",
637 serde_json::json!({
638 "subject_id": subject_id, "predicate": predicate,
639 "object_id": object_id, "confidence": confidence,
640 }),
641 )
642 .await
643 }
644
645 pub async fn batch_create_triples(
647 &self,
648 triples: &[TripleSpec],
649 ) -> Result<BatchCreateTriplesResponse, NSRError> {
650 self.post(
651 "/api/v1/triples/batch",
652 serde_json::json!({ "triples": triples }),
653 )
654 .await
655 }
656
657 pub async fn kb_stats(&self) -> Result<KBStats, NSRError> {
658 self.get("/api/v1/kb/stats").await
659 }
660
661 pub async fn query(
664 &self,
665 patterns: &[TriplePattern],
666 limit: Option<usize>,
667 ) -> Result<QueryResponse, NSRError> {
668 let mut body = serde_json::json!({ "patterns": patterns });
669 if let Some(l) = limit {
670 body["limit"] = serde_json::json!(l);
671 }
672 self.post("/api/v1/query", body).await
673 }
674
675 pub async fn kb_graph(
678 &self,
679 analysis_type: &str,
680 entity_id: Option<&str>,
681 limit: Option<usize>,
682 ) -> Result<GraphAnalysisResponse, NSRError> {
683 let mut body = serde_json::json!({ "analysis_type": analysis_type });
684 if let Some(id) = entity_id {
685 body["entity_id"] = serde_json::json!(id);
686 }
687 if let Some(l) = limit {
688 body["limit"] = serde_json::json!(l);
689 }
690 self.post("/api/v1/kb/graph", body).await
691 }
692
693 pub async fn verify_proof(
700 &self,
701 bundle: serde_json::Value,
702 ) -> Result<ProofVerifyResponse, NSRError> {
703 self.post("/v1/proofs/verify", bundle).await
704 }
705
706 pub async fn signup(&self, email: &str, password: &str) -> Result<AuthResponse, NSRError> {
711 self.post(
712 "/api/v1/auth/signup",
713 serde_json::json!({"email": email, "password": password}),
714 )
715 .await
716 }
717
718 pub async fn login(&self, email: &str, password: &str) -> Result<AuthResponse, NSRError> {
720 self.post(
721 "/api/v1/auth/login",
722 serde_json::json!({"email": email, "password": password}),
723 )
724 .await
725 }
726
727 pub async fn auth_session(&self) -> Result<AuthSessionResponse, NSRError> {
729 self.get("/api/v1/auth/session").await
730 }
731
732 pub async fn create_api_key(
735 &self,
736 req: &ApiKeyCreateRequest,
737 ) -> Result<ApiKeyCreateResponse, NSRError> {
738 self.post("/api/v1/auth/keys", serde_json::to_value(req)?)
739 .await
740 }
741
742 pub async fn list_api_keys(&self) -> Result<ApiKeyListResponse, NSRError> {
744 self.get("/api/v1/auth/keys").await
745 }
746
747 pub async fn revoke_api_key(&self, id: &str) -> Result<ApiKeyRevokeResponse, NSRError> {
749 self.delete_as(&format!("/api/v1/auth/keys/{id}")).await
750 }
751
752 pub async fn list_jobs(&self, params: &JobListParams) -> Result<ListJobsResponse, NSRError> {
758 self.get(&format!("/api/v1/jobs{}", params.to_query())).await
759 }
760
761 pub async fn submit_batch_infer(
763 &self,
764 req: &BatchInferRequest,
765 ) -> Result<JobSubmitResponse, NSRError> {
766 self.post("/api/v1/jobs/batch-infer", serde_json::to_value(req)?)
767 .await
768 }
769
770 pub async fn get_job(&self, job_id: &str) -> Result<JobStatusResponse, NSRError> {
772 self.get(&format!("/api/v1/jobs/{job_id}")).await
773 }
774
775 pub async fn cancel_job(&self, job_id: &str) -> Result<CancelJobResponse, NSRError> {
777 self.post(&format!("/api/v1/jobs/{job_id}/cancel"), serde_json::json!({}))
778 .await
779 }
780
781 pub async fn delete_job(&self, job_id: &str) -> Result<serde_json::Value, NSRError> {
783 self.delete(&format!("/api/v1/jobs/{job_id}")).await
784 }
785
786 pub async fn add_belief(
790 &self,
791 proposition: &str,
792 confidence: f32,
793 source: Option<&str>,
794 ) -> Result<BeliefResponse, NSRError> {
795 let mut body = serde_json::json!({"proposition": proposition, "confidence": confidence});
796 if let Some(s) = source {
797 body["source"] = serde_json::json!(s);
798 }
799 self.post("/api/v1/beliefs", body).await
800 }
801
802 pub async fn get_belief(&self, proposition: &str) -> Result<BeliefResponse, NSRError> {
804 self.get(&format!("/api/v1/beliefs/{}", urlencode(proposition)))
805 .await
806 }
807
808 pub async fn support_belief(
810 &self,
811 proposition: &str,
812 strength: f32,
813 source: Option<&str>,
814 ) -> Result<ModifyBeliefResponse, NSRError> {
815 self.modify_belief("/api/v1/beliefs/support", proposition, strength, source)
816 .await
817 }
818
819 pub async fn contradict_belief(
821 &self,
822 proposition: &str,
823 strength: f32,
824 source: Option<&str>,
825 ) -> Result<ModifyBeliefResponse, NSRError> {
826 self.modify_belief("/api/v1/beliefs/contradict", proposition, strength, source)
827 .await
828 }
829
830 async fn modify_belief(
831 &self,
832 path: &str,
833 proposition: &str,
834 strength: f32,
835 source: Option<&str>,
836 ) -> Result<ModifyBeliefResponse, NSRError> {
837 let mut body = serde_json::json!({"proposition": proposition, "strength": strength});
838 if let Some(s) = source {
839 body["source"] = serde_json::json!(s);
840 }
841 self.post(path, body).await
842 }
843
844 pub async fn refute_belief(&self, proposition: &str) -> Result<serde_json::Value, NSRError> {
846 self.post(
847 &format!("/api/v1/beliefs/refute/{}", urlencode(proposition)),
848 serde_json::json!({}),
849 )
850 .await
851 }
852
853 pub async fn check_belief_conflicts(
855 &self,
856 prop1: &str,
857 prop2: &str,
858 ) -> Result<BeliefConflictsResponse, NSRError> {
859 self.post(
860 "/api/v1/beliefs/conflicts",
861 serde_json::json!({"prop1": prop1, "prop2": prop2}),
862 )
863 .await
864 }
865
866 pub async fn explain_belief(&self, proposition: &str) -> Result<serde_json::Value, NSRError> {
868 self.get(&format!("/api/v1/beliefs/{}/explain", urlencode(proposition)))
869 .await
870 }
871
872 pub async fn belief_history(&self, proposition: &str) -> Result<serde_json::Value, NSRError> {
874 self.get(&format!("/api/v1/beliefs/{}/history", urlencode(proposition)))
875 .await
876 }
877
878 pub async fn create_constraint(
882 &self,
883 spec: &ConstraintSpec,
884 ) -> Result<ConstraintResponse, NSRError> {
885 self.post("/api/v1/constraints", serde_json::to_value(spec)?)
886 .await
887 }
888
889 pub async fn list_constraints(&self) -> Result<ListConstraintsResponse, NSRError> {
891 self.get("/api/v1/constraints").await
892 }
893
894 pub async fn get_constraint(&self, id: &str) -> Result<ConstraintResponse, NSRError> {
896 self.get(&format!("/api/v1/constraints/{}", urlencode(id)))
897 .await
898 }
899
900 pub async fn delete_constraint(&self, id: &str) -> Result<serde_json::Value, NSRError> {
902 self.delete(&format!("/api/v1/constraints/{}", urlencode(id)))
903 .await
904 }
905
906 pub async fn validate_constraints(
909 &self,
910 facts: &[&str],
911 ) -> Result<ValidateConstraintsResponse, NSRError> {
912 self.post(
913 "/api/v1/constraints/validate",
914 serde_json::json!({ "facts": facts }),
915 )
916 .await
917 }
918
919 pub async fn policy_infer(
923 &self,
924 tool_name: &str,
925 tool_input: serde_json::Value,
926 ) -> Result<PolicyInferResponse, NSRError> {
927 self.post(
928 "/api/v1/policy/infer",
929 serde_json::json!({"tool_name": tool_name, "tool_input": tool_input}),
930 )
931 .await
932 }
933
934 pub async fn policy_evaluate(
936 &self,
937 inquiry: &str,
938 response: &str,
939 executed_tools: &[&str],
940 ) -> Result<PolicyEvaluateResponse, NSRError> {
941 self.post(
942 "/api/v1/policy/evaluate",
943 serde_json::json!({
944 "inquiry": inquiry,
945 "response": response,
946 "executed_tools": executed_tools,
947 }),
948 )
949 .await
950 }
951
952 pub async fn policy_train(
954 &self,
955 body: serde_json::Value,
956 ) -> Result<serde_json::Value, NSRError> {
957 self.post("/api/v1/policy/train", body).await
958 }
959
960 pub async fn policy_vocab_init(
962 &self,
963 body: serde_json::Value,
964 ) -> Result<serde_json::Value, NSRError> {
965 self.post("/api/v1/policy/vocab/init", body).await
966 }
967
968 pub async fn link_entitlement(
974 &self,
975 org_id: &str,
976 token: &str,
977 entitlement: serde_json::Value,
978 ) -> Result<serde_json::Value, NSRError> {
979 self.post(
980 "/v1/metering/entitlement",
981 serde_json::json!({"org_id": org_id, "token": token, "entitlement": entitlement}),
982 )
983 .await
984 }
985
986 pub async fn get_entitlement(&self, org_id: &str) -> Result<serde_json::Value, NSRError> {
988 self.get(&format!("/v1/metering/entitlement/{}", urlencode(org_id)))
989 .await
990 }
991
992 pub async fn aws_register(
994 &self,
995 req: &AwsRegisterRequest,
996 ) -> Result<serde_json::Value, NSRError> {
997 self.post("/v1/metering/aws/register", serde_json::to_value(req)?)
998 .await
999 }
1000
1001 pub async fn azure_register(
1003 &self,
1004 req: &AzureRegisterRequest,
1005 ) -> Result<serde_json::Value, NSRError> {
1006 self.post("/v1/metering/azure/register", serde_json::to_value(req)?)
1007 .await
1008 }
1009
1010 pub async fn gcp_pubsub(
1012 &self,
1013 event: serde_json::Value,
1014 ) -> Result<serde_json::Value, NSRError> {
1015 self.post("/v1/metering/gcp/pubsub", event).await
1016 }
1017
1018 pub async fn provision_machine(&self, seed_from_gss: bool) -> Result<serde_json::Value, NSRError> {
1021 self.post("/api/v1/machines/provision", serde_json::json!({"seed_from_gss": seed_from_gss})).await
1022 }
1023
1024 pub async fn train_machine(&self, examples: Vec<TrainingExample>) -> Result<serde_json::Value, NSRError> {
1025 self.post("/api/v1/machines/train", serde_json::json!({"examples": examples})).await
1026 }
1027
1028 pub async fn evaluate_machine(&self, examples: Vec<TrainingExample>) -> Result<serde_json::Value, NSRError> {
1029 self.post("/api/v1/machines/evaluate", serde_json::json!({"test_examples": examples})).await
1030 }
1031
1032 pub async fn machine_infer(&self, inputs: &[&str]) -> Result<serde_json::Value, NSRError> {
1033 self.post("/api/v1/machines/infer", serde_json::json!({"inputs": inputs})).await
1034 }
1035
1036 pub async fn machine_status(&self) -> Result<MachineStatus, NSRError> {
1037 self.get("/api/v1/machines/status").await
1038 }
1039
1040 pub async fn seed_machine_pack(
1046 &self,
1047 body: serde_json::Value,
1048 ) -> Result<serde_json::Value, NSRError> {
1049 self.post("/api/v1/machines/seed", body).await
1050 }
1051
1052 pub async fn compile_machine_pack(
1054 &self,
1055 body: serde_json::Value,
1056 ) -> Result<serde_json::Value, NSRError> {
1057 self.post("/api/v1/machines/compile", body).await
1058 }
1059
1060 pub async fn evaluate_machine_seed(
1062 &self,
1063 body: serde_json::Value,
1064 ) -> Result<serde_json::Value, NSRError> {
1065 self.post("/api/v1/machines/evaluate-seed", body).await
1066 }
1067
1068 pub async fn activate_machine_pack(
1070 &self,
1071 body: serde_json::Value,
1072 ) -> Result<serde_json::Value, NSRError> {
1073 self.post("/api/v1/machines/activate", body).await
1074 }
1075
1076 pub async fn create_webhook(
1083 &self,
1084 url: &str,
1085 events: &[&str],
1086 ) -> Result<serde_json::Value, NSRError> {
1087 self.post(
1088 "/api/v1/webhooks",
1089 serde_json::json!({"url": url, "events": events}),
1090 )
1091 .await
1092 }
1093
1094 pub async fn list_webhooks(&self) -> Result<serde_json::Value, NSRError> {
1096 self.get("/api/v1/webhooks").await
1097 }
1098
1099 pub async fn delete_webhook(&self, id: &str) -> Result<serde_json::Value, NSRError> {
1101 self.delete(&format!("/api/v1/webhooks/{id}")).await
1102 }
1103
1104 pub async fn webhook_deliveries(
1106 &self,
1107 id: &str,
1108 limit: usize,
1109 ) -> Result<serde_json::Value, NSRError> {
1110 self.get(&format!("/api/v1/webhooks/{id}/deliveries?limit={limit}"))
1111 .await
1112 }
1113
1114 pub async fn list_templates(&self) -> Result<serde_json::Value, NSRError> {
1118 self.get("/api/v1/templates").await
1119 }
1120
1121 pub async fn get_template(&self, slug: &str) -> Result<serde_json::Value, NSRError> {
1123 self.get(&format!("/api/v1/templates/{slug}")).await
1124 }
1125
1126 pub async fn apply_template(
1131 &self,
1132 slug: &str,
1133 mode: Option<&str>,
1134 ) -> Result<serde_json::Value, NSRError> {
1135 let query = mode.map(|m| format!("?mode={m}")).unwrap_or_default();
1136 self.post(
1137 &format!("/api/v1/templates/{slug}/apply{query}"),
1138 serde_json::json!({}),
1139 )
1140 .await
1141 }
1142
1143 pub async fn list_machines(&self) -> Result<serde_json::Value, NSRError> {
1144 self.get("/api/v1/machines").await
1145 }
1146
1147 pub async fn reason(&self, query: &str, strategy: &str) -> Result<serde_json::Value, NSRError> {
1150 self.post("/api/v1/reason", serde_json::json!({"query": query, "strategy": strategy})).await
1151 }
1152
1153 pub async fn forward_chain(&self, max_iterations: u32) -> Result<serde_json::Value, NSRError> {
1154 self.post("/api/v1/forward-chain", serde_json::json!({"max_iterations": max_iterations})).await
1155 }
1156
1157 pub async fn backward_chain(&self, goal_predicate: &str, goal_args: &[&str]) -> Result<serde_json::Value, NSRError> {
1158 self.post("/api/v1/backward-chain", serde_json::json!({"goal_predicate": goal_predicate, "goal_args": goal_args})).await
1159 }
1160
1161 pub async fn explain(&self, query: &str) -> Result<serde_json::Value, NSRError> {
1162 self.post("/api/v1/explain", serde_json::json!({"query": query})).await
1163 }
1164
1165 pub async fn rag_query(&self, query: &str, max_context: u32) -> Result<serde_json::Value, NSRError> {
1168 self.post("/api/v1/rag/query", serde_json::json!({"query": query, "max_context": max_context})).await
1169 }
1170
1171 pub async fn create_session(&self) -> Result<serde_json::Value, NSRError> {
1174 self.post("/api/v1/sessions", serde_json::json!({})).await
1175 }
1176
1177 pub async fn get_session(&self, id: &str) -> Result<serde_json::Value, NSRError> {
1178 self.get(&format!("/api/v1/sessions/{id}")).await
1179 }
1180
1181 pub async fn session_history(&self, id: &str) -> Result<serde_json::Value, NSRError> {
1182 self.get(&format!("/api/v1/sessions/{id}/history")).await
1183 }
1184
1185 pub async fn flywheel_feedback(&self, query: &str, answer: &str, positive: bool) -> Result<serde_json::Value, NSRError> {
1188 self.post("/api/v1/flywheel/feedback", serde_json::json!({"query": query, "answer": answer, "positive": positive})).await
1189 }
1190
1191 pub async fn flywheel_stats(&self) -> Result<serde_json::Value, NSRError> {
1192 self.get("/api/v1/flywheel/stats").await
1193 }
1194
1195 pub async fn flywheel_train(&self) -> Result<serde_json::Value, NSRError> {
1196 self.post("/api/v1/flywheel/train", serde_json::json!({})).await
1197 }
1198
1199 pub async fn nsrl_parse(&self, program: &str) -> Result<serde_json::Value, NSRError> {
1202 self.post("/api/v1/nsrl/parse", serde_json::json!({"program": program})).await
1203 }
1204
1205 pub async fn nsrl_execute(&self, program: &str) -> Result<serde_json::Value, NSRError> {
1206 self.post("/api/v1/nsrl/execute", serde_json::json!({"program": program})).await
1207 }
1208
1209 pub async fn nsrl_prove(&self, goal: &str) -> Result<serde_json::Value, NSRError> {
1210 self.post("/api/v1/nsrl/prove", serde_json::json!({"goal": goal})).await
1211 }
1212
1213 pub async fn list_symbols(&self) -> Result<serde_json::Value, NSRError> {
1216 self.get("/api/v1/nsr/symbols").await
1217 }
1218
1219 pub async fn nsr_stats(&self) -> Result<serde_json::Value, NSRError> {
1220 self.get("/api/v1/nsr/stats").await
1221 }
1222
1223 pub async fn nsr_features(&self) -> Result<serde_json::Value, NSRError> {
1224 self.get("/api/v1/nsr/features").await
1225 }
1226
1227 pub async fn usage(&self) -> Result<UsageResponse, NSRError> {
1230 self.get("/api/v1/billing/usage").await
1231 }
1232
1233 pub async fn subscription_info(&self) -> Result<serde_json::Value, NSRError> {
1234 self.get("/api/v1/billing/subscription").await
1235 }
1236
1237 pub async fn plans(&self) -> Result<serde_json::Value, NSRError> {
1238 self.get("/api/v1/billing/plans").await
1239 }
1240
1241 pub async fn credits(&self) -> Result<serde_json::Value, NSRError> {
1242 self.get("/api/v1/billing/credits").await
1243 }
1244
1245 pub async fn purchase_credits(&self, amount_dollars: f64) -> Result<serde_json::Value, NSRError> {
1246 self.post("/api/v1/billing/credits/purchase", serde_json::json!({"amount_dollars": amount_dollars})).await
1247 }
1248
1249 pub async fn invoices(&self) -> Result<serde_json::Value, NSRError> {
1250 self.get("/api/v1/billing/invoices").await
1251 }
1252
1253 pub async fn list_agents(&self) -> Result<serde_json::Value, NSRError> {
1256 self.get("/api/v1/agents").await
1257 }
1258
1259 pub async fn start_agent(&self, name: &str) -> Result<serde_json::Value, NSRError> {
1260 self.post(&format!("/api/v1/agents/{name}/start"), serde_json::json!({})).await
1261 }
1262
1263 pub async fn stop_agent(&self, name: &str) -> Result<serde_json::Value, NSRError> {
1264 self.post(&format!("/api/v1/agents/{name}/stop"), serde_json::json!({})).await
1265 }
1266
1267 pub async fn sandbox_run(&self, language: &str, code: &str, timeout_secs: u32) -> Result<serde_json::Value, NSRError> {
1270 self.post("/api/v1/sandbox/run", serde_json::json!({"language": language, "code": code, "timeout_seconds": timeout_secs})).await
1271 }
1272
1273 pub async fn health(&self) -> Result<serde_json::Value, NSRError> {
1276 self.get("/health").await
1277 }
1278
1279 pub async fn ready(&self) -> Result<serde_json::Value, NSRError> {
1280 self.get("/ready").await
1281 }
1282}
1283
1284pub fn verify_webhook_signature(
1292 signing_secret: &str,
1293 body: &str,
1294 header: &str,
1295 tolerance_secs: Option<u64>,
1296) -> bool {
1297 use hmac::{Hmac, Mac};
1298 use sha2::Sha256;
1299
1300 let mut t_count = 0usize;
1304 let mut timestamp: Option<i64> = None;
1305 let mut sigs: Vec<&str> = Vec::new();
1306 for part in header.split(',') {
1307 let part = part.trim();
1308 if let Some(v) = part.strip_prefix("t=") {
1309 t_count += 1;
1310 timestamp = v.parse::<i64>().ok();
1311 } else if let Some(v) = part.strip_prefix("v1=") {
1312 sigs.push(v);
1313 }
1314 }
1315 if t_count != 1 {
1316 return false;
1317 }
1318 let Some(t) = timestamp else {
1319 return false;
1320 };
1321 if sigs.is_empty() {
1322 return false;
1323 }
1324 if let Some(tolerance) = tolerance_secs {
1325 let now = std::time::SystemTime::now()
1326 .duration_since(std::time::UNIX_EPOCH)
1327 .map(|d| d.as_secs() as i64)
1328 .unwrap_or(0);
1329 if now.saturating_sub(t).unsigned_abs() > tolerance {
1334 return false;
1335 }
1336 }
1337 let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(signing_secret.as_bytes()) else {
1338 return false;
1339 };
1340 mac.update(format!("{t}.{body}").as_bytes());
1341 let expected: String = mac
1342 .finalize()
1343 .into_bytes()
1344 .iter()
1345 .map(|b| format!("{b:02x}"))
1346 .collect();
1347 let mut any_match = false;
1350 for sig in sigs {
1351 let sig = sig.to_ascii_lowercase();
1352 if expected.len() != sig.len() {
1353 continue;
1354 }
1355 any_match |= expected
1356 .bytes()
1357 .zip(sig.bytes())
1358 .fold(0u8, |acc, (a, b)| acc | (a ^ b))
1359 == 0;
1360 }
1361 any_match
1362}
1363
1364#[cfg(test)]
1365mod webhook_signature_tests {
1366 use super::verify_webhook_signature;
1367
1368 const BODY: &str = r#"{"event":"outcome.produced"}"#;
1369 const HEADER: &str =
1370 "t=1700000000,v1=d64be69f786ce81f89cfc89f1bd78ddae1996475e6b916e5c3107ee3ce1cecde";
1371
1372 #[test]
1373 fn golden_vector_verifies() {
1374 assert!(verify_webhook_signature("whsec_testsecret", BODY, HEADER, None));
1375 }
1376
1377 #[test]
1378 fn tampered_body_and_wrong_secret_fail() {
1379 assert!(!verify_webhook_signature(
1380 "whsec_testsecret",
1381 r#"{"event":"tampered"}"#,
1382 HEADER,
1383 None
1384 ));
1385 assert!(!verify_webhook_signature("whsec_wrong", BODY, HEADER, None));
1386 }
1387
1388 #[test]
1389 fn any_matching_v1_verifies_during_secret_rotation() {
1390 let header = format!("v1=deadbeef{},{}", "0".repeat(56), HEADER);
1393 assert!(verify_webhook_signature("whsec_testsecret", BODY, &header, None));
1394 let header = format!("{},v1=deadbeef{}", HEADER, "0".repeat(56));
1396 assert!(verify_webhook_signature("whsec_testsecret", BODY, &header, None));
1397 }
1398
1399 #[test]
1400 fn duplicate_t_is_rejected() {
1401 let header = format!("t=1700000000,{HEADER}");
1402 assert!(!verify_webhook_signature(
1403 "whsec_testsecret",
1404 BODY,
1405 &header,
1406 None
1407 ));
1408 }
1409
1410 #[test]
1411 fn uppercase_hex_signature_verifies() {
1412 let upper = HEADER.replace(
1413 "d64be69f786ce81f89cfc89f1bd78ddae1996475e6b916e5c3107ee3ce1cecde",
1414 "D64BE69F786CE81F89CFC89F1BD78DDAE1996475E6B916E5C3107EE3CE1CECDE",
1415 );
1416 assert!(verify_webhook_signature("whsec_testsecret", BODY, &upper, None));
1417 }
1418
1419 #[test]
1420 fn whitespace_around_parts_is_trimmed() {
1421 let spaced = HEADER.replace(",", ", ");
1422 assert!(verify_webhook_signature("whsec_testsecret", BODY, &spaced, None));
1423 }
1424
1425 #[test]
1426 fn missing_v1_is_rejected() {
1427 assert!(!verify_webhook_signature(
1428 "whsec_testsecret",
1429 BODY,
1430 "t=1700000000",
1431 None
1432 ));
1433 }
1434
1435 #[test]
1436 fn stale_timestamp_fails_under_tolerance() {
1437 assert!(!verify_webhook_signature(
1438 "whsec_testsecret",
1439 BODY,
1440 HEADER,
1441 Some(300)
1442 ));
1443 }
1444
1445 #[test]
1446 fn extreme_timestamp_is_rejected_without_panicking() {
1447 let header = format!(
1452 "t={},v1=d64be69f786ce81f89cfc89f1bd78ddae1996475e6b916e5c3107ee3ce1cecde",
1453 i64::MIN
1454 );
1455 assert!(!verify_webhook_signature(
1456 "whsec_testsecret",
1457 BODY,
1458 &header,
1459 Some(300)
1460 ));
1461 }
1462}