telepi 0.2.1

Telegram bridge for the Pi coding agent — Rust implementation
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;

use serde::Deserialize;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::{mpsc, Mutex};
use tracing::{error, info, warn};

use crate::config::TelePiConfig;
use crate::error::{Result, TelePiError};
use crate::pi::session::*;

/// Pi session backed by the `pi` CLI subprocess.
///
/// Uses `pi --mode json --print` for structured streaming output.
/// Each line from stdout is a JSON event that gets parsed into `PiEvent`s.
#[allow(dead_code)]
pub struct CliSession {
    config: Arc<TelePiConfig>,
    ctx: SessionContext,
    session_path: PathBuf,
    workspace: PathBuf,
    session_id: String,
    model: Mutex<Option<String>>,
    /// Handle to the currently running child process (for abort).
    running_child: Arc<Mutex<Option<Child>>>,
}

impl std::fmt::Debug for CliSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CliSession")
            .field("session_id", &self.session_id)
            .field("workspace", &self.workspace)
            .finish()
    }
}

// --- JSON event types from `pi --mode json` ---

#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
#[allow(dead_code)]
enum JsonEvent {
    #[serde(rename = "session")]
    Session { id: Option<String> },
    #[serde(rename = "agent_start")]
    AgentStart,
    #[serde(rename = "agent_end")]
    AgentEnd,
    #[serde(rename = "turn_start")]
    TurnStart,
    #[serde(rename = "turn_end")]
    TurnEnd { message: Option<JsonMessage> },
    #[serde(rename = "message_start")]
    MessageStart { message: JsonMessage },
    #[serde(rename = "message_end")]
    MessageEnd { message: JsonMessage },
    #[serde(rename = "message_update")]
    MessageUpdate { #[serde(rename = "assistantMessageEvent")] assistant_message_event: Option<AssistantMessageEvent> },
    /// Catch-all for unknown events.
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct JsonMessage {
    role: Option<String>,
    content: Option<serde_json::Value>,
    usage: Option<JsonUsage>,
    #[serde(rename = "stopReason")]
    stop_reason: Option<String>,
    #[serde(rename = "responseId")]
    response_id: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct JsonUsage {
    input: Option<u64>,
    output: Option<u64>,
    #[serde(rename = "cacheRead")]
    cache_read: Option<u64>,
    #[serde(rename = "cacheWrite")]
    cache_write: Option<u64>,
    cost: Option<JsonCost>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct JsonCost {
    total: Option<f64>,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
#[allow(dead_code)]
enum AssistantMessageEvent {
    #[serde(rename = "thinking_start")]
    ThinkingStart { content_index: Option<u32>, partial: Option<JsonMessage> },
    #[serde(rename = "thinking_delta")]
    ThinkingDelta { delta: String, content_index: Option<u32>, partial: Option<JsonMessage> },
    #[serde(rename = "thinking_end")]
    ThinkingEnd { content_index: Option<u32>, content: Option<String> },
    #[serde(rename = "text_start")]
    TextStart { content_index: Option<u32>, partial: Option<JsonMessage> },
    #[serde(rename = "text_delta")]
    TextDelta { delta: String, content_index: Option<u32>, partial: Option<JsonMessage> },
    #[serde(rename = "text_end")]
    TextEnd { content_index: Option<u32>, content: Option<String> },
    #[serde(rename = "tool_start")]
    ToolStart {
        tool_name: Option<String>,
        #[serde(rename = "toolCallId")]
        tool_call_id: Option<String>,
        #[serde(rename = "toolCall")]
        tool_call: Option<ToolCallInfo>,
        partial: Option<JsonMessage>,
    },
    #[serde(rename = "tool_update")]
    ToolUpdate {
        #[serde(rename = "toolCallId")]
        tool_call_id: Option<String>,
        output: Option<String>,
        partial: Option<JsonMessage>,
    },
    #[serde(rename = "tool_end")]
    ToolEnd {
        #[serde(rename = "toolCallId")]
        tool_call_id: Option<String>,
        #[serde(rename = "is_error")]
        is_error: Option<bool>,
        partial: Option<JsonMessage>,
    },
    /// Catch-all for unknown assistant events.
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct ToolCallInfo {
    name: Option<String>,
    #[serde(rename = "toolCallId")]
    tool_call_id: Option<String>,
}

/// Information about an available AI model.
#[derive(Debug, Clone)]
pub struct ModelInfo {
    pub provider: String,
    pub model: String,
    pub context_window: String,
    pub max_output: String,
    pub supports_thinking: bool,
    pub supports_images: bool,
}

impl std::fmt::Display for ModelInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", self.provider, self.model)
    }
}

/// Parse the output of `pi --list-models`.
fn parse_model_list(output: &str) -> Vec<ModelInfo> {
    let mut models = Vec::new();
    for line in output.lines().skip(1) {
        // Skip header line
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        // Split by whitespace — the format is fixed-width columns
        let parts: Vec<&str> = trimmed.split_whitespace().collect();
        if parts.len() >= 6 {
            models.push(ModelInfo {
                provider: parts[0].to_string(),
                model: parts[1].to_string(),
                context_window: parts[2].to_string(),
                max_output: parts[3].to_string(),
                supports_thinking: parts[4] == "yes",
                supports_images: parts[5] == "yes",
            });
        }
    }
    models
}
impl CliSession {
    /// Create a new CLI-backed Pi session.
    pub async fn create(
        config: Arc<TelePiConfig>,
        ctx: SessionContext,
        bootstrap_session_path: Option<PathBuf>,
    ) -> Result<Self> {
        let workspace = config.workspace.clone();
        let session_id = uuid::Uuid::new_v4().to_string();

        // If we have a bootstrap session path, use it; otherwise create a new one
        let session_path = match bootstrap_session_path {
            Some(p) if p.exists() => {
                info!(path = %p.display(), "using bootstrap session");
                p
            }
            _ => {
                // Create a new session directory
                let session_dir = dirs::data_dir()
                    .unwrap_or_else(|| PathBuf::from("/tmp"))
                    .join("telepi")
                    .join("sessions")
                    .join(&session_id);
                tokio::fs::create_dir_all(&session_dir).await?;
                session_dir
            }
        };

        Ok(Self {
            config,
            ctx,
            session_path,
            workspace,
            session_id,
            model: Mutex::new(None),
            running_child: Arc::new(Mutex::new(None)),
        })
    }

    /// Check if the `pi` CLI is available on PATH.
    pub fn pi_cli_available() -> bool {
        which::which("pi").is_ok()
    }

    /// List available models from `pi --list-models`.
    pub async fn list_models() -> Result<Vec<ModelInfo>> {
        let output = tokio::process::Command::new("pi")
            .arg("--list-models")
            .output()
            .await
            .map_err(|e| TelePiError::PiProcess(format!("failed to run pi --list-models: {e}")))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(TelePiError::PiProcess(format!("pi --list-models failed: {stderr}")));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let models = parse_model_list(&stdout);
        Ok(models)
    }
    /// Execute a streaming prompt, parsing JSON events line by line.
    async fn execute_streaming(
        &self,
        args: Vec<String>,
        tx: &mpsc::Sender<PiEvent>,
    ) -> Result<PromptResponse> {
        let pi_bin = which::which("pi")
            .map_err(|_| TelePiError::PiProcess("`pi` CLI not found on PATH".into()))?;

        info!(
            session_id = %self.session_id,
            args = ?args,
            "spawning pi CLI in streaming mode"
        );

        let mut cmd = Command::new(&pi_bin);
        cmd.args(&args)
            .current_dir(&self.workspace)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .env("PI_SESSION_PATH", &self.session_path);

        let model_guard = self.model.lock().await.clone();
        if let Some(ref m) = model_guard {
            cmd.env("PI_MODEL", m);
        }

        let child = cmd.spawn()
            .map_err(|e| TelePiError::PiProcess(format!("failed to spawn pi: {e}")))?;

        // Store the child PID for abort support
        let _child_id = child.id();
        {
            let mut running = self.running_child.lock().await;
            *running = Some(child);
        }

        // Take stdout for reading
        let stdout = {
            let mut running = self.running_child.lock().await;
            running.as_mut().and_then(|c| c.stdout.take())
        };
        let _stderr = {
            let mut running = self.running_child.lock().await;
            running.as_mut().and_then(|c| c.stderr.take())
        };

        let stdout = stdout.ok_or_else(|| TelePiError::PiProcess("no stdout from pi".into()))?;

        // Wrap the entire streaming + wait in a 10-minute timeout
        let timeout_result = tokio::time::timeout(Duration::from_secs(600), async {
            // Read JSON events line by line
            let mut accumulated_text = String::new();
            let mut tokens_in: u64 = 0;
            let mut tokens_out: u64 = 0;
            let mut cost: f64 = 0.0;
            let model_name = String::new();

        let reader = BufReader::new(stdout);
        let mut lines = reader.lines();

        while let Some(line) = lines.next_line().await.map_err(|e| {
            TelePiError::PiProcess(format!("failed to read pi output: {e}"))
        })? {
            // Skip empty lines
            if line.trim().is_empty() {
                continue;
            }

            // Parse the JSON event
            match serde_json::from_str::<JsonEvent>(&line) {
                Ok(event) => {
                    match event {
                        JsonEvent::MessageUpdate { assistant_message_event: Some(ame) } => {
                            match ame {
                                AssistantMessageEvent::ThinkingDelta { delta, .. } => {
                                    tx.send(PiEvent::ThinkingDelta { delta }).await.ok();
                                }
                                AssistantMessageEvent::TextDelta { delta, .. } => {
                                    accumulated_text.push_str(&delta);
                                    tx.send(PiEvent::TextDelta { delta }).await.ok();
                                }
                                AssistantMessageEvent::ToolStart { tool_name, tool_call_id, .. } => {
                                    let name = tool_name.unwrap_or_else(|| "unknown".into());
                                    let id = tool_call_id.unwrap_or_else(|| "unknown".into());
                                    tx.send(PiEvent::ToolStart {
                                        tool_name: name,
                                        tool_call_id: id,
                                    }).await.ok();
                                }
                                AssistantMessageEvent::ToolEnd { tool_call_id, is_error: _, .. } => {
                                    let id = tool_call_id.unwrap_or_else(|| "unknown".into());
                                    tx.send(PiEvent::ToolEnd {
                                        tool_call_id: id,
                                    }).await.ok();
                                }
                                _ => {
                                    // thinking_start, thinking_end, text_start, text_end,
                                    // tool_update, unknown — skip for now
                                }
                            }
                        }
                        JsonEvent::MessageUpdate { assistant_message_event: None } => {
                            // No assistant event — ignore
                        }
                        JsonEvent::MessageEnd { message } => {
                            // Extract usage info from assistant message end
                            if let Some(usage) = &message.usage {
                                tokens_in = usage.input.unwrap_or(0);
                                tokens_out = usage.output.unwrap_or(0);
                                cost = usage.cost.as_ref().and_then(|c| c.total).unwrap_or(0.0);
                            }
                        }
                        JsonEvent::TurnEnd { message } => {
                            // Extract final usage if available
                            if let Some(msg) = &message {
                                if let Some(usage) = &msg.usage {
                                    tokens_in = usage.input.unwrap_or(0);
                                    tokens_out = usage.output.unwrap_or(0);
                                    cost = usage.cost.as_ref().and_then(|c| c.total).unwrap_or(0.0);
                                }
                            }
                        }
                        JsonEvent::Session { .. }
                        | JsonEvent::AgentStart
                        | JsonEvent::AgentEnd
                        | JsonEvent::MessageStart { .. }
                        | JsonEvent::TurnStart => {
                            // Lifecycle events — ignore for now
                        }
                        JsonEvent::Unknown => {
                            // Unknown event type — ignore
                        }
                    }
                }
                Err(_) => {
                    // Not a JSON event line — might be plain text output (fallback)
                    // Only accumulate if we haven't gotten any text_delta events
                    if accumulated_text.is_empty() {
                        if !accumulated_text.is_empty() {
                            accumulated_text.push('\n');
                        }
                        accumulated_text.push_str(&line);
                    }
                }
            }
        }

        // Wait for child to exit
        let exit_status = {
            let mut running = self.running_child.lock().await;
            if let Some(ref mut child) = *running {
                child.wait().await.map_err(|e| {
                    TelePiError::PiProcess(format!("pi process error: {e}"))
                })?
            } else {
                return Err(TelePiError::PiProcess("child process disappeared".into()));
            }
        };

        // Clear the running child
        {
            let mut running = self.running_child.lock().await;
            *running = None;
        }

        // If the process failed and we have no output, report error
        if !exit_status.success() && accumulated_text.is_empty() {
            error!("pi process exited with error");
            return Err(TelePiError::PiProcess(
                "pi process failed — check pi CLI output".into()
            ));
        }

        // Send usage event
        tx.send(PiEvent::Usage {
            tokens_in,
            tokens_out,
            cost,
            model: model_name,
        }).await.ok();

        // Send turn end event
        tx.send(PiEvent::TurnEnd {
            text: accumulated_text.clone(),
        }).await.ok();

        info!(
            text_len = accumulated_text.len(),
            tokens_in,
            tokens_out,
            "streaming complete"
        );

            Ok(PromptResponse {
                text: accumulated_text,
                tool_calls: vec![],
            })
        }).await;

        match timeout_result {
            Ok(result) => result,
            Err(_elapsed) => {
                warn!(
                    session_id = %self.session_id,
                    "pi process timed out after 600s, killing"
                );
                let mut running = self.running_child.lock().await;
                if let Some(ref mut child) = *running {
                    child.kill().await.ok();
                }
                *running = None;
                Err(TelePiError::PiProcess(
                    "pi process timed out after 10 minutes".into()
                ))
            }
        }
    }
}

#[async_trait::async_trait]
impl PiSession for CliSession {
    fn info(&self) -> SessionInfo {
        SessionInfo {
            session_id: self.session_id.clone(),
            session_path: self.session_path.clone(),
            workspace: self.workspace.clone(),
            model: self.model.try_lock().ok().and_then(|g| g.clone()),
            session_name: None,
        }
    }

    async fn stats(&self) -> SessionStats {
        // TODO: Parse session JSONL file for actual stats
        SessionStats {
            session_id: self.session_id.clone(),
            total_messages: 0,
            tokens_in: 0,
            tokens_out: 0,
            cost: 0.0,
        }
    }

    async fn prompt(&self, text: &str) -> Result<PromptResponse> {
        let (tx, _rx) = mpsc::channel(256);
        let args = vec![
            "--mode".to_string(), "json".to_string(),
            "--print".to_string(),
            text.to_string(),
        ];
        self.execute_streaming(args, &tx).await
    }

    async fn prompt_with_images(&self, text: &str, images: &[PathBuf]) -> Result<PromptResponse> {
        if images.is_empty() {
            return self.prompt(text).await;
        }

        let (tx, _rx) = mpsc::channel(256);

        // Build args with @file syntax for images
        let mut args = vec![
            "--mode".to_string(), "json".to_string(),
            "--print".to_string(),
        ];
        for img in images {
            args.push(format!("@{}", img.display()));
        }
        args.push(text.to_string());

        self.execute_streaming(args, &tx).await
    }

    async fn prompt_streaming(
        &self,
        text: &str,
        tx: mpsc::Sender<PiEvent>,
    ) -> Result<PromptResponse> {
        let args = vec![
            "--mode".to_string(), "json".to_string(),
            "--print".to_string(),
            text.to_string(),
        ];
        self.execute_streaming(args, &tx).await
    }

    async fn abort(&self) -> Result<()> {
        let mut running = self.running_child.lock().await;
        if let Some(ref mut child) = *running {
            if let Some(pid) = child.id() {
                info!(pid, "sending SIGTERM to pi process");
                // Send SIGTERM first, then SIGKILL if needed
                #[cfg(unix)]
                {
                    unsafe { libc::kill(pid as i32, libc::SIGTERM); }
                }
            }
        } else {
            warn!("abort called but no running process");
        }
        Ok(())
    }

    async fn set_model(&self, model: &str) -> Result<()> {
        let mut guard = self.model.lock().await;
        *guard = Some(model.to_string());
        info!(model = model, "model set");
        Ok(())
    }

    async fn dispose(&self) -> Result<()> {
        info!(session_id = %self.session_id, "disposing session");
        Ok(())
    }
}