opencrabs 0.3.20

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Session Context Tool
//!
//! Manage conversation context, store session variables, and maintain state.

use super::error::{Result, ToolError};
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;

/// Session context management tool
pub struct ContextTool;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ContextEntry {
    key: String,
    value: Value,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(default)]
    tags: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct ContextStore {
    session_id: String,
    variables: HashMap<String, ContextEntry>,
    #[serde(default)]
    facts: Vec<String>,
    #[serde(default)]
    decisions: Vec<String>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

impl ContextStore {
    fn new(session_id: String) -> Self {
        let now = Utc::now();
        Self {
            session_id,
            variables: HashMap::new(),
            facts: Vec::new(),
            decisions: Vec::new(),
            created_at: now,
            updated_at: now,
        }
    }

    async fn load(path: &Path, session_id: &str) -> Result<Self> {
        if path.exists() {
            let content = fs::read_to_string(path).await.map_err(ToolError::Io)?;
            let mut store: Self = serde_json::from_str(&content).map_err(|e| {
                ToolError::Execution(format!("Failed to parse context store: {}", e))
            })?;
            store.session_id = session_id.to_string();
            Ok(store)
        } else {
            Ok(Self::new(session_id.to_string()))
        }
    }

    async fn save(&self, path: &Path) -> Result<()> {
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| ToolError::Execution(format!("Failed to serialize context: {}", e)))?;

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).await.map_err(ToolError::Io)?;
        }

        fs::write(path, content).await.map_err(ToolError::Io)?;
        Ok(())
    }
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "operation")]
enum ContextOperation {
    #[serde(rename = "set")]
    Set {
        key: String,
        value: Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(default)]
        tags: Vec<String>,
    },

    #[serde(rename = "get")]
    Get { key: String },

    #[serde(rename = "delete")]
    Delete { key: String },

    #[serde(rename = "list")]
    List {
        #[serde(skip_serializing_if = "Option::is_none")]
        tag: Option<String>,
    },

    #[serde(rename = "add_fact")]
    AddFact { fact: String },

    #[serde(rename = "add_decision")]
    AddDecision { decision: String },

    #[serde(rename = "summary")]
    Summary,

    #[serde(rename = "clear")]
    Clear {
        #[serde(default)]
        confirm: bool,
    },
}

#[derive(Debug, Deserialize, Serialize)]
struct ContextInput {
    #[serde(flatten)]
    operation: ContextOperation,
}

fn get_store_path(context: &ToolExecutionContext) -> PathBuf {
    let dir = crate::config::opencrabs_home()
        .join("agents")
        .join("session");
    let _ = std::fs::create_dir_all(&dir);
    dir.join(format!("context_{}.json", context.session_id))
}

#[async_trait]
impl Tool for ContextTool {
    fn name(&self) -> &str {
        "session_context"
    }

    fn description(&self) -> &str {
        "Manage session context and variables. Store key-value pairs, track important facts and decisions, and maintain state across the conversation."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "operation": {
                    "type": "string",
                    "description": "Operation to perform",
                    "enum": ["set", "get", "delete", "list", "add_fact", "add_decision", "summary", "clear"]
                },
                "key": {
                    "type": "string",
                    "description": "Variable key (for set, get, delete)"
                },
                "value": {
                    "description": "Variable value (for set operation, can be any JSON type)"
                },
                "description": {
                    "type": "string",
                    "description": "Description of the variable (optional)"
                },
                "tags": {
                    "type": "array",
                    "description": "Tags for categorizing variables",
                    "items": {
                        "type": "string"
                    },
                    "default": []
                },
                "tag": {
                    "type": "string",
                    "description": "Filter by tag (for list operation)"
                },
                "fact": {
                    "type": "string",
                    "description": "Important fact to remember (for add_fact)"
                },
                "decision": {
                    "type": "string",
                    "description": "Important decision made (for add_decision)"
                },
                "confirm": {
                    "type": "boolean",
                    "description": "Confirm clear operation (must be true)",
                    "default": false
                }
            },
            "required": ["operation"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::ReadFiles, ToolCapability::WriteFiles]
    }

    fn requires_approval(&self) -> bool {
        false // Context management is safe
    }

    fn validate_input(&self, input: &Value) -> Result<()> {
        let _: ContextInput = serde_json::from_value(input.clone())
            .map_err(|e| ToolError::InvalidInput(format!("Invalid input: {}", e)))?;
        Ok(())
    }

    async fn execute(&self, input: Value, context: &ToolExecutionContext) -> Result<ToolResult> {
        let input: ContextInput = serde_json::from_value(input)?;
        let store_path = get_store_path(context);
        let session_id_str = context.session_id.to_string();
        let mut store = ContextStore::load(&store_path, &session_id_str).await?;

        let result = match input.operation {
            ContextOperation::Set {
                key,
                value,
                description,
                tags,
            } => {
                let now = Utc::now();
                let is_update = store.variables.contains_key(&key);

                let entry = ContextEntry {
                    key: key.clone(),
                    value: value.clone(),
                    created_at: if is_update {
                        store
                            .variables
                            .get(&key)
                            .map(|e| e.created_at)
                            .unwrap_or(now)
                    } else {
                        now
                    },
                    updated_at: now,
                    description,
                    tags,
                };

                store.variables.insert(key.clone(), entry);
                store.updated_at = now;
                store.save(&store_path).await?;

                if is_update {
                    format!("Updated variable '{}' = {}", key, value)
                } else {
                    format!("Set variable '{}' = {}", key, value)
                }
            }

            ContextOperation::Get { key } => {
                let entry = store.variables.get(&key).ok_or_else(|| {
                    ToolError::InvalidInput(format!("Variable not found: {}", key))
                })?;

                let mut output = format!("Variable: {}\n", key);
                output.push_str(&format!("Value: {}\n", entry.value));
                if let Some(desc) = &entry.description {
                    output.push_str(&format!("Description: {}\n", desc));
                }
                if !entry.tags.is_empty() {
                    output.push_str(&format!("Tags: {}\n", entry.tags.join(", ")));
                }
                output.push_str(&format!(
                    "Created: {}\n",
                    entry.created_at.format("%Y-%m-%d %H:%M:%S")
                ));
                output.push_str(&format!(
                    "Updated: {}\n",
                    entry.updated_at.format("%Y-%m-%d %H:%M:%S")
                ));

                output
            }

            ContextOperation::Delete { key } => {
                store.variables.remove(&key).ok_or_else(|| {
                    ToolError::InvalidInput(format!("Variable not found: {}", key))
                })?;

                store.updated_at = Utc::now();
                store.save(&store_path).await?;

                format!("Deleted variable '{}'", key)
            }

            ContextOperation::List { tag } => {
                let mut filtered_vars: Vec<_> = store
                    .variables
                    .values()
                    .filter(|e| {
                        if let Some(ref t) = tag {
                            e.tags.contains(t)
                        } else {
                            true
                        }
                    })
                    .collect();

                if filtered_vars.is_empty() {
                    return Ok(ToolResult::success("No variables found".to_string()));
                }

                filtered_vars.sort_by(|a, b| a.key.cmp(&b.key));

                let mut output = format!("Found {} variables:\n\n", filtered_vars.len());
                for entry in filtered_vars {
                    output.push_str(&format!("{} = {}\n", entry.key, entry.value));
                    if let Some(desc) = &entry.description {
                        output.push_str(&format!("  {}\n", desc));
                    }
                    if !entry.tags.is_empty() {
                        output.push_str(&format!("  Tags: {}\n", entry.tags.join(", ")));
                    }
                    output.push('\n');
                }

                output
            }

            ContextOperation::AddFact { fact } => {
                store.facts.push(fact.clone());
                store.updated_at = Utc::now();
                store.save(&store_path).await?;

                format!("Added fact: {}\nTotal facts: {}", fact, store.facts.len())
            }

            ContextOperation::AddDecision { decision } => {
                store.decisions.push(decision.clone());
                store.updated_at = Utc::now();
                store.save(&store_path).await?;

                format!(
                    "Added decision: {}\nTotal decisions: {}",
                    decision,
                    store.decisions.len()
                )
            }

            ContextOperation::Summary => {
                let mut output = "Session Context Summary\n".to_string();
                output.push_str(&format!("Session ID: {}\n", store.session_id));
                output.push_str(&format!(
                    "Created: {}\n",
                    store.created_at.format("%Y-%m-%d %H:%M:%S")
                ));
                output.push_str(&format!(
                    "Last Updated: {}\n\n",
                    store.updated_at.format("%Y-%m-%d %H:%M:%S")
                ));

                output.push_str(&format!("Variables: {}\n", store.variables.len()));
                output.push_str(&format!("Facts: {}\n", store.facts.len()));
                output.push_str(&format!("Decisions: {}\n\n", store.decisions.len()));

                if !store.facts.is_empty() {
                    output.push_str("Key Facts:\n");
                    for (i, fact) in store.facts.iter().enumerate() {
                        output.push_str(&format!("{}. {}\n", i + 1, fact));
                    }
                    output.push('\n');
                }

                if !store.decisions.is_empty() {
                    output.push_str("Key Decisions:\n");
                    for (i, decision) in store.decisions.iter().enumerate() {
                        output.push_str(&format!("{}. {}\n", i + 1, decision));
                    }
                    output.push('\n');
                }

                if !store.variables.is_empty() {
                    output.push_str("Variables:\n");
                    let mut vars: Vec<_> = store.variables.keys().collect();
                    vars.sort();
                    for key in vars {
                        output.push_str(&format!("  {}\n", key));
                    }
                }

                output
            }

            ContextOperation::Clear { confirm } => {
                if !confirm {
                    return Ok(ToolResult::error(
                        "Clear operation requires confirm=true to proceed".to_string(),
                    ));
                }

                let var_count = store.variables.len();
                let fact_count = store.facts.len();
                let decision_count = store.decisions.len();

                store.variables.clear();
                store.facts.clear();
                store.decisions.clear();
                store.updated_at = Utc::now();
                store.save(&store_path).await?;

                format!(
                    "Cleared all context data\nVariables: {}\nFacts: {}\nDecisions: {}",
                    var_count, fact_count, decision_count
                )
            }
        };

        Ok(ToolResult::success(result))
    }
}