Skip to main content

stateset_nsr_sdk/
types.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize)]
4pub struct ChatMessage {
5    pub role: String,
6    pub content: String,
7}
8
9#[derive(Debug, Clone, Deserialize)]
10pub struct ToolCallPolicy {
11    pub rule_name: String,
12    pub rule_conclusion: String,
13    pub confidence: f32,
14    pub reason: String,
15}
16
17#[derive(Debug, Clone, Deserialize)]
18pub struct ToolCall {
19    pub id: String,
20    pub function: String,
21    pub arguments: serde_json::Value,
22    pub policy: ToolCallPolicy,
23    pub status: String,
24}
25
26impl ToolCall {
27    pub fn is_ready(&self) -> bool {
28        self.status == "ready"
29    }
30}
31
32#[derive(Debug, Clone, Deserialize)]
33pub struct Category {
34    pub category: String,
35    pub score: f64,
36    #[serde(default)]
37    pub domain: String,
38    #[serde(default)]
39    pub intent: String,
40}
41
42#[derive(Debug, Clone, Deserialize)]
43pub struct SymbolicAnalysis {
44    pub categories: Vec<Category>,
45    pub confidence: f64,
46    #[serde(default)]
47    pub domains: Vec<String>,
48    #[serde(default)]
49    pub intents: Vec<String>,
50    #[serde(default)]
51    pub escalation_triggered: bool,
52    #[serde(default)]
53    pub safety_gate_triggered: bool,
54    #[serde(default)]
55    pub matching_rule_count: u32,
56}
57
58#[derive(Debug, Clone, Deserialize)]
59pub struct UncertaintyEstimate {
60    pub epistemic: f64,
61    pub aleatoric: f64,
62    pub total: f64,
63    pub calibration_score: f64,
64}
65
66#[derive(Debug, Clone, Deserialize)]
67pub struct AdvancedReasoning {
68    #[serde(default)]
69    pub enabled_features: Vec<String>,
70    pub recommended_strategy: Option<String>,
71    pub machine_confidence: Option<f64>,
72    #[serde(default)]
73    pub inferred_symbols: Vec<String>,
74    pub explanation_summary: Option<String>,
75    pub uncertainty: Option<UncertaintyEstimate>,
76    pub thought_count: Option<u32>,
77}
78
79#[derive(Debug, Clone, Deserialize)]
80pub struct GroundingSnapshot {
81    #[serde(default)]
82    pub org_id: String,
83    #[serde(default)]
84    pub strategy: String,
85    #[serde(default)]
86    pub strategy_reason: String,
87    #[serde(default)]
88    pub kb_entity_count: u32,
89    #[serde(default)]
90    pub kb_rule_count: u32,
91    #[serde(default)]
92    pub seed_rule_count: u32,
93    pub advanced_reasoning: Option<AdvancedReasoning>,
94}
95
96#[derive(Debug, Clone, Deserialize)]
97pub struct KBRuleEvidence {
98    #[serde(default)]
99    pub name: String,
100    #[serde(default)]
101    pub conclusion: String,
102    #[serde(default)]
103    pub confidence: f32,
104    #[serde(default)]
105    pub score: f64,
106}
107
108#[derive(Debug, Clone, Deserialize)]
109pub struct KBEntityEvidence {
110    #[serde(default)]
111    pub name: String,
112    #[serde(default)]
113    pub entity_type: String,
114    #[serde(default)]
115    pub score: f64,
116}
117
118#[derive(Debug, Clone, Deserialize)]
119pub struct GroundingEvidence {
120    #[serde(default)]
121    pub kb_rules: Vec<KBRuleEvidence>,
122    #[serde(default)]
123    pub kb_entities: Vec<KBEntityEvidence>,
124    #[serde(default)]
125    pub kb_facts: Vec<serde_json::Value>,
126    #[serde(default)]
127    pub seed_rules: Vec<serde_json::Value>,
128}
129
130#[derive(Debug, Clone, Deserialize)]
131pub struct CompletionGeneration {
132    #[serde(default)]
133    pub mode: String,
134    pub model: Option<String>,
135}
136
137#[derive(Debug, Clone, Deserialize)]
138pub struct ChatCompletion {
139    pub reply: String,
140    #[serde(default)]
141    pub summary: String,
142    pub clarifying_question: Option<String>,
143    #[serde(default)]
144    pub grounded: bool,
145    #[serde(default)]
146    pub needs_human_review: bool,
147    #[serde(default)]
148    pub tool_calls: Vec<ToolCall>,
149    pub grounding: GroundingSnapshot,
150    pub evidence: GroundingEvidence,
151    pub generation: CompletionGeneration,
152}
153
154impl ChatCompletion {
155    /// Get only the ready-to-execute tool calls.
156    pub fn ready_tool_calls(&self) -> Vec<&ToolCall> {
157        self.tool_calls.iter().filter(|tc| tc.is_ready()).collect()
158    }
159}
160
161#[derive(Debug, Clone, Deserialize)]
162pub struct ChatResponse {
163    pub session_id: Option<String>,
164    pub analysis: SymbolicAnalysis,
165    pub completion: ChatCompletion,
166    #[serde(default)]
167    pub messages: Vec<ChatMessage>,
168}
169
170impl ChatResponse {
171    pub fn reply(&self) -> &str {
172        &self.completion.reply
173    }
174
175    pub fn top_category(&self) -> Option<&str> {
176        self.analysis
177            .categories
178            .first()
179            .map(|c| c.category.as_str())
180    }
181
182    pub fn confidence(&self) -> f64 {
183        self.analysis.confidence
184    }
185
186    pub fn ready_tool_calls(&self) -> Vec<&ToolCall> {
187        self.completion.ready_tool_calls()
188    }
189}
190
191#[derive(Debug, Clone, Deserialize)]
192pub struct Entity {
193    pub id: String,
194    pub name: String,
195    pub entity_type: String,
196    #[serde(default)]
197    pub properties: serde_json::Value,
198    #[serde(default = "default_confidence")]
199    pub confidence: f32,
200}
201
202fn default_confidence() -> f32 {
203    1.0
204}
205
206#[derive(Debug, Clone, Deserialize)]
207pub struct Rule {
208    pub id: String,
209    pub name: String,
210    #[serde(default)]
211    pub status: String,
212}
213
214#[derive(Debug, Clone, Deserialize)]
215pub struct KBStats {
216    pub entity_count: u64,
217    pub triple_count: u64,
218    pub rule_count: u64,
219}
220
221#[derive(Debug, Clone, Deserialize)]
222pub struct MachineStatus {
223    pub status: String,
224    #[serde(default)]
225    pub vocabulary_size: u32,
226    #[serde(default)]
227    pub programs_learned: u32,
228    #[serde(default)]
229    pub training_examples: u32,
230    #[serde(default)]
231    pub successful_inferences: u32,
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct TrainingExample {
236    pub input: String,
237    pub expected_category: String,
238}
239
240/// Minimal RFC 3986 percent-encoding for query-string values.
241pub(crate) fn urlencode(v: &str) -> String {
242    let mut out = String::with_capacity(v.len());
243    for b in v.bytes() {
244        match b {
245            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
246                out.push(b as char)
247            }
248            _ => out.push_str(&format!("%{b:02X}")),
249        }
250    }
251    out
252}
253
254// ── Pagination ───────────────────────────────────────────────────────
255
256/// Standard pagination/sorting query parameters for list endpoints
257/// (see the server's `pagination` module: limit/offset or cursor, plus
258/// `sort` with an optional `-` descending prefix).
259///
260/// Applies to the entity and rule listings
261/// ([`list_entities_with`](crate::NSRClient::list_entities_with),
262/// [`list_rules_with`](crate::NSRClient::list_rules_with)). The jobs listing
263/// speaks a different dialect — use [`JobListParams`] with
264/// [`list_jobs`](crate::NSRClient::list_jobs) instead.
265#[derive(Debug, Clone, Default, Serialize)]
266pub struct ListParams {
267    /// Maximum items to return (server default 50, capped at 1000).
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub limit: Option<usize>,
270    /// Items to skip (offset-based pagination).
271    #[serde(skip_serializing_if = "Option::is_none")]
272    pub offset: Option<usize>,
273    /// Opaque cursor from a previous page's `pagination.next_cursor`.
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub cursor: Option<String>,
276    /// Sort field, `-` prefix for descending (e.g. `-created_at`).
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub sort: Option<String>,
279}
280
281impl ListParams {
282    pub fn new() -> Self {
283        Self::default()
284    }
285    pub fn limit(mut self, limit: usize) -> Self {
286        self.limit = Some(limit);
287        self
288    }
289    pub fn offset(mut self, offset: usize) -> Self {
290        self.offset = Some(offset);
291        self
292    }
293    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
294        self.cursor = Some(cursor.into());
295        self
296    }
297    pub fn sort(mut self, sort: impl Into<String>) -> Self {
298        self.sort = Some(sort.into());
299        self
300    }
301
302    /// Render as a URL query string (`?limit=20&offset=40`), or `""` when
303    /// every field is unset. Cursor and sort values are percent-encoded.
304    pub fn to_query(&self) -> String {
305        let mut parts: Vec<String> = Vec::new();
306        if let Some(l) = self.limit {
307            parts.push(format!("limit={l}"));
308        }
309        if let Some(o) = self.offset {
310            parts.push(format!("offset={o}"));
311        }
312        if let Some(c) = &self.cursor {
313            parts.push(format!("cursor={}", urlencode(c)));
314        }
315        if let Some(s) = &self.sort {
316            parts.push(format!("sort={}", urlencode(s)));
317        }
318        if parts.is_empty() {
319            String::new()
320        } else {
321            format!("?{}", parts.join("&"))
322        }
323    }
324}
325
326/// Query parameters for `GET /api/v1/jobs`, which does NOT speak the
327/// standard `ListParams` dialect: it accepts `limit`/`offset` plus
328/// `sort_by` (`created_at` | `updated_at`) and `sort_order` (`asc` |
329/// `desc`) — no cursor, no `-`-prefixed `sort`.
330#[derive(Debug, Clone, Default, Serialize)]
331pub struct JobListParams {
332    /// Maximum jobs to return (server default 100, capped at the server's
333    /// max page size).
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub limit: Option<usize>,
336    /// Jobs to skip (offset-based pagination).
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub offset: Option<usize>,
339    /// Sort field: `created_at` (default) or `updated_at`.
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub sort_by: Option<String>,
342    /// Sort order: `desc` (default) or `asc`.
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub sort_order: Option<String>,
345}
346
347impl JobListParams {
348    pub fn new() -> Self {
349        Self::default()
350    }
351    pub fn limit(mut self, limit: usize) -> Self {
352        self.limit = Some(limit);
353        self
354    }
355    pub fn offset(mut self, offset: usize) -> Self {
356        self.offset = Some(offset);
357        self
358    }
359    /// `created_at` or `updated_at`.
360    pub fn sort_by(mut self, field: impl Into<String>) -> Self {
361        self.sort_by = Some(field.into());
362        self
363    }
364    /// `asc` or `desc`.
365    pub fn sort_order(mut self, order: impl Into<String>) -> Self {
366        self.sort_order = Some(order.into());
367        self
368    }
369
370    /// Render as a URL query string, or `""` when every field is unset.
371    pub fn to_query(&self) -> String {
372        let mut parts: Vec<String> = Vec::new();
373        if let Some(l) = self.limit {
374            parts.push(format!("limit={l}"));
375        }
376        if let Some(o) = self.offset {
377            parts.push(format!("offset={o}"));
378        }
379        if let Some(s) = &self.sort_by {
380            parts.push(format!("sort_by={}", urlencode(s)));
381        }
382        if let Some(s) = &self.sort_order {
383            parts.push(format!("sort_order={}", urlencode(s)));
384        }
385        if parts.is_empty() {
386            String::new()
387        } else {
388            format!("?{}", parts.join("&"))
389        }
390    }
391}
392
393// ── Verified decisions (`/v1/decisions*`) ────────────────────────────
394//
395// Typed mirrors of the server's `DecisionResponse` family. Open-ended or
396// fast-moving sub-objects (`grounding`, `gss_machine`, `trace`,
397// `verifiable_bundle`, derivation internals) stay `serde_json::Value`, and
398// almost every field is `#[serde(default)]`, so new server fields never break
399// deserialization (forward-compatible by construction).
400
401/// One verified decision (`POST /v1/decisions`): `approved | denied |
402/// refused`, with a cited proof chain and per-decision usage.
403#[derive(Debug, Clone, Deserialize)]
404pub struct DecisionResponse {
405    #[serde(default)]
406    pub decision_id: String,
407    /// `approved` | `denied` | `refused`.
408    pub decision: String,
409    /// Exact predicate evaluated as the permit target (absent on the legacy
410    /// action/query-inference path).
411    #[serde(default)]
412    pub evaluated_goal: Option<String>,
413    #[serde(default)]
414    pub confidence: f64,
415    #[serde(default)]
416    pub rationale: String,
417    /// Deterministic, proof-derived, business-readable "why".
418    #[serde(default)]
419    pub plain_explanation: String,
420    #[serde(default)]
421    pub proof: DecisionProof,
422    /// Present only when `decision == "refused"`.
423    #[serde(default)]
424    pub refusal: Option<DecisionRefusal>,
425    /// The authorized action + its policy justification, when an action was
426    /// in play.
427    #[serde(default)]
428    pub action: Option<DecisionAction>,
429    #[serde(default)]
430    pub grounding: serde_json::Value,
431    #[serde(default)]
432    pub gss_machine: serde_json::Value,
433    #[serde(default)]
434    pub usage: DecisionUsage,
435    /// Non-fatal advisories about how the verdict was derived.
436    #[serde(default)]
437    pub warnings: Vec<String>,
438    /// Org rules that fired during hydration but were dropped from
439    /// `proof.cited_rules` as unrelated to this decision.
440    #[serde(default)]
441    pub dropped_citations: Vec<String>,
442    /// Full proof trace, when `include_trace` was set.
443    #[serde(default)]
444    pub trace: Option<serde_json::Value>,
445    /// Raw recursive engine payload, when `include_trace` was set.
446    #[serde(default)]
447    pub x_nsr: Option<serde_json::Value>,
448    /// Self-contained, independently-verifiable proof bundle — POST it
449    /// VERBATIM to [`verify_proof`](crate::NSRClient::verify_proof).
450    #[serde(default)]
451    pub verifiable_bundle: Option<serde_json::Value>,
452}
453
454#[derive(Debug, Clone, Default, Deserialize)]
455pub struct DecisionProof {
456    /// Org rules cited in the derivation (the audit trail).
457    #[serde(default)]
458    pub cited_rules: Vec<String>,
459    #[serde(default)]
460    pub symbolic_steps: usize,
461    #[serde(default)]
462    pub neural_steps: usize,
463    #[serde(default)]
464    pub planner_steps: usize,
465    /// 0–1 proof strength from the engine's validation pass.
466    #[serde(default)]
467    pub proof_score: f64,
468    #[serde(default)]
469    pub proof_status: String,
470    /// Step-by-step replay of the cited derivation, when available.
471    #[serde(default)]
472    pub derivation: Option<serde_json::Value>,
473    /// `sha256:<hex>` over the canonicalized request-scoped policy inputs.
474    #[serde(default)]
475    pub request_policy_hash: Option<String>,
476}
477
478#[derive(Debug, Clone, Deserialize)]
479pub struct DecisionRefusal {
480    #[serde(default)]
481    pub reason: String,
482    #[serde(default)]
483    pub requires_human_review: bool,
484    /// Request-scoped premises that would unblock an authorization proof
485    /// (each carries `predicate`, `args`, `needed_by_rule`, `question`, and
486    /// an optional `resolves_with` retry fact). Empty for safety-gated
487    /// refusals.
488    #[serde(default)]
489    pub missing_facts: Vec<serde_json::Value>,
490}
491
492/// The authorized action + its policy justification.
493#[derive(Debug, Clone, Deserialize)]
494pub struct DecisionAction {
495    #[serde(default)]
496    pub name: String,
497    #[serde(default)]
498    pub ready: bool,
499    #[serde(default)]
500    pub rule_name: String,
501    #[serde(default)]
502    pub rule_conclusion: String,
503    #[serde(default)]
504    pub confidence: f32,
505    #[serde(default)]
506    pub reason: String,
507}
508
509/// Per-decision metering.
510#[derive(Debug, Clone, Default, Deserialize)]
511pub struct DecisionUsage {
512    #[serde(default)]
513    pub billable: bool,
514    #[serde(default)]
515    pub outcome_cost_microdollars: u64,
516    #[serde(default)]
517    pub billing_tier: String,
518    #[serde(default)]
519    pub elapsed_ms: u64,
520    #[serde(default)]
521    pub iterations: usize,
522    #[serde(default)]
523    pub max_depth_reached: usize,
524}
525
526/// `POST /v1/decisions/batch` response.
527#[derive(Debug, Clone, Deserialize)]
528pub struct BatchDecisionResponse {
529    #[serde(default)]
530    pub results: Vec<BatchDecisionItem>,
531    #[serde(default)]
532    pub summary: BatchSummary,
533}
534
535#[derive(Debug, Clone, Deserialize)]
536pub struct BatchDecisionItem {
537    #[serde(default)]
538    pub index: usize,
539    /// Present when this item succeeded.
540    #[serde(default)]
541    pub decision: Option<DecisionResponse>,
542    /// Present instead of `decision` when this item failed (e.g. quota
543    /// exhausted, `batch_deadline_exceeded`). Other items still proceed.
544    #[serde(default)]
545    pub error: Option<BatchItemError>,
546}
547
548#[derive(Debug, Clone, Deserialize)]
549pub struct BatchItemError {
550    #[serde(default)]
551    pub code: String,
552    #[serde(default)]
553    pub message: String,
554}
555
556#[derive(Debug, Clone, Default, Deserialize)]
557pub struct BatchSummary {
558    #[serde(default)]
559    pub total: usize,
560    #[serde(default)]
561    pub approved: usize,
562    #[serde(default)]
563    pub denied: usize,
564    #[serde(default)]
565    pub refused: usize,
566    #[serde(default)]
567    pub errored: usize,
568    /// Items that consumed a billable outcome.
569    #[serde(default)]
570    pub billable_decisions: usize,
571    /// Aggregate charge for the batch, in microdollars.
572    #[serde(default)]
573    pub total_cost_micros: u64,
574}
575
576/// One row of the ephemeral decision analytics log
577/// (`GET /v1/decisions/recent`, `GET /v1/decisions/{id}`).
578#[derive(Debug, Clone, Deserialize)]
579pub struct DecisionRecord {
580    #[serde(default)]
581    pub decision_id: String,
582    /// RFC 3339 timestamp.
583    #[serde(default)]
584    pub timestamp: String,
585    /// `approved` | `denied` | `refused`.
586    #[serde(default)]
587    pub decision: String,
588    /// The decision query, truncated server-side to 200 chars.
589    #[serde(default)]
590    pub query: String,
591    #[serde(default)]
592    pub latency_ms: u64,
593    #[serde(default)]
594    pub billable: bool,
595    #[serde(default)]
596    pub cost_micros: u64,
597    #[serde(default)]
598    pub cited_rules: Vec<String>,
599    #[serde(default)]
600    pub dropped_citations: Vec<String>,
601    #[serde(default)]
602    pub request_policy_hash: Option<String>,
603    /// Deduped predicate names from a refusal's `missing_facts`.
604    #[serde(default)]
605    pub missing_predicates: Vec<String>,
606    /// True when the decision came through `/v1/decisions/batch`.
607    #[serde(default)]
608    pub batch: bool,
609    #[serde(default)]
610    pub confidence: f64,
611    /// Real-world outcome recorded after the fact
612    /// (`honored | reversed | overridden | escalated`); `None` until reported.
613    #[serde(default)]
614    pub outcome: Option<String>,
615    /// Client-supplied correlation key, when one was given.
616    #[serde(default)]
617    pub external_ref: Option<String>,
618    /// Reproducible request inputs, when captured.
619    #[serde(default)]
620    pub request: Option<serde_json::Value>,
621}
622
623/// A page of recent decision analytics rows (`GET /v1/decisions/recent`).
624#[derive(Debug, Clone, Deserialize)]
625pub struct RecentDecisionsResponse {
626    #[serde(default)]
627    pub records: Vec<DecisionRecord>,
628    /// The effective limit applied to this page.
629    #[serde(default)]
630    pub limit: usize,
631    /// The offset this page started at.
632    #[serde(default)]
633    pub offset: usize,
634    /// True when more records exist beyond this page.
635    #[serde(default)]
636    pub has_more: bool,
637}
638
639// ── Billing usage (`GET /api/v1/billing/usage`) ──────────────────────
640
641#[derive(Debug, Clone, Deserialize)]
642pub struct UsageResponse {
643    #[serde(default)]
644    pub api_requests_month: u64,
645    #[serde(default)]
646    pub inference_requests_month: u64,
647    #[serde(default)]
648    pub entities: usize,
649    #[serde(default)]
650    pub triples: usize,
651    #[serde(default)]
652    pub rules: usize,
653    #[serde(default)]
654    pub storage_bytes: u64,
655    #[serde(default)]
656    pub tier: String,
657    /// Tier limits (`max_entities`, `max_triples`, `max_rules`,
658    /// `max_requests_per_minute`).
659    #[serde(default)]
660    pub limits: serde_json::Value,
661    #[serde(default)]
662    pub outcomes: OutcomeUsage,
663    /// Recursive runtime usage metrics.
664    #[serde(default)]
665    pub recursive: serde_json::Value,
666    #[serde(default)]
667    pub account: UsageAccount,
668}
669
670/// Outcome-based billing metrics.
671#[derive(Debug, Clone, Default, Deserialize)]
672pub struct OutcomeUsage {
673    /// Total resolved outcomes this month.
674    #[serde(default)]
675    pub outcomes_month: u64,
676    /// Outcomes included in the tier (no extra charge).
677    #[serde(default)]
678    pub outcomes_included: u64,
679    /// Billable outcomes (beyond included quota).
680    #[serde(default)]
681    pub outcomes_billable: u64,
682    /// Price per billable outcome in dollars.
683    #[serde(default)]
684    pub price_per_outcome: f64,
685    /// Total outcome charges this month in dollars.
686    #[serde(default)]
687    pub outcome_charges: f64,
688    /// Base platform fee in dollars.
689    #[serde(default)]
690    pub base_fee: f64,
691    /// Total estimated bill (base + outcome charges) in dollars.
692    #[serde(default)]
693    pub estimated_total: f64,
694}
695
696/// Tenant account posture for outcome production and prepaid runway.
697#[derive(Debug, Clone, Default, Deserialize)]
698pub struct UsageAccount {
699    #[serde(default)]
700    pub status: String,
701    /// Whether the tenant can currently produce another billable outcome.
702    #[serde(default)]
703    pub can_produce_outcome: bool,
704    /// Included outcomes remaining before billable overage starts.
705    #[serde(default)]
706    pub included_outcomes_remaining: u64,
707    /// Trial credits remaining in cents.
708    #[serde(default)]
709    pub trial_credits_remaining_cents: i64,
710    /// Prepaid (purchased) credits remaining in cents. Never expire.
711    #[serde(default)]
712    pub prepaid_credits_remaining_cents: i64,
713}
714
715// ── Proof verification ───────────────────────────────────────────────
716
717/// Verdict from `POST /v1/proofs/verify` — always 200; an unsound proof is a
718/// valid answer (`verified: false` plus the located reason), not an error.
719#[derive(Debug, Clone, Deserialize)]
720pub struct ProofVerifyResponse {
721    pub verified: bool,
722    #[serde(default)]
723    pub reason: Option<String>,
724    #[serde(default)]
725    pub failed_step: Option<usize>,
726}
727
728// ── API-key management (`/api/v1/auth/*`) ────────────────────────────
729
730#[derive(Debug, Clone, Default, Serialize)]
731pub struct ApiKeyCreateRequest {
732    pub name: String,
733    #[serde(skip_serializing_if = "Option::is_none")]
734    pub org_id: Option<String>,
735    #[serde(skip_serializing_if = "Option::is_none")]
736    pub scopes: Option<Vec<String>>,
737    #[serde(skip_serializing_if = "Option::is_none")]
738    pub rate_limit_per_minute: Option<u32>,
739}
740
741/// The plaintext `key` is shown ONLY in this creation response — store it.
742#[derive(Debug, Clone, Deserialize)]
743pub struct ApiKeyCreateResponse {
744    pub id: String,
745    pub name: String,
746    pub org_id: String,
747    #[serde(default)]
748    pub scopes: Vec<String>,
749    #[serde(default)]
750    pub rate_limit_per_minute: Option<u32>,
751    pub key: String,
752    pub prefix: String,
753    pub created_at: String,
754    #[serde(default)]
755    pub expires_at: Option<String>,
756}
757
758#[derive(Debug, Clone, Deserialize)]
759pub struct ApiKeyListItem {
760    pub id: String,
761    pub name: String,
762    pub org_id: String,
763    #[serde(default)]
764    pub scopes: Vec<String>,
765    #[serde(default)]
766    pub rate_limit_per_minute: Option<u32>,
767    pub prefix: String,
768    pub created_at: String,
769    #[serde(default)]
770    pub expires_at: Option<String>,
771    #[serde(default)]
772    pub revoked_at: Option<String>,
773    #[serde(default)]
774    pub last_used_at: Option<String>,
775}
776
777#[derive(Debug, Clone, Deserialize)]
778pub struct ApiKeyListResponse {
779    pub keys: Vec<ApiKeyListItem>,
780    pub total: usize,
781}
782
783#[derive(Debug, Clone, Deserialize)]
784pub struct ApiKeyRevokeResponse {
785    pub id: String,
786    pub revoked_at: String,
787}
788
789/// `POST /api/v1/auth/signup` and `/login` response — carries the org's API key.
790#[derive(Debug, Clone, Deserialize)]
791pub struct AuthResponse {
792    pub user_id: String,
793    pub email: String,
794    pub org_id: String,
795    pub api_key: String,
796    pub api_key_prefix: String,
797    pub api_key_created_at: String,
798}
799
800#[derive(Debug, Clone, Deserialize)]
801pub struct AuthSessionResponse {
802    pub auth_type: String,
803    #[serde(default)]
804    pub org_id: Option<String>,
805    #[serde(default)]
806    pub scopes: Vec<String>,
807    #[serde(default)]
808    pub rate_limit_per_minute: Option<u32>,
809    #[serde(default)]
810    pub user_id: Option<String>,
811    #[serde(default)]
812    pub email: Option<String>,
813    #[serde(default)]
814    pub name: Option<String>,
815}
816
817// ── Rules ────────────────────────────────────────────────────────────
818
819/// One body atom of a rule.
820#[derive(Debug, Clone, Serialize, Deserialize)]
821pub struct RuleAtom {
822    pub predicate: String,
823    pub args: Vec<String>,
824    #[serde(skip_serializing_if = "Option::is_none")]
825    pub negated: Option<bool>,
826}
827
828/// A rule specification, as accepted by create/lint/batch rule endpoints.
829#[derive(Debug, Clone, Serialize)]
830pub struct RuleSpec {
831    pub name: String,
832    pub head_predicate: String,
833    pub head_args: Vec<String>,
834    pub body: Vec<RuleAtom>,
835    pub confidence: f32,
836}
837
838/// `PATCH /api/v1/rules/:id` — only the provided fields are changed.
839#[derive(Debug, Clone, Default, Serialize)]
840pub struct RuleUpdate {
841    #[serde(skip_serializing_if = "Option::is_none")]
842    pub description: Option<String>,
843    #[serde(skip_serializing_if = "Option::is_none")]
844    pub enabled: Option<bool>,
845    #[serde(skip_serializing_if = "Option::is_none")]
846    pub priority: Option<i32>,
847    #[serde(skip_serializing_if = "Option::is_none")]
848    pub confidence: Option<f32>,
849}
850
851/// `POST /api/v1/rules/lint` — diagnostics only; the rule is NOT installed.
852#[derive(Debug, Clone, Deserialize)]
853pub struct RuleLintResponse {
854    #[serde(default)]
855    pub diagnostics: Vec<serde_json::Value>,
856    #[serde(default)]
857    pub has_errors: bool,
858}
859
860#[derive(Debug, Clone, Deserialize)]
861pub struct BatchCreateRulesResponse {
862    pub created: usize,
863    pub failed: usize,
864    #[serde(default)]
865    pub rules: Vec<serde_json::Value>,
866    #[serde(default)]
867    pub errors: Vec<String>,
868}
869
870// ── Triples ──────────────────────────────────────────────────────────
871
872#[derive(Debug, Clone, Serialize)]
873pub struct TripleSpec {
874    pub subject_id: String,
875    pub predicate: String,
876    pub object_id: String,
877    pub confidence: f32,
878}
879
880#[derive(Debug, Clone, Deserialize)]
881pub struct BatchCreateTriplesResponse {
882    pub created: usize,
883    pub failed: usize,
884    #[serde(default)]
885    pub triples: Vec<serde_json::Value>,
886    #[serde(default)]
887    pub errors: Vec<String>,
888}
889
890// ── KB query & graph analysis ────────────────────────────────────────
891
892/// One triple pattern for `POST /api/v1/query`; use `?var` for variables.
893#[derive(Debug, Clone, Serialize)]
894pub struct TriplePattern {
895    pub subject: String,
896    pub predicate: String,
897    pub object: String,
898}
899
900#[derive(Debug, Clone, Deserialize)]
901pub struct QueryResponse {
902    #[serde(default)]
903    pub bindings: Vec<std::collections::HashMap<String, serde_json::Value>>,
904    #[serde(default)]
905    pub total_count: usize,
906    #[serde(default)]
907    pub execution_time_ms: u64,
908}
909
910#[derive(Debug, Clone, Deserialize)]
911pub struct GraphAnalysisResponse {
912    pub analysis_type: String,
913    #[serde(default)]
914    pub results: serde_json::Value,
915    #[serde(default)]
916    pub metadata: serde_json::Value,
917}
918
919// ── Async jobs (`/api/v1/jobs*`) ─────────────────────────────────────
920
921#[derive(Debug, Clone, Serialize)]
922pub struct BatchInferRequest {
923    pub inputs: Vec<String>,
924    #[serde(skip_serializing_if = "Option::is_none")]
925    pub max_depth: Option<usize>,
926    #[serde(skip_serializing_if = "Option::is_none")]
927    pub include_explanation: Option<bool>,
928}
929
930#[derive(Debug, Clone, Deserialize)]
931pub struct JobSubmitResponse {
932    pub job_id: String,
933    pub status: String,
934    #[serde(default)]
935    pub total_items: usize,
936}
937
938#[derive(Debug, Clone, Deserialize)]
939pub struct JobStatusResponse {
940    pub job: serde_json::Value,
941}
942
943#[derive(Debug, Clone, Deserialize)]
944pub struct ListJobsResponse {
945    #[serde(default)]
946    pub jobs: Vec<serde_json::Value>,
947    #[serde(default)]
948    pub total: usize,
949    #[serde(default)]
950    pub count: usize,
951    #[serde(default)]
952    pub offset: usize,
953    #[serde(default)]
954    pub limit: usize,
955}
956
957#[derive(Debug, Clone, Deserialize)]
958pub struct CancelJobResponse {
959    pub job_id: String,
960    #[serde(default)]
961    pub cancelled: bool,
962    #[serde(default)]
963    pub status: Option<String>,
964}
965
966// ── Beliefs (`/api/v1/beliefs*`) ─────────────────────────────────────
967
968#[derive(Debug, Clone, Deserialize)]
969pub struct BeliefResponse {
970    pub proposition: String,
971    pub confidence: f32,
972    #[serde(default)]
973    pub belief_interval: (f32, f32),
974    #[serde(default)]
975    pub uncertainty: f32,
976    #[serde(default)]
977    pub is_certain: bool,
978    #[serde(default)]
979    pub is_rejected: bool,
980}
981
982#[derive(Debug, Clone, Deserialize)]
983pub struct ModifyBeliefResponse {
984    pub proposition: String,
985    pub previous_confidence: f32,
986    pub new_confidence: f32,
987    #[serde(default)]
988    pub change: f32,
989}
990
991#[derive(Debug, Clone, Deserialize)]
992pub struct BeliefConflictsResponse {
993    pub prop1: String,
994    pub prop2: String,
995    pub conflicts: bool,
996    #[serde(default)]
997    pub explanation: String,
998}
999
1000// ── Constraints (`/api/v1/constraints*`) ─────────────────────────────
1001
1002/// Constraint strength: `hard`, `soft { tolerance }`, or `weighted { weight }`.
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1004#[serde(tag = "type", rename_all = "lowercase")]
1005pub enum ConstraintStrength {
1006    Hard,
1007    Soft { tolerance: f32 },
1008    Weighted { weight: f32 },
1009}
1010
1011#[derive(Debug, Clone, Serialize)]
1012pub struct ConstraintSpec {
1013    pub id: String,
1014    pub description: String,
1015    pub strength: ConstraintStrength,
1016    /// Logical expression in NSR-L syntax.
1017    pub expression: String,
1018    #[serde(skip_serializing_if = "Option::is_none")]
1019    pub source: Option<String>,
1020}
1021
1022#[derive(Debug, Clone, Deserialize)]
1023pub struct ConstraintResponse {
1024    pub id: String,
1025    pub description: String,
1026    pub strength: ConstraintStrength,
1027    pub expression: String,
1028    #[serde(default)]
1029    pub source: String,
1030}
1031
1032#[derive(Debug, Clone, Deserialize)]
1033pub struct ListConstraintsResponse {
1034    #[serde(default)]
1035    pub constraints: Vec<ConstraintResponse>,
1036    #[serde(default)]
1037    pub total: usize,
1038    #[serde(default)]
1039    pub hard_count: usize,
1040    #[serde(default)]
1041    pub soft_count: usize,
1042}
1043
1044#[derive(Debug, Clone, Deserialize)]
1045pub struct ConstraintViolationResponse {
1046    pub constraint_id: String,
1047    pub satisfied: bool,
1048    pub is_hard: bool,
1049    #[serde(default)]
1050    pub confidence_penalty: f32,
1051    #[serde(default)]
1052    pub explanation: String,
1053}
1054
1055#[derive(Debug, Clone, Deserialize)]
1056pub struct ValidateConstraintsResponse {
1057    pub valid: bool,
1058    #[serde(default)]
1059    pub has_refutation: bool,
1060    #[serde(default)]
1061    pub hard_violations: usize,
1062    #[serde(default)]
1063    pub soft_violations: usize,
1064    #[serde(default)]
1065    pub total_penalty: f32,
1066    #[serde(default)]
1067    pub violations: Vec<ConstraintViolationResponse>,
1068}
1069
1070// ── Policy (`/api/v1/policy/*`) ──────────────────────────────────────
1071
1072#[derive(Debug, Clone, Deserialize)]
1073pub struct PolicyInferResponse {
1074    pub decision: String,
1075    pub confidence: f64,
1076    #[serde(default)]
1077    pub proof_trace: Vec<serde_json::Value>,
1078    #[serde(default)]
1079    pub processing_time_ms: u64,
1080}
1081
1082#[derive(Debug, Clone, Deserialize)]
1083pub struct PolicyEvaluateResponse {
1084    pub decision: String,
1085    #[serde(default)]
1086    pub rule_decision: String,
1087    #[serde(default)]
1088    pub machine_decision: String,
1089    pub confidence: f64,
1090    #[serde(default)]
1091    pub policy_score: i32,
1092    #[serde(default)]
1093    pub triggered_signals: Vec<String>,
1094    #[serde(default)]
1095    pub proof_trace: Vec<serde_json::Value>,
1096    #[serde(default)]
1097    pub processing_time_ms: u64,
1098}
1099
1100// ── Metering & marketplace (`/v1/metering/*`) ────────────────────────
1101
1102#[derive(Debug, Clone, Serialize)]
1103pub struct AwsRegisterRequest {
1104    pub org_id: String,
1105    /// The `x-amzn-marketplace-token` posted after subscribing on AWS Marketplace.
1106    pub registration_token: String,
1107    #[serde(skip_serializing_if = "Option::is_none")]
1108    pub dimension: Option<String>,
1109}
1110
1111#[derive(Debug, Clone, Serialize)]
1112pub struct AzureRegisterRequest {
1113    pub org_id: String,
1114    /// The `x-ms-marketplace-token` posted after subscribing to the Azure SaaS offer.
1115    pub marketplace_token: String,
1116    #[serde(skip_serializing_if = "Option::is_none")]
1117    pub dimension: Option<String>,
1118}