gent-link 0.2.4

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
//! A first, named host input may open its own root. The receipt identifies
//! the receiving item, without making a claim about the sender.
use super::*;
mod collab;
mod direct;
mod preamble;
mod previous;
use crate::wake::codex::babysit::rollout::decision;
pub(super) use preamble::foreground_start;
use previous::Previous;
pub(super) use previous::observe as previous_receipt;

#[derive(Deserialize)]
struct Row {
    r#type: String,
    payload: Fields,
}

#[derive(Default, Deserialize)]
struct Fields {
    r#type: Option<String>,
    id: Option<String>,
    namespace: Option<String>,
    name: Option<String>,
    call_id: Option<String>,
    client_id: Option<String>,
    role: Option<String>,
    source: Option<String>,
    tool: Option<String>,
    server: Option<String>,
    sender_thread_id: Option<String>,
    receiver_thread_ids: Option<Vec<String>>,
    questions: Option<serde::de::IgnoredAny>,
    status: Option<String>,
    started_at_ms: Option<i64>,
    completed_at_ms: Option<i64>,
    thread_id: Option<String>,
    turn_id: Option<String>,
    root_turn_id: Option<String>,
    item: Option<Box<Fields>>,
    internal_chat_message_metadata_passthrough: Option<Scope>,
}

#[derive(Deserialize)]
struct Scope {
    turn_id: Option<String>,
    thread_id: Option<String>,
    executed_tool_calls: Option<Vec<Tool>>,
    content_item_kinds: Option<Vec<String>>,
}

#[derive(Deserialize)]
struct Tool {
    name: String,
}

impl Fields {
    fn within(&self, thread: &str, turn: &str) -> bool {
        self.thread_id.as_deref().is_none_or(|id| id == thread)
            && self.turn_id.as_deref().is_none_or(|id| id == turn)
            && self.root_turn_id.as_deref().is_none_or(|id| id == turn)
            && self
                .internal_chat_message_metadata_passthrough
                .as_ref()
                .is_none_or(|m| {
                    m.thread_id.as_deref().is_none_or(|id| id == thread)
                        && m.turn_id.as_deref().is_none_or(|id| id == turn)
                        && !m
                            .executed_tool_calls
                            .iter()
                            .flatten()
                            .any(|tool| decision(&tool.name))
                        && !m
                            .content_item_kinds
                            .iter()
                            .flatten()
                            .any(|kind| kind == "user.goal")
                })
    }

    fn named(&self) -> bool {
        self.namespace.as_deref() == Some("codex_tui")
            && self.name.as_deref() == Some("send_message_to_thread")
            && self.call_id.is_none()
    }
}

impl Row {
    fn next(rows: &mut ReverseLines<'_>, line: &mut Vec<u8>) -> Result<Option<Self>> {
        if !rows.previous(line)? {
            return Ok(None);
        }
        Ok(Some(serde_json::from_slice(line)?))
    }

    // Later native input, controls, decisions and unfamiliar activity close this path.
    fn work(&self, thread: &str, turn: &str) -> bool {
        let p = &self.payload;
        let scoped = p.thread_id.as_deref() == Some(thread) && p.turn_id.as_deref() == Some(turn);
        p.within(thread, turn)
            && match (self.r#type.as_str(), p.r#type.as_deref()) {
                ("token_usage_record", _) => scoped,
                ("event_msg", Some("token_count")) | ("response_item", Some("reasoning")) => true,
                ("event_msg", Some("item_completed")) => {
                    scoped
                        && p.item.as_ref().is_some_and(|i| {
                            i.within(thread, turn)
                                && match i.r#type.as_deref() {
                                    Some("AgentMessage" | "Reasoning") => true,
                                    Some("FileChange") => i.status.as_deref() == Some("completed"),
                                    Some("CommandExecution") => {
                                        (i.status.as_deref() == Some("completed")
                                            || (i.status.as_deref() == Some("failed")
                                                && i.id
                                                    .as_deref()
                                                    .is_some_and(|id| !id.is_empty())))
                                            && matches!(
                                                i.source.as_deref(),
                                                Some(
                                                    "agent"
                                                        | "unified_exec_startup"
                                                        | "unified_exec_interaction"
                                                )
                                            )
                                    }
                                    _ => false,
                                }
                        })
                }
                ("response_item", Some("message")) => p.role.as_deref() == Some("assistant"),
                (
                    "response_item",
                    Some(
                        "function_call"
                        | "custom_tool_call"
                        | "function_call_output"
                        | "custom_tool_call_output",
                    ),
                ) => {
                    p.call_id.as_deref().is_some_and(|id| !id.is_empty())
                        && !p.name.as_deref().is_some_and(decision)
                }
                _ => false,
            }
    }
}

pub(super) fn named_marker(line: &[u8]) -> bool {
    serde_json::from_slice::<Row>(line).is_ok_and(|row| {
        row.payload.named() || row.payload.item.as_ref().is_some_and(|item| item.named())
    })
}

fn named_pair(
    row: Row,
    rows: &mut ReverseLines<'_>,
    line: &mut Vec<u8>,
    failed: &Failed,
) -> Result<Option<Uuid>> {
    let turn = failed.turn.to_string();
    let p = row.payload;
    if row.r#type != "event_msg"
        || p.r#type.as_deref() != Some("item_completed")
        || p.thread_id.as_deref() != Some(&failed.thread)
        || p.turn_id.as_ref() != Some(&turn)
        || !p.within(&failed.thread, &turn)
    {
        return Ok(None);
    }
    let Some(item) = p.item.filter(|i| {
        i.r#type.as_deref() == Some("FunctionCallOutput")
            && i.named()
            && i.within(&failed.thread, &turn)
    }) else {
        return Ok(None);
    };
    let Some(id) = item
        .id
        .as_deref()
        .and_then(|s| s.strip_prefix("fco_"))
        .and_then(|s| Uuid::parse_str(s).ok())
        .filter(|id| !id.is_nil())
    else {
        return Ok(None);
    };
    let Some(response) = Row::next(rows, line)? else {
        return Ok(None);
    };
    let r = response.payload;
    if response.r#type != "response_item"
        || r.r#type.as_deref() != Some("function_call_output")
        || !r.named()
        || !r.within(&failed.thread, &turn)
        || r.id != item.id
        || r.id != Some(format!("fco_{id}"))
        || !r
            .internal_chat_message_metadata_passthrough
            .is_some_and(|m| m.turn_id.as_ref() == Some(&turn))
    {
        return Ok(None);
    }
    Ok(Some(id))
}

// This replay only runs after the ordinary reader reached the same proven
// task_started. Verified notification receipts are supplied in reverse order.
pub(super) fn read(
    file: &File,
    stamp: &Stamp,
    failed: &Failed,
    deadline: Instant,
    previous: Option<Previous>,
    mut inputs: &[ForegroundInput],
) -> Result<Option<Uuid>> {
    let mut rows = ReverseLines::new(file, stamp.len, true)?;
    let mut line = Vec::new();
    let turn = failed.turn.to_string();
    // The first pass checked the exact terminal error and the strict tail receipt format.
    // In a machine-origin turn, a tail command must also have a non-human source.
    loop {
        if Instant::now() >= deadline {
            return Ok(None);
        }
        let Some(row) = Row::next(&mut rows, &mut line)? else {
            return Ok(None);
        };
        if row.r#type == "event_msg" && row.payload.r#type.as_deref() == Some("task_complete") {
            break;
        }
        let owner = row
            .payload
            .turn_id
            .as_deref()
            .and_then(|s| Uuid::parse_str(s).ok());
        if !owner.is_some_and(|id| {
            (id == failed.turn || previous.as_ref().is_some_and(|p| p.turn == id))
                && terminal_command(&line, &failed.thread, id)
                && row.work(&failed.thread, &id.to_string())
        }) {
            return Ok(None);
        }
    }
    let dispatched = !inputs.is_empty();
    let mut named = HashSet::new();
    let mut collab = collab::Work::default();
    let mut opener = None;
    let mut unbound_tool = false;
    while Instant::now() < deadline {
        let Some(row) = Row::next(&mut rows, &mut line)? else {
            break;
        };
        let preceding_pair = opener.take();
        if row.r#type != "turn_context" {
            // The notification lane has already consumed its final user receipt.
            // Its original opener must still immediately follow the context.
            if dispatched && preceding_pair.is_some() {
                break;
            }
            let work = if dispatched {
                direct::work(&row, &mut rows, &mut line, failed, &turn, &mut inputs)?
            } else if collab.group(&row, &mut rows, &mut line, failed, deadline)? {
                true
            } else {
                // Legacy single admissions may contain ordinary tools. A new
                // mixed path requires both ends of every invoked tool group.
                unbound_tool |= row.payload.call_id.is_some()
                    || row.payload.questions.is_some()
                    || row
                        .payload
                        .item
                        .as_ref()
                        .is_some_and(|i| i.questions.is_some());
                row.work(&failed.thread, &turn)
            };
            if work {
                continue;
            }
            let Some(id) = named_pair(row, &mut rows, &mut line, failed)? else {
                break;
            };
            if named.len() >= MAX_CHAT_INPUTS || !named.insert(id) {
                break;
            }
            if inputs.is_empty() {
                opener = Some(id);
            }
            continue;
        }
        let Some(id) = preceding_pair else { break };
        if !dispatched && (named.len() > 1 || collab.has_nested()) && unbound_tool {
            break;
        }
        if !row.payload.within(&failed.thread, &turn)
            || row.payload.turn_id.as_ref() != Some(&turn)
            || row.payload.root_turn_id.as_ref() != Some(&turn)
        {
            break;
        }
        let Some(start) = preamble::start(&mut rows, &mut line, &failed.thread, &turn)? else {
            break;
        };
        if start.r#type == "event_msg"
            && start.payload.r#type.as_deref() == Some("task_started")
            && start.payload.within(&failed.thread, &turn)
            && start.payload.turn_id.as_ref() == Some(&turn)
            && match previous {
                Some(previous) => previous.confirm(&mut rows, &mut line, failed, deadline)?,
                None => true,
            }
            && Instant::now() < deadline
            && stamp.matches(&failed.path)?
        {
            return Ok(Some(id));
        }
        break;
    }
    Ok(None)
}