Skip to main content

lean_ctx/tools/
ctx_share.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3
4#[derive(Serialize, Deserialize, Clone)]
5struct SharedContext {
6    from_agent: String,
7    to_agent: Option<String>,
8    files: Vec<SharedFile>,
9    message: Option<String>,
10    timestamp: String,
11}
12
13#[derive(Serialize, Deserialize, Clone)]
14struct SharedFile {
15    path: String,
16    content: String,
17    mode: String,
18    tokens: usize,
19}
20
21fn shared_dir() -> PathBuf {
22    crate::core::data_dir::lean_ctx_data_dir()
23        .unwrap_or_else(|_| PathBuf::from("."))
24        .join("agents")
25        .join("shared")
26}
27
28pub fn handle(
29    action: &str,
30    from_agent: Option<&str>,
31    to_agent: Option<&str>,
32    paths: Option<&str>,
33    message: Option<&str>,
34    cache: &crate::core::cache::SessionCache,
35) -> String {
36    match action {
37        "push" => handle_push(from_agent, to_agent, paths, message, cache),
38        "pull" => handle_pull(from_agent),
39        "list" => handle_list(),
40        "clear" => handle_clear(from_agent),
41        _ => format!("Unknown action: {action}. Use: push, pull, list, clear"),
42    }
43}
44
45fn handle_push(
46    from_agent: Option<&str>,
47    to_agent: Option<&str>,
48    paths: Option<&str>,
49    message: Option<&str>,
50    cache: &crate::core::cache::SessionCache,
51) -> String {
52    let Some(from) = from_agent else {
53        return "Error: from_agent is required (register first via ctx_agent)".to_string();
54    };
55
56    let path_list: Vec<&str> = match paths {
57        Some(p) => p.split(',').map(str::trim).collect(),
58        None => return "Error: paths is required (comma-separated file paths)".to_string(),
59    };
60
61    let mut shared_files = Vec::new();
62    let mut not_found = Vec::new();
63
64    for path in &path_list {
65        if let Some(entry) = cache.get(path) {
66            shared_files.push(SharedFile {
67                path: entry.path.clone(),
68                content: entry.content.clone(),
69                mode: "full".to_string(),
70                tokens: entry.original_tokens,
71            });
72        } else {
73            not_found.push(*path);
74        }
75    }
76
77    if shared_files.is_empty() {
78        return format!(
79            "No cached files found to share. Files must be read first via ctx_read.\nNot found: {}",
80            not_found.join(", ")
81        );
82    }
83
84    let context = SharedContext {
85        from_agent: from.to_string(),
86        to_agent: to_agent.map(String::from),
87        files: shared_files.clone(),
88        message: message.map(String::from),
89        timestamp: chrono::Utc::now().to_rfc3339(),
90    };
91
92    let dir = shared_dir();
93    let _ = std::fs::create_dir_all(&dir);
94
95    let filename = format!(
96        "{}_{}.json",
97        from,
98        chrono::Utc::now().format("%Y%m%d_%H%M%S")
99    );
100    let path = dir.join(&filename);
101
102    match serde_json::to_string_pretty(&context) {
103        Ok(json) => {
104            if let Err(e) = std::fs::write(&path, json) {
105                return format!("Error writing shared context: {e}");
106            }
107        }
108        Err(e) => return format!("Error serializing shared context: {e}"),
109    }
110
111    let total_tokens: usize = shared_files.iter().map(|f| f.tokens).sum();
112    let mut result = format!(
113        "Shared {} files ({} tokens) from {from}",
114        shared_files.len(),
115        total_tokens
116    );
117
118    if let Some(target) = to_agent {
119        result.push_str(&format!(" → {target}"));
120    } else {
121        result.push_str(" → all agents (broadcast)");
122    }
123
124    if !not_found.is_empty() {
125        result.push_str(&format!(
126            "\nNot in cache (skipped): {}",
127            not_found.join(", ")
128        ));
129    }
130
131    result
132}
133
134fn handle_pull(agent_id: Option<&str>) -> String {
135    let dir = shared_dir();
136    if !dir.exists() {
137        return "No shared contexts available.".to_string();
138    }
139
140    let my_id = agent_id.unwrap_or("anonymous");
141    let mut entries: Vec<SharedContext> = Vec::new();
142
143    if let Ok(readdir) = std::fs::read_dir(&dir) {
144        for entry in readdir.flatten() {
145            if let Ok(content) = std::fs::read_to_string(entry.path()) {
146                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
147                    let is_for_me =
148                        ctx.to_agent.is_none() || ctx.to_agent.as_deref() == Some(my_id);
149                    let is_not_from_me = ctx.from_agent != my_id;
150
151                    if is_for_me && is_not_from_me {
152                        entries.push(ctx);
153                    }
154                }
155            }
156        }
157    }
158
159    if entries.is_empty() {
160        return "No shared contexts for you.".to_string();
161    }
162
163    entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
164
165    let mut out = format!("Shared contexts available ({}):\n", entries.len());
166    for ctx in &entries {
167        let file_list: Vec<&str> = ctx.files.iter().map(|f| f.path.as_str()).collect();
168        let total_tokens: usize = ctx.files.iter().map(|f| f.tokens).sum();
169        out.push_str(&format!(
170            "\n  From: {} ({})\n  Files: {} ({} tokens)\n  {}\n",
171            ctx.from_agent,
172            &ctx.timestamp[..19],
173            file_list.join(", "),
174            total_tokens,
175            ctx.message
176                .as_deref()
177                .map(|m| format!("Message: {m}"))
178                .unwrap_or_default(),
179        ));
180    }
181
182    let total_files: usize = entries.iter().map(|e| e.files.len()).sum();
183    out.push_str(&format!(
184        "\nTotal: {} contexts, {} files. Use ctx_read on pulled files to load them into your cache.",
185        entries.len(),
186        total_files
187    ));
188
189    out
190}
191
192fn handle_list() -> String {
193    let dir = shared_dir();
194    if !dir.exists() {
195        return "No shared contexts.".to_string();
196    }
197
198    let mut count = 0;
199    let mut total_files = 0;
200    let mut out = String::from("Shared context store:\n");
201
202    if let Ok(readdir) = std::fs::read_dir(&dir) {
203        for entry in readdir.flatten() {
204            if let Ok(content) = std::fs::read_to_string(entry.path()) {
205                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
206                    count += 1;
207                    total_files += ctx.files.len();
208                    let target = ctx.to_agent.as_deref().unwrap_or("broadcast");
209                    out.push_str(&format!(
210                        "  {} → {} ({} files, {})\n",
211                        ctx.from_agent,
212                        target,
213                        ctx.files.len(),
214                        &ctx.timestamp[..19]
215                    ));
216                }
217            }
218        }
219    }
220
221    if count == 0 {
222        return "No shared contexts.".to_string();
223    }
224
225    out.push_str(&format!("\nTotal: {count} shares, {total_files} files"));
226    out
227}
228
229fn handle_clear(agent_id: Option<&str>) -> String {
230    let dir = shared_dir();
231    if !dir.exists() {
232        return "Nothing to clear.".to_string();
233    }
234
235    let my_id = agent_id.unwrap_or("anonymous");
236    let mut removed = 0;
237
238    if let Ok(readdir) = std::fs::read_dir(&dir) {
239        for entry in readdir.flatten() {
240            if let Ok(content) = std::fs::read_to_string(entry.path()) {
241                if let Ok(ctx) = serde_json::from_str::<SharedContext>(&content) {
242                    if ctx.from_agent == my_id {
243                        let _ = std::fs::remove_file(entry.path());
244                        removed += 1;
245                    }
246                }
247            }
248        }
249    }
250
251    format!("Cleared {removed} shared context(s) from {my_id}")
252}