collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
//! Slack adapter — reqwest (HTTP API) + tokio-tungstenite 0.26 (Socket Mode).
//!
//! Feature-gated behind `slack`. Max message: ~4000 chars.

use anyhow::{Context, Result};
use async_trait::async_trait;
use futures::{SinkExt, StreamExt};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message as WsMessage;

use super::adapter::{ChannelId, IncomingCommand, PlatformAdapter};
use super::commands::parse_remote_command;

// ---------------------------------------------------------------------------
// WebSocket type aliases
// ---------------------------------------------------------------------------

type WsStream =
    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
type WsSink = futures::stream::SplitSink<WsStream, WsMessage>;

// ---------------------------------------------------------------------------
// Adapter
// ---------------------------------------------------------------------------

pub struct SlackAdapter {
    bot_token: String,
    app_token: String,
    client: reqwest::Client,
}

impl SlackAdapter {
    pub fn new(bot_token: String, app_token: String) -> Self {
        Self {
            bot_token,
            app_token,
            client: reqwest::Client::new(),
        }
    }

    // -----------------------------------------------------------------------
    // HTTP helpers
    // -----------------------------------------------------------------------

    /// POST to `https://slack.com/api/{method}` with Bearer bot_token.
    async fn api_post(&self, method: &str, body: Value) -> Result<Value> {
        let url = format!("https://slack.com/api/{method}");
        let resp: Value = self
            .client
            .post(&url)
            .bearer_auth(&self.bot_token)
            .json(&body)
            .send()
            .await
            .with_context(|| format!("slack api request failed: {method}"))?
            .json()
            .await
            .with_context(|| format!("slack api response parse failed: {method}"))?;

        if resp.get("ok") != Some(&Value::Bool(true)) {
            let err = resp["error"].as_str().unwrap_or("unknown");
            anyhow::bail!("slack api {method} error: {err}");
        }

        Ok(resp)
    }

    /// Build the base JSON body for a message to a channel, including
    /// `thread_ts` when the channel has a thread set.
    fn message_body(channel: &ChannelId) -> Value {
        let mut body = json!({ "channel": channel.channel });
        if let Some(ref ts) = channel.thread {
            body["thread_ts"] = json!(ts);
        }
        body
    }

    // -----------------------------------------------------------------------
    // Socket Mode helpers
    // -----------------------------------------------------------------------

    /// Request a fresh WebSocket URL via `apps.connections.open` using the
    /// **app-level token** (not the bot token).
    async fn open_socket_url(&self) -> Result<String> {
        let resp: Value = self
            .client
            .post("https://slack.com/api/apps.connections.open")
            .bearer_auth(&self.app_token)
            .json(&json!({}))
            .send()
            .await
            .context("apps.connections.open request failed")?
            .json()
            .await
            .context("apps.connections.open parse failed")?;

        if resp.get("ok") != Some(&Value::Bool(true)) {
            let err = resp["error"].as_str().unwrap_or("unknown");
            anyhow::bail!("apps.connections.open error: {err}");
        }

        resp["url"]
            .as_str()
            .map(String::from)
            .context("apps.connections.open: missing url field")
    }

    /// Send an envelope acknowledgement over the WebSocket sink.
    async fn ack_envelope(sink: &mut WsSink, envelope_id: &str) -> Result<()> {
        let ack = json!({ "envelope_id": envelope_id }).to_string();
        sink.send(WsMessage::Text(ack.into())).await?;
        Ok(())
    }

    /// Dispatch a single Socket Mode envelope.
    fn handle_socket_event(envelope: &Value, command_tx: &mpsc::UnboundedSender<IncomingCommand>) {
        let event_type = match envelope["type"].as_str() {
            Some(t) => t,
            None => return,
        };

        match event_type {
            "hello" => {
                tracing::info!("[slack] socket mode connected (hello)");
            }
            "disconnect" => {
                tracing::warn!("[slack] server requested disconnect");
            }
            "events_api" => {
                Self::handle_events_api(envelope, command_tx);
            }
            "interactive" => {
                Self::handle_interactive(envelope, command_tx);
            }
            "slash_commands" => {
                Self::handle_slash_command(envelope, command_tx);
            }
            other => {
                tracing::debug!("[slack] unhandled envelope type: {other}");
            }
        }
    }

    /// Handle an `events_api` envelope — currently only `message` events.
    fn handle_events_api(envelope: &Value, command_tx: &mpsc::UnboundedSender<IncomingCommand>) {
        let event = &envelope["payload"]["event"];

        // Only handle plain user messages (no bots, no subtypes like
        // message_changed, message_deleted, etc.)
        if event["type"].as_str() != Some("message") {
            return;
        }
        if event.get("bot_id").is_some() || event.get("subtype").is_some() {
            return;
        }

        let text = match event["text"].as_str() {
            Some(t) if !t.is_empty() => t,
            _ => return,
        };
        let ch = match event["channel"].as_str() {
            Some(c) => c,
            None => return,
        };
        let user = event["user"].as_str().unwrap_or("unknown");

        let mut channel = ChannelId::new("slack", ch);
        if let Some(ts) = event["thread_ts"].as_str() {
            channel = channel.with_thread(ts);
        }

        let command = parse_remote_command(text);
        let _ = command_tx.send(IncomingCommand {
            channel,
            user_id: user.to_string(),
            command,
        });
    }

    /// Handle an `interactive` envelope — button clicks (block actions).
    fn handle_interactive(envelope: &Value, command_tx: &mpsc::UnboundedSender<IncomingCommand>) {
        let payload = &envelope["payload"];
        let actions = match payload["actions"].as_array() {
            Some(a) => a,
            None => return,
        };

        let ch = match payload["channel"]["id"].as_str() {
            Some(c) => c,
            None => return,
        };
        let user = payload["user"]["id"].as_str().unwrap_or("unknown");

        let mut channel = ChannelId::new("slack", ch);
        if let Some(ts) = payload["message"]["thread_ts"].as_str() {
            channel = channel.with_thread(ts);
        }

        for action in actions {
            let action_id = match action["action_id"].as_str() {
                Some(a) => a,
                None => continue,
            };

            let command = parse_remote_command(action_id);
            let _ = command_tx.send(IncomingCommand {
                channel: channel.clone(),
                user_id: user.to_string(),
                command,
            });
        }
    }

    /// Handle a `slash_commands` envelope — native Slack slash commands.
    fn handle_slash_command(envelope: &Value, command_tx: &mpsc::UnboundedSender<IncomingCommand>) {
        let payload = &envelope["payload"];

        let command_name = match payload["command"].as_str() {
            Some(c) => c,
            None => return,
        };

        let ch = match payload["channel_id"].as_str() {
            Some(c) => c,
            None => return,
        };
        let user = payload["user_id"].as_str().unwrap_or("unknown");

        let channel = ChannelId::new("slack", ch);
        let command = parse_remote_command(command_name);

        let _ = command_tx.send(IncomingCommand {
            channel,
            user_id: user.to_string(),
            command,
        });
    }
}

// ---------------------------------------------------------------------------
// PlatformAdapter
// ---------------------------------------------------------------------------

#[async_trait]
impl PlatformAdapter for SlackAdapter {
    fn platform_name(&self) -> &str {
        "slack"
    }

    fn max_message_length(&self) -> usize {
        4000
    }

    async fn register_commands(&self, commands: &[(&str, &str)]) -> Result<()> {
        // Slack does not support runtime slash-command registration.
        // Slash commands must be pre-registered in the Slack App Dashboard.
        // Skill names are surfaced to users via /help instead.
        if !commands.is_empty() {
            tracing::info!(
                "[slack] {} skill(s) available via /help (Slack requires static app-dashboard registration)",
                commands.len()
            );
        }
        Ok(())
    }

    async fn send_message(&self, channel: &ChannelId, text: &str) -> Result<()> {
        let mut body = Self::message_body(channel);
        body["text"] = json!(text);
        self.api_post("chat.postMessage", body).await?;
        Ok(())
    }

    async fn send_long_message(
        &self,
        channel: &ChannelId,
        text: &str,
        filename: Option<&str>,
    ) -> Result<()> {
        if text.len() <= self.max_message_length() {
            return self.send_message(channel, text).await;
        }

        let name = filename.unwrap_or("response.txt");
        let filetype = if name.ends_with(".md") {
            "markdown"
        } else {
            "text"
        };

        // files.upload uses multipart form, not JSON.
        let form = reqwest::multipart::Form::new()
            .text("channels", channel.channel.clone())
            .text("content", text.to_string())
            .text("filename", name.to_string())
            .text("filetype", filetype.to_string());

        let resp: Value = self
            .client
            .post("https://slack.com/api/files.upload")
            .bearer_auth(&self.bot_token)
            .multipart(form)
            .send()
            .await?
            .json()
            .await?;

        if resp.get("ok") != Some(&Value::Bool(true)) {
            tracing::warn!(
                "[slack] files.upload failed ({}), falling back to send_message",
                resp["error"].as_str().unwrap_or("unknown")
            );
            // Truncate to fit and send as a plain message.
            let truncated = if text.len() > self.max_message_length() {
                &text[..self.max_message_length()]
            } else {
                text
            };
            return self.send_message(channel, truncated).await;
        }

        Ok(())
    }

    async fn send_buttons(
        &self,
        channel: &ChannelId,
        text: &str,
        buttons: &[(String, String)],
    ) -> Result<()> {
        let button_elements: Vec<Value> = buttons
            .iter()
            .map(|(label, data)| {
                json!({
                    "type": "button",
                    "text": { "type": "plain_text", "text": label },
                    "action_id": data,
                })
            })
            .collect();

        let blocks = json!([
            {
                "type": "section",
                "text": { "type": "mrkdwn", "text": text },
            },
            {
                "type": "actions",
                "elements": button_elements,
            }
        ]);

        let mut body = Self::message_body(channel);
        body["text"] = json!(text);
        body["blocks"] = blocks;

        self.api_post("chat.postMessage", body).await?;
        Ok(())
    }

    async fn edit_message(
        &self,
        channel: &ChannelId,
        message_id: &str,
        new_text: &str,
    ) -> Result<bool> {
        let body = json!({
            "channel": channel.channel,
            "ts": message_id,
            "text": new_text,
        });
        self.api_post("chat.update", body).await?;
        Ok(true)
    }

    async fn run(&self, command_tx: mpsc::UnboundedSender<IncomingCommand>) -> Result<()> {
        tracing::info!("[slack] adapter starting with Socket Mode (tokio-tungstenite)");

        loop {
            match self.run_socket_connection(&command_tx).await {
                Ok(()) => {
                    tracing::info!("[slack] socket closed gracefully, reconnecting...");
                }
                Err(e) => {
                    tracing::warn!("[slack] socket error: {e:#}, reconnecting in 5s...");
                }
            }
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
        }
    }
}

impl SlackAdapter {
    /// Run a single Socket Mode connection until disconnect or error.
    async fn run_socket_connection(
        &self,
        command_tx: &mpsc::UnboundedSender<IncomingCommand>,
    ) -> Result<()> {
        let url = self.open_socket_url().await?;
        tracing::debug!("[slack] connecting to socket mode endpoint");

        let (ws_stream, _) = tokio_tungstenite::connect_async(&url)
            .await
            .context("websocket connect failed")?;

        let (mut sink, mut stream) = ws_stream.split();

        while let Some(msg) = stream.next().await {
            let msg = match msg {
                Ok(m) => m,
                Err(e) => {
                    tracing::warn!("[slack] websocket read error: {e}");
                    break;
                }
            };

            match msg {
                WsMessage::Text(text) => {
                    let envelope: Value = match serde_json::from_str(&text) {
                        Ok(v) => v,
                        Err(e) => {
                            tracing::debug!("[slack] invalid json envelope: {e}");
                            continue;
                        }
                    };

                    // Acknowledge the envelope before processing.
                    if let Some(id) = envelope["envelope_id"].as_str()
                        && let Err(e) = Self::ack_envelope(&mut sink, id).await
                    {
                        tracing::warn!("[slack] ack failed: {e}");
                        break;
                    }

                    // Check for disconnect request before dispatching.
                    if envelope["type"].as_str() == Some("disconnect") {
                        Self::handle_socket_event(&envelope, command_tx);
                        break;
                    }

                    Self::handle_socket_event(&envelope, command_tx);
                }
                WsMessage::Close(_) => {
                    tracing::info!("[slack] websocket close frame received");
                    break;
                }
                WsMessage::Ping(data) => {
                    let _ = sink.send(WsMessage::Pong(data)).await;
                }
                _ => {}
            }
        }

        Ok(())
    }
}