-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathplugin_cmd.rs
More file actions
4433 lines (3809 loc) · 134 KB
/
Copy pathplugin_cmd.rs
File metadata and controls
4433 lines (3809 loc) · 134 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
//! Plugin management command for Cortex CLI.
//!
//! Provides plugin management functionality:
//! - List installed plugins
//! - Install plugins
//! - Remove plugins
//! - Enable/disable plugins
//! - Show plugin info
//! - Create new plugin projects
//! - Development mode with hot-reload
//! - Build plugin WASM files
//! - Validate plugin manifests
//! - Publish plugins (dry-run)
use anyhow::{Context, Result, bail};
use clap::Parser;
use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::Duration;
// =============================================================================
// Plugin SDK Templates (embedded for standalone CLI operation)
// =============================================================================
/// Manifest template for new plugins.
const MANIFEST_TEMPLATE: &str = r#"[plugin]
id = "{{plugin_id}}"
name = "{{plugin_name}}"
version = "0.1.0"
description = "{{description}}"
authors = ["{{author}}"]
# Capabilities your plugin needs
# Available: commands, hooks, events, tools, formatters, themes, config, filesystem, shell, network
capabilities = ["commands"]
# Permissions your plugin requires (optional)
# permissions = [
# { read_file = { paths = ["**/*"] } },
# { execute = { commands = ["ls", "cat"] } },
# { network = { domains = ["api.example.com"] } },
# ]
# Commands provided by your plugin
[[commands]]
name = "{{command_name}}"
description = "{{command_description}}"
usage = "/{{command_name}} [args]"
# Command arguments (optional)
# [[commands.args]]
# name = "arg"
# description = "An argument"
# required = false
# default = "default_value"
# Hooks your plugin registers (optional)
# [[hooks]]
# hook_type = "tool_execute_before" # or: tool_execute_after, chat_message, permission_ask, etc.
# priority = 100 # Lower runs first
# pattern = "*" # Tool pattern filter
# Plugin configuration schema (optional)
# [config]
# setting_name = { description = "Description", type = "string", default = "value" }
# WASM settings (optional)
[wasm]
memory_pages = 256 # 64KB per page, 256 = 16MB
timeout_ms = 30000 # 30 seconds
"#;
/// Basic Rust template for plugins.
const RUST_TEMPLATE: &str = r#"//! {{plugin_name}} - A Cortex plugin
//!
//! Build with: cargo build --target wasm32-wasi --release
#![no_std]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
// ============================================================================
// Host function imports
// ============================================================================
#[link(wasm_import_module = "cortex")]
extern "C" {
/// Log a message at the specified level.
/// level: 0=trace, 1=debug, 2=info, 3=warn, 4=error
fn log(level: i32, msg_ptr: i32, msg_len: i32);
/// Get context JSON (returns length)
fn get_context() -> i64;
}
// ============================================================================
// Logging helpers
// ============================================================================
fn log_message(level: i32, msg: &str) {
// SAFETY: FFI call to host-provided `log` function.
// Contract with the host runtime:
// 1. `log` is a valid function pointer provided by the WASM runtime during instantiation
// 2. The host reads the message from WASM linear memory using (ptr, len) immediately
// 3. The host does not retain the pointer past the call boundary
// 4. The host handles all memory management on its side (copies data if needed)
// 5. Invalid level values are handled gracefully by the host (treated as info)
// 6. The pointer is valid for the duration of this call (Rust string guarantee)
unsafe {
log(level, msg.as_ptr() as i32, msg.len() as i32);
}
}
fn log_info(msg: &str) { log_message(2, msg); }
// ============================================================================
// Plugin lifecycle
// ============================================================================
/// Called when the plugin is initialized.
#[no_mangle]
pub extern "C" fn init() -> i32 {
log_info("{{plugin_name}} initialized");
0 // Return 0 for success
}
/// Called when the plugin is shutting down.
#[no_mangle]
pub extern "C" fn shutdown() -> i32 {
log_info("{{plugin_name}} shutting down");
0
}
// ============================================================================
// Command handlers
// ============================================================================
/// Handler for the /{{command_name}} command.
#[no_mangle]
pub extern "C" fn cmd_{{command_name_snake}}() -> i32 {
log_info("{{command_name}} command executed");
0
}
// ============================================================================
// Panic handler (required for no_std)
// ============================================================================
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
// ============================================================================
// Global allocator (required for alloc)
// ============================================================================
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
"#;
/// Advanced Rust template with TUI hooks.
const RUST_ADVANCED_TEMPLATE: &str = r#"//! {{plugin_name}} - Advanced Cortex Plugin
//!
//! This template demonstrates advanced plugin features including:
//! - TUI customization hooks
//! - Custom widgets
//! - Keyboard bindings
//! - Event handling
//!
//! Build with: cargo build --target wasm32-wasi --release
#![no_std]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use alloc::vec;
// ============================================================================
// Host function imports
// ============================================================================
#[link(wasm_import_module = "cortex")]
extern "C" {
fn log(level: i32, msg_ptr: i32, msg_len: i32);
fn get_context() -> i64;
fn register_widget(region: i32, widget_type_ptr: i32, widget_type_len: i32) -> i32;
fn register_keybinding(key_ptr: i32, key_len: i32, action_ptr: i32, action_len: i32) -> i32;
fn show_toast(level: i32, msg_ptr: i32, msg_len: i32, duration_ms: i32) -> i32;
fn emit_event(name_ptr: i32, name_len: i32, data_ptr: i32, data_len: i32) -> i32;
}
// ============================================================================
// Logging helpers
// ============================================================================
fn log_message(level: i32, msg: &str) {
// SAFETY: FFI call to host-provided `log` function.
// The host reads the message immediately and does not retain the pointer.
unsafe {
log(level, msg.as_ptr() as i32, msg.len() as i32);
}
}
fn log_info(msg: &str) { log_message(2, msg); }
fn log_debug(msg: &str) { log_message(1, msg); }
// ============================================================================
// Widget helpers
// ============================================================================
/// UI regions for widget placement
#[repr(i32)]
enum UiRegion {
Header = 0,
Footer = 1,
SidebarLeft = 2,
SidebarRight = 3,
StatusBar = 7,
}
fn register_widget_in_region(region: UiRegion, widget_type: &str) -> bool {
// SAFETY: FFI call to host-provided `register_widget` function.
// Arguments are passed by value (region) and by pointer+len (widget_type string).
// The host copies the string data before this call returns.
unsafe {
register_widget(
region as i32,
widget_type.as_ptr() as i32,
widget_type.len() as i32,
) == 0
}
}
fn register_key(key: &str, action: &str) -> bool {
// SAFETY: FFI call to host-provided `register_keybinding` function.
// Both string arguments are passed as (ptr, len) pairs and copied by the host.
unsafe {
register_keybinding(
key.as_ptr() as i32,
key.len() as i32,
action.as_ptr() as i32,
action.len() as i32,
) == 0
}
}
/// Toast notification levels
#[repr(i32)]
enum ToastLevel {
Info = 0,
Success = 1,
Warning = 2,
Error = 3,
}
fn show_notification(level: ToastLevel, message: &str, duration_ms: i32) {
// SAFETY: FFI call to host-provided `show_toast` function.
// The message string is copied by the host before this call returns.
unsafe {
show_toast(
level as i32,
message.as_ptr() as i32,
message.len() as i32,
duration_ms,
);
}
}
// ============================================================================
// Plugin lifecycle
// ============================================================================
#[no_mangle]
pub extern "C" fn init() -> i32 {
log_info("{{plugin_name}} initializing...");
// Register custom widgets
if register_widget_in_region(UiRegion::StatusBar, "{{plugin_id}}_status") {
log_debug("Status widget registered");
}
// Register keyboard bindings
if register_key("ctrl+shift+p", "{{plugin_id}}_action") {
log_debug("Keybinding registered: Ctrl+Shift+P");
}
log_info("{{plugin_name}} initialized successfully");
0
}
#[no_mangle]
pub extern "C" fn shutdown() -> i32 {
log_info("{{plugin_name}} shutting down");
0
}
// ============================================================================
// Command handlers
// ============================================================================
#[no_mangle]
pub extern "C" fn cmd_{{command_name_snake}}() -> i32 {
log_info("{{command_name}} command executed");
show_notification(ToastLevel::Info, "Command executed!", 2000);
0
}
// ============================================================================
// Hook handlers
// ============================================================================
/// UI render hook - customize component rendering
#[no_mangle]
pub extern "C" fn hook_ui_render() -> i32 {
// Return 0 to continue with normal rendering
0
}
/// Animation frame hook - called every frame for animations
#[no_mangle]
pub extern "C" fn hook_animation_frame(_frame: u64, _delta_us: u64) -> i32 {
// Return 1 to request another frame, 0 to stop
0
}
/// Focus change hook
#[no_mangle]
pub extern "C" fn hook_focus_change(_focused: i32) -> i32 {
0
}
/// TUI event handler
#[no_mangle]
pub extern "C" fn hook_tui_event() -> i32 {
0
}
// ============================================================================
// Custom action handlers
// ============================================================================
#[no_mangle]
pub extern "C" fn action_{{plugin_id_snake}}_action() -> i32 {
log_info("Custom action triggered via keybinding");
show_notification(ToastLevel::Success, "Action executed!", 1500);
0
}
// ============================================================================
// Panic handler
// ============================================================================
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
// ============================================================================
// Global allocator
// ============================================================================
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
"#;
/// Cargo.toml template for plugins.
const CARGO_TEMPLATE: &str = r#"[package]
name = "{{plugin_id}}"
version = "0.1.0"
edition = "2021"
# Build for WASM target: cargo build --target wasm32-wasi --release
[lib]
crate-type = ["cdylib"]
[dependencies]
wee_alloc = "0.4"
[profile.release]
opt-level = "s"
lto = true
"#;
/// TypeScript template for plugins.
const TYPESCRIPT_TEMPLATE: &str = r#"/**
* {{plugin_name}} - A Cortex Plugin
*
* This template provides a TypeScript-based plugin structure.
* Compile with: npx tsc && npx wasm-pack build
*/
// Plugin metadata
export const PLUGIN_ID = "{{plugin_id}}";
export const PLUGIN_VERSION = "0.1.0";
// ============================================================================
// Plugin Lifecycle
// ============================================================================
/**
* Called when the plugin is initialized.
*/
export function init(): number {
console.log(`${PLUGIN_ID} initialized`);
return 0;
}
/**
* Called when the plugin is shutting down.
*/
export function shutdown(): number {
console.log(`${PLUGIN_ID} shutting down`);
return 0;
}
// ============================================================================
// Command Handlers
// ============================================================================
/**
* Handler for the /{{command_name}} command.
*/
export function cmd_{{command_name_snake}}(args: string[]): number {
console.log("{{command_name}} command executed with args:", args);
return 0;
}
// ============================================================================
// Hook Handlers
// ============================================================================
/**
* Called before a tool is executed.
* Return: 0 = continue, 1 = skip, 2 = abort
*/
export function hook_tool_execute_before(input: ToolExecuteBeforeInput): number {
console.log(`Tool ${input.tool} about to execute`);
return 0;
}
// ============================================================================
// Type Definitions
// ============================================================================
interface ToolExecuteBeforeInput {
tool: string;
session_id: string;
call_id: string;
args: Record<string, unknown>;
}
"#;
/// tsconfig.json template.
const TSCONFIG_TEMPLATE: &str = r#"{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"declaration": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
"#;
/// Plugin CLI command.
#[derive(Debug, Parser)]
pub struct PluginCli {
#[command(subcommand)]
pub subcommand: PluginSubcommand,
}
/// Plugin subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum PluginSubcommand {
/// List installed plugins
#[command(visible_alias = "ls")]
List(PluginListArgs),
/// Install a plugin
#[command(visible_alias = "add")]
Install(PluginInstallArgs),
/// Remove a plugin
#[command(visible_aliases = ["rm", "uninstall"])]
Remove(PluginRemoveArgs),
/// Enable a plugin
Enable(PluginEnableArgs),
/// Disable a plugin
Disable(PluginDisableArgs),
/// Show plugin information
#[command(visible_alias = "info")]
Show(PluginShowArgs),
/// Create a new plugin project
#[command(visible_alias = "create")]
New(PluginNewArgs),
/// Start development mode with hot-reload
Dev(PluginDevArgs),
/// Build the plugin WASM file
Build(PluginBuildArgs),
/// Validate plugin manifest and structure
#[command(visible_alias = "check")]
Validate(PluginValidateArgs),
/// Prepare plugin for publication (dry-run)
Publish(PluginPublishArgs),
}
/// Arguments for plugin list command.
#[derive(Debug, Parser)]
pub struct PluginListArgs {
/// Output as JSON
#[arg(long)]
pub json: bool,
/// Show only enabled plugins
#[arg(long)]
pub enabled: bool,
/// Show only disabled plugins
#[arg(long)]
pub disabled: bool,
}
/// Arguments for plugin install command.
#[derive(Debug, Parser)]
pub struct PluginInstallArgs {
/// Plugin name or URL to install
pub name: String,
/// Plugin version (defaults to latest)
#[arg(long, short = 'v')]
pub version: Option<String>,
/// Force reinstall if already installed
#[arg(long, short = 'f')]
pub force: bool,
}
/// Arguments for plugin remove command.
#[derive(Debug, Parser)]
pub struct PluginRemoveArgs {
/// Plugin name to remove
pub name: String,
/// Skip confirmation prompt
#[arg(long, short = 'y')]
pub yes: bool,
}
/// Arguments for plugin enable command.
#[derive(Debug, Parser)]
pub struct PluginEnableArgs {
/// Plugin name to enable
pub name: String,
}
/// Arguments for plugin disable command.
#[derive(Debug, Parser)]
pub struct PluginDisableArgs {
/// Plugin name to disable
pub name: String,
}
/// Arguments for plugin show command.
#[derive(Debug, Parser)]
pub struct PluginShowArgs {
/// Plugin name to show
pub name: String,
/// Output as JSON
#[arg(long)]
pub json: bool,
}
/// Arguments for plugin new command.
#[derive(Debug, Parser)]
pub struct PluginNewArgs {
/// Plugin name (will be used as directory name and ID)
pub name: String,
/// Plugin description
#[arg(long, short = 'd', default_value = "A Cortex plugin")]
pub description: String,
/// Plugin author
#[arg(long, short = 'a')]
pub author: Option<String>,
/// Output directory (defaults to current directory)
#[arg(long, short = 'o')]
pub output: Option<PathBuf>,
/// Use advanced template with TUI hooks
#[arg(long)]
pub advanced: bool,
/// Use TypeScript template instead of Rust
#[arg(long)]
pub typescript: bool,
}
/// Arguments for plugin dev command.
#[derive(Debug, Parser)]
pub struct PluginDevArgs {
/// Plugin directory (defaults to current directory)
#[arg(long, short = 'p')]
pub path: Option<PathBuf>,
/// Watch for file changes and auto-rebuild
#[arg(long, short = 'w')]
pub watch: bool,
/// Debounce time in milliseconds for file change events
#[arg(long, default_value = "500")]
pub debounce_ms: u64,
}
/// Arguments for plugin build command.
#[derive(Debug, Parser)]
pub struct PluginBuildArgs {
/// Plugin directory (defaults to current directory)
#[arg(long, short = 'p')]
pub path: Option<PathBuf>,
/// Build in debug mode (faster, larger output)
#[arg(long)]
pub debug: bool,
/// Output directory for the compiled WASM file
#[arg(long, short = 'o')]
pub output: Option<PathBuf>,
}
/// Arguments for plugin validate command.
#[derive(Debug, Parser)]
pub struct PluginValidateArgs {
/// Plugin directory (defaults to current directory)
#[arg(long, short = 'p')]
pub path: Option<PathBuf>,
/// Output as JSON
#[arg(long)]
pub json: bool,
/// Show verbose output with all checks
#[arg(long, short = 'v')]
pub verbose: bool,
}
/// Arguments for plugin publish command.
#[derive(Debug, Parser)]
pub struct PluginPublishArgs {
/// Plugin directory (defaults to current directory)
#[arg(long, short = 'p')]
pub path: Option<PathBuf>,
/// Dry-run mode (default, no actual publishing)
#[arg(long, default_value = "true")]
pub dry_run: bool,
/// Output tarball path (defaults to plugin-name-version.tar.gz)
#[arg(long, short = 'o')]
pub output: Option<PathBuf>,
}
/// Plugin information for display.
#[derive(Debug, Serialize)]
struct PluginInfo {
name: String,
version: String,
description: String,
enabled: bool,
path: PathBuf,
}
/// Get the plugins directory.
fn get_plugins_dir() -> PathBuf {
dirs::home_dir()
.map(|h| h.join(".cortex").join("plugins"))
.unwrap_or_else(|| PathBuf::from(".cortex/plugins"))
}
// =============================================================================
// Plugin Scaffolding Functions
// =============================================================================
/// Generate a manifest from the template.
fn generate_manifest(
plugin_id: &str,
plugin_name: &str,
description: &str,
author: &str,
command_name: &str,
command_description: &str,
) -> String {
MANIFEST_TEMPLATE
.replace("{{plugin_id}}", plugin_id)
.replace("{{plugin_name}}", plugin_name)
.replace("{{description}}", description)
.replace("{{author}}", author)
.replace("{{command_name}}", command_name)
.replace("{{command_description}}", command_description)
}
/// Generate basic Rust plugin code.
fn generate_rust_code(plugin_name: &str, command_name: &str) -> String {
let command_name_snake = command_name.replace('-', "_");
RUST_TEMPLATE
.replace("{{plugin_name}}", plugin_name)
.replace("{{command_name}}", command_name)
.replace("{{command_name_snake}}", &command_name_snake)
}
/// Generate advanced Rust plugin code with TUI hooks.
fn generate_advanced_rust_code(plugin_id: &str, plugin_name: &str, command_name: &str) -> String {
let command_name_snake = command_name.replace('-', "_");
let plugin_id_snake = plugin_id.replace('-', "_");
RUST_ADVANCED_TEMPLATE
.replace("{{plugin_id}}", plugin_id)
.replace("{{plugin_id_snake}}", &plugin_id_snake)
.replace("{{plugin_name}}", plugin_name)
.replace("{{command_name}}", command_name)
.replace("{{command_name_snake}}", &command_name_snake)
}
/// Generate Cargo.toml for a plugin.
fn generate_cargo_toml(plugin_id: &str) -> String {
CARGO_TEMPLATE.replace("{{plugin_id}}", plugin_id)
}
/// Generate TypeScript plugin code.
fn generate_typescript_code(plugin_id: &str, plugin_name: &str, command_name: &str) -> String {
let command_name_snake = command_name.replace('-', "_");
TYPESCRIPT_TEMPLATE
.replace("{{plugin_id}}", plugin_id)
.replace("{{plugin_name}}", plugin_name)
.replace("{{command_name}}", command_name)
.replace("{{command_name_snake}}", &command_name_snake)
}
/// Scaffold a basic plugin project.
fn scaffold_basic_plugin(
output_dir: &Path,
plugin_id: &str,
plugin_name: &str,
description: &str,
author: &str,
) -> std::io::Result<()> {
use std::fs;
let plugin_dir = output_dir.join(plugin_id);
let src_dir = plugin_dir.join("src");
fs::create_dir_all(&src_dir)?;
// Generate manifest
let manifest = generate_manifest(
plugin_id,
plugin_name,
description,
author,
"example",
"An example command",
);
// Generate Rust code
let rust_code = generate_rust_code(plugin_name, "example");
let cargo_toml = generate_cargo_toml(plugin_id);
// Write files
fs::write(plugin_dir.join("plugin.toml"), manifest)?;
fs::write(src_dir.join("lib.rs"), rust_code)?;
fs::write(plugin_dir.join("Cargo.toml"), cargo_toml)?;
// Write README
let readme = format!(
"# {}\n\n{}\n\n## Building\n\n```bash\ncargo build --target wasm32-wasi --release\n```\n\n## Installing\n\nCopy the compiled WASM and manifest to your Cortex plugins directory:\n\n```bash\nmkdir -p ~/.cortex/plugins/{}\ncp target/wasm32-wasi/release/{}.wasm ~/.cortex/plugins/{}/plugin.wasm\ncp plugin.toml ~/.cortex/plugins/{}/\n```\n",
plugin_name,
description,
plugin_id,
plugin_id.replace('-', "_"),
plugin_id,
plugin_id,
);
fs::write(plugin_dir.join("README.md"), readme)?;
// Write .gitignore
fs::write(plugin_dir.join(".gitignore"), "target/\n")?;
Ok(())
}
/// Scaffold an advanced plugin project with optional TypeScript support.
fn scaffold_advanced_plugin(
output_dir: &Path,
plugin_id: &str,
plugin_name: &str,
description: &str,
author: &str,
use_typescript: bool,
) -> std::io::Result<()> {
use std::fs;
let plugin_dir = output_dir.join(plugin_id);
let src_dir = plugin_dir.join("src");
let tests_dir = plugin_dir.join("tests");
fs::create_dir_all(&src_dir)?;
fs::create_dir_all(&tests_dir)?;
// Generate manifest
let manifest = generate_manifest(
plugin_id,
plugin_name,
description,
author,
"example",
"An example command",
);
fs::write(plugin_dir.join("plugin.toml"), manifest)?;
if use_typescript {
// TypeScript project
let ts_code = generate_typescript_code(plugin_id, plugin_name, "example");
fs::write(src_dir.join("index.ts"), ts_code)?;
fs::write(plugin_dir.join("tsconfig.json"), TSCONFIG_TEMPLATE)?;
// package.json
let package_json = format!(
r#"{{
"name": "{}",
"version": "0.1.0",
"description": "{}",
"main": "dist/index.js",
"scripts": {{
"build": "tsc",
"watch": "tsc --watch"
}},
"devDependencies": {{
"typescript": "^5.0.0"
}}
}}"#,
plugin_id, description
);
fs::write(plugin_dir.join("package.json"), package_json)?;
// gitignore for TypeScript
fs::write(
plugin_dir.join(".gitignore"),
"node_modules/\ndist/\n*.wasm\n",
)?;
} else {
// Rust project with advanced template
let rust_code = generate_advanced_rust_code(plugin_id, plugin_name, "example");
fs::write(src_dir.join("lib.rs"), rust_code)?;
// Cargo.toml
let cargo_toml = generate_cargo_toml(plugin_id);
fs::write(plugin_dir.join("Cargo.toml"), cargo_toml)?;
// gitignore for Rust
fs::write(plugin_dir.join(".gitignore"), "target/\n*.wasm\n")?;
}
// Write README
let readme = format!(
r#"# {}
{}
## Features
- Custom widgets and UI customization
- Keyboard bindings
- Event handling
- Hot-reload support for development
## Building
{}
## Development
Enable hot-reload during development:
```bash
cortex plugin dev --watch
```
## Installing
Copy the compiled WASM and manifest to your Cortex plugins directory:
```bash
mkdir -p ~/.cortex/plugins/{}
cp target/wasm32-wasi/release/{}.wasm ~/.cortex/plugins/{}/plugin.wasm
cp plugin.toml ~/.cortex/plugins/{}/
```
"#,
plugin_name,
description,
if use_typescript {
"```bash\nnpm install\nnpm run build\n```"
} else {
"```bash\ncargo build --target wasm32-wasi --release\n```"
},
plugin_id,
plugin_id.replace('-', "_"),
plugin_id,
plugin_id,
);
fs::write(plugin_dir.join("README.md"), readme)?;
Ok(())
}
impl PluginCli {
/// Run the plugin command.
pub async fn run(self) -> Result<()> {
match self.subcommand {
PluginSubcommand::List(args) => run_list(args).await,
PluginSubcommand::Install(args) => run_install(args).await,
PluginSubcommand::Remove(args) => run_remove(args).await,
PluginSubcommand::Enable(args) => run_enable(args).await,
PluginSubcommand::Disable(args) => run_disable(args).await,
PluginSubcommand::Show(args) => run_show(args).await,
PluginSubcommand::New(args) => run_new(args).await,
PluginSubcommand::Dev(args) => run_dev(args).await,
PluginSubcommand::Build(args) => run_build(args).await,
PluginSubcommand::Validate(args) => run_validate(args).await,
PluginSubcommand::Publish(args) => run_publish(args).await,
}
}
}
async fn run_list(args: PluginListArgs) -> Result<()> {
// Validate mutually exclusive flags
if args.enabled && args.disabled {
bail!(
"Cannot specify both --enabled and --disabled. Choose one filter or use neither for all plugins."
);
}
let plugins_dir = get_plugins_dir();
if !plugins_dir.exists() {
if args.json {
println!("[]");
} else {
println!("No plugins installed.");
println!("\nPlugin directory: {}", plugins_dir.display());
println!("Use 'cortex plugin install <name>' to install a plugin.");
}
return Ok(());
}
let mut plugins = Vec::new();
// Scan plugins directory
if let Ok(entries) = std::fs::read_dir(&plugins_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let manifest_path = path.join("plugin.toml");
if manifest_path.exists()
&& let Ok(content) = std::fs::read_to_string(&manifest_path)
&& let Ok(manifest) = toml::from_str::<toml::Value>(&content)
{
let name = manifest
.get("name")
.and_then(|v| v.as_str())
.unwrap_or_else(|| {
path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
})
.to_string();