mentra 0.12.0

An agent runtime for tool-using LLM applications
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
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{ContentBlock, Message, Role};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct AgentTranscript {
    items: Vec<TranscriptItem>,
}

impl AgentTranscript {
    pub fn new(items: Vec<TranscriptItem>) -> Self {
        Self { items }
    }

    pub fn from_messages(messages: Vec<Message>) -> Self {
        Self {
            items: messages
                .into_iter()
                .map(transcript_item_from_message)
                .collect(),
        }
    }

    pub fn items(&self) -> &[TranscriptItem] {
        &self.items
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn push(&mut self, item: TranscriptItem) {
        self.items.push(item);
    }

    pub fn to_messages(&self) -> Vec<Message> {
        self.items
            .iter()
            .filter_map(TranscriptItem::project_message)
            .collect()
    }

    pub fn projected_messages_from(&self, start: usize) -> Vec<Message> {
        self.items
            .iter()
            .skip(start)
            .filter_map(TranscriptItem::project_message)
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TranscriptItem {
    pub kind: TranscriptKind,
    pub message: Option<Message>,
    /// Opaque per-call host metadata attached via [`TranscriptItem::with_details`]
    /// (populated from [`crate::tool::ToolOutput::details`]), keyed by
    /// `tool_use_id` because one tool-result message can carry several
    /// results. mentra never interprets these values; they survive
    /// transcript persistence and replay but are never projected into a
    /// provider request — [`TranscriptItem::project_message`] only ever
    /// returns `message`. `serde(default)` keeps transcripts persisted
    /// before this field existed deserializing unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    details: Option<BTreeMap<String, Value>>,
}

impl TranscriptItem {
    pub fn user_turn(message: Message) -> Self {
        Self {
            kind: TranscriptKind::UserTurn,
            message: Some(message),
            details: None,
        }
    }

    pub fn assistant_turn(message: Message) -> Self {
        Self {
            kind: TranscriptKind::AssistantTurn,
            message: Some(message),
            details: None,
        }
    }

    pub fn tool_exchange(message: Message, tool_use_id: Option<String>, is_error: bool) -> Self {
        Self {
            kind: TranscriptKind::ToolExchange {
                tool_use_id,
                is_error,
            },
            message: Some(message),
            details: None,
        }
    }

    pub fn canonical_context(message: Message) -> Self {
        Self {
            kind: TranscriptKind::CanonicalContext,
            message: Some(message),
            details: None,
        }
    }

    pub fn delegation_request(
        message: Message,
        delegation: DelegationArtifact,
        edge: Option<DelegationEdge>,
    ) -> Self {
        Self {
            kind: TranscriptKind::DelegationRequest { delegation, edge },
            message: Some(message),
            details: None,
        }
    }

    pub fn delegation_result(
        message: Message,
        delegation: DelegationArtifact,
        edge: Option<DelegationEdge>,
    ) -> Self {
        Self {
            kind: TranscriptKind::DelegationResult { delegation, edge },
            message: Some(message),
            details: None,
        }
    }

    pub fn compaction_summary(summary: CompactionSummary) -> Self {
        Self {
            message: Some(Message::user(ContentBlock::text(
                summary.render_for_handoff(),
            ))),
            kind: TranscriptKind::CompactionSummary { summary },
            details: None,
        }
    }

    /// Attaches opaque per-call host metadata to this item, keyed by
    /// `tool_use_id`. A no-op for an empty map, so attaching a possibly-empty
    /// collected map never turns a details-free item into one carrying
    /// `Some(empty map)`.
    pub fn with_details(mut self, details: BTreeMap<String, Value>) -> Self {
        if !details.is_empty() {
            self.details = Some(details);
        }
        self
    }

    /// This item's opaque per-call host metadata, if any. mentra never
    /// interprets these values — a host recovers its own metadata after a
    /// round through this accessor alone, without mentra knowing any host
    /// type.
    pub fn details(&self) -> Option<&BTreeMap<String, Value>> {
        self.details.as_ref()
    }

    /// Looks up this item's opaque metadata for one `tool_use_id`.
    pub fn detail(&self, tool_use_id: &str) -> Option<&Value> {
        self.details.as_ref()?.get(tool_use_id)
    }

    pub fn project_message(&self) -> Option<Message> {
        self.message.clone()
    }

    pub fn is_real_user_turn(&self) -> bool {
        matches!(self.kind, TranscriptKind::UserTurn)
    }

    pub fn is_delegation_result(&self) -> bool {
        matches!(self.kind, TranscriptKind::DelegationResult { .. })
    }

    pub fn text(&self) -> String {
        self.message.as_ref().map(Message::text).unwrap_or_default()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TranscriptKind {
    UserTurn,
    AssistantTurn,
    ToolExchange {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tool_use_id: Option<String>,
        is_error: bool,
    },
    CanonicalContext,
    MemoryRecall,
    DelegationRequest {
        delegation: DelegationArtifact,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        edge: Option<DelegationEdge>,
    },
    DelegationResult {
        delegation: DelegationArtifact,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        edge: Option<DelegationEdge>,
    },
    CompactionSummary {
        summary: CompactionSummary,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DelegationKind {
    Subagent,
    Teammate,
    Parent,
    Child,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DelegationStatus {
    Requested,
    Finished,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DelegationEdge {
    pub kind: DelegationKind,
    pub local_agent_id: String,
    pub remote_agent_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DelegationArtifact {
    pub kind: DelegationKind,
    pub agent_id: String,
    pub agent_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    pub status: DelegationStatus,
    pub task_summary: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_summary: Option<String>,
    #[serde(default)]
    pub artifacts: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CompactionSummary {
    pub goal: String,
    pub progress: String,
    #[serde(default)]
    pub decisions: Vec<String>,
    #[serde(default)]
    pub constraints: Vec<String>,
    #[serde(default)]
    pub delegated_work: Vec<String>,
    #[serde(default)]
    pub artifacts: Vec<String>,
    #[serde(default)]
    pub open_questions: Vec<String>,
    #[serde(default)]
    pub next_steps: Vec<String>,
}

impl CompactionSummary {
    pub fn render_for_handoff(&self) -> String {
        let mut lines = vec![
            "[Compaction summary]".to_string(),
            format!("Goal: {}", fallback_text(&self.goal)),
            format!("Progress: {}", fallback_text(&self.progress)),
        ];
        append_list(&mut lines, "Decisions", &self.decisions);
        append_list(&mut lines, "Constraints", &self.constraints);
        append_list(&mut lines, "Delegated work", &self.delegated_work);
        append_list(&mut lines, "Artifacts", &self.artifacts);
        append_list(&mut lines, "Open questions", &self.open_questions);
        append_list(&mut lines, "Next steps", &self.next_steps);
        lines.join("\n")
    }

    pub fn from_fallback_text(text: String) -> Self {
        Self {
            progress: text,
            next_steps: vec![
                "Review the preserved transcript tail and continue from there.".to_string(),
            ],
            ..Self::default()
        }
    }
}

pub(crate) fn transcript_item_from_message(message: Message) -> TranscriptItem {
    match message.role {
        Role::Assistant => TranscriptItem::assistant_turn(message),
        Role::User => {
            if let Some((tool_use_id, is_error)) =
                message.content.first().and_then(|block| match block {
                    ContentBlock::ToolResult {
                        tool_use_id,
                        is_error,
                        ..
                    } => Some((tool_use_id.clone(), *is_error)),
                    _ => None,
                })
            {
                TranscriptItem::tool_exchange(message, Some(tool_use_id), is_error)
            } else {
                TranscriptItem::user_turn(message)
            }
        }
        Role::Unknown(_) => TranscriptItem::user_turn(message),
    }
}

fn append_list(lines: &mut Vec<String>, label: &str, items: &[String]) {
    if items.is_empty() {
        return;
    }
    lines.push(format!("{label}:"));
    for item in items {
        lines.push(format!("- {item}"));
    }
}

fn fallback_text(text: &str) -> &str {
    if text.trim().is_empty() {
        "(none)"
    } else {
        text
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    // Old-format compatibility (M3 test 6): a transcript persisted before
    // `details` existed is exactly the JSON a details-free item serializes
    // to today (the field is `skip_serializing_if` on `None`), so proving
    // that JSON deserializes back to `details: None` proves genuinely old
    // persisted transcripts still load.
    #[test]
    fn item_without_details_serializes_and_deserializes_as_old_format() {
        let item = TranscriptItem::user_turn(Message::user(ContentBlock::text("hello")));
        let json = serde_json::to_string(&item).expect("serialize");
        assert!(
            !json.contains("details"),
            "a details-free item must serialize identically to pre-M3 transcripts, got: {json}"
        );

        let reloaded: TranscriptItem = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(reloaded.details(), None);
        assert_eq!(reloaded, item);
    }

    #[test]
    fn details_round_trip_through_json_keyed_by_tool_use_id() {
        let mut details = BTreeMap::new();
        details.insert("call-1".to_string(), json!({ "secret": "shh" }));
        let item = TranscriptItem::tool_exchange(
            Message::user(ContentBlock::text("result")),
            Some("call-1".to_string()),
            false,
        )
        .with_details(details.clone());

        let json = serde_json::to_string(&item).expect("serialize");
        let reloaded: TranscriptItem = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(reloaded.details(), Some(&details));
        assert_eq!(reloaded.detail("call-1"), Some(&json!({ "secret": "shh" })));
        assert_eq!(reloaded.detail("call-2"), None);
    }

    #[test]
    fn with_details_is_a_no_op_for_an_empty_map() {
        let item = TranscriptItem::user_turn(Message::user(ContentBlock::text("hello")))
            .with_details(BTreeMap::new());
        assert_eq!(item.details(), None);
    }

    // M3 test 2 (projection-boundary half): `to_messages()`/`project_message`
    // are the single place internal transcript state turns into what a
    // provider request carries (`Message`/`ContentBlock`) — proving details
    // never appears in that projection, independent of any live agent
    // plumbing, is what makes "provider requests receive only content" true
    // by construction rather than by convention. The live round-trip through
    // a real model request is covered by
    // `agent::tests::tool_output::structured_tool_projects_content_and_hides_details_from_provider`.
    #[test]
    fn to_messages_projection_never_carries_details() {
        let mut details = BTreeMap::new();
        details.insert("call-1".to_string(), json!({ "secret": "shh" }));
        let transcript = AgentTranscript::new(vec![
            TranscriptItem::user_turn(Message::user(ContentBlock::text("go"))),
            TranscriptItem::assistant_turn(Message::assistant(ContentBlock::ToolUse {
                id: "call-1".to_string(),
                name: "structured_details_tool".to_string(),
                input: json!({}),
            })),
            TranscriptItem::tool_exchange(
                Message::user(ContentBlock::ToolResult {
                    tool_use_id: "call-1".to_string(),
                    content: crate::tool::ToolResultContent::Structured(json!({ "answer": 42 })),
                    is_error: false,
                }),
                Some("call-1".to_string()),
                false,
            )
            .with_details(details),
        ]);

        let projected = serde_json::to_string(&transcript.to_messages()).expect("serialize");
        assert!(projected.contains("answer"), "content must still project");
        assert!(!projected.contains("secret"));
        assert!(!projected.contains("shh"));
    }
}