brokk-mj-transcript 2.74.0

Transcript projection and presentation for Mjolnir
Documentation
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 {
    crate::tool_item_id(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 {
    record.into()
}