1#![doc = include_str!("../README.md")]
8
9mod answer;
10#[cfg(feature = "broker")]
11pub mod broker;
12mod chunking;
13mod explain;
14mod graph;
15mod prompt;
16mod select;
17mod snapshot;
18mod tokenizer;
19mod views;
20#[cfg(feature = "bpe")]
21#[path = "worker/mod.rs"]
22pub mod worker;
23
24pub use answer::{
25 AnswerAssessment, AnswerClaim, AnswerDecision, AnswerDraft, AnswerPolicy, ClaimAssessment,
26 ClaimIssue, ClaimReview, ClaimVerdict,
27};
28pub use explain::{SelectionExplanation, SelectionSignal, SelectionStep};
29pub use graph::{ContextGraph, Document, EdgeKind, GraphLimits, SourceUpdate};
30pub use prompt::ContextPrompt;
31pub use select::{ContextRequest, ExcerptMode, SelectionStats};
32pub use snapshot::{Citation, ContextDelta, ContextSnapshot, EvidenceBlock};
33#[cfg(feature = "bpe")]
34pub use tokenizer::O200kTokenizer;
35pub use tokenizer::{
36 CachedTokenCounter, TokenCacheLimits, TokenCacheStats, TokenCounter, Utf8ByteCounter,
37};
38pub use views::{
39 ContextView, ContextViewAssessment, ContextViewHandle, ContextViewSpec, ContextViews,
40};
41
42use sha2::{Digest, Sha256};
43use std::fmt::Write as _;
44
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub enum ContextError {
48 InvalidInput,
50 LimitExceeded,
52 RequiredUnavailable,
54 BudgetUnsatisfiable,
56 Tokenizer,
58 Integrity,
60 BaseMismatch,
62}
63
64impl std::fmt::Display for ContextError {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 write!(f, "context graph error: {self:?}")
67 }
68}
69
70impl std::error::Error for ContextError {}
71
72pub(crate) fn digest<T: serde::Serialize>(domain: &str, value: &T) -> Result<String, ContextError> {
73 let mut hash = Sha256::new();
74 hash.update(domain.as_bytes());
75 hash.update([0]);
76 serde_json::to_writer(HashWriter(&mut hash), value).map_err(|_| ContextError::Integrity)?;
79 let mut output = String::with_capacity(64);
80 for byte in hash.finalize() {
81 write!(&mut output, "{byte:02x}").map_err(|_| ContextError::Integrity)?;
82 }
83 Ok(output)
84}
85
86struct HashWriter<'a>(&'a mut Sha256);
87
88impl std::io::Write for HashWriter<'_> {
89 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
90 self.0.update(bytes);
91 Ok(bytes.len())
92 }
93
94 fn flush(&mut self) -> std::io::Result<()> {
95 Ok(())
96 }
97}
98
99#[cfg(test)]
100mod digest_tests {
101 use super::*;
102
103 fn legacy_digest<T: serde::Serialize>(
104 domain: &str,
105 value: &T,
106 ) -> Result<String, Box<dyn std::error::Error>> {
107 let mut hash = Sha256::new();
108 hash.update(domain.as_bytes());
109 hash.update([0]);
110 hash.update(serde_json::to_vec(value)?);
111 Ok(hash
112 .finalize()
113 .iter()
114 .map(|byte| format!("{byte:02x}"))
115 .collect())
116 }
117
118 #[test]
119 fn streamed_commitments_preserve_legacy_bytes_and_domain_separation()
120 -> Result<(), Box<dyn std::error::Error>> {
121 for index in 0..256_u64 {
122 let value = serde_json::json!({
123 "record": [index, u64::MAX - index],
124 "text": format!("café 🦀 \"quote\"\\slash\n\t\0 {index}"),
125 "nested": {"empty": [], "optional": null, "boolean": index % 2 == 0},
126 });
127 for domain in ["cigar.document.v1", "cigar.context-snapshot.v1", ""] {
128 assert_eq!(digest(domain, &value)?, legacy_digest(domain, &value)?);
129 }
130 }
131 let large = "source \"quoted\" café 🦀\n".repeat(65_536);
132 assert_eq!(digest("large", &large)?, legacy_digest("large", &large)?);
133 assert_ne!(digest("a", &"bc")?, digest("ab", &"c")?);
134 Ok(())
135 }
136
137 #[test]
138 fn serialization_failure_still_returns_content_free_integrity_error() {
139 struct Invalid;
140 impl serde::Serialize for Invalid {
141 fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
142 Err(serde::ser::Error::custom(
143 "caller-controlled failure detail",
144 ))
145 }
146 }
147 assert_eq!(digest("failure", &Invalid), Err(ContextError::Integrity));
148 }
149}