brokk-mj-transcript 2.72.0

Transcript projection and presentation for Mjolnir
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
use super::*;

/// Fold the ACP v1 display-terminal extension into the same durable records
/// used for client-owned terminals. Metadata on updates is not part of
/// `ToolCallUpdateFields`, so `ToolCall::update` alone loses these bytes.
pub(super) fn apply_terminal_metadata(
    item: &mut TranscriptItem,
    meta: Option<&serde_json::Map<String, Value>>,
) {
    let Some(meta) = meta else { return };
    let TranscriptBody::Tool {
        terminal_outputs,
        terminal_refs,
        ..
    } = &mut item.body
    else {
        return;
    };

    #[derive(Deserialize)]
    struct Output {
        terminal_id: String,
        data: String,
    }
    #[derive(Deserialize)]
    struct Exit {
        terminal_id: String,
        exit_code: Option<u32>,
        signal: Option<String>,
    }
    let exit = meta.get("terminal_exit").and_then(|value| {
        serde_json::from_value::<Exit>(value.clone())
            .inspect_err(|error| tracing::warn!(%error, "invalid ACP terminal exit metadata"))
            .ok()
    });
    for key in ["terminal_output", "terminal_output_delta", "terminal_exit"] {
        let Some(value) = meta.get(key) else { continue };
        let output = if key == "terminal_exit" {
            None
        } else {
            match serde_json::from_value::<Output>(value.clone()) {
                Ok(output) => Some(output),
                Err(error) => {
                    tracing::warn!(%error, key, "invalid ACP terminal output metadata");
                    continue;
                }
            }
        };
        let Some(id) = output
            .as_ref()
            .map(|output| &output.terminal_id)
            .or_else(|| exit.as_ref().map(|exit| &exit.terminal_id))
        else {
            continue;
        };
        if !terminal_refs.contains(id) {
            terminal_refs.push(id.clone());
        }
        let record = match terminal_outputs
            .iter()
            .position(|record| &record.terminal_id == id)
        {
            Some(index) => &mut terminal_outputs[index],
            None => {
                terminal_outputs.push(TerminalOutputRecord {
                    terminal_id: id.clone(),
                    output: Default::default(),
                    truncated: false,
                    exit_code: None,
                    signal: None,
                });
                terminal_outputs
                    .last_mut()
                    .expect("just inserted terminal output")
            }
        };
        if let Some(output) = output {
            // Older Codex bridges use terminal_output for streamed chunks,
            // then send an exit without output. Output accompanying an exit
            // is a final snapshot; the explicit delta channel always appends.
            if key == "terminal_output"
                && exit
                    .as_ref()
                    .is_some_and(|exit| exit.terminal_id == record.terminal_id)
            {
                record.output = mj_core::packed_text::PackedText::plain(output.data);
                record.truncated = false;
            } else {
                let mut text = std::mem::take(&mut record.output).into_text();
                text.push_str(&output.data);
                record.output = mj_core::packed_text::PackedText::plain(text);
            }
            let mut text = std::mem::take(&mut record.output).into_text();
            record.truncated |=
                mj_core::transcript::truncate_string_start(&mut text, 4 * 1024 * 1024);
            record.output = mj_core::packed_text::PackedText::plain(text);
        } else if let Some(exit) = &exit {
            record.exit_code = exit.exit_code;
            record.signal = exit.signal.clone();
            record.output = std::mem::take(&mut record.output).into_text().into();
        }
    }
}

/// Stable id of the standalone item that holds a terminal's output until a
/// tool call refers to it.
pub(super) fn terminal_item_id(terminal_id: &str) -> String {
    format!("terminal:{terminal_id}")
}

/// The terminal ids one stored ACP tool call refers to. This is the only place
/// that reads terminal content out of a call, so attaching output and
/// consuming a parked item cannot disagree about what a call refers to.
///
/// Content hel cannot read as an ACP block names no terminal; the renderer
/// already reports such a call as invalid, so this hides no failure.
pub(crate) use mj_core::transcript::tool_call_terminal_ids;

/// The output already recorded for `terminal_id`, wherever it is parked.
pub(super) fn find_terminal_record(
    index: &ProjectionIndex,
    terminal_id: &str,
) -> Option<TerminalOutputRecord> {
    index
        .get(&terminal_item_id(terminal_id))
        .and_then(|item| match &item.body {
            TranscriptBody::TerminalOutput { record } if record.terminal_id == terminal_id => {
                Some(record.clone())
            }
            _ => None,
        })
}

pub(super) fn replace_or_push_terminal_record(
    records: &mut Vec<TerminalOutputRecord>,
    record: TerminalOutputRecord,
) {
    match records
        .iter_mut()
        .find(|existing| existing.terminal_id == record.terminal_id)
    {
        Some(existing) => *existing = record,
        None => records.push(record),
    }
}

pub(super) fn fallback_terminal_tool_item_id(terminal_id: &str) -> String {
    format!(
        "tool:{}",
        mj_core::acp::fallback_terminal_tool_call_id(terminal_id)
    )
}

pub(super) fn fallback_tool_item(item: &TranscriptItem) -> Result<bool> {
    let TranscriptBody::Tool { call, .. } = &item.body else {
        return Ok(false);
    };
    if !call.typed_valid() {
        bail!("invalid ACP fallback terminal tool call");
    }
    Ok(call.is_fallback())
}

/// The one provider tool demonstrably owning a result through its raw value.
/// Identical concurrent results are deliberately left with the fallback tool.
pub(super) fn uniquely_matching_raw_tool(
    index: &ProjectionIndex,
    record: &TerminalOutputRecord,
) -> Option<Arc<TranscriptItem>> {
    let digest = record.raw_result_digest();
    let mut matching = index.transcript.values().filter_map(|item| {
        let TranscriptBody::Tool { call, .. } = &item.body else {
            return None;
        };
        if fallback_tool_item(item).ok()? {
            return None;
        }
        call.matches_raw_result(record, &digest)
            .then(|| Arc::clone(item))
    });
    let item = matching.next()?;
    matching.next().is_none().then_some(item)
}

/// A provider may publish its real tool before it asks the client to create
/// the terminal. In that ordering the existing call already provides the
/// durable start item, so the compatibility call would only duplicate it.
pub(super) fn fallback_terminal_already_claimed(
    index: &ProjectionIndex,
    call: &ToolCall,
) -> Result<bool> {
    if !mj_core::acp::is_fallback_terminal_tool_call(call) {
        return Ok(false);
    }
    let value = serde_json::to_value(call)?;
    Ok(tool_call_terminal_ids(&value)
        .into_iter()
        .any(|terminal_id| {
            index.terminal_referrers(&terminal_id).any(|item| {
                let TranscriptBody::Tool { call, .. } = &item.body else {
                    return false;
                };
                call.typed_valid() && !call.is_fallback()
            })
        }))
}

/// Replace Hel's interim terminal tool with the real ACP tool once the agent
/// supplies one. Output may already have landed on the interim item, so move
/// it along. A newly created real item can also adopt the interim item's start
/// identity; an existing tool keeps its immutable position and timestamp.
pub(super) fn consume_fallback_terminal_tools(
    index: &ProjectionIndex,
    mutation: &mut MaterializedSessionMutation,
    item: &mut TranscriptItem,
    may_adopt_identity: bool,
) -> Result<()> {
    let TranscriptBody::Tool {
        call,
        terminal_outputs,
        terminal_refs,
        ..
    } = &mut item.body
    else {
        return Ok(());
    };
    let materialized: ToolCall = call
        .decode()
        .context("parse ACP tool call while claiming fallback terminal tools")?;
    if mj_core::acp::is_fallback_terminal_tool_call(&materialized) {
        return Ok(());
    }

    let mut terminal_ids = call.terminal_ids().to_vec();
    terminal_ids.extend(terminal_refs.iter().cloned());
    for terminal_id in terminal_ids {
        let stable_id = fallback_terminal_tool_item_id(&terminal_id);
        if stable_id == item.stable_id {
            continue;
        }
        let Some(fallback) = index.get(&stable_id) else {
            continue;
        };
        let TranscriptBody::Tool {
            call: fallback_call,
            terminal_outputs: fallback_outputs,
            terminal_refs: fallback_refs,
            ..
        } = &fallback.body
        else {
            continue;
        };
        let fallback_call: ToolCall = fallback_call
            .decode()
            .context("parse fallback terminal tool call")?;
        if !mj_core::acp::is_fallback_terminal_tool_call(&fallback_call) {
            continue;
        }
        for record in fallback_outputs {
            replace_or_push_terminal_record(terminal_outputs, record.clone());
        }
        for terminal_ref in fallback_refs {
            if !terminal_refs.contains(terminal_ref) {
                terminal_refs.push(terminal_ref.clone());
            }
        }
        if !terminal_refs.contains(&terminal_id) {
            terminal_refs.push(terminal_id);
        }
        if may_adopt_identity {
            item.position = item.position.min(fallback.position);
            item.created_at_ms = item.created_at_ms.min(fallback.created_at_ms);
        }
        item.last_changed_at_ms = item.last_changed_at_ms.max(fallback.last_changed_at_ms);
        mutation
            .transcript
            .push(TranscriptMutation::Remove { stable_id });
    }
    Ok(())
}

/// Terminal close is a Hel event rather than an ACP tool update. Complete only
/// the interim call Hel created; a provider-owned call keeps its own status.
pub(super) fn finalize_fallback_terminal_tool(item: &mut TranscriptItem) -> Result<()> {
    let TranscriptBody::Tool {
        call,
        terminal_outputs,
        ..
    } = &mut item.body
    else {
        return Ok(());
    };
    if terminal_outputs.is_empty() {
        return Ok(());
    }
    let mut materialized: ToolCall = call
        .decode()
        .context("parse ACP tool call while finalizing fallback terminal tool")?;
    if !mj_core::acp::is_fallback_terminal_tool_call(&materialized) {
        return Ok(());
    }
    materialized.status = if terminal_outputs
        .iter()
        .all(TerminalOutputRecord::exited_cleanly)
    {
        ToolCallStatus::Completed
    } else {
        ToolCallStatus::Failed
    };
    *call = serde_json::to_value(materialized)?.into();
    Ok(())
}

/// The one parked terminal result an ACP tool demonstrably owns through its
/// raw result. Ambiguous identical results stay standalone rather than being
/// assigned to an arbitrary concurrent tool.
pub(super) fn uniquely_matching_raw_terminal(
    current: &MaterializedSession,
    call: &mj_core::transcript::OpaqueToolCall,
) -> Option<String> {
    let mut matching = current.transcript.iter().filter_map(|item| {
        let record = match &item.body {
            TranscriptBody::TerminalOutput { record } => record,
            TranscriptBody::Tool {
                terminal_outputs, ..
            } if fallback_tool_item(item).ok()? => terminal_outputs.first()?,
            _ => return None,
        };
        call.matches_raw_result(record, &record.raw_result_digest())
            .then(|| record.terminal_id.clone())
    });
    let terminal_id = matching.next()?;
    matching.next().is_none().then_some(terminal_id)
}

/// Remember every terminal the current call refers to, move any parked output
/// for the terminals `item` has ever referred to into the item, and remove the
/// standalone items it consumed. An exact provider raw result also claims its
/// one matching parked terminal: Kimi supplies that result but no ACP terminal
/// reference. Output that arrives before the tool call therefore ends up
/// exactly where output that arrives after it does, and a call that drops its
/// terminal reference on a later content update still owns the terminal it
/// started.
pub(super) fn attach_terminal_outputs(
    current: &MaterializedSession,
    index: &ProjectionIndex,
    mutation: &mut MaterializedSessionMutation,
    item: &mut TranscriptItem,
) {
    let TranscriptBody::Tool {
        call,
        terminal_outputs,
        terminal_refs,
        ..
    } = &mut item.body
    else {
        return;
    };
    for terminal_id in call.terminal_ids().iter().cloned() {
        if !terminal_refs.contains(&terminal_id) {
            terminal_refs.push(terminal_id);
        }
    }
    if terminal_refs.is_empty()
        && let Some(terminal_id) = uniquely_matching_raw_terminal(current, call)
        && !terminal_refs.contains(&terminal_id)
    {
        terminal_refs.push(terminal_id);
    }
    let mut consumed = Vec::new();
    for terminal_id in terminal_refs.iter() {
        let Some(record) = find_terminal_record(index, terminal_id) else {
            continue;
        };
        replace_or_push_terminal_record(terminal_outputs, record);
        consumed.push(terminal_item_id(terminal_id));
    }
    for stable_id in consumed {
        mutation
            .transcript
            .push(TranscriptMutation::Remove { stable_id });
    }
}

pub(super) fn canonical_terminal_output(record: &TerminalOutputRecord) -> CanonicalTerminalOutput {
    CanonicalTerminalOutput {
        terminal_id: record.terminal_id.clone(),
        output: record.output.text().into_owned(),
        truncated: record.truncated,
        exit_code: record.exit_code,
        signal: record.signal.clone(),
    }
}

pub(super) fn materialized_terminal_output(
    record: &CanonicalTerminalOutput,
) -> TerminalOutputRecord {
    TerminalOutputRecord {
        terminal_id: record.terminal_id.clone(),
        output: record.output.clone().into(),
        truncated: record.truncated,
        exit_code: record.exit_code,
        signal: record.signal.clone(),
    }
}