juglans 0.2.19

Compiler and runtime for Juglans Workflow Language
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
// src/adapters/telegram.rs
#![cfg(not(target_arch = "wasm32"))]

use anyhow::Result;
use dashmap::DashSet;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{error, info};

use super::{run_agent_for_message, PlatformMessage};
use crate::services::config::JuglansConfig;

// ======================================================================
// Public webhook handler (for web_server.rs serverless integration)
// ======================================================================

/// Telegram webhook handler, embeddable in web_server.
///
/// Receives Telegram Bot API webhook pushes, processes messages and replies.
/// Suitable for serverless deployment (FC containers are not suited for long-polling).
pub struct TelegramWebhookHandler {
    config: JuglansConfig,
    project_root: PathBuf,
    agent_slug: String,
    token: String,
    processed_updates: DashSet<i64>,
}

impl TelegramWebhookHandler {
    /// Create from JuglansConfig; returns Some if Telegram config is complete
    pub fn from_config(config: &JuglansConfig, project_root: &Path) -> Option<Self> {
        let bot_config = config.bot.as_ref()?.telegram.as_ref()?;
        let token = bot_config.token.clone();
        let agent_slug = bot_config.agent.clone();

        Some(Self {
            config: config.clone(),
            project_root: project_root.to_path_buf(),
            agent_slug,
            token,
            processed_updates: DashSet::new(),
        })
    }

    /// Handle Telegram webhook Update JSON, return response
    pub async fn handle_update(&self, body: Value) -> Value {
        let update_id = body["update_id"].as_i64().unwrap_or(0);

        // Deduplication
        if update_id != 0 && !self.processed_updates.insert(update_id) {
            return json!({"ok": true, "description": "duplicate"});
        }

        // Extract message
        let msg = match body.get("message") {
            Some(m) => m,
            None => return json!({"ok": true}),
        };

        let text = msg["text"].as_str().unwrap_or("").to_string();
        if text.is_empty() {
            return json!({"ok": true});
        }

        let chat_id = msg["chat"]["id"].as_i64().unwrap_or(0);
        let user_id = msg["from"]["id"].as_i64().unwrap_or(0).to_string();
        let username = msg["from"]["username"].as_str().map(|s| s.to_string());
        let first_name = msg["from"]["first_name"].as_str().unwrap_or("User");

        info!(
            "[Telegram Webhook] {} (@{}): {}",
            first_name,
            username.as_deref().unwrap_or("?"),
            if text.chars().count() > 50 {
                &text[..text
                    .char_indices()
                    .nth(50)
                    .map(|(i, _)| i)
                    .unwrap_or(text.len())]
            } else {
                &text
            }
        );

        let platform_msg = PlatformMessage {
            event_type: "message".into(),
            event_data: json!({ "text": &text }),
            platform_user_id: user_id,
            platform_chat_id: chat_id.to_string(),
            text,
            username,
            platform: "telegram".into(),
        };

        // Process asynchronously (don't block webhook response)
        let config = self.config.clone();
        let project_root = self.project_root.clone();
        let agent_slug = self.agent_slug.clone();
        let token = self.token.clone();

        tokio::spawn(async move {
            let base_url = format!("https://api.telegram.org/bot{}", token);
            let client = reqwest::Client::new();

            // Send typing status
            let _ = client
                .post(format!("{}/sendChatAction", base_url))
                .json(&json!({"chat_id": chat_id, "action": "typing"}))
                .send()
                .await;

            let result =
                run_agent_for_message(&config, &project_root, &agent_slug, &platform_msg, None)
                    .await;

            match result {
                Ok(reply) => {
                    if reply.text.is_empty() || reply.text == "(No response)" {
                        return;
                    }
                    let chunks = split_message(&reply.text, 4096);
                    for chunk in chunks {
                        let send_result = client
                            .post(format!("{}/sendMessage", base_url))
                            .json(&json!({
                                "chat_id": chat_id,
                                "text": chunk,
                                "parse_mode": "Markdown"
                            }))
                            .send()
                            .await;

                        if let Err(e) = send_result {
                            error!("[Telegram Webhook] Send failed: {}", e);
                            let _ = client
                                .post(format!("{}/sendMessage", base_url))
                                .json(&json!({"chat_id": chat_id, "text": chunk}))
                                .send()
                                .await;
                        }
                    }
                }
                Err(e) => {
                    error!("[Telegram Webhook] Agent error: {}", e);
                    let _ = client
                        .post(format!("{}/sendMessage", base_url))
                        .json(&json!({"chat_id": chat_id, "text": format!("Error: {}", e)}))
                        .send()
                        .await;
                }
            }
        });

        json!({"ok": true})
    }
}

/// Start Telegram Bot (long polling mode)
pub async fn start(config: JuglansConfig, project_root: PathBuf, agent_slug: String) -> Result<()> {
    let bot_config = config
        .bot
        .as_ref()
        .and_then(|b| b.telegram.as_ref())
        .ok_or_else(|| anyhow::anyhow!("Missing [bot.telegram] config in juglans.toml"))?;

    let token = bot_config.token.clone();

    info!("🤖 Starting Telegram Bot...");
    info!("   Agent: {}", agent_slug);

    let client = reqwest::Client::new();
    let base_url = format!("https://api.telegram.org/bot{}", token);

    // Verify token
    let me_resp: serde_json::Value = client
        .get(format!("{}/getMe", base_url))
        .send()
        .await?
        .json()
        .await?;

    if me_resp["ok"].as_bool() != Some(true) {
        return Err(anyhow::anyhow!("Invalid Telegram bot token: {:?}", me_resp));
    }

    let bot_name = me_resp["result"]["username"].as_str().unwrap_or("unknown");
    info!("   Bot: @{}", bot_name);
    info!("   Ready! Waiting for messages...");

    let config = Arc::new(config);
    let project_root = Arc::new(project_root);
    let agent_slug = Arc::new(agent_slug);

    // Long polling loop
    let mut offset: i64 = 0;

    loop {
        let updates: serde_json::Value = match client
            .get(format!("{}/getUpdates", base_url))
            .query(&[
                ("offset", offset.to_string()),
                ("timeout", "30".to_string()),
            ])
            .send()
            .await
        {
            Ok(resp) => match resp.json().await {
                Ok(v) => v,
                Err(e) => {
                    error!("Failed to parse updates: {}", e);
                    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
                    continue;
                }
            },
            Err(e) => {
                error!("Failed to get updates: {}", e);
                tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
                continue;
            }
        };

        if let Some(results) = updates["result"].as_array() {
            for update in results {
                let update_id = update["update_id"].as_i64().unwrap_or(0);
                offset = update_id + 1;

                // Extract message
                let msg = if let Some(m) = update.get("message") {
                    m
                } else {
                    continue;
                };

                let text = msg["text"].as_str().unwrap_or("").to_string();
                if text.is_empty() {
                    continue;
                }

                let chat_id = msg["chat"]["id"].as_i64().unwrap_or(0);
                let user_id = msg["from"]["id"].as_i64().unwrap_or(0).to_string();
                let username = msg["from"]["username"].as_str().map(|s| s.to_string());
                let first_name = msg["from"]["first_name"].as_str().unwrap_or("User");

                info!(
                    "📩 [Telegram] {} (@{}): {}",
                    first_name,
                    username.as_deref().unwrap_or("?"),
                    if text.len() > 50 { &text[..50] } else { &text }
                );

                // Process message asynchronously
                let config = config.clone();
                let project_root = project_root.clone();
                let agent_slug = agent_slug.clone();
                let client = client.clone();
                let base_url = base_url.clone();

                tokio::spawn(async move {
                    let platform_msg = PlatformMessage {
                        event_type: "message".into(),
                        event_data: serde_json::json!({ "text": &text }),
                        platform_user_id: user_id,
                        platform_chat_id: chat_id.to_string(),
                        text,
                        username,
                        platform: "telegram".into(),
                    };

                    // Send "typing" status
                    let _ = client
                        .post(format!("{}/sendChatAction", base_url))
                        .json(&serde_json::json!({
                            "chat_id": chat_id,
                            "action": "typing"
                        }))
                        .send()
                        .await;

                    match run_agent_for_message(
                        &config,
                        &project_root,
                        &agent_slug,
                        &platform_msg,
                        None,
                    )
                    .await
                    {
                        Ok(reply) => {
                            // Send in chunks (Telegram message limit: 4096 characters)
                            let chunks = split_message(&reply.text, 4096);
                            for chunk in chunks {
                                let send_result = client
                                    .post(format!("{}/sendMessage", base_url))
                                    .json(&serde_json::json!({
                                        "chat_id": chat_id,
                                        "text": chunk,
                                        "parse_mode": "Markdown"
                                    }))
                                    .send()
                                    .await;

                                if let Err(e) = send_result {
                                    error!("Failed to send message: {}", e);
                                    // Fallback: retry without parse_mode
                                    let _ = client
                                        .post(format!("{}/sendMessage", base_url))
                                        .json(&serde_json::json!({
                                            "chat_id": chat_id,
                                            "text": chunk
                                        }))
                                        .send()
                                        .await;
                                }
                            }
                        }
                        Err(e) => {
                            error!("Agent execution failed: {}", e);
                            let _ = client
                                .post(format!("{}/sendMessage", base_url))
                                .json(&serde_json::json!({
                                    "chat_id": chat_id,
                                    "text": format!("❌ Error: {}", e)
                                }))
                                .send()
                                .await;
                        }
                    }
                });
            }
        }
    }
}

/// Telegram Bot API base URL.
pub(crate) const TELEGRAM_API: &str = "https://api.telegram.org";

/// Telegram message character limit.
pub(crate) const TELEGRAM_MAX_LEN: usize = 4096;

/// Send a text message to a Telegram chat. Falls back to plain-text if
/// `parse_mode`-formatted send fails (typical cause: malformed Markdown).
/// Chunks long messages using `split_message`.
pub(crate) async fn send_message_api(
    http: &reqwest::Client,
    token: &str,
    chat_id: &str,
    text: &str,
    parse_mode: Option<&str>,
) -> anyhow::Result<usize> {
    let base_url = format!("{}/bot{}", TELEGRAM_API, token);
    let chunks = split_message(text, TELEGRAM_MAX_LEN);
    let chunk_count = chunks.len();
    for chunk in chunks {
        let mut body = serde_json::json!({
            "chat_id": chat_id,
            "text": chunk,
        });
        if let Some(pm) = parse_mode {
            body["parse_mode"] = serde_json::json!(pm);
        }
        let resp = http
            .post(format!("{}/sendMessage", base_url))
            .json(&body)
            .send()
            .await?;
        if resp.status().is_success() {
            continue;
        }
        // Fallback without parse_mode
        let resp2 = http
            .post(format!("{}/sendMessage", base_url))
            .json(&serde_json::json!({
                "chat_id": chat_id,
                "text": chunk,
            }))
            .send()
            .await?;
        if !resp2.status().is_success() {
            let status = resp2.status();
            let err = resp2.text().await.unwrap_or_default();
            return Err(anyhow::anyhow!(
                "Telegram sendMessage failed: {} {}",
                status,
                err
            ));
        }
    }
    Ok(chunk_count)
}

/// Send typing action (auto-expires after a few seconds, best-effort).
pub(crate) async fn send_typing(http: &reqwest::Client, token: &str, chat_id: &str) {
    let base_url = format!("{}/bot{}", TELEGRAM_API, token);
    let _ = http
        .post(format!("{}/sendChatAction", base_url))
        .json(&serde_json::json!({
            "chat_id": chat_id,
            "action": "typing",
        }))
        .send()
        .await;
}

/// Edit a previously-sent message.
pub(crate) async fn edit_message_api(
    http: &reqwest::Client,
    token: &str,
    chat_id: &str,
    message_id: i64,
    text: &str,
    parse_mode: Option<&str>,
) -> anyhow::Result<()> {
    let base_url = format!("{}/bot{}", TELEGRAM_API, token);
    let mut body = serde_json::json!({
        "chat_id": chat_id,
        "message_id": message_id,
        "text": text,
    });
    if let Some(pm) = parse_mode {
        body["parse_mode"] = serde_json::json!(pm);
    }
    let resp = http
        .post(format!("{}/editMessageText", base_url))
        .json(&body)
        .send()
        .await?;
    if !resp.status().is_success() {
        let status = resp.status();
        let err = resp.text().await.unwrap_or_default();
        return Err(anyhow::anyhow!(
            "Telegram editMessageText failed: {} {}",
            status,
            err
        ));
    }
    Ok(())
}

/// Split long message into chunks (Telegram limit: 4096 characters).
/// Prefers splitting at a newline, falls back to `max_len`.
pub(crate) fn split_message(text: &str, max_len: usize) -> Vec<String> {
    if text.len() <= max_len {
        return vec![text.to_string()];
    }

    let mut chunks = Vec::new();
    let mut remaining = text;

    while !remaining.is_empty() {
        if remaining.len() <= max_len {
            chunks.push(remaining.to_string());
            break;
        }

        // Try to split at a newline
        let split_pos = remaining[..max_len].rfind('\n').unwrap_or(max_len);

        chunks.push(remaining[..split_pos].to_string());
        remaining = remaining[split_pos..].trim_start();
    }

    chunks
}