-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate.rs
More file actions
1148 lines (1023 loc) · 37.8 KB
/
create.rs
File metadata and controls
1148 lines (1023 loc) · 37.8 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 anyhow::{Context, Result};
use inquire::{Confirm, InquireError, MultiSelect, Select, Text, error::InquireResult};
use log::{debug, info};
use std::fmt;
use std::path::PathBuf;
use crate::compile::sanitize_filename;
use crate::mcp_metadata::McpMetadataFile;
/// Available AI models for agent configuration
const AVAILABLE_MODELS: &[&str] = &[
"claude-opus-4.5",
"claude-sonnet-4.5",
"gpt-5.2-codex",
"gemini-3-pro-preview",
];
/// Configuration gathered from the interactive wizard
#[derive(Debug, Default)]
struct AgentConfig {
name: String,
description: String,
model: String,
schedule: Option<String>,
branch: Option<String>,
workspace: String,
repositories: Vec<RepositoryConfig>,
/// Repository aliases to checkout (if empty, all repos are checked out)
checkout: Vec<String>,
mcps: Vec<McpSelection>,
prompt_body: String,
}
/// MCP selection with optional tool allow-list
#[derive(Debug, Clone)]
struct McpSelection {
name: String,
/// If None, all tools are allowed. If Some, only these tools are allowed.
allowed_tools: Option<Vec<String>>,
}
#[derive(Debug)]
struct RepositoryConfig {
alias: String,
repo_type: String,
name: String,
ref_branch: String,
}
/// Wizard steps for navigation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WizardStep {
Name,
Description,
Model,
Schedule,
Branch,
Workspace,
Repositories,
Checkout,
Mcps,
Done,
}
impl WizardStep {
fn next(self) -> Self {
match self {
Self::Name => Self::Description,
Self::Description => Self::Model,
Self::Model => Self::Schedule,
Self::Schedule => Self::Branch,
Self::Branch => Self::Workspace,
Self::Workspace => Self::Repositories,
Self::Repositories => Self::Checkout,
Self::Checkout => Self::Mcps,
Self::Mcps => Self::Done,
Self::Done => Self::Done,
}
}
fn prev(self) -> Self {
match self {
Self::Name => Self::Name,
Self::Description => Self::Name,
Self::Model => Self::Description,
Self::Schedule => Self::Model,
Self::Branch => Self::Schedule,
Self::Workspace => Self::Branch,
Self::Repositories => Self::Workspace,
Self::Checkout => Self::Repositories,
Self::Mcps => Self::Checkout,
Self::Done => Self::Mcps,
}
}
}
/// Helper to handle prompt results with back navigation
fn handle_prompt<T>(result: InquireResult<T>, step: &mut WizardStep) -> Result<Option<T>> {
match result {
Ok(value) => Ok(Some(value)),
Err(InquireError::OperationCanceled) => {
let prev = step.prev();
if prev == *step {
// Already at the beginning, ask if user wants to quit
let quit = Confirm::new("Exit wizard?")
.with_default(false)
.prompt()
.unwrap_or(false);
if quit {
anyhow::bail!("Wizard cancelled by user");
}
} else {
*step = prev;
}
Ok(None)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Prompt failed"),
}
}
/// Run the interactive agent creation wizard
pub async fn create_agent(output_dir: Option<PathBuf>) -> Result<()> {
info!("Starting interactive agent creation wizard");
debug!("Output directory: {:?}", output_dir);
println!("\n🚀 Azure DevOps Agentic Pipeline Creator\n");
println!("This wizard will guide you through creating a new agent configuration.");
println!("Press Esc to go back to the previous step.\n");
let mut config = AgentConfig::default();
let mut step = WizardStep::Name;
let mcp_metadata = McpMetadataFile::bundled();
loop {
match step {
WizardStep::Name => {
let prompt = Text::new("Agent Name:")
.with_help_message(
"Enter a human-readable name for your agent (Esc to go back)",
)
.with_default(&config.name)
.prompt();
if let Some(name) = handle_prompt(prompt, &mut step)? {
config.name = name;
step = step.next();
}
}
WizardStep::Description => {
let prompt = Text::new("Description:")
.with_help_message(
"One-line description of what this agent does (Esc to go back)",
)
.with_default(&config.description)
.prompt();
if let Some(desc) = handle_prompt(prompt, &mut step)? {
config.description = desc;
step = step.next();
}
}
WizardStep::Model => {
let default_idx = AVAILABLE_MODELS
.iter()
.position(|&m| m == config.model)
.unwrap_or(0);
let prompt = Select::new("AI Model:", AVAILABLE_MODELS.to_vec())
.with_help_message("Select the AI model for this agent (Esc to go back)")
.with_starting_cursor(default_idx)
.prompt();
if let Some(model) = handle_prompt(prompt, &mut step)? {
config.model = model.to_string();
step = step.next();
}
}
WizardStep::Schedule => {
match prompt_schedule_with_back(&mut step)? {
Some(schedule) => {
config.schedule = schedule;
step = step.next();
}
None => {
// User pressed Esc, step already updated by handle_prompt
}
}
}
WizardStep::Branch => {
let default_val = config.branch.clone().unwrap_or_default();
let prompt = Text::new("Branch (optional):")
.with_help_message(
"Pin checkout to a specific branch (e.g., 'main'). Leave empty for default behavior. (Esc to go back)",
)
.with_default(&default_val)
.prompt();
match prompt {
Ok(val) => {
config.branch = if val.trim().is_empty() {
None
} else {
Some(val.trim().to_string())
};
step = step.next();
}
Err(InquireError::OperationCanceled) => {
step = step.prev();
}
Err(e) => return Err(e).context("Failed to get branch"),
}
}
WizardStep::Workspace => {
let workspace_options = vec![
WorkspaceOption {
value: "root",
description: "Agent runs in $(Build.SourcesDirectory)",
},
WorkspaceOption {
value: "repo",
description: "Agent runs in $(Build.SourcesDirectory)/$(Build.Repository.Name)",
},
];
let default_idx = workspace_options
.iter()
.position(|w| w.value == config.workspace)
.unwrap_or(0);
let prompt = Select::new("Workspace:", workspace_options)
.with_help_message("Where should the agent execute? (Esc to go back)")
.with_starting_cursor(default_idx)
.prompt();
if let Some(choice) = handle_prompt(prompt, &mut step)? {
config.workspace = choice.value.to_string();
step = step.next();
}
}
WizardStep::Repositories => {
match prompt_repositories_with_back(&mut config.repositories, &mut step)? {
true => step = step.next(),
false => { /* User went back, step already updated */ }
}
}
WizardStep::Checkout => {
match prompt_checkout_with_back(
&config.repositories,
&mut config.checkout,
&mut step,
)? {
true => step = step.next(),
false => { /* User went back, step already updated */ }
}
}
WizardStep::Mcps => {
match prompt_mcps_with_back(&mcp_metadata, &mut step)? {
Some(mcps) => {
config.mcps = mcps;
step = step.next();
}
None => {
// User pressed Esc, step already updated
}
}
}
WizardStep::Done => break,
}
}
info!("Agent wizard completed - generating markdown");
debug!("Agent config: {:?}", config);
// Generate the markdown file (user will edit instructions in the file directly)
let markdown = generate_markdown(&config);
// Determine output path
let filename = sanitize_filename(&config.name);
let output_path = output_dir
.unwrap_or_else(|| PathBuf::from("."))
.join(format!("{}.md", filename));
info!("Writing agent file to: {}", output_path.display());
// Create parent directories if they don't exist
if let Some(parent) = output_path.parent() {
if let Err(e) = tokio::fs::create_dir_all(parent).await {
log::error!("Failed to create directory {}: {}", parent.display(), e);
eprintln!(
"\n❌ Failed to create directory {}: {}\n",
parent.display(),
e
);
eprintln!("Generated markdown:\n");
eprintln!("{}", "─".repeat(60));
eprintln!("{}", markdown);
eprintln!("{}", "─".repeat(60));
anyhow::bail!("Failed to create directory: {}", parent.display());
}
}
if let Err(e) = tokio::fs::write(&output_path, &markdown).await {
log::error!("Failed to write file {}: {}", output_path.display(), e);
eprintln!(
"\n❌ Failed to write file {}: {}\n",
output_path.display(),
e
);
eprintln!("Generated markdown:\n");
eprintln!("{}", "─".repeat(60));
eprintln!("{}", markdown);
eprintln!("{}", "─".repeat(60));
anyhow::bail!("Failed to write file: {}", output_path.display());
}
info!("Agent file created successfully: {}", output_path.display());
println!("\n✅ Agent file created: {}", output_path.display());
println!("\nNext steps:");
println!(" 1. Edit the file to add your agent instructions");
println!(
" 2. Compile with: ado-aw compile {}",
output_path.display()
);
println!(" 3. Commit both the .md and generated .yml files");
Ok(())
}
/// Prompt for repositories with back navigation support
fn prompt_repositories_with_back(
repositories: &mut Vec<RepositoryConfig>,
step: &mut WizardStep,
) -> Result<bool> {
let prompt = Confirm::new("Add additional repositories?")
.with_default(false)
.with_help_message(
"Configure extra repositories for the agent to checkout (Esc to go back)",
)
.prompt();
match prompt {
Ok(false) => Ok(true), // No repos, proceed
Ok(true) => {
// Clear existing repos if re-entering this step
repositories.clear();
loop {
match prompt_repository_with_back() {
Ok(Some(repo)) => {
repositories.push(repo);
let more = Confirm::new("Add another repository?")
.with_default(false)
.prompt()
.unwrap_or(false);
if !more {
break;
}
}
Ok(None) => {
// User cancelled during repo entry, go back to confirm
if repositories.is_empty() {
*step = step.prev();
return Ok(false);
}
// If we have some repos, just stop adding more
break;
}
Err(e) => return Err(e),
}
}
Ok(true)
}
Err(InquireError::OperationCanceled) => {
*step = step.prev();
Ok(false)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Failed to get confirmation"),
}
}
/// Prompt for a single repository with back navigation
fn prompt_repository_with_back() -> Result<Option<RepositoryConfig>> {
let name = match Text::new("Repository name (org/repo):")
.with_help_message("e.g., my-org/my-repo (Esc to cancel)")
.prompt()
{
Ok(n) => n,
Err(InquireError::OperationCanceled) => return Ok(None),
Err(e) => return Err(e).context("Failed to get repository name"),
};
let alias_default = name.split('/').last().unwrap_or(&name);
let alias = Text::new("Alias:")
.with_default(alias_default)
.with_help_message("Short name to reference this repository")
.prompt()
.context("Failed to get alias")?;
let repo_type = Text::new("Type:")
.with_default("git")
.prompt()
.context("Failed to get type")?;
let ref_branch = Text::new("Ref:")
.with_default("refs/heads/main")
.with_help_message("Branch reference")
.prompt()
.context("Failed to get ref")?;
Ok(Some(RepositoryConfig {
alias,
repo_type,
name,
ref_branch,
}))
}
/// Prompt for checkout selection with back navigation
/// Allows user to select which repositories the agent should checkout and work with
fn prompt_checkout_with_back(
repositories: &[RepositoryConfig],
checkout: &mut Vec<String>,
step: &mut WizardStep,
) -> Result<bool> {
// If no repositories configured, skip this step
if repositories.is_empty() {
return Ok(true);
}
let prompt = Confirm::new("Checkout additional repositories?")
.with_default(false)
.with_help_message(
"By default, only 'self' is checked out. Select 'yes' to checkout additional repositories. (Esc to go back)",
)
.prompt();
match prompt {
Ok(false) => {
// No additional repos checked out (only self)
checkout.clear();
Ok(true)
}
Ok(true) => {
// Let user select which repos to checkout
let repo_aliases: Vec<&str> = repositories.iter().map(|r| r.alias.as_str()).collect();
let selected = MultiSelect::new(
"Select repositories to checkout:",
repo_aliases.clone(),
)
.with_help_message(
"Space to select, Enter to confirm. These will be checked out alongside 'self'.",
)
.prompt();
match selected {
Ok(choices) => {
checkout.clear();
checkout.extend(choices.into_iter().map(String::from));
Ok(true)
}
Err(InquireError::OperationCanceled) => {
*step = step.prev();
Ok(false)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Failed to get checkout selection"),
}
}
Err(InquireError::OperationCanceled) => {
*step = step.prev();
Ok(false)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Failed to get confirmation"),
}
}
/// Prompt for schedule with back navigation
fn prompt_schedule_with_back(step: &mut WizardStep) -> Result<Option<Option<String>>> {
let frequency_options = vec![
ScheduleOption {
value: "none",
description: "Manual or trigger-based only",
},
ScheduleOption {
value: "hourly",
description: "Every hour at a scattered minute",
},
ScheduleOption {
value: "every_hours",
description: "Every N hours (2, 3, 4, 6, 8, or 12)",
},
ScheduleOption {
value: "every_minutes",
description: "Every N minutes (5, 10, 15, 30)",
},
ScheduleOption {
value: "daily",
description: "Once per day",
},
ScheduleOption {
value: "weekly",
description: "Once per week",
},
ScheduleOption {
value: "bi-weekly",
description: "Every 14 days",
},
ScheduleOption {
value: "tri-weekly",
description: "Every 21 days",
},
ScheduleOption {
value: "custom",
description: "Enter custom fuzzy schedule expression",
},
];
let prompt = Select::new("Schedule Frequency:", frequency_options)
.with_help_message("How often should this agent run? (Esc to go back)")
.prompt();
match prompt {
Ok(frequency) => {
let schedule = match frequency.value {
"none" => None,
"hourly" => Some("hourly".to_string()),
"every_hours" => prompt_every_hours()?,
"every_minutes" => prompt_every_minutes()?,
"daily" => prompt_daily_schedule()?,
"weekly" => prompt_weekly_schedule()?,
"bi-weekly" => Some("bi-weekly".to_string()),
"tri-weekly" => Some("tri-weekly".to_string()),
"custom" => prompt_custom_schedule()?,
_ => None,
};
Ok(Some(schedule))
}
Err(InquireError::OperationCanceled) => {
*step = step.prev();
Ok(None)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Failed to select schedule frequency"),
}
}
/// Prompt for MCPs with back navigation
fn prompt_mcps_with_back(
metadata: &McpMetadataFile,
step: &mut WizardStep,
) -> Result<Option<Vec<McpSelection>>> {
use std::collections::{HashMap, HashSet};
use terminal_size::{Height, Width, terminal_size};
// Get terminal dimensions for dynamic sizing
let (term_width, term_height) = terminal_size()
.map(|(Width(w), Height(h))| (w as usize, h as usize))
.unwrap_or((80, 24));
let page_size = term_height.saturating_sub(10).max(5).min(30);
let builtin_mcps = metadata.builtin_mcp_names();
let mut all_tools: Vec<McpToolOption> = Vec::new();
for mcp_name in &builtin_mcps {
if let Some(mcp) = metadata.get(mcp_name) {
for tool in &mcp.tools {
all_tools.push(McpToolOption {
mcp_name: mcp_name.to_string(),
tool_name: tool.name.clone(),
description: tool.description.clone().unwrap_or_default(),
max_width: term_width,
});
}
}
}
all_tools.sort_by(|a, b| a.full_name().cmp(&b.full_name()));
let total_tools = all_tools.len();
let total_mcps = builtin_mcps.len();
println!("\n🔧 MCP Tool Selection");
println!("Select tools to enable. Tools are shown as mcp:tool_name.");
println!("Type to search/filter, Space to toggle, Enter to confirm, Esc to go back.");
println!("({} tools across {} MCPs)\n", total_tools, total_mcps);
let prompt = MultiSelect::new("Select tools to enable:", all_tools)
.with_help_message(
"Type to filter (e.g., 'ado:' or 'work_item'), Space to toggle, Enter to confirm",
)
.with_page_size(page_size)
.prompt();
match prompt {
Ok(selected) => {
if selected.is_empty() {
return Ok(Some(Vec::new()));
}
let mut mcp_tools: HashMap<String, HashSet<String>> = HashMap::new();
for tool in selected {
mcp_tools
.entry(tool.mcp_name.clone())
.or_default()
.insert(tool.tool_name);
}
let mut mcp_selections: Vec<McpSelection> = mcp_tools
.into_iter()
.map(|(mcp_name, selected_tools)| {
let total_for_mcp = metadata.get(&mcp_name).map(|m| m.tools.len()).unwrap_or(0);
if selected_tools.len() == total_for_mcp {
McpSelection {
name: mcp_name,
allowed_tools: None,
}
} else {
let mut tools: Vec<String> = selected_tools.into_iter().collect();
tools.sort();
McpSelection {
name: mcp_name,
allowed_tools: Some(tools),
}
}
})
.collect();
mcp_selections.sort_by(|a, b| a.name.cmp(&b.name));
println!("\n📋 Selected {} MCPs:", mcp_selections.len());
for mcp in &mcp_selections {
match &mcp.allowed_tools {
None => println!(" {} (all tools)", mcp.name),
Some(tools) => println!(" {} ({} tools)", mcp.name, tools.len()),
}
}
Ok(Some(mcp_selections))
}
Err(InquireError::OperationCanceled) => {
*step = step.prev();
Ok(None)
}
Err(InquireError::OperationInterrupted) => {
anyhow::bail!("Wizard interrupted");
}
Err(e) => Err(e).context("Failed to select tools"),
}
}
/// Workspace option for display
struct WorkspaceOption {
value: &'static str,
description: &'static str,
}
impl fmt::Display for WorkspaceOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} - {}", self.value, self.description)
}
}
/// Schedule frequency option for display
struct ScheduleOption {
value: &'static str,
description: &'static str,
}
impl fmt::Display for ScheduleOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} - {}", self.value, self.description)
}
}
/// Weekday option for display
struct WeekdayOption {
value: &'static str,
display: &'static str,
}
impl fmt::Display for WeekdayOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.display)
}
}
/// Time constraint option for display
struct TimeConstraintOption {
value: &'static str,
description: &'static str,
}
impl fmt::Display for TimeConstraintOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} - {}", self.value, self.description)
}
}
/// Prompt for "every N hours" schedule
fn prompt_every_hours() -> Result<Option<String>> {
let hour_options = vec!["2", "3", "4", "6", "8", "12"];
let hours = Select::new("Every how many hours?", hour_options)
.with_help_message("Valid intervals that divide evenly into 24")
.prompt()
.context("Failed to select hours")?;
Ok(Some(format!("every {}h", hours)))
}
/// Prompt for "every N minutes" schedule
fn prompt_every_minutes() -> Result<Option<String>> {
let minute_options = vec!["5", "10", "15", "30"];
let minutes = Select::new("Every how many minutes?", minute_options)
.with_help_message("Minimum 5 minutes (platform constraint)")
.prompt()
.context("Failed to select minutes")?;
Ok(Some(format!("every {} minutes", minutes)))
}
/// Prompt for daily schedule with time constraint options
fn prompt_daily_schedule() -> Result<Option<String>> {
let constraint = prompt_time_constraint()?;
match constraint.as_str() {
"" => Ok(Some("daily".to_string())),
c => Ok(Some(format!("daily {}", c))),
}
}
/// Prompt for weekly schedule with day and time constraint options
fn prompt_weekly_schedule() -> Result<Option<String>> {
let weekday_options = vec![
WeekdayOption {
value: "any",
display: "Any day (scattered)",
},
WeekdayOption {
value: "monday",
display: "Monday",
},
WeekdayOption {
value: "tuesday",
display: "Tuesday",
},
WeekdayOption {
value: "wednesday",
display: "Wednesday",
},
WeekdayOption {
value: "thursday",
display: "Thursday",
},
WeekdayOption {
value: "friday",
display: "Friday",
},
WeekdayOption {
value: "saturday",
display: "Saturday",
},
WeekdayOption {
value: "sunday",
display: "Sunday",
},
];
let weekday = Select::new("Which day of the week?", weekday_options)
.with_help_message("Select a specific day or let it scatter across the week")
.prompt()
.context("Failed to select weekday")?;
let constraint = prompt_time_constraint()?;
let schedule = match (weekday.value, constraint.as_str()) {
("any", "") => "weekly".to_string(),
("any", c) => format!("weekly {}", c),
(day, "") => format!("weekly on {}", day),
(day, c) => format!("weekly on {} {}", day, c),
};
Ok(Some(schedule))
}
/// Prompt for time constraint (around/between/none)
fn prompt_time_constraint() -> Result<String> {
let constraint_options = vec![
TimeConstraintOption {
value: "none",
description: "Scattered across the full period",
},
TimeConstraintOption {
value: "around",
description: "Around a specific time (±60 minutes)",
},
TimeConstraintOption {
value: "between",
description: "Between two times (e.g., business hours)",
},
];
let constraint = Select::new("Time constraint:", constraint_options)
.with_help_message("Optionally constrain when the agent runs")
.prompt()
.context("Failed to select time constraint")?;
match constraint.value {
"none" => Ok(String::new()),
"around" => {
let time = Text::new("Around what time?")
.with_help_message("e.g., 14:00, 3pm, noon, midnight")
.prompt()
.context("Failed to get time")?;
let timezone = prompt_optional_timezone()?;
Ok(format!("around {}{}", time, timezone))
}
"between" => {
let start = Text::new("Start time:")
.with_help_message("e.g., 9:00, 9am")
.prompt()
.context("Failed to get start time")?;
let end = Text::new("End time:")
.with_help_message("e.g., 17:00, 5pm")
.prompt()
.context("Failed to get end time")?;
let timezone = prompt_optional_timezone()?;
Ok(format!(
"between {}{} and {}{}",
start, timezone, end, timezone
))
}
_ => Ok(String::new()),
}
}
/// Prompt for optional timezone offset
fn prompt_optional_timezone() -> Result<String> {
let add_tz = Confirm::new("Add timezone offset?")
.with_default(false)
.with_help_message("Specify a UTC offset (e.g., utc+9 for JST, utc-5 for EST)")
.prompt()
.context("Failed to get timezone confirmation")?;
if add_tz {
let tz = Text::new("UTC offset:")
.with_help_message("e.g., utc+9, utc-5, utc+05:30")
.prompt()
.context("Failed to get timezone")?;
Ok(format!(" {}", tz))
} else {
Ok(String::new())
}
}
/// Prompt for custom fuzzy schedule expression
fn prompt_custom_schedule() -> Result<Option<String>> {
println!("\n📚 Fuzzy Schedule Syntax Examples:");
println!(" daily - Scattered across full day");
println!(" daily around 14:00 - Within ±60 min of 2 PM");
println!(" daily between 9:00 and 17:00 - Business hours");
println!(" weekly on monday - Every Monday, scattered time");
println!(" weekly on friday around 17:00 - Friday evenings");
println!(" hourly - Every hour");
println!(" every 6h - Every 6 hours");
println!(" every 15 minutes - Every 15 minutes");
println!(" bi-weekly - Every 14 days");
println!(" daily around 14:00 utc+9 - With timezone offset\n");
let schedule = Text::new("Enter schedule expression:")
.with_help_message("See examples above or refer to fuzzy schedule documentation")
.prompt()
.context("Failed to get custom schedule")?;
if schedule.trim().is_empty() {
Ok(None)
} else {
Ok(Some(schedule))
}
}
/// MCP tool option for flat list display (mcp:tool format)
struct McpToolOption {
mcp_name: String,
tool_name: String,
description: String,
/// Maximum width for the display (set based on terminal width)
max_width: usize,
}
impl McpToolOption {
fn full_name(&self) -> String {
format!("{}:{}", self.mcp_name, self.tool_name)
}
}
impl fmt::Display for McpToolOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let full_name = self.full_name();
if self.description.is_empty() {
write!(f, "{}", full_name)
} else {
// Calculate available space for description
// Format is: "mcp:tool_name: description"
// Account for ": " separator (2 chars) and margin for inquire's UI
let prefix_len = full_name.len() + 2;
let margin = 6; // Space for checkbox, cursor, and padding
let available = self.max_width.saturating_sub(prefix_len + margin);
if available < 10 {
// Not enough space for description, just show the name
write!(f, "{}", full_name)
} else {
let desc = if self.description.len() > available {
format!("{}...", &self.description[..available.saturating_sub(3)])
} else {
self.description.clone()
};
write!(f, "{}: {}", full_name, desc)
}
}
}
}
/// Generate the markdown file content from the configuration
fn generate_markdown(config: &AgentConfig) -> String {
let mut yaml_parts = Vec::new();
// Name and description
yaml_parts.push(format!("name: \"{}\"", escape_yaml_string(&config.name)));
yaml_parts.push(format!(
"description: \"{}\"",
escape_yaml_string(&config.description)
));
// Engine (only if not default)
if config.model != "claude-opus-4.5" {
yaml_parts.push(format!("engine: {}", config.model));
}
// Schedule
if let Some(ref schedule) = config.schedule {
yaml_parts.push(format!("schedule: {}", schedule));
}
// Branch (only if set)
if let Some(ref branch) = config.branch {
yaml_parts.push(format!("branch: {}", branch));
}
// Workspace (only if not default)
if config.workspace != "root" {
yaml_parts.push(format!("workspace: {}", config.workspace));
}
// Repositories
if !config.repositories.is_empty() {
yaml_parts.push("repositories:".to_string());
for repo in &config.repositories {
yaml_parts.push(format!(" - repository: {}", repo.alias));
yaml_parts.push(format!(" type: {}", repo.repo_type));
yaml_parts.push(format!(" name: {}", repo.name));
if repo.ref_branch != "refs/heads/main" {
yaml_parts.push(format!(" ref: {}", repo.ref_branch));
}
}
}
// Checkout (only if not all repos)
if !config.checkout.is_empty() {
yaml_parts.push("checkout:".to_string());
for alias in &config.checkout {
yaml_parts.push(format!(" - {}", alias));
}