-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathmain.rs
More file actions
2320 lines (1997 loc) · 78.1 KB
/
main.rs
File metadata and controls
2320 lines (1997 loc) · 78.1 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
#!/usr/bin/env cargo
//! Terminator CLI
//!
//! A cross-platform Rust tool to manage the Terminator project, including version management,
//! releases, and development workflows.
//!
//! Usage from workspace root:
//! cargo run --bin terminator -- patch # Bump patch version
//! cargo run --bin terminator -- minor # Bump minor version
//! cargo run --bin terminator -- major # Bump major version
//! cargo run --bin terminator -- sync # Sync all versions
//! cargo run --bin terminator -- status # Show current status
//! cargo run --bin terminator -- tag # Tag and push current version
//! cargo run --bin terminator -- release # Full release: bump patch + tag + push
//! cargo run --bin terminator -- release minor # Full release: bump minor + tag + push
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::Value;
use std::env;
use std::fs;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, BufReader as AsyncBufReader};
use tokio::sync::Mutex;
mod commands;
mod mcp_client;
mod typescript_workflow;
mod workflow_result;
mod workflow_validator;
use workflow_result::WorkflowResult;
use workflow_validator::WorkflowOutputValidator;
#[derive(Parser)]
#[command(name = "terminator")]
#[command(about = "🤖 Terminator CLI - AI-native GUI automation")]
#[command(
long_about = "Terminator CLI provides tools for managing the Terminator project, including version management, releases, and development workflows."
)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(ValueEnum, Clone, Copy, Debug, Default)]
#[clap(rename_all = "lower")]
enum BumpLevel {
#[default]
Patch,
Minor,
Major,
}
impl std::fmt::Display for BumpLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", format!("{self:?}").to_lowercase())
}
}
#[derive(Parser, Debug)]
struct ReleaseArgs {
/// The part of the version to bump: patch, minor, or major.
#[clap(value_enum, default_value_t = BumpLevel::Patch)]
level: BumpLevel,
}
#[derive(Parser, Debug)]
struct McpChatArgs {
/// MCP server URL (e.g., http://localhost:3000)
#[clap(long, short = 'u', conflicts_with = "command")]
url: Option<String>,
/// Command to start MCP server via stdio (e.g., "npx -y terminator-mcp-agent")
#[clap(long, short = 'c', conflicts_with = "url")]
command: Option<String>,
}
#[derive(Parser, Debug)]
struct McpExecArgs {
/// MCP server URL
#[clap(long, short = 'u', conflicts_with = "command")]
url: Option<String>,
/// Command to start MCP server via stdio
#[clap(long, short = 'c', conflicts_with = "url")]
command: Option<String>,
/// Tool name to execute
tool: String,
/// Arguments for the tool (as JSON or simple string)
args: Option<String>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
#[clap(rename_all = "lower")]
enum InputType {
Auto,
Gist,
Raw,
File,
}
#[derive(Parser, Debug, Clone)]
struct McpRunArgs {
/// MCP server URL (e.g., http://localhost:3000)
#[clap(long, short = 'u', conflicts_with = "command")]
url: Option<String>,
/// Command to start MCP server via stdio (e.g., "npx -y terminator-mcp-agent")
#[clap(long, short = 'c', conflicts_with = "url")]
command: Option<String>,
/// Input source - can be a GitHub gist URL, raw gist URL, or local file path (JSON/YAML)
input: String,
/// Input type (auto-detected by default)
#[clap(long, value_enum, default_value = "auto")]
input_type: InputType,
/// Dry run - parse and validate the workflow without executing
#[clap(long)]
dry_run: bool,
/// Verbose output
#[clap(long, short)]
verbose: bool,
/// Stop on first error (default: true)
#[clap(long)]
no_stop_on_error: bool,
/// Include detailed results (default: true)
#[clap(long)]
no_detailed_results: bool,
/// Skip retry logic on errors (default: false, will retry on errors)
#[clap(long)]
no_retry: bool,
/// Skip TypeScript type checking before execution (not recommended)
#[clap(long)]
skip_type_check: bool,
/// Start execution from a specific step ID
#[clap(long)]
start_from_step: Option<String>,
/// End execution at a specific step ID (inclusive)
#[clap(long)]
end_at_step: Option<String>,
/// Follow fallback_id even beyond end_at_step boundary (default: false when end_at_step is specified)
#[clap(long)]
follow_fallback: Option<bool>,
/// Execute jumps when reaching the end_at_step boundary (default: false)
#[clap(long)]
execute_jumps_at_end: Option<bool>,
/// Disable output logging to file (logging is enabled by default)
#[clap(long)]
no_log: bool,
/// JSON object with input values for workflow variables
/// Example: --inputs '{"user":"john","count":5}'
#[clap(long)]
inputs: Option<String>,
}
#[derive(Subcommand)]
enum McpCommands {
/// Interactive chat with MCP server
Chat(McpChatArgs),
/// Interactive AI-powered chat with MCP server
AiChat(McpChatArgs),
/// Execute a single MCP tool
Exec(McpExecArgs),
/// Execute a workflow sequence from a local file or GitHub gist
Run(McpRunArgs),
/// Validate workflow output structure
Validate(McpValidateArgs),
/// Generate TypeScript SDK snippet from MCP tool call
Snippet(McpSnippetArgs),
}
#[derive(Parser, Debug, Clone)]
struct McpSnippetArgs {
/// Tool name (e.g., click_element, type_into_element)
tool: String,
/// Arguments as JSON string
args: String,
}
#[derive(Parser, Debug, Clone)]
struct McpValidateArgs {
/// Input file containing workflow output (JSON format). Use '-' or omit to read from stdin
input: Option<String>,
/// Show quality score (0-100)
#[clap(long)]
score: bool,
}
#[derive(Subcommand)]
enum Commands {
/// Bump patch version (x.y.Z+1)
Patch,
/// Bump minor version (x.Y+1.0)
Minor,
/// Bump major version (X+1.0.0)
Major,
/// Sync all package versions without bumping
Sync,
/// Show current version status
Status,
/// Tag current version and push (triggers CI)
Tag,
/// Full release: bump version + tag + push
Release(ReleaseArgs),
/// MCP client commands
#[command(subcommand)]
Mcp(McpCommands),
/// Setup Terminator environment (Chrome extension, SDKs, dependencies)
Setup(commands::setup::SetupCommand),
/// Create a new TypeScript workflow project
Init(commands::init::InitCommand),
}
fn main() {
let cli = Cli::parse();
// Only ensure we're in the project root for development commands
match cli.command {
Commands::Patch => {
ensure_project_root();
bump_version("patch");
}
Commands::Minor => {
ensure_project_root();
bump_version("minor");
}
Commands::Major => {
ensure_project_root();
bump_version("major");
}
Commands::Sync => {
ensure_project_root();
sync_all_versions();
}
Commands::Status => {
ensure_project_root();
show_status();
}
Commands::Tag => {
ensure_project_root();
tag_and_push();
}
Commands::Release(args) => {
ensure_project_root();
full_release(&args.level.to_string());
}
Commands::Mcp(mcp_cmd) => handle_mcp_command(mcp_cmd),
Commands::Setup(setup_cmd) => {
// Setup command doesn't require project root
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
if let Err(e) = setup_cmd.execute().await {
eprintln!("❌ Setup failed: {e}");
std::process::exit(1);
}
});
}
Commands::Init(init_cmd) => {
// Init command doesn't require project root
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
if let Err(e) = init_cmd.execute().await {
eprintln!("❌ Init failed: {e}");
std::process::exit(1);
}
});
}
}
}
fn ensure_project_root() {
// Check if we're already in the project root
if Path::new("Cargo.toml").exists() && Path::new("crates/terminator").exists() {
return;
}
// If we're in terminator-cli, go up two levels (crates/terminator-cli -> crates -> root)
if env::current_dir()
.map(|p| {
p.file_name()
.map(|n| n == "terminator-cli")
.unwrap_or(false)
})
.unwrap_or(false)
{
// Go up one level to crates/
if env::set_current_dir("..").is_ok() {
// Go up one more level to project root
if env::set_current_dir("..").is_err() {
eprintln!("❌ Failed to change to project root directory");
std::process::exit(1);
}
} else {
eprintln!("❌ Failed to change to crates directory");
std::process::exit(1);
}
return;
}
// If we're in crates/, go up one level
if env::current_dir()
.map(|p| p.file_name().map(|n| n == "crates").unwrap_or(false))
.unwrap_or(false)
&& env::set_current_dir("..").is_err()
{
eprintln!("❌ Failed to change to project root directory");
std::process::exit(1);
}
// Final check
if !Path::new("Cargo.toml").exists() || !Path::new("crates/terminator").exists() {
eprintln!("❌ Not in Terminator project root. Please run from workspace root.");
eprintln!("💡 Usage: terminator <command>");
std::process::exit(1);
}
}
fn get_workspace_version() -> Result<String, Box<dyn std::error::Error>> {
let cargo_toml = fs::read_to_string("Cargo.toml")?;
let mut in_workspace_package = false;
for line in cargo_toml.lines() {
let trimmed_line = line.trim();
if trimmed_line == "[workspace.package]" {
in_workspace_package = true;
continue;
}
if in_workspace_package {
if trimmed_line.starts_with('[') {
// We've left the workspace.package section
break;
}
if trimmed_line.starts_with("version") {
if let Some(version_part) = trimmed_line.split('=').nth(1) {
if let Some(version) = version_part.trim().split('"').nth(1) {
return Ok(version.to_string());
}
}
}
}
}
Err("Version not found in [workspace.package] in Cargo.toml".into())
}
fn sync_cargo_versions() -> Result<(), Box<dyn std::error::Error>> {
println!("📦 Syncing Cargo.toml dependency versions...");
let workspace_version = get_workspace_version()?;
let cargo_toml = fs::read_to_string("Cargo.toml")?;
let mut lines: Vec<String> = cargo_toml.lines().map(|s| s.to_string()).collect();
let mut in_workspace_deps = false;
let mut deps_version_updated = false;
let tmp = 0..lines.len();
for i in tmp {
let line = &lines[i];
let trimmed_line = line.trim();
if trimmed_line.starts_with('[') {
in_workspace_deps = trimmed_line == "[workspace.dependencies]";
continue;
}
if in_workspace_deps && trimmed_line.starts_with("terminator =") {
let line_clone = line.clone();
if let Some(start) = line_clone.find("version = \"") {
let version_start = start + "version = \"".len();
if let Some(end_quote_offset) = line_clone[version_start..].find('"') {
let range = version_start..(version_start + end_quote_offset);
if &line_clone[range.clone()] != workspace_version.as_str() {
lines[i].replace_range(range, &workspace_version);
println!(
"✅ Updated 'terminator' dependency version to {workspace_version}."
);
deps_version_updated = true;
} else {
println!("✅ 'terminator' dependency version is already up to date.");
deps_version_updated = true; // Mark as done
}
}
}
break; // Assume only one terminator dependency to update
}
}
if deps_version_updated {
fs::write("Cargo.toml", lines.join("\n") + "\n")?;
} else {
eprintln!(
"⚠️ Warning: Could not find 'terminator' in [workspace.dependencies] to sync version."
);
}
Ok(())
}
fn set_workspace_version(new_version: &str) -> Result<(), Box<dyn std::error::Error>> {
let cargo_toml = fs::read_to_string("Cargo.toml")?;
let mut lines: Vec<String> = cargo_toml.lines().map(|s| s.to_string()).collect();
let mut in_workspace_package = false;
let mut package_version_updated = false;
let tmp = 0..lines.len();
for i in tmp {
let line = &lines[i];
let trimmed_line = line.trim();
if trimmed_line.starts_with('[') {
in_workspace_package = trimmed_line == "[workspace.package]";
continue;
}
if in_workspace_package && trimmed_line.starts_with("version =") {
let indentation = line.len() - line.trim_start().len();
lines[i] = format!("{}version = \"{}\"", " ".repeat(indentation), new_version);
package_version_updated = true;
break; // Exit after finding and updating the version
}
}
if !package_version_updated {
return Err("version key not found in [workspace.package] in Cargo.toml".into());
}
fs::write("Cargo.toml", lines.join("\n") + "\n")?;
Ok(())
}
fn parse_version(version: &str) -> Result<(u32, u32, u32), Box<dyn std::error::Error>> {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() != 3 {
return Err("Invalid version format".into());
}
let major = parts[0].parse::<u32>()?;
let minor = parts[1].parse::<u32>()?;
let patch = parts[2].parse::<u32>()?;
Ok((major, minor, patch))
}
fn bump_version(bump_type: &str) {
println!("🔄 Bumping {bump_type} version...");
let current_version = match get_workspace_version() {
Ok(v) => v,
Err(e) => {
eprintln!("❌ Failed to get current version: {e}");
return;
}
};
let (major, minor, patch) = match parse_version(¤t_version) {
Ok(v) => v,
Err(e) => {
eprintln!("❌ Failed to parse version {current_version}: {e}");
return;
}
};
let new_version = match bump_type {
"patch" => format!("{}.{}.{}", major, minor, patch + 1),
"minor" => format!("{}.{}.0", major, minor + 1),
"major" => format!("{}.0.0", major + 1),
_ => {
eprintln!("❌ Invalid bump type: {bump_type}");
return;
}
};
println!("📝 {current_version} → {new_version}");
if let Err(e) = set_workspace_version(&new_version) {
eprintln!("❌ Failed to update workspace version: {e}");
return;
}
println!("✅ Updated workspace version to {new_version}");
sync_all_versions();
}
fn sync_all_versions() {
println!("🔄 Syncing all package versions...");
// First, sync versions within Cargo.toml
if let Err(e) = sync_cargo_versions() {
eprintln!("❌ Failed to sync versions in Cargo.toml: {e}");
return;
}
let workspace_version = match get_workspace_version() {
Ok(v) => v,
Err(e) => {
eprintln!("❌ Failed to get workspace version: {e}");
return;
}
};
println!("📦 Workspace version: {workspace_version}");
// Sync Node.js bindings
sync_nodejs_bindings(&workspace_version);
// Sync MCP agent
sync_mcp_agent(&workspace_version);
// Sync CLI package
sync_cli(&workspace_version);
// Sync Browser Extension
sync_browser_extension(&workspace_version);
// Sync Workflow Package
sync_workflow_package(&workspace_version);
// Sync KV Package
sync_kv_package(&workspace_version);
// Update Cargo.lock
println!("🔒 Updating Cargo.lock...");
if let Err(e) = run_command("cargo", &["check", "--quiet"]) {
eprintln!("⚠️ Warning: Failed to update Cargo.lock: {e}");
}
println!("✅ All versions synchronized!");
}
fn sync_nodejs_bindings(version: &str) {
println!("📦 Syncing Node.js bindings to version {version}...");
let nodejs_dir = Path::new("packages/terminator-nodejs");
if !nodejs_dir.exists() {
println!("⚠️ Node.js bindings directory not found, skipping");
return;
}
// Update main package.json directly
if let Err(e) = update_package_json("packages/terminator-nodejs/package.json", version) {
eprintln!("⚠️ Warning: Failed to update Node.js package.json directly: {e}");
} else {
println!("✅ Updated Node.js package.json to {version}");
}
// ALSO update CPU/platform-specific packages under packages/terminator-nodejs/npm
let npm_dir = nodejs_dir.join("npm");
if npm_dir.exists() {
if let Ok(entries) = fs::read_dir(&npm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let package_json = entry.path().join("package.json");
if package_json.exists() {
if let Err(e) =
update_package_json(&package_json.to_string_lossy(), version)
{
eprintln!(
"⚠️ Warning: Failed to update {}: {}",
package_json.display(),
e
);
} else {
println!("📦 Updated {}", entry.file_name().to_string_lossy());
}
}
}
}
}
}
// Run sync script if it exists (still useful for additional tasks like N-API metadata)
let original_dir = match env::current_dir() {
Ok(dir) => dir,
Err(e) => {
eprintln!("❌ Could not get current directory: {e}");
return;
}
};
if env::set_current_dir(nodejs_dir).is_ok() {
println!("🔄 Running npm run sync-version...");
if run_command("npm", &["run", "sync-version"]).is_ok() {
println!("✅ Node.js sync script completed");
} else {
// This is not really a failure - the versions are already synced
println!(
"ℹ️ Note: npm sync-version script exited (versions may already be up-to-date)"
);
}
// Always change back to the original directory
if let Err(e) = env::set_current_dir(&original_dir) {
eprintln!("❌ Failed to restore original directory: {e}");
std::process::exit(1); // Exit if we can't get back, to avoid further errors
}
} else {
eprintln!("⚠️ Warning: Could not switch to Node.js directory");
}
}
fn sync_mcp_agent(version: &str) {
println!("📦 Syncing MCP agent...");
let mcp_dir = Path::new("crates/terminator-mcp-agent");
if !mcp_dir.exists() {
return;
}
// Update main package.json
if let Err(e) = update_package_json("crates/terminator-mcp-agent/package.json", version) {
eprintln!("⚠️ Warning: Failed to update MCP agent package.json: {e}");
return;
}
// Update platform packages
let npm_dir = mcp_dir.join("npm");
if npm_dir.exists() {
if let Ok(entries) = fs::read_dir(npm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let package_json = entry.path().join("package.json");
if package_json.exists() {
if let Err(e) =
update_package_json(&package_json.to_string_lossy(), version)
{
eprintln!(
"⚠️ Warning: Failed to update {}: {}",
entry.path().display(),
e
);
} else {
println!("📦 Updated {}", entry.file_name().to_string_lossy());
}
}
}
}
}
}
// Update package-lock.json
let original_dir = match env::current_dir() {
Ok(dir) => dir,
Err(e) => {
eprintln!("❌ Could not get current directory: {e}");
return;
}
};
if env::set_current_dir(mcp_dir).is_ok() {
if run_command("npm", &["install", "--package-lock-only", "--silent"]).is_ok() {
println!("✅ MCP package-lock.json updated");
} else {
println!("ℹ️ Note: package-lock.json update skipped (run 'npm install' in crates/terminator-mcp-agent if needed)");
}
// Always change back to the original directory
if let Err(e) = env::set_current_dir(&original_dir) {
eprintln!("❌ Failed to restore original directory: {e}");
std::process::exit(1);
}
}
println!("✅ MCP agent synced");
}
fn sync_cli(version: &str) {
println!("📦 Syncing CLI package...");
let cli_dir = Path::new("crates/terminator-cli");
if !cli_dir.exists() {
return;
}
// Update main package.json
if let Err(e) = update_package_json("crates/terminator-cli/package.json", version) {
eprintln!("⚠️ Warning: Failed to update CLI package.json: {e}");
return;
}
// Update platform packages
let npm_dir = cli_dir.join("npm");
if npm_dir.exists() {
if let Ok(entries) = fs::read_dir(npm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let package_json = entry.path().join("package.json");
if package_json.exists() {
if let Err(e) =
update_package_json(&package_json.to_string_lossy(), version)
{
eprintln!(
"⚠️ Warning: Failed to update {}: {}",
entry.path().display(),
e
);
} else {
println!("📦 Updated {}", entry.file_name().to_string_lossy());
}
}
}
}
}
}
println!("✅ CLI package synced");
}
fn sync_browser_extension(version: &str) {
println!("📦 Syncing browser extension to version {version}...");
let ext_dir = Path::new("crates/terminator/browser-extension");
if !ext_dir.exists() {
println!("⚠️ Browser extension directory not found, skipping");
return;
}
let manifest_path = ext_dir.join("manifest.json");
if manifest_path.exists() {
if let Err(e) = update_json_version(&manifest_path.to_string_lossy(), version) {
eprintln!(
"⚠️ Warning: Failed to update {}: {}",
manifest_path.display(),
e
);
} else {
println!("✅ Updated manifest.json to {version}");
}
}
let build_check_path = ext_dir.join("build_check.json");
if build_check_path.exists() {
if let Err(e) = update_json_version(&build_check_path.to_string_lossy(), version) {
eprintln!(
"⚠️ Warning: Failed to update {}: {}",
build_check_path.display(),
e
);
} else {
println!("✅ Updated build_check.json to {version}");
}
}
}
fn sync_workflow_package(version: &str) {
println!("📦 Syncing workflow package to version {version}...");
let workflow_dir = Path::new("packages/workflow");
if !workflow_dir.exists() {
println!("⚠️ Workflow package directory not found, skipping");
return;
}
let package_json = workflow_dir.join("package.json");
if package_json.exists() {
if let Err(e) = update_package_json(&package_json.to_string_lossy(), version) {
eprintln!("⚠️ Warning: Failed to update workflow package.json: {e}");
} else {
println!("✅ Workflow package synced to {version}");
}
}
}
fn sync_kv_package(version: &str) {
println!("📦 Syncing KV package to version {version}...");
let kv_dir = Path::new("packages/kv");
if !kv_dir.exists() {
println!("⚠️ KV package directory not found, skipping");
return;
}
let package_json = kv_dir.join("package.json");
if package_json.exists() {
if let Err(e) = update_package_json(&package_json.to_string_lossy(), version) {
eprintln!("⚠️ Warning: Failed to update KV package.json: {e}");
} else {
println!("✅ KV package synced to {version}");
}
}
}
fn update_package_json(path: &str, version: &str) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
let mut pkg: serde_json::Value = serde_json::from_str(&content)?;
// Update main version
pkg["version"] = serde_json::Value::String(version.to_string());
// Update optional dependencies for platform packages
if let Some(deps) = pkg
.get_mut("optionalDependencies")
.and_then(|v| v.as_object_mut())
{
for (key, value) in deps.iter_mut() {
// Update @mediar-ai/terminator-* platform packages
if key.starts_with("@mediar-ai/terminator-")
|| key.starts_with("@mediar-ai/cli-")
|| key.starts_with("terminator-mcp-")
|| key.starts_with("terminator.js-")
{
*value = serde_json::Value::String(version.to_string());
}
}
}
// Update peerDependencies for @mediar-ai/terminator
if let Some(peer_deps) = pkg
.get_mut("peerDependencies")
.and_then(|v| v.as_object_mut())
{
for (key, value) in peer_deps.iter_mut() {
if key == "@mediar-ai/terminator" {
// Use caret range for peer dependencies (allows compatible versions)
*value = serde_json::Value::String(format!("^{version}"));
}
}
}
// Write back with pretty formatting
let formatted = serde_json::to_string_pretty(&pkg)?;
fs::write(path, formatted + "\n")?;
Ok(())
}
fn update_json_version(path: &str, version: &str) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
let mut json_value: serde_json::Value = serde_json::from_str(&content)?;
json_value["version"] = serde_json::Value::String(version.to_string());
let formatted = serde_json::to_string_pretty(&json_value)?;
fs::write(path, formatted + "\n")?;
Ok(())
}
fn show_status() {
println!("📊 Terminator Project Status");
println!("============================");
let workspace_version = get_workspace_version().unwrap_or_else(|_| "ERROR".to_string());
println!("📦 Workspace version: {workspace_version}");
// Show package versions
let nodejs_version = get_package_version("packages/terminator-nodejs/package.json");
let mcp_version = get_package_version("crates/terminator-mcp-agent/package.json");
let browser_extension_version =
get_package_version("crates/terminator/browser-extension/manifest.json");
let workflow_version = get_package_version("packages/workflow/package.json");
println!();
println!("Package versions:");
println!(" Node.js bindings: {nodejs_version}");
println!(" MCP agent: {mcp_version}");
println!(" Browser extension: {browser_extension_version}");
println!(" Workflow package: {workflow_version}");
// Git status
println!();
println!("Git status:");
if let Ok(output) = Command::new("git").args(["status", "--porcelain"]).output() {
let status = String::from_utf8_lossy(&output.stdout);
if status.trim().is_empty() {
println!(" ✅ Working directory clean");
} else {
println!(" ⚠️ Uncommitted changes:");
for line in status.lines().take(5) {
println!(" {line}");
}
}
}
}
fn get_package_version(path: &str) -> String {
match fs::read_to_string(path) {
Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
Ok(pkg) => pkg
.get("version")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "No version field".to_string()),
Err(_) => "Parse error".to_string(),
},
Err(_) => "Not found".to_string(),
}
}
fn tag_and_push() {
let version = match get_workspace_version() {
Ok(v) => v,
Err(e) => {
eprintln!("❌ Failed to get current version: {e}");
return;
}
};
println!("🏷️ Tagging and pushing version {version}...");
// Check for uncommitted changes
if let Ok(output) = Command::new("git").args(["diff", "--name-only"]).output() {
let diff = String::from_utf8_lossy(&output.stdout);
if !diff.trim().is_empty() {
println!("⚠️ Uncommitted changes detected. Committing...");
if let Err(e) = run_command("git", &["add", "."]) {
eprintln!("❌ Failed to git add: {e}");
return;
}
if let Err(e) = run_command(
"git",
&["commit", "-m", &format!("Bump version to {version}")],
) {
eprintln!("❌ Failed to git commit: {e}");
return;
}
}
}
// Create tag
let tag = format!("v{version}");
if let Err(e) = run_command(
"git",
&[
"tag",
"-a",
&tag,
"-m",
&format!("Release version {version}"),
],
) {
eprintln!("❌ Failed to create tag: {e}");
return;
}
// Push changes and tag
if let Err(e) = run_command("git", &["push", "origin", "main"]) {
eprintln!("❌ Failed to push changes: {e}");
return;
}
if let Err(e) = run_command("git", &["push", "origin", &tag]) {
eprintln!("❌ Failed to push tag: {e}");
return;
}
println!("✅ Successfully released version {version}!");
println!("🔗 Check CI: https://github.com/mediar-ai/terminator/actions");
}
fn full_release(bump_type: &str) {
println!("🚀 Starting full release process with {bump_type} bump...");
bump_version(bump_type);
tag_and_push();
}
fn run_command(program: &str, args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
let output = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"Command failed: {} {}\nError: {}",
program,
args.join(" "),
stderr
)
.into());
}
Ok(())
}