Skip to main content

infinity_protocol/
lib.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4use tokio_util::codec::LengthDelimitedCodec;
5
6/// The identifier kinds used throughout the runtime (re-exported from
7/// `rap-protocol`).
8pub use rap_protocol::{ChoiceId, ProviderCallId, ThreadId, ToolCallId};
9
10strkind::strkind! {
11    /// The name of a configured remote daemon (from `remotes.json`), e.g.
12    /// `"devbox"`. Remote names must not contain `/` (they are joined with
13    /// thread IDs in [`ThreadRef`]'s wire encoding).
14    pub RemoteName;
15}
16
17/// A client-facing reference to a thread: which daemon it lives on
18/// (`remote: None` means the local daemon) plus its thread ID there.
19///
20/// On the wire this serializes as the historical composite string —
21/// `"{remote}/{id}"` for remote threads, bare `"{id}"` for local ones — so
22/// clients see a plain string and the daemon parses it back losslessly.
23/// A session is identified by its root thread's `ThreadRef`.
24///
25/// Ordering is `(remote, id)`: local threads sort before remote ones, then
26/// by thread ID. (This differs from lexicographic ordering of the composite
27/// string, which would interleave remotes with local IDs.)
28#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct ThreadRef {
30    /// The remote daemon hosting the thread; `None` for the local daemon.
31    pub remote: Option<RemoteName>,
32    /// The thread's ID on its home daemon.
33    pub id: ThreadId,
34}
35
36impl ThreadRef {
37    /// A reference to a thread on the local daemon.
38    pub fn local(id: ThreadId) -> Self {
39        Self { remote: None, id }
40    }
41
42    /// A reference to a thread on the named remote daemon.
43    ///
44    /// # Panics
45    ///
46    /// Panics if `remote` contains `/`, which would make the composite wire
47    /// encoding (`"{remote}/{id}"`) ambiguous.
48    pub fn remote(remote: RemoteName, id: ThreadId) -> Self {
49        assert!(
50            !remote.as_str().contains('/'),
51            "bug: remote name {remote:?} contains '/'"
52        );
53        Self {
54            remote: Some(remote),
55            id,
56        }
57    }
58
59    /// Re-home this reference onto `remote` (used when a daemon proxies a
60    /// remote daemon's messages to its own clients).
61    ///
62    /// # Panics
63    ///
64    /// Panics if `remote` contains `/`, which would make the composite wire
65    /// encoding (`"{remote}/{id}"`) ambiguous.
66    pub fn prefixed(self, remote: &RemoteName) -> Self {
67        Self::remote(remote.clone(), self.id)
68    }
69
70    /// Strip the given remote, yielding the thread's ID on its home daemon.
71    /// References to other remotes (or local ones) are returned unchanged.
72    pub fn strip(self, remote: &RemoteName) -> Self {
73        match self.remote {
74            Some(ref r) if r == remote => Self {
75                remote: None,
76                id: self.id,
77            },
78            _ => self,
79        }
80    }
81}
82
83impl std::fmt::Display for ThreadRef {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        match &self.remote {
86            Some(remote) => write!(f, "{}/{}", remote, self.id),
87            None => write!(f, "{}", self.id),
88        }
89    }
90}
91
92/// Error parsing a [`ThreadRef`] from its composite string form.
93///
94/// Produced when the input is not a bare thread ID or a well-formed
95/// `"{remote}/{id}"` composite: an empty remote or ID half, or a second `/`
96/// (remote names and thread IDs must not contain `/`).
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct ThreadRefParseError {
99    input: String,
100    reason: &'static str,
101}
102
103impl std::fmt::Display for ThreadRefParseError {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        write!(f, "invalid thread ref {:?}: {}", self.input, self.reason)
106    }
107}
108
109impl std::error::Error for ThreadRefParseError {}
110
111impl std::str::FromStr for ThreadRef {
112    type Err = ThreadRefParseError;
113    fn from_str(s: &str) -> Result<Self, Self::Err> {
114        let err = |reason| {
115            Err(ThreadRefParseError {
116                input: s.to_owned(),
117                reason,
118            })
119        };
120        match s.split_once('/') {
121            Some((remote, id)) => {
122                if remote.is_empty() {
123                    return err("empty remote name");
124                }
125                if id.is_empty() {
126                    return err("empty thread ID");
127                }
128                if id.contains('/') {
129                    return err("more than one '/'");
130                }
131                Ok(Self {
132                    remote: Some(remote.into()),
133                    id: id.into(),
134                })
135            }
136            None => Ok(Self {
137                remote: None,
138                id: s.into(),
139            }),
140        }
141    }
142}
143
144impl From<&str> for ThreadRef {
145    fn from(s: &str) -> Self {
146        s.parse().expect("invalid ThreadRef")
147    }
148}
149
150impl From<String> for ThreadRef {
151    fn from(s: String) -> Self {
152        s.as_str().into()
153    }
154}
155
156impl From<ThreadId> for ThreadRef {
157    fn from(id: ThreadId) -> Self {
158        Self::local(id)
159    }
160}
161
162impl Serialize for ThreadRef {
163    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
164        serializer.collect_str(self)
165    }
166}
167
168impl<'de> Deserialize<'de> for ThreadRef {
169    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
170        let s = String::deserialize(deserializer)?;
171        s.parse().map_err(serde::de::Error::custom)
172    }
173}
174
175/// Maximum frame size for daemon ↔ client communication (256 MiB).
176///
177/// The default `LengthDelimitedCodec` limit is 8 MiB, which is too small for
178/// messages that carry large tool outputs, file contents, or replayed
179/// conversation history. We use a generous 256 MiB limit to avoid "frame size
180/// too big" errors in practice.
181const MAX_FRAME_LENGTH: usize = 256 * 1024 * 1024;
182
183/// Create a [`LengthDelimitedCodec`] configured with the project-wide maximum
184/// frame size. Use this instead of `LengthDelimitedCodec::new()` to ensure
185/// both client and daemon agree on the limit.
186pub fn length_delimited_codec() -> LengthDelimitedCodec {
187    LengthDelimitedCodec::builder()
188        .max_frame_length(MAX_FRAME_LENGTH)
189        .new_codec()
190}
191
192/// Returns the path to the daemon unix socket: `~/.infinity/daemon.sock`.
193pub fn socket_path() -> PathBuf {
194    dirs::home_dir()
195        .expect("could not determine home directory")
196        .join(".infinity")
197        .join("daemon.sock")
198}
199
200/// Returns the path to the daemon PID file: `~/.infinity/daemon.pid`.
201pub fn pid_path() -> PathBuf {
202    dirs::home_dir()
203        .expect("could not determine home directory")
204        .join(".infinity")
205        .join("daemon.pid")
206}
207
208/// Returns the base directory for daemon state: `~/.infinity/`.
209pub fn state_dir() -> PathBuf {
210    dirs::home_dir()
211        .expect("could not determine home directory")
212        .join(".infinity")
213}
214
215/// Returns the path to the remotes config: `~/.infinity/remotes.json`.
216pub fn remotes_config_path() -> PathBuf {
217    dirs::home_dir()
218        .expect("could not determine home directory")
219        .join(".infinity")
220        .join("remotes.json")
221}
222
223// ── Client → Daemon ─────────────────────────────────────────────────────────
224
225fn default_true() -> bool {
226    true
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub enum ClientMessage {
231    /// Create a new session with the given working directory.
232    CreateSession {
233        cwd: PathBuf,
234        /// Optional target location. `None` means local.
235        /// Otherwise, the name of a remote.
236        #[serde(default)]
237        location: Option<RemoteName>,
238        /// Optional model to use for the new session. `None` uses the
239        /// daemon's default model.
240        #[serde(default)]
241        model: Option<ModelRef>,
242        /// When `false`, this connection will not prevent the session from
243        /// going idle and being shut down by the daemon. Defaults to `true`
244        /// so that normal interactive clients keep sessions alive.
245        #[serde(default = "default_true")]
246        keeps_session_alive: bool,
247    },
248    /// Connect to an existing session (optionally a specific thread).
249    Connect {
250        root_thread_id: ThreadRef,
251        thread_id: Option<ThreadRef>,
252        /// When `false`, this connection will not prevent the session from
253        /// going idle and being shut down by the daemon. Defaults to `true`
254        /// so that normal interactive clients keep sessions alive.
255        #[serde(default = "default_true")]
256        keeps_session_alive: bool,
257    },
258    UserInput {
259        thread_id: ThreadRef,
260        text: String,
261    },
262    /// Disconnect from the session while letting the agent continue to run in the background.
263    Disconnect,
264    /// Immediately attempt to detach. If the agent is idle, the daemon shuts
265    /// down the session (closing the display channel). If not idle, the daemon
266    /// responds with `DisconnectNotIdle` so the client can show a picker.
267    SoftDetach {
268        root_thread_id: ThreadRef,
269    },
270    /// Disconnects from the session and shuts down the agent so that it can only be woken bu
271    /// new user inputs.
272    ShutdownSession {
273        root_thread_id: ThreadRef,
274    },
275    /// Archive a session (shut it down and hide from the main list).
276    ArchiveSession {
277        root_thread_id: ThreadRef,
278    },
279    /// Switch the model used for future requests on a thread. `thread_id`
280    /// may be any thread (root or subthread); the switch affects only that
281    /// specific thread — it does not propagate to child threads. If a
282    /// completion is currently in flight on the thread, it finishes on the
283    /// old model and the switch applies to subsequent requests.
284    SwitchModel {
285        thread_id: ThreadRef,
286        model: ModelRef,
287    },
288    /// Notify the daemon that a user choice was answered so it can be
289    /// removed from the pending replay list.
290    UserChoiceAnswered {
291        choice_id: ChoiceId,
292        selected: usize,
293    },
294    /// Trigger compaction for the given session.
295    TriggerCompaction {
296        root_thread_id: ThreadRef,
297    },
298    /// Request migration of a session to a different host.
299    RequestMigrate {
300        root_thread_id: ThreadRef,
301        /// `None` means local, `Some(name)` means a remote.
302        #[serde(default)]
303        to: Option<RemoteName>,
304        dest_cwd: PathBuf,
305    },
306    /// Daemon-to-daemon: request a session to emigrate. Includes destination RAP URLs
307    /// so source RAP servers can migrate their state.
308    Emigrate {
309        root_thread_id: ThreadId,
310        /// config_id → destination URL
311        dest_rap_urls: HashMap<String, String>,
312    },
313    /// Daemon-to-daemon: immigration is complete, source can clean up.
314    EmigrateDone {
315        root_thread_id: ThreadId,
316    },
317    /// Daemon-to-daemon: import a serialized session at the given cwd.
318    ImportSession {
319        root_thread_id: ThreadId,
320        cwd: PathBuf,
321        session_data: String,
322    },
323    /// Daemon-to-daemon: boot RAP servers at the given cwd and return their ports.
324    BootRapServers {
325        cwd: PathBuf,
326    },
327    /// Request directory listing for path completion.
328    ListDirectory {
329        path: String,
330        /// Target remote name. `None` means list on the local filesystem.
331        #[serde(default)]
332        on: Option<RemoteName>,
333    },
334}
335
336// ── Daemon → Client ─────────────────────────────────────────────────────────
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub enum DaemonMessage {
340    Connected {
341        root_thread_id: ThreadRef,
342        thread_id: ThreadRef,
343        model_name: String,
344        context_window: usize,
345        title: Option<String>,
346        total_tokens_used: usize,
347        #[serde(default)]
348        provider_id: String,
349    },
350    StartOutput {
351        thread_id: Option<ThreadRef>,
352    },
353    TextChunk {
354        thread_id: Option<ThreadRef>,
355        chunk: String,
356    },
357    ToolCall {
358        name: String,
359        args: String,
360        thread_id: Option<ThreadRef>,
361        display_as: Option<String>,
362    },
363    ToolResult {
364        /// Prioritized display segments. Clients use the first type they support.
365        segments: Vec<rap_protocol::DisplaySegment>,
366        thread_id: Option<ThreadRef>,
367    },
368    Info {
369        thread_id: Option<ThreadRef>,
370        text: String,
371    },
372    ResponseDone {
373        thread_id: Option<ThreadRef>,
374        token_usage: Option<TokenUsage>,
375    },
376    UserInputEcho {
377        thread_id: Option<ThreadRef>,
378        text: String,
379    },
380    SubscriptionEvent {
381        name: String,
382        text: String,
383        thread_id: Option<ThreadRef>,
384    },
385    OAuthRequired {
386        thread_id: Option<ThreadRef>,
387        auth_url: String,
388    },
389    UserChoiceRequired {
390        thread_id: Option<ThreadRef>,
391        id: ChoiceId,
392        prompt: String,
393        choices: Vec<String>,
394        default: usize,
395    },
396    UserChoiceComplete {
397        choice_id: ChoiceId,
398    },
399    ThinkingStart {
400        thread_id: Option<ThreadRef>,
401    },
402    ThinkingEnd {
403        thread_id: Option<ThreadRef>,
404    },
405    ThinkingChunk {
406        thread_id: Option<ThreadRef>,
407        chunk: String,
408    },
409    CompactionApplied {
410        thread_id: Option<ThreadRef>,
411    },
412    /// Confirmation that a thread's model was switched (via
413    /// [`ClientMessage::SwitchModel`]). Sent to the requesting client and
414    /// broadcast to the thread's subscribers so every attached UI can update
415    /// its model indicator.
416    ModelSwitched {
417        thread_id: ThreadRef,
418        model_name: String,
419        context_window: usize,
420        provider_id: String,
421    },
422    Error {
423        thread_id: Option<ThreadRef>,
424        text: String,
425    },
426    /// A view update pushed by a RAP tool server.
427    ViewUpdate {
428        thread_id: Option<ThreadRef>,
429        view_type: String,
430        content: serde_json::Value,
431    },
432    /// Batch replay of history messages, sent on connect/load.
433    Replay {
434        history: Vec<DaemonMessage>,
435        pending_choices: Vec<DaemonMessage>,
436        #[serde(default)]
437        views: HashMap<String, serde_json::Value>,
438        /// Whether a completion is currently in flight for this thread. When
439        /// false, clients should treat the end of the replay as an implicit
440        /// ResponseDone (a trailing unresolved ToolCall in the history still
441        /// implies a "waiting for tool result" state); when true, the
442        /// spinner state implied by the end of the history is live and more
443        /// events will follow.
444        #[serde(default)]
445        in_progress: bool,
446    },
447    /// Sent immediately on socket connection with session list and default model info.
448    Welcome {
449        sessions: HashMap<ThreadRef, SessionInfo>,
450        available_models: Vec<ModelInfo>,
451        default_model_name: String,
452        default_context_window: usize,
453        provider_name: String,
454        #[serde(default)]
455        remotes: Vec<RemoteInfo>,
456    },
457    /// Broadcast: one or more sessions were created or updated.
458    SessionsUpdated {
459        sessions: HashMap<ThreadRef, SessionInfo>,
460    },
461    /// Broadcast: remote connection statuses changed.
462    RemotesUpdated {
463        remotes: Vec<RemoteInfo>,
464    },
465    /// The agent is not idle — the client should show the full quit picker UI.
466    DisconnectNotIdle,
467    /// The agent was idle and has been detached — the client can proceed with
468    /// its pending action (quit, switch, new session) without showing a picker.
469    DetachedIdle,
470    /// Response to Emigrate: serialized session data (thread tree as JSON).
471    EmigrateResult {
472        root_thread_id: ThreadId,
473        session_data: String,
474    },
475    MigrateStarted {
476        root_thread_id: ThreadRef,
477    },
478    MigrateComplete {
479        root_thread_id: ThreadRef,
480        new_root_thread_id: ThreadRef,
481    },
482    MigrateError {
483        root_thread_id: ThreadRef,
484        error: String,
485    },
486    /// Response to ImportSession.
487    ImportComplete {
488        root_thread_id: ThreadId,
489    },
490    /// Response to BootRapServers: maps config ID → local port for servers needing migration.
491    RapServersBooted {
492        /// config_id → port on the remote host (only servers with needsMigration)
493        server_ports: HashMap<String, u16>,
494    },
495    /// Response to ListDirectory: directory entries for path completion.
496    DirectoryListing {
497        /// The path that was requested (for matching responses to requests).
498        request_path: String,
499        /// Directory entries (names only, directories have trailing `/`).
500        entries: Vec<String>,
501        /// The remote that was queried, if any.
502        #[serde(default)]
503        on: Option<RemoteName>,
504    },
505}
506
507// ── Supporting types ────────────────────────────────────────────────────────
508
509#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
510pub enum SessionStatus {
511    Running,
512    Idle,
513    Stopped,
514    WaitingForChoice,
515    Migrating,
516    Archived,
517}
518
519#[derive(Debug, Clone, Serialize, Deserialize)]
520pub struct SessionInfo {
521    pub title: Option<String>,
522    pub last_updated: String,
523    pub total_tokens_used: usize,
524    pub status: SessionStatus,
525    #[serde(default)]
526    pub threads: Vec<SubthreadInfo>,
527    /// If set, this session lives on a remote daemon with this name.
528    #[serde(default)]
529    pub remote: Option<RemoteName>,
530}
531
532#[derive(Debug, Clone, Serialize, Deserialize)]
533pub struct SubthreadInfo {
534    pub thread_id: ThreadRef,
535    pub parent_thread_id: ThreadRef,
536    pub title: Option<String>,
537}
538
539#[derive(Debug, Clone, Serialize, Deserialize)]
540pub struct TokenUsage {
541    pub input_tokens: Option<u64>,
542    pub output_tokens: Option<u64>,
543    /// Total tokens including cached input. When prompt caching is active,
544    /// `input_tokens` only reflects uncached input, so consumers should prefer
545    /// `total_tokens` (falling back to `input + output` if absent for
546    /// backwards compatibility).
547    #[serde(default)]
548    pub total_tokens: Option<u64>,
549}
550
551#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct ModelInfo {
553    pub display_name: String,
554    /// The provider this model belongs to.
555    #[serde(default)]
556    pub provider_id: String,
557    pub model_id: String,
558    pub context_window: usize,
559}
560
561/// Globally unique reference to a model: a provider id plus the model's
562/// provider-scoped id.
563#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
564pub struct ModelRef {
565    pub provider_id: String,
566    pub model_id: String,
567}
568
569#[derive(Debug, Clone, Serialize, Deserialize)]
570pub struct RemoteInfo {
571    pub name: RemoteName,
572    pub status: String,
573}
574
575#[cfg(test)]
576mod tests {
577    use super::*;
578
579    #[test]
580    fn thread_ref_parse_local() {
581        let r: ThreadRef = "abc-123".parse().expect("local ref should parse");
582        assert_eq!(r, ThreadRef::local("abc-123".into()));
583        assert_eq!(r.to_string(), "abc-123");
584    }
585
586    #[test]
587    fn thread_ref_parse_remote() {
588        let r: ThreadRef = "devbox/abc-123".parse().expect("remote ref should parse");
589        assert_eq!(r, ThreadRef::remote("devbox".into(), "abc-123".into()));
590        assert_eq!(r.to_string(), "devbox/abc-123");
591    }
592
593    #[test]
594    fn thread_ref_parse_rejects_malformed() {
595        assert!("a/b/c".parse::<ThreadRef>().is_err(), "second '/'");
596        assert!("/abc".parse::<ThreadRef>().is_err(), "empty remote");
597        assert!("devbox/".parse::<ThreadRef>().is_err(), "empty thread ID");
598    }
599
600    #[test]
601    fn thread_ref_deserialize_rejects_malformed() {
602        assert!(serde_json::from_str::<ThreadRef>("\"a/b/c\"").is_err());
603        let r: ThreadRef =
604            serde_json::from_str("\"devbox/abc-123\"").expect("valid composite should deserialize");
605        assert_eq!(r, ThreadRef::remote("devbox".into(), "abc-123".into()));
606    }
607
608    #[test]
609    #[should_panic(expected = "contains '/'")]
610    fn thread_ref_remote_rejects_slash_in_name() {
611        ThreadRef::remote("dev/box".into(), "abc-123".into());
612    }
613}