-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathclient.rs
More file actions
1014 lines (906 loc) · 32 KB
/
client.rs
File metadata and controls
1014 lines (906 loc) · 32 KB
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use reqwest::{Client as ReqwestClient, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashSet;
use std::fs::File;
use std::path::Path;
use tempfile::{Builder, NamedTempFile};
use zip::CompressionMethod;
use zip::write::FileOptions;
use crate::error::{Error, Result};
/// High-level HTTP client for OpenViking API
#[derive(Clone)]
pub struct HttpClient {
http: ReqwestClient,
base_url: String,
api_key: Option<String>,
account: Option<String>,
user: Option<String>,
agent_id: Option<String>,
}
impl HttpClient {
/// Create a new HTTP client
pub fn new(
base_url: impl Into<String>,
api_key: Option<String>,
agent_id: Option<String>,
account: Option<String>,
user: Option<String>,
timeout_secs: f64,
) -> Self {
let http = ReqwestClient::builder()
.timeout(std::time::Duration::from_secs_f64(timeout_secs))
.build()
.expect("Failed to build HTTP client");
Self {
http,
base_url: base_url.into().trim_end_matches('/').to_string(),
api_key,
account,
user,
agent_id,
}
}
/// Zip a directory to a temporary file
fn zip_directory(&self, dir_path: &Path) -> Result<NamedTempFile> {
if !dir_path.is_dir() {
return Err(Error::Network(format!(
"Path {} is not a directory",
dir_path.display()
)));
}
let temp_file = Builder::new().suffix(".zip").tempfile()?;
let file = File::create(temp_file.path())?;
let mut zip = zip::ZipWriter::new(file);
let options: FileOptions<'_, ()> =
FileOptions::default().compression_method(CompressionMethod::Deflated);
let walkdir = walkdir::WalkDir::new(dir_path);
for entry in walkdir.into_iter().filter_map(|e| e.ok()) {
let path = entry.path();
if path.is_file() {
let name = path.strip_prefix(dir_path).unwrap_or(path);
zip.start_file(name.to_string_lossy(), options)?;
let mut file = File::open(path)?;
std::io::copy(&mut file, &mut zip)?;
}
}
zip.finish()?;
Ok(temp_file)
}
/// Upload a temporary file and return the temp_file_id
async fn upload_temp_file(&self, file_path: &Path) -> Result<String> {
let url = format!("{}/api/v1/resources/temp_upload", self.base_url);
let file_name = file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("temp_upload.zip");
// Read file content
let file_content = tokio::fs::read(file_path).await?;
// Create multipart form
let part = reqwest::multipart::Part::bytes(file_content).file_name(file_name.to_string());
let part = part
.mime_str("application/octet-stream")
.map_err(|e| Error::Network(format!("Failed to set mime type: {}", e)))?;
let form = reqwest::multipart::Form::new().part("file", part);
let mut headers = self.build_headers();
// Remove Content-Type: application/json, let reqwest set multipart/form-data automatically
headers.remove(reqwest::header::CONTENT_TYPE);
let response = self
.http
.post(&url)
.headers(headers)
.multipart(form)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
let result: Value = self.handle_response(response).await?;
result
.get("temp_file_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| Error::Parse("Missing temp_file_id in response".to_string()))
}
fn build_headers(&self) -> reqwest::header::HeaderMap {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
if let Some(api_key) = &self.api_key {
if let Ok(value) = reqwest::header::HeaderValue::from_str(api_key) {
headers.insert("X-API-Key", value);
}
}
if let Some(agent_id) = &self.agent_id {
if let Ok(value) = reqwest::header::HeaderValue::from_str(agent_id) {
headers.insert("X-OpenViking-Agent", value);
}
}
if let Some(account) = &self.account {
if let Ok(value) = reqwest::header::HeaderValue::from_str(account) {
headers.insert("X-OpenViking-Account", value);
}
}
if let Some(user) = &self.user {
if let Ok(value) = reqwest::header::HeaderValue::from_str(user) {
headers.insert("X-OpenViking-User", value);
}
}
headers
}
/// Make a GET request
pub async fn get<T: DeserializeOwned>(
&self,
path: &str,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
let response = self
.http
.get(&url)
.headers(self.build_headers())
.query(params)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
self.handle_response(response).await
}
/// Make a POST request
pub async fn post<B: serde::Serialize, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
let response = self
.http
.post(&url)
.headers(self.build_headers())
.json(body)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
self.handle_response(response).await
}
/// Make a PUT request
pub async fn put<B: serde::Serialize, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
let response = self
.http
.put(&url)
.headers(self.build_headers())
.json(body)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
self.handle_response(response).await
}
/// Make a DELETE request
pub async fn delete<T: DeserializeOwned>(
&self,
path: &str,
params: &[(String, String)],
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
let response = self
.http
.delete(&url)
.headers(self.build_headers())
.query(params)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
self.handle_response(response).await
}
/// Make a DELETE request with a JSON body
pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = format!("{}{}", self.base_url, path);
let response = self
.http
.delete(&url)
.headers(self.build_headers())
.json(body)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
self.handle_response(response).await
}
async fn handle_response<T: DeserializeOwned>(&self, response: reqwest::Response) -> Result<T> {
let status = response.status();
// Handle empty response (204 No Content, etc.)
if status == StatusCode::NO_CONTENT || status == StatusCode::ACCEPTED {
return serde_json::from_value(Value::Null)
.map_err(|e| Error::Parse(format!("Failed to parse empty response: {}", e)));
}
let json: Value = response
.json()
.await
.map_err(|e| Error::Network(format!("Failed to parse JSON response: {}", e)))?;
// Handle HTTP errors
if !status.is_success() {
let error_msg = json
.get("error")
.and_then(|e| e.get("message"))
.and_then(|m| m.as_str())
.map(|s| s.to_string())
.or_else(|| {
json.get("detail")
.and_then(|d| d.as_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| format!("HTTP error {}", status));
return Err(Error::Api(error_msg));
}
// Handle API errors (status == success but body has error)
if let Some(error) = json.get("error") {
if !error.is_null() {
let code = error
.get("code")
.and_then(|c| c.as_str())
.unwrap_or("UNKNOWN");
let message = error
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("Unknown error");
return Err(Error::Api(format!("[{}] {}", code, message)));
}
}
// Extract result from wrapped response or use the whole response
let result = if let Some(result) = json.get("result") {
result.clone()
} else {
json
};
serde_json::from_value(result)
.map_err(|e| Error::Parse(format!("Failed to deserialize response: {}", e)))
}
// ============ Content Methods ============
pub async fn read(&self, uri: &str) -> Result<String> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/content/read", ¶ms).await
}
pub async fn abstract_content(&self, uri: &str) -> Result<String> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/content/abstract", ¶ms).await
}
pub async fn overview(&self, uri: &str) -> Result<String> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/content/overview", ¶ms).await
}
pub async fn write(
&self,
uri: &str,
content: &str,
mode: &str,
wait: bool,
timeout: Option<f64>,
) -> Result<serde_json::Value> {
let body = Self::build_write_body(uri, content, mode, wait, timeout);
self.post("/api/v1/content/write", &body).await
}
fn build_write_body(
uri: &str,
content: &str,
mode: &str,
wait: bool,
timeout: Option<f64>,
) -> Value {
serde_json::json!({
"uri": uri,
"content": content,
"mode": mode,
"wait": wait,
"timeout": timeout,
})
}
pub async fn reindex(
&self,
uri: &str,
regenerate: bool,
wait: bool,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"uri": uri,
"regenerate": regenerate,
"wait": wait,
});
self.post("/api/v1/content/reindex", &body).await
}
/// Download file as raw bytes
pub async fn get_bytes(&self, uri: &str) -> Result<Vec<u8>> {
let url = format!("{}/api/v1/content/download", self.base_url);
let params = vec![("uri".to_string(), uri.to_string())];
let response = self
.http
.get(&url)
.headers(self.build_headers())
.query(¶ms)
.send()
.await
.map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
let status = response.status();
if !status.is_success() {
// Try to parse error message as JSON
let json_result: Result<serde_json::Value> = response
.json()
.await
.map_err(|e| Error::Network(format!("Failed to parse error response: {}", e)));
let error_msg = match json_result {
Ok(json) => json
.get("error")
.and_then(|e| e.get("message"))
.and_then(|m| m.as_str())
.map(|s| s.to_string())
.or_else(|| {
json.get("detail")
.and_then(|d| d.as_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| format!("HTTP error {}", status)),
Err(_) => format!("HTTP error {}", status),
};
return Err(Error::Api(error_msg));
}
response
.bytes()
.await
.map(|b| b.to_vec())
.map_err(|e| Error::Network(format!("Failed to read response bytes: {}", e)))
}
// ============ Filesystem Methods ============
pub async fn ls(
&self,
uri: &str,
simple: bool,
recursive: bool,
output: &str,
abs_limit: i32,
show_all_hidden: bool,
node_limit: i32,
) -> Result<serde_json::Value> {
let params = vec![
("uri".to_string(), uri.to_string()),
("simple".to_string(), simple.to_string()),
("recursive".to_string(), recursive.to_string()),
("output".to_string(), output.to_string()),
("abs_limit".to_string(), abs_limit.to_string()),
("show_all_hidden".to_string(), show_all_hidden.to_string()),
("node_limit".to_string(), node_limit.to_string()),
];
self.get("/api/v1/fs/ls", ¶ms).await
}
pub async fn tree(
&self,
uri: &str,
output: &str,
abs_limit: i32,
show_all_hidden: bool,
node_limit: i32,
level_limit: i32,
) -> Result<serde_json::Value> {
let params = vec![
("uri".to_string(), uri.to_string()),
("output".to_string(), output.to_string()),
("abs_limit".to_string(), abs_limit.to_string()),
("show_all_hidden".to_string(), show_all_hidden.to_string()),
("node_limit".to_string(), node_limit.to_string()),
("level_limit".to_string(), level_limit.to_string()),
];
self.get("/api/v1/fs/tree", ¶ms).await
}
pub async fn mkdir(&self, uri: &str) -> Result<()> {
let body = serde_json::json!({ "uri": uri });
let _: serde_json::Value = self.post("/api/v1/fs/mkdir", &body).await?;
Ok(())
}
pub async fn rm(&self, uri: &str, recursive: bool) -> Result<()> {
let params = vec![
("uri".to_string(), uri.to_string()),
("recursive".to_string(), recursive.to_string()),
];
let _: serde_json::Value = self.delete("/api/v1/fs", ¶ms).await?;
Ok(())
}
pub async fn mv(&self, from_uri: &str, to_uri: &str) -> Result<()> {
let body = serde_json::json!({
"from_uri": from_uri,
"to_uri": to_uri,
});
let _: serde_json::Value = self.post("/api/v1/fs/mv", &body).await?;
Ok(())
}
pub async fn stat(&self, uri: &str) -> Result<serde_json::Value> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/fs/stat", ¶ms).await
}
// ============ Search Methods ============
fn build_tags_filter(tags: &str) -> Result<Value> {
let mut tag_list: Vec<&str> = tags
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
let mut seen = HashSet::new();
tag_list.retain(|s| seen.insert(*s));
if tag_list.is_empty() {
return Err(Error::Client(
"'tags' must contain at least one non-empty tag".to_string(),
));
}
let conds: Vec<Value> = tag_list
.into_iter()
.map(|s| {
serde_json::json!({
"op": "contains",
"field": "tags",
"substring": s
})
})
.collect();
Ok(if conds.len() == 1 {
conds[0].clone()
} else {
serde_json::json!({
"op": "and",
"conds": conds
})
})
}
pub async fn find(
&self,
query: String,
uri: String,
node_limit: i32,
threshold: Option<f64>,
tags: Option<String>,
) -> Result<serde_json::Value> {
let mut body_map = serde_json::Map::new();
body_map.insert("query".to_string(), serde_json::json!(query));
body_map.insert("target_uri".to_string(), serde_json::json!(uri));
body_map.insert("limit".to_string(), serde_json::json!(node_limit));
if let Some(t) = threshold {
body_map.insert("score_threshold".to_string(), serde_json::json!(t));
}
if let Some(t) = tags {
let filter = Self::build_tags_filter(&t)?;
body_map.insert("filter".to_string(), filter);
}
self.post("/api/v1/search/find", &serde_json::Value::Object(body_map)).await
}
pub async fn search(
&self,
query: String,
uri: String,
session_id: Option<String>,
node_limit: i32,
threshold: Option<f64>,
tags: Option<String>,
) -> Result<serde_json::Value> {
let mut body_map = serde_json::Map::new();
body_map.insert("query".to_string(), serde_json::json!(query));
body_map.insert("target_uri".to_string(), serde_json::json!(uri));
if let Some(s) = session_id {
body_map.insert("session_id".to_string(), serde_json::json!(s));
}
body_map.insert("limit".to_string(), serde_json::json!(node_limit));
if let Some(t) = threshold {
body_map.insert("score_threshold".to_string(), serde_json::json!(t));
}
if let Some(t) = tags {
let filter = Self::build_tags_filter(&t)?;
body_map.insert("filter".to_string(), filter);
}
self.post("/api/v1/search/search", &serde_json::Value::Object(body_map)).await
}
pub async fn grep(
&self,
uri: &str,
exclude_uri: Option<String>,
pattern: &str,
ignore_case: bool,
node_limit: i32,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"uri": uri,
"exclude_uri": exclude_uri,
"pattern": pattern,
"case_insensitive": ignore_case,
"node_limit": node_limit,
});
self.post("/api/v1/search/grep", &body).await
}
pub async fn glob(
&self,
pattern: &str,
uri: &str,
node_limit: i32,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"pattern": pattern,
"uri": uri,
"node_limit": node_limit,
});
self.post("/api/v1/search/glob", &body).await
}
// ============ Resource Methods ============
pub async fn add_resource(
&self,
path: &str,
to: Option<String>,
parent: Option<String>,
reason: &str,
instruction: &str,
wait: bool,
timeout: Option<f64>,
strict: bool,
ignore_dirs: Option<String>,
include: Option<String>,
exclude: Option<String>,
directly_upload_media: bool,
watch_interval: f64,
tags: Option<String>,
) -> Result<serde_json::Value> {
let path_obj = Path::new(path);
if path_obj.exists() {
if path_obj.is_dir() {
let source_name = path_obj
.file_name()
.and_then(|n| n.to_str())
.map(|s| s.to_string());
let zip_file = self.zip_directory(path_obj)?;
let temp_file_id = self.upload_temp_file(zip_file.path()).await?;
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"source_name": source_name,
"to": to,
"parent": parent,
"reason": reason,
"instruction": instruction,
"wait": wait,
"timeout": timeout,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
"exclude": exclude,
"directly_upload_media": directly_upload_media,
"watch_interval": watch_interval,
"tags": tags,
});
self.post("/api/v1/resources", &body).await
} else if path_obj.is_file() {
let temp_file_id = self.upload_temp_file(path_obj).await?;
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"to": to,
"parent": parent,
"reason": reason,
"instruction": instruction,
"wait": wait,
"timeout": timeout,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
"exclude": exclude,
"directly_upload_media": directly_upload_media,
"watch_interval": watch_interval,
"tags": tags,
});
self.post("/api/v1/resources", &body).await
} else {
let body = serde_json::json!({
"path": path,
"to": to,
"parent": parent,
"reason": reason,
"instruction": instruction,
"wait": wait,
"timeout": timeout,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
"exclude": exclude,
"directly_upload_media": directly_upload_media,
"watch_interval": watch_interval,
});
self.post("/api/v1/resources", &body).await
}
} else {
let body = serde_json::json!({
"path": path,
"to": to,
"parent": parent,
"reason": reason,
"instruction": instruction,
"wait": wait,
"timeout": timeout,
"strict": strict,
"ignore_dirs": ignore_dirs,
"include": include,
"exclude": exclude,
"directly_upload_media": directly_upload_media,
"watch_interval": watch_interval,
});
self.post("/api/v1/resources", &body).await
}
}
pub async fn add_skill(
&self,
data: &str,
wait: bool,
timeout: Option<f64>,
) -> Result<serde_json::Value> {
let path_obj = Path::new(data);
if path_obj.exists() {
if path_obj.is_dir() {
let zip_file = self.zip_directory(path_obj)?;
let temp_file_id = self.upload_temp_file(zip_file.path()).await?;
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"wait": wait,
"timeout": timeout,
});
self.post("/api/v1/skills", &body).await
} else if path_obj.is_file() {
let temp_file_id = self.upload_temp_file(path_obj).await?;
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"wait": wait,
"timeout": timeout,
});
self.post("/api/v1/skills", &body).await
} else {
let body = serde_json::json!({
"data": data,
"wait": wait,
"timeout": timeout,
});
self.post("/api/v1/skills", &body).await
}
} else {
let body = serde_json::json!({
"data": data,
"wait": wait,
"timeout": timeout,
});
self.post("/api/v1/skills", &body).await
}
}
// ============ Relation Methods ============
pub async fn relations(&self, uri: &str) -> Result<serde_json::Value> {
let params = vec![("uri".to_string(), uri.to_string())];
self.get("/api/v1/relations", ¶ms).await
}
pub async fn link(
&self,
from_uri: &str,
to_uris: &[String],
reason: &str,
) -> Result<serde_json::Value> {
let body = serde_json::json!({
"from_uri": from_uri,
"to_uris": to_uris,
"reason": reason,
});
self.post("/api/v1/relations/link", &body).await
}
pub async fn unlink(&self, from_uri: &str, to_uri: &str) -> Result<serde_json::Value> {
let body = serde_json::json!({
"from_uri": from_uri,
"to_uri": to_uri,
});
self.delete_with_body("/api/v1/relations/link", &body).await
}
// ============ Pack Methods ============
pub async fn export_ovpack(&self, uri: &str, to: &str) -> Result<serde_json::Value> {
let body = serde_json::json!({
"uri": uri,
"to": to,
});
self.post("/api/v1/pack/export", &body).await
}
pub async fn import_ovpack(
&self,
file_path: &str,
parent: &str,
force: bool,
vectorize: bool,
) -> Result<serde_json::Value> {
let file_path_obj = Path::new(file_path);
if !file_path_obj.exists() {
return Err(Error::Client(format!(
"Local ovpack file not found: {}",
file_path
)));
}
if !file_path_obj.is_file() {
return Err(Error::Client(format!(
"Path is not a file: {}",
file_path
)));
}
let temp_file_id = self.upload_temp_file(file_path_obj).await?;
let body = serde_json::json!({
"temp_file_id": temp_file_id,
"parent": parent,
"force": force,
"vectorize": vectorize,
});
self.post("/api/v1/pack/import", &body).await
}
// ============ Admin Methods ============
pub async fn admin_create_account(
&self,
account_id: &str,
admin_user_id: &str,
) -> Result<Value> {
let body = serde_json::json!({
"account_id": account_id,
"admin_user_id": admin_user_id,
});
self.post("/api/v1/admin/accounts", &body).await
}
pub async fn admin_list_accounts(&self) -> Result<Value> {
self.get("/api/v1/admin/accounts", &[]).await
}
pub async fn admin_delete_account(&self, account_id: &str) -> Result<Value> {
let path = format!("/api/v1/admin/accounts/{}", account_id);
self.delete(&path, &[]).await
}
pub async fn admin_register_user(
&self,
account_id: &str,
user_id: &str,
role: &str,
) -> Result<Value> {
let path = format!("/api/v1/admin/accounts/{}/users", account_id);
let body = serde_json::json!({
"user_id": user_id,
"role": role,
});
self.post(&path, &body).await
}
pub async fn admin_list_users(&self, account_id: &str) -> Result<Value> {
let path = format!("/api/v1/admin/accounts/{}/users", account_id);
self.get(&path, &[]).await
}
pub async fn admin_remove_user(&self, account_id: &str, user_id: &str) -> Result<Value> {
let path = format!("/api/v1/admin/accounts/{}/users/{}", account_id, user_id);
self.delete(&path, &[]).await
}
pub async fn admin_set_role(
&self,
account_id: &str,
user_id: &str,
role: &str,
) -> Result<Value> {
let path = format!(
"/api/v1/admin/accounts/{}/users/{}/role",
account_id, user_id
);
let body = serde_json::json!({ "role": role });
self.put(&path, &body).await
}
pub async fn admin_regenerate_key(&self, account_id: &str, user_id: &str) -> Result<Value> {
let path = format!(
"/api/v1/admin/accounts/{}/users/{}/key",
account_id, user_id
);
self.post(&path, &serde_json::json!({})).await
}
// ============ Debug Vector Methods ============
/// Get paginated vector records
pub async fn debug_vector_scroll(
&self,
limit: Option<u32>,
cursor: Option<String>,
uri_prefix: Option<String>,
) -> Result<(Vec<serde_json::Value>, Option<String>)> {
let mut params = Vec::new();
if let Some(l) = limit {
params.push(("limit".to_string(), l.to_string()));
}
if let Some(c) = cursor {
params.push(("cursor".to_string(), c));
}
if let Some(u) = uri_prefix {
params.push(("uri".to_string(), u));
}
let result: serde_json::Value = self.get("/api/v1/debug/vector/scroll", ¶ms).await?;
let records = result["records"]
.as_array()
.ok_or_else(|| Error::Parse("Missing records in response".to_string()))?
.clone();
let next_cursor = result["next_cursor"].as_str().map(|s| s.to_string());
Ok((records, next_cursor))
}
/// Get count of vector records
pub async fn debug_vector_count(
&self,
filter: Option<&serde_json::Value>,
uri_prefix: Option<String>,
) -> Result<u64> {
let mut params = Vec::new();
if let Some(f) = filter {
params.push(("filter".to_string(), serde_json::to_string(f)?));
}
if let Some(u) = uri_prefix {
params.push(("uri".to_string(), u));
}
let result: serde_json::Value = self.get("/api/v1/debug/vector/count", ¶ms).await?;
let count = result["count"]
.as_u64()
.ok_or_else(|| Error::Parse("Missing count in response".to_string()))?;
Ok(count)
}
}
#[cfg(test)]
mod tests {
use super::HttpClient;
use serde_json::json;
#[test]
fn build_headers_includes_tenant_identity_headers() {
let client = HttpClient::new(
"http://localhost:1933",
Some("test-key".to_string()),
Some("assistant-1".to_string()),
Some("acme".to_string()),
Some("alice".to_string()),
5.0,
);
let headers = client.build_headers();
assert_eq!(
headers
.get("X-API-Key")
.and_then(|value| value.to_str().ok()),
Some("test-key")
);
assert_eq!(
headers
.get("X-OpenViking-Agent")
.and_then(|value| value.to_str().ok()),
Some("assistant-1")
);
assert_eq!(
headers
.get("X-OpenViking-Account")
.and_then(|value| value.to_str().ok()),
Some("acme")
);
assert_eq!(
headers
.get("X-OpenViking-User")
.and_then(|value| value.to_str().ok()),
Some("alice")
);
}
#[test]
fn build_write_body_omits_removed_semantic_flags() {
let body = HttpClient::build_write_body(
"viking://resources/demo.md",
"updated",
"replace",
true,
Some(3.0),
);