supercode-interchange 0.4.17

Canonical, provider-neutral session interchange primitives for Supercode
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Helpers shared by more than one harness codec.

use super::*;

/// D7: repair tool-result/tool-call ORDERING for the Claude Code loader.
///
/// Real Claude Code transcripts are well-formed by `uuid`/`parentUuid` tree
/// structure but are NOT guaranteed to be well-formed in raw file order: async
/// tool-result delivery (or an edited turn) can write a `tool_result` `user`
/// line BEFORE the assistant `tool_use` line that owns it, even though the
/// parent/child tree itself is fine. The active-branch projection restores
/// parent-before-child order, but a result can still trail a later assistant
/// turn instead of sitting next to the assistant that owns it. Both OpenAI-
/// and Anthropic-shaped wire APIs reject either shape on `resume`. Measured
/// on a real corpus: 21/450 sessions (4.7%), 89 inverted pairs.
///
/// This reorders `messages` so every OWNED `Role::Tool` result (its
/// `tool_call_id` matches a `tool_calls` entry on some `Role::Assistant`
/// message anywhere in the list) sits immediately after the `Role::Assistant`
/// message that owns it, while leaving every other message's relative order
/// untouched. Orphan tool results — no matching call anywhere in the list —
/// are left in their ORIGINAL position, untouched; they are never moved. It
/// is a pure reorder: same message count, same multiset of messages, in/out.
///
/// Tool-call ids (`toolu_*`) are globally unique within a Claude Code session
/// — each appears exactly once as a call and once as its result — so a
/// simple id -> owning-assistant map is sufficient; no special-casing is
/// needed for sidechain (`isSidechain`) messages, since `push_claude_*`
/// already pushes those inline with their own distinct ids.
///
/// Results whose matching call is missing entirely (no owner found) are left
/// in place untouched — `ensure_tool_results_paired` (which runs right after
/// this) is responsible for synthesizing a placeholder result for any call
/// that ends up unanswered; this pass never drops or fabricates anything.
pub(super) fn reorder_tool_results_after_calls(messages: &mut Vec<ChatMessage>) {
    // 0. First pass: which tool_call_ids are actually "owned" — emitted by
    //    some assistant message anywhere in the list — and the position of
    //    that owning assistant. Owned as `String` (not borrowed) so this map
    //    can outlive the later `messages.drain(..)`.
    let mut owner_positions: HashMap<String, usize> = HashMap::new();
    for (index, m) in messages.iter().enumerate() {
        if m.role == Role::Assistant {
            for c in m.tool_calls() {
                if !c.id.is_empty() {
                    owner_positions.entry(c.id.clone()).or_insert(index);
                }
            }
        }
    }

    // Fast, cheap detection of "nothing to do": every owned result must be
    // in the contiguous tool-result block immediately following its owning
    // assistant. Checking only result-before-owner inversions is insufficient
    // after Claude's active-branch projection: that projection can put the
    // owner first while leaving its result behind a later assistant turn.
    // Mere orphans never set this flag. A canonical session returns with
    // `messages` byte-for-byte unchanged, mirroring
    // `ensure_tool_results_paired`'s own no-op guard.
    let mut contiguous_owner = None;
    let needs_reorder =
        messages
            .iter()
            .enumerate()
            .any(|(message_index, message)| match message.role {
                Role::Assistant => {
                    contiguous_owner = Some(message_index);
                    false
                }
                Role::Tool => match message
                    .tool_call_id
                    .as_deref()
                    .and_then(|id| owner_positions.get(id))
                    .copied()
                {
                    Some(owner) => Some(owner) != contiguous_owner,
                    None => {
                        // An orphan or unlinked tool message interrupts the
                        // owner's contiguous result block but never moves by
                        // itself.
                        contiguous_owner = None;
                        false
                    }
                },
                _ => {
                    contiguous_owner = None;
                    false
                }
            });
    if !needs_reorder {
        return;
    }

    // 1. Second pass: route messages into the "spine" (everything that stays
    //    at its own position — non-tool messages AND orphan tool results)
    //    versus owned tool results (pulled out, to be reattached right after
    //    their owner). Record, for each spine index that's an assistant, the
    //    set of tool_call_ids it owns.
    let mut spine: Vec<ChatMessage> = Vec::with_capacity(messages.len());
    let mut call_owner: HashMap<String, usize> = HashMap::new();
    // Buffer of (original_position, message) for every OWNED tool result,
    // built alongside the spine; a result can reference a call emitted later
    // in file order, so owner spine-index is resolved in a later step once
    // `call_owner` is complete.
    let mut owned_results: Vec<(usize, ChatMessage)> = Vec::new();

    let drained: Vec<ChatMessage> = std::mem::take(messages);
    for (orig_pos, msg) in drained.into_iter().enumerate() {
        if msg.role == Role::Tool {
            let is_owned = msg
                .tool_call_id
                .as_deref()
                .map(|id| !id.is_empty() && owner_positions.contains_key(id))
                .unwrap_or(false);
            if is_owned {
                owned_results.push((orig_pos, msg));
                continue;
            }
            // Orphan: no matching call anywhere. Treat exactly like a
            // non-tool message for placement — it joins the spine at its
            // current position and is never moved.
            spine.push(msg);
            continue;
        }
        if msg.role == Role::Assistant {
            let spine_idx = spine.len();
            for c in msg.tool_calls() {
                if !c.id.is_empty() {
                    call_owner.entry(c.id.clone()).or_insert(spine_idx);
                }
            }
        }
        spine.push(msg);
    }

    // 2. Resolve each owned result's owner spine-index now that `call_owner`
    //    is complete, then bucket results by owner spine-index. Every result
    //    here was routed as "owned" because its id was found in `owned_ids`,
    //    which was built from the exact same `tool_calls()` scan that
    //    populates `call_owner` below, so the lookup is guaranteed to hit.
    let mut buckets: HashMap<usize, Vec<(usize, ChatMessage)>> = HashMap::new();
    for (orig_pos, msg) in owned_results.into_iter() {
        let id = msg
            .tool_call_id
            .as_deref()
            .filter(|id| !id.is_empty())
            .expect("routed as owned, so tool_call_id must be a non-empty owned id");
        let idx = *call_owner
            .get(id)
            .expect("owned id must have an owning assistant in call_owner");
        buckets.entry(idx).or_default().push((orig_pos, msg));
    }
    // Keep each bucket's results in their original relative file order.
    for v in buckets.values_mut() {
        v.sort_by_key(|(pos, _)| *pos);
    }

    // 3. Rebuild: emit each spine message (which now includes orphans at
    //    their original position, untouched) in order; immediately after
    //    emitting an assistant message that owns one or more tool results,
    //    emit its owned results, in original relative order.
    let mut out: Vec<ChatMessage> = Vec::with_capacity(spine.len() + buckets.len());
    for (idx, msg) in spine.into_iter().enumerate() {
        out.push(msg);
        if let Some(results) = buckets.remove(&idx) {
            for (_, r) in results {
                out.push(r);
            }
        }
    }
    *messages = out;
}

/// Guarantee every assistant `tool_calls` entry is answered by a following tool
/// result. Interrupted/aborted turns leave a tool call with no result, which
/// many chat-completions endpoints reject when the conversation is replayed.
/// We insert a synthetic placeholder result immediately after the assistant
/// turn so the transcript stays valid for continuation. (Orphan results — a
/// tool message with no preceding call — do not occur in practice and are left
/// untouched.)
pub(super) fn ensure_tool_results_paired(messages: &mut Vec<ChatMessage>) {
    let answered: HashSet<String> = messages
        .iter()
        .filter(|m| m.role == Role::Tool)
        .filter_map(|m| m.tool_call_id.clone())
        .collect();

    // Nothing missing? Leave the vector byte-for-byte unchanged.
    let any_missing = messages.iter().any(|m| {
        m.tool_calls()
            .iter()
            .any(|c| !c.id.is_empty() && !answered.contains(&c.id))
    });
    if !any_missing {
        return;
    }

    let mut out: Vec<ChatMessage> = Vec::with_capacity(messages.len() + 4);
    for msg in messages.drain(..) {
        let synth: Vec<ChatMessage> = msg
            .tool_calls()
            .iter()
            .filter(|c| !c.id.is_empty() && !answered.contains(&c.id))
            .map(|c| {
                let mut m = ChatMessage::tool_result(
                    c.id.clone(),
                    c.function.name.clone(),
                    "[no tool result recorded — turn interrupted]".to_string(),
                );
                // TR-10: an interrupted call never executed to completion —
                // never a candidate for `ReductionKind::ToolInputElided`
                // (the "still-pending calls are never input-elided"
                // boundary).
                crate::mark_tool_error(&mut m);
                m
            })
            .collect();
        out.push(msg);
        out.extend(synth);
    }
    *messages = out;
}

/// Whether `msg` is excluded from every replay/export path — the frozen
/// cross-format discipline (`docs/interop/opencode-pi-spec.md` §2.1/§2.2/§6):
/// a message marked `compacted_out` (pre-compaction history a source harness
/// itself no longer replays) or `pi_exclude_from_context` (a pi `!!` bash
/// escape) must never reach `to_jsonl`/`to_jsonl_spliced` for ANY target
/// format, not just the one that produced the marker — so a translated
/// compacted session replays the same sliced context the source harness
/// would, instead of double-including history plus its own summary.
pub(super) fn is_replay_excluded(msg: &ChatMessage) -> bool {
    msg.metadata.get("compacted_out").map(String::as_str) == Some("true")
        || msg
            .metadata
            .get("pi_exclude_from_context")
            .map(String::as_str)
            == Some("true")
}

/// STRICT-VERBATIM line split for `raw` capture (IX-1) — the counterpart to
/// [`non_empty_lines`]'s blank-skipping/trimming PARSE view.
///
/// Splits only on `\n` (never treats `\r\n` specially), so a CRLF source's
/// `\r` survives as part of the returned line's own content; blank lines and
/// trailing-whitespace-only lines are kept verbatim rather than dropped or
/// trimmed. This is what makes `Session.raw` — populated from this at every
/// raw-capture site — byte-for-byte faithful to the source for ANY input, not
/// just well-formed LF JSONL with no blank lines.
///
/// Returns `(lines, ends_with_newline)`. `lines.join("\n")` alone cannot
/// distinguish a source that ended with a trailing newline from one that
/// didn't (both split into the same line list), so `ends_with_newline`
/// records that fact out-of-band — [`join_lines_verbatim`] is the exact
/// inverse, given both. `text == ""` yields `(vec![], false)`: an empty
/// source has zero lines, not one blank line.
pub(super) fn split_lines_verbatim(text: &str) -> (Vec<&str>, bool) {
    if text.is_empty() {
        return (Vec::new(), false);
    }
    let ends_with_newline = text.ends_with('\n');
    let body = if ends_with_newline {
        &text[..text.len() - 1]
    } else {
        text
    };
    (body.split('\n').collect(), ends_with_newline)
}

/// The exact inverse of [`split_lines_verbatim`]: reconstruct the original
/// source bytes from its verbatim lines plus the trailing-newline flag.
pub(super) fn join_lines_verbatim(lines: &[String], ends_with_newline: bool) -> String {
    let mut out = lines.join("\n");
    if ends_with_newline {
        out.push('\n');
    }
    out
}

/// PARSE-iteration view (blank/whitespace-only lines skipped, each line
/// trimmed, `\r` line endings normalized away by [`str::lines`]) — used
/// everywhere a loader walks lines looking for JSON *records*, where a blank
/// line is simply not a record and must not become a spurious parse
/// failure/empty entry. Deliberately NOT used for `raw` capture any more
/// (IX-1) — see [`split_lines_verbatim`] for that.
pub(super) fn non_empty_lines(text: &str) -> impl Iterator<Item = &str> {
    text.lines().map(str::trim).filter(|l| !l.is_empty())
}

pub(super) fn inject_first_jsonl_top_level(out: &mut String, key: &str, extension: Value) {
    let Some(line_end) = out.find('\n') else {
        return;
    };
    let Ok(mut record) = serde_json::from_str::<Value>(&out[..line_end]) else {
        return;
    };
    let Some(object) = record.as_object_mut() else {
        return;
    };
    object.insert(key.to_string(), extension);
    out.replace_range(..line_end, &record.to_string());
}

/// Remove the last conversational turn from `messages`: everything from the
/// last `user` message to the end (the user prompt plus the assistant's
/// response and any tool calls/results it triggered).
pub(super) fn remove_last_turn(messages: &mut Vec<ChatMessage>) {
    if let Some(idx) = messages.iter().rposition(|m| m.role == Role::User) {
        messages.truncate(idx);
    } else {
        messages.clear();
    }
    // IX-6 fix: the new tail exposed by `truncate` may still carry
    // `__codex_open_turn` from when it was marked (it was NOT the last
    // message at that time — items after it, now removed by the rollback,
    // intervened). A bare `function_call` arriving after the rollback is a
    // genuinely NEW turn and must get its own message, not merge into this
    // stale marked tail — close it out here so `push_codex_item`'s
    // adjacency check (`out.last()` + marker) can't be fooled by the
    // truncation re-exposing it.
    if let Some(last) = messages.last_mut() {
        last.metadata.remove("__codex_open_turn");
    }
}

fn truncate_messages(messages: &mut Vec<ChatMessage>, message_limit: usize) {
    truncate_messages_with_anchor(messages, message_limit, Vec::new());
}

pub(super) fn truncate_messages_with_anchor(
    messages: &mut Vec<ChatMessage>,
    message_limit: usize,
    preceding_users: Vec<ChatMessage>,
) {
    let limit = message_limit.max(1);
    // Anchor the numeric tail at its own human boundary. Choosing the newest
    // users anywhere in the window is not enough: after several short prompts
    // followed by a tool-heavy turn, those users can all sit near the end while
    // the tail begins in older orphaned tool activity. The UI then correctly
    // hides that activity, so increasing `tail_messages` appears to load
    // nothing and the next prompt can collapse the visible history.
    //
    // Keep up to two users from before the raw tail boundary. The nearest one
    // makes the retained activity a real turn; the preceding one preserves
    // overlap when one turn alone exceeds the whole numeric window.
    let raw_tail_start = messages.len().saturating_sub(limit);
    let anchor_limit = if messages.len() < limit {
        limit.saturating_sub(messages.len()).min(2)
    } else {
        limit.min(2)
    };
    let mut anchor_candidates = preceding_users;
    anchor_candidates.extend(
        messages[..raw_tail_start]
            .iter()
            .filter(|message| message.role == Role::User)
            .cloned(),
    );
    let mut anchors = anchor_candidates
        .into_iter()
        .rev()
        .take(anchor_limit)
        .collect::<Vec<_>>();
    anchors.reverse();

    if messages.len() <= limit && anchors.is_empty() {
        return;
    }
    let tail_count = limit.saturating_sub(anchors.len()).min(messages.len());
    let tail_start = messages.len() - tail_count;
    let mut selected = Vec::with_capacity(anchors.len() + tail_count);
    selected.append(&mut anchors);
    selected.extend(messages[tail_start..].iter().cloned());
    debug_assert_eq!(selected.len(), limit.min(messages.len() + anchor_limit));
    *messages = selected;
}

pub(super) fn truncate_session_messages(session: &mut Session, message_limit: usize) {
    truncate_messages(&mut session.messages, message_limit);
}

/// Depth of a node in the parent forest (root = 0), bounded against cycles.
pub(super) fn depth_of(mut i: usize, parent_of: &[Option<usize>]) -> usize {
    let mut d = 0;
    let mut guard = 0;
    while let Some(p) = parent_of[i] {
        if p == i || guard > parent_of.len() {
            break;
        }
        i = p;
        d += 1;
        guard += 1;
    }
    d
}

/// Namespaced line-level extension carrying the one tool-result outcome state
/// Claude cannot represent natively. Keeping this narrower than the full Grok
/// portability envelope avoids changing unrelated target-message projection.
pub(super) const SUPERCODE_TOOL_OUTCOME_KEY: &str = "_supercode_tool_outcome";

pub(super) fn restore_tool_outcome_extension(value: &Value, message: &mut ChatMessage) {
    if !crate::is_tool_error(message)
        && value
            .get(SUPERCODE_TOOL_OUTCOME_KEY)
            .and_then(Value::as_str)
            == Some("unknown")
    {
        crate::mark_tool_outcome_unknown(message);
    }
}

#[doc(hidden)]
pub fn percent_decode_path(encoded: &str) -> Option<String> {
    fn hex(byte: u8) -> Option<u8> {
        match byte {
            b'0'..=b'9' => Some(byte - b'0'),
            b'a'..=b'f' => Some(byte - b'a' + 10),
            b'A'..=b'F' => Some(byte - b'A' + 10),
            _ => None,
        }
    }

    let bytes = encoded.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0usize;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let high = *bytes.get(index + 1)?;
            let low = *bytes.get(index + 2)?;
            decoded.push(hex(high)? * 16 + hex(low)?);
            index += 3;
        } else {
            decoded.push(bytes[index]);
            index += 1;
        }
    }
    String::from_utf8(decoded).ok()
}

// ---- shared helpers -------------------------------------------------------

pub(super) fn push_text(buf: &mut String, v: Option<&Value>) {
    if let Some(Value::String(s)) = v {
        if !buf.is_empty() {
            buf.push('\n');
        }
        buf.push_str(s);
    }
}

/// Extract a Claude `tool_result` block's content, preserving non-text items
/// instead of silently dropping them:
///
/// - text blocks are concatenated;
/// - PARITY-11 (nested images, real-session-confirmed — the everyday "Read a
///   PNG / screenshot tool output" shape): `image` blocks are captured into
///   the returned `content_parts`-shaped `Vec<Value>` via
///   [`claude_image_block_to_part`] — the SAME base64/url conversion the
///   top-level `image` content-block path (`push_claude_user`) already uses
///   — instead of being flattened to the bare `[image]` marker text that used
///   to make the data unrecoverable from every writer. An unconvertible
///   source (D5 discipline — a Files-API `{"type":"file",...}` reference,
///   etc.) folds [`UNCONVERTIBLE_IMAGE_MARKER`] into the text instead of
///   vanishing, exactly like the top-level path;
/// - `tool_reference` blocks become `[tool_reference: <name>]`;
///
/// and if the block yields no text/images at all, fall back to the record's
/// `toolUseResult` field (string used directly, structured value serialized),
/// which is where Claude Code stores the actual result in many cases.
///
/// Returns `(text, images)`; callers that only need the old text-only
/// behavior can ignore the second element — every caller MUST fold non-empty
/// `images` into the resulting `ChatMessage.content_parts` themselves (this
/// function has no `ChatMessage` to attach to).
pub(super) fn extract_tool_result_content(
    content: Option<&Value>,
    tool_use_result: Option<&Value>,
) -> (String, Vec<Value>) {
    let mut parts: Vec<String> = Vec::new();
    let mut images: Vec<Value> = Vec::new();
    match content {
        Some(Value::String(s)) => {
            if !s.is_empty() {
                parts.push(s.clone());
            }
        }
        Some(Value::Array(items)) => {
            for item in items {
                match item.get("type").and_then(Value::as_str) {
                    Some("text") => {
                        if let Some(t) = item.get("text").and_then(Value::as_str) {
                            parts.push(t.to_string());
                        }
                    }
                    Some("image") => match claude_image_block_to_part(item) {
                        Some(part) => images.push(part),
                        None => parts.push(UNCONVERTIBLE_IMAGE_MARKER.to_string()),
                    },
                    Some("tool_reference") => {
                        let name = item.get("tool_name").and_then(Value::as_str).unwrap_or("?");
                        parts.push(format!("[tool_reference: {name}]"));
                    }
                    _ => {
                        if let Some(s) = item.as_str() {
                            parts.push(s.to_string());
                        }
                    }
                }
            }
        }
        Some(other) => parts.push(other.to_string()),
        None => {}
    }

    let joined = parts.join("\n");
    if !joined.trim().is_empty() || !images.is_empty() {
        return (joined, images);
    }
    // Empty tool_result content — recover from toolUseResult.
    match tool_use_result {
        Some(Value::String(s)) => (s.clone(), images),
        Some(v) => (v.to_string(), images),
        None => (joined, images),
    }
}

/// Pull readable text out of a content value that may be a plain string or an
/// array of `{ "text": "..." }`-bearing blocks (any block type).
pub(super) fn extract_text_content(v: Option<&Value>) -> String {
    match v {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Array(items)) => {
            let mut parts = Vec::new();
            for item in items {
                if let Some(t) = item.get("text").and_then(Value::as_str) {
                    parts.push(t.to_string());
                } else if let Some(s) = item.as_str() {
                    parts.push(s.to_string());
                }
            }
            parts.join("\n")
        }
        Some(other) => other.to_string(),
        None => String::new(),
    }
}

/// Extract Codex `input_image` content blocks from a `message` response_item's
/// `content` value into `content_parts` `image_url` entries — the inverse of
/// [`codex_message_content_blocks`]'s `input_image` emission (IX-5). Only a
/// block whose `image_url` is a non-empty string is recognized; anything else
/// (a missing/malformed `image_url`, a `file_id`-only reference) is left as
/// raw-only residue rather than synthesizing a corrupt/empty part — mirroring
/// the pi/opencode/Claude loaders' image-shape discipline.
pub(super) fn codex_extract_images(content: Option<&Value>) -> Vec<Value> {
    let Some(Value::Array(items)) = content else {
        return Vec::new();
    };
    items
        .iter()
        .filter(|item| item.get("type").and_then(Value::as_str) == Some("input_image"))
        .filter_map(|item| {
            let url = item.get("image_url").and_then(Value::as_str)?;
            if url.is_empty() {
                return None;
            }
            Some(serde_json::json!({"type": "image_url", "image_url": {"url": url}}))
        })
        .collect()
}

pub(super) fn value_to_arg_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

pub(super) fn push_gemini_user_parts(
    messages: &mut Vec<ChatMessage>,
    content_parts: Vec<Value>,
    timestamp: Option<&str>,
    source: &Value,
) {
    if content_parts.is_empty() {
        return;
    }
    let mut message = ChatMessage {
        role: Role::User,
        content: None,
        content_parts: Some(content_parts),
        tool_calls: None,
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    if let Some(timestamp) = timestamp {
        message
            .metadata
            .insert("timestamp".into(), timestamp.into());
    }
    restore_gemini_message_extension(source, &mut message);
    messages.push(message);
}

pub(super) fn function_call(id: &str, name: &str, arguments: String) -> ToolCall {
    ToolCall {
        id: id.to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: name.to_string(),
            arguments,
        },
    }
}

pub(super) fn tool_message(tool_call_id: &str, content: String) -> ChatMessage {
    ChatMessage {
        role: Role::Tool,
        content: Some(content),
        content_parts: None,
        tool_calls: None,
        tool_call_id: Some(tool_call_id.to_string()),
        name: None,
        metadata: Default::default(),
    }
}

/// Emit a single assistant message combining accumulated text and tool calls.
/// A turn with neither (e.g. thinking-only) produces nothing.
pub(super) fn push_assistant(out: &mut Vec<ChatMessage>, text: String, calls: Vec<ToolCall>) {
    let has_text = !text.trim().is_empty();
    if !has_text && calls.is_empty() {
        return;
    }
    out.push(ChatMessage {
        role: Role::Assistant,
        content: has_text.then_some(text),
        content_parts: None,
        tool_calls: (!calls.is_empty()).then_some(calls),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    });
}

// ---- writers --------------------------------------------------------------

/// A placeholder timestamp for SYNTHESIZED records only — WAVE-2 item 1's
/// fallback (`docs/interop` build brief): every writer now emits a message's
/// REAL source timestamp (`metadata["timestamp"]`, the canonical ISO-8601
/// field every loader populates) when one is present. `SYNTH_TS` fires only
/// for a message with no source timestamp at all — a turn synthesized/
/// appended after import (the live agent loop, a splice's appended tail,
/// ...), which was never loaded from a real per-message timestamp to begin
/// with. Both tools tolerate identical timestamps; callers that need real
/// ones for a synthesized turn can post-process.
pub(super) const SYNTH_TS: &str = "2026-01-01T00:00:00.000Z";

/// The unix-millisecond twin of [`SYNTH_TS`], for OpenCode's numeric
/// `time.created`/`time.updated` fields.
pub(super) const SYNTH_TS_MS: i64 = 1_767_225_600_000;

/// `msg`'s real source timestamp (`metadata["timestamp"]`, canonical
/// ISO-8601 — WAVE-2 item 1) when present AND well-formed, else the
/// [`SYNTH_TS`] fallback. Validated via [`crate::sidecar::rfc3339_to_ms`] (a
/// parse, not just a presence check) so an absent, empty, or malformed
/// source value all degrade to the same documented fallback rather than
/// propagating garbage verbatim. Used by every writer that emits an
/// ISO-8601 timestamp field
/// (Claude Code, Codex, pi's entry-level `timestamp`).
pub(super) fn msg_timestamp_or_synth(msg: &ChatMessage) -> &str {
    match msg.metadata.get("timestamp") {
        Some(ts) if crate::sidecar::rfc3339_to_ms(ts).is_some() => ts.as_str(),
        _ => SYNTH_TS,
    }
}

/// A format-valid (v4-shaped) but deterministic uuid, derived from a counter.
pub(super) fn synth_uuid(n: usize) -> String {
    format!("00000000-0000-4000-8000-{n:012x}")
}

pub(super) fn push_jsonl(out: &mut String, value: &Value) {
    out.push_str(&value.to_string());
    out.push('\n');
}

/// Replay a raw (verbatim) JSONL `line` into `out`, rewriting `key` to
/// `new_id` when the line parses as a JSON object carrying that key — used
/// by A12's Claude Code splice, where the session id lives at the top level
/// of (almost) every record under `key = "sessionId"`. A line that fails to
/// parse, or parses but lacks `key`, is copied through byte-for-byte
/// (nothing to patch, so nothing is reserialized).
pub(super) fn push_spliced_line(out: &mut String, line: &str, new_id: Option<&str>, key: &str) {
    if let Some(new_id) = new_id {
        if let Ok(mut v) = serde_json::from_str::<Value>(line) {
            if v.get(key).is_some() {
                v[key] = Value::String(new_id.to_string());
                out.push_str(&v.to_string());
                out.push('\n');
                return;
            }
        }
    }
    out.push_str(line);
    out.push('\n');
}

impl Session {
    pub(super) fn cwd_string(&self) -> String {
        self.meta
            .cwd
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| ".".to_string())
    }

    /// `(raw_prefix_len, message_prefix_len)` for A12 splicing: how many
    /// leading `raw` lines / `messages` came from the imported log, as
    /// opposed to being appended after import.
    ///
    /// `imported_message_count` (see its doc comment) pins the message-side
    /// boundary directly. The raw-side boundary isn't separately tracked —
    /// [`Self::from_native_str`]'s turn-appending loop pushes exactly one
    /// `raw` line per appended message, so the two lists grow by the same
    /// `appended_count` from the same starting point, and
    /// `raw.len() - appended_count` recovers it without a second counter.
    pub(super) fn spliced_prefix_lens(&self) -> (usize, usize) {
        let message_prefix_len = self
            .imported_message_count
            .unwrap_or(self.messages.len())
            .min(self.messages.len());
        let appended_count = self.messages.len() - message_prefix_len;
        let raw_prefix_len = self.raw.len().saturating_sub(appended_count);
        (raw_prefix_len, message_prefix_len)
    }
}