ares-server 0.6.2

A.R.E.S - Agentic Retrieval Enhanced Server: A production-grade agentic chatbot server with multi-provider LLM support, tool calling, RAG, and MCP integration
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
use sqlx::{PgPool, Row};
use crate::types::{AppError, Result};
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

fn now_ts() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

// =============================================================================
// Structs
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TenantAgent {
    pub id: String,
    pub tenant_id: String,
    pub agent_name: String,
    pub display_name: String,
    pub description: Option<String>,
    pub config: serde_json::Value,
    pub enabled: bool,
    pub created_at: i64,
    pub updated_at: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentTemplate {
    pub id: String,
    pub product_type: String,
    pub agent_name: String,
    pub display_name: String,
    pub description: Option<String>,
    pub config: serde_json::Value,
    pub created_at: i64,
}

#[derive(Debug, Deserialize)]
pub struct CreateTenantAgentRequest {
    pub agent_name: String,
    pub display_name: String,
    pub description: Option<String>,
    pub config: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub struct UpdateTenantAgentRequest {
    pub display_name: Option<String>,
    pub description: Option<String>,
    pub config: Option<serde_json::Value>,
    pub enabled: Option<bool>,
}

// =============================================================================
// Tenant Agent CRUD
// =============================================================================

pub async fn list_tenant_agents(pool: &PgPool, tenant_id: &str) -> Result<Vec<TenantAgent>> {
    let rows = sqlx::query(
        "SELECT id, tenant_id, agent_name, display_name, description, config, enabled, created_at, updated_at
         FROM tenant_agents WHERE tenant_id = $1 ORDER BY agent_name"
    )
    .bind(tenant_id)
    .fetch_all(pool)
    .await
    .map_err(|e| AppError::Database(e.to_string()))?;

    rows.iter().map(|row| {
        Ok(TenantAgent {
            id: row.get("id"),
            tenant_id: row.get("tenant_id"),
            agent_name: row.get("agent_name"),
            display_name: row.get("display_name"),
            description: row.get("description"),
            config: row.get::<serde_json::Value, _>("config"),
            enabled: row.get("enabled"),
            created_at: row.get("created_at"),
            updated_at: row.get("updated_at"),
        })
    }).collect()
}

pub async fn get_tenant_agent(pool: &PgPool, tenant_id: &str, agent_name: &str) -> Result<TenantAgent> {
    let row = sqlx::query(
        "SELECT id, tenant_id, agent_name, display_name, description, config, enabled, created_at, updated_at
         FROM tenant_agents WHERE tenant_id = $1 AND agent_name = $2"
    )
    .bind(tenant_id)
    .bind(agent_name)
    .fetch_optional(pool)
    .await
    .map_err(|e| AppError::Database(e.to_string()))?
    .ok_or_else(|| AppError::NotFound(format!("Agent '{}' not found for tenant '{}'", agent_name, tenant_id)))?;

    Ok(TenantAgent {
        id: row.get("id"),
        tenant_id: row.get("tenant_id"),
        agent_name: row.get("agent_name"),
        display_name: row.get("display_name"),
        description: row.get("description"),
        config: row.get::<serde_json::Value, _>("config"),
        enabled: row.get("enabled"),
        created_at: row.get("created_at"),
        updated_at: row.get("updated_at"),
    })
}

pub async fn create_tenant_agent(pool: &PgPool, tenant_id: &str, req: CreateTenantAgentRequest) -> Result<TenantAgent> {
    let id = uuid::Uuid::new_v4().to_string();
    let now = now_ts();

    sqlx::query(
        "INSERT INTO tenant_agents (id, tenant_id, agent_name, display_name, description, config, enabled, created_at, updated_at)
         VALUES ($1, $2, $3, $4, $5, $6, true, $7, $7)"
    )
    .bind(&id)
    .bind(tenant_id)
    .bind(&req.agent_name)
    .bind(&req.display_name)
    .bind(&req.description)
    .bind(&req.config)
    .bind(now)
    .execute(pool)
    .await
    .map_err(|e| AppError::Database(e.to_string()))?;

    get_tenant_agent(pool, tenant_id, &req.agent_name).await
}

pub async fn update_tenant_agent(pool: &PgPool, tenant_id: &str, agent_name: &str, req: UpdateTenantAgentRequest) -> Result<TenantAgent> {
    let now = now_ts();

    // Fetch current state
    let current = get_tenant_agent(pool, tenant_id, agent_name).await?;

    let display_name = req.display_name.unwrap_or(current.display_name);
    let description = req.description.or(current.description);
    let config = req.config.unwrap_or(current.config);
    let enabled = req.enabled.unwrap_or(current.enabled);

    sqlx::query(
        "UPDATE tenant_agents SET display_name = $1, description = $2, config = $3, enabled = $4, updated_at = $5
         WHERE tenant_id = $6 AND agent_name = $7"
    )
    .bind(&display_name)
    .bind(&description)
    .bind(&config)
    .bind(enabled)
    .bind(now)
    .bind(tenant_id)
    .bind(agent_name)
    .execute(pool)
    .await
    .map_err(|e| AppError::Database(e.to_string()))?;

    get_tenant_agent(pool, tenant_id, agent_name).await
}

pub async fn delete_tenant_agent(pool: &PgPool, tenant_id: &str, agent_name: &str) -> Result<()> {
    let result = sqlx::query(
        "DELETE FROM tenant_agents WHERE tenant_id = $1 AND agent_name = $2"
    )
    .bind(tenant_id)
    .bind(agent_name)
    .execute(pool)
    .await
    .map_err(|e| AppError::Database(e.to_string()))?;

    if result.rows_affected() == 0 {
        return Err(AppError::NotFound(format!("Agent '{}' not found for tenant '{}'", agent_name, tenant_id)));
    }
    Ok(())
}

// =============================================================================
// Template operations
// =============================================================================

pub async fn list_agent_templates(pool: &PgPool, product_type: Option<&str>) -> Result<Vec<AgentTemplate>> {
    let rows = if let Some(pt) = product_type {
        sqlx::query(
            "SELECT id, product_type, agent_name, display_name, description, config, created_at
             FROM agent_templates WHERE product_type = $1 ORDER BY agent_name"
        )
        .bind(pt)
        .fetch_all(pool)
        .await
        .map_err(|e| AppError::Database(e.to_string()))?
    } else {
        sqlx::query(
            "SELECT id, product_type, agent_name, display_name, description, config, created_at
             FROM agent_templates ORDER BY product_type, agent_name"
        )
        .fetch_all(pool)
        .await
        .map_err(|e| AppError::Database(e.to_string()))?
    };

    rows.iter().map(|row| {
        Ok(AgentTemplate {
            id: row.get("id"),
            product_type: row.get("product_type"),
            agent_name: row.get("agent_name"),
            display_name: row.get("display_name"),
            description: row.get("description"),
            config: row.get::<serde_json::Value, _>("config"),
            created_at: row.get("created_at"),
        })
    }).collect()
}

/// Clones all agent templates for a product type into a tenant's agent list.
/// Idempotent — skips agents that already exist (ON CONFLICT DO NOTHING).
pub async fn clone_templates_for_tenant(
    pool: &PgPool,
    tenant_id: &str,
    product_type: &str,
) -> Result<Vec<TenantAgent>> {
    let templates = list_agent_templates(pool, Some(product_type)).await?;
    let now = now_ts();

    for tpl in &templates {
        let id = uuid::Uuid::new_v4().to_string();
        sqlx::query(
            "INSERT INTO tenant_agents (id, tenant_id, agent_name, display_name, description, config, enabled, created_at, updated_at)
             VALUES ($1, $2, $3, $4, $5, $6, true, $7, $7)
             ON CONFLICT (tenant_id, agent_name) DO NOTHING"
        )
        .bind(&id)
        .bind(tenant_id)
        .bind(&tpl.agent_name)
        .bind(&tpl.display_name)
        .bind(&tpl.description)
        .bind(&tpl.config)
        .bind(now)
        .execute(pool)
        .await
        .map_err(|e| AppError::Database(e.to_string()))?;
    }

    list_tenant_agents(pool, tenant_id).await
}

// =============================================================================
// Seed default templates
// =============================================================================

/// Seeds default agent templates. Idempotent — uses ON CONFLICT DO NOTHING.
/// Called once on ARES startup after migrations.
pub async fn seed_default_templates(pool: &PgPool) -> Result<()> {
    let now = now_ts();

    struct TemplateSpec {
        product_type: &'static str,
        agent_name: &'static str,
        display_name: &'static str,
        description: &'static str,
        model: &'static str,
        system_prompt: &'static str,
    }

    let templates: &[TemplateSpec] = &[
        // Generic
        TemplateSpec {
            product_type: "generic",
            agent_name: "assistant",
            display_name: "General Assistant",
            description: "Default conversational agent",
            model: "fast",
            system_prompt: "You are a helpful AI assistant. Answer questions clearly and concisely. If you don't know something, say so. Be direct and useful.",
        },
        // Kasino
        TemplateSpec {
            product_type: "kasino",
            agent_name: "classifier",
            display_name: "Domain Classifier",
            description: "Classifies domains as gambling or safe",
            model: "groq-fast",
            system_prompt: r#"You are a gambling website classifier specializing in Indian gambling patterns.

Given a domain name, SNI/page title, time of access, and recent user activity,
determine if this is likely a gambling-related website.

INDIAN GAMBLING PATTERNS TO WATCH FOR:
- Satta/Matka: satta king, matka result, panel chart, gali, desawar, kalyan matka
- Cricket betting: IPL odds, match prediction, session betting, live rate, bhav, fancy bet
- Card games: teen patti cash, andar bahar real money, rummy cash game, poker real money
- Casinos: live dealer, slot machines, jackpot, roulette, spin
- Generic: bet, wager, odds, stake, bookmaker, bookie, punt

SCORING:
- 90-100: Confirmed gambling (known patterns, obvious indicators)
- 70-89: Highly likely gambling (strong signals, new/unknown domain)
- 40-69: Suspicious (some indicators, needs monitoring)
- 0-39: Likely safe

Respond ONLY with JSON:
{
  "gambling_score": <0-100>,
  "confidence": <0.0-1.0>,
  "category": "<satta|cricket_betting|casino|card_game|general_betting|safe>",
  "action": "<block|flag|pass>",
  "reasoning": "<brief explanation>"
}"#,
        },
        TemplateSpec {
            product_type: "kasino",
            agent_name: "risk",
            display_name: "Risk Assessor",
            description: "Daily behavioral risk assessment",
            model: "groq-balanced",
            system_prompt: r#"You are a behavioral risk analyst for gambling addiction monitoring.

Given 24 hours of device telemetry data, produce a risk assessment.

CONSIDER:
- Number and severity of blocked gambling attempts
- Time-of-day patterns (late night activity = higher risk)
- Financial transaction patterns (unusual amounts, frequency)
- App usage anomalies (excessive browser time, new apps)
- Attempted workarounds (VPN installs, settings access)
- Communication patterns (messages about borrowing money)

SCORING:
- 0-20: Low risk (normal activity, no gambling indicators)
- 21-40: Mild concern (minor anomalies, worth noting)
- 41-60: Moderate risk (some gambling-related activity detected)
- 61-80: High risk (active gambling attempts, financial anomalies)
- 81-100: Critical (confirmed gambling activity, intervention needed)

Respond with JSON:
{
  "risk_score": <0-100>,
  "factors": ["<factor1>", "<factor2>"],
  "trend": "<improving|stable|worsening>",
  "summary": "<2-3 sentence assessment>",
  "alerts": [{"severity": "<critical|warning|info>", "message": "<...>"}],
  "positive_signals": ["<anything good to acknowledge>"]
}"#,
        },
        TemplateSpec {
            product_type: "kasino",
            agent_name: "report",
            display_name: "Report Generator",
            description: "Weekly compassionate family report",
            model: "groq-powerful",
            system_prompt: r#"You are a compassionate counselor-assistant helping a family manage gambling addiction recovery. Generate a weekly report.

AUDIENCE: Family members (mother with basic tech literacy, adult son).
TONE: Caring but honest. Acknowledge progress. Don't minimize concerns.

REPORT STRUCTURE:
1. Overall Assessment (1-2 sentences, clear status)
2. This Week's Highlights
   - Positive behaviors (acknowledge these first)
   - Concerning events (be specific but compassionate)
3. Risk Trend (improving/stable/worsening with context)
4. Key Numbers
   - Gambling attempts blocked
   - Financial transactions flagged
   - Average daily risk score
5. Recommendations
   - What the family should discuss
   - Any therapy-related suggestions
   - Adjustments to monitoring if needed
6. Encouragement (end on a supportive note)

Write in simple English. Avoid technical jargon.
Include specific numbers and dates where relevant.
If the week was good, celebrate it. If it was concerning, be direct.

Format the report in a clean, readable structure suitable for WhatsApp/Telegram delivery."#,
        },
        TemplateSpec {
            product_type: "kasino",
            agent_name: "transaction",
            display_name: "Transaction Analyzer",
            description: "Analyzes financial transactions for gambling",
            model: "groq-fast",
            system_prompt: r#"Analyze a financial transaction notification for gambling patterns.

INPUT FORMAT: Indian bank SMS or UPI notification text.

LOOK FOR:
- Deposits to unknown/suspicious merchants
- Round amounts to non-standard recipients
- Rapid sequence of small transactions (multiple in short time)
- Late night / early morning financial activity (11 PM - 6 AM)
- Known gambling payment gateways or wallet names
- Merchant names containing gambling keywords
- P2P transfers to unknown numbers (possible bookie payments)

KNOWN GAMBLING GATEWAYS:
- Paytm merchant IDs for betting sites
- UPI handles containing "bet", "game", "play"
- International payment processors used by offshore casinos

Respond with JSON:
{
  "is_suspicious": <true|false>,
  "reason": "<explanation>",
  "amount": <number>,
  "merchant_category": "<standard|unknown|suspicious|confirmed_gambling>",
  "risk_level": "<low|medium|high|critical>"
}"#,
        },
        // EHB
        TemplateSpec {
            product_type: "ehb",
            agent_name: "intake",
            display_name: "Intake Agent",
            description: "Patient intake and initial assessment",
            model: "groq-balanced",
            system_prompt: r#"You are a clinical intake assistant for eHealthBuddy. Conduct an initial patient assessment.

PROCESS:
1. Collect basic demographics (name, age, presenting complaint)
2. Medical history (conditions, medications, allergies)
3. Current symptoms (severity, duration, triggers)
4. Mental health screening (PHQ-2, GAD-2 if appropriate)
5. Social determinants (support system, barriers to care)

OUTPUT: Structured JSON with all collected fields and a triage recommendation (routine/urgent/emergency).

Be empathetic. Use simple language. One question at a time.
Never diagnose -- you collect and organize, the clinician decides."#,
        },
        TemplateSpec {
            product_type: "ehb",
            agent_name: "followup",
            display_name: "Follow-up Agent",
            description: "Follow-up session management",
            model: "groq-balanced",
            system_prompt: r#"You are a follow-up care assistant for eHealthBuddy. Manage ongoing patient sessions.

PROCESS:
1. Review previous session summary from context
2. Check on treatment adherence (medications, lifestyle changes)
3. Assess symptom progression (better/same/worse)
4. Note any new concerns
5. Update care plan recommendations

OUTPUT: Session notes in structured JSON with changes since last visit and updated recommendations.

Be warm and supportive. Celebrate progress. Flag concerns without alarming."#,
        },
        TemplateSpec {
            product_type: "ehb",
            agent_name: "summary",
            display_name: "Summary Agent",
            description: "Generate patient session summaries",
            model: "groq-powerful",
            system_prompt: r#"You are a clinical documentation assistant for eHealthBuddy. Generate professional session summaries.

INPUT: Raw session transcript or notes.

OUTPUT: Structured clinical summary with:
1. Chief Complaint
2. History of Present Illness (HPI)
3. Assessment
4. Plan
5. Follow-up timeline

Write in clinical documentation style. Be precise. Include relevant quotes from patient.
Flag any red flags (suicidal ideation, abuse indicators, medication non-compliance)."#,
        },
    ];

    for tpl in templates {
        let id = uuid::Uuid::new_v4().to_string();
        let config = serde_json::json!({
            "model": tpl.model,
            "system_prompt": tpl.system_prompt,
            "tools": [],
            "max_tool_iterations": 3
        });

        sqlx::query(
            "INSERT INTO agent_templates (id, product_type, agent_name, display_name, description, config, created_at)
             VALUES ($1, $2, $3, $4, $5, $6, $7)
             ON CONFLICT (product_type, agent_name) DO NOTHING"
        )
        .bind(&id)
        .bind(tpl.product_type)
        .bind(tpl.agent_name)
        .bind(tpl.display_name)
        .bind(tpl.description)
        .bind(&config)
        .bind(now)
        .execute(pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to seed template {}/{}: {}", tpl.product_type, tpl.agent_name, e)))?;
    }

    tracing::info!("Agent templates seeded ({} templates)", templates.len());
    Ok(())
}