Skip to main content

rigspark_runtime/
context.rs

1use crate::{
2    sessions::Attachment,
3    workspace::{LineRange, WorkspaceError, WorkspaceService},
4};
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7use std::{collections::HashSet, path::Path};
8#[derive(Debug, Deserialize)]
9#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
10pub enum ContextRef {
11    File {
12        #[serde(rename = "workspaceId")]
13        workspace_id: String,
14        path: String,
15        range: Option<LineRange>,
16    },
17    Terminal {
18        label: Option<String>,
19        content: String,
20    },
21    Diagnostics {
22        label: Option<String>,
23        content: String,
24    },
25    Git {
26        #[serde(rename = "workspaceId")]
27        workspace_id: String,
28        mode: String,
29    },
30}
31#[derive(Debug, Serialize)]
32pub struct ContextBundle {
33    pub text: String,
34    pub manifest: Vec<Attachment>,
35}
36fn digest(content: &str) -> String {
37    format!("{:x}", Sha256::digest(content.as_bytes()))
38}
39impl ContextBundle {
40    pub fn resolve(
41        workspace: &WorkspaceService,
42        refs: &[ContextRef],
43    ) -> Result<Self, WorkspaceError> {
44        if refs.len() > 20
45            || refs
46                .iter()
47                .filter(|reference| matches!(reference, ContextRef::File { .. }))
48                .count()
49                > 10
50            || refs
51                .iter()
52                .filter(|reference| !matches!(reference, ContextRef::File { .. }))
53                .count()
54                > 10
55        {
56            return Err(WorkspaceError("context source limit".into()));
57        }
58        let mut blocks = Vec::new();
59        let mut manifest = Vec::new();
60        let mut used = 0;
61        for reference in refs {
62            let (kind, label, path, content, hash, range, truncated, block) = match reference {
63                ContextRef::File {
64                    workspace_id,
65                    path,
66                    range,
67                } => {
68                    let snapshot = match workspace.read(workspace_id, path, range.clone()) {
69                        Ok(snapshot) => snapshot,
70                        Err(_) => continue,
71                    };
72                    let block = if let Some(range) = &snapshot.range {
73                        format!(
74                            "FILE: {} (lines {}-{})",
75                            snapshot.path, range.start_line, range.end_line
76                        )
77                    } else {
78                        format!("FILE: {}", snapshot.path)
79                    };
80                    (
81                        "file",
82                        snapshot.path.clone(),
83                        Some(snapshot.path),
84                        snapshot.content,
85                        snapshot.hash,
86                        snapshot.range,
87                        snapshot.truncated,
88                        block,
89                    )
90                }
91                ContextRef::Terminal { label, content }
92                | ContextRef::Diagnostics { label, content } => {
93                    if content.len() > 65536 {
94                        return Err(WorkspaceError("pasted context exceeds limit".into()));
95                    }
96                    let content = crate::sessions::gui_text(content);
97                    if content.trim().is_empty() {
98                        continue;
99                    }
100                    let terminal = matches!(reference, ContextRef::Terminal { .. });
101                    let kind = if terminal { "terminal" } else { "diagnostics" };
102                    let label = label
103                        .as_ref()
104                        .filter(|label| !label.trim().is_empty())
105                        .map(|label| {
106                            rigspark_core::reports::strip_control(label)
107                                .chars()
108                                .take(120)
109                                .collect::<String>()
110                        })
111                        .unwrap_or_else(|| {
112                            if terminal {
113                                "Terminal output".into()
114                            } else {
115                                "Diagnostics".into()
116                            }
117                        });
118                    let hash = digest(&content);
119                    let block = format!("{}: {label}", kind.to_uppercase());
120                    (kind, label, None, content, hash, None, false, block)
121                }
122                ContextRef::Git { workspace_id, mode } => {
123                    let snapshot = match workspace.git_context(workspace_id, mode) {
124                        Ok(snapshot) => snapshot,
125                        Err(_) => continue,
126                    };
127                    if snapshot["available"] != true {
128                        continue;
129                    }
130                    let content = snapshot["content"].as_str().unwrap_or("").to_owned();
131                    let hash = digest(&content);
132                    (
133                        "git",
134                        format!("git {mode}"),
135                        None,
136                        content,
137                        hash,
138                        None,
139                        snapshot["truncated"] == true,
140                        format!("GIT {}", mode.to_uppercase()),
141                    )
142                }
143            };
144            let size = content.len();
145            let included = used + size <= 256 * 1024;
146            manifest.push(Attachment {
147                kind: Some(kind.into()),
148                label: Some(label),
149                path,
150                hash,
151                size: size as u64,
152                truncated,
153                included,
154                range,
155            });
156            if included {
157                used += size;
158                blocks.push(format!("--- {block} ---\n{content}"));
159            }
160        }
161        Ok(Self {
162            text: if blocks.is_empty() {
163                String::new()
164            } else {
165                format!(
166                    "The user attached the following read-only context. Use it to inform your answer; do not assume any other files or state.\n\n{}",
167                    blocks.join("\n\n")
168                )
169            },
170            manifest,
171        })
172    }
173}
174#[derive(Default, Clone)]
175pub struct DisclosureStore {
176    approved: HashSet<String>,
177}
178impl DisclosureStore {
179    fn key(session: &str, provider: &str, bundle: &ContextBundle) -> String {
180        digest(
181            &serde_json::json!([session, provider, bundle.manifest, digest(&bundle.text)])
182                .to_string(),
183        )
184    }
185    pub fn allowed(&self, session: &str, provider: &str, bundle: &ContextBundle) -> bool {
186        provider == "local"
187            || bundle.manifest.is_empty()
188            || self
189                .approved
190                .contains(&Self::key(session, provider, bundle))
191    }
192    pub fn approve(&mut self, session: &str, provider: &str, bundle: &ContextBundle) {
193        if self.approved.len() >= 10000 {
194            self.approved.clear();
195        }
196        self.approved.insert(Self::key(session, provider, bundle));
197    }
198    pub fn clear(&mut self) {
199        self.approved.clear();
200    }
201}
202pub struct ArtifactImage {
203    pub content: Vec<u8>,
204    pub content_type: &'static str,
205}
206pub fn read_artifact(root: &Path, name: &str) -> Result<ArtifactImage, WorkspaceError> {
207    if name.len() > 3072 {
208        return Err(WorkspaceError("invalid artifact basename".into()));
209    }
210    let decoded = percent_encoding::percent_decode_str(name)
211        .decode_utf8()
212        .map_err(|_| WorkspaceError("invalid artifact encoding".into()))?;
213    let name = decoded.as_ref();
214    if name.len() > 1024
215        || !name
216            .as_bytes()
217            .first()
218            .is_some_and(u8::is_ascii_alphanumeric)
219        || !name
220            .bytes()
221            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
222    {
223        return Err(WorkspaceError("invalid artifact basename".into()));
224    }
225    let extension = Path::new(name)
226        .extension()
227        .and_then(|extension| extension.to_str())
228        .unwrap_or("")
229        .to_lowercase();
230    let content_type = match extension.as_str() {
231        "png" => "image/png",
232        "jpg" | "jpeg" => "image/jpeg",
233        "gif" => "image/gif",
234        "webp" => "image/webp",
235        "svg" => "image/svg+xml",
236        _ => return Err(WorkspaceError("unsupported artifact type".into())),
237    };
238    let missing = |error: std::io::Error| {
239        if error.kind() == std::io::ErrorKind::NotFound {
240            WorkspaceError(ARTIFACT_NOT_FOUND.into())
241        } else {
242            error.into()
243        }
244    };
245    let directory = crate::secure_fs::Directory::open(root).map_err(missing)?;
246    let content = directory
247        .read(Path::new(name), 12 * 1024 * 1024, false)
248        .map_err(missing)?;
249    Ok(ArtifactImage {
250        content,
251        content_type,
252    })
253}
254pub const ARTIFACT_NOT_FOUND: &str = "artifact not found";