1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use std::fs;
6use chrono::{DateTime, Utc};
7
8#[derive(Clone, Debug)]
9struct ClipEntry {
10 content: String,
11 #[allow(dead_code)]
12 tag: String,
13 source: ClipSource,
14 timestamp: DateTime<Utc>,
15 line_count: usize,
16 byte_size: usize,
17}
18
19#[derive(Clone, Debug)]
20enum ClipSource {
21 File {
22 path: String,
23 lines: Option<Vec<(usize, usize)>>,
24 },
25 Direct,
26}
27
28pub struct ClipboardModule {
29 entries: Arc<Mutex<HashMap<String, ClipEntry>>>,
30}
31
32impl Default for ClipboardModule {
33 fn default() -> Self {
34 Self::new()
35 }
36}
37
38impl ClipboardModule {
39 pub fn new() -> Self {
40 Self {
41 entries: Arc::new(Mutex::new(HashMap::new())),
42 }
43 }
44
45 pub fn get_tools(&self) -> Vec<Value> {
46 vec![
47 json!({
48 "name": "clip_copy_file",
49 "description": "Copy text from a file into the session clipboard with a tag. Reads file content (optionally specific line ranges) and stores it for later paste operations. Saves tokens by avoiding redundant file reads.",
50 "inputSchema": {
51 "type": "object",
52 "properties": {
53 "path": {
54 "type": "string",
55 "description": "Path to the file to copy from"
56 },
57 "tag": {
58 "type": "string",
59 "description": "Tag name to store this content under (used to retrieve it later)"
60 },
61 "lines": {
62 "type": "array",
63 "description": "Optional line ranges to copy, e.g. [[1,10], [20,30]]. Copies entire file if omitted.",
64 "items": {
65 "type": "array",
66 "minItems": 2,
67 "maxItems": 2,
68 "items": { "type": "integer" }
69 }
70 }
71 },
72 "required": ["path", "tag"]
73 }
74 }),
75 json!({
76 "name": "clip_copy",
77 "description": "Copy arbitrary text directly into the session clipboard with a tag. Use this to store computed/generated content or text from tool outputs for later reuse without re-generating.",
78 "inputSchema": {
79 "type": "object",
80 "properties": {
81 "content": {
82 "type": "string",
83 "description": "Text content to store"
84 },
85 "tag": {
86 "type": "string",
87 "description": "Tag name to store this content under"
88 }
89 },
90 "required": ["content", "tag"]
91 }
92 }),
93 json!({
94 "name": "clip_paste_file",
95 "description": "Paste tagged clipboard content into a file. Can overwrite the entire file, append, prepend, or replace specific line ranges.",
96 "inputSchema": {
97 "type": "object",
98 "properties": {
99 "tag": {
100 "type": "string",
101 "description": "Tag of the clipboard entry to paste"
102 },
103 "path": {
104 "type": "string",
105 "description": "Destination file path"
106 },
107 "mode": {
108 "type": "string",
109 "enum": ["overwrite", "append", "prepend", "lines"],
110 "description": "Paste mode (default: overwrite). 'lines' uses the lines parameter to replace specific ranges."
111 },
112 "lines": {
113 "type": "array",
114 "description": "Line ranges to replace in the destination file (for mode='lines'), e.g. [[5,10]].",
115 "items": {
116 "type": "array",
117 "minItems": 2,
118 "maxItems": 2,
119 "items": { "type": "integer" }
120 }
121 }
122 },
123 "required": ["tag", "path"]
124 }
125 }),
126 json!({
127 "name": "clip_paste",
128 "description": "Retrieve tagged clipboard content. Returns the stored text so the agent can use it without re-reading the original source. Omit tag to list all entries.",
129 "inputSchema": {
130 "type": "object",
131 "properties": {
132 "tag": {
133 "type": "string",
134 "description": "Tag of the clipboard entry to retrieve. Omit to list all tags with metadata."
135 }
136 }
137 }
138 }),
139 json!({
140 "name": "clip_clear",
141 "description": "Clear one or all clipboard entries from the session.",
142 "inputSchema": {
143 "type": "object",
144 "properties": {
145 "tag": {
146 "type": "string",
147 "description": "Tag to clear. Omit to clear all entries."
148 }
149 }
150 }
151 }),
152 ]
153 }
154
155 pub async fn copy_file(&self, args: Value) -> Result<Value> {
156 let path = args["path"].as_str().context("Missing 'path' parameter")?;
157 let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
158
159 let full_content = fs::read_to_string(path)
160 .with_context(|| format!("Failed to read file: {}", path))?;
161
162 let mut line_ranges: Option<Vec<(usize, usize)>> = None;
163
164 let content = if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
165 let all_lines: Vec<&str> = full_content.lines().collect();
166 let mut selected_lines = Vec::new();
167 let mut ranges = Vec::new();
168
169 for range in lines_array {
170 if let Some(range_arr) = range.as_array() {
171 if range_arr.len() == 2 {
172 let from = range_arr[0].as_u64().unwrap_or(1) as usize;
173 let to = range_arr[1].as_u64().unwrap_or(all_lines.len() as u64) as usize;
174 let from_idx = from.saturating_sub(1);
175 let to_idx = to.min(all_lines.len());
176
177 if from_idx < all_lines.len() && from_idx < to_idx {
178 selected_lines.extend_from_slice(&all_lines[from_idx..to_idx]);
179 }
180 ranges.push((from, to));
181 }
182 }
183 }
184
185 line_ranges = Some(ranges);
186 selected_lines.join("\n")
187 } else {
188 full_content
189 };
190
191 let line_count = content.lines().count();
192 let byte_size = content.len();
193
194 let entry = ClipEntry {
195 content,
196 tag: tag.to_string(),
197 source: ClipSource::File {
198 path: path.to_string(),
199 lines: line_ranges.clone(),
200 },
201 timestamp: Utc::now(),
202 line_count,
203 byte_size,
204 };
205
206 let mut entries = self.entries.lock().unwrap();
207 entries.insert(tag.to_string(), entry);
208
209 Ok(json!({
210 "success": true,
211 "tag": tag,
212 "source": path,
213 "lines": line_ranges.map(|r| r.iter().map(|(a, b)| json!([a, b])).collect::<Vec<_>>()),
214 "line_count": line_count,
215 "byte_size": byte_size,
216 "total_entries": entries.len()
217 }))
218 }
219
220 pub async fn copy(&self, args: Value) -> Result<Value> {
221 let content = args["content"].as_str().context("Missing 'content' parameter")?;
222 let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
223
224 let line_count = content.lines().count();
225 let byte_size = content.len();
226
227 let entry = ClipEntry {
228 content: content.to_string(),
229 tag: tag.to_string(),
230 source: ClipSource::Direct,
231 timestamp: Utc::now(),
232 line_count,
233 byte_size,
234 };
235
236 let mut entries = self.entries.lock().unwrap();
237 entries.insert(tag.to_string(), entry);
238
239 Ok(json!({
240 "success": true,
241 "tag": tag,
242 "source": "direct",
243 "line_count": line_count,
244 "byte_size": byte_size,
245 "total_entries": entries.len()
246 }))
247 }
248
249 pub async fn paste_file(&self, args: Value) -> Result<Value> {
250 let tag = args["tag"].as_str().context("Missing 'tag' parameter")?;
251 let path = args["path"].as_str().context("Missing 'path' parameter")?;
252 let mode = args["mode"].as_str().unwrap_or("overwrite");
253
254 let entries = self.entries.lock().unwrap();
255 let entry = entries.get(tag)
256 .with_context(|| format!("No clipboard entry with tag '{}'", tag))?;
257 let content = entry.content.clone();
258 drop(entries);
259
260 let final_content = match mode {
261 "append" => {
262 let existing = fs::read_to_string(path).unwrap_or_default();
263 format!("{}{}", existing, content)
264 }
265 "prepend" => {
266 let existing = fs::read_to_string(path).unwrap_or_default();
267 format!("{}{}", content, existing)
268 }
269 "lines" => {
270 let existing = fs::read_to_string(path).unwrap_or_default();
271 let mut all_lines: Vec<String> = existing.lines().map(|s| s.to_string()).collect();
272 let new_lines: Vec<&str> = content.lines().collect();
273 let mut new_line_idx = 0;
274
275 if let Some(lines_array) = args.get("lines").and_then(|v| v.as_array()) {
276 for range in lines_array {
277 if let Some(range_arr) = range.as_array() {
278 if range_arr.len() == 2 {
279 let from = range_arr[0].as_u64().unwrap_or(1) as usize;
280 let to = range_arr[1].as_u64().unwrap_or(all_lines.len() as u64) as usize;
281 let from_idx = from.saturating_sub(1);
282 let to_idx = to.min(all_lines.len());
283 let range_size = to_idx.saturating_sub(from_idx);
284
285 while all_lines.len() < to_idx {
286 all_lines.push(String::new());
287 }
288
289 for i in 0..range_size {
290 if new_line_idx < new_lines.len() {
291 all_lines[from_idx + i] = new_lines[new_line_idx].to_string();
292 new_line_idx += 1;
293 }
294 }
295 }
296 }
297 }
298 } else {
299 return Err(anyhow::anyhow!("Mode 'lines' requires 'lines' parameter"));
300 }
301
302 all_lines.join("\n") + "\n"
303 }
304 _ => content.clone(), };
306
307 if let Some(parent) = std::path::Path::new(path).parent() {
308 fs::create_dir_all(parent)
309 .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
310 }
311
312 let bytes_written = final_content.len();
313 fs::write(path, &final_content)
314 .with_context(|| format!("Failed to write to file: {}", path))?;
315
316 Ok(json!({
317 "success": true,
318 "tag": tag,
319 "destination": path,
320 "mode": mode,
321 "bytes_written": bytes_written
322 }))
323 }
324
325 pub async fn paste(&self, args: Value) -> Result<Value> {
326 let entries = self.entries.lock().unwrap();
327
328 if let Some(tag) = args["tag"].as_str() {
329 if let Some(entry) = entries.get(tag) {
330 let source = match &entry.source {
331 ClipSource::File { path, lines } => json!({
332 "type": "file",
333 "path": path,
334 "lines": lines.as_ref().map(|r| r.iter().map(|(a, b)| json!([a, b])).collect::<Vec<_>>())
335 }),
336 ClipSource::Direct => json!({ "type": "direct" }),
337 };
338
339 Ok(json!({
340 "tag": tag,
341 "content": entry.content,
342 "source": source,
343 "line_count": entry.line_count,
344 "byte_size": entry.byte_size,
345 "timestamp": entry.timestamp.to_rfc3339(),
346 "found": true
347 }))
348 } else {
349 Ok(json!({
350 "tag": tag,
351 "found": false,
352 "error": format!("No entry with tag '{}'", tag)
353 }))
354 }
355 } else {
356 let listing: Vec<Value> = entries.iter().map(|(tag, entry)| {
357 let source_type = match &entry.source {
358 ClipSource::File { path, .. } => json!({"type": "file", "path": path}),
359 ClipSource::Direct => json!({"type": "direct"}),
360 };
361 json!({
362 "tag": tag,
363 "source": source_type,
364 "line_count": entry.line_count,
365 "byte_size": entry.byte_size,
366 "timestamp": entry.timestamp.to_rfc3339()
367 })
368 }).collect();
369
370 Ok(json!({
371 "entries": listing,
372 "count": listing.len()
373 }))
374 }
375 }
376
377 pub async fn clear(&self, args: Value) -> Result<Value> {
378 let mut entries = self.entries.lock().unwrap();
379
380 if let Some(tag) = args["tag"].as_str() {
381 let removed = entries.remove(tag).is_some();
382 Ok(json!({
383 "success": removed,
384 "tag": tag,
385 "removed": removed,
386 "remaining": entries.len()
387 }))
388 } else {
389 let count = entries.len();
390 entries.clear();
391 Ok(json!({
392 "success": true,
393 "cleared": count,
394 "remaining": 0
395 }))
396 }
397 }
398}