babelforce-manager-sdk 0.46.0

Rust SDK for the babelforce manager APIs — auth, user & agent management, call reporting, metrics, and task automations.
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use crate::error::{map_manager_err, ManagerError};
use crate::gen::manager::apis::configuration::Configuration;
use crate::gen::manager::apis::{agent_api, agent_group_api, manager_api};
use crate::gen::manager::models;
use crate::http::{collect_all, fetch_page, Page};
use crate::resources::raw::get_json;
use crate::retry::{with_retry, RetryPolicy};
use crate::token::SharedCfg;

/// Optional server-side filters for the agents list surfaces ([`AgentsResource::list`] /
/// [`AgentsResource::list_page`]). All fields combine; the default filters nothing.
#[derive(Debug, Clone, Default)]
pub struct ListAgentsQuery {
    /// Free-text search across name, group name, number, email, sourceId and integration label.
    pub q: Option<String>,
    /// Only enabled (`true`) or only disabled (`false`) agents.
    pub enabled: Option<bool>,
    /// Filter by agent name.
    pub name: Option<String>,
    /// Filter by the agent's number.
    pub number: Option<String>,
    /// Filter by integration source id.
    pub source_id: Option<String>,
    /// Filter by line status.
    pub state: Option<models::AgentLineStatus>,
    /// Filter by source integration.
    pub source: Option<String>,
    /// Restrict to agents in these group id(s). A hyphenated UUID is normalized to the API's
    /// unhyphenated form, so a listed group id round-trips as a filter.
    pub group_ids: Vec<String>,
    /// Restrict to agents in these group name(s).
    pub groups: Vec<String>,
    /// Filter by tag(s).
    pub tags: Vec<String>,
}

impl ListAgentsQuery {
    /// Serialize as `/api/v2/agents?...` with the spec's form/explode semantics — array filters
    /// travel as repeated `key=value` pairs.
    fn to_path(&self, page: i32, max: Option<i32>) -> String {
        let mut ser = url::form_urlencoded::Serializer::new(String::new());
        ser.append_pair("page", &page.to_string());
        if let Some(max) = max {
            ser.append_pair("max", &max.to_string());
        }
        if let Some(v) = &self.q {
            ser.append_pair("q", v);
        }
        if let Some(v) = self.enabled {
            ser.append_pair("enabled", if v { "true" } else { "false" });
        }
        if let Some(v) = &self.name {
            ser.append_pair("name", v);
        }
        if let Some(v) = &self.number {
            ser.append_pair("number", v);
        }
        if let Some(v) = &self.source_id {
            ser.append_pair("sourceId", v);
        }
        if let Some(v) = &self.state {
            ser.append_pair("state", &v.to_string());
        }
        if let Some(v) = &self.source {
            ser.append_pair("source", v);
        }
        for id in &self.group_ids {
            ser.append_pair("groupIds", &normalize_entity_id(id));
        }
        for g in &self.groups {
            ser.append_pair("groups", g);
        }
        for t in &self.tags {
            ser.append_pair("tags", t);
        }
        format!("/api/v2/agents?{}", ser.finish())
    }
}

/// babelforce entity ids are unhyphenated 32-char hex; normalize a hyphenated UUID the same way
/// the generated path helper does. Non-UUID values pass through unchanged.
fn normalize_entity_id(v: &str) -> String {
    match uuid::Uuid::parse_str(v) {
        Ok(u) => u.simple().to_string(),
        Err(_) => v.to_string(),
    }
}

/// Agent management — `/api/v2/agents`, with a nested `groups` sub-resource.
pub struct AgentsResource {
    pub(crate) cfg: SharedCfg<Configuration>,
    pub(crate) retry: RetryPolicy,
    /// Agent groups — `/api/v2/agents/groups`.
    pub groups: AgentGroupsResource,
}

impl AgentsResource {
    /// List agents matching `query`, auto-paginated across pages.
    ///
    /// Stands in for the generated `list_agents`, whose `groupIds`/`groups`/`tags` parameters
    /// (anyOf string-or-array types) are JSON-serialized into the query — a single id would be
    /// sent as `?groupIds="…"` with literal quotes, which the server does not match. The facade
    /// builds the form/explode query itself and decodes into the same generated response model.
    pub async fn list(&self, query: ListAgentsQuery) -> Result<Vec<models::Agent>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let query = &query;
        collect_all(
            &self.retry,
            |e| e,
            |page| async move {
                let v = get_json(cfg, &query.to_path(page, None)).await?;
                let r: models::PaginatedAgentResponse =
                    serde_json::from_value(v).map_err(|e| ManagerError::Decode(e.to_string()))?;
                Ok((
                    r.items,
                    r.pagination.pages.unwrap_or(1),
                    r.pagination.current.unwrap_or(1),
                ))
            },
        )
        .await
    }

    /// List all agents (unfiltered, auto-paginated) — [`AgentsResource::list`] with no filters.
    pub async fn list_all(&self) -> Result<Vec<models::Agent>, ManagerError> {
        self.list(ListAgentsQuery::default()).await
    }

    /// List one page of agents, optionally filtered server-side.
    pub async fn list_page(
        &self,
        page: i32,
        per_page: Option<i32>,
        query: ListAgentsQuery,
    ) -> Result<Page<models::Agent>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let query = &query;
        fetch_page(
            &self.retry,
            |e| e,
            || async move {
                let v = get_json(cfg, &query.to_path(page, per_page)).await?;
                let r: models::PaginatedAgentResponse =
                    serde_json::from_value(v).map_err(|e| ManagerError::Decode(e.to_string()))?;
                Ok((
                    r.items,
                    r.pagination.pages.unwrap_or(1),
                    r.pagination.current.unwrap_or(1),
                    r.pagination.total,
                ))
            },
        )
        .await
    }

    /// Create an agent.
    pub async fn create(
        &self,
        body: models::RestCreateAgent,
    ) -> Result<models::AgentItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::create_agent(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Get an agent by id.
    pub async fn get(&self, id: &str) -> Result<models::AgentItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || agent_api::get_agent(cfg, id))
            .await
            .map_err(map_manager_err)
    }

    /// Update an agent.
    pub async fn update(
        &self,
        id: &str,
        body: models::RestUpdateAgent,
    ) -> Result<models::AgentItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::update_agent(cfg, id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Delete an agent.
    pub async fn delete(&self, id: &str) -> Result<(), ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || agent_api::delete_agent(cfg, id))
            .await
            .map_err(map_manager_err)?;
        Ok(())
    }

    /// Update an agent's status.
    pub async fn update_status(
        &self,
        id: &str,
        status: models::UpdateAgentStatusRequest,
    ) -> Result<models::AgentStatus, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            manager_api::update_agent_status(cfg, id, Some(status.clone()))
        })
        .await
        .map_err(map_manager_err)
    }

    /// List agent presences.
    pub async fn presences(&self) -> Result<models::AgentPresenceListResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || agent_api::list_agent_presences(cfg))
            .await
            .map_err(map_manager_err)
    }

    /// Get an agent presence by name.
    pub async fn get_presence(
        &self,
        name: &str,
    ) -> Result<models::AgentPresenceItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            agent_api::get_agent_presence(cfg, name)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Create an agent presence.
    pub async fn create_presence(
        &self,
        body: models::AgentPresenceWriteBody,
    ) -> Result<models::AgentPresenceItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::create_agent_presence(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Update an agent presence.
    pub async fn update_presence(
        &self,
        name: &str,
        body: models::AgentPresenceWriteBody,
    ) -> Result<models::AgentPresenceItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::update_agent_presence(cfg, name, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Delete an agent presence.
    pub async fn delete_presence(
        &self,
        name: &str,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::delete_agent_presence(cfg, name)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Get an agent's total status by id.
    pub async fn get_status(
        &self,
        id: &str,
    ) -> Result<models::AgentTotalStatusResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || agent_api::get_agent_status(cfg, id))
            .await
            .map_err(map_manager_err)
    }

    /// List available agent statuses.
    pub async fn available_statuses(
        &self,
    ) -> Result<models::AgentAvailabilityListResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            agent_api::list_available_agent_statuses(cfg)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Enable an agent.
    pub async fn enable(&self, id: &str) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || agent_api::enable_agent(cfg, id))
            .await
            .map_err(map_manager_err)
    }

    /// Disable an agent.
    pub async fn disable(
        &self,
        id: &str,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || agent_api::disable_agent(cfg, id))
            .await
            .map_err(map_manager_err)
    }

    /// Hang up an agent's active call.
    pub async fn hangup_call(
        &self,
        id: &str,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || agent_api::hangup_agent_call(cfg, id))
            .await
            .map_err(map_manager_err)
    }

    /// Perform a bulk action (e.g. `enable`, `disable`, `delete`) on multiple agents.
    pub async fn bulk_action(
        &self,
        action: &str,
        body: models::AgentBulkRequest,
    ) -> Result<models::AgentBulkResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::bulk_agent_action(cfg, action, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Export all agents in the given format.
    pub async fn export(&self, format: &str) -> Result<String, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || agent_api::export_agents(cfg, format))
            .await
            .map_err(map_manager_err)
    }

    /// Import agents from a file in the given format.
    #[allow(clippy::too_many_arguments)]
    pub async fn import_agents(
        &self,
        format: &str,
        file: std::path::PathBuf,
        r#async: Option<bool>,
        create_only: Option<bool>,
        update_only: Option<bool>,
        delete_unlisted: Option<bool>,
    ) -> Result<models::AgentImportValidationResults, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::import_agents(
                cfg,
                format,
                file.clone(),
                r#async,
                create_only,
                update_only,
                delete_unlisted,
            )
        })
        .await
        .map_err(map_manager_err)
    }

    /// Validate an agent import file without applying it.
    pub async fn validate_import(
        &self,
        file: std::path::PathBuf,
    ) -> Result<models::AgentImportValidationResults, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::validate_agent_import(cfg, file.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Get an agent import job by id.
    pub async fn get_import_job(
        &self,
        id: &str,
    ) -> Result<models::AgentImportJobItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            agent_api::get_agent_import_job(cfg, id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// List an agent's logs (auto-paginated), optionally filtered by a `from`/`to` range.
    pub async fn logs(
        &self,
        id: &str,
        from: Option<i32>,
        to: Option<i32>,
    ) -> Result<Vec<models::AgentLogEntry>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = agent_api::list_agent_logs(cfg, id, Some(page), None, from, to).await?;
            let (pages, current) = r
                .pagination
                .as_ref()
                .map(|p| (p.pages.unwrap_or(1), p.current.unwrap_or(1)))
                .unwrap_or((1, 1));
            Ok((r.items, pages, current))
        })
        .await
    }

    /// List logs across all agents (auto-paginated).
    pub async fn all_logs(&self) -> Result<Vec<models::AgentLogEntry>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = agent_api::list_all_agent_logs(cfg, Some(page), None).await?;
            let (pages, current) = r
                .pagination
                .as_ref()
                .map(|p| (p.pages.unwrap_or(1), p.current.unwrap_or(1)))
                .unwrap_or((1, 1));
            Ok((r.items, pages, current))
        })
        .await
    }

    /// Push a message to an agent (or broadcast to all agents).
    pub async fn push(
        &self,
        body: models::AgentPushRequest,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::push_to_agent(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Update an agent's password.
    pub async fn update_password(
        &self,
        id: &str,
        body: models::AgentPasswordUpdateRequest,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_api::update_agent_password(cfg, id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }
}

/// Agent groups — `/api/v2/agents/groups`.
pub struct AgentGroupsResource {
    pub(crate) cfg: SharedCfg<Configuration>,
    pub(crate) retry: RetryPolicy,
}

impl AgentGroupsResource {
    /// List all agent groups (auto-paginated).
    pub async fn list_all(&self) -> Result<Vec<models::AgentGroup>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = agent_group_api::list_agent_groups(cfg, Some(page), None).await?;
            Ok((
                r.items,
                r.pagination.pages.unwrap_or(1),
                r.pagination.current.unwrap_or(1),
            ))
        })
        .await
    }

    /// Create an agent group.
    pub async fn create(
        &self,
        body: models::RestCreateAgentGroup,
    ) -> Result<models::AgentGroupItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_group_api::create_agent_group(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Get an agent group by id.
    pub async fn get(&self, id: &str) -> Result<models::AgentGroupItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            agent_group_api::get_agent_group(cfg, id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Update an agent group.
    pub async fn update(
        &self,
        id: &str,
        body: models::RestUpdateAgentGroup,
    ) -> Result<models::AgentGroupItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_group_api::update_agent_group(cfg, id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Delete an agent group.
    pub async fn delete(&self, id: &str) -> Result<(), ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_group_api::delete_agent_group(cfg, id)
        })
        .await
        .map_err(map_manager_err)?;
        Ok(())
    }

    /// Add an agent to a group.
    pub async fn add_agent(
        &self,
        group_id: &str,
        agent_id: &str,
    ) -> Result<models::AgentGroupAdditionResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let id = uuid::Uuid::parse_str(agent_id)
            .map_err(|e| ManagerError::InvalidArgument(format!("agent_id: {e}")))?;
        let body = models::AddAgentToGroupRequest { id };
        with_retry(&self.retry, false, || {
            manager_api::add_agent_to_group(cfg, group_id, Some(body.clone()))
        })
        .await
        .map_err(map_manager_err)
    }

    /// Remove an agent from a group.
    pub async fn remove_agent(
        &self,
        group_id: &str,
        agent_id: &str,
    ) -> Result<models::AgentGroupItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            agent_group_api::remove_agent_from_group(cfg, group_id, agent_id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// List all agents in a group (auto-paginated).
    pub async fn list_agents(&self, group_id: &str) -> Result<Vec<models::Agent>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = agent_group_api::list_agents_in_group(cfg, group_id, Some(page), None).await?;
            Ok((
                r.items,
                r.pagination.pages.unwrap_or(1),
                r.pagination.current.unwrap_or(1),
            ))
        })
        .await
    }

    /// Bulk-delete agent groups by id.
    pub async fn bulk_delete(
        &self,
        ids: Vec<String>,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let ids = ids
            .iter()
            .map(|id| {
                uuid::Uuid::parse_str(id)
                    .map_err(|e| ManagerError::InvalidArgument(format!("ids: {e}")))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let body = models::BulkIdsRequest { ids };
        with_retry(&self.retry, false, || {
            agent_group_api::bulk_delete_agent_groups(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }
}