arc-agi-rs 0.1.0

🤖 A Rust client SDK for the ARC-AGI-3 API.
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
// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # HTTP Client
//!
//! This module provides [`Client`] and its associated [`ClientBuilder`],
//! the primary entry points for interacting with the ARC-AGI-3 REST API.
//!
//! ## API Methods Overview
//!
//! | Method | Endpoint | Description |
//! |--------|----------|-------------|
//! | [`Client::get_anonymous_key`] | `GET /api/games/anonkey` | Obtain an anonymous API key |
//! | [`Client::list_environments`] | `GET /api/games` | List all available environments |
//! | [`Client::get_environment`] | `GET /api/games/{id}` | Get metadata for one environment |
//! | [`Client::open_scorecard`] | `POST /api/scorecard/open` | Create a new scorecard |
//! | [`Client::get_scorecard`] | `GET /api/scorecard/{id}` | Retrieve a scorecard by ID |
//! | [`Client::close_scorecard`] | `POST /api/scorecard/close` | Close and finalise a scorecard |
//! | [`Client::reset`] | `POST /api/cmd/RESET` | Reset (or start) a game environment |
//! | [`Client::step`] | `POST /api/cmd/{action}` | Send one action and receive the next frame |
//!
//! ## Configuration
//!
//! Use [`Client::builder()`] to set a custom API key, base URL, cookie
//! storage, or HTTP proxy before constructing the client. The zero-argument
//! [`Client::new()`] uses the `ARC_API_KEY` and `ARC_BASE_URL`
//! environment variables (or defaults) automatically.
//!
//! ## See Also
//!
//! - [ARC-AGI-3 Reference](https://arcprize.org/arc-agi/3)

use anyhow::Context;
use reqwest::Method;
use reqwest::Proxy;
use reqwest::Response;
use serde_json::{Value, json};

use crate::error::ArcAgiError;
use crate::models::{EnvironmentInfo, FrameData};
use crate::params::{ClientConfig, MakeParams, ScorecardParams, StepParams};
use crate::response::{AnonKeyResponse, EnvironmentScorecard, ScorecardOpenResponse};

/// The default ARC-AGI-3 production server URL.
pub const DEFAULT_BASE_URL: &str = "https://three.arcprize.org";

/// A fluent builder for [`Client`].
///
/// Obtain one via [`Client::builder()`].
///
/// # Example
/// ```rust
/// use arc_agi_rs::client::Client;
///
/// let client = Client::builder()
///     .api_key("my-key")
///     .cookie_store(true)
///     .build()
///     .expect("Failed to build client");
/// ```
#[derive(Debug, Default)]
pub struct ClientBuilder {
    config: ClientConfig,
    #[cfg(not(target_arch = "wasm32"))]
    cookie_store: bool,
    #[cfg(not(target_arch = "wasm32"))]
    proxy: Option<String>,
}

impl ClientBuilder {
    /// Sets the ARC-AGI-3 API key sent in the `X-API-Key` request header.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::builder().api_key("my-key").build().unwrap();
    /// ```
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.config = self.config.api_key(key);
        self
    }

    /// Sets the base URL of the ARC-AGI-3 server.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::builder()
    ///     .base_url("http://localhost:8080")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.config = self.config.base_url(url);
        self
    }

    /// Enables or disables cookie storage for the underlying HTTP client.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::builder()
    ///     .cookie_store(true)
    ///     .build()
    ///     .unwrap();
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn cookie_store(mut self, enable: bool) -> Self {
        self.cookie_store = enable;
        self
    }

    /// Configures a proxy for all HTTP requests.
    ///
    /// Accepts any URL string recognised by [`Proxy::all`], e.g.
    /// `"socks5://127.0.0.1:9050"`.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::builder()
    ///     .proxy("http://localhost:8080")
    ///     .build()
    ///     .unwrap();
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn proxy(mut self, url: impl Into<String>) -> Self {
        self.proxy = Some(url.into());
        self
    }

    /// Consumes the builder and returns a configured [`Client`].
    ///
    /// The proxy/cookie-store wiring is adapted from the `duckduckgo` crate's
    /// [`BrowserBuilder::build`] method:
    /// <https://github.com/wiseaidotdev/duckduckgo/blob/main/src/browser.rs>
    ///
    /// # Errors
    /// Returns an error if the proxy URL is invalid or the underlying
    /// [`reqwest::Client`] cannot be constructed.
    pub fn build(self) -> Result<Client, ArcAgiError> {
        let mut builder = reqwest::Client::builder();

        #[cfg(not(target_arch = "wasm32"))]
        if self.cookie_store {
            builder = builder.cookie_store(true);
        }

        #[cfg(not(target_arch = "wasm32"))]
        if let Some(proxy_url) = self.proxy {
            let proxy = Proxy::all(&proxy_url)
                .with_context(|| format!("Invalid proxy URL: {proxy_url}"))
                .map_err(ArcAgiError::from)?;
            builder = builder.proxy(proxy);
        }

        let client = builder
            .build()
            .context("Failed to build reqwest HTTP client")
            .map_err(ArcAgiError::from)?;

        Ok(Client {
            client,
            config: self.config,
        })
    }
}

/// An HTTP client for interacting with the ARC-AGI-3 REST API.
///
/// Use [`Client::new()`] for a zero-configuration default that reads
/// credentials from environment variables, or [`Client::builder()`] to
/// supply them programmatically.
///
/// All methods are `async`; wrap them in a [`tokio`] runtime or use the
/// synchronous Python / Node.js bindings which embed their own runtime.
///
/// # Example
/// ```rust
/// use arc_agi_rs::client::Client;
///
/// let client = Client::new();
/// ```
pub struct Client {
    client: reqwest::Client,
    config: ClientConfig,
}

impl Client {
    /// Creates a new `Client` with the default HTTP client, reading
    /// credentials from the `ARC_API_KEY` and `ARC_BASE_URL` environment
    /// variables.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::new();
    /// ```
    pub fn new() -> Self {
        Client {
            client: reqwest::Client::new(),
            config: ClientConfig::default(),
        }
    }

    /// Returns a [`ClientBuilder`] for configuring the client before
    /// construction.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// let client = Client::builder()
    ///     .cookie_store(true)
    ///     .build()
    ///     .expect("Failed to build client");
    /// ```
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Returns the resolved base URL used for all requests.
    pub fn base_url(&self) -> String {
        self.config.resolved_base_url()
    }

    /// Returns the resolved API key used in the `X-API-Key` header.
    pub fn api_key(&self) -> String {
        self.config.resolved_api_key()
    }

    /// Sends an authenticated HTTP request with optional query parameters.
    ///
    /// The `.query(params)` + `.header` + `.error_for_status()` chain is adapted
    /// from the `duckduckgo` crate's `Browser::request` method:
    /// <https://github.com/wiseaidotdev/duckduckgo/blob/main/src/browser.rs>
    async fn request(
        &self,
        method: Method,
        url: &str,
        params: &[(&str, &str)],
    ) -> Result<Response, ArcAgiError> {
        let api_key = self.api_key();
        let resp = self
            .client
            .request(method, url)
            .query(params)
            .header("X-API-Key", &api_key)
            .header("Accept", "application/json")
            .send()
            .await
            .with_context(|| format!("Failed to send request to {url}"))
            .map_err(ArcAgiError::from)?;
        let status = resp.status();
        let resp = resp
            .error_for_status()
            .with_context(|| format!("Request to {url} failed (HTTP {status})"))
            .map_err(ArcAgiError::from)?;
        Ok(resp)
    }

    /// Sends an authenticated HTTP POST request with a JSON body.
    async fn post_json(&self, url: &str, body: Value) -> Result<Response, ArcAgiError> {
        let api_key = self.api_key();
        let resp = self
            .client
            .post(url)
            .header("X-API-Key", &api_key)
            .header("Accept", "application/json")
            .json(&body)
            .send()
            .await
            .with_context(|| format!("Failed to POST to {url}"))
            .map_err(ArcAgiError::from)?;
        let status = resp.status();
        let resp = resp
            .error_for_status()
            .with_context(|| format!("POST to {url} failed (HTTP {status})"))
            .map_err(ArcAgiError::from)?;
        Ok(resp)
    }

    /// Retrieves an anonymous API key from the server.
    ///
    /// Useful when no personal API key is available; the anonymous key
    /// allows limited access to the public API.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] on network or HTTP failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let key = client.get_anonymous_key().await?;
    ///     println!("Got anon key: {key}");
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_anonymous_key(&self) -> Result<String, ArcAgiError> {
        let url = format!("{}/api/games/anonkey", self.base_url());
        let resp = self
            .client
            .get(&url)
            .header("Accept", "application/json")
            .send()
            .await
            .with_context(|| format!("Failed to GET {url}"))
            .map_err(ArcAgiError::from)?
            .error_for_status()
            .map_err(ArcAgiError::from)?;
        let body: AnonKeyResponse = resp
            .json()
            .await
            .context("Failed to deserialise anon key response")
            .map_err(ArcAgiError::from)?;
        Ok(body.api_key)
    }

    /// Returns all game environments available on the server.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] on network, HTTP, or JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let envs = client.list_environments().await?;
    ///     println!("{} environments available", envs.len());
    ///     Ok(())
    /// }
    /// ```
    pub async fn list_environments(&self) -> Result<Vec<EnvironmentInfo>, ArcAgiError> {
        let url = format!("{}/api/games", self.base_url());
        let resp = self.request(Method::GET, &url, &[]).await?;
        resp.json()
            .await
            .context("Failed to deserialise environment list")
            .map_err(ArcAgiError::from)
    }

    /// Returns metadata for the environment with the given `game_id`.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] when the game is not found (HTTP 404) or
    /// on network/JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let info = client.get_environment("ls20").await?;
    ///     println!("{:?}", info.title);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_environment(&self, game_id: &str) -> Result<EnvironmentInfo, ArcAgiError> {
        let url = format!("{}/api/games/{}", self.base_url(), game_id);
        let resp = self.request(Method::GET, &url, &[]).await?;
        resp.json()
            .await
            .context("Failed to deserialise environment info")
            .map_err(ArcAgiError::from)
    }

    /// Creates a new scorecard on the server and returns its ID.
    ///
    /// Passes `None` to use default params (`tags: ["agent"]`).
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] on network or HTTP failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let card_id = client.open_scorecard(None).await?;
    ///     println!("Scorecard: {card_id}");
    ///     Ok(())
    /// }
    /// ```
    pub async fn open_scorecard(
        &self,
        params: Option<ScorecardParams>,
    ) -> Result<String, ArcAgiError> {
        let url = format!("{}/api/scorecard/open", self.base_url());
        let body = params.unwrap_or_default().to_json_body();
        let resp = self.post_json(&url, body).await?;
        let open_resp: ScorecardOpenResponse = resp
            .json()
            .await
            .context("Failed to deserialise scorecard open response")
            .map_err(ArcAgiError::from)?;
        Ok(open_resp.card_id)
    }

    /// Retrieves an existing scorecard by its ID.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] when the scorecard is not found (HTTP 404)
    /// or on network/JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let card_id = client.open_scorecard(None).await?;
    ///     match client.get_scorecard(&card_id).await {
    ///         Ok(card) => println!("Score: {}", card.score),
    ///         Err(_)  => {}
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_scorecard(&self, card_id: &str) -> Result<EnvironmentScorecard, ArcAgiError> {
        let url = format!("{}/api/scorecard/{}", self.base_url(), card_id);
        let resp = self.request(Method::GET, &url, &[]).await?;
        resp.json()
            .await
            .context("Failed to deserialise scorecard")
            .map_err(ArcAgiError::from)
    }

    /// Closes an existing scorecard, finalises its scores, and returns the
    /// completed [`EnvironmentScorecard`].
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] when the scorecard is not found or on
    /// network/JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::new();
    ///     let card_id = client.open_scorecard(None).await?;
    ///     match client.close_scorecard(&card_id).await {
    ///         Ok(result) => println!("Final score: {}", result.score),
    ///         Err(_)    => {} // endpoint may not be available in this environment
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn close_scorecard(
        &self,
        card_id: &str,
    ) -> Result<EnvironmentScorecard, ArcAgiError> {
        let url = format!("{}/api/scorecard/close", self.base_url());
        let body = json!({ "card_id": card_id });
        let resp = self.post_json(&url, body).await?;
        resp.json()
            .await
            .context("Failed to deserialise close scorecard response")
            .map_err(ArcAgiError::from)
    }

    /// Resets (or starts) a game environment and returns the initial frame.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] on network, HTTP, or JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    /// use arc_agi_rs::params::MakeParams;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::builder().cookie_store(true).build()?;
    ///     let card_id = client.open_scorecard(None).await?;
    ///     let envs = client.list_environments().await?;
    ///     let game_id = envs.first().map(|e| &e.game_id).expect("no envs");
    ///     let params = MakeParams::new(game_id, &card_id);
    ///     let frame = client.reset(params).await?;
    ///     println!("GUID: {:?}", frame.guid);
    ///     Ok(())
    /// }
    /// ```
    pub async fn reset(&self, params: MakeParams) -> Result<FrameData, ArcAgiError> {
        let url = format!("{}/api/cmd/RESET", self.base_url());
        let mut body = json!({
            "game_id": params.game_id,
            "card_id": params.scorecard_id,
        });
        if let Some(guid) = &params.guid {
            body["guid"] = Value::String(guid.clone());
        }
        let resp = self.post_json(&url, body).await?;
        resp.json()
            .await
            .context("Failed to deserialise reset frame")
            .map_err(ArcAgiError::from)
    }

    /// Sends one game action and returns the resulting frame.
    ///
    /// Action ID `0` maps to `POST /api/cmd/RESET`; any other ID maps to
    /// `POST /api/cmd/ACTION{n}`.
    ///
    /// # Errors
    /// Returns an [`ArcAgiError`] on network, HTTP, or JSON failure.
    ///
    /// # Example
    /// ```rust
    /// use arc_agi_rs::client::Client;
    /// use arc_agi_rs::params::{MakeParams, StepParams};
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     if std::env::var("ARC_API_KEY").is_err() { return Ok(()); }
    ///     let client = Client::builder().cookie_store(true).build()?;
    ///     let card_id = client.open_scorecard(None).await?;
    ///     let envs = client.list_environments().await?;
    ///     let game_id = envs.first().map(|e| &e.game_id).expect("no envs");
    ///     let frame = client.reset(MakeParams::new(game_id, &card_id)).await?;
    ///     let guid = frame.guid.expect("server always returns a guid");
    ///     let action_id = *frame.available_actions.iter().find(|&&a| a != 0).unwrap_or(&1);
    ///     let params = StepParams::new(game_id, &card_id, &guid, action_id)
    ///         .data(arc_agi_rs::serde_json::json!({"x": 0, "y": 0}));
    ///     let frame = client.step(params).await?;
    ///     println!("State: {:?}", frame.state);
    ///     Ok(())
    /// }
    /// ```
    pub async fn step(&self, params: StepParams) -> Result<FrameData, ArcAgiError> {
        let action_segment = if params.action_id == 0 {
            "RESET".to_string()
        } else {
            format!("ACTION{}", params.action_id)
        };
        let url = format!("{}/api/cmd/{}", self.base_url(), action_segment);
        let mut body = json!({
            "game_id": params.game_id,
            "card_id": params.scorecard_id,
            "guid": params.guid,
        });
        if let Some(data) = &params.data {
            if let Some(x) = data.get("x") {
                body["x"] = x.clone();
            }
            if let Some(y) = data.get("y") {
                body["y"] = y.clone();
            }
        }
        if let Some(reasoning) = &params.reasoning {
            body["reasoning"] = reasoning.clone();
        }
        let resp = self.post_json(&url, body).await?;
        resp.json()
            .await
            .context("Failed to deserialise step frame")
            .map_err(ArcAgiError::from)
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.