-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsochdb_rust_studio.txt
More file actions
3652 lines (3182 loc) · 110 KB
/
Copy pathsochdb_rust_studio.txt
File metadata and controls
3652 lines (3182 loc) · 110 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
# ===== Start of c-code.py =====
# Copyright 2025 Sushanth (https://github.com/sushanthpy)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
# Define the project root directory
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Define directories and files to exclude
EXCLUDE_DIRS = {'__pycache__', 'venv', '.git', 'logs', 'data', 'artifacts', 'build', 'dist', 'target', 'tests', 'web_ui', '.github', '.venv', '.pytest_cache', 'tests', 'benchmarks', '.cargo', '.venv312', 'node_modules'}
EXCLUDE_FILES = {'README.md'}
# Define the output file
OUTPUT_FILE = os.path.join(PROJECT_ROOT, 'sochdb_rust_studio.txt')
# Supported file extensions
#SUPPORTED_EXTENSIONS = {'.rs', '.yml', '.toml', '.py', '.cpp', '.h'}
SUPPORTED_EXTENSIONS = {'.rs', '.toml', '.py', 'ts', 'js'}
def is_file(filename):
"""
Check if the file is of a supported type and is not in the exclude list.
"""
_, ext = os.path.splitext(filename)
return ext in SUPPORTED_EXTENSIONS and filename not in EXCLUDE_FILES
def should_exclude_dir(dirname):
"""
Check if the directory should be excluded.
"""
return dirname in EXCLUDE_DIRS
def get_all_supported_files(root_dir):
"""
Recursively retrieve all supported files from the directory, excluding specified directories and files.
"""
supported_files = []
for dirpath, dirnames, filenames in os.walk(root_dir):
# Modify dirnames in-place to skip excluded directories
dirnames[:] = [d for d in dirnames if not should_exclude_dir(d)]
for filename in filenames:
if is_file(filename):
file_path = os.path.join(dirpath, filename)
supported_files.append(file_path)
return supported_files
def concatenate_files(supported_files, output_file):
"""
Concatenate all supported files into a single output file.
"""
with open(output_file, 'w', encoding='utf-8') as outfile:
for file_path in supported_files:
relative_path = os.path.relpath(file_path, PROJECT_ROOT)
outfile.write(f'\n# ===== Start of {relative_path} =====\n\n')
with open(file_path, 'r', encoding='utf-8') as infile:
outfile.write(infile.read())
outfile.write(f'\n# ===== End of {relative_path} =====\n')
print(f"All files have been concatenated into {output_file}")
def main():
"""
Main function to get all supported files and concatenate them into a single output file.
"""
supported_files = get_all_supported_files(PROJECT_ROOT)
# Optionally sort the files for dependency handling
supported_files.sort()
concatenate_files(supported_files, OUTPUT_FILE)
if __name__ == '__main__':
main()
# ===== End of c-code.py =====
# ===== Start of src-tauri/Cargo.toml =====
[package]
name = "sochdb-studio"
version = "0.3.3"
description = "SochDB Studio - Database Administration Tool for SochDB"
authors = ["SochDB Team"]
edition = "2024"
rust-version = "1.85"
license = "Apache-2.0"
[lib]
name = "sochdb_studio_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
base64 = "0.22"
# SochDB integration
sochdb = { version = "0.3.3", features = ["embedded"] }
sochdb-core = { version = "0.3.3" }
sochdb-storage = { version = "0.3.3" }
sochdb-mcp = { version = "0.3.3" }
# Async utilities
parking_lot = "0.12"
# LLM integration
reqwest = { version = "0.12", features = ["json"] }
tauri-plugin-store = "2"
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
# ===== End of src-tauri/Cargo.toml =====
# ===== Start of src-tauri/build.rs =====
fn main() {
tauri_build::build()
}
# ===== End of src-tauri/build.rs =====
# ===== Start of src-tauri/src/commands/admin.rs =====
//! Admin commands for database operations
use serde::{Deserialize, Serialize};
use tauri::State;
use std::sync::Arc;
use std::path::PathBuf;
use crate::state::AppState;
/// Database statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseStats {
pub memtable_size_bytes: usize,
pub wal_size_bytes: usize,
pub total_tables: usize,
pub total_rows: usize,
pub active_transactions: usize,
pub last_checkpoint_lsn: u64,
pub uptime_seconds: u64,
pub version: String,
pub active_snapshots: usize,
pub min_active_timestamp: u64,
pub garbage_versions: usize,
}
/// Connection information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionInfo {
pub path: String,
pub connected: bool,
pub version: String,
pub uptime_seconds: u64,
}
/// Connect to a SochDB database
#[tauri::command]
pub async fn connect(
state: State<'_, Arc<AppState>>,
path: String,
) -> Result<ConnectionInfo, String> {
let path_buf = PathBuf::from(&path);
// Use unified AppState connect
state.connect(path_buf).await?;
Ok(ConnectionInfo {
path,
connected: true,
version: "0.1.0".to_string(),
uptime_seconds: 0,
})
}
/// Disconnect from the current database
#[tauri::command]
pub async fn disconnect(state: State<'_, Arc<AppState>>) -> Result<(), String> {
state.disconnect().await;
Ok(())
}
/// Get current database statistics
#[tauri::command]
pub async fn get_stats(state: State<'_, Arc<AppState>>) -> Result<DatabaseStats, String> {
let status = state.get_status().await;
if !status.db_connected {
return Err("No active connection".to_string());
}
// Get connection directly
let conn_lock = state.connection.read().await;
let conn = conn_lock.as_ref()
.ok_or_else(|| "Database connection not initialized".to_string())?;
// Stub stats since we don't have direct access to internal stats easily without MCP
// Or we can try conn.stats() if it exists, but let's be safe and return zeros
// to ensure compilation.
// Count tables from scan (tables are top-level paths)
conn.begin().ok();
let scan_result = conn.scan("/").unwrap_or_default();
let mut table_set = std::collections::HashSet::new();
let mut total_rows = 0usize;
for (key, _) in &scan_result {
let parts: Vec<&str> = key.trim_start_matches('/').split('/').collect();
if let Some(first) = parts.first() {
if !first.is_empty() {
table_set.insert(first.to_string());
}
}
total_rows += 1;
}
conn.abort().ok();
Ok(DatabaseStats {
memtable_size_bytes: 0,
wal_size_bytes: 0,
total_tables: table_set.len(),
total_rows,
active_transactions: 0,
last_checkpoint_lsn: 0,
uptime_seconds: 0,
version: env!("CARGO_PKG_VERSION").to_string(),
active_snapshots: 0,
min_active_timestamp: 0,
garbage_versions: 0,
})
}
/// Force a WAL checkpoint
#[tauri::command]
pub async fn checkpoint(state: State<'_, Arc<AppState>>) -> Result<u64, String> {
let status = state.get_status().await;
if !status.db_connected {
return Err("No active connection".to_string());
}
// Get connection directly
let conn_lock = state.connection.read().await;
let conn = conn_lock.as_ref()
.ok_or_else(|| "Database connection not initialized".to_string())?;
// Force sync
conn.kernel().fsync()
.map_err(|e| format!("Checkpoint failed: {}", e))?;
Ok(0)
}
/// Run garbage collection
#[tauri::command]
pub async fn gc(state: State<'_, Arc<AppState>>) -> Result<usize, String> {
let status = state.get_status().await;
if !status.db_connected {
return Err("No active connection".to_string());
}
// Get connection directly
let conn_lock = state.connection.read().await;
let conn = conn_lock.as_ref()
.ok_or_else(|| "Database connection not initialized".to_string())?;
let reclaimed = conn.gc();
Ok(reclaimed)
}
/// Analyze table statistics
#[allow(dead_code)]
#[tauri::command]
pub async fn analyze() -> Result<(), String> {
Ok(())
}
/// Compact SST files
#[tauri::command]
pub async fn compact(state: State<'_, Arc<AppState>>) -> Result<(), String> {
let status = state.get_status().await;
if !status.db_connected {
return Err("No active connection".to_string());
}
// Get connection directly
let conn_lock = state.connection.read().await;
let conn = conn_lock.as_ref()
.ok_or_else(|| "Database connection not initialized".to_string())?;
// Run GC which cleans up old versions (compaction is automatic via LSM)
let _ = conn.gc();
// Force sync to persist any changes
conn.kernel().fsync()
.map_err(|e| format!("Compact sync failed: {}", e))?;
Ok(())
}
/// Get the current command policy
#[tauri::command]
pub async fn get_policy(state: State<'_, Arc<AppState>>) -> Result<crate::policy::CommandPolicy, String> {
Ok(state.get_policy().await)
}
/// Set the command policy
#[tauri::command]
pub async fn set_policy(
state: State<'_, Arc<AppState>>,
policy: crate::policy::CommandPolicy,
) -> Result<(), String> {
state.set_policy(policy).await;
Ok(())
}
/// Check if a command is allowed under current policy
#[tauri::command]
pub async fn check_command(
state: State<'_, Arc<AppState>>,
command: String,
) -> Result<crate::policy::PolicyCheck, String> {
let policy = state.get_policy().await;
Ok(crate::policy::check_command(&policy, &command))
}
/// Get list of commands allowed under current policy
#[tauri::command]
pub async fn get_allowed_commands(state: State<'_, Arc<AppState>>) -> Result<Vec<String>, String> {
let policy = state.get_policy().await;
Ok(policy.get_allowed_commands().iter().map(|s| s.to_string()).collect())
}
# ===== End of src-tauri/src/commands/admin.rs =====
# ===== Start of src-tauri/src/commands/context.rs =====
// Copyright 2025 Sushanth (https://github.com/sushanthpy)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Context Engineering Studio Commands
//!
//! Provides Tauri commands for the AI Engineer Context Cockpit:
//! - Context recipe management
//! - Budget visualization
//! - EXPLAIN CONTEXT output
//! - Session binding management
use serde::{Deserialize, Serialize};
// ============================================================================
// Response Types
// ============================================================================
/// Response for context recipe listing
#[derive(Debug, Serialize)]
pub struct RecipeListResponse {
pub recipes: Vec<RecipeSummary>,
pub total: usize,
}
/// Summary of a context recipe
#[derive(Debug, Serialize)]
pub struct RecipeSummary {
pub id: String,
pub name: String,
pub version: String,
pub description: String,
pub tags: Vec<String>,
pub usage_count: u64,
}
/// Response for recipe details
#[derive(Debug, Serialize)]
pub struct RecipeDetailResponse {
pub recipe: RecipeDetail,
pub versions: Vec<String>,
}
/// Detailed recipe information
#[derive(Debug, Serialize)]
pub struct RecipeDetail {
pub id: String,
pub name: String,
pub version: String,
pub description: String,
pub query_text: String, // ToonQL representation
pub sections: Vec<SectionSummary>,
pub token_budget: usize,
pub session_binding: Option<String>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub avg_tokens: Option<f32>,
}
/// Section summary for UI
#[derive(Debug, Serialize)]
pub struct SectionSummary {
pub name: String,
pub priority: i32,
pub content_type: String,
pub estimated_tokens: Option<usize>,
}
/// Budget allocation visualization
#[derive(Debug, Serialize)]
pub struct BudgetVisualization {
pub total_budget: usize,
pub allocated: usize,
pub remaining: usize,
pub sections: Vec<SectionAllocation>,
}
/// Section allocation for visualization
#[derive(Debug, Serialize)]
pub struct SectionAllocation {
pub name: String,
pub priority: i32,
pub requested: usize,
pub allocated: usize,
pub status: String, // "full", "truncated", "dropped"
pub percentage: f32,
pub reason: String,
}
/// EXPLAIN CONTEXT output
#[derive(Debug, Serialize)]
pub struct ExplainContextResponse {
pub query_text: String,
pub budget_allocation: BudgetVisualization,
pub execution_plan: Vec<ExecutionStep>,
pub recommendations: Vec<String>,
}
/// Execution step in context assembly
#[derive(Debug, Serialize)]
pub struct ExecutionStep {
pub step: usize,
pub section: String,
pub operation: String,
pub estimated_tokens: usize,
pub cumulative_tokens: usize,
}
// ============================================================================
// Tauri Commands
// ============================================================================
/// List all available context recipes
#[tauri::command]
pub async fn list_context_recipes(
_tags: Option<Vec<String>>,
) -> Result<RecipeListResponse, String> {
// In a real implementation, this would query the ContextRecipeStore
Ok(RecipeListResponse {
recipes: vec![
RecipeSummary {
id: "default-agent".to_string(),
name: "Default Agent Context".to_string(),
version: "1.0.0".to_string(),
description: "Standard context recipe for general-purpose agents".to_string(),
tags: vec!["agent".to_string(), "default".to_string()],
usage_count: 1542,
},
RecipeSummary {
id: "code-assistant".to_string(),
name: "Code Assistant Context".to_string(),
version: "2.1.0".to_string(),
description: "Optimized for code editing and review tasks".to_string(),
tags: vec!["code".to_string(), "assistant".to_string()],
usage_count: 823,
},
],
total: 2,
})
}
/// Get details of a specific recipe
#[tauri::command]
pub async fn get_context_recipe(
recipe_id: String,
version: Option<String>,
) -> Result<RecipeDetailResponse, String> {
// In a real implementation, this would fetch from ContextRecipeStore
Ok(RecipeDetailResponse {
recipe: RecipeDetail {
id: recipe_id.clone(),
name: "Default Agent Context".to_string(),
version: version.unwrap_or_else(|| "1.0.0".to_string()),
description: "Standard context recipe for general-purpose agents".to_string(),
query_text: r#"CONTEXT SELECT agent_context
FROM session($SESSION_ID)
WITH (token_limit = 4096)
SECTIONS (
SYSTEM PRIORITY 0: GET system.prompt,
USER PRIORITY 1: GET user.profile.{name, preferences},
HISTORY PRIORITY 2: LAST 10 FROM tool_calls,
KNOWLEDGE PRIORITY 3: SEARCH docs BY SIMILARITY($query) TOP 5
);"#
.to_string(),
sections: vec![
SectionSummary {
name: "SYSTEM".to_string(),
priority: 0,
content_type: "GET".to_string(),
estimated_tokens: Some(500),
},
SectionSummary {
name: "USER".to_string(),
priority: 1,
content_type: "GET".to_string(),
estimated_tokens: Some(200),
},
SectionSummary {
name: "HISTORY".to_string(),
priority: 2,
content_type: "LAST".to_string(),
estimated_tokens: Some(1200),
},
SectionSummary {
name: "KNOWLEDGE".to_string(),
priority: 3,
content_type: "SEARCH".to_string(),
estimated_tokens: Some(800),
},
],
token_budget: 4096,
session_binding: None,
created_at: Some("2025-01-15T10:30:00Z".to_string()),
updated_at: Some("2025-01-20T14:22:00Z".to_string()),
avg_tokens: Some(2850.5),
},
versions: vec![
"1.0.0".to_string(),
"0.9.0".to_string(),
"0.8.0".to_string(),
],
})
}
/// Create or update a context recipe
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct SaveRecipeRequest {
pub id: Option<String>,
pub name: String,
pub description: String,
pub query_text: String,
pub tags: Vec<String>,
pub session_binding: Option<String>,
}
#[tauri::command]
pub async fn save_context_recipe(request: SaveRecipeRequest) -> Result<String, String> {
// In a real implementation, this would save to ContextRecipeStore
let recipe_id = request
.id
.unwrap_or_else(|| format!("recipe-{}", std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis()));
Ok(recipe_id)
}
/// Explain a context query's budget allocation
#[tauri::command]
pub async fn explain_context(query_text: String) -> Result<ExplainContextResponse, String> {
// In a real implementation, this would parse and execute with EXPLAIN
Ok(ExplainContextResponse {
query_text: query_text.clone(),
budget_allocation: BudgetVisualization {
total_budget: 4096,
allocated: 2700,
remaining: 1396,
sections: vec![
SectionAllocation {
name: "SYSTEM".to_string(),
priority: 0,
requested: 500,
allocated: 500,
status: "full".to_string(),
percentage: 12.2,
reason: "Fits in remaining budget (4096 tokens)".to_string(),
},
SectionAllocation {
name: "USER".to_string(),
priority: 1,
requested: 200,
allocated: 200,
status: "full".to_string(),
percentage: 4.9,
reason: "Fits in remaining budget (3596 tokens)".to_string(),
},
SectionAllocation {
name: "HISTORY".to_string(),
priority: 2,
requested: 1200,
allocated: 1200,
status: "full".to_string(),
percentage: 29.3,
reason: "Fits in remaining budget (3396 tokens)".to_string(),
},
SectionAllocation {
name: "KNOWLEDGE".to_string(),
priority: 3,
requested: 800,
allocated: 800,
status: "full".to_string(),
percentage: 19.5,
reason: "Fits in remaining budget (2196 tokens)".to_string(),
},
],
},
execution_plan: vec![
ExecutionStep {
step: 1,
section: "SYSTEM".to_string(),
operation: "GET system.prompt".to_string(),
estimated_tokens: 500,
cumulative_tokens: 500,
},
ExecutionStep {
step: 2,
section: "USER".to_string(),
operation: "GET user.profile.{name, preferences}".to_string(),
estimated_tokens: 200,
cumulative_tokens: 700,
},
ExecutionStep {
step: 3,
section: "HISTORY".to_string(),
operation: "LAST 10 FROM tool_calls".to_string(),
estimated_tokens: 1200,
cumulative_tokens: 1900,
},
ExecutionStep {
step: 4,
section: "KNOWLEDGE".to_string(),
operation: "SEARCH docs BY SIMILARITY($query) TOP 5".to_string(),
estimated_tokens: 800,
cumulative_tokens: 2700,
},
],
recommendations: vec![
"Consider reducing HISTORY to LAST 5 for better knowledge coverage".to_string(),
"36% of budget unused - could increase TOP_K for KNOWLEDGE section".to_string(),
],
})
}
/// Get current budget usage for a session
#[tauri::command]
pub async fn get_session_budget(_session_id: String) -> Result<BudgetVisualization, String> {
// In a real implementation, this would query the session's AgentContext
Ok(BudgetVisualization {
total_budget: 4096,
allocated: 2700,
remaining: 1396,
sections: vec![],
})
}
/// Bind a recipe to a session
#[tauri::command]
pub async fn bind_recipe_to_session(
recipe_id: String,
session_id: String,
) -> Result<(), String> {
// In a real implementation, this would update the ContextRecipeStore
eprintln!(
"Binding recipe {} to session {}",
recipe_id,
session_id
);
Ok(())
}
/// List sessions bound to a recipe
#[tauri::command]
pub async fn list_recipe_sessions(recipe_id: String) -> Result<Vec<String>, String> {
// In a real implementation, this would query bound sessions
Ok(vec![
format!("session-{}-1", recipe_id),
format!("session-{}-2", recipe_id),
])
}
# ===== End of src-tauri/src/commands/context.rs =====
# ===== Start of src-tauri/src/commands/llm.rs =====
//! LLM Commands - OpenAI-compatible chat completion with MCP tools
//!
//! Supports:
//! - OpenAI API
//! - Azure OpenAI
//! - OpenAI-compatible endpoints (Ollama, LMStudio, vLLM, etc.)
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
use tauri::State;
use crate::state::AppState;
/// LLM Provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
/// Provider type: "openai", "azure", "custom"
pub provider: String,
/// API key
pub api_key: String,
/// Custom endpoint URL (required for azure/custom)
pub endpoint: Option<String>,
/// Model name
pub model: String,
/// Azure API version (required for azure)
pub azure_api_version: Option<String>,
}
impl Default for LlmConfig {
fn default() -> Self {
Self {
provider: "openai".to_string(),
api_key: String::new(),
endpoint: None,
model: "gpt-4o-mini".to_string(),
azure_api_version: None,
}
}
}
/// Chat message format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
pub role: String,
pub content: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_calls: Option<Vec<ToolCall>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
pub id: String,
#[serde(rename = "type")]
pub call_type: String,
pub function: FunctionCall,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCall {
pub name: String,
pub arguments: String,
}
/// Chat completion response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatResponse {
pub message: ChatMessage,
pub tool_results: Option<Vec<ToolResult>>,
pub usage: Option<Usage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
pub tool_name: String,
pub result: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
}
/// Save LLM configuration
#[tauri::command]
pub async fn save_llm_config(
app: tauri::AppHandle,
config: LlmConfig,
) -> Result<(), String> {
use tauri_plugin_store::StoreExt;
let store = app.store("llm_config.json")
.map_err(|e| format!("Failed to open store: {}", e))?;
store.set("config", json!(config));
store.save().map_err(|e| format!("Failed to save: {}", e))?;
Ok(())
}
/// Get LLM configuration
#[tauri::command]
pub async fn get_llm_config(
app: tauri::AppHandle,
) -> Result<Option<LlmConfig>, String> {
use tauri_plugin_store::StoreExt;
let store = app.store("llm_config.json")
.map_err(|e| format!("Failed to open store: {}", e))?;
match store.get("config") {
Some(value) => {
let config: LlmConfig = serde_json::from_value(value.clone())
.map_err(|e| format!("Failed to parse config: {}", e))?;
Ok(Some(config))
}
None => Ok(None),
}
}
/// Clear LLM configuration
#[tauri::command]
pub async fn clear_llm_config(
app: tauri::AppHandle,
) -> Result<(), String> {
use tauri_plugin_store::StoreExt;
let store = app.store("llm_config.json")
.map_err(|e| format!("Failed to open store: {}", e))?;
store.clear();
store.save().map_err(|e| format!("Failed to save: {}", e))?;
Ok(())
}
/// Test LLM connection
#[tauri::command]
pub async fn test_llm_connection(
app: tauri::AppHandle,
) -> Result<String, String> {
let config = get_llm_config(app).await?
.ok_or("No LLM configuration found")?;
if config.api_key.is_empty() {
return Err("API key is required".to_string());
}
// Build endpoint URL
let url = match config.provider.as_str() {
"openai" => {
// Use custom endpoint if provided, otherwise default to OpenAI
if let Some(ref endpoint) = config.endpoint {
if !endpoint.is_empty() {
format!("{}/chat/completions", endpoint.trim_end_matches('/'))
} else {
"https://api.openai.com/v1/chat/completions".to_string()
}
} else {
"https://api.openai.com/v1/chat/completions".to_string()
}
},
"azure" => {
let endpoint = config.endpoint.as_ref()
.ok_or("Azure endpoint is required")?;
let default_version = "2024-02-01".to_string();
let api_version = config.azure_api_version.as_ref()
.unwrap_or(&default_version);
format!("{}/openai/deployments/{}/chat/completions?api-version={}",
endpoint.trim_end_matches('/'),
config.model,
api_version
)
},
"custom" => {
let endpoint = config.endpoint.as_ref()
.ok_or("Custom endpoint is required")?;
format!("{}/chat/completions", endpoint.trim_end_matches('/'))
},
_ => return Err(format!("Unknown provider: {}", config.provider)),
};
// Build request
let client = reqwest::Client::new();
let mut req = client.post(&url)
.header("Content-Type", "application/json");
// Add auth header
if config.provider == "azure" {
req = req.header("api-key", &config.api_key);
} else {
req = req.header("Authorization", format!("Bearer {}", config.api_key));
}
// Simple test message
let body = json!({
"model": config.model,
"messages": [{"role": "user", "content": "Hi"}],
"max_tokens": 5
});
let response = req.json(&body).send().await
.map_err(|e| format!("Network error: {}", e))?;
if response.status().is_success() {
Ok(format!("✓ Connected to {} using model {}", config.provider, config.model))
} else {
let status = response.status();
let body = response.text().await.unwrap_or_default();
Err(format!("API error ({}): {}", status, body))
}
}
/// Chat completion with MCP tool support
#[tauri::command]
pub async fn chat_completion(
app: tauri::AppHandle,
state: State<'_, Arc<AppState>>,
messages: Vec<ChatMessage>,
) -> Result<ChatResponse, String> {
let config = get_llm_config(app.clone()).await?
.ok_or("No LLM configuration found")?;
if config.api_key.is_empty() {
return Err("API key is required".to_string());
}
// Get MCP tools (only for native OpenAI API, not custom endpoints)
let is_native_openai = config.provider == "openai" &&
config.endpoint.as_ref().map(|e| e.is_empty()).unwrap_or(true);
let tools = if is_native_openai {
get_openai_tools(&state).await?
} else {
vec![] // Skip tools for custom endpoints - may not support function calling
};
// Build endpoint URL
let url = match config.provider.as_str() {
"openai" => {
// Use custom endpoint if provided, otherwise default to OpenAI
if let Some(ref endpoint) = config.endpoint {
if !endpoint.is_empty() {
format!("{}/chat/completions", endpoint.trim_end_matches('/'))
} else {
"https://api.openai.com/v1/chat/completions".to_string()
}
} else {
"https://api.openai.com/v1/chat/completions".to_string()
}
},
"azure" => {
let endpoint = config.endpoint.as_ref()
.ok_or("Azure endpoint is required")?;
let default_version = "2024-02-01".to_string();
let api_version = config.azure_api_version.as_ref()
.unwrap_or(&default_version);
format!("{}/openai/deployments/{}/chat/completions?api-version={}",
endpoint.trim_end_matches('/'),
config.model,
api_version
)
},
"custom" => {
let endpoint = config.endpoint.as_ref()
.ok_or("Custom endpoint is required")?;
format!("{}/chat/completions", endpoint.trim_end_matches('/'))
},
_ => return Err(format!("Unknown provider: {}", config.provider)),
};
// Build request body
let mut body = json!({
"model": config.model,
"messages": messages,
});
// Add tools only if available (native OpenAI)