clawgarden-agent 0.18.0

Agent runtime with persona/memory loader, judge, and pi RPC for ClawGarden
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
//! Intent Generator — BIMR Step 1+2: Agent decides whether to respond.
//!
//! Uses the intent model (e.g., glm-4.5-air) to generate a cheap,
//! structured intent JSON. Output is ~40 tokens, not a full response.

use anyhow::{Context, Result};
use clawgarden_proto::IntentResponsePayload;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::time::Duration;

use crate::pi_rpc::intent_model_config;

// ── OpenAI-compatible chat types (intent model) ─────────────────────────────

#[derive(Debug, Serialize)]
struct ChatRequest {
    model: String,
    messages: Vec<SerMessage>,
    max_tokens: u32,
    temperature: f32,
    #[serde(rename = "thinking", skip_serializing_if = "Option::is_none")]
    thinking: Option<ThinkingConfig>,
}

#[derive(Debug, Serialize)]
struct ThinkingConfig {
    #[serde(rename = "type")]
    config_type: String,
}

#[derive(Debug, Serialize)]
struct SerMessage {
    role: String,
    content: String,
}

#[derive(Debug, Deserialize)]
struct ChatResponse {
    choices: Vec<ChatChoice>,
}

#[derive(Debug, Deserialize)]
struct ChatChoice {
    message: ChoiceMessage,
}

#[derive(Debug, Deserialize)]
struct ChoiceMessage {
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    reasoning_content: Option<String>,
}

impl ChoiceMessage {
    fn get_text(&self) -> String {
        if let Some(ref c) = self.content {
            if !c.is_empty() {
                return c.clone();
            }
        }
        if let Some(ref r) = self.reasoning_content {
            return r.trim().to_string();
        }
        String::new()
    }
}

// ── Public API ─────────────────────────────────────────────────────────────

/// Generate an intent for the current conversation turn.
///
/// Uses the intent model to produce a structured JSON:
/// `{"want": true, "priority": 3, "reason": "...", "angle": "..."}`
///
/// On any failure, returns a default "pass" intent so the BIMR flow
/// is never blocked by a single agent's intent model error.
pub async fn generate_intent(
    agent_name: &str,
    role: &str,
    message: &str,
    history: &[String],
    turn_number: u32,
    last_speaker: Option<&str>,
    mentions: &[String],
) -> IntentResponsePayload {
    match generate_intent_inner(agent_name, role, message, history, turn_number, last_speaker, mentions).await {
        Ok(intent) => intent,
        Err(e) => {
            log::warn!(
                "Intent generation failed for {}: {} — defaulting to pass",
                agent_name,
                e
            );
            IntentResponsePayload {
                want: true,
                priority: 3,
                reason: format!("fallback: intent model unavailable ({})", e),
                angle: None,
                agent_name: agent_name.to_string(),
            }
        }
    }
}

async fn generate_intent_inner(
    agent_name: &str,
    role: &str,
    message: &str,
    history: &[String],
    turn_number: u32,
    last_speaker: Option<&str>,
    mentions: &[String],
) -> Result<IntentResponsePayload> {
    let cfg = intent_model_config()?;

    let system = build_intent_system_prompt(agent_name, role);
    let user = build_intent_user_message(message, history, turn_number, last_speaker, mentions);

    let client = Client::builder()
        .timeout(Duration::from_millis(cfg.timeout_ms))
        .build()?;

    let url = format!("{}/chat/completions", cfg.api_base);

    let request = ChatRequest {
        model: cfg.model.clone(),
        messages: vec![
            SerMessage {
                role: "system".into(),
                content: system,
            },
            SerMessage {
                role: "user".into(),
                content: user,
            },
        ],
        max_tokens: cfg.max_tokens,
        temperature: cfg.temperature,
        thinking: Some(ThinkingConfig { config_type: "disabled".to_string() }),
    };

    let mut attempts = 0u32;
    let max_attempts = 3u32;

    let response = loop {
        attempts += 1;
        let r = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", cfg.api_key))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await;

        match r {
            Ok(r) if r.status().is_success() => {
                break r.json::<ChatResponse>().await.context("Intent model parse failed")?;
            }
            Ok(r) => {
                let status = r.status();
                let body = r.text().await.unwrap_or_default();
                if (status.as_u16() == 429 || status.is_server_error()) && attempts < max_attempts {
                    log::warn!(
                        "Intent model {} (attempt {}/{}), retrying",
                        status,
                        attempts,
                        max_attempts
                    );
                    tokio::time::sleep(Duration::from_millis(attempts as u64 * 500)).await;
                    continue;
                }
                anyhow::bail!("Intent model error {}: {}", status, body);
            }
            Err(e) => anyhow::bail!("Intent model request failed: {}", e),
        }
    };

    let content = response
        .choices
        .first()
        .map(|c| c.message.get_text())
        .unwrap_or_default();

    parse_intent_response(&content, agent_name)
}

// ── Prompt Engineering ─────────────────────────────────────────────────────

fn build_intent_system_prompt(agent_name: &str, role: &str) -> String {
    let mut p = String::new();

    if !role.is_empty() {
        // Truncate role to keep prompt short for intent model
        let role_preview: String = role.chars().take(500).collect();
        p.push_str(&role_preview);
        p.push_str("\n\n");
    } else {
        p.push_str(&format!("You are {}.\n\n", agent_name));
    }

    // ── Team members ──
    let my_username = std::env::var("TELEGRAM_BOT_USERNAME").unwrap_or_default();
    if let Ok(members) = std::env::var("TEAM_MEMBERS") {
        if !members.is_empty() {
            p.push_str("Team members (name: @username):\n");
            for entry in members.split(',') {
                let entry = entry.trim();
                if !entry.is_empty() {
                    if !my_username.is_empty() && entry.contains(&format!("@{}", my_username)) {
                        p.push_str(&format!("- {} (you)\n", entry));
                    } else {
                        p.push_str(&format!("- {}\n", entry));
                    }
                }
            }
            p.push('\n');
        }
    }

    p.push_str(
        r#"You are an agent in a multi-agent team. Your task in THIS call is NOT to respond — only to decide whether you WANT to respond.

Reply with JSON only:
{"want": true/false, "priority": 1-5, "reason": "brief explanation", "angle": "one-line summary of your intended direction"}

Priority guide:
5 = This is EXACTLY my expertise, I have critical new info
4 = Strongly relevant to my role, I can add significant value
3 = Somewhat relevant, I could contribute
2 = Tangentially related, I might have something useful
1 = Not really my area, but I could respond if needed

Be honest. If someone else is better suited, set want=false.
IMPORTANT: If you are directly addressed or @mentioned, you should almost always respond with high priority (4-5)."#,
    );

    p
}

fn build_intent_user_message(
    message: &str,
    history: &[String],
    turn_number: u32,
    last_speaker: Option<&str>,
    mentions: &[String],
) -> String {
    let mut out = String::new();

    if !history.is_empty() {
        out.push_str("Recent conversation:\n");
        for line in history.iter().take(10) {
            out.push_str(line);
            out.push('\n');
        }
        out.push('\n');
    }

    out.push_str("New message:\n");
    out.push_str(message);
    out.push('\n');

    if let Some(speaker) = last_speaker {
        out.push_str(&format!(
            "\nLast speaker: {} (avoid having them speak again immediately)\n",
            speaker
        ));
    }
    out.push_str(&format!("\nTurn: {}/3\n", turn_number));

    // Explicit mention signal — the bus parsed these from @username in responses.
    if !mentions.is_empty() {
        out.push_str(&format!(
            "\n⚠️ The following team members were @mentioned in this round: {}\n",
            mentions.join(", ")
        ));
        out.push_str("If you are one of them, you are expected to respond. Set high priority (4-5).\n");
    }

    out.push_str("\nImportant: Messages in [brackets] show who said what. Do NOT repeat or rephrase what you already said. Only respond if you have NEW information or a different angle to add.\n");
    out.push_str("\nYour intent (JSON only):");

    out
}

// ── Response Parsing ───────────────────────────────────────────────────────

fn parse_intent_response(content: &str, agent_name: &str) -> Result<IntentResponsePayload> {
    let trimmed = content.trim();

    // Try to extract JSON from the response
    let json_str = if trimmed.starts_with('{') {
        trimmed.to_string()
    } else if let Some(start) = trimmed.find('{') {
        if let Some(end) = trimmed.rfind('}') {
            trimmed[start..=end].to_string()
        } else {
            trimmed.to_string()
        }
    } else {
        // No JSON found — default to pass
        log::info!(
            "Intent: model returned non-JSON for {}, defaulting to pass",
            agent_name
        );
        return Ok(IntentResponsePayload {
            want: false,
            priority: 0,
            reason: "non-JSON response".into(),
            angle: None,
            agent_name: agent_name.to_string(),
        });
    };

    // Parse the JSON
    #[derive(Deserialize)]
    struct RawIntent {
        #[serde(default)]
        want: Option<bool>,
        #[serde(default)]
        priority: Option<u8>,
        #[serde(default)]
        reason: Option<String>,
        #[serde(default)]
        angle: Option<String>,
    }

    match serde_json::from_str::<RawIntent>(&json_str) {
        Ok(raw) => Ok(IntentResponsePayload {
            want: raw.want.unwrap_or(false),
            priority: raw.priority.unwrap_or(1).min(5),
            reason: raw.reason.unwrap_or_default(),
            angle: raw.angle,
            agent_name: agent_name.to_string(),
        }),
        Err(e) => {
            log::warn!("Intent parse error for {}: {} — raw: {}", agent_name, e, json_str);
            Ok(IntentResponsePayload {
                want: false,
                priority: 0,
                reason: format!("parse error: {}", e),
                angle: None,
                agent_name: agent_name.to_string(),
            })
        }
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_intent_response_valid() {
        let json = r#"{"want": true, "priority": 4, "reason": "tech stack", "angle": "recommend Rust"}"#;
        let intent = parse_intent_response(json, "alex").unwrap();
        assert!(intent.want);
        assert_eq!(intent.priority, 4);
        assert_eq!(intent.reason, "tech stack");
        assert_eq!(intent.angle.as_deref(), Some("recommend Rust"));
    }

    #[test]
    fn test_parse_intent_response_pass() {
        let json = r#"{"want": false, "priority": 1, "reason": "not my area"}"#;
        let intent = parse_intent_response(json, "senya").unwrap();
        assert!(!intent.want);
        assert_eq!(intent.priority, 1);
    }

    #[test]
    fn test_parse_intent_response_wrapped_in_markdown() {
        let content = "```json\n{\"want\": true, \"priority\": 3, \"reason\": \"can help\"}\n```";
        let intent = parse_intent_response(content, "camus").unwrap();
        assert!(intent.want);
        assert_eq!(intent.priority, 3);
    }

    #[test]
    fn test_parse_intent_response_no_json() {
        let content = "I think someone else should respond.";
        let intent = parse_intent_response(content, "alex").unwrap();
        assert!(!intent.want);
    }

    #[test]
    fn test_parse_intent_response_priority_clamped() {
        let json = r#"{"want": true, "priority": 10, "reason": "very important"}"#;
        let intent = parse_intent_response(json, "alex").unwrap();
        assert_eq!(intent.priority, 5); // clamped to max 5
    }

    #[test]
    fn test_build_intent_system_prompt() {
        let p = build_intent_system_prompt("alex", "You are a developer.");
        assert!(p.contains("developer"));
        assert!(p.contains("JSON"));
    }

    #[test]
    fn test_build_intent_system_prompt_no_role() {
        let p = build_intent_system_prompt("alex", "");
        assert!(p.contains("alex"));
        assert!(p.contains("JSON"));
    }

    #[test]
    fn test_build_intent_user_message() {
        let msg = build_intent_user_message(
            "Hello",
            &["[senya]: Hi".to_string()],
            1,
            Some("senya"),
            &["camus".to_string()],
        );
        assert!(msg.contains("Recent conversation"));
        assert!(msg.contains("[senya]"));
        assert!(msg.contains("Hello"));
        assert!(msg.contains("Last speaker: senya"));
        assert!(msg.contains("Turn: 1/3"));
        assert!(msg.contains("@mentioned"));
    }

    #[test]
    fn test_build_intent_user_message_empty_history() {
        let msg = build_intent_user_message("Hello", &[], 2, None, &[]);
        assert!(!msg.contains("Recent conversation"));
        assert!(msg.contains("New message"));
        assert!(msg.contains("Turn: 2/3"));
        assert!(!msg.contains("@mentioned"));
    }
}