Skip to main content

codex_protocol/
thread_id.rs

1use std::fmt::Display;
2
3use schemars::JsonSchema;
4use schemars::r#gen::SchemaGenerator;
5use schemars::schema::Schema;
6use serde::Deserialize;
7use serde::Serialize;
8use ts_rs::TS;
9use uuid::Uuid;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)]
12#[ts(type = "string")]
13/// Identifier for a Codex thread.
14///
15/// Codex-generated thread IDs are UUIDv7, and some use cases rely on that.
16pub struct ThreadId {
17    pub(crate) uuid: Uuid,
18}
19
20impl ThreadId {
21    pub fn new() -> Self {
22        Self {
23            uuid: Uuid::now_v7(),
24        }
25    }
26
27    pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
28        Ok(Self {
29            uuid: Uuid::parse_str(s)?,
30        })
31    }
32}
33
34impl TryFrom<&str> for ThreadId {
35    type Error = uuid::Error;
36
37    fn try_from(value: &str) -> Result<Self, Self::Error> {
38        Self::from_string(value)
39    }
40}
41
42impl TryFrom<String> for ThreadId {
43    type Error = uuid::Error;
44
45    fn try_from(value: String) -> Result<Self, Self::Error> {
46        Self::from_string(value.as_str())
47    }
48}
49
50impl From<ThreadId> for String {
51    fn from(value: ThreadId) -> Self {
52        value.to_string()
53    }
54}
55
56impl Default for ThreadId {
57    fn default() -> Self {
58        Self::new()
59    }
60}
61
62impl Display for ThreadId {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        Display::fmt(&self.uuid, f)
65    }
66}
67
68impl Serialize for ThreadId {
69    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
70    where
71        S: serde::Serializer,
72    {
73        serializer.collect_str(&self.uuid)
74    }
75}
76
77impl<'de> Deserialize<'de> for ThreadId {
78    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79    where
80        D: serde::Deserializer<'de>,
81    {
82        let value = String::deserialize(deserializer)?;
83        let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?;
84        Ok(Self { uuid })
85    }
86}
87
88impl JsonSchema for ThreadId {
89    fn schema_name() -> String {
90        "ThreadId".to_string()
91    }
92
93    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
94        <String>::json_schema(generator)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    #[test]
102    fn test_thread_id_default_is_not_zeroes() {
103        let id = ThreadId::default();
104        assert_ne!(id.uuid, Uuid::nil());
105    }
106}