use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use tokio_util::codec::LengthDelimitedCodec;
pub use rap_protocol::{ChoiceId, ProviderCallId, ThreadId, ToolCallId};
strkind::strkind! {
pub RemoteName;
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ThreadRef {
pub remote: Option<RemoteName>,
pub id: ThreadId,
}
impl ThreadRef {
pub fn local(id: ThreadId) -> Self {
Self { remote: None, id }
}
pub fn remote(remote: RemoteName, id: ThreadId) -> Self {
assert!(
!remote.as_str().contains('/'),
"bug: remote name {remote:?} contains '/'"
);
Self {
remote: Some(remote),
id,
}
}
pub fn prefixed(self, remote: &RemoteName) -> Self {
Self::remote(remote.clone(), self.id)
}
pub fn strip(self, remote: &RemoteName) -> Self {
match self.remote {
Some(ref r) if r == remote => Self {
remote: None,
id: self.id,
},
_ => self,
}
}
}
impl std::fmt::Display for ThreadRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.remote {
Some(remote) => write!(f, "{}/{}", remote, self.id),
None => write!(f, "{}", self.id),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadRefParseError {
input: String,
reason: &'static str,
}
impl std::fmt::Display for ThreadRefParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid thread ref {:?}: {}", self.input, self.reason)
}
}
impl std::error::Error for ThreadRefParseError {}
impl std::str::FromStr for ThreadRef {
type Err = ThreadRefParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = |reason| {
Err(ThreadRefParseError {
input: s.to_owned(),
reason,
})
};
match s.split_once('/') {
Some((remote, id)) => {
if remote.is_empty() {
return err("empty remote name");
}
if id.is_empty() {
return err("empty thread ID");
}
if id.contains('/') {
return err("more than one '/'");
}
Ok(Self {
remote: Some(remote.into()),
id: id.into(),
})
}
None => Ok(Self {
remote: None,
id: s.into(),
}),
}
}
}
impl From<&str> for ThreadRef {
fn from(s: &str) -> Self {
s.parse().expect("invalid ThreadRef")
}
}
impl From<String> for ThreadRef {
fn from(s: String) -> Self {
s.as_str().into()
}
}
impl From<ThreadId> for ThreadRef {
fn from(id: ThreadId) -> Self {
Self::local(id)
}
}
impl Serialize for ThreadRef {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ThreadRef {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
const MAX_FRAME_LENGTH: usize = 256 * 1024 * 1024;
pub fn length_delimited_codec() -> LengthDelimitedCodec {
LengthDelimitedCodec::builder()
.max_frame_length(MAX_FRAME_LENGTH)
.new_codec()
}
pub fn socket_path() -> PathBuf {
dirs::home_dir()
.expect("could not determine home directory")
.join(".infinity")
.join("daemon.sock")
}
pub fn pid_path() -> PathBuf {
dirs::home_dir()
.expect("could not determine home directory")
.join(".infinity")
.join("daemon.pid")
}
pub fn state_dir() -> PathBuf {
dirs::home_dir()
.expect("could not determine home directory")
.join(".infinity")
}
pub fn remotes_config_path() -> PathBuf {
dirs::home_dir()
.expect("could not determine home directory")
.join(".infinity")
.join("remotes.json")
}
fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ClientMessage {
CreateSession {
cwd: PathBuf,
#[serde(default)]
location: Option<RemoteName>,
#[serde(default)]
model: Option<ModelRef>,
#[serde(default = "default_true")]
keeps_session_alive: bool,
},
Connect {
root_thread_id: ThreadRef,
thread_id: Option<ThreadRef>,
#[serde(default = "default_true")]
keeps_session_alive: bool,
},
UserInput {
thread_id: ThreadRef,
text: String,
},
Disconnect,
SoftDetach {
root_thread_id: ThreadRef,
},
ShutdownSession {
root_thread_id: ThreadRef,
},
ArchiveSession {
root_thread_id: ThreadRef,
},
SwitchModel {
thread_id: ThreadRef,
model: ModelRef,
},
UserChoiceAnswered {
choice_id: ChoiceId,
selected: usize,
},
TriggerCompaction {
root_thread_id: ThreadRef,
},
RequestMigrate {
root_thread_id: ThreadRef,
#[serde(default)]
to: Option<RemoteName>,
dest_cwd: PathBuf,
},
Emigrate {
root_thread_id: ThreadId,
dest_rap_urls: HashMap<String, String>,
},
EmigrateDone {
root_thread_id: ThreadId,
},
ImportSession {
root_thread_id: ThreadId,
cwd: PathBuf,
session_data: String,
},
BootRapServers {
cwd: PathBuf,
},
ListDirectory {
path: String,
#[serde(default)]
on: Option<RemoteName>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DaemonMessage {
Connected {
root_thread_id: ThreadRef,
thread_id: ThreadRef,
model_name: String,
context_window: usize,
title: Option<String>,
total_tokens_used: usize,
#[serde(default)]
provider_id: String,
},
StartOutput {
thread_id: Option<ThreadRef>,
},
TextChunk {
thread_id: Option<ThreadRef>,
chunk: String,
},
ToolCall {
name: String,
args: String,
thread_id: Option<ThreadRef>,
display_as: Option<String>,
},
ToolResult {
segments: Vec<rap_protocol::DisplaySegment>,
thread_id: Option<ThreadRef>,
},
Info {
thread_id: Option<ThreadRef>,
text: String,
},
ResponseDone {
thread_id: Option<ThreadRef>,
token_usage: Option<TokenUsage>,
},
UserInputEcho {
thread_id: Option<ThreadRef>,
text: String,
},
SubscriptionEvent {
name: String,
text: String,
thread_id: Option<ThreadRef>,
},
OAuthRequired {
thread_id: Option<ThreadRef>,
auth_url: String,
},
UserChoiceRequired {
thread_id: Option<ThreadRef>,
id: ChoiceId,
prompt: String,
choices: Vec<String>,
default: usize,
},
UserChoiceComplete {
choice_id: ChoiceId,
},
ThinkingStart {
thread_id: Option<ThreadRef>,
},
ThinkingEnd {
thread_id: Option<ThreadRef>,
},
ThinkingChunk {
thread_id: Option<ThreadRef>,
chunk: String,
},
CompactionApplied {
thread_id: Option<ThreadRef>,
},
ModelSwitched {
thread_id: ThreadRef,
model_name: String,
context_window: usize,
provider_id: String,
},
Error {
thread_id: Option<ThreadRef>,
text: String,
},
ViewUpdate {
thread_id: Option<ThreadRef>,
view_type: String,
content: serde_json::Value,
},
Replay {
history: Vec<DaemonMessage>,
pending_choices: Vec<DaemonMessage>,
#[serde(default)]
views: HashMap<String, serde_json::Value>,
#[serde(default)]
in_progress: bool,
},
Welcome {
sessions: HashMap<ThreadRef, SessionInfo>,
available_models: Vec<ModelInfo>,
default_model_name: String,
default_context_window: usize,
provider_name: String,
#[serde(default)]
remotes: Vec<RemoteInfo>,
},
SessionsUpdated {
sessions: HashMap<ThreadRef, SessionInfo>,
},
RemotesUpdated {
remotes: Vec<RemoteInfo>,
},
DisconnectNotIdle,
DetachedIdle,
EmigrateResult {
root_thread_id: ThreadId,
session_data: String,
},
MigrateStarted {
root_thread_id: ThreadRef,
},
MigrateComplete {
root_thread_id: ThreadRef,
new_root_thread_id: ThreadRef,
},
MigrateError {
root_thread_id: ThreadRef,
error: String,
},
ImportComplete {
root_thread_id: ThreadId,
},
RapServersBooted {
server_ports: HashMap<String, u16>,
},
DirectoryListing {
request_path: String,
entries: Vec<String>,
#[serde(default)]
on: Option<RemoteName>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SessionStatus {
Running,
Idle,
Stopped,
WaitingForChoice,
Migrating,
Archived,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
pub title: Option<String>,
pub last_updated: String,
pub total_tokens_used: usize,
pub status: SessionStatus,
#[serde(default)]
pub threads: Vec<SubthreadInfo>,
#[serde(default)]
pub remote: Option<RemoteName>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubthreadInfo {
pub thread_id: ThreadRef,
pub parent_thread_id: ThreadRef,
pub title: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenUsage {
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
#[serde(default)]
pub total_tokens: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
pub display_name: String,
#[serde(default)]
pub provider_id: String,
pub model_id: String,
pub context_window: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ModelRef {
pub provider_id: String,
pub model_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteInfo {
pub name: RemoteName,
pub status: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn thread_ref_parse_local() {
let r: ThreadRef = "abc-123".parse().expect("local ref should parse");
assert_eq!(r, ThreadRef::local("abc-123".into()));
assert_eq!(r.to_string(), "abc-123");
}
#[test]
fn thread_ref_parse_remote() {
let r: ThreadRef = "devbox/abc-123".parse().expect("remote ref should parse");
assert_eq!(r, ThreadRef::remote("devbox".into(), "abc-123".into()));
assert_eq!(r.to_string(), "devbox/abc-123");
}
#[test]
fn thread_ref_parse_rejects_malformed() {
assert!("a/b/c".parse::<ThreadRef>().is_err(), "second '/'");
assert!("/abc".parse::<ThreadRef>().is_err(), "empty remote");
assert!("devbox/".parse::<ThreadRef>().is_err(), "empty thread ID");
}
#[test]
fn thread_ref_deserialize_rejects_malformed() {
assert!(serde_json::from_str::<ThreadRef>("\"a/b/c\"").is_err());
let r: ThreadRef =
serde_json::from_str("\"devbox/abc-123\"").expect("valid composite should deserialize");
assert_eq!(r, ThreadRef::remote("devbox".into(), "abc-123".into()));
}
#[test]
#[should_panic(expected = "contains '/'")]
fn thread_ref_remote_rejects_slash_in_name() {
ThreadRef::remote("dev/box".into(), "abc-123".into());
}
}