Skip to main content

stateset_nsr_sdk/
lib.rs

1//! Stateset NSR Rust SDK
2//!
3//! ```rust,no_run
4//! use stateset_nsr_sdk::NSRClient;
5//!
6//! #[tokio::main(flavor = "current_thread")]
7//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
8//!     let client = NSRClient::new("nsr_api_key", "org_id");
9//!     let response = client.chat("I want to cancel my subscription").await?;
10//!     println!("Reply: {}", response.completion.reply);
11//!     for tc in response.ready_tool_calls() {
12//!         println!("Execute: {} (rule: {})", tc.function, tc.policy.rule_name);
13//!     }
14//!     Ok(())
15//! }
16//! ```
17
18mod types;
19
20pub use types::*;
21
22use reqwest::{Client, Method, StatusCode};
23use std::time::Duration;
24
25/// Error type for NSR API operations.
26#[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    /// `code` from the structured error envelope `{"code": ..., "message": ...}`,
42    /// when this is an [`NSRError::Api`] whose body has that shape.
43    pub fn api_code(&self) -> Option<String> {
44        self.envelope_field("code")
45    }
46
47    /// `message` from the structured error envelope, when present.
48    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
61/// Unique-per-call `Idempotency-Key` value (time + pid + counter — no extra
62/// deps). The server replays the cached response for a repeated key within
63/// 24h, so client retries never double-execute or double-bill a decision.
64fn 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
75/// Client for the Stateset NSR AI platform.
76///
77/// Includes automatic retries, rate limit handling, and full API coverage.
78pub 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
88/// Longest server-supplied `Retry-After` the client will honor.
89const RETRY_AFTER_CAP_SECS: f64 = 60.0;
90
91/// Ceiling for a single HTTP attempt; the effective per-attempt timeout is
92/// `min(PER_REQUEST_TIMEOUT, remaining overall-deadline budget)`.
93const PER_REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
94
95impl NSRClient {
96    /// Create a new client.
97    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    /// Use a custom base URL.
114    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    /// Set max retries.
120    pub fn with_max_retries(mut self, n: u32) -> Self {
121        self.max_retries = n;
122        self
123    }
124
125    /// Cap for a single retry backoff sleep (default 10s).
126    pub fn with_max_backoff(mut self, d: Duration) -> Self {
127        self.max_backoff = d;
128        self
129    }
130
131    /// Overall deadline for one logical call including all retries and
132    /// backoff sleeps (default 120s). The remaining budget is also applied
133    /// as each attempt's per-request timeout (capped at 60s), so the call
134    /// returns within the deadline even against a hung server. Once
135    /// exceeded, the last error (or [`NSRError::DeadlineExceeded`]) is
136    /// returned instead of trying again.
137    pub fn with_overall_deadline(mut self, d: Duration) -> Self {
138        self.overall_deadline = d;
139        self
140    }
141
142    /// Exponential backoff (500ms * 2^attempt) with jitter in the upper half
143    /// ("equal jitter"), capped at `max_backoff`.
144    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        // Cheap jitter source — no rand dependency needed for backoff spread.
148        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    /// True if we may still sleep `delay` and retry within the deadline.
162    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        // Every mutating request carries an Idempotency-Key so blind retries
186        // (5xx, transport failures) replay instead of re-executing. The key is
187        // generated ONCE per logical call, so it is stable across attempts;
188        // an explicitly supplied key wins.
189        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            // Bound each attempt by the REMAINING overall budget (capped at
200            // the 60s per-request ceiling), so a hung server cannot stretch
201            // the call to attempts × 60s past the deadline.
202            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            // Same extra headers on every attempt, so retries replay (not
217            // re-execute) mutations guarded by an Idempotency-Key.
218            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            // Transport errors (connect refused/reset, timeout) are retried
230            // within the same attempt budget — safe because of the key above.
231            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            // Rate limit
245            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            // Server error retry
262            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    // ── Chat ──────────────────────────────────────────────────────
316
317    /// Send a message through the NSR reasoning pipeline.
318    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    /// Chat with full options.
327    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    /// OpenAI-compatible completions.
348    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    /// Anthropic-compatible Messages endpoint (`POST /v1/messages`).
364    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    /// Verified Decision API (`POST /v1/decisions`).
382    ///
383    /// Returns an auditable decision (`approved | denied | refused`) with a
384    /// cited proof chain, confidence, optional refusal, the authorized action,
385    /// and per-decision usage. The engine refuses rather than guessing when it
386    /// cannot ground the answer. `facts`/`rules` are optional request-scoped
387    /// JSON arrays.
388    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    /// Batch Verified Decisions (`POST /v1/decisions/batch`).
421    ///
422    /// Scores many decision requests in one call. Each item is a JSON object
423    /// with the same fields as [`decide`](Self::decide)'s request (`query`
424    /// required; `mode` defaults server-side to `safe`). Items are metered
425    /// independently and a failing item is reported in place without aborting
426    /// the batch. Items past the server's time budget return per-item error
427    /// code `batch_deadline_exceeded` and are never evaluated or billed —
428    /// retry those in a smaller batch.
429    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    /// [`decide_batch`](Self::decide_batch) with a caller-pinned
438    /// `Idempotency-Key`. Pin the key (e.g. your job id) when you may retry
439    /// the whole batch call across process restarts — the server replays the
440    /// cached response instead of re-executing (and re-billing) completed
441    /// items.
442    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    /// Most recent decisions for the org, newest first
457    /// (`GET /v1/decisions/recent`). Ephemeral analytics — billing truth
458    /// lives in the metering pipeline.
459    pub async fn recent_decisions(&self, limit: usize) -> Result<RecentDecisionsResponse, NSRError> {
460        self.get(&format!("/v1/decisions/recent?limit={limit}")).await
461    }
462
463    /// Aggregate decision stats over a window (`GET /v1/decisions/stats`):
464    /// outcome counts, billable volume, latency percentiles, top rules.
465    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    /// Per-rule cited-vs-noise usage over a window
471    /// (`GET /v1/decisions/rule-stats`), most-noisy first — the demotion
472    /// signal for `demote_noisy`. Returns a JSON array.
473    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    /// The missing premises that blocked the most decisions over a window
479    /// (`GET /v1/decisions/refusal-gaps`), most-frequent first — the KB
480    /// coverage gaps to fill so those refusals become billable decisions.
481    /// Returns a JSON array.
482    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    /// Disable mined `flywheel:*` rules whose noise ratio exceeds threshold
488    /// over a minimum sample (`POST /api/v1/flywheel/demote-noisy`); curated
489    /// policy is flagged, never auto-disabled. Pass `{"dry_run": true}` to
490    /// preview without mutating.
491    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    /// Resolve a `decision_id` (from a decision response or an
496    /// `outcome.produced` webhook) to its analytics record
497    /// (`GET /v1/decisions/{id}`). The log is bounded and ephemeral — a 404
498    /// means "rotated out of the recent window".
499    pub async fn get_decision(&self, decision_id: &str) -> Result<DecisionRecord, NSRError> {
500        self.get(&format!("/v1/decisions/{decision_id}")).await
501    }
502
503    /// Live grounded-symbol seed pack metadata (`GET /api/v1/gss/seed`):
504    /// source (env override / cwd file / embedded), rule + symbol counts, and
505    /// the `grounded` flag — verify grounding is on instead of trusting
506    /// silence.
507    pub async fn gss_seed_info(&self) -> Result<serde_json::Value, NSRError> {
508        self.get("/api/v1/gss/seed").await
509    }
510
511    // ── Knowledge Base ────────────────────────────────────────────
512
513    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    /// List entities with pagination/sort (`GET /api/v1/entities?limit=...`).
539    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    /// Search entities by name/regex (`GET /api/v1/entities/search?q=...`).
548    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    /// List rules with pagination/sort (`GET /api/v1/rules?limit=...`).
583    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    /// Fetch one rule (`GET /api/v1/rules/:id`).
591    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    /// Partially update a rule (`PATCH /api/v1/rules/:id`).
596    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    /// Delete a rule (`DELETE /api/v1/rules/:id`).
606    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    /// Lint a rule without installing it (`POST /api/v1/rules/lint`).
611    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    /// Create many rules in one call (`POST /api/v1/rules/batch`).
617    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    /// Create many triples in one call (`POST /api/v1/triples/batch`).
646    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    /// Structured pattern query over the KB (`POST /api/v1/query`).
662    /// Use `?var` terms in patterns for variables.
663    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    /// Knowledge-graph analysis (`POST /api/v1/kb/graph`).
676    /// `analysis_type` is `"paths"`, `"centrality"`, or `"clusters"`.
677    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    // ── Proof verification ────────────────────────────────────────
694
695    /// Independently verify a self-contained proof bundle
696    /// (`POST /v1/proofs/verify`). Pass a decision's `verifiable_bundle`
697    /// VERBATIM. Always 200: an unsound proof is a valid answer
698    /// (`verified: false` + located reason), not an error.
699    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    // ── Auth & API-key management ─────────────────────────────────
707
708    /// Create an account + org (`POST /api/v1/auth/signup`). The response
709    /// carries the org's API key.
710    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    /// Log in (`POST /api/v1/auth/login`).
719    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    /// Introspect the current credentials (`GET /api/v1/auth/session`).
728    pub async fn auth_session(&self) -> Result<AuthSessionResponse, NSRError> {
729        self.get("/api/v1/auth/session").await
730    }
731
732    /// Mint a new API key (`POST /api/v1/auth/keys`). The plaintext `key` is
733    /// shown ONLY in this response.
734    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    /// List the org's API keys, secrets redacted (`GET /api/v1/auth/keys`).
743    pub async fn list_api_keys(&self) -> Result<ApiKeyListResponse, NSRError> {
744        self.get("/api/v1/auth/keys").await
745    }
746
747    /// Revoke an API key (`DELETE /api/v1/auth/keys/:id`).
748    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    // ── Async jobs ────────────────────────────────────────────────
753
754    /// List jobs (`GET /api/v1/jobs`), paginated. The jobs endpoint speaks
755    /// `limit`/`offset`/`sort_by`/`sort_order` (NOT the standard
756    /// [`ListParams`] cursor/`sort` dialect), so it takes [`JobListParams`].
757    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    /// Submit an async batch-inference job (`POST /api/v1/jobs/batch-infer`).
762    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    /// Poll a job (`GET /api/v1/jobs/:job_id`).
771    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    /// Cancel a running job (`POST /api/v1/jobs/:job_id/cancel`).
776    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    /// Delete a finished job record (`DELETE /api/v1/jobs/:job_id`).
782    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    // ── Beliefs ───────────────────────────────────────────────────
787
788    /// Add a belief (`POST /api/v1/beliefs`).
789    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    /// Fetch a belief (`GET /api/v1/beliefs/:proposition`).
803    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    /// Add supporting evidence (`POST /api/v1/beliefs/support`).
809    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    /// Add contradicting evidence (`POST /api/v1/beliefs/contradict`).
820    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    /// Refute a belief outright (`POST /api/v1/beliefs/refute/:proposition`).
845    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    /// Check two propositions for conflict (`POST /api/v1/beliefs/conflicts`).
854    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    /// Explain a belief's current state (`GET /api/v1/beliefs/:p/explain`).
867    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    /// Revision history of a belief (`GET /api/v1/beliefs/:p/history`).
873    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    // ── Constraints ───────────────────────────────────────────────
879
880    /// Create a constraint (`POST /api/v1/constraints`).
881    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    /// List constraints (`GET /api/v1/constraints`).
890    pub async fn list_constraints(&self) -> Result<ListConstraintsResponse, NSRError> {
891        self.get("/api/v1/constraints").await
892    }
893
894    /// Fetch one constraint (`GET /api/v1/constraints/:id`).
895    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    /// Delete a constraint (`DELETE /api/v1/constraints/:id`).
901    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    /// Validate NSR-L facts against the org's constraints
907    /// (`POST /api/v1/constraints/validate`).
908    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    // ── Policy ────────────────────────────────────────────────────
920
921    /// Pre-execution tool-call policy check (`POST /api/v1/policy/infer`).
922    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    /// Post-hoc response evaluation (`POST /api/v1/policy/evaluate`).
935    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    /// Train the policy machine (`POST /api/v1/policy/train`).
953    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    /// Initialize the policy vocabulary (`POST /api/v1/policy/vocab/init`).
961    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    // ── Metering & marketplace ────────────────────────────────────
969
970    /// Link an org to its billing entitlement
971    /// (`POST /v1/metering/entitlement`). `entitlement` names the billing
972    /// backend and the identifiers it reports against.
973    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    /// Fetch an org's entitlement (`GET /v1/metering/entitlement/:org_id`).
987    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    /// AWS Marketplace onboarding (`POST /v1/metering/aws/register`).
993    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    /// Azure Marketplace onboarding (`POST /v1/metering/azure/register`).
1002    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    /// GCP Marketplace Pub/Sub lifecycle event (`POST /v1/metering/gcp/pubsub`).
1011    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    // ── Machines ──────────────────────────────────────────────────
1019
1020    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    // ── Brand machine onboarding (seed → compile → evaluate → activate) ──
1041    // Thin JSON wrappers over the org-scoped machine-pack lifecycle; see
1042    // docs/BRAND_MACHINE_ONBOARDING.md for payload shapes.
1043
1044    /// Create a seed pack (`POST /api/v1/machines/seed`); carries `seed_id`.
1045    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    /// Compile a seed pack (`POST /api/v1/machines/compile`, body carries `seed_id`).
1053    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    /// Score a compiled spec before activation (`POST /api/v1/machines/evaluate-seed`).
1061    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    /// Activate a compiled spec as the org's live brand machine.
1069    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    // ── Webhooks (register, list, revoke, delivery log) ──────────────
1077
1078    /// Register an https endpoint for event deliveries
1079    /// (`POST /api/v1/webhooks`). The response's `signing_secret` is shown
1080    /// ONLY here — store it; use [`verify_webhook_signature`] on inbound
1081    /// deliveries.
1082    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    /// List the org's registered endpoints (secrets redacted).
1095    pub async fn list_webhooks(&self) -> Result<serde_json::Value, NSRError> {
1096        self.get("/api/v1/webhooks").await
1097    }
1098
1099    /// Revoke an endpoint (`DELETE /api/v1/webhooks/{id}`).
1100    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    /// Recent delivery attempts for an endpoint — status, attempt, latency.
1105    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    // ── Industry templates (one-call KB seeding) ─────────────────────
1115
1116    /// List available industry templates (`GET /api/v1/templates`).
1117    pub async fn list_templates(&self) -> Result<serde_json::Value, NSRError> {
1118        self.get("/api/v1/templates").await
1119    }
1120
1121    /// Fetch one template's entities/rules (`GET /api/v1/templates/{slug}`).
1122    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    /// Install a template into the org's KB
1127    /// (`POST /api/v1/templates/{slug}/apply`). `mode` is `additive`
1128    /// (default, skips existing names) or `replace`; fires the
1129    /// `template.applied` webhook.
1130    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    // ── Reasoning ─────────────────────────────────────────────────
1148
1149    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    // ── RAG ───────────────────────────────────────────────────────
1166
1167    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    // ── Sessions ──────────────────────────────────────────────────
1172
1173    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    // ── Flywheel ──────────────────────────────────────────────────
1186
1187    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    // ── NSR-L ─────────────────────────────────────────────────────
1200
1201    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    // ── Symbols & Features ────────────────────────────────────────
1214
1215    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    // ── Billing ───────────────────────────────────────────────────
1228
1229    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    // ── Agents ────────────────────────────────────────────────────
1254
1255    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    // ── Sandbox ───────────────────────────────────────────────────
1268
1269    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    // ── Health ────────────────────────────────────────────────────
1274
1275    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
1284/// Verify an NSR webhook delivery (`X-NSR-Signature` header).
1285///
1286/// Stripe-compatible scheme: the header carries
1287/// `t=<unix_seconds>,v1=<hex_hmac_sha256(secret, "{t}.{body}")>`.
1288/// Comparison is constant-time. `tolerance_secs` rejects replayed deliveries
1289/// older than the window (300 is a sensible handler default); pass `None` to
1290/// skip the timestamp check (e.g. when verifying stored payloads).
1291pub 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    // Parse `t=...,v1=...` parts. Multiple `v1=` values are legitimate
1301    // (secret rotation — any one matching verifies, Stripe-style), but more
1302    // than one `t=` is ambiguous/adversarial and is rejected outright.
1303    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        // `t` is attacker-controlled (from a forged webhook header); use
1330        // saturating subtraction so an extreme value can't overflow the
1331        // freshness check (a debug-build panic, or a release wrap past the
1332        // window). `unsigned_abs` is already total for `i64::MIN`.
1333        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    // Constant-time, case-insensitive hex comparison against EVERY candidate
1348    // signature — verification succeeds if any one matches.
1349    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        // Stripe-style rotation: multiple v1= signatures, one from the old
1391        // secret. Verification succeeds if ANY candidate matches.
1392        let header = format!("v1=deadbeef{},{}", "0".repeat(56), HEADER);
1393        assert!(verify_webhook_signature("whsec_testsecret", BODY, &header, None));
1394        // ...and order must not matter.
1395        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        // The `t=` value comes from the request header, so a forged webhook can
1448        // set it to anything. An extreme value must be rejected as stale, never
1449        // overflow the freshness subtraction (a debug-build panic in the
1450        // customer's handler, or a release wrap past the tolerance window).
1451        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}