txcript 0.10.0

Convert coding-agent session transcripts between harness formats.
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Canonical model used as the conversion hub.
//!
//! Where harnesses disagree on representation, this module uses one canonical
//! shape. Harness-specific detail needed for same-harness round trips lives in
//! typed optional fields. Opaque JSON is limited to open boundaries: unmodeled
//! tool inputs/outputs and the [`Tool::Raw`] catch-all for MCP and unknown
//! tools.
//!
//! A [`Transcript<Common>`](crate::Transcript) pairs a [`Meta`] with a
//! `Vec<Message>`. The model is harness-agnostic: it does not record where it
//! came from.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Session-level metadata, common to every harness.
///
/// Harness-specific header fields do not live here; they belong to the native
/// [`Body`](crate::Harness::Body) and are regenerated by
/// [`from_common`](crate::Codec::from_common).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Meta {
    /// Session identifier, as the originating harness knows it.
    pub id: String,
    /// When the session started.
    pub timestamp: DateTime<Utc>,
    /// Working directory the session ran in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Git branch checked out at session time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_branch: Option<String>,
    /// Human-facing title, if the harness records one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Version of the CLI that produced the session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cli_version: Option<String>,
    /// Primary model used across the session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Who authored a message. Tool results ride on [`Role::User`] messages, per
/// the Anthropic convention every harness is normalized into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Assistant,
}

/// One turn in the conversation: a role and its content blocks, plus the
/// assistant-only attribution fields when present.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
    pub role: Role,
    pub content: Vec<Block>,
    pub timestamp: DateTime<Utc>,
    /// Model that produced this turn (assistant only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Why the turn ended (assistant only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<StopReason>,
    /// Token accounting for the turn (assistant only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
}

/// A single content block. Tagged by `type` on the wire to match the Anthropic
/// block shape every harness is reconciled against.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Block {
    /// Plain text.
    Text { text: String },
    /// Model reasoning. `signature`/`encrypted` carry the opaque provider
    /// reasoning token (Anthropic signature, codex `encrypted_content`) so a
    /// same-harness round-trip can replay it verbatim.
    Thinking {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        encrypted: Option<String>,
    },
    /// A tool invocation. The `id` pairs it with its [`Block::ToolResult`].
    ToolUse { id: String, tool: Tool },
    /// The outcome of a tool invocation. Lives on a [`Role::User`] message.
    ToolResult {
        tool_use_id: String,
        content: ToolOutput,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        is_error: bool,
    },
    /// An inline image.
    Image { source: ImageSource },
    /// A generated or attached file. Unlike an image, an artifact is kept as
    /// a named file so target harnesses can expose it through their native
    /// file or artifact mechanism.
    Artifact { artifact: Artifact },
}

/// Why an assistant turn ended. `Other` keeps any harness-specific reason
/// round-trippable rather than collapsing it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    /// The model finished its turn normally.
    EndTurn,
    /// The model stopped to call a tool.
    ToolUse,
    /// The output token limit was hit.
    MaxTokens,
    /// A stop sequence was produced.
    StopSequence,
    /// The turn was cancelled or aborted.
    Aborted,
    /// The turn ended in an error.
    Error,
    /// Any reason not in the canonical set, preserved verbatim.
    Other(String),
}

/// Token accounting for one assistant turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Usage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_read_input_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_creation_input_tokens: Option<u64>,
}

/// A base64-encoded inline image.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageSource {
    /// Encoding, e.g. `"base64"`.
    #[serde(rename = "type")]
    pub source_type: String,
    /// MIME type, e.g. `"image/png"`.
    pub media_type: String,
    /// The encoded bytes.
    pub data: String,
}

/// A named file carried by a conversation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
    /// Stable source identity when the harness supplies one.
    pub id: String,
    /// Human-facing filename or title.
    pub name: String,
    /// The artifact contents or a durable local path to them.
    pub source: ArtifactSource,
}

impl Artifact {
    /// A readable fallback for harnesses without a native artifact carrier.
    #[must_use]
    pub fn display_text(&self) -> String {
        match &self.source {
            ArtifactSource::Text { text, .. } => format!("[artifact: {}]\n{text}", self.name),
            ArtifactSource::Base64 { .. } => format!("[artifact: {}]", self.name),
            ArtifactSource::Path { path, .. } => format!("[artifact: {}] {path}", self.name),
        }
    }
}

/// Where an artifact's contents live.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ArtifactSource {
    /// Textual content supplied inline by the source harness.
    Text {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_type: Option<String>,
    },
    /// Binary content encoded as base64.
    Base64 {
        data: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_type: Option<String>,
    },
    /// A file already materialized on the local machine.
    Path {
        path: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_type: Option<String>,
    },
}

/// The result payload of a tool call: text, or the harness's structured
/// output kept as JSON.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolOutput {
    Text(String),
    Json(Value),
}

/// A canonical tool invocation.
///
/// Known tools are normalized to Claude-canonical names with typed arguments.
/// Everything else — MCP tools (`mcp__*`), harness-private tools, anything
/// unmodeled — lands in [`Tool::Raw`] with its name and untouched input.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "name")]
pub enum Tool {
    /// A command the *user* ran at the harness itself — a slash command, not
    /// a model tool call. It rides on a [`Role::User`] turn, and whatever the
    /// harness printed back arrives as the paired [`Block::ToolResult`].
    ///
    /// The leading `/` in `name` is what distinguishes it canonically: no
    /// model-facing tool name may start with one, so every codec and renderer
    /// round-trips it through [`Tool::from_canonical`] without a special case.
    /// (`command` rather than `name`: the enum is tagged by `name`, so a
    /// field of that name would collide with the tag on the wire.)
    Command {
        /// Canonical name including the leading slash, e.g. `"/release"`.
        command: String,
        /// Everything the user typed after the command name, when any.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        args: Option<String>,
    },
    Read {
        file_path: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        offset: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        limit: Option<u64>,
    },
    Write {
        file_path: String,
        content: String,
    },
    Edit {
        file_path: String,
        old_string: String,
        new_string: String,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        replace_all: bool,
    },
    MultiEdit {
        file_path: String,
        edits: Vec<EditOp>,
    },
    Bash {
        command: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        workdir: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        run_in_background: bool,
    },
    /// MCP tools, harness-private tools, and anything whose input doesn't fit
    /// a typed variant. Holds the canonical name and the untouched input;
    /// always lossless.
    Raw {
        tool_name: String,
        input: Value,
    },
}

impl Tool {
    /// Build a [`Tool`] from a *canonical* tool name and input — names and
    /// argument keys already in the Claude convention (`Read`/`Edit`/`Bash`,
    /// `file_path`/`old_string`/…).
    ///
    /// A typed variant is used only when the input fits its schema exactly;
    /// any unexpected key falls through to [`Tool::Raw`]. The mapping is
    /// lossless.
    #[must_use]
    pub fn from_canonical(name: &str, input: Value) -> Tool {
        // Deserializing from `&Value` copies each string once, straight into
        // the typed struct — no intermediate clone of the whole input tree —
        // and leaves `input` intact for the `Tool::Raw` fallback.
        fn typed<A: for<'de> Deserialize<'de>>(input: &Value) -> Option<A> {
            A::deserialize(input).ok()
        }
        match name {
            // No model-facing tool name starts with a slash, so the prefix
            // alone identifies a user command — no name registry to keep in
            // sync as harnesses add commands.
            _ if name.starts_with('/') => typed::<CommandArgs>(&input)
                .map(|a| Tool::Command {
                    command: name.to_string(),
                    args: a.args,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            "Read" => typed::<ReadArgs>(&input)
                .map(|a| Tool::Read {
                    file_path: a.file_path,
                    offset: a.offset,
                    limit: a.limit,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            "Write" => typed::<WriteArgs>(&input)
                .map(|a| Tool::Write {
                    file_path: a.file_path,
                    content: a.content,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            "Edit" => typed::<EditArgs>(&input)
                .map(|a| Tool::Edit {
                    file_path: a.file_path,
                    old_string: a.old_string,
                    new_string: a.new_string,
                    replace_all: a.replace_all,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            "MultiEdit" => typed::<MultiEditArgs>(&input)
                .map(|a| Tool::MultiEdit {
                    file_path: a.file_path,
                    edits: a.edits,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            "Bash" => typed::<BashArgs>(&input)
                .map(|a| Tool::Bash {
                    command: a.command,
                    workdir: a.workdir,
                    timeout_ms: a.timeout_ms,
                    description: a.description,
                    run_in_background: a.run_in_background,
                })
                .unwrap_or(Tool::Raw {
                    tool_name: name.to_string(),
                    input,
                }),
            other => Tool::Raw {
                tool_name: other.to_string(),
                input,
            },
        }
    }

    /// Inverse of [`Tool::from_canonical`]: the canonical name and input for
    /// this tool, ready for a codec to denormalize into a harness's native
    /// names and keys.
    #[must_use]
    pub fn to_canonical(&self) -> (String, Value) {
        let value = |v: serde_json::Result<Value>| v.unwrap_or(Value::Null);
        match self {
            Tool::Command { command, args } => (
                command.clone(),
                value(serde_json::to_value(CommandArgs {
                    args: args.as_deref(),
                })),
            ),
            Tool::Read {
                file_path,
                offset,
                limit,
            } => (
                "Read".into(),
                value(serde_json::to_value(ReadArgs {
                    file_path: file_path.as_str(),
                    offset: *offset,
                    limit: *limit,
                })),
            ),
            Tool::Write { file_path, content } => (
                "Write".into(),
                value(serde_json::to_value(WriteArgs {
                    file_path: file_path.as_str(),
                    content: content.as_str(),
                })),
            ),
            Tool::Edit {
                file_path,
                old_string,
                new_string,
                replace_all,
            } => (
                "Edit".into(),
                value(serde_json::to_value(EditArgs {
                    file_path: file_path.as_str(),
                    old_string: old_string.as_str(),
                    new_string: new_string.as_str(),
                    replace_all: *replace_all,
                })),
            ),
            Tool::MultiEdit { file_path, edits } => (
                "MultiEdit".into(),
                value(serde_json::to_value(MultiEditArgs {
                    file_path: file_path.as_str(),
                    edits: edits.as_slice(),
                })),
            ),
            Tool::Bash {
                command,
                workdir,
                timeout_ms,
                description,
                run_in_background,
            } => (
                "Bash".into(),
                value(serde_json::to_value(BashArgs {
                    command: command.as_str(),
                    workdir: workdir.as_deref(),
                    timeout_ms: *timeout_ms,
                    description: description.as_deref(),
                    run_in_background: *run_in_background,
                })),
            ),
            Tool::Raw { tool_name, input } => (tool_name.clone(), input.clone()),
        }
    }
}

// Argument structs for the typed tools. `deny_unknown_fields` is what makes
// `from_canonical` lossless: an input carrying a key we don't model fails to
// parse and falls back to `Tool::Raw` rather than silently losing the key.
//
// Generic over the string type so both directions use one schema:
// `from_canonical` deserializes owned strings; `to_canonical` serializes
// borrowed strings.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CommandArgs<S = String> {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    args: Option<S>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ReadArgs<S = String> {
    file_path: S,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    offset: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    limit: Option<u64>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WriteArgs<S = String> {
    file_path: S,
    content: S,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EditArgs<S = String> {
    file_path: S,
    old_string: S,
    new_string: S,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    replace_all: bool,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct MultiEditArgs<S = String, E = Vec<EditOp>> {
    file_path: S,
    edits: E,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct BashArgs<S = String> {
    command: S,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    workdir: Option<S>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    timeout_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    description: Option<S>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    run_in_background: bool,
}

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

    /// A known tool with a known schema becomes the typed variant, and round
    /// trips back to the same canonical name and input.
    #[test]
    fn typed_tool_round_trips() {
        let input = json!({
            "file_path": "/a/b.rs",
            "old_string": "x",
            "new_string": "y",
        });
        let tool = Tool::from_canonical("Edit", input.clone());
        assert!(matches!(tool, Tool::Edit { .. }));
        let (name, back) = tool.to_canonical();
        assert_eq!(name, "Edit");
        assert_eq!(back, input);
    }

    /// `replace_all` survives the round trip when set.
    #[test]
    fn edit_preserves_replace_all() {
        let input = json!({
            "file_path": "/a", "old_string": "x", "new_string": "y", "replace_all": true,
        });
        let (_, back) = Tool::from_canonical("Edit", input.clone()).to_canonical();
        assert_eq!(back, input);
    }

    /// Unmodeled keys on known tools fall back to `Raw` without dropping input.
    #[test]
    fn unknown_key_on_known_tool_falls_back_to_raw_losslessly() {
        let input = json!({"file_path": "/a", "surprise": 1});
        let tool = Tool::from_canonical("Read", input.clone());
        match &tool {
            Tool::Raw {
                tool_name,
                input: kept,
            } => {
                assert_eq!(tool_name, "Read");
                assert_eq!(*kept, input);
            }
            other => panic!("expected Raw, got {other:?}"),
        }
        assert_eq!(tool.to_canonical(), ("Read".to_string(), input));
    }

    /// MCP and unknown tools pass through as `Raw` with name and input intact.
    #[test]
    fn mcp_tool_is_raw() {
        let input = json!({"q": "hello"});
        let tool = Tool::from_canonical("mcp__search__query", input.clone());
        assert_eq!(
            tool.to_canonical(),
            ("mcp__search__query".to_string(), input)
        );
    }

    /// An unknown key on an individual edit demotes the whole call to `Raw`,
    /// exactly like an unknown key on the call itself — nothing is silently
    /// dropped.
    #[test]
    fn multi_edit_with_unknown_edit_key_is_raw() {
        let input = json!({
            "file_path": "/f",
            "edits": [{"old_string": "x", "new_string": "y", "surprise": 1}],
        });
        let tool = Tool::from_canonical("MultiEdit", input.clone());
        assert!(matches!(tool, Tool::Raw { .. }), "got {tool:?}");
        assert_eq!(tool.to_canonical(), ("MultiEdit".to_string(), input));
    }

    /// Bash preserves optional fields such as description and timeout.
    #[test]
    fn bash_keeps_incidental_fields() {
        let input = json!({"command": "ls", "description": "list", "timeout_ms": 5000});
        let tool = Tool::from_canonical("Bash", input.clone());
        assert!(matches!(tool, Tool::Bash { .. }));
        assert_eq!(tool.to_canonical().1, input);
    }
}

/// One find/replace within a [`Tool::MultiEdit`].
// deny_unknown_fields keeps the lossless contract: an edit carrying a key
// this struct doesn't model must fail the typed parse so the whole call
// demotes to `Tool::Raw`, instead of silently dropping the key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EditOp {
    pub old_string: String,
    pub new_string: String,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub replace_all: bool,
}