autogpt 0.3.2

🦀 A Pure Rust Framework For Building AGIs.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[cfg(feature = "cli")]
use chrono::{DateTime, Utc};
#[cfg(feature = "cli")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "cli")]
use std::cmp;
#[cfg(feature = "cli")]
use std::fs;
#[cfg(feature = "cli")]
use std::path::PathBuf;
#[cfg(feature = "cli")]
use uuid::Uuid;

/// Completion state of a single session task.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
    Skipped,
}

#[cfg(feature = "cli")]
impl TaskStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::InProgress => "in_progress",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Skipped => "skipped",
        }
    }

    pub fn icon(self) -> &'static str {
        match self {
            Self::Pending => "",
            Self::InProgress => "",
            Self::Completed => "",
            Self::Failed => "",
            Self::Skipped => "",
        }
    }
}

/// A single message exchanged during a session.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMessage {
    pub role: String,
    pub content: String,
    pub timestamp: DateTime<Utc>,
}

/// A task item tracked within a session, including its execution outcome.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionTask {
    pub description: String,
    pub status: TaskStatus,
}

/// A file that was created or written during task execution.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionFile {
    pub path: String,
    pub action: String,
}

/// Persistent session data stored under `~/.autogpt/sessions/<id>/`.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: String,
    pub title: String,
    pub prompt: String,
    pub model: String,
    pub provider: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub messages: Vec<SessionMessage>,
    pub tasks: Vec<SessionTask>,
    pub files_created: Vec<SessionFile>,
    pub plan: Option<String>,
    pub walkthrough: Option<String>,
    pub workspace: String,
    pub reasoning_log: Vec<String>,
    pub build_attempts: u8,
}

#[cfg(feature = "cli")]
impl Session {
    pub fn new(prompt: &str, workspace: &str, model: &str, provider: &str) -> Self {
        let now = Utc::now();
        let title = prompt.chars().take(60).collect::<String>();
        Self {
            id: Uuid::new_v4().to_string(),
            title,
            prompt: prompt.to_string(),
            model: model.to_string(),
            provider: provider.to_string(),
            created_at: now,
            updated_at: now,
            messages: Vec::new(),
            tasks: Vec::new(),
            files_created: Vec::new(),
            plan: None,
            walkthrough: None,
            workspace: workspace.to_string(),
            reasoning_log: Vec::new(),
            build_attempts: 0,
        }
    }

    pub fn add_reasoning(&mut self, thought: &str) {
        self.reasoning_log.push(thought.to_string());
        self.updated_at = Utc::now();
    }

    pub fn increment_build_attempt(&mut self) {
        self.build_attempts = self.build_attempts.saturating_add(1);
        self.updated_at = Utc::now();
    }

    pub fn add_message(&mut self, role: &str, content: &str) {
        self.messages.push(SessionMessage {
            role: role.to_string(),
            content: content.to_string(),
            timestamp: Utc::now(),
        });
        self.updated_at = Utc::now();
    }

    pub fn set_tasks(&mut self, tasks: Vec<SessionTask>) {
        self.tasks = tasks;
        self.updated_at = Utc::now();
    }

    pub fn update_task_status(&mut self, index: usize, status: TaskStatus) {
        if let Some(task) = self.tasks.get_mut(index) {
            task.status = status;
            self.updated_at = Utc::now();
        }
    }

    pub fn record_file(&mut self, path: &str, action: &str) {
        self.files_created.push(SessionFile {
            path: path.to_string(),
            action: action.to_string(),
        });
        self.updated_at = Utc::now();
    }

    pub fn set_plan(&mut self, plan: &str) {
        self.plan = Some(plan.to_string());
        self.updated_at = Utc::now();
    }

    pub fn set_walkthrough(&mut self, walkthrough: &str) {
        self.walkthrough = Some(walkthrough.to_string());
        self.updated_at = Utc::now();
    }

    /// Produces a compact, token-efficient summary of the session's prior state.
    ///
    /// The output is injected into `{HISTORY}` and `{PREVIOUS_CONTEXT}` placeholders in
    /// follow-up prompts so the LLM knows exactly what was already built without receiving
    /// the full, potentially large session JSON. Capped at roughly 1200 tokens.
    pub fn session_context_summary(&self) -> String {
        let mut parts: Vec<String> = Vec::new();

        parts.push(format!("## Prior Session: {}", self.title));
        parts.push(format!("Workspace: {}", self.workspace));

        if !self.tasks.is_empty() {
            let task_lines: Vec<String> = self
                .tasks
                .iter()
                .enumerate()
                .map(|(i, t)| format!("  {}. [{}] {}", i + 1, t.status.as_str(), t.description))
                .collect();
            parts.push(format!("Tasks completed:\n{}", task_lines.join("\n")));
        }

        if !self.files_created.is_empty() {
            let file_lines: Vec<String> = self
                .files_created
                .iter()
                .take(30)
                .map(|f| format!("  - {} ({})", f.path, f.action))
                .collect();
            let suffix = if self.files_created.len() > 30 {
                format!("\n  ... and {} more", self.files_created.len() - 30)
            } else {
                String::new()
            };
            parts.push(format!(
                "Files created:\n{}{}",
                file_lines.join("\n"),
                suffix
            ));
        }

        if let Some(ref plan) = self.plan {
            let excerpt: String = plan.lines().take(20).collect::<Vec<_>>().join("\n");
            parts.push(format!("Implementation plan (excerpt):\n{excerpt}"));
        }

        let last_messages: Vec<String> = self
            .messages
            .iter()
            .rev()
            .take(6)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .map(|m| {
                let snippet: String = m.content.chars().take(200).collect();
                format!("[{}]: {}", m.role, snippet)
            })
            .collect();
        if !last_messages.is_empty() {
            parts.push(format!(
                "Recent conversation:\n{}",
                last_messages.join("\n")
            ));
        }

        parts.join("\n\n")
    }
}

/// A lightweight summary entry for listing available sessions.
#[cfg(feature = "cli")]
#[derive(Debug, Clone)]
pub struct SessionEntry {
    pub id: String,
    pub title: String,
    pub prompt: String,
    pub model: String,
    pub provider: String,
    pub updated_at: DateTime<Utc>,
    pub task_count: usize,
    pub completed_count: usize,
}

/// Manages session persistence under the autogpt home directory.
#[cfg(feature = "cli")]
pub struct SessionManager {
    pub base_dir: PathBuf,
}

#[cfg(feature = "cli")]
impl SessionManager {
    pub fn new(base_dir: Option<&str>) -> Self {
        let base = match base_dir {
            Some(dir) => PathBuf::from(dir),
            None => dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".autogpt"),
        };
        Self { base_dir: base }
    }

    pub fn sessions_dir(&self) -> PathBuf {
        self.base_dir.join("sessions")
    }

    pub fn session_dir(&self, session_id: &str) -> PathBuf {
        self.sessions_dir().join(session_id)
    }

    pub fn ensure_dirs(&self) -> anyhow::Result<()> {
        fs::create_dir_all(self.sessions_dir())?;
        Ok(())
    }

    pub fn save(&self, session: &Session) -> anyhow::Result<()> {
        let dir = self.session_dir(&session.id);
        fs::create_dir_all(&dir)?;

        let json = serde_json::to_string_pretty(session)?;
        fs::write(dir.join("session.json"), json)?;

        if let Some(ref plan) = session.plan {
            fs::write(dir.join("implementation_plan.md"), plan)?;
        }

        if let Some(ref walkthrough) = session.walkthrough {
            fs::write(dir.join("walkthrough.md"), walkthrough)?;
        }

        if !session.tasks.is_empty() {
            fs::write(dir.join("tasks.md"), Self::render_tasks_md(&session.tasks))?;
        }

        if !session.reasoning_log.is_empty() {
            let reasoning_md = session
                .reasoning_log
                .iter()
                .enumerate()
                .map(|(i, t)| format!("## Task {} Reasoning\n\n{}\n", i + 1, t))
                .collect::<Vec<_>>()
                .join("\n");
            fs::write(dir.join("reasoning_log.md"), reasoning_md)?;
        }

        Ok(())
    }

    pub fn load(&self, session_id: &str) -> anyhow::Result<Session> {
        let path = self.session_dir(session_id).join("session.json");
        let content = fs::read_to_string(path)?;
        Ok(serde_json::from_str(&content)?)
    }

    pub fn list(&self) -> anyhow::Result<Vec<SessionEntry>> {
        let sessions_dir = self.sessions_dir();
        if !sessions_dir.exists() {
            return Ok(Vec::new());
        }

        let mut entries = Vec::new();
        for entry in fs::read_dir(&sessions_dir)? {
            let entry = entry?;
            if !entry.file_type()?.is_dir() {
                continue;
            }
            let session_file = entry.path().join("session.json");
            if !session_file.exists() {
                continue;
            }
            if let Ok(content) = fs::read_to_string(&session_file)
                && let Ok(session) = serde_json::from_str::<Session>(&content)
            {
                let completed_count = session
                    .tasks
                    .iter()
                    .filter(|t| t.status == TaskStatus::Completed)
                    .count();
                entries.push(SessionEntry {
                    id: session.id,
                    title: session.title,
                    prompt: session.prompt,
                    model: session.model,
                    provider: session.provider,
                    updated_at: session.updated_at,
                    task_count: session.tasks.len(),
                    completed_count,
                });
            }
        }

        entries.sort_by_key(|b| cmp::Reverse(b.updated_at));
        Ok(entries)
    }

    fn render_tasks_md(tasks: &[SessionTask]) -> String {
        let mut md = String::from("# Tasks\n\n");
        for task in tasks {
            let checkbox = match task.status {
                TaskStatus::Completed => "[x]",
                TaskStatus::InProgress => "[/]",
                TaskStatus::Failed => "[-]",
                TaskStatus::Skipped => "[~]",
                TaskStatus::Pending => "[ ]",
            };
            md.push_str(&format!("- {} {}\n", checkbox, task.description));
        }
        md
    }

    pub fn generate_walkthrough(session: &Session) -> String {
        let mut md = String::from("# AutoGPT Session Walkthrough\n\n");
        md.push_str(&format!("**Session:** {}\n", session.title));
        md.push_str(&format!("**ID:** {}\n", session.id));
        md.push_str(&format!(
            "**Created:** {}\n",
            session.created_at.format("%Y-%m-%d %H:%M:%S UTC")
        ));
        md.push_str(&format!(
            "**Model:** {} ({})\n",
            session.model, session.provider
        ));
        md.push_str(&format!("**Workspace:** {}\n\n", session.workspace));

        if let Some(ref plan) = session.plan {
            md.push_str("## Implementation Plan\n\n");
            md.push_str(plan);
            md.push_str("\n\n");
        }

        if !session.tasks.is_empty() {
            md.push_str("## Tasks\n\n");
            for task in &session.tasks {
                md.push_str(&format!("- {} {}\n", task.status.icon(), task.description));
            }
            md.push('\n');
        }

        if !session.files_created.is_empty() {
            md.push_str("## Files Created\n\n");
            for file in &session.files_created {
                md.push_str(&format!("- `{}` ({})\n", file.path, file.action));
            }
            md.push('\n');
        }

        md.push_str("## Conversation\n\n");
        for msg in &session.messages {
            md.push_str(&format!(
                "**{}** *({})*:\n{}\n\n",
                msg.role,
                msg.timestamp.format("%H:%M:%S"),
                msg.content
            ));
        }

        md
    }
}

#[cfg(feature = "cli")]
impl Default for SessionManager {
    fn default() -> Self {
        Self::new(None)
    }
}

// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.