babelforce-manager-sdk 0.44.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
use serde_json::Value;

use crate::error::{map_manager_err, ManagerError};
use crate::gen::manager::apis::configuration::Configuration;
use crate::gen::manager::apis::{application_api as api, local_automation_api, manager_api};
use crate::gen::manager::models;
use crate::http::{collect_all, fetch_page, Page};
use crate::resources::raw::{get_json, post_json, post_json_body, put_json};
use crate::retry::{with_retry, RetryPolicy};
use crate::token::SharedCfg;

/// One application as returned by the API — typed when this SDK version knows its `module`,
/// preserved raw when it doesn't.
///
/// The applications list mixes module types, and the platform can ship modules newer than this
/// SDK. Instead of failing a whole list (or get) on the first unfamiliar `module`, such items are
/// returned as [`ApplicationItem::Unknown`] with their JSON intact.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ApplicationItem {
    /// A module type this SDK version knows.
    Typed(models::Application),
    /// A module type unknown to this SDK version — raw JSON preserved.
    Unknown {
        /// The `module` discriminator the server sent (empty if it sent none).
        module: String,
        /// The full application object, verbatim.
        raw: serde_json::Value,
    },
}

impl ApplicationItem {
    /// The typed application, when this SDK version knows its module.
    pub fn as_typed(&self) -> Option<&models::Application> {
        match self {
            ApplicationItem::Typed(app) => Some(app),
            ApplicationItem::Unknown { .. } => None,
        }
    }

    /// The `module` string, for both variants.
    pub fn module(&self) -> &str {
        use models::Application as App;
        match self {
            ApplicationItem::Typed(app) => match app {
                App::AgentQueue(_) => "agentQueue",
                App::Agentic(_) => "agentic",
                App::AudioPlayer(_) => "audioPlayer",
                App::ConsumerQueue(_) => "consumerQueue",
                App::InputReader(_) => "inputReader",
                App::InputReaderV2(_) => "inputReader.v2",
                App::PromptPlayer(_) => "promptPlayer",
                App::Recording(_) => "recording",
                App::SimpleMenu(_) => "simpleMenu",
                App::SpeechToText(_) => "speechToText",
                App::SwitchNode(_) => "switchNode",
                App::TextToSpeech(_) => "textToSpeech",
                App::Transfer(_) => "transfer",
            },
            ApplicationItem::Unknown { module, .. } => module,
        }
    }
}

/// Decode one application object **variant-directly**.
///
/// The generated [`models::Application`] is an internally-tagged enum (`#[serde(tag = "module")]`),
/// so serde strips the tag before deserializing the variant content — but every generated variant
/// struct *requires* its own `module` field, making the derived `Deserialize` fail on **every**
/// real payload (an openapi-generator discriminator artifact). The facade reads the tag itself and
/// deserializes the full (tag-carrying) object straight into the variant struct — no generated
/// code touched. Modules this SDK version doesn't know come back as [`ApplicationItem::Unknown`]
/// rather than an error; only items that aren't JSON objects at all still fail.
fn decode_application(v: Value) -> Result<ApplicationItem, ManagerError> {
    use models::Application as App;
    fn var<T: serde::de::DeserializeOwned>(v: Value) -> Result<Box<T>, ManagerError> {
        serde_json::from_value(v)
            .map(Box::new)
            .map_err(|e| ManagerError::Decode(e.to_string()))
    }
    if !v.is_object() {
        return Err(ManagerError::Decode(
            "application item is not a JSON object".into(),
        ));
    }
    let module = v
        .get("module")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    Ok(ApplicationItem::Typed(match module.as_str() {
        "agentQueue" => App::AgentQueue(var(v)?),
        "agentic" => App::Agentic(var(v)?),
        "audioPlayer" => App::AudioPlayer(var(v)?),
        "consumerQueue" => App::ConsumerQueue(var(v)?),
        "inputReader" => App::InputReader(var(v)?),
        "inputReader.v2" => App::InputReaderV2(var(v)?),
        "promptPlayer" => App::PromptPlayer(var(v)?),
        "recording" => App::Recording(var(v)?),
        "simpleMenu" => App::SimpleMenu(var(v)?),
        "speechToText" => App::SpeechToText(var(v)?),
        "switchNode" => App::SwitchNode(var(v)?),
        "textToSpeech" => App::TextToSpeech(var(v)?),
        "transfer" => App::Transfer(var(v)?),
        _ => return Ok(ApplicationItem::Unknown { module, raw: v }),
    }))
}

/// Decode a `{ item, … }` envelope (get/create/update/clone responses) into an
/// [`ApplicationItem`].
fn decode_item_envelope(v: Value) -> Result<ApplicationItem, ManagerError> {
    let item = v
        .get("item")
        .cloned()
        .ok_or_else(|| ManagerError::Decode("response had no `item`".into()))?;
    decode_application(item)
}

/// One raw page of `/api/v2/applications`, decoded item-by-item.
///
/// Stands in for the generated `list_applications`: that returns the internally-tagged
/// [`models::Application`] enum, which fails to deserialize on every real payload (see
/// [`decode_application`]), so the facade reads raw and decodes each item itself.
async fn applications_page(
    cfg: &Configuration,
    page: i32,
    per_page: Option<i32>,
) -> Result<(Vec<ApplicationItem>, i32, i32, Option<i32>), ManagerError> {
    let mut path = format!("/api/v2/applications?page={page}");
    if let Some(max) = per_page {
        path.push_str(&format!("&max={max}"));
    }
    let v = get_json(cfg, &path).await?;
    let items = v
        .get("items")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default()
        .into_iter()
        .map(decode_application)
        .collect::<Result<Vec<_>, _>>()?;
    let p = v.get("pagination").cloned().unwrap_or(Value::Null);
    let num = |k: &str| p.get(k).and_then(Value::as_i64).map(|n| n as i32);
    Ok((
        items,
        num("pages").unwrap_or(1),
        num("current").unwrap_or(page),
        num("total"),
    ))
}

/// Applications — `/api/v2/applications`, with a nested `local_automations` sub-resource.
pub struct ApplicationsResource {
    pub(crate) cfg: SharedCfg<Configuration>,
    pub(crate) retry: RetryPolicy,
    /// Per-application local automations — `/api/v2/applications/{applicationId}/actions`.
    pub local_automations: LocalAutomationsResource,
}

impl ApplicationsResource {
    /// List all applications (auto-paginated).
    pub async fn list_all(&self) -> Result<Vec<ApplicationItem>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(
            &self.retry,
            |e| e,
            |page| async move {
                applications_page(cfg, page, None)
                    .await
                    .map(|(items, pages, current, _)| (items, pages, current))
            },
        )
        .await
    }

    /// List one page of applications.
    pub async fn list_page(
        &self,
        page: i32,
        per_page: Option<i32>,
    ) -> Result<Page<ApplicationItem>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        fetch_page(
            &self.retry,
            |e| e,
            || async move { applications_page(cfg, page, per_page).await },
        )
        .await
    }

    /// List all local automations across applications (auto-paginated).
    pub async fn all_local_automations(
        &self,
    ) -> Result<Vec<models::LocalAutomation>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r = local_automation_api::list_all_local_automations(cfg, Some(page), None).await?;
            Ok((r.items, r.pagination.pages, r.pagination.current))
        })
        .await
    }

    /// Create an application.
    ///
    /// Routes the write through the raw JSON path and [`decode_application`], standing in for the
    /// generated `create_application` — whose typed [`models::ApplicationItemResponse`] return
    /// fails to deserialize on every real success payload, misreporting a *completed* create as
    /// an error.
    pub async fn create(
        &self,
        body: models::ApplicationCreateBody,
    ) -> Result<ApplicationItem, ManagerError> {
        let body = serde_json::to_value(&body)
            .map_err(|e| ManagerError::InvalidArgument(e.to_string()))?;
        decode_item_envelope(self.create_raw(body).await?)
    }

    /// Create an application, reading the response **raw** — for callers that want the
    /// server's JSON verbatim instead of the decoded [`ApplicationItem`].
    pub async fn create_raw(&self, body: Value) -> Result<Value, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        // Non-idempotent create → no retry on ambiguous failures.
        with_retry(&self.retry, false, || {
            post_json_body(cfg, "/api/v2/applications", &body)
        })
        .await
    }

    /// Get an application by id.
    ///
    /// Reads the response **raw** and decodes via [`decode_application`], standing in for the
    /// generated `get_application` — whose typed [`models::Application`] return fails to
    /// deserialize on every real payload.
    pub async fn get(&self, id: &str) -> Result<ApplicationItem, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let path = format!(
            "/api/v2/applications/{}",
            crate::gen::manager::apis::urlencode(id)
        );
        with_retry(&self.retry, true, || async {
            decode_item_envelope(get_json(cfg, &path).await?)
        })
        .await
    }

    /// Update an application.
    ///
    /// Routes the write through the raw JSON path and [`decode_application`], standing in for the
    /// generated `update_application` — same typed-response decode failure as [`Self::create`].
    pub async fn update(
        &self,
        id: &str,
        body: models::ApplicationUpdateBody,
    ) -> Result<ApplicationItem, ManagerError> {
        let body = serde_json::to_value(&body)
            .map_err(|e| ManagerError::InvalidArgument(e.to_string()))?;
        decode_item_envelope(self.update_raw(id, body).await?)
    }

    /// Update an application, reading the response **raw** (the PUT sibling of
    /// [`Self::create_raw`]).
    pub async fn update_raw(&self, id: &str, body: Value) -> Result<Value, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let path = format!(
            "/api/v2/applications/{}",
            crate::gen::manager::apis::urlencode(id)
        );
        // Non-idempotent write → no retry on ambiguous failures.
        with_retry(&self.retry, false, || put_json(cfg, &path, &body)).await
    }

    /// Delete an application.
    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, || api::delete_application(cfg, id))
            .await
            .map_err(map_manager_err)?;
        Ok(())
    }

    /// Delete several applications by id.
    pub async fn delete_many(
        &self,
        ids: Vec<String>,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let body = models::DeleteManyApplicationsRequest { ids };
        with_retry(&self.retry, false, || {
            api::delete_many_applications(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// List the available application modules.
    pub async fn list_modules(&self) -> Result<models::ListModulesResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || api::list_modules(cfg))
            .await
            .map_err(map_manager_err)
    }

    /// Dispatch an application's local automations at a given position. `is_async` runs without
    /// waiting for the result.
    pub async fn dispatch(
        &self,
        id: &str,
        position: &str,
        is_async: bool,
        body: models::LocalAutomationDispatch,
    ) -> Result<models::DispatchLocalAutomationsResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            manager_api::dispatch_local_automations(cfg, id, position, is_async, Some(body.clone()))
        })
        .await
        .map_err(map_manager_err)
    }

    /// Clone an application by id.
    ///
    /// Routes the write through the raw JSON path and [`decode_application`], standing in for the
    /// generated `clone_application` — same typed-response decode failure as [`Self::create`].
    pub async fn clone(&self, id: &str) -> Result<ApplicationItem, ManagerError> {
        decode_item_envelope(self.clone_raw(id).await?)
    }

    /// Clone an application by id, reading the response **raw** — for callers that want the
    /// server's JSON verbatim instead of the decoded [`ApplicationItem`].
    pub async fn clone_raw(&self, id: &str) -> Result<Value, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        let path = format!(
            "/api/v2/applications/{}/clone",
            crate::gen::manager::apis::urlencode(id)
        );
        // Non-idempotent action → no retry on ambiguous failures.
        with_retry(&self.retry, false, || post_json(cfg, &path)).await
    }

    /// Bulk-update several applications in one request.
    pub async fn bulk_update(
        &self,
        body: models::BulkUpdateApplicationsRequest,
    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            api::bulk_update_applications(cfg, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// List the actions available across applications.
    pub async fn list_app_actions(&self) -> Result<models::ObjectListResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            api::list_application_actions(cfg, None, None)
        })
        .await
        .map_err(map_manager_err)
    }

    /// List application errors.
    pub async fn list_errors(&self) -> Result<models::ObjectListResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || api::list_application_errors(cfg))
            .await
            .map_err(map_manager_err)
    }
}

/// Per-application local automations — `/api/v2/applications/{applicationId}/actions`.
pub struct LocalAutomationsResource {
    pub(crate) cfg: SharedCfg<Configuration>,
    pub(crate) retry: RetryPolicy,
}

impl LocalAutomationsResource {
    /// List all of an application's local automations (auto-paginated).
    pub async fn list_all(
        &self,
        application_id: &str,
    ) -> Result<Vec<models::LocalAutomation>, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        collect_all(&self.retry, map_manager_err, |page| async move {
            let r =
                local_automation_api::list_local_automations(cfg, application_id, Some(page), None)
                    .await?;
            Ok((r.items, r.pagination.pages, r.pagination.current))
        })
        .await
    }

    /// Create a local automation on an application.
    pub async fn create(
        &self,
        application_id: &str,
        body: models::RestCreateLocalAutomation,
    ) -> Result<models::LocalAutomationItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            local_automation_api::create_local_automation(cfg, application_id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Get a local automation by id.
    pub async fn get(
        &self,
        application_id: &str,
        id: &str,
    ) -> Result<models::LocalAutomationItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, true, || {
            local_automation_api::get_local_automation(cfg, application_id, id)
        })
        .await
        .map_err(map_manager_err)
    }

    /// Update a local automation.
    pub async fn update(
        &self,
        application_id: &str,
        id: &str,
        body: models::RestUpdateLocalAutomation,
    ) -> Result<models::LocalAutomationItemResponse, ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            local_automation_api::update_local_automation(cfg, application_id, id, body.clone())
        })
        .await
        .map_err(map_manager_err)
    }

    /// Delete a local automation.
    pub async fn delete(&self, application_id: &str, id: &str) -> Result<(), ManagerError> {
        let cfg = self.cfg.get().await?;
        let cfg = cfg.as_ref();
        with_retry(&self.retry, false, || {
            local_automation_api::delete_local_automation(cfg, application_id, id)
        })
        .await
        .map_err(map_manager_err)?;
        Ok(())
    }
}