gent-link 0.1.1

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
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
//! Bind the failed turn to native admission metadata without reading prompt text.
use super::super::babysit::rollout::{ReverseLines, terminal_command};
use super::*;
mod handoff;
#[cfg(test)]
mod handoff_tests;
mod legacy;
use super::super::babysit::rollout::input_hash;
use gent_protocol::babysitter::{ForegroundInput, ForegroundInputs, MAX_CHAT_INPUTS};
use rustix::fs::{Mode, OFlags};
use serde::Deserialize;
use std::{
    collections::HashSet,
    fs::{File, Metadata},
    io::{BufReader, Read},
    time::{Duration, Instant},
};

#[derive(PartialEq)]
pub(super) struct Stamp {
    dev: u64,
    ino: u64,
    len: u64,
    modified: std::time::SystemTime,
}

impl Stamp {
    fn from(meta: Metadata) -> Result<Self> {
        Ok(Self {
            dev: meta.dev(),
            ino: meta.ino(),
            len: meta.len(),
            modified: meta.modified()?,
        })
    }
    pub(super) fn current(path: &Path) -> Result<Self> {
        Self::from(std::fs::symlink_metadata(path)?)
    }
    pub(super) fn matches(&self, path: &Path) -> Result<bool> {
        Ok(*self == Self::current(path)?)
    }
    pub(super) fn grew_from(&self, older: &Self) -> bool {
        self.dev == older.dev && self.ino == older.ino && self.len > older.len
    }
}

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

#[derive(Default, Deserialize)]
struct Payload {
    id: Option<String>,
    r#type: Option<String>,
    thread_id: Option<String>,
    turn_id: Option<String>,
    root_turn_id: Option<String>,
    started_at: Option<i64>,
    completed_at: Option<i64>,
    error: Option<Error>,
    turn_attribution: Option<Attribution>,
    history_mode: Option<String>,
    item: Option<Item>,
}
#[derive(Deserialize)]
struct Error {
    message: String,
}
#[derive(Deserialize)]
struct Attribution {
    turn_id: Uuid,
    turn_trigger: Option<String>,
    root_turn_id: Uuid,
    parent_turn_id: Option<Uuid>,
    initiating_agent_path: Option<serde::de::IgnoredAny>,
}
#[derive(Deserialize)]
struct Item {
    r#type: String,
    id: Option<String>,
    client_id: Option<String>,
}

// Each caller supplies the command receipts it can attribute across this boundary.
fn completion(
    rows: &mut ReverseLines<'_>,
    line: &mut Vec<u8>,
    thread: &str,
    turn: Uuid,
    deadline: Instant,
    mut receipt: impl FnMut(&[u8]) -> bool,
) -> Result<Option<Payload>> {
    while Instant::now() < deadline && rows.previous(line)? {
        let record: Record = serde_json::from_slice(line)?;
        let p = record.payload;
        if record.r#type == "event_msg" && p.r#type.as_deref() == Some("task_complete") {
            return Ok((p.turn_id.as_deref() == Some(&turn.to_string())
                && p.thread_id.as_deref().is_none_or(|id| id == thread))
            .then_some(p));
        }
        if !receipt(line) {
            break;
        }
    }
    Ok(None)
}

fn foreground_receipt(line: &[u8], item: &Item) -> Option<ForegroundInput> {
    #[derive(Deserialize)]
    struct Time<'a> {
        timestamp: &'a str,
    }
    let time: Time<'_> = serde_json::from_slice(line).ok()?;
    Some(ForegroundInput {
        client: canonical_uuid(item.client_id.as_deref()?)?,
        sha256: input_hash(line, true)?,
        received_at_ms: chrono::DateTime::parse_from_rfc3339(time.timestamp)
            .ok()?
            .timestamp_millis(),
    })
}

fn canonical_uuid(raw: &str) -> Option<Uuid> {
    Uuid::parse_str(raw)
        .ok()
        .filter(|id| !id.is_nil() && id.to_string() == raw)
}

fn operator(failed: &Failed, mut inputs: Vec<Item>, trigger: Option<&str>) -> Option<ChatOrigin> {
    // A user may steer a running foreground turn. Keep every distinct native
    // input's client ID so the store can exclude Gent delivery at any position.
    if inputs.len() > 1 {
        let mut ids = HashSet::new();
        if !matches!(trigger, Some("user" | "composer"))
            || !inputs.iter().all(|i| {
                i.id.as_deref()
                    .is_some_and(|id| !id.is_empty() && ids.insert(id))
                    && i.client_id.as_deref().is_some_and(|id| !id.is_empty())
            })
        {
            return None;
        }
    }
    let first = inputs.pop()?;
    Some(ChatOrigin::Operator {
        turn: failed.turn,
        started_at: failed.started,
        client_id: first.client_id,
        additional_client_ids: inputs
            .into_iter()
            .rev()
            .map(|i| i.client_id)
            .collect::<Option<_>>()?,
    })
}

// The reverse scan ends at the oldest input. Only its client ID may match
// the durable admission for the preceding failure.
fn continuation(
    failed: &Failed,
    mut inputs: Vec<Item>,
    parent: Uuid,
    terminal: Payload,
    proven_sources: bool,
) -> Option<ChatOrigin> {
    terminal.error?;
    let first = inputs.pop()?;
    let client = first.client_id.as_deref()?;
    let attempt = Uuid::parse_str(client).ok()?;
    if inputs.is_empty() {
        return Some(ChatOrigin::Continuation { attempt });
    }
    let mut ids = HashSet::new();
    if !proven_sources
        || attempt.is_nil()
        || attempt.to_string() != client
        || !std::iter::once(&first).chain(&inputs).all(|i| {
            i.id.as_deref()
                .is_some_and(|id| !id.trim().is_empty() && ids.insert(id))
        })
    {
        return None;
    }
    Some(ChatOrigin::SteeredContinuation {
        attempt,
        parent,
        root: failed.root,
        started_at: failed.started,
        parent_failed_at: terminal.completed_at?,
        additional_client_ids: inputs
            .into_iter()
            .rev()
            .map(|i| i.client_id)
            .collect::<Option<_>>()?,
    })
}

pub(super) fn read(failed: &Failed) -> Result<Option<(ChatOrigin, Option<Uuid>, Stamp)>> {
    let path = &failed.path;
    if !path.is_absolute()
        || !path
            .file_name()
            .and_then(|s| s.to_str())
            .is_some_and(|name| {
                name.starts_with("rollout-") && name.ends_with(&format!("-{}.jsonl", failed.thread))
            })
    {
        return Ok(None);
    }
    let file = File::from(rustix::fs::open(
        path,
        OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK,
        Mode::empty(),
    )?);
    let meta = file.metadata()?;
    if !meta.is_file() || meta.len() == 0 || meta.uid() != rustix::process::geteuid().as_raw() {
        return Ok(None);
    }
    let stamp = Stamp::from(meta)?;
    let header = Record::deserialize(&mut serde_json::Deserializer::from_reader(BufReader::new(
        (&file).take(1024 * 1024),
    )))?;
    if header.r#type != "session_meta" || header.payload.id.as_deref() != Some(&failed.thread) {
        return Ok(None);
    }
    let legacy = failed.legacy_history && header.payload.history_mode.as_deref() == Some("legacy");
    let mut rows = ReverseLines::new(&file, stamp.len, true)?;
    let mut line = Vec::new();
    let deadline = Instant::now() + Duration::from_secs(2);
    let mut previous = None;
    let Some(p) = completion(
        &mut rows,
        &mut line,
        &failed.thread,
        failed.turn,
        deadline,
        |line| {
            terminal_command(line, &failed.thread, failed.turn)
                || (failed.handoff_parent
                    && failed.turn == failed.root
                    && handoff::previous_receipt(&mut previous, line, failed))
        },
    )?
    else {
        return Ok(None);
    };
    let turn = failed.turn.to_string();
    if p.started_at != Some(failed.started)
        || p.completed_at != Some(failed.ended)
        || p.error.as_ref().map(|e| &e.message) != Some(&failed.error)
    {
        return Ok(None);
    }
    let mut inputs: Vec<Item> = Vec::new();
    let descendant = failed.root != failed.turn;
    let mut pending_receipt: Option<usize> = None;
    let mut sources = HashSet::new();
    // Earlier single-input hosts do not always supply response provenance.
    // Accumulate ambiguity here and require a complete pairing on multi-input descendants.
    let mut ambiguous = false;
    // Walk backwards across the first user receipt, its message and the root context.
    // If anything intervenes before task_started, the mixed-input exception stays closed.
    let mut proven = Vec::new();
    let mut pending_input = None::<ForegroundInput>;
    let mut paired_message = false;
    let mut opening_context = false;
    while Instant::now() < deadline && rows.previous(&mut line)? {
        let record: Record = serde_json::from_slice(&line)?;
        let receipt = pending_receipt.take();
        let input = pending_input.take();
        let next_is_message = std::mem::take(&mut paired_message);
        let next_is_context = std::mem::take(&mut opening_context);
        if record.r#type != "event_msg" {
            if !legacy
                && record.r#type == "response_item"
                && record.payload.r#type.as_deref() == Some("message")
                && legacy::unpaired_user(&line).unwrap_or(true)
            {
                let source = receipt
                    .and_then(|index| inputs[index].client_id.as_deref())
                    .and_then(|client| {
                        legacy::user_source(&line, &failed.thread, failed.turn, client)
                    });
                paired_message = source.is_some();
                if paired_message
                    && let Some(input) = input
                    && input_hash(&line, false).as_ref() == Some(&input.sha256)
                {
                    proven.push(input);
                }
                ambiguous |= source.is_none_or(|id| !sources.insert(id));
            }
            if record.r#type == "turn_context" {
                let p = &record.payload;
                opening_context = next_is_message
                    && p.turn_id.as_ref() == Some(&turn)
                    && p.root_turn_id.as_ref() == Some(&turn)
                    && p.thread_id.as_ref().is_none_or(|id| id == &failed.thread);
            }
            if legacy && record.r#type == "response_item" && legacy::unpaired_user(&line)? {
                return Ok(None);
            }
            continue;
        }
        let p = record.payload;
        match p.r#type.as_deref() {
            Some("user_message") if legacy => {
                let Some(item) = legacy::input(&mut rows, &mut line, &failed.thread, failed.turn)?
                else {
                    return Ok(None);
                };
                if inputs.len() >= MAX_CHAT_INPUTS {
                    return Ok(None);
                }
                inputs.push(item);
            }
            Some("user_message") => ambiguous = true,
            Some(
                "turn_aborted"
                | "task_complete"
                | "thread_rolled_back"
                | "thread_goal_updated"
                | "thread_goal_cleared",
            ) => return Ok(None),
            Some("item_completed") => {
                let Some(item) = p.item.filter(|item| item.r#type == "UserMessage") else {
                    continue;
                };
                if legacy
                    || p.turn_id.as_ref() != Some(&turn)
                    || p.thread_id.as_ref() != Some(&failed.thread)
                    || inputs.len() >= MAX_CHAT_INPUTS
                {
                    return Ok(None);
                }
                pending_receipt = Some(inputs.len());
                if !descendant && failed.handoff_parent {
                    pending_input = foreground_receipt(&line, &item);
                }
                inputs.push(item);
            }
            Some("task_started") => {
                let Some(a) = p.turn_attribution else {
                    return Ok(None);
                };
                if p.turn_id.as_ref() != Some(&turn)
                    || p.started_at != Some(failed.started)
                    || a.turn_id != failed.turn
                    || a.root_turn_id != failed.root
                    || a.initiating_agent_path.is_some()
                    || !stamp.matches(path)?
                {
                    return Ok(None);
                }
                let origin = match a.turn_trigger.as_deref() {
                    None if inputs.is_empty()
                        && failed.handoff_parent
                        && header.payload.history_mode.as_deref() == Some("paginated")
                        && a.parent_turn_id.is_none()
                        && failed.root == failed.turn =>
                    {
                        let Some(item) = handoff::read(&file, &stamp, failed, deadline, previous)?
                        else {
                            return Ok(None);
                        };
                        ChatOrigin::ThreadHandoff {
                            item,
                            started_at: failed.started,
                        }
                    }
                    None | Some("user" | "composer")
                        if previous.is_none()
                            && a.parent_turn_id.is_none()
                            && failed.root == failed.turn =>
                    {
                        let Some(origin) = operator(failed, inputs, a.turn_trigger.as_deref())
                        else {
                            return Ok(None);
                        };
                        origin
                    }
                    Some(TRIGGER) if failed.root != failed.turn => {
                        let Some(parent) = a
                            .parent_turn_id
                            .filter(|id| !id.is_nil() && id != &failed.turn)
                        else {
                            return Ok(None);
                        };
                        let Some(terminal) = completion(
                            &mut rows,
                            &mut line,
                            &failed.thread,
                            parent,
                            deadline,
                            |line| terminal_command(line, &failed.thread, parent),
                        )?
                        else {
                            return Ok(None);
                        };
                        let proven_sources =
                            !ambiguous && (legacy || sources.len() == inputs.len());
                        let Some(origin) =
                            continuation(failed, inputs, parent, terminal, proven_sources)
                        else {
                            return Ok(None);
                        };
                        origin
                    }
                    _ => return Ok(None),
                };
                let origin = if let ChatOrigin::Operator {
                    additional_client_ids,
                    ..
                } = &origin
                    && !additional_client_ids.is_empty()
                    && failed.handoff_parent
                    && a.turn_trigger.as_deref() == Some("user")
                    && header.payload.history_mode.as_deref() == Some("paginated")
                    && next_is_context
                    && !ambiguous
                    && sources.len() == additional_client_ids.len() + 1
                    && proven.len() == sources.len()
                    && p.thread_id.as_ref().is_none_or(|id| id == &failed.thread)
                    && p.root_turn_id.as_ref() == Some(&turn)
                    && let Some(thread) = canonical_uuid(&failed.thread)
                {
                    proven.reverse();
                    ChatOrigin::ForegroundInputs(ForegroundInputs {
                        thread,
                        turn: failed.turn,
                        started_at: failed.started,
                        inputs: proven,
                    })
                } else {
                    origin
                };
                return Ok(Some((origin, a.parent_turn_id, stamp)));
            }
            _ => {}
        }
    }
    Ok(None)
}

#[cfg(test)]
mod tests;