forked from aws/amazon-q-developer-cli-autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
2663 lines (2453 loc) · 103 KB
/
Copy pathmod.rs
File metadata and controls
2663 lines (2453 loc) · 103 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
mod cli;
mod consts;
mod context;
mod conversation;
mod error_formatter;
mod input_source;
mod message;
mod parse;
use std::path::MAIN_SEPARATOR;
mod parser;
mod prompt;
mod prompt_parser;
mod server_messenger;
#[cfg(unix)]
mod skim_integration;
mod token_counter;
pub mod tool_manager;
pub mod tools;
pub mod util;
use std::borrow::Cow;
use std::collections::{
HashMap,
HashSet,
VecDeque,
};
use std::io::Write;
use std::process::ExitCode;
use std::time::Duration;
use amzn_codewhisperer_client::types::SubscriptionStatus;
use clap::{
Args,
CommandFactory,
Parser,
};
use context::ContextManager;
pub use conversation::ConversationState;
use conversation::TokenWarningLevel;
use crossterm::style::{
Attribute,
Color,
Stylize,
};
use crossterm::{
cursor,
execute,
queue,
style,
terminal,
};
use eyre::{
Report,
Result,
bail,
eyre,
};
use input_source::InputSource;
use message::{
AssistantMessage,
AssistantToolUse,
ToolUseResult,
ToolUseResultBlock,
};
use parse::{
ParseState,
interpret_markdown,
};
use parser::{
RecvErrorKind,
ResponseParser,
};
use regex::Regex;
use spinners::{
Spinner,
Spinners,
};
use thiserror::Error;
use time::OffsetDateTime;
use token_counter::TokenCounter;
use tokio::signal::ctrl_c;
use tool_manager::{
McpServerConfig,
ToolManager,
ToolManagerBuilder,
};
use tools::gh_issue::GhIssueContext;
use tools::{
OutputKind,
QueuedTool,
Tool,
ToolPermissions,
ToolSpec,
};
use tracing::{
debug,
error,
info,
trace,
warn,
};
use util::images::RichImageBlock;
use util::ui::draw_box;
use util::{
animate_output,
play_notification_bell,
};
use winnow::Partial;
use winnow::stream::Offset;
use crate::api_client::ApiClientError;
use crate::api_client::model::{
Tool as FigTool,
ToolResultStatus,
};
use crate::api_client::send_message_output::SendMessageOutput;
use crate::auth::AuthError;
use crate::auth::builder_id::is_idc_user;
use crate::cli::chat::cli::SlashCommand;
use crate::cli::chat::cli::model::{
MODEL_OPTIONS,
default_model_id,
};
use crate::cli::chat::cli::prompts::{
GetPromptError,
PromptsSubcommand,
};
use crate::database::settings::Setting;
use crate::mcp_client::Prompt;
use crate::os::Os;
use crate::telemetry::core::ToolUseEventBuilder;
use crate::telemetry::{
ReasonCode,
TelemetryResult,
get_error_reason,
};
const LIMIT_REACHED_TEXT: &str = color_print::cstr! { "You've used all your free requests for this month. You have two options:
1. Upgrade to a paid subscription for increased limits. See our Pricing page for what's included> <blue!>https://aws.amazon.com/q/developer/pricing/</blue!>
2. Wait until next month when your limit automatically resets." };
pub const EXTRA_HELP: &str = color_print::cstr! {"
<cyan,em>MCP:</cyan,em>
<black!>You can now configure the Amazon Q CLI to use MCP servers. \nLearn how: https://docs.aws.amazon.com/en_us/amazonq/latest/qdeveloper-ug/command-line-mcp.html</black!>
<cyan,em>Tips:</cyan,em>
<em>!{command}</em> <black!>Quickly execute a command in your current session</black!>
<em>Ctrl(^) + j</em> <black!>Insert new-line to provide multi-line prompt. Alternatively, [Alt(⌥) + Enter(⏎)]</black!>
<em>Ctrl(^) + s</em> <black!>Fuzzy search commands and context files. Use Tab to select multiple items.</black!>
<black!>Change the keybind to ctrl+x with: q settings chat.skimCommandKey x (where x is any key)</black!>
<em>chat.editMode</em> <black!>Set editing mode (vim or emacs) using: q settings chat.editMode vi/emacs</black!>
"};
#[derive(Debug, Clone, PartialEq, Eq, Default, Args)]
pub struct ChatArgs {
/// Resumes the previous conversation from this directory.
#[arg(short, long)]
pub resume: bool,
/// Context profile to use
#[arg(long = "profile")]
pub profile: Option<String>,
/// Current model to use
#[arg(long = "model")]
pub model: Option<String>,
/// Allows the model to use any tool to run commands without asking for confirmation.
#[arg(long)]
pub trust_all_tools: bool,
/// Trust only this set of tools. Example: trust some tools:
/// '--trust-tools=fs_read,fs_write', trust no tools: '--trust-tools='
#[arg(long, value_delimiter = ',', value_name = "TOOL_NAMES")]
pub trust_tools: Option<Vec<String>>,
/// Whether the command should run without expecting user input
#[arg(long, alias = "no-interactive")]
pub non_interactive: bool,
/// The first question to ask
pub input: Option<String>,
}
impl ChatArgs {
pub async fn execute(self, os: &mut Os) -> Result<ExitCode> {
if self.non_interactive && self.input.is_none() {
bail!("Input must be supplied when running in non-interactive mode");
}
let stdout = std::io::stdout();
let mut stderr = std::io::stderr();
let mcp_server_configs = match McpServerConfig::load_config(&mut stderr).await {
Ok(config) => {
if !os.database.settings.get_bool(Setting::McpLoadedBefore).unwrap_or(false) {
execute!(
stderr,
style::Print(
"To learn more about MCP safety, see https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-mcp-security.html\n\n"
)
)?;
}
os.database.settings.set(Setting::McpLoadedBefore, true).await?;
config
},
Err(e) => {
warn!("No mcp server config loaded: {}", e);
McpServerConfig::default()
},
};
// If profile is specified, verify it exists before starting the chat
if let Some(ref profile_name) = self.profile {
// Create a temporary context manager to check if the profile exists
match ContextManager::new(os, None).await {
Ok(context_manager) => {
let profiles = context_manager.list_profiles(os).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
},
}
}
// If modelId is specified, verify it exists before starting the chat
let model_id: Option<String> = if let Some(model_name) = self.model {
let model_name_lower = model_name.to_lowercase();
match MODEL_OPTIONS.iter().find(|opt| opt.name == model_name_lower) {
Some(opt) => Some((opt.model_id).to_string()),
None => {
let available_names: Vec<&str> = MODEL_OPTIONS.iter().map(|opt| opt.name).collect();
bail!(
"Model '{}' does not exist. Available models: {}",
model_name,
available_names.join(", ")
);
},
}
} else {
None
};
let conversation_id = uuid::Uuid::new_v4().to_string();
info!(?conversation_id, "Generated new conversation id");
let (prompt_request_sender, prompt_request_receiver) = std::sync::mpsc::channel::<Option<String>>();
let (prompt_response_sender, prompt_response_receiver) = std::sync::mpsc::channel::<Vec<String>>();
let mut tool_manager = ToolManagerBuilder::default()
.mcp_server_config(mcp_server_configs)
.prompt_list_sender(prompt_response_sender)
.prompt_list_receiver(prompt_request_receiver)
.conversation_id(&conversation_id)
.build(os, Box::new(std::io::stderr()), !self.non_interactive)
.await?;
let tool_config = tool_manager.load_tools(os, &mut stderr).await?;
let mut tool_permissions = ToolPermissions::new(tool_config.len());
if self.trust_all_tools {
tool_permissions.trust_all = true;
for tool in tool_config.values() {
tool_permissions.trust_tool(&tool.name);
}
} else if let Some(trusted) = self.trust_tools.map(|vec| vec.into_iter().collect::<HashSet<_>>()) {
// --trust-all-tools takes precedence over --trust-tools=...
for tool_name in &trusted {
if !tool_name.is_empty() {
// Store the original trust settings for later use with MCP tools
tool_permissions.add_pending_trust_tool(tool_name.clone());
}
}
// Apply to currently known tools
for tool in tool_config.values() {
if trusted.contains(&tool.name) {
tool_permissions.trust_tool(&tool.name);
} else {
tool_permissions.untrust_tool(&tool.name);
}
}
} else {
// CLI args has precendence over Database config
tool_permissions.trust_from_database(&os.database);
}
ChatSession::new(
os,
stdout,
stderr,
&conversation_id,
self.input,
InputSource::new(os, prompt_request_sender, prompt_response_receiver)?,
self.resume,
|| terminal::window_size().map(|s| s.columns.into()).ok(),
tool_manager,
self.profile,
model_id,
tool_config,
tool_permissions,
!self.non_interactive,
)
.await?
.spawn(os)
.await
.map(|_| ExitCode::SUCCESS)
}
}
const WELCOME_TEXT: &str = color_print::cstr! {"<cyan!>
⢠⣶⣶⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣶⣿⣿⣿⣶⣦⡀⠀
⠀⠀⠀⣾⡿⢻⣿⡆⠀⠀⠀⢀⣄⡄⢀⣠⣤⣤⡀⢀⣠⣤⣤⡀⠀⠀⢀⣠⣤⣤⣤⣄⠀⠀⢀⣤⣤⣤⣤⣤⣤⡀⠀⠀⣀⣤⣤⣤⣀⠀⠀⠀⢠⣤⡀⣀⣤⣤⣄⡀⠀⠀⠀⠀⠀⠀⢠⣿⣿⠋⠀⠀⠀⠙⣿⣿⡆
⠀⠀⣼⣿⠇⠀⣿⣿⡄⠀⠀⢸⣿⣿⠛⠉⠻⣿⣿⠛⠉⠛⣿⣿⠀⠀⠘⠛⠉⠉⠻⣿⣧⠀⠈⠛⠛⠛⣻⣿⡿⠀⢀⣾⣿⠛⠉⠻⣿⣷⡀⠀⢸⣿⡟⠛⠉⢻⣿⣷⠀⠀⠀⠀⠀⠀⣼⣿⡏⠀⠀⠀⠀⠀⢸⣿⣿
⠀⢰⣿⣿⣤⣤⣼⣿⣷⠀⠀⢸⣿⣿⠀⠀⠀⣿⣿⠀⠀⠀⣿⣿⠀⠀⢀⣴⣶⣶⣶⣿⣿⠀⠀⠀⣠⣾⡿⠋⠀⠀⢸⣿⣿⠀⠀⠀⣿⣿⡇⠀⢸⣿⡇⠀⠀⢸⣿⣿⠀⠀⠀⠀⠀⠀⢹⣿⣇⠀⠀⠀⠀⠀⢸⣿⡿
⢀⣿⣿⠋⠉⠉⠉⢻⣿⣇⠀⢸⣿⣿⠀⠀⠀⣿⣿⠀⠀⠀⣿⣿⠀⠀⣿⣿⡀⠀⣠⣿⣿⠀⢀⣴⣿⣋⣀⣀⣀⡀⠘⣿⣿⣄⣀⣠⣿⣿⠃⠀⢸⣿⡇⠀⠀⢸⣿⣿⠀⠀⠀⠀⠀⠀⠈⢿⣿⣦⣀⣀⣀⣴⣿⡿⠃
⠚⠛⠋⠀⠀⠀⠀⠘⠛⠛⠀⠘⠛⠛⠀⠀⠀⠛⠛⠀⠀⠀⠛⠛⠀⠀⠙⠻⠿⠟⠋⠛⠛⠀⠘⠛⠛⠛⠛⠛⠛⠃⠀⠈⠛⠿⠿⠿⠛⠁⠀⠀⠘⠛⠃⠀⠀⠘⠛⠛⠀⠀⠀⠀⠀⠀⠀⠀⠙⠛⠿⢿⣿⣿⣋⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠛⠿⢿⡧</cyan!>"};
const SMALL_SCREEN_WELCOME_TEXT: &str = color_print::cstr! {"<em>Welcome to <cyan!>Amazon Q</cyan!>!</em>"};
const RESUME_TEXT: &str = color_print::cstr! {"<em>Picking up where we left off...</em>"};
// Only show the model-related tip for now to make users aware of this feature.
const ROTATING_TIPS: [&str; 16] = [
color_print::cstr! {"You can resume the last conversation from your current directory by launching with
<green!>q chat --resume</green!>"},
color_print::cstr! {"Get notified whenever Q CLI finishes responding.
Just run <green!>q settings chat.enableNotifications true</green!>"},
color_print::cstr! {"You can use
<green!>/editor</green!> to edit your prompt with a vim-like experience"},
color_print::cstr! {"<green!>/usage</green!> shows you a visual breakdown of your current context window usage"},
color_print::cstr! {"Get notified whenever Q CLI finishes responding. Just run <green!>q settings
chat.enableNotifications true</green!>"},
color_print::cstr! {"You can execute bash commands by typing
<green!>!</green!> followed by the command"},
color_print::cstr! {"Q can use tools without asking for
confirmation every time. Give <green!>/tools trust</green!> a try"},
color_print::cstr! {"You can
programmatically inject context to your prompts by using hooks. Check out <green!>/context hooks
help</green!>"},
color_print::cstr! {"You can use <green!>/compact</green!> to replace the conversation
history with its summary to free up the context space"},
color_print::cstr! {"If you want to file an issue
to the Q CLI team, just tell me, or run <green!>q issue</green!>"},
color_print::cstr! {"You can enable
custom tools with <green!>MCP servers</green!>. Learn more with /help"},
color_print::cstr! {"You can
specify wait time (in ms) for mcp server loading with <green!>q settings mcp.initTimeout {timeout in
int}</green!>. Servers that takes longer than the specified time will continue to load in the background. Use
/tools to see pending servers."},
color_print::cstr! {"You can see the server load status as well as any
warnings or errors associated with <green!>/mcp</green!>"},
color_print::cstr! {"Use <green!>/model</green!> to select the model to use for this conversation"},
color_print::cstr! {"Set a default model by running <green!>q settings chat.defaultModel MODEL</green!>. Run <green!>/model</green!> to learn more."},
color_print::cstr! {"Run <green!>/prompts</green!> to learn how to build & run repeatable workflows"},
];
const GREETING_BREAK_POINT: usize = 80;
const POPULAR_SHORTCUTS: &str = color_print::cstr! {
"<black!><green!>/help</green!> all commands <em>•</em> <green!>ctrl + j</green!> new lines
<green!>ctrl + s</green!> fuzzy search <em>•</em> <green!>ctrl + f</green!> accept completion</black!>"};
const SMALL_SCREEN_POPULAR_SHORTCUTS: &str = color_print::cstr! {"<black!><green!>/help</green!> all commands
<green!>ctrl + j</green!> new lines
<green!>ctrl + s</green!> fuzzy search
<green!>ctrl + f</green!> accept completion
</black!>"};
const RESPONSE_TIMEOUT_CONTENT: &str = "Response timed out - message took too long to generate";
const TRUST_ALL_TEXT: &str = color_print::cstr! {"<green!>All tools are now trusted (<red!>!</red!>). Amazon Q will execute tools <bold>without</bold> asking for confirmation.\
\nAgents can sometimes do unexpected things so understand the risks.</green!>
\nLearn more at https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-chat-security.html#command-line-chat-trustall-safety"};
const TOOL_BULLET: &str = " ● ";
const CONTINUATION_LINE: &str = " ⋮ ";
const PURPOSE_ARROW: &str = " ↳ ";
/// 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(Box<crate::api_client::ApiClientError>),
#[error("{0}")]
Auth(#[from] AuthError),
#[error("{0}")]
ResponseStream(Box<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(transparent)]
GetPromptError(#[from] GetPromptError),
#[error(
"Tool approval required but --no-interactive was specified. Use --trust-all-tools to automatically approve tools."
)]
NonInteractiveToolApproval,
}
impl ChatError {
fn status_code(&self) -> Option<u16> {
match self {
ChatError::Client(e) => e.status_code(),
ChatError::Auth(_) => None,
ChatError::ResponseStream(_) => None,
ChatError::Std(_) => None,
ChatError::Readline(_) => None,
ChatError::Custom(_) => None,
ChatError::Interrupted { .. } => None,
ChatError::GetPromptError(_) => None,
ChatError::NonInteractiveToolApproval => None,
}
}
}
impl ReasonCode for ChatError {
fn reason_code(&self) -> String {
match self {
ChatError::Client(e) => e.reason_code(),
ChatError::ResponseStream(e) => e.reason_code(),
ChatError::Std(_) => "StdIoError".to_string(),
ChatError::Readline(_) => "ReadlineError".to_string(),
ChatError::Custom(_) => "GenericError".to_string(),
ChatError::Interrupted { .. } => "Interrupted".to_string(),
ChatError::GetPromptError(_) => "GetPromptError".to_string(),
ChatError::Auth(_) => "AuthError".to_string(),
ChatError::NonInteractiveToolApproval => "NonInteractiveToolApproval".to_string(),
}
}
}
impl From<ApiClientError> for ChatError {
fn from(value: ApiClientError) -> Self {
Self::Client(Box::new(value))
}
}
impl From<parser::RecvError> for ChatError {
fn from(value: parser::RecvError) -> Self {
Self::ResponseStream(Box::new(value))
}
}
pub struct ChatSession {
/// For output read by humans and machine
pub stdout: std::io::Stdout,
/// For display output, only read by humans
pub stderr: std::io::Stderr,
initial_input: Option<String>,
/// Whether we're starting a new conversation or continuing an old one.
existing_conversation: bool,
input_source: InputSource,
/// Width of the terminal, required for [ParseState].
terminal_width_provider: fn() -> Option<usize>,
spinner: Option<Spinner>,
/// [ConversationState].
conversation: ConversationState,
tool_uses: Vec<QueuedTool>,
pending_tool_index: Option<usize>,
/// State to track tools that need confirmation.
tool_permissions: ToolPermissions,
/// 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,
/// Any failed requests that could be useful for error report/debugging
failed_request_ids: Vec<String>,
/// Pending prompts to be sent
pending_prompts: VecDeque<Prompt>,
interactive: bool,
inner: Option<ChatState>,
}
impl ChatSession {
#[allow(clippy::too_many_arguments)]
pub async fn new(
os: &mut Os,
stdout: std::io::Stdout,
stderr: std::io::Stderr,
conversation_id: &str,
mut input: Option<String>,
input_source: InputSource,
resume_conversation: bool,
terminal_width_provider: fn() -> Option<usize>,
tool_manager: ToolManager,
profile: Option<String>,
model_id: Option<String>,
tool_config: HashMap<String, ToolSpec>,
tool_permissions: ToolPermissions,
interactive: bool,
) -> Result<Self> {
let valid_model_id = model_id
.or_else(|| {
os.database
.settings
.get_string(Setting::ChatDefaultModel)
.and_then(|model_name| {
MODEL_OPTIONS
.iter()
.find(|opt| opt.name == model_name)
.map(|opt| opt.model_id.to_owned())
})
})
.unwrap_or_else(|| default_model_id(os).to_owned());
// Reload prior conversation
let mut existing_conversation = false;
let previous_conversation = std::env::current_dir()
.ok()
.and_then(|cwd| os.database.get_conversation_by_path(cwd).ok())
.flatten();
// Only restore conversations where there were actual messages.
// Prevents edge case where user clears conversation then exits without chatting.
let conversation = match resume_conversation
&& previous_conversation
.as_ref()
.is_some_and(|cs| !cs.history().is_empty())
{
true => {
let mut cs = previous_conversation.unwrap();
existing_conversation = true;
cs.reload_serialized_state(os).await;
input = Some(input.unwrap_or("In a few words, summarize our conversation so far.".to_owned()));
cs.tool_manager = tool_manager;
cs.update_state(true).await;
cs.enforce_tool_use_history_invariants();
cs
},
false => {
ConversationState::new(
os,
conversation_id,
tool_config,
profile,
tool_manager,
Some(valid_model_id),
)
.await
},
};
Ok(Self {
stdout,
stderr,
initial_input: input,
existing_conversation,
input_source,
terminal_width_provider,
spinner: None,
tool_permissions,
conversation,
tool_uses: vec![],
pending_tool_index: None,
tool_use_telemetry_events: HashMap::new(),
tool_use_status: ToolUseStatus::Idle,
failed_request_ids: Vec::new(),
pending_prompts: VecDeque::new(),
interactive,
inner: Some(ChatState::default()),
})
}
pub async fn next(&mut self, os: &mut Os) -> Result<(), ChatError> {
// Update conversation state with new tool information
self.conversation.update_state(false).await;
let ctrl_c_stream = ctrl_c();
let result = match self.inner.take().expect("state must always be Some") {
ChatState::PromptUser { skip_printing_tools } => {
match (self.interactive, self.tool_uses.is_empty()) {
(false, true) => {
self.inner = Some(ChatState::Exit);
return Ok(());
},
(false, false) => {
return Err(ChatError::NonInteractiveToolApproval);
},
_ => (),
};
self.prompt_user(os, skip_printing_tools).await
},
ChatState::HandleInput { input } => {
tokio::select! {
res = self.handle_input(os, input) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: Some(self.tool_uses.clone()) })
}
},
ChatState::CompactHistory { prompt, show_summary } => {
tokio::select! {
res = self.compact_history(os, prompt, show_summary) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: Some(self.tool_uses.clone()) })
}
},
ChatState::ExecuteTools => {
let tool_uses_clone = self.tool_uses.clone();
tokio::select! {
res = self.tool_use_execute(os) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: Some(tool_uses_clone) })
}
},
ChatState::ValidateTools(tool_uses) => {
tokio::select! {
res = self.validate_tools(os, tool_uses) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: None })
}
},
ChatState::HandleResponseStream(response) => tokio::select! {
res = self.handle_response(os, response) => res,
Ok(_) = ctrl_c_stream => {
self.send_chat_telemetry(os, None, TelemetryResult::Cancelled, None, None, None).await;
Err(ChatError::Interrupted { tool_uses: None })
}
},
ChatState::Exit => return Ok(()),
};
let err = match result {
Ok(state) => {
self.inner = Some(state);
return Ok(());
},
Err(err) => err,
};
// We encountered an error. Handle it.
error!(?err, "An error occurred processing the current state");
let (reason, reason_desc) = get_error_reason(&err);
self.send_error_telemetry(os, reason, Some(reason_desc), err.status_code())
.await;
if self.spinner.is_some() {
drop(self.spinner.take());
queue!(
self.stderr,
terminal::Clear(terminal::ClearType::CurrentLine),
cursor::MoveToColumn(0),
)?;
}
let (context, report, display_err_message) = match err {
ChatError::Interrupted { tool_uses: ref inter } => {
execute!(self.stderr, style::Print("\n\n"))?;
// If there was an interrupt during tool execution, then we add fake
// messages to "reset" the chat state.
match inter {
Some(tool_uses) if !tool_uses.is_empty() => {
self.conversation
.abandon_tool_use(tool_uses, "The user interrupted the tool execution.".to_string());
let _ = self
.conversation
.as_sendable_conversation_state(os, &mut self.stderr, false)
.await?;
self.conversation.push_assistant_message(
os,
AssistantMessage::new_response(
None,
"Tool uses were interrupted, waiting for the next user prompt".to_string(),
),
);
},
_ => (),
}
("Tool use was interrupted", Report::from(err), false)
},
ChatError::Client(err) => match *err {
// Errors from attempting to send too large of a conversation history. In
// this case, attempt to automatically compact the history for the user.
ApiClientError::ContextWindowOverflow { .. } => {
if !self.conversation.can_create_summary_request(os).await? {
execute!(
self.stderr,
style::SetForegroundColor(Color::Red),
style::Print("Your conversation is too large to continue.\n"),
style::SetForegroundColor(Color::Reset),
style::Print(format!("• Run {} to analyze your context usage\n", "/usage".green())),
style::Print(format!("• Run {} to reset your conversation state\n", "/clear".green())),
style::SetAttribute(Attribute::Reset),
style::Print("\n\n"),
)?;
self.conversation.reset_next_user_message();
self.inner = Some(ChatState::PromptUser {
skip_printing_tools: false,
});
return Ok(());
}
self.inner = Some(ChatState::CompactHistory {
prompt: None,
show_summary: false,
});
(
"The context window has overflowed, summarizing the history...",
Report::from(err),
true,
)
},
ApiClientError::QuotaBreach { message, .. } => (message, Report::from(err), true),
ApiClientError::ModelOverloadedError { request_id, .. } => {
let err = format!(
"The model you've selected is temporarily unavailable. Please use '/model' to select a different model and try again.{}\n\n",
match request_id {
Some(id) => format!("\n Request ID: {}", id),
None => "".to_owned(),
}
);
self.conversation.append_transcript(err.clone());
("Amazon Q is having trouble responding right now", eyre!(err), true)
},
ApiClientError::MonthlyLimitReached { .. } => {
let subscription_status = get_subscription_status(os).await;
if subscription_status.is_err() {
execute!(
self.stderr,
style::SetForegroundColor(Color::Red),
style::Print(format!(
"Unable to verify subscription status: {}\n\n",
subscription_status.as_ref().err().unwrap()
)),
style::SetForegroundColor(Color::Reset),
)?;
}
execute!(
self.stderr,
style::SetForegroundColor(Color::Yellow),
style::Print("Monthly request limit reached"),
style::SetForegroundColor(Color::Reset),
)?;
let limits_text = format!(
"The limits reset on {:02}/01.",
OffsetDateTime::now_utc().month().next() as u8
);
if subscription_status.is_err()
|| subscription_status.is_ok_and(|s| s == ActualSubscriptionStatus::None)
{
execute!(
self.stderr,
style::Print(format!("\n\n{LIMIT_REACHED_TEXT} {limits_text}")),
style::SetForegroundColor(Color::DarkGrey),
style::Print("\n\nUse "),
style::SetForegroundColor(Color::Green),
style::Print("/subscribe"),
style::SetForegroundColor(Color::DarkGrey),
style::Print(" to upgrade your subscription.\n\n"),
style::SetForegroundColor(Color::Reset),
)?;
} else {
execute!(
self.stderr,
style::SetForegroundColor(Color::Yellow),
style::Print(format!(" - {limits_text}\n\n")),
style::SetForegroundColor(Color::Reset),
)?;
}
self.inner = Some(ChatState::PromptUser {
skip_printing_tools: false,
});
return Ok(());
},
_ => (
"Amazon Q is having trouble responding right now",
Report::from(err),
true,
),
},
_ => (
"Amazon Q is having trouble responding right now",
Report::from(err),
true,
),
};
if display_err_message {
// Remove non-ASCII and ANSI characters.
let re = Regex::new(r"((\x9B|\x1B\[)[0-?]*[ -\/]*[@-~])|([^\x00-\x7F]+)").unwrap();
queue!(
self.stderr,
style::SetAttribute(Attribute::Bold),
style::SetForegroundColor(Color::Red),
)?;
let text = re.replace_all(&format!("{}: {:?}\n", context, report), "").into_owned();
queue!(self.stderr, style::Print(&text),)?;
self.conversation.append_transcript(text);
execute!(
self.stderr,
style::SetAttribute(Attribute::Reset),
style::SetForegroundColor(Color::Reset),
)?;
}
self.conversation.enforce_conversation_invariants();
self.conversation.reset_next_user_message();
self.pending_tool_index = None;
self.inner = Some(ChatState::PromptUser {
skip_printing_tools: false,
});
Ok(())
}
}
impl Drop for ChatSession {
fn drop(&mut self) {
if let Some(spinner) = &mut self.spinner {
spinner.stop();
}
execute!(
self.stderr,
cursor::MoveToColumn(0),
style::SetAttribute(Attribute::Reset),
style::ResetColor,
cursor::Show
)
.ok();
}
}
/// 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.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
enum ChatState {
/// Prompt the user with `tool_uses`, if available.
PromptUser {
/// Used to avoid displaying the tool info at inappropriate times, e.g. after clear or help
/// commands.
skip_printing_tools: bool,
},
/// Handle the user input, depending on if any tools require execution.
HandleInput { input: String },
/// Validate the list of tool uses provided by the model.
ValidateTools(Vec<AssistantToolUse>),
/// Execute the list of tools.
ExecuteTools,
/// Consume the response stream and display to the user.
HandleResponseStream(SendMessageOutput),
/// Compact the chat history.
CompactHistory {
/// Custom prompt to include as part of history compaction.
prompt: Option<String>,
/// Whether or not the summary should be shown on compact success.
show_summary: bool,
},
/// Exit the chat.
Exit,
}
impl Default for ChatState {
fn default() -> Self {
Self::PromptUser {
skip_printing_tools: false,
}
}
}
impl ChatSession {
async fn spawn(&mut self, os: &mut Os) -> Result<()> {
let is_small_screen = self.terminal_width() < GREETING_BREAK_POINT;
if os
.database
.settings
.get_bool(Setting::ChatGreetingEnabled)
.unwrap_or(true)
{
let welcome_text = match self.existing_conversation {
true => RESUME_TEXT,
false => match is_small_screen {
true => SMALL_SCREEN_WELCOME_TEXT,
false => WELCOME_TEXT,
},
};
execute!(self.stderr, style::Print(welcome_text), style::Print("\n\n"),)?;
let tip = ROTATING_TIPS[usize::try_from(rand::random::<u32>()).unwrap_or(0) % ROTATING_TIPS.len()];
if is_small_screen {
// If the screen is small, print the tip in a single line
execute!(
self.stderr,
style::Print("💡 ".to_string()),
style::Print(tip),
style::Print("\n")
)?;
} else {
draw_box(
&mut self.stderr,
"Did you know?",
tip,
GREETING_BREAK_POINT,
Color::DarkGrey,
)?;
}
execute!(
self.stderr,
style::Print("\n"),
style::Print(match is_small_screen {
true => SMALL_SCREEN_POPULAR_SHORTCUTS,
false => POPULAR_SHORTCUTS,
}),
style::Print("\n"),
style::Print(
"━"
.repeat(if is_small_screen { 0 } else { GREETING_BREAK_POINT })
.dark_grey()
)
)?;
execute!(self.stderr, style::Print("\n"), style::SetForegroundColor(Color::Reset))?;
}
if self.all_tools_trusted() {
queue!(
self.stderr,
style::Print(format!(
"{}{TRUST_ALL_TEXT}\n\n",
if !is_small_screen { "\n" } else { "" }
))
)?;
}
self.stderr.flush()?;
if let Some(ref id) = self.conversation.model {
if let Some(model_option) = MODEL_OPTIONS.iter().find(|option| option.model_id == *id) {
execute!(
self.stderr,
style::SetForegroundColor(Color::Cyan),
style::Print(format!("🤖 You are chatting with {}\n", model_option.name)),
style::SetForegroundColor(Color::Reset),
style::Print("\n")
)?;
}
}
if let Some(user_input) = self.initial_input.take() {
self.inner = Some(ChatState::HandleInput { input: user_input });
}
while !matches!(self.inner, Some(ChatState::Exit)) {
self.next(os).await?;
}
Ok(())
}
/// Compacts the conversation history, replacing the history with a summary generated by the
/// model.
///
/// The last two user messages in the history are not included in the compaction process.
async fn compact_history(
&mut self,
os: &Os,
custom_prompt: Option<String>,
show_summary: bool,
) -> Result<ChatState, ChatError> {
let hist = self.conversation.history();
debug!(?hist, "compacting history");
if self.conversation.history().len() < 2 {
execute!(
self.stderr,
style::SetForegroundColor(Color::Yellow),
style::Print("\nConversation too short to compact.\n\n"),
style::SetForegroundColor(Color::Reset)
)?;
return Ok(ChatState::PromptUser {
skip_printing_tools: true,
});