oxios_kernel/kernel_handle/
knowledge_lens.rs1use std::collections::HashSet;
13use std::path::PathBuf;
14use std::sync::Arc;
15
16use anyhow::Result;
17use parking_lot::RwLock;
18use serde::{Deserialize, Serialize};
19use tokio::sync::mpsc;
20
21use crate::memory::{MemoryEntry, MemoryManager, MemoryType};
22
23#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25pub struct KnowledgeContext {
26 pub notes: Vec<KnowledgeNote>,
28 pub memories: Vec<MemoryNote>,
30 pub index_entries_used: usize,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct KnowledgeNote {
37 pub path: String,
39 pub name: String,
41 pub content: String,
43 pub backlink_count: usize,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct MemoryNote {
50 pub id: String,
52 pub source: String,
54 pub content: String,
56 pub importance: f32,
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct CopilotResponse {
63 pub content: String,
65 pub referenced_notes: Vec<String>,
67 pub referenced_memories: Vec<String>,
69}
70
71pub struct KnowledgeLens {
76 kb: Arc<oxios_markdown::KnowledgeBase>,
78 memory: Arc<MemoryManager>,
80 agent_writes: Arc<RwLock<HashSet<String>>>,
82 #[allow(dead_code)]
84 callback_handle: Option<mpsc::Sender<oxios_markdown::knowledge::FileChange>>,
85 model_id: String,
87}
88
89impl std::fmt::Debug for KnowledgeLens {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.debug_struct("KnowledgeLens").finish()
92 }
93}
94
95impl KnowledgeLens {
96 pub fn new(
100 kb: Arc<oxios_markdown::KnowledgeBase>,
101 memory: Arc<MemoryManager>,
102 ) -> anyhow::Result<Self> {
103 let (tx, mut rx) = mpsc::channel::<oxios_markdown::knowledge::FileChange>(64);
104 let tx_for_cb = tx.clone();
105 kb.on_file_change(move |_path, event| {
106 let tx = tx.clone();
107 tokio::spawn(async move {
108 let _ = tx.send(event).await;
109 });
110 });
111
112 let lens = Self {
113 kb,
114 memory,
115 agent_writes: Arc::new(RwLock::new(HashSet::new())),
116 callback_handle: Some(tx_for_cb),
117 model_id: "anthropic/claude-sonnet-4".to_string(),
118 };
119
120 let memory = lens.memory.clone();
122 let kb = lens.kb.clone();
123 tokio::spawn(async move {
124 while let Some(event) = rx.recv().await {
125 lens_handle_event(kb.clone(), memory.clone(), event);
126 }
127 });
128
129 Ok(lens)
130 }
131
132 pub fn root(&self) -> PathBuf {
134 self.kb.root()
135 }
136
137 pub fn knowledge_base(&self) -> &Arc<oxios_markdown::KnowledgeBase> {
139 &self.kb
140 }
141
142 pub fn model_id(&self) -> &str {
144 &self.model_id
145 }
146
147 pub fn mark_agent_write(&self, path: &str) {
149 self.agent_writes.write().insert(path.to_string());
150 }
151
152 pub fn is_agent_write(&self, path: &str) -> bool {
154 self.agent_writes.read().contains(path)
155 }
156
157 pub fn clear_agent_write(&self, path: &str) {
159 self.agent_writes.write().remove(path);
160 }
161
162 pub async fn recall_for_context(&self, query: &str, limit: usize) -> Result<KnowledgeContext> {
167 let mem_entries = self
169 .memory
170 .search(query, None, limit)
171 .await
172 .unwrap_or_default();
173
174 let memories: Vec<MemoryNote> = mem_entries
175 .iter()
176 .map(|e| MemoryNote {
177 id: e.id.clone(),
178 source: e.source.clone(),
179 content: e.content.chars().take(300).collect(),
180 importance: e.importance,
181 })
182 .collect();
183
184 let note_hits = self.kb.search(query, limit)?;
186
187 let notes: Vec<KnowledgeNote> = note_hits
188 .into_iter()
189 .map(|h| {
190 let content = self
191 .kb
192 .note_read(&h.path)
193 .ok()
194 .flatten()
195 .map(|c| c.chars().take(500).collect::<String>())
196 .unwrap_or_default();
197 KnowledgeNote {
198 path: h.path,
199 name: h.name,
200 content,
201 backlink_count: h.backlink_count,
202 }
203 })
204 .collect();
205
206 Ok(KnowledgeContext {
207 notes,
208 memories,
209 index_entries_used: mem_entries.len(),
210 })
211 }
212
213 #[allow(clippy::unused_async)]
217 pub async fn copilot_chat(
218 &self,
219 engine: Arc<dyn crate::engine::EngineProvider>,
220 model_id: &str,
221 question: &str,
222 context_path: Option<&str>,
223 ) -> Result<CopilotResponse> {
224 let mut context_parts = Vec::new();
225 let mut referenced_notes = Vec::new();
226
227 if let Some(path) = context_path {
229 if let Ok(Some(content)) = self.kb.note_read(path) {
230 let snippet: String = content.chars().take(2000).collect();
231 context_parts.push(format!("## Current: {}\n\n{}", path, snippet));
232 referenced_notes.push(path.to_string());
233 }
234 }
235
236 let hits = self.kb.search(question, 5).unwrap_or_default();
238 for hit in &hits {
239 if referenced_notes.contains(&hit.path) {
240 continue;
241 }
242 if let Ok(Some(content)) = self.kb.note_read(&hit.path) {
243 let snippet: String = content.chars().take(500).collect();
244 context_parts.push(format!("## Related: {}\n\n{}", hit.path, snippet));
245 referenced_notes.push(hit.path.clone());
246 }
247 }
248
249 let mut referenced_memories = Vec::new();
251 if let Ok(entries) = self.memory.search(question, None, 3).await {
252 for mem in &entries {
253 context_parts.push(format!(
254 "## Memory [{}]: {}",
255 mem.memory_type.label(),
256 mem.content.chars().take(200).collect::<String>()
257 ));
258 referenced_memories.push(mem.id.clone());
259 }
260 }
261
262 let system_prompt = format!(
264 "You are a knowledge assistant embedded in a markdown editor.\
265 Answer questions about the user's notes using the provided context.\
266 Be concise. Respond in the same language as the question.\n\n\
267 ## Context:\n\n{}",
268 context_parts.join("\n\n")
269 );
270
271 let provider_name = model_id
272 .split_once('/')
273 .map(|(p, _)| p)
274 .unwrap_or("anthropic");
275 let provider = engine
276 .create_provider(provider_name)
277 .map_err(|e| anyhow::anyhow!("Provider: {e}"))?;
278 let model = engine
279 .resolve_model(model_id)
280 .map_err(|e| anyhow::anyhow!("Model: {e}"))?;
281
282 let mut ctx = oxi_sdk::Context::new();
283 ctx.set_system_prompt(&system_prompt);
284 ctx.add_message(oxi_sdk::Message::User(oxi_sdk::UserMessage::new(question)));
285
286 let stream = provider
287 .stream(&model, &ctx, None)
288 .await
289 .map_err(|e| anyhow::anyhow!("Stream: {e}"))?;
290
291 let mut text = String::new();
292 use futures::StreamExt;
293 let mut pinned = std::pin::pin!(stream);
294 while let Some(event) = pinned.next().await {
295 match event {
296 oxi_sdk::ProviderEvent::TextDelta { delta, .. } => text.push_str(&delta),
297 oxi_sdk::ProviderEvent::Done { .. } => break,
298 oxi_sdk::ProviderEvent::Error { error, .. } => {
299 return Err(anyhow::anyhow!("AI: {:?}", error));
300 }
301 _ => {}
302 }
303 }
304
305 Ok(CopilotResponse {
306 content: text,
307 referenced_notes,
308 referenced_memories,
309 })
310 }
311}
312
313fn lens_handle_event(
316 kb: Arc<oxios_markdown::KnowledgeBase>,
317 memory: Arc<MemoryManager>,
318 event: oxios_markdown::knowledge::FileChange,
319) {
320 use oxios_markdown::knowledge::FileChange::*;
321 match event {
322 Created(path) | Updated(path) => {
323 if let Ok(Some(content)) = kb.note_read(&path) {
324 index_to_memory(&path, &content, &memory);
325 }
326 }
327 Deleted(path) => {
328 let id = format!("note-{}", path.replace('/', "-").trim_end_matches(".md"));
329 let rt = tokio::runtime::Handle::try_current();
330 if let Ok(handle) = rt {
331 let memory = memory.clone();
332 handle.spawn(async move {
333 let _ = memory.forget(&id, MemoryType::Knowledge).await;
334 });
335 }
336 }
337 Moved { old, new } => {
338 let id = format!("note-{}", old.replace('/', "-").trim_end_matches(".md"));
339 let rt = tokio::runtime::Handle::try_current();
340 if let Ok(handle) = rt {
341 let memory = memory.clone();
342 let kb = kb.clone();
343 let new_path = new.clone();
344 handle.spawn(async move {
345 let _ = memory.forget(&id, MemoryType::Knowledge).await;
346 if let Ok(Some(content)) = kb.note_read(&new_path) {
347 index_to_memory(&new_path, &content, &memory);
348 }
349 });
350 }
351 }
352 }
353}
354
355fn index_to_memory(path: &str, content: &str, memory: &Arc<MemoryManager>) {
356 let tags = oxios_markdown::parser::extract_headings(content)
357 .into_iter()
358 .take(5)
359 .collect::<Vec<_>>();
360 let now = chrono::Utc::now();
361 let importance = 0.5_f32.min(0.3 + (tags.len() as f32 * 0.05));
362
363 let entry = MemoryEntry {
364 id: format!("note-{}", path.replace('/', "-").trim_end_matches(".md")),
365 memory_type: MemoryType::Knowledge,
366 content: content.to_string(),
367 source: "knowledge:lens".to_string(),
368 session_id: None,
369 tags,
370 importance,
371 created_at: now,
372 accessed_at: now,
373 access_count: 0,
374 };
375
376 let rt = tokio::runtime::Handle::try_current();
377 if let Ok(handle) = rt {
378 let memory = memory.clone();
379 handle.spawn(async move {
380 let _ = memory.remember(entry).await;
381 });
382 }
383}