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
//! `Tools` resource — Tool grain lifecycle + invocation.
//!
//! Mirrors the Python SDK's `client.tools.*` surface: `bind`, `list`,
//! `unbind`, `invoke`, `parse`, `wait_for_resolution`.
//!
//! Two execution flows share this resource:
//!
//! - **Sync**: `invoke()` returns `{"status": "completed", "result": …}`
//! directly.
//! - **Async**: `invoke()` returns `{"status": "pending",
//! "audit_grain_id": …}`; the caller then polls with
//! [`Tools::wait_for_resolution`] until the audit grain reaches
//! `completed` or `failed`.
use std::time::{Duration, Instant};
use serde_json::{json, Map, Value};
use crate::error::{AreevError, Result};
use crate::http::HttpClient;
use crate::resources::connectors::Connectors;
/// Tool grain lifecycle + invocation.
///
/// Access via [`crate::Areev::tools`].
pub struct Tools<'a> {
http: &'a HttpClient,
memory_id: String,
}
impl<'a> Tools<'a> {
/// Internal constructor — use [`crate::Areev::tools`].
pub(crate) fn new(http: &'a HttpClient, memory_id: String) -> Self {
Self { http, memory_id }
}
/// Start a [`BindBuilder`] for binding a tool to a harness.
///
/// Chain optional knobs (`output_schema`, `description`, …) and
/// call `send()`.
pub fn bind<'b>(
&'b self,
slug: &str,
executor: Value,
param_schema: Value,
) -> BindBuilder<'b, 'a> {
BindBuilder::new(self, slug, executor, param_schema)
}
/// Bind an Axtion connector action as a tool — schema fetched for you.
///
/// Looks up `action`'s parameter schema from the connector catalog (so
/// the caller never hand-writes JSON Schema), then binds it with an
/// Axtion executor (`{"type": "axtion", "connector": …, "action": …}`).
/// `action` is the action *key* (e.g. `"send-email"`), as returned by
/// [`Connectors::actions`]`(connector)[*].name`.
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> areev::Result<()> {
/// let areev = areev::Areev::from_env();
/// areev
/// .tools()
/// .bind_axtion("sales-bot", "gmail", "send-email")
/// .description("Send an email via Gmail")
/// .send()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// The returned builder's `send()` raises [`AreevError::NotFound`]
/// (`SDK-E010`) — listing the available actions — when `action` is not
/// in the connector's catalog.
pub fn bind_axtion<'b>(
&'b self,
slug: &str,
connector: &str,
action: &str,
) -> BindAxtionBuilder<'b, 'a> {
BindAxtionBuilder::new(self, slug, connector, action)
}
/// List all bound tools on a harness.
///
/// Returns the raw server response:
/// `{"harness_slug", "namespace", "hipaa_active", "tools": [...]}`
/// where each tool entry has `tool_hash`, `tool_id`,
/// `description`, `axtion_uri`, `baa_ok`, etc.
pub async fn list(&self, slug: &str) -> Result<Value> {
let path = format!("/memories/{}/harnesses/{}/tools", self.memory_id, slug);
self.http._get(&path, None).await
}
/// Remove a bound tool from a harness.
///
/// Pass either `tool_id` (human-readable — will be resolved to
/// `tool_hash` via [`Tools::list`]) or `tool_hash` directly.
/// Returns `Ok(())` on success; raises
/// [`AreevError::Validation`] if neither is provided, and
/// [`AreevError::NotFound`] if the tool isn't bound.
pub async fn unbind(
&self,
slug: &str,
tool_id: Option<&str>,
tool_hash: Option<&str>,
) -> Result<()> {
if tool_id.is_none() && tool_hash.is_none() {
return Err(AreevError::Validation {
code: Some("SDK-E001".to_string()),
http_status: 400,
message: "tools.unbind requires either tool_id or tool_hash".to_string(),
body: Value::Null,
request_id: None,
});
}
let hash = match tool_hash {
Some(h) => h.to_string(),
None => {
// Safe: tool_id is Some when tool_hash is None (validated above).
let target = tool_id.unwrap();
let listing = self.list(slug).await?;
let tools = listing
.get("tools")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let found = tools.iter().find(|t| {
t.get("tool_id")
.and_then(|v| v.as_str())
.map(|s| s == target)
.unwrap_or(false)
});
let Some(entry) = found else {
return Err(AreevError::NotFound {
code: Some("SDK-E011".to_string()),
http_status: 404,
message: format!(
"no bound tool with tool_id={target:?} on harness {slug:?}"
),
body: Value::Null,
request_id: None,
});
};
entry
.get("tool_hash")
.and_then(|v| v.as_str())
.ok_or_else(|| AreevError::Other {
http_status: 0,
code: None,
message: format!(
"tool listing for tool_id={target:?} is missing tool_hash"
),
body: Value::Null,
request_id: None,
})?
.to_string()
}
};
let path = format!(
"/memories/{}/harnesses/{}/tools/{}",
self.memory_id, slug, hash
);
self.http._delete(&path).await.map(|_| ())
}
/// Start an [`InvokeBuilder`] for the given tool.
pub fn invoke<'b>(&'b self, slug: &str, tool_id: &str, args: Value) -> InvokeBuilder<'b, 'a> {
InvokeBuilder::new(self, slug, tool_id, args)
}
/// Parse LLM output into tool calls.
///
/// `format` is **required by the server** and must be one of:
/// `openai-tools`, `openai-responses`, `anthropic-tools`,
/// `gemini-tools`, `mcp-tools`, `hermes`, `llama31`, `markdown-tools`,
/// `sml-tools`. Any other value (including `auto`) is rejected with
/// HTTP 400 `MEM-E107`. An empty string defaults to `openai-tools`.
pub async fn parse(&self, text: &str, format: &str) -> Result<Value> {
let fmt = if format.is_empty() {
"openai-tools"
} else {
format
};
let body = json!({ "raw_output": text, "format": fmt });
self.http._post("/v1/tools/parse", Some(&body)).await
}
/// Poll an async Pending audit grain until it resolves to
/// `completed` / `failed`.
///
/// Returns the resolved grain. Raises [`AreevError::Other`] with
/// `http_status = 408` if the deadline is hit (so it surfaces
/// through the same `AreevError` match arms as other timeouts).
pub async fn wait_for_resolution(
&self,
audit_grain_id: &str,
timeout_s: f64,
poll_interval_s: f64,
) -> Result<Value> {
let deadline = Instant::now() + Duration::from_secs_f64(timeout_s);
let poll = Duration::from_secs_f64(poll_interval_s.max(0.05));
loop {
let path = format!("/memories/{}/grains/{}", self.memory_id, audit_grain_id);
let grain = self.http._get(&path, None).await?;
let status = grain.get("status").and_then(|v| v.as_str()).or_else(|| {
grain
.get("fields")
.and_then(|f| f.get("status"))
.and_then(|v| v.as_str())
});
if matches!(status, Some("completed") | Some("failed")) {
return Ok(grain);
}
if Instant::now() >= deadline {
return Err(AreevError::Other {
http_status: 408,
code: Some("SDK-E408".to_string()),
message: format!(
"pending grain {audit_grain_id} not resolved within {timeout_s}s"
),
body: Value::Null,
request_id: None,
});
}
tokio::time::sleep(poll).await;
}
}
}
/// Builder for [`Tools::bind`].
pub struct BindBuilder<'b, 'a> {
tools: &'b Tools<'a>,
slug: String,
body: Map<String, Value>,
}
impl<'b, 'a> BindBuilder<'b, 'a> {
fn new(tools: &'b Tools<'a>, slug: &str, executor: Value, param_schema: Value) -> Self {
let mut body = Map::new();
body.insert("executor".to_string(), executor);
body.insert("description".to_string(), Value::String(String::new()));
body.insert("param_schema".to_string(), param_schema);
body.insert("output_schema".to_string(), json!({ "type": "object" }));
body.insert("locked_params".to_string(), Value::Object(Map::new()));
body.insert("async_mode".to_string(), Value::Bool(false));
body.insert("examples".to_string(), Value::Array(Vec::new()));
Self {
tools,
slug: slug.to_string(),
body,
}
}
/// Override the tool's `output_schema` (default `{ "type": "object" }`).
pub fn output_schema(mut self, schema: Value) -> Self {
self.body.insert("output_schema".to_string(), schema);
self
}
/// Set a human-readable description (default empty).
pub fn description(mut self, description: &str) -> Self {
self.body.insert(
"description".to_string(),
Value::String(description.to_string()),
);
self
}
/// Pin server-side parameter values (cannot be overridden by the LLM).
pub fn locked_params(mut self, locked: Value) -> Self {
self.body.insert("locked_params".to_string(), locked);
self
}
/// Mark the tool as long-running — invocations return `pending`
/// and resolve asynchronously.
pub fn async_mode(mut self, async_mode: bool) -> Self {
self.body
.insert("async_mode".to_string(), Value::Bool(async_mode));
self
}
/// Provide few-shot examples surfaced to the LLM.
pub fn examples(mut self, examples: Vec<Value>) -> Self {
self.body
.insert("examples".to_string(), Value::Array(examples));
self
}
/// Server-supplied spec hash for the tool definition.
pub fn spec_hash(mut self, spec_hash: &str) -> Self {
self.body.insert(
"spec_hash".to_string(),
Value::String(spec_hash.to_string()),
);
self
}
/// Issue the bind request.
pub async fn send(self) -> Result<Value> {
let path = format!(
"/memories/{}/harnesses/{}/tools",
self.tools.memory_id, self.slug
);
self.tools
.http
._post(&path, Some(&Value::Object(self.body)))
.await
}
}
/// Builder for [`Tools::bind_axtion`].
///
/// Defers the connector-catalog schema lookup to [`Self::send`] (the
/// `actions()` call is async). Chain `description` / `locked_params` /
/// `async_mode` like [`BindBuilder`], then `send()`.
pub struct BindAxtionBuilder<'b, 'a> {
tools: &'b Tools<'a>,
slug: String,
connector: String,
action: String,
description: Option<String>,
locked_params: Option<Value>,
async_mode: bool,
}
impl<'b, 'a> BindAxtionBuilder<'b, 'a> {
fn new(tools: &'b Tools<'a>, slug: &str, connector: &str, action: &str) -> Self {
Self {
tools,
slug: slug.to_string(),
connector: connector.to_string(),
action: action.to_string(),
description: None,
locked_params: None,
async_mode: false,
}
}
/// Override the tool description (defaults to the action's catalog
/// description when unset).
pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_string());
self
}
/// Pin server-side parameter values (cannot be overridden by the LLM).
pub fn locked_params(mut self, locked: Value) -> Self {
self.locked_params = Some(locked);
self
}
/// Mark the tool as long-running — invocations return `pending` and
/// resolve asynchronously.
pub fn async_mode(mut self, async_mode: bool) -> Self {
self.async_mode = async_mode;
self
}
/// Look up the action's schema, then issue the bind request.
pub async fn send(self) -> Result<Value> {
let connectors = Connectors::new(self.tools.http);
let descriptors = connectors.actions(&self.connector).await?;
let Some(matched) = descriptors.iter().find(|d| d.name == self.action) else {
let available = if descriptors.is_empty() {
"(none)".to_string()
} else {
descriptors
.iter()
.map(|d| d.name.as_str())
.collect::<Vec<_>>()
.join(", ")
};
return Err(AreevError::NotFound {
code: Some("SDK-E010".to_string()),
http_status: 404,
message: format!(
"connector {:?} has no action {:?}; available: {available}",
self.connector, self.action
),
body: Value::Null,
request_id: None,
});
};
let param_schema = if matched.param_schema.is_null() {
json!({ "type": "object" })
} else {
matched.param_schema.clone()
};
let executor = json!({
"type": "axtion",
"connector": self.connector,
"action": self.action,
});
let description = self
.description
.unwrap_or_else(|| matched.description.clone());
let mut builder = self
.tools
.bind(&self.slug, executor, param_schema)
.description(&description)
.async_mode(self.async_mode);
if let Some(locked) = self.locked_params {
builder = builder.locked_params(locked);
}
builder.send().await
}
}
/// Builder for [`Tools::invoke`].
pub struct InvokeBuilder<'b, 'a> {
tools: &'b Tools<'a>,
slug: String,
body: Map<String, Value>,
}
impl<'b, 'a> InvokeBuilder<'b, 'a> {
fn new(tools: &'b Tools<'a>, slug: &str, tool_id: &str, args: Value) -> Self {
let mut body = Map::new();
body.insert("tool_name".to_string(), Value::String(tool_id.to_string()));
body.insert("arguments".to_string(), args);
Self {
tools,
slug: slug.to_string(),
body,
}
}
/// Tie this invocation to an existing Flow-B session.
pub fn session_id(mut self, session_id: &str) -> Self {
self.body.insert(
"session_id".to_string(),
Value::String(session_id.to_string()),
);
self
}
/// Mark this invocation as the final answer — short-circuits the
/// LLM loop on the cell side.
pub fn final_answer(mut self, final_answer: bool) -> Self {
self.body
.insert("final_answer".to_string(), Value::Bool(final_answer));
self
}
/// Issue the invoke request.
pub async fn send(self) -> Result<Value> {
let path = format!(
"/memories/{}/harnesses/{}/tools/invoke",
self.tools.memory_id, self.slug
);
self.tools
.http
._post(&path, Some(&Value::Object(self.body)))
.await
}
}