-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathmod.rs
1659 lines (1536 loc) · 67.7 KB
/
mod.rs
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
mod command;
mod context;
mod conversation_state;
mod input_source;
mod parse;
mod parser;
mod prompt;
mod tools;
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::{
IsTerminal,
Read,
Write,
};
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use command::Command;
use context::ContextManager;
use conversation_state::ConversationState;
use crossterm::style::{
Attribute,
Color,
Stylize,
};
use crossterm::{
cursor,
execute,
queue,
style,
terminal,
};
use eyre::{
Result,
bail,
};
use fig_api_client::StreamingClient;
use fig_api_client::clients::SendMessageOutput;
use fig_api_client::model::{
AssistantResponseMessage,
ChatResponseStream,
ToolResult,
ToolResultContentBlock,
ToolResultStatus,
};
use fig_os_shim::Context;
use fig_settings::Settings;
use fig_util::CLI_BINARY_NAME;
use input_source::InputSource;
use parser::{
RecvErrorKind,
ResponseParser,
ToolUse,
};
use regex::Regex;
use serde_json::Map;
use spinners::{
Spinner,
Spinners,
};
use thiserror::Error;
use tokio::signal::unix::{
SignalKind,
signal,
};
use tools::gh_issue::GhIssueContext;
use tools::{
Tool,
ToolSpec,
};
use tracing::{
debug,
error,
trace,
warn,
};
use winnow::Partial;
use winnow::stream::Offset;
use crate::cli::chat::parse::{
ParseState,
interpret_markdown,
};
use crate::util::region_check;
const WELCOME_TEXT: &str = color_print::cstr! {"
<em>Hi, I'm <magenta,em>Amazon Q</magenta,em>. Ask me anything.</em>
<cyan!>Things to try</cyan!>
• Fix the build failures in this project.
• List my s3 buckets in us-west-2.
• Write unit tests for my application.
• Help me understand my git status
<em>/acceptall</em> <black!>Toggles acceptance prompting for the session.</black!>
<em>/issue</em> <black!>Report an issue or make a feature request.</black!>
<em>/profile</em> <black!>(Beta) Manage profiles for the chat session</black!>
<em>/context</em> <black!>(Beta) Manage context files for a profile</black!>
<em>/help</em> <black!>Show the help dialogue</black!>
<em>/quit</em> <black!>Quit the application</black!>
"};
const HELP_TEXT: &str = color_print::cstr! {"
<magenta,em>q</magenta,em> (Amazon Q Chat)
<em>/clear</em> <black!>Clear the conversation history</black!>
<em>/acceptall</em> <black!>Toggles acceptance prompting for the session.</black!>
<em>/issue</em> <black!>Report an issue or make a feature request.</black!>
<em>/help</em> <black!>Show this help dialogue</black!>
<em>/quit</em> <black!>Quit the application</black!>
<em>/profile</em> <black!>Manage profiles</black!>
<em>help</em> <black!>Show profile help</black!>
<em>list</em> <black!>List profiles</black!>
<em>set</em> <black!>Set the current profile</black!>
<em>create</em> <black!>Create a new profile</black!>
<em>delete</em> <black!>Delete a profile</black!>
<em>rename</em> <black!>Rename a profile</black!>
<em>/context</em> <black!>Manage context files for the chat session</black!>
<em>help</em> <black!>Show context help</black!>
<em>show</em> <black!>Display current context configuration [--expand]</black!>
<em>add</em> <black!>Add file(s) to context [--global] [--force]</black!>
<em>rm</em> <black!>Remove file(s) from context [--global]</black!>
<em>clear</em> <black!>Clear all files from current context [--global]</black!>
<em>!{command}</em> <black!>Quickly execute a command in your current session</black!>
"};
pub async fn chat(
input: Option<String>,
no_interactive: bool,
accept_all: bool,
profile: Option<String>,
) -> Result<ExitCode> {
if !fig_util::system_info::in_cloudshell() && !fig_auth::is_logged_in().await {
bail!(
"You are not logged in, please log in with {}",
format!("{CLI_BINARY_NAME} login",).bold()
);
}
region_check("chat")?;
let ctx = Context::new();
let stdin = std::io::stdin();
// no_interactive flag or part of a pipe
let interactive = !no_interactive && stdin.is_terminal();
let input = if !interactive && !stdin.is_terminal() {
// append to input string any extra info that was provided, e.g. via pipe
let mut input = input.unwrap_or_default();
stdin.lock().read_to_string(&mut input)?;
Some(input)
} else {
input
};
let output: Box<dyn Write> = match interactive {
true => Box::new(std::io::stderr()),
false => Box::new(std::io::stdout()),
};
let client = match ctx.env().get("Q_MOCK_CHAT_RESPONSE") {
Ok(json) => create_stream(serde_json::from_str(std::fs::read_to_string(json)?.as_str())?),
_ => StreamingClient::new().await?,
};
// If profile is specified, verify it exists before starting the chat
if let Some(ref profile_name) = profile {
// Create a temporary context manager to check if the profile exists
match ContextManager::new(Arc::clone(&ctx)).await {
Ok(context_manager) => {
let profiles = context_manager.list_profiles().await?;
if !profiles.contains(profile_name) {
bail!(
"Profile '{}' does not exist. Available profiles: {}",
profile_name,
profiles.join(", ")
);
}
},
Err(e) => {
warn!("Failed to initialize context manager to verify profile: {}", e);
// Continue without verification if context manager can't be initialized
},
}
}
let mut chat = ChatContext::new(
ctx,
Settings::new(),
output,
input,
InputSource::new()?,
interactive,
client,
|| terminal::window_size().map(|s| s.columns.into()).ok(),
accept_all,
profile,
)
.await?;
let result = chat.try_chat().await.map(|_| ExitCode::SUCCESS);
drop(chat); // Explicit drop for clarity
result
}
/// Enum used to denote the origin of a tool use event
enum ToolUseStatus {
/// Variant denotes that the tool use event associated with chat context is a direct result of
/// a user request
Idle,
/// Variant denotes that the tool use event associated with the chat context is a result of a
/// retry for one or more previously attempted tool use. The tuple is the utterance id
/// associated with the original user request that necessitated the tool use
RetryInProgress(String),
}
#[derive(Debug, Error)]
pub enum ChatError {
#[error("{0}")]
Client(#[from] fig_api_client::Error),
#[error("{0}")]
ResponseStream(#[from] parser::RecvError),
#[error("{0}")]
Std(#[from] std::io::Error),
#[error("{0}")]
Readline(#[from] rustyline::error::ReadlineError),
#[error("{0}")]
Custom(Cow<'static, str>),
#[error("interrupted")]
Interrupted { tool_uses: Option<Vec<QueuedTool>> },
#[error(
"Tool approval required but --no-interactive was specified. Use --accept-all to automatically approve tools."
)]
NonInteractiveToolApproval,
}
pub struct ChatContext<W: Write> {
ctx: Arc<Context>,
settings: Settings,
/// The [Write] destination for printing conversation text.
output: W,
initial_input: Option<String>,
input_source: InputSource,
interactive: bool,
/// The client to use to interact with the model.
client: StreamingClient,
/// Width of the terminal, required for [ParseState].
terminal_width_provider: fn() -> Option<usize>,
spinner: Option<Spinner>,
/// [ConversationState].
conversation_state: ConversationState,
/// Telemetry events to be sent as part of the conversation.
tool_use_telemetry_events: HashMap<String, ToolUseEventBuilder>,
/// State used to keep track of tool use relation
tool_use_status: ToolUseStatus,
accept_all: bool,
/// Any failed requests that could be useful for error report/debugging
failed_request_ids: Vec<String>,
}
impl<W: Write> ChatContext<W> {
#[allow(clippy::too_many_arguments)]
pub async fn new(
ctx: Arc<Context>,
settings: Settings,
output: W,
input: Option<String>,
input_source: InputSource,
interactive: bool,
client: StreamingClient,
terminal_width_provider: fn() -> Option<usize>,
accept_all: bool,
profile: Option<String>,
) -> Result<Self> {
let ctx_clone = Arc::clone(&ctx);
Ok(Self {
ctx,
settings,
output,
initial_input: input,
input_source,
interactive,
client,
terminal_width_provider,
spinner: None,
conversation_state: ConversationState::new(ctx_clone, load_tools()?, profile).await,
tool_use_telemetry_events: HashMap::new(),
tool_use_status: ToolUseStatus::Idle,
accept_all,
failed_request_ids: Vec::new(),
})
}
}
impl<W: Write> Drop for ChatContext<W> {
fn drop(&mut self) {
if let Some(spinner) = &mut self.spinner {
spinner.stop();
}
if self.interactive {
queue!(
self.output,
cursor::MoveToColumn(0),
style::SetAttribute(Attribute::Reset),
style::ResetColor,
cursor::Show
)
.ok();
}
self.output.flush().ok();
}
}
/// An executable `(tool_use_id, Tool)` tuple.
type QueuedTool = (String, Tool);
/// The chat execution state.
///
/// Intended to provide more robust handling around state transitions while dealing with, e.g.,
/// tool validation, execution, response stream handling, etc.
#[derive(Debug)]
enum ChatState {
/// Prompt the user with `tool_uses`, if available.
PromptUser {
/// Tool uses to present to the user.
tool_uses: Option<Vec<QueuedTool>>,
skip_printing_tools: bool,
},
/// Handle the user input, depending on if any tools require execution.
HandleInput {
input: String,
tool_uses: Option<Vec<QueuedTool>>,
},
/// Validate the list of tool uses provided by the model.
ValidateTools(Vec<ToolUse>),
/// Execute the list of tools.
ExecuteTools(Vec<QueuedTool>),
/// Consume the response stream and display to the user.
HandleResponseStream(SendMessageOutput),
/// Exit the chat.
Exit,
}
impl Default for ChatState {
fn default() -> Self {
Self::PromptUser {
tool_uses: None,
skip_printing_tools: false,
}
}
}
impl<W> ChatContext<W>
where
W: Write,
{
async fn try_chat(&mut self) -> Result<()> {
if self.interactive && self.settings.get_bool_or("chat.greeting.enabled", true) {
execute!(self.output, style::Print(WELCOME_TEXT))?;
}
let mut ctrl_c_stream = signal(SignalKind::interrupt())?;
let mut next_state = Some(ChatState::PromptUser {
tool_uses: None,
skip_printing_tools: true,
});
if let Some(user_input) = self.initial_input.take() {
if self.interactive {
execute!(
self.output,
style::SetForegroundColor(Color::Magenta),
style::Print("> "),
style::SetAttribute(Attribute::Reset),
style::Print(&user_input),
style::Print("\n")
)?;
}
next_state = Some(ChatState::HandleInput {
input: user_input,
tool_uses: None,
});
}
// Remove non-ASCII and ANSI characters.
let re = Regex::new(r"((\x9B|\x1B\[)[0-?]*[ -\/]*[@-~])|([^\x00-\x7F]+)").unwrap();
loop {
debug_assert!(next_state.is_some());
let chat_state = next_state.take().unwrap_or_default();
debug!(?chat_state, "changing to state");
let result = match chat_state {
ChatState::PromptUser {
tool_uses,
skip_printing_tools,
} => {
// Cannot prompt in non-interactive mode no matter what.
if !self.interactive {
return Ok(());
}
self.prompt_user(tool_uses, skip_printing_tools).await
},
ChatState::HandleInput { input, tool_uses } => self.handle_input(input, tool_uses).await,
ChatState::ExecuteTools(tool_uses) => {
let tool_uses_clone = tool_uses.clone();
tokio::select! {
res = self.tool_use_execute(tool_uses) => res,
Some(_) = ctrl_c_stream.recv() => Err(ChatError::Interrupted { tool_uses: Some(tool_uses_clone) })
}
},
ChatState::ValidateTools(tool_uses) => {
tokio::select! {
res = self.validate_tools(tool_uses) => res,
Some(_) = ctrl_c_stream.recv() => Err(ChatError::Interrupted { tool_uses: None })
}
},
ChatState::HandleResponseStream(response) => tokio::select! {
res = self.handle_response(response) => res,
Some(_) = ctrl_c_stream.recv() => Err(ChatError::Interrupted { tool_uses: None })
},
ChatState::Exit => return Ok(()),
};
match result {
Ok(state) => next_state = Some(state),
Err(e) => {
let mut print_error = |output: &mut W,
prepend_msg: &str,
report: Option<eyre::Report>|
-> Result<(), std::io::Error> {
queue!(
output,
style::SetAttribute(Attribute::Bold),
style::SetForegroundColor(Color::Red),
)?;
match report {
Some(report) => {
let text = re
.replace_all(&format!("{}: {:?}\n", prepend_msg, report), "")
.into_owned();
queue!(output, style::Print(&text),)?;
self.conversation_state.append_transcript(text);
},
None => {
queue!(output, style::Print(prepend_msg), style::Print("\n"))?;
self.conversation_state.append_transcript(prepend_msg.to_string());
},
}
execute!(
output,
style::SetAttribute(Attribute::Reset),
style::SetForegroundColor(Color::Reset),
)
};
error!(?e, "An error occurred processing the current state");
if self.interactive && self.spinner.is_some() {
drop(self.spinner.take());
queue!(
self.output,
terminal::Clear(terminal::ClearType::CurrentLine),
cursor::MoveToColumn(0),
)?;
}
match e {
ChatError::Interrupted { tool_uses: inter } => {
execute!(self.output, style::Print("\n\n"))?;
// If there was an interrupt during tool execution, then we add fake
// messages to "reset" the chat state.
if let Some(ref tool_uses) = inter {
self.conversation_state.abandon_tool_use(
tool_uses.clone(),
"The user interrupted the tool execution.".to_string(),
);
let _ = self.conversation_state.as_sendable_conversation_state().await;
self.conversation_state
.push_assistant_message(AssistantResponseMessage {
message_id: None,
content: "Tool uses were interrupted, waiting for the next user prompt"
.to_string(),
tool_uses: None,
});
}
},
ChatError::Client(err) => {
if let fig_api_client::Error::QuotaBreach(msg) = err {
print_error(&mut self.output, msg, None)?;
} else {
print_error(
&mut self.output,
"Amazon Q is having trouble responding right now",
Some(err.into()),
)?;
}
},
_ => {
print_error(
&mut self.output,
"Amazon Q is having trouble responding right now",
Some(e.into()),
)?;
},
}
self.conversation_state.fix_history();
next_state = Some(ChatState::PromptUser {
tool_uses: None,
skip_printing_tools: false,
});
},
}
}
}
/// Read input from the user.
async fn prompt_user(
&mut self,
mut tool_uses: Option<Vec<QueuedTool>>,
skip_printing_tools: bool,
) -> Result<ChatState, ChatError> {
execute!(self.output, cursor::Show)?;
let tool_uses = tool_uses.take().unwrap_or_default();
if !tool_uses.is_empty() && !skip_printing_tools {
self.print_tool_descriptions(&tool_uses).await?;
execute!(
self.output,
style::SetForegroundColor(Color::DarkGrey),
style::Print("\nEnter "),
style::SetForegroundColor(Color::Green),
style::Print("y"),
style::SetForegroundColor(Color::DarkGrey),
style::Print(format!(
" to run {}, otherwise continue chatting.\n\n",
match tool_uses.len() == 1 {
true => "this tool",
false => "these tools",
}
)),
style::SetForegroundColor(Color::Reset),
)?;
}
// Require two consecutive sigint's to exit.
let mut ctrl_c = false;
let user_input = loop {
// Generate prompt based on active context profile
let prompt = prompt::generate_prompt(self.conversation_state.current_profile());
match (self.input_source.read_line(Some(&prompt))?, ctrl_c) {
(Some(line), _) => break line,
(None, false) => {
execute!(
self.output,
style::Print(format!(
"\n(To exit, press Ctrl+C or Ctrl+D again or type {})\n\n",
"/quit".green()
))
)?;
ctrl_c = true;
},
(None, true) => return Ok(ChatState::Exit),
}
};
self.conversation_state.append_user_transcript(&user_input);
Ok(ChatState::HandleInput {
input: user_input,
tool_uses: Some(tool_uses),
})
}
async fn handle_input(
&mut self,
user_input: String,
tool_uses: Option<Vec<QueuedTool>>,
) -> Result<ChatState, ChatError> {
let command_result = Command::parse(&user_input);
if let Err(error_message) = &command_result {
// Display error message for command parsing errors
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError: {}\n\n", error_message)),
style::SetForegroundColor(Color::Reset)
)?;
return Ok(ChatState::PromptUser {
tool_uses,
skip_printing_tools: true,
});
}
let command = command_result.unwrap();
let tool_uses = tool_uses.unwrap_or_default();
Ok(match command {
Command::Ask { prompt } => {
if ["y", "Y"].contains(&prompt.as_str()) && !tool_uses.is_empty() {
return Ok(ChatState::ExecuteTools(tool_uses));
}
self.tool_use_status = ToolUseStatus::Idle;
if self.interactive {
queue!(self.output, style::SetForegroundColor(Color::Magenta))?;
queue!(self.output, style::SetForegroundColor(Color::Reset))?;
queue!(self.output, cursor::Hide)?;
execute!(self.output, style::Print("\n"))?;
self.spinner = Some(Spinner::new(Spinners::Dots, "Thinking...".to_owned()));
}
if tool_uses.is_empty() {
self.conversation_state.append_new_user_message(user_input).await;
} else {
self.conversation_state.abandon_tool_use(tool_uses, user_input);
}
self.send_tool_use_telemetry().await;
ChatState::HandleResponseStream(
self.client
.send_message(self.conversation_state.as_sendable_conversation_state().await)
.await?,
)
},
Command::Execute { command } => {
queue!(self.output, style::Print('\n'))?;
std::process::Command::new("bash").args(["-c", &command]).status().ok();
queue!(self.output, style::Print('\n'))?;
ChatState::PromptUser {
tool_uses: None,
skip_printing_tools: false,
}
},
Command::Clear => {
self.conversation_state.clear();
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print("\nConversation history cleared.\n\n"),
style::SetForegroundColor(Color::Reset)
)?;
ChatState::PromptUser {
tool_uses: None,
skip_printing_tools: true,
}
},
Command::Help => {
execute!(self.output, style::Print(HELP_TEXT))?;
ChatState::PromptUser {
tool_uses: Some(tool_uses),
skip_printing_tools: true,
}
},
Command::Issue { prompt } => {
let input = "I would like to report an issue or make a feature request";
ChatState::HandleInput {
input: if let Some(prompt) = prompt {
format!("{input}: {prompt}")
} else {
input.to_string()
},
tool_uses: Some(tool_uses),
}
},
Command::AcceptAll => {
self.accept_all = !self.accept_all;
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\n{}\n\n", match self.accept_all {
true =>
"Disabled acceptance prompting.\nAgents can sometimes do unexpected things so understand the risks.",
false => "Enabled acceptance prompting. Run again to disable.",
})),
style::SetForegroundColor(Color::Reset)
)?;
ChatState::PromptUser {
tool_uses: Some(tool_uses),
skip_printing_tools: true,
}
},
Command::Quit => ChatState::Exit,
Command::Profile { subcommand } => {
if let Some(context_manager) = &mut self.conversation_state.context_manager {
macro_rules! print_err {
($err:expr) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError: {}\n\n", $err)),
style::SetForegroundColor(Color::Reset)
)?
};
}
match subcommand {
command::ProfileSubcommand::List => {
let profiles = match context_manager.list_profiles().await {
Ok(profiles) => profiles,
Err(e) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError listing profiles: {}\n\n", e)),
style::SetForegroundColor(Color::Reset)
)?;
vec![]
},
};
execute!(self.output, style::Print("\n"))?;
for profile in profiles {
if profile == context_manager.current_profile {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print("* "),
style::Print(&profile),
style::SetForegroundColor(Color::Reset),
style::Print("\n")
)?;
} else {
execute!(
self.output,
style::Print(" "),
style::Print(&profile),
style::Print("\n")
)?;
}
}
execute!(self.output, style::Print("\n"))?;
},
command::ProfileSubcommand::Create { name } => {
match context_manager.create_profile(&name).await {
Ok(_) => {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\nCreated profile: {}\n\n", name)),
style::SetForegroundColor(Color::Reset)
)?;
context_manager
.switch_profile(&name)
.await
.map_err(|e| warn!(?e, "failed to switch to newly created profile"))
.ok();
},
Err(e) => print_err!(e),
}
},
command::ProfileSubcommand::Delete { name } => {
match context_manager.delete_profile(&name).await {
Ok(_) => {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\nDeleted profile: {}\n\n", name)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => print_err!(e),
}
},
command::ProfileSubcommand::Set { name } => match context_manager.switch_profile(&name).await {
Ok(_) => {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\nSwitched to profile: {}\n\n", name)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => print_err!(e),
},
command::ProfileSubcommand::Rename { old_name, new_name } => {
match context_manager.rename_profile(&old_name, &new_name).await {
Ok(_) => {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\nRenamed profile: {} -> {}\n\n", old_name, new_name)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => print_err!(e),
}
},
command::ProfileSubcommand::Help => {
execute!(
self.output,
style::Print("\n"),
style::Print(command::ProfileSubcommand::help_text()),
style::Print("\n")
)?;
},
}
}
ChatState::PromptUser {
tool_uses: Some(tool_uses),
skip_printing_tools: true,
}
},
Command::Context { subcommand } => {
if let Some(context_manager) = &mut self.conversation_state.context_manager {
match subcommand {
command::ContextSubcommand::Show { expand } => {
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\ncurrent profile: {}\n\n", context_manager.current_profile)),
style::SetForegroundColor(Color::Reset)
)?;
// Display global context
execute!(self.output, style::Print("global:\n"))?;
if context_manager.global_config.paths.is_empty() {
execute!(
self.output,
style::SetForegroundColor(Color::DarkGrey),
style::Print(" <none>\n"),
style::SetForegroundColor(Color::Reset)
)?;
} else {
for path in &context_manager.global_config.paths {
execute!(self.output, style::Print(format!(" {}\n", path)))?;
}
}
// Display profile context
execute!(self.output, style::Print("\nprofile:\n"))?;
if context_manager.profile_config.paths.is_empty() {
execute!(
self.output,
style::SetForegroundColor(Color::DarkGrey),
style::Print(" <none>\n\n"),
style::SetForegroundColor(Color::Reset)
)?;
} else {
for path in &context_manager.profile_config.paths {
execute!(self.output, style::Print(format!(" {}\n", path)))?;
}
execute!(self.output, style::Print("\n"))?;
}
match context_manager.get_context_files(false).await {
Ok(context_files) => {
if context_files.is_empty() {
execute!(
self.output,
style::SetForegroundColor(Color::DarkGrey),
style::Print("No files matched the configured context paths.\n\n"),
style::SetForegroundColor(Color::Reset)
)?;
} else if expand {
// Show expanded file list when expand flag is set
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("Expanded files ({}):\n", context_files.len())),
style::SetForegroundColor(Color::Reset)
)?;
for (filename, _) in context_files {
execute!(self.output, style::Print(format!(" {}\n", filename)))?;
}
execute!(self.output, style::Print("\n"))?;
} else {
// Just show the count when expand flag is not set
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!(
"Number of context files in use: {}\n",
context_files.len()
)),
style::SetForegroundColor(Color::Reset)
)?;
}
},
Err(e) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("Error retrieving context files: {}\n\n", e)),
style::SetForegroundColor(Color::Reset)
)?;
},
}
},
command::ContextSubcommand::Add { global, force, paths } => {
match context_manager.add_paths(paths.clone(), global, force).await {
Ok(_) => {
let target = if global { "global" } else { "profile" };
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!(
"\nAdded {} path(s) to {} context.\n\n",
paths.len(),
target
)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError: {}\n\n", e)),
style::SetForegroundColor(Color::Reset)
)?;
},
}
},
command::ContextSubcommand::Remove { global, paths } => {
match context_manager.remove_paths(paths.clone(), global).await {
Ok(_) => {
let target = if global { "global" } else { "profile" };
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!(
"\nRemoved {} path(s) from {} context.\n\n",
paths.len(),
target
)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError: {}\n\n", e)),
style::SetForegroundColor(Color::Reset)
)?;
},
}
},
command::ContextSubcommand::Clear { global } => match context_manager.clear(global).await {
Ok(_) => {
let target = if global {
"global".to_string()
} else {
format!("profile '{}'", context_manager.current_profile)
};
execute!(
self.output,
style::SetForegroundColor(Color::Green),
style::Print(format!("\nCleared context for {}\n\n", target)),
style::SetForegroundColor(Color::Reset)
)?;
},
Err(e) => {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print(format!("\nError: {}\n\n", e)),
style::SetForegroundColor(Color::Reset)
)?;
},
},
command::ContextSubcommand::Help => {
execute!(
self.output,
style::Print("\n"),
style::Print(command::ContextSubcommand::help_text()),
style::Print("\n")
)?;
},
}
// fig_telemetry::send_context_command_executed
} else {
execute!(
self.output,
style::SetForegroundColor(Color::Red),
style::Print("\nContext management is not available.\n\n"),
style::SetForegroundColor(Color::Reset)