infinity_protocol/lib.rs
1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4use tokio_util::codec::LengthDelimitedCodec;
5
6/// Maximum frame size for daemon ↔ client communication (256 MiB).
7///
8/// The default `LengthDelimitedCodec` limit is 8 MiB, which is too small for
9/// messages that carry large tool outputs, file contents, or replayed
10/// conversation history. We use a generous 256 MiB limit to avoid "frame size
11/// too big" errors in practice.
12const MAX_FRAME_LENGTH: usize = 256 * 1024 * 1024;
13
14/// Create a [`LengthDelimitedCodec`] configured with the project-wide maximum
15/// frame size. Use this instead of `LengthDelimitedCodec::new()` to ensure
16/// both client and daemon agree on the limit.
17pub fn length_delimited_codec() -> LengthDelimitedCodec {
18 LengthDelimitedCodec::builder()
19 .max_frame_length(MAX_FRAME_LENGTH)
20 .new_codec()
21}
22
23/// Returns the path to the daemon unix socket: `~/.infinity/daemon.sock`.
24pub fn socket_path() -> PathBuf {
25 dirs::home_dir()
26 .expect("could not determine home directory")
27 .join(".infinity")
28 .join("daemon.sock")
29}
30
31/// Returns the path to the daemon PID file: `~/.infinity/daemon.pid`.
32pub fn pid_path() -> PathBuf {
33 dirs::home_dir()
34 .expect("could not determine home directory")
35 .join(".infinity")
36 .join("daemon.pid")
37}
38
39/// Returns the base directory for daemon state: `~/.infinity/`.
40pub fn state_dir() -> PathBuf {
41 dirs::home_dir()
42 .expect("could not determine home directory")
43 .join(".infinity")
44}
45
46/// Returns the path to the remotes config: `~/.infinity/remotes.json`.
47pub fn remotes_config_path() -> PathBuf {
48 dirs::home_dir()
49 .expect("could not determine home directory")
50 .join(".infinity")
51 .join("remotes.json")
52}
53
54// ── Client → Daemon ─────────────────────────────────────────────────────────
55
56fn default_true() -> bool {
57 true
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub enum ClientMessage {
62 /// Create a new session with the given working directory.
63 CreateSession {
64 cwd: PathBuf,
65 /// Optional target location. `None` means local.
66 /// Otherwise, the name of a remote.
67 #[serde(default)]
68 location: Option<String>,
69 /// Optional model to use for the new session. `None` uses the
70 /// daemon's default model.
71 #[serde(default)]
72 model: Option<ModelRef>,
73 /// When `false`, this connection will not prevent the session from
74 /// going idle and being shut down by the daemon. Defaults to `true`
75 /// so that normal interactive clients keep sessions alive.
76 #[serde(default = "default_true")]
77 keeps_session_alive: bool,
78 },
79 /// Connect to an existing session (optionally a specific thread).
80 Connect {
81 session_id: String,
82 thread_id: Option<String>,
83 /// When `false`, this connection will not prevent the session from
84 /// going idle and being shut down by the daemon. Defaults to `true`
85 /// so that normal interactive clients keep sessions alive.
86 #[serde(default = "default_true")]
87 keeps_session_alive: bool,
88 },
89 UserInput {
90 session_id: String,
91 text: String,
92 },
93 /// Disconnect from the session while letting the agent continue to run in the background.
94 Disconnect,
95 /// Immediately attempt to detach. If the agent is idle, the daemon shuts
96 /// down the session (closing the display channel). If not idle, the daemon
97 /// responds with `DisconnectNotIdle` so the client can show a picker.
98 SoftDetach {
99 session_id: String,
100 },
101 /// Disconnects from the session and shuts down the agent so that it can only be woken bu
102 /// new user inputs.
103 ShutdownSession {
104 session_id: String,
105 },
106 /// Archive a session (shut it down and hide from the main list).
107 ArchiveSession {
108 session_id: String,
109 },
110 /// Switch the model used for future requests on a thread. `session_id`
111 /// may be any thread id (root or subthread); the switch affects only that
112 /// specific thread — it does not propagate to child threads. If a
113 /// completion is currently in flight on the thread, it finishes on the
114 /// old model and the switch applies to subsequent requests.
115 SwitchModel {
116 session_id: String,
117 model: ModelRef,
118 },
119 /// Notify the daemon that a user choice was answered so it can be
120 /// removed from the pending replay list.
121 UserChoiceAnswered {
122 choice_id: String,
123 selected: usize,
124 },
125 /// Trigger compaction for the given session.
126 TriggerCompaction {
127 session_id: String,
128 },
129 /// Request migration of a session to a different host.
130 RequestMigrate {
131 session_id: String,
132 /// `None` means local, `Some(name)` means a remote.
133 #[serde(default)]
134 to: Option<String>,
135 dest_cwd: PathBuf,
136 },
137 /// Daemon-to-daemon: request a session to emigrate. Includes destination RAP URLs
138 /// so source RAP servers can migrate their state.
139 Emigrate {
140 session_id: String,
141 /// config_id → destination URL
142 dest_rap_urls: HashMap<String, String>,
143 },
144 /// Daemon-to-daemon: immigration is complete, source can clean up.
145 EmigrateDone {
146 session_id: String,
147 },
148 /// Daemon-to-daemon: import a serialized session at the given cwd.
149 ImportSession {
150 session_id: String,
151 cwd: PathBuf,
152 session_data: String,
153 },
154 /// Daemon-to-daemon: boot RAP servers at the given cwd and return their ports.
155 BootRapServers {
156 cwd: PathBuf,
157 },
158 /// Request directory listing for path completion.
159 ListDirectory {
160 path: String,
161 /// Target remote name. `None` means list on the local filesystem.
162 #[serde(default)]
163 on: Option<String>,
164 },
165}
166
167// ── Daemon → Client ─────────────────────────────────────────────────────────
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub enum DaemonMessage {
171 Connected {
172 session_id: String,
173 thread_id: String,
174 model_name: String,
175 context_window: usize,
176 title: Option<String>,
177 total_tokens_used: usize,
178 #[serde(default)]
179 provider_id: String,
180 },
181 StartOutput {
182 thread_id: Option<String>,
183 },
184 TextChunk {
185 thread_id: Option<String>,
186 chunk: String,
187 },
188 ToolCall {
189 name: String,
190 args: String,
191 thread_id: Option<String>,
192 display_as: Option<String>,
193 },
194 ToolResult {
195 /// Prioritized display segments. Clients use the first type they support.
196 segments: Vec<rap_protocol::DisplaySegment>,
197 thread_id: Option<String>,
198 },
199 Info {
200 thread_id: Option<String>,
201 text: String,
202 },
203 ResponseDone {
204 thread_id: Option<String>,
205 token_usage: Option<TokenUsage>,
206 },
207 UserInputEcho {
208 thread_id: Option<String>,
209 text: String,
210 },
211 SubscriptionEvent {
212 name: String,
213 text: String,
214 thread_id: Option<String>,
215 },
216 OAuthRequired {
217 thread_id: Option<String>,
218 auth_url: String,
219 },
220 UserChoiceRequired {
221 thread_id: Option<String>,
222 id: String,
223 prompt: String,
224 choices: Vec<String>,
225 default: usize,
226 },
227 UserChoiceComplete {
228 choice_id: String,
229 },
230 ThinkingStart {
231 thread_id: Option<String>,
232 },
233 ThinkingEnd {
234 thread_id: Option<String>,
235 },
236 ThinkingChunk {
237 thread_id: Option<String>,
238 chunk: String,
239 },
240 CompactionApplied {
241 thread_id: Option<String>,
242 },
243 /// Confirmation that a thread's model was switched (via
244 /// [`ClientMessage::SwitchModel`]). Sent to the requesting client and
245 /// broadcast to the thread's subscribers so every attached UI can update
246 /// its model indicator.
247 ModelSwitched {
248 thread_id: String,
249 model_name: String,
250 context_window: usize,
251 provider_id: String,
252 },
253 Error {
254 thread_id: Option<String>,
255 text: String,
256 },
257 /// A view update pushed by a RAP tool server.
258 ViewUpdate {
259 thread_id: Option<String>,
260 view_type: String,
261 content: serde_json::Value,
262 },
263 /// Batch replay of history messages, sent on connect/load.
264 Replay {
265 history: Vec<DaemonMessage>,
266 pending_choices: Vec<DaemonMessage>,
267 #[serde(default)]
268 views: HashMap<String, serde_json::Value>,
269 /// Whether a completion is currently in flight for this thread. When
270 /// false, clients should treat the end of the replay as an implicit
271 /// ResponseDone (a trailing unresolved ToolCall in the history still
272 /// implies a "waiting for tool result" state); when true, the
273 /// spinner state implied by the end of the history is live and more
274 /// events will follow.
275 #[serde(default)]
276 in_progress: bool,
277 },
278 /// Sent immediately on socket connection with session list and default model info.
279 Welcome {
280 sessions: HashMap<String, SessionInfo>,
281 available_models: Vec<ModelInfo>,
282 default_model_name: String,
283 default_context_window: usize,
284 provider_name: String,
285 #[serde(default)]
286 remotes: Vec<RemoteInfo>,
287 },
288 /// Broadcast: one or more sessions were created or updated.
289 SessionsUpdated {
290 sessions: HashMap<String, SessionInfo>,
291 },
292 /// Broadcast: remote connection statuses changed.
293 RemotesUpdated {
294 remotes: Vec<RemoteInfo>,
295 },
296 /// The agent is not idle — the client should show the full quit picker UI.
297 DisconnectNotIdle,
298 /// The agent was idle and has been detached — the client can proceed with
299 /// its pending action (quit, switch, new session) without showing a picker.
300 DetachedIdle,
301 /// Response to Emigrate: serialized session data (thread tree as JSON).
302 EmigrateResult {
303 session_id: String,
304 session_data: String,
305 },
306 MigrateStarted {
307 session_id: String,
308 },
309 MigrateComplete {
310 session_id: String,
311 new_session_id: String,
312 },
313 MigrateError {
314 session_id: String,
315 error: String,
316 },
317 /// Response to ImportSession.
318 ImportComplete {
319 session_id: String,
320 },
321 /// Response to BootRapServers: maps config ID → local port for servers needing migration.
322 RapServersBooted {
323 /// config_id → port on the remote host (only servers with needsMigration)
324 server_ports: HashMap<String, u16>,
325 },
326 /// Response to ListDirectory: directory entries for path completion.
327 DirectoryListing {
328 /// The path that was requested (for matching responses to requests).
329 request_path: String,
330 /// Directory entries (names only, directories have trailing `/`).
331 entries: Vec<String>,
332 /// The remote that was queried, if any.
333 #[serde(default)]
334 on: Option<String>,
335 },
336}
337
338// ── Supporting types ────────────────────────────────────────────────────────
339
340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341pub enum SessionStatus {
342 Running,
343 Idle,
344 Stopped,
345 WaitingForChoice,
346 Migrating,
347 Archived,
348}
349
350#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct SessionInfo {
352 pub title: Option<String>,
353 pub last_updated: String,
354 pub total_tokens_used: usize,
355 pub status: SessionStatus,
356 #[serde(default)]
357 pub threads: Vec<SubthreadInfo>,
358 /// If set, this session lives on a remote daemon with this name.
359 #[serde(default)]
360 pub remote: Option<String>,
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize)]
364pub struct SubthreadInfo {
365 pub thread_id: String,
366 pub parent_thread_id: String,
367 pub title: Option<String>,
368}
369
370#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct TokenUsage {
372 pub input_tokens: Option<u64>,
373 pub output_tokens: Option<u64>,
374 /// Total tokens including cached input. When prompt caching is active,
375 /// `input_tokens` only reflects uncached input, so consumers should prefer
376 /// `total_tokens` (falling back to `input + output` if absent for
377 /// backwards compatibility).
378 #[serde(default)]
379 pub total_tokens: Option<u64>,
380}
381
382#[derive(Debug, Clone, Serialize, Deserialize)]
383pub struct ModelInfo {
384 pub display_name: String,
385 /// The provider this model belongs to.
386 #[serde(default)]
387 pub provider_id: String,
388 pub model_id: String,
389 pub context_window: usize,
390}
391
392/// Globally unique reference to a model: a provider id plus the model's
393/// provider-scoped id.
394#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
395pub struct ModelRef {
396 pub provider_id: String,
397 pub model_id: String,
398}
399
400#[derive(Debug, Clone, Serialize, Deserialize)]
401pub struct RemoteInfo {
402 pub name: String,
403 pub status: String,
404}