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
// Juncture client types for remote graph execution
//
// This module provides client types for interacting with Juncture Server
// from external applications.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Authentication configuration for client
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AuthConfig {
/// No authentication
None,
/// Bearer token authentication
Token(String),
/// API key authentication with custom header
ApiKey {
/// Header name for the API key
header: String,
/// API key value
key: String,
},
}
/// Configuration for graph invocation
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct InvokeConfig {
/// Thread ID for stateful execution
pub thread_id: Option<String>,
/// Checkpoint ID for time-travel
pub checkpoint_id: Option<String>,
/// Recursion limit
pub recursion_limit: Option<usize>,
/// Metadata
pub metadata: Option<HashMap<String, serde_json::Value>>,
/// Tags
pub tags: Option<Vec<String>>,
/// Interrupt before nodes
pub interrupt_before: Option<Vec<String>>,
/// Interrupt after nodes
pub interrupt_after: Option<Vec<String>>,
}
/// Thread information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Thread {
/// Thread ID
pub id: String,
/// Creation timestamp
pub created_at: chrono::DateTime<chrono::Utc>,
/// Metadata
pub metadata: Option<HashMap<String, serde_json::Value>>,
}
/// Graph information
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GraphInfo {
/// Graph ID
pub id: String,
/// Graph name
pub name: String,
/// Creation timestamp
pub created_at: chrono::DateTime<chrono::Utc>,
}
/// State snapshot
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StateSnapshot<T> {
/// State values
pub values: T,
/// Next checkpoint ID
pub next: Option<String>,
/// Metadata
pub metadata: Option<HashMap<String, serde_json::Value>>,
/// Creation timestamp
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}
/// Client error types
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
/// Connection error
#[error("connection error: {0}")]
Connection(String),
/// Authentication failed
#[error("authentication failed: {0}")]
Auth(String),
/// Graph not found
#[error("graph not found: {0}")]
GraphNotFound(String),
/// Thread not found
#[error("thread not found: {0}")]
ThreadNotFound(String),
/// Run not found
#[error("run not found: {0}")]
RunNotFound(String),
/// Serialization error
#[error("serialization error: {0}")]
Serialize(#[from] serde_json::Error),
/// HTTP request error
#[error("HTTP request error: {0}")]
RequestError(#[from] reqwest::Error),
/// Server error
#[error("server error ({status}): {message}")]
Server {
/// HTTP status code
status: u16,
/// Error message
message: String,
},
/// Timeout
#[error("timeout")]
Timeout,
/// Other errors
#[error("client error: {0}")]
Other(String),
}
/// Juncture client for server interaction
///
/// Provides methods for managing graphs and threads.
#[derive(Debug)]
pub struct JunctureClient {
/// HTTP client
client: reqwest::Client,
/// Server endpoint
endpoint: String,
/// Authentication configuration
auth: AuthConfig,
}
impl JunctureClient {
/// Create new client
///
/// # Arguments
///
/// * `endpoint` - Server base URL
pub fn new(endpoint: impl Into<String>) -> Self {
Self {
client: reqwest::Client::new(),
endpoint: endpoint.into(),
auth: AuthConfig::None,
}
}
/// Set authentication
///
/// # Arguments
///
/// * `auth` - Authentication configuration
#[must_use]
pub fn with_auth(mut self, auth: AuthConfig) -> Self {
self.auth = auth;
self
}
/// List all deployed graphs
///
/// # Returns
///
/// List of graph information
///
/// # Errors
///
/// Returns `ClientError` if the request fails, authentication fails, or the server returns an error.
pub async fn list_graphs(&self) -> Result<Vec<GraphInfo>, ClientError> {
let url = format!("{}/graphs", self.endpoint);
let response = self
.client
.get(&url)
.apply_auth(&self.auth)?
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Get graph client for specific graph
///
/// # Arguments
///
/// * `graph_id` - Graph identifier
///
/// # Errors
///
/// This function cannot fail.
#[must_use]
pub fn graph(&self, graph_id: &str) -> GraphClient {
GraphClient {
client: self.client.clone(),
endpoint: format!("{}/graphs/{}", self.endpoint, graph_id),
auth: self.auth.clone(),
}
}
/// Create new thread
///
/// # Arguments
///
/// * `metadata` - Optional thread metadata
///
/// # Errors
///
/// Returns `ClientError` if the request fails, authentication fails, or the server returns an error.
pub async fn create_thread(
&self,
metadata: Option<HashMap<String, serde_json::Value>>,
) -> Result<Thread, ClientError> {
let url = format!("{}/threads", self.endpoint);
let response = self
.client
.post(&url)
.apply_auth(&self.auth)?
.json(&serde_json::json!({ "metadata": metadata }))
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Get thread information
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn get_thread(&self, thread_id: &str) -> Result<Thread, ClientError> {
let url = format!("{}/threads/{}", self.endpoint, thread_id);
let response = self
.client
.get(&url)
.apply_auth(&self.auth)?
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// List all threads
///
/// # Arguments
///
/// * `limit` - Optional result limit
///
/// # Errors
///
/// Returns `ClientError` if the request fails, authentication fails, or the server returns an error.
pub async fn list_threads(&self, limit: Option<usize>) -> Result<Vec<Thread>, ClientError> {
let url = format!("{}/threads", self.endpoint);
let mut request = self.client.get(&url).apply_auth(&self.auth)?;
if let Some(limit) = limit {
request = request.query(&[("limit", limit)]);
}
let response = request
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Delete thread
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn delete_thread(&self, thread_id: &str) -> Result<(), ClientError> {
let url = format!("{}/threads/{}", self.endpoint, thread_id);
let response = self
.client
.delete(&url)
.apply_auth(&self.auth)?
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
Ok(())
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
}
/// Extension trait for applying authentication to requests
trait RequestBuilderExt: Sized {
fn apply_auth(self, auth: &AuthConfig) -> Result<Self, ClientError>;
}
impl RequestBuilderExt for reqwest::RequestBuilder {
fn apply_auth(self, auth: &AuthConfig) -> Result<Self, ClientError> {
match auth {
AuthConfig::None => Ok(self),
AuthConfig::Token(token) => Ok(self.bearer_auth(token)),
AuthConfig::ApiKey { header, key } => Ok(self.header(header, key)),
}
}
}
/// Graph-specific client
///
/// Provides methods for invoking and managing a specific graph.
#[derive(Debug)]
pub struct GraphClient {
/// HTTP client
client: reqwest::Client,
/// Graph endpoint
endpoint: String,
/// Authentication configuration
auth: AuthConfig,
}
impl GraphClient {
/// Create new `GraphClient`
///
/// # Arguments
///
/// * `client` - HTTP client
/// * `endpoint` - Graph endpoint
/// * `auth` - Authentication configuration
#[must_use]
pub(crate) const fn new(client: reqwest::Client, endpoint: String, auth: AuthConfig) -> Self {
Self {
client,
endpoint,
auth,
}
}
/// Invoke graph synchronously
///
/// # Type Parameters
///
/// * `S` - Output state type
///
/// # Arguments
///
/// * `input` - Input state as JSON
/// * `config` - Optional invocation configuration
///
/// # Errors
///
/// Returns `ClientError` if the request fails, authentication fails, or the server returns an error.
pub async fn invoke<S: for<'de> Deserialize<'de>>(
&self,
input: serde_json::Value,
config: Option<InvokeConfig>,
) -> Result<S, ClientError> {
let response = self
.client
.post(format!("{}/invoke", self.endpoint))
.apply_auth(&self.auth)?
.json(&serde_json::json!({
"input": input,
"config": config
}))
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Get current state
///
/// # Type Parameters
///
/// * `T` - State type
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn get_state<T: for<'de> Deserialize<'de>>(
&self,
thread_id: &str,
) -> Result<StateSnapshot<T>, ClientError> {
let response = self
.client
.get(format!("{}/threads/{}/state", self.endpoint, thread_id))
.apply_auth(&self.auth)?
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Get state history
///
/// # Type Parameters
///
/// * `T` - State type
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
/// * `limit` - Optional result limit
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn get_state_history<T: for<'de> Deserialize<'de>>(
&self,
thread_id: &str,
limit: Option<usize>,
) -> Result<Vec<StateSnapshot<T>>, ClientError> {
let url = format!("{}/threads/{}/history", self.endpoint, thread_id);
let mut request = self.client.get(&url).apply_auth(&self.auth)?;
if let Some(limit) = limit {
request = request.query(&[("limit", limit)]);
}
let response = request
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Update state
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
/// * `update` - State update as JSON
/// * `as_node` - Optional node name for update
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn update_state(
&self,
thread_id: &str,
update: serde_json::Value,
as_node: Option<&str>,
) -> Result<(), ClientError> {
let response = self
.client
.post(format!("{}/threads/{}/state", self.endpoint, thread_id))
.apply_auth(&self.auth)?
.json(&serde_json::json!({
"update": update,
"as_node": as_node
}))
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
Ok(())
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Resume execution
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
/// * `values` - Resume values
///
/// # Errors
///
/// Returns `ClientError` if the thread is not found, the request fails, or the server returns an error.
pub async fn resume(
&self,
thread_id: &str,
values: Vec<serde_json::Value>,
) -> Result<serde_json::Value, ClientError> {
let response = self
.client
.post(format!("{}/threads/{}/resume", self.endpoint, thread_id))
.apply_auth(&self.auth)?
.json(&serde_json::json!({ "values": values }))
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
response.json().await.map_err(ClientError::RequestError)
} else if response.status() == 404 {
Err(ClientError::ThreadNotFound(thread_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Cancel execution
///
/// # Arguments
///
/// * `thread_id` - Thread identifier
/// * `run_id` - Run identifier
///
/// # Errors
///
/// Returns `ClientError` if the run is not found, the request fails, or the server returns an error.
pub async fn cancel(&self, thread_id: &str, run_id: &str) -> Result<(), ClientError> {
let response = self
.client
.post(format!(
"{}/threads/{}/runs/{}/cancel",
self.endpoint, thread_id, run_id
))
.apply_auth(&self.auth)?
.send()
.await
.map_err(|e| ClientError::Connection(e.to_string()))?;
if response.status().is_success() {
Ok(())
} else if response.status() == 404 {
Err(ClientError::RunNotFound(run_id.to_string()))
} else {
Err(ClientError::Server {
status: response.status().as_u16(),
message: response.text().await.unwrap_or_default(),
})
}
}
/// Get the HTTP client
#[must_use]
pub(crate) const fn client(&self) -> &reqwest::Client {
&self.client
}
/// Get the endpoint
#[must_use]
pub(crate) fn endpoint(&self) -> &str {
&self.endpoint
}
/// Get the auth configuration
#[must_use]
pub(crate) const fn auth(&self) -> &AuthConfig {
&self.auth
}
}
// Rust guideline compliant 2026-05-19