areev 0.2.0

Rust SDK for the Areev knowledge database — gRPC and HTTP transports
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! `Harness` resource — Flow-A conversational interface.
//!
//! Mirrors the Python SDK's `client.harness.*` surface: `chat`,
//! `chat_resume`, `chat_cancel`, `chat_interactive`, `provision`,
//! `list_conversations`, `delete_conversation`,
//! `rotate_callback_secret`.
//!
//! The wire-level `chat` / `chat_resume` wrappers return raw JSON; for an
//! interactive request/pause/resume loop driven by client-side tool
//! executors use [`Harness::chat_interactive`].
//!
//! Harness CRUD (`create`, `list`, `get`, `update`, `delete`,
//! `templates`) is owned by the cell (`src/server/harness_routes.rs`) and
//! returns the `HarnessEnvelope` shape (`{...record, etag}`) as raw JSON.

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;

use serde_json::{json, Map, Value};

use crate::error::{AreevError, Result};
use crate::http::HttpClient;
use crate::types::{
    ChatResumeRequest, ChatToolOutput, HarnessChatRequest, HarnessChatResponse, HarnessChatStatus,
};

/// Conversational harness chat.
///
/// Access via [`crate::Areev::harness`].
pub struct Harness<'a> {
    http: &'a HttpClient,
    memory_id: String,
}

impl<'a> Harness<'a> {
    /// Internal constructor — use [`crate::Areev::harness`].
    pub(crate) fn new(http: &'a HttpClient, memory_id: String) -> Self {
        Self { http, memory_id }
    }

    // ── Harness CRUD ────────────────────────────────────────────────────
    //
    // The cell is the single writer for `HarnessRecord` (PG-backed
    // `harness_state` per-memory table). Every record/list response carries
    // an `etag` alongside the flattened record fields — pass it back as
    // `if_match` to [`Harness::update`] for optimistic concurrency.

    /// Create a harness. `chat` 404s (`HRN-E001`) until a record exists, so
    /// this is the entry point for the Flow-A surface.
    ///
    /// `name` + `slug` are required; everything else is optional. Returns
    /// the `HarnessEnvelope` (`{...record, etag}`) as raw JSON.
    pub fn create(&self, name: &str, slug: &str) -> CreateHarnessBuilder<'_, 'a> {
        CreateHarnessBuilder::new(self, name, slug)
    }

    /// List every harness in the memory. Each entry is a `HarnessEnvelope`
    /// (`{...record, etag}`).
    pub async fn list(&self) -> Result<Value> {
        let path = format!("/memories/{}/harnesses", self.memory_id);
        self.http._get(&path, None).await
    }

    /// Fetch one harness by slug. The response carries an `etag` — capture
    /// it to drive a subsequent [`Harness::update`].
    pub async fn get(&self, slug: &str) -> Result<Value> {
        let path = format!("/memories/{}/harnesses/{}", self.memory_id, slug);
        self.http._get(&path, None).await
    }

    /// Patch a harness. `if_match` (the current `etag`) is required by the
    /// server for optimistic concurrency — a stale value returns 412
    /// ([`crate::AreevError::Conflict`]). **Not auto-retried**: the etag
    /// guard already makes a blind replay a no-op or a 412, and the SDK
    /// must not paper over a lost-update race.
    ///
    /// `fields` is a partial map of the mutable record fields (`name`,
    /// `description`, `avatar`, `accent_color`, `welcome_message`,
    /// `status`, `assemble_query`, `slug`, `llm_config`). `if_match` is
    /// merged into the body, so callers pass only what they want changed.
    pub async fn update(&self, slug: &str, if_match: &str, fields: Value) -> Result<Value> {
        let mut body = match fields {
            Value::Object(m) => m,
            Value::Null => Map::new(),
            other => {
                return Err(AreevError::Other {
                    http_status: 0,
                    code: Some("CFG-E004".into()),
                    message: format!("update fields must be a JSON object, got {other}"),
                    body: Value::Null,
                    request_id: None,
                });
            }
        };
        body.insert("if_match".to_string(), Value::String(if_match.to_string()));
        default_provider_type(&mut body);
        let path = format!("/memories/{}/harnesses/{}", self.memory_id, slug);
        self.http._patch(&path, Some(&Value::Object(body))).await
    }

    /// Delete a harness by slug. **Not auto-retried** — a delete is
    /// terminal and a blind retry can mask a 404 on an already-removed
    /// record.
    pub async fn delete(&self, slug: &str) -> Result<()> {
        let path = format!("/memories/{}/harnesses/{}", self.memory_id, slug);
        self.http._delete_no_retry(&path).await.map(|_| ())
    }

    /// List the harness templates available in this memory. The cell
    /// lazy-seeds the baseline catalogue on first read. Returns
    /// `{templates: [...]}`.
    pub async fn templates(&self) -> Result<Value> {
        let path = format!("/memories/{}/harness-templates", self.memory_id);
        self.http._get(&path, None).await
    }

    /// Start a [`ChatBuilder`] for one harness turn.
    pub fn chat<'b>(&'b self, slug: &str, message: &str) -> ChatBuilder<'b, 'a> {
        ChatBuilder::new(self, slug, message)
    }

    /// Resume a paused chat turn after caller-side tools have run.
    ///
    /// `tool_outputs` is a list of `{"tool_call_id": "...",
    /// "output": ...}` (or `"content"` — server accepts either) — one
    /// entry per `pending_tool_calls` entry in the prior
    /// `requires_action` response.
    pub async fn chat_resume(
        &self,
        slug: &str,
        session_id: &str,
        tool_outputs: Vec<Value>,
    ) -> Result<Value> {
        let body = json!({
            "session_id": session_id,
            "tool_outputs": tool_outputs,
        });
        let path = format!(
            "/memories/{}/harnesses/{}/chat/resume",
            self.memory_id, slug
        );
        self.http._post(&path, Some(&body)).await
    }

    /// Cancel a paused chat session — frees server-side state.
    ///
    /// The underlying endpoint is idempotent across 204 + 404 (HPL
    /// opaque cross-principal shape, HRN-E015). 404s surface as a
    /// transport-layer success so callers can treat cancellation as
    /// best-effort.
    pub async fn chat_cancel(&self, slug: &str, session_id: &str) -> Result<()> {
        let path = format!(
            "/memories/{}/harnesses/{}/chat/sessions/{}",
            self.memory_id, slug, session_id
        );
        match self.http._delete(&path).await {
            Ok(_) => Ok(()),
            Err(e) => {
                if e.http_status() == 404 {
                    Ok(())
                } else {
                    Err(e)
                }
            }
        }
    }

    /// Start a builder to drive a full Flow-A turn with client-side tool
    /// executors. Prefer this over [`Harness::chat_interactive`] — the
    /// builder names each argument so the call site isn't three
    /// indistinguishable bare strings.
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> areev::Result<()> {
    /// # let areev = areev::Areev::from_env();
    /// let executors: areev::ChatExecutors = areev::ChatExecutors::new();
    /// let resp = areev
    ///     .harness()
    ///     .chat_session("weather")
    ///     .conversation_id("conv-1") // omit for a fresh single-shot turn
    ///     .message("what's the weather in Paris?")
    ///     .executors(&executors)
    ///     .send()
    ///     .await?;
    /// # let _ = resp;
    /// # Ok(())
    /// # }
    /// ```
    pub fn chat_session(&self, slug: &str) -> ChatSessionBuilder<'_, 'a> {
        ChatSessionBuilder::new(self, slug)
    }

    /// Drive a full Flow-A turn with client-side tool executors.
    ///
    /// Runs one turn (`POST .../chat`); if it pauses on `client://` tool
    /// calls, looks up an executor for each pending `tool_name` in
    /// `executors`, runs them, and resumes the turn (`POST
    /// .../chat/resume`). Loops until `status == Completed`.
    ///
    /// Positional — for self-documenting named arguments use the
    /// [`Harness::chat_session`] builder instead.
    ///
    /// # Errors
    ///
    /// - Returns [`AreevError::Other`] with `http_status = 500` if a
    ///   pending tool has no registered executor.
    /// - Any HTTP error from the underlying calls is propagated.
    pub async fn chat_interactive<E>(
        &self,
        slug: &str,
        conversation_id: &str,
        user_message: &str,
        executors: &ChatExecutors<E>,
    ) -> Result<HarnessChatResponse>
    where
        E: Fn(String, Value) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync,
    {
        // The server requires a non-empty `conversation_id` (422 otherwise);
        // mint one when the caller passes "" so single-shot interactive
        // turns work without bookkeeping.
        let conversation_id = if conversation_id.is_empty() {
            gen_conversation_id()
        } else {
            conversation_id.to_string()
        };
        let req = HarnessChatRequest {
            conversation_id,
            user_message: user_message.to_string(),
            model: None,
            provider: None,
        };
        let mut resp = self.http.harness_chat(slug, &req).await?;
        loop {
            if matches!(resp.status, HarnessChatStatus::Completed) {
                return Ok(resp);
            }
            let session_id = resp.session_id.clone().ok_or_else(|| AreevError::Other {
                http_status: 500,
                code: None,
                message: "requires_action without session_id".into(),
                body: Value::Null,
                request_id: None,
            })?;
            let mut tool_outputs = Vec::with_capacity(resp.pending_tool_calls.len());
            for pc in &resp.pending_tool_calls {
                let executor = executors
                    .get(&pc.tool_name)
                    .ok_or_else(|| AreevError::Other {
                        http_status: 500,
                        code: None,
                        message: format!(
                            "no executor registered for tool '{}' (tool_call_id={})",
                            pc.tool_name, pc.tool_call_id
                        ),
                        body: Value::Null,
                        request_id: None,
                    })?;
                let args: Value = serde_json::from_str(&pc.arguments).unwrap_or(Value::Null);
                let output = executor(pc.tool_name.clone(), args).await?;
                tool_outputs.push(ChatToolOutput {
                    tool_call_id: pc.tool_call_id.clone(),
                    output,
                    is_error: None,
                });
            }
            let resume_req = ChatResumeRequest {
                session_id,
                tool_outputs,
                tenant_timestamp_ms: None,
            };
            resp = self.http.harness_chat_resume(slug, &resume_req).await?;
        }
    }

    /// Provision a harness from a template.
    ///
    /// Requires: Scale or Custom plan. Emits an audit event.
    pub async fn provision(&self, slug: &str, template_id: &str) -> Result<Value> {
        let body = json!({ "template_id": template_id });
        let path = format!("/memories/{}/harnesses/{}/provision", self.memory_id, slug);
        self.http._post(&path, Some(&body)).await
    }

    /// List a harness's conversations. `filters` is added as query
    /// parameters. Requires: Scale or Custom plan.
    pub async fn list_conversations(&self, slug: &str, filters: Option<&Value>) -> Result<Value> {
        let path = format!(
            "/memories/{}/harnesses/{}/conversations",
            self.memory_id, slug
        );
        self.http._get(&path, filters).await
    }

    /// Delete a harness conversation and its turns.
    ///
    /// Requires: Scale or Custom plan. Emits an audit event.
    pub async fn delete_conversation(&self, slug: &str, conversation_id: &str) -> Result<()> {
        let path = format!(
            "/memories/{}/harnesses/{}/conversations/{}",
            self.memory_id, slug, conversation_id
        );
        self.http._delete(&path).await.map(|_| ())
    }

    /// Rotate the harness's tool-callback signing secret.
    ///
    /// Returns a [`RotatedCallbackSecret`] whose plaintext `secret` is
    /// shown once and never retrievable — store it now and do not log it
    /// (the returned struct redacts the secret from its `Debug`).
    ///
    /// Pass `if_match` (the current secret fingerprint) for optimistic
    /// concurrency — the server returns 409 / 412 ([`crate::AreevError::Conflict`])
    /// if it no longer matches, guarding against a lost-update race
    /// between two rotations.
    ///
    /// Requires: Scale or Custom plan + admin scope. Emits an audit
    /// event. **Not auto-retried** — a retried rotation would mint a
    /// second secret and invalidate the first.
    pub async fn rotate_callback_secret(
        &self,
        slug: &str,
        if_match: Option<&str>,
    ) -> Result<RotatedCallbackSecret> {
        let path = format!(
            "/memories/{}/harnesses/{}/tool_callback_secret/rotate",
            self.memory_id, slug
        );
        let resp = self
            .http
            ._post_if_match_no_retry(&path, Some(&json!({})), if_match)
            .await?;
        let get = |keys: &[&str]| -> Option<String> {
            let map = resp.as_object()?;
            for k in keys {
                if let Some(s) = map.get(*k).and_then(|v| v.as_str()) {
                    if !s.is_empty() {
                        return Some(s.to_string());
                    }
                }
            }
            None
        };
        Ok(RotatedCallbackSecret {
            secret: get(&["secret", "callback_secret"]).unwrap_or_default(),
            callback_secret_fp: get(&["callback_secret_fp", "fingerprint"]),
            rotated_at_ms: resp.get("rotated_at_ms").and_then(|v| v.as_i64()),
        })
    }
}

/// Result of [`Harness::rotate_callback_secret`].
///
/// The plaintext `secret` is shown exactly once and is never retrievable
/// afterwards — store it immediately and do not log it. This struct does
/// **not** derive `Debug`; the manual [`fmt::Debug`] impl redacts the
/// secret so it cannot leak into `{:?}`, logging, or panic messages.
/// Read [`RotatedCallbackSecret::secret`] explicitly to use it.
#[derive(Clone)]
pub struct RotatedCallbackSecret {
    /// The one-time plaintext callback secret. Redacted from `Debug`.
    pub secret: String,
    /// Fingerprint of the new secret — safe to log / persist.
    pub callback_secret_fp: Option<String>,
    /// Epoch milliseconds when the rotation took effect.
    pub rotated_at_ms: Option<i64>,
}

impl fmt::Debug for RotatedCallbackSecret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RotatedCallbackSecret")
            .field("secret", &"[REDACTED]")
            .field("callback_secret_fp", &self.callback_secret_fp)
            .field("rotated_at_ms", &self.rotated_at_ms)
            .finish()
    }
}

/// Builder for [`Harness::chat`].
pub struct ChatBuilder<'b, 'a> {
    harness: &'b Harness<'a>,
    slug: String,
    body: Map<String, Value>,
}

impl<'b, 'a> ChatBuilder<'b, 'a> {
    fn new(harness: &'b Harness<'a>, slug: &str, message: &str) -> Self {
        let mut body = Map::new();
        body.insert(
            "user_message".to_string(),
            Value::String(message.to_string()),
        );
        Self {
            harness,
            slug: slug.to_string(),
            body,
        }
    }

    /// Stable conversation id (defaults to one generated server-side
    /// when omitted).
    pub fn conversation_id(mut self, conversation_id: &str) -> Self {
        self.body.insert(
            "conversation_id".to_string(),
            Value::String(conversation_id.to_string()),
        );
        self
    }

    /// Override the LLM provider for this turn.
    pub fn provider(mut self, provider: &str) -> Self {
        self.body
            .insert("provider".to_string(), Value::String(provider.to_string()));
        self
    }

    /// Override the LLM model for this turn.
    pub fn model(mut self, model: &str) -> Self {
        self.body
            .insert("model".to_string(), Value::String(model.to_string()));
        self
    }

    /// Issue the chat request.
    pub async fn send(mut self) -> Result<Value> {
        // The server requires a non-empty `conversation_id` (422 otherwise).
        // Mint one when the caller didn't set it so single-shot chat works.
        self.body
            .entry("conversation_id".to_string())
            .or_insert_with(|| Value::String(gen_conversation_id()));
        let path = format!(
            "/memories/{}/harnesses/{}/chat",
            self.harness.memory_id, self.slug
        );
        self.harness
            .http
            ._post(&path, Some(&Value::Object(self.body)))
            .await
    }
}

/// Builder for [`Harness::create`]. `name` + `slug` are mandatory; the
/// remaining fields are optional and omitted from the wire body when
/// unset.
pub struct CreateHarnessBuilder<'b, 'a> {
    harness: &'b Harness<'a>,
    body: Map<String, Value>,
}

impl<'b, 'a> CreateHarnessBuilder<'b, 'a> {
    fn new(harness: &'b Harness<'a>, name: &str, slug: &str) -> Self {
        let mut body = Map::new();
        body.insert("name".to_string(), Value::String(name.to_string()));
        body.insert("slug".to_string(), Value::String(slug.to_string()));
        Self { harness, body }
    }

    fn set(mut self, key: &str, value: &str) -> Self {
        self.body
            .insert(key.to_string(), Value::String(value.to_string()));
        self
    }

    /// Human-readable description.
    pub fn description(self, description: &str) -> Self {
        self.set("description", description)
    }

    /// Template id to provision the harness from.
    pub fn template_id(self, template_id: &str) -> Self {
        self.set("template_id", template_id)
    }

    /// Override the CAL saved-query used to assemble chat context
    /// (defaults server-side to `harness_context`).
    pub fn assemble_query(self, assemble_query: &str) -> Self {
        self.set("assemble_query", assemble_query)
    }

    /// Cosmetic avatar reference.
    pub fn avatar(self, avatar: &str) -> Self {
        self.set("avatar", avatar)
    }

    /// Cosmetic accent colour.
    pub fn accent_color(self, accent_color: &str) -> Self {
        self.set("accent_color", accent_color)
    }

    /// First-turn welcome message.
    pub fn welcome_message(self, welcome_message: &str) -> Self {
        self.set("welcome_message", welcome_message)
    }

    /// Per-harness LLM selection. `provider_id` + `model` are required;
    /// `provider_type` defaults to `provider_id` when not set via
    /// [`Self::provider_type`]. Validated server-side (`HRN-E062..E064`).
    pub fn llm_config(mut self, provider_id: &str, model: &str) -> Self {
        self.body.insert(
            "llm_config".to_string(),
            json!({
                "provider_id": provider_id,
                "model": model,
            }),
        );
        self
    }

    /// Override `llm_config.provider_type` (defaults to `provider_id`).
    /// No-op unless [`Self::llm_config`] was called first.
    pub fn provider_type(mut self, provider_type: &str) -> Self {
        if let Some(Value::Object(cfg)) = self.body.get_mut("llm_config") {
            cfg.insert(
                "provider_type".to_string(),
                Value::String(provider_type.to_string()),
            );
        }
        self
    }

    /// Issue the create request. Returns the `HarnessEnvelope`
    /// (`{...record, etag}`) as raw JSON.
    pub async fn send(mut self) -> Result<Value> {
        default_provider_type(&mut self.body);
        let path = format!("/memories/{}/harnesses", self.harness.memory_id);
        self.harness
            .http
            ._post(&path, Some(&Value::Object(self.body)))
            .await
    }
}

/// Default `llm_config.provider_type` to `provider_id` when the former is
/// absent and the latter is set.
///
/// The cell's `llm_config` requires `provider_type`; a config carrying only
/// `provider_id` would 422. Most callers use the provider id as the type
/// (`"openai"`, `"anthropic"`, …), so fill it in transparently. Mirrors the
/// Python SDK's `_default_provider_type`.
fn default_provider_type(body: &mut Map<String, Value>) {
    if let Some(Value::Object(cfg)) = body.get_mut("llm_config") {
        let has_provider_id = cfg
            .get("provider_id")
            .and_then(Value::as_str)
            .is_some_and(|s| !s.is_empty());
        let has_provider_type = cfg
            .get("provider_type")
            .and_then(Value::as_str)
            .is_some_and(|s| !s.is_empty());
        if has_provider_id && !has_provider_type {
            let pid = cfg["provider_id"].clone();
            cfg.insert("provider_type".to_string(), pid);
        }
    }
}

/// Builder for [`Harness::chat_session`] — the ergonomic, self-documenting
/// front-end to [`Harness::chat_interactive`].
///
/// Set `.conversation_id(...)` (optional — omit to mint a fresh id for a
/// single-shot turn), `.message(...)` (required), and `.executors(...)`
/// (required — the client-side tool registry), then `.send()`.
pub struct ChatSessionBuilder<'b, 'a, E = ChatExecutor> {
    harness: &'b Harness<'a>,
    slug: String,
    conversation_id: Option<String>,
    message: Option<String>,
    executors: Option<&'b ChatExecutors<E>>,
}

impl<'b, 'a, E> ChatSessionBuilder<'b, 'a, E> {
    fn new(harness: &'b Harness<'a>, slug: &str) -> Self {
        Self {
            harness,
            slug: slug.to_string(),
            conversation_id: None,
            message: None,
            executors: None,
        }
    }

    /// Set the conversation id. Omit (or pass `""`) to mint a fresh id
    /// for a single-shot turn.
    pub fn conversation_id(mut self, conversation_id: impl Into<String>) -> Self {
        self.conversation_id = Some(conversation_id.into());
        self
    }

    /// Set the user message to send (required).
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// Set the client-side tool executor registry (required).
    pub fn executors(mut self, executors: &'b ChatExecutors<E>) -> Self {
        self.executors = Some(executors);
        self
    }

    /// Run the turn (pausing/resuming on `client://` tool calls) until it
    /// completes. Returns [`AreevError::Validation`] (`SDK-E003`) if
    /// `.message(...)` or `.executors(...)` was not set.
    pub async fn send(self) -> Result<HarnessChatResponse>
    where
        E: Fn(String, Value) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync,
    {
        let message = self.message.ok_or_else(|| AreevError::Validation {
            code: Some("SDK-E003".to_string()),
            http_status: 0,
            message: "chat_session: .message(...) is required".to_string(),
            body: Value::Null,
            request_id: None,
        })?;
        let executors = self.executors.ok_or_else(|| AreevError::Validation {
            code: Some("SDK-E003".to_string()),
            http_status: 0,
            message: "chat_session: .executors(...) is required".to_string(),
            body: Value::Null,
            request_id: None,
        })?;
        let conversation_id = self.conversation_id.unwrap_or_default();
        self.harness
            .chat_interactive(&self.slug, &conversation_id, &message, executors)
            .await
    }
}

/// Mint a stable conversation id when the caller didn't supply one, so a
/// single-shot chat turn satisfies the server's required `conversation_id`.
fn gen_conversation_id() -> String {
    format!("conv-{}", uuid::Uuid::new_v4())
}

/// Map of tool-name → async executor used by [`Harness::chat_interactive`].
///
/// Each executor takes `(tool_name, arguments)` (arguments already
/// JSON-parsed from the LLM's raw string) and must return the
/// structured output that will be POSTed back to `/chat/resume`.
pub type ChatExecutor =
    Box<dyn Fn(String, Value) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync>;

/// Registry of client-side tool executors keyed by `tool_name`, consumed
/// by [`Harness::chat_interactive`].
pub struct ChatExecutors<E = ChatExecutor> {
    inner: HashMap<String, E>,
}

impl<E> Default for ChatExecutors<E> {
    fn default() -> Self {
        Self {
            inner: HashMap::new(),
        }
    }
}

impl<E> ChatExecutors<E> {
    /// Construct an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register an executor for a tool name. Overwrites any prior entry.
    pub fn insert(&mut self, name: impl Into<String>, exec: E) -> &mut Self {
        self.inner.insert(name.into(), exec);
        self
    }

    /// Look up an executor by tool name.
    pub fn get(&self, name: &str) -> Option<&E> {
        self.inner.get(name)
    }

    /// Number of registered executors.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether the registry has no executors.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::default_provider_type;
    use serde_json::{json, Map, Value};

    fn map(v: Value) -> Map<String, Value> {
        v.as_object().cloned().unwrap()
    }

    #[test]
    fn defaults_provider_type_to_provider_id_when_absent() {
        let mut body = map(json!({
            "llm_config": {"provider_id": "openai", "model": "gpt-4o-mini"}
        }));
        default_provider_type(&mut body);
        assert_eq!(body["llm_config"]["provider_type"], "openai");
    }

    #[test]
    fn keeps_explicit_provider_type() {
        let mut body = map(json!({
            "llm_config": {"provider_id": "openrouter", "provider_type": "openai", "model": "x"}
        }));
        default_provider_type(&mut body);
        assert_eq!(body["llm_config"]["provider_type"], "openai");
    }

    #[test]
    fn noop_without_llm_config_or_provider_id() {
        let mut body = map(json!({"name": "Bot"}));
        default_provider_type(&mut body);
        assert!(!body.contains_key("llm_config"));

        let mut body2 = map(json!({"llm_config": {"model": "x"}}));
        default_provider_type(&mut body2);
        assert!(body2["llm_config"].get("provider_type").is_none());
    }
}