agent-first-mail 0.3.0

Let your AI agent work your inbox — email pulled into plain files it reads, sorts, and drafts on your machine, with nothing sent until you confirm.
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
mod execute;
mod io;
mod preview;

use execute::*;
use io::*;
use preview::*;

use crate::config::{ActionStep, ActionStepOn, MailConfig, SpecialUseKind};
use crate::error::{AppError, Result};
use crate::frontmatter::DraftFrontmatter;
use crate::progress::ProgressCallback;
use crate::types::{
    MessageActionPush, MessagePushAction, OutboundAction, OutboundPush, PushItem, PushLocation,
    PushPayload, PushStepState, PushStepStatus,
};
use crate::util::write_string_atomic;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Clone, Debug)]
pub struct RemovedOutbound {
    pub push_id: String,
    pub action: OutboundAction,
}

#[derive(Clone, Debug)]
pub struct RemovedMessagePush {
    pub push_id: String,
}

pub fn queue_outbound(
    root: &Path,
    case_uid: &str,
    draft_name: &str,
    action: OutboundAction,
) -> Result<Value> {
    let existing = find_outbound_item(root, case_uid, draft_name)?;
    let push_id = existing
        .as_ref()
        .map(|item| item.push_id.clone())
        .unwrap_or_else(|| unique_push_id(root));
    let push_dir = root.join(".afmail/push");
    create_dir_all(&push_dir)?;
    let now = crate::store::now_rfc3339();
    let existing_outbound = existing.as_ref().and_then(|item| item.outbound());
    let same_action = existing_outbound.is_some_and(|outbound| outbound.action == action);
    let step_states = if same_action {
        existing
            .as_ref()
            .map(|item| item.step_states.clone())
            .unwrap_or_default()
    } else {
        Vec::new()
    };
    let item = PushItem {
        schema_name: "push_item".to_string(),
        schema_version: 1,
        push_id: push_id.clone(),
        payload: PushPayload::Outbound(Box::new(OutboundPush {
            action,
            case_uid: case_uid.to_string(),
            draft_name: draft_name.to_string(),
            draft_uid_validity: existing_outbound.and_then(|outbound| outbound.draft_uid_validity),
            draft_uid: existing_outbound.and_then(|outbound| outbound.draft_uid),
        })),
        created_rfc3339: existing
            .as_ref()
            .map(|item| item.created_rfc3339.clone())
            .unwrap_or_else(|| now.clone()),
        updated_rfc3339: now,
        attempt_count: if same_action {
            existing.as_ref().map_or(0, |item| item.attempt_count)
        } else {
            0
        },
        step_states,
        last_error: None,
    };
    write_item(root, &item)?;
    Ok(json!({
        "code": "push_queued",
        "push_id": push_id,
        "kind": "outbound",
        "action": action.as_str(),
        "case_uid": case_uid,
        "draft_name": draft_name
    }))
}

pub(crate) fn find_outbound_for_draft(
    root: &Path,
    case_uid: &str,
    draft_name: &str,
) -> Result<Option<PushItem>> {
    find_outbound_item(root, case_uid, draft_name)
}

pub fn queue_action_steps(
    root: &Path,
    kind: &str,
    message_ids: &[String],
    locations: &[PushLocation],
    steps: &[ActionStep],
    reply_to_message_id: Option<String>,
) -> Result<Option<PushItem>> {
    if locations.is_empty() || steps.is_empty() {
        return Ok(None);
    }
    let action = MessagePushAction::from_kind(kind).ok_or_else(|| {
        AppError::new(
            "push_item_invalid",
            format!("unsupported message push action kind: {kind}"),
        )
    })?;
    let push_dir = root.join(".afmail/push");
    create_dir_all(&push_dir)?;
    let push_id = unique_push_id(root);
    let now = crate::store::now_rfc3339();
    let item = PushItem {
        schema_name: "push_item".to_string(),
        schema_version: 1,
        push_id,
        payload: PushPayload::MessageAction(MessageActionPush {
            action,
            message_ids: message_ids.to_vec(),
            locations: locations.to_vec(),
            steps: steps.to_vec(),
            reply_to_message_id,
        }),
        created_rfc3339: now.clone(),
        updated_rfc3339: now,
        attempt_count: 0,
        step_states: Vec::new(),
        last_error: None,
    };
    write_item(root, &item)?;
    Ok(Some(item))
}

#[derive(Clone, Debug, Default, serde::Serialize)]
pub struct PushStatus {
    /// Outbound drafts queued to save or send.
    pub drafts: usize,
    /// Case-membership flag operations queued.
    pub case: usize,
    /// Archive moves queued, not yet applied on the server.
    pub archive: usize,
    /// Spam (junk) moves queued, not yet applied on the server.
    pub spam: usize,
    /// Trash moves queued, not yet applied on the server.
    pub trash: usize,
}

pub fn push_status(root: &Path) -> Result<PushStatus> {
    let mut status = PushStatus::default();
    for item in sorted_items(root)? {
        match item_summary_label(&item) {
            "drafts" => status.drafts += 1,
            "case" => status.case += 1,
            "archive" => status.archive += 1,
            "spam" => status.spam += 1,
            "trash" => status.trash += 1,
            _ => {}
        }
    }
    Ok(status)
}

pub fn list(root: &Path) -> Result<Value> {
    let items = sorted_items(root)?;
    Ok(json!({
        "code": "push_list",
        "count": items.len(),
        "items": items
    }))
}

pub(crate) fn pending_items(root: &Path) -> Result<Vec<PushItem>> {
    sorted_items(root)
}

pub fn push_with_progress(
    root: &Path,
    confirmed: bool,
    progress: Option<&mut ProgressCallback<'_>>,
) -> Result<Value> {
    let mut progress = progress;
    let items = sorted_items(root)?;
    let config = MailConfig::load(root)?;
    if !confirmed {
        crate::progress::emit(
            &mut progress,
            "push_preview",
            json!({
                "item_count": items.len(),
            }),
        );
        let rendered = items
            .iter()
            .map(|item| {
                let outbound = item.outbound();
                Ok(json!({
                    "push_id": item.push_id,
                    "kind": item.kind(),
                    "display_kind": item.display_kind(),
                    "actions": actions_for(root, &config, item)?,
                    "case_uid": outbound.map(|outbound| outbound.case_uid.as_str()),
                    "draft_name": outbound.map(|outbound| outbound.draft_name.as_str()),
                    "action": outbound.map(|outbound| outbound.action.as_str())
                }))
            })
            .collect::<Result<Vec<_>>>()?;
        return Ok(json!({
            "code": "push_dry_run",
            "confirmed": false,
            "hint": preview_hint(),
            "items": rendered,
            "count": rendered.len()
        }));
    }

    let remote = crate::remote::ImapSmtpRemote::new(&config);
    let mut pushed = 0usize;
    let mut failed = 0usize;
    let mut failures = Vec::new();
    let item_count = items.len();
    crate::progress::emit(
        &mut progress,
        "push_start",
        json!({
            "item_count": item_count,
        }),
    );
    for (index, mut item) in items.into_iter().enumerate() {
        let progress_context = PushProgressContext {
            item_index: index,
            item_count,
        };
        crate::progress::emit(
            &mut progress,
            "push_item_start",
            push_item_progress_fields(&item, index, item_count, None),
        );
        let result = match &item.payload {
            PushPayload::Outbound(_) => push_outbound(
                root,
                &config,
                &remote,
                &mut item,
                progress_context,
                progress.as_deref_mut(),
            ),
            PushPayload::MessageAction(_) => push_action_steps(
                root,
                &config,
                &remote,
                &mut item,
                progress_context,
                progress.as_deref_mut(),
            ),
        };
        match result {
            Ok(()) => {
                let workspace = crate::store::Workspace::at(root);
                let transaction = workspace.begin_transaction(
                    "push_commit",
                    vec![
                        format!(".afmail/push/{}.json", item.push_id),
                        "cases".to_string(),
                        "messages".to_string(),
                    ],
                )?;
                workspace.consume_outbound_draft_after_push(&item, &config)?;
                delete_item(root, &item)?;
                workspace.clear_pending_push_item(&item)?;
                transaction.commit()?;
                let _ = audit_push(root, "push_succeeded", &item, None);
                pushed += 1;
                crate::progress::emit(
                    &mut progress,
                    "push_item_done",
                    push_item_progress_fields(&item, index, item_count, None),
                );
            }
            Err(err) => {
                let _ = audit_push(root, "push_failed", &item, Some(&err));
                failed += 1;
                failures.push(json!({
                    "push_id": item.push_id,
                    "error_code": err.error_code,
                    "error": err.message
                }));
                item.attempt_count += 1;
                item.updated_rfc3339 = crate::store::now_rfc3339();
                item.last_error = Some(err.to_string());
                write_item(root, &item)?;
                crate::store::Workspace::at(root)
                    .mark_pending_push_error(&item, &err.to_string())?;
                crate::progress::emit(
                    &mut progress,
                    "push_item_failed",
                    push_item_progress_fields(&item, index, item_count, Some(&err)),
                );
            }
        }
    }
    crate::progress::emit(
        &mut progress,
        "push_done",
        json!({
            "item_count": item_count,
            "pushed_count": pushed,
            "failed_count": failed,
        }),
    );
    Ok(json!({
        "code": "push_result",
        "confirmed": true,
        "pushed_count": pushed,
        "failed_count": failed,
        "failures": failures
    }))
}

fn push_item_progress_fields(
    item: &PushItem,
    index: usize,
    item_count: usize,
    err: Option<&AppError>,
) -> Value {
    let mut value = json!({
        "push_id": item.push_id.as_str(),
        "kind": item.kind(),
        "display_kind": item.display_kind(),
        "index": index + 1,
        "item_count": item_count,
    });
    if let Some(err) = err {
        if let Value::Object(map) = &mut value {
            map.insert("error_code".to_string(), json!(err.error_code));
            map.insert("error".to_string(), json!(err.message.as_str()));
            map.insert("retryable".to_string(), json!(err.retryable));
        }
    }
    value
}

fn audit_push(root: &Path, kind: &str, item: &PushItem, err: Option<&AppError>) -> Result<()> {
    let mut targets = vec![json!({"kind": "push", "id": item.push_id.as_str()})];
    if let Some(outbound) = item.outbound() {
        targets.push(json!({"kind": "case", "id": outbound.case_uid.as_str()}));
    } else {
        targets.extend(
            item.message_ids()
                .iter()
                .map(|message_id| json!({"kind": "message", "id": message_id})),
        );
    }
    let mut fields = json!({
        "push_id": item.push_id.as_str(),
        "push_kind": item.display_kind(),
        "succeeded_step_count": item.succeeded_step_count(),
        "attempt_count": item.attempt_count,
    });
    if let Some(outbound) = item.outbound() {
        if let Value::Object(map) = &mut fields {
            map.insert("case_uid".to_string(), json!(outbound.case_uid.as_str()));
            map.insert(
                "draft_name".to_string(),
                json!(outbound.draft_name.as_str()),
            );
            map.insert("action".to_string(), json!(outbound.action.as_str()));
        }
    }
    if let Some(err) = err {
        if let Value::Object(map) = &mut fields {
            map.insert("error_code".to_string(), json!(err.error_code));
            map.insert("error".to_string(), json!(err.message.as_str()));
            map.insert("retryable".to_string(), json!(err.retryable));
        }
    }
    crate::store::Workspace::at(root).append_audit_event(kind, targets, None, fields)
}

pub fn remove_outbound_for_draft(
    root: &Path,
    case_uid: &str,
    draft_name: &str,
) -> Result<Vec<RemovedOutbound>> {
    let items = read_items(root)?
        .into_iter()
        .filter(|item| {
            item.outbound().is_some_and(|outbound| {
                outbound.case_uid == case_uid && outbound.draft_name == draft_name
            })
        })
        .collect::<Vec<_>>();
    let mut removed = Vec::new();
    for item in items {
        removed.push(RemovedOutbound {
            push_id: item.push_id.clone(),
            action: item
                .outbound()
                .map(|outbound| outbound.action)
                .unwrap_or(OutboundAction::Send),
        });
        delete_item(root, &item)?;
    }
    Ok(removed)
}

pub fn remove_pending_message_pushes(
    root: &Path,
    message_id: &str,
    kind: &str,
) -> Result<Vec<RemovedMessagePush>> {
    let action = MessagePushAction::from_kind(kind).ok_or_else(|| {
        AppError::new(
            "push_item_invalid",
            format!("unsupported message push action kind: {kind}"),
        )
    })?;
    let items = read_items(root)?
        .into_iter()
        .filter(|item| {
            item.message_action().is_some_and(|payload| {
                payload.action == action
                    && (payload.message_ids.iter().any(|id| id == message_id)
                        || payload
                            .locations
                            .iter()
                            .any(|loc| loc.message_id == message_id))
            })
        })
        .collect::<Vec<_>>();
    if let Some(item) = items.iter().find(|item| item.has_started_steps()) {
        return Err(AppError::new(
            "push_already_started",
            format!(
                "push item already started and cannot be undone locally: {}",
                item.push_id
            ),
        ));
    }

    let mut removed = Vec::new();
    for mut item in items {
        let push_id = item.push_id.clone();
        if let Some(payload) = item.message_action_mut() {
            payload.message_ids.retain(|id| id != message_id);
            payload.locations.retain(|loc| loc.message_id != message_id);
        }
        let empty = item
            .message_action()
            .is_some_and(|payload| payload.message_ids.is_empty() && payload.locations.is_empty());
        if empty {
            delete_item(root, &item)?;
        } else {
            item.updated_rfc3339 = crate::store::now_rfc3339();
            write_item(root, &item)?;
        }
        removed.push(RemovedMessagePush { push_id });
    }
    Ok(removed)
}

fn preview_hint() -> &'static str {
    "No remote changes were made. Re-run with --confirm to apply queued effects."
}