-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathmod.rs
More file actions
4829 lines (4515 loc) · 214 KB
/
Copy pathmod.rs
File metadata and controls
4829 lines (4515 loc) · 214 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 command;
mod consts;
mod context;
mod conversation_state;
mod hooks;
mod input_source;
mod message;
mod parse;
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::{
IsTerminal,
Read,
Write,
};
use std::process::{
Command as ProcessCommand,
ExitCode,
};
use std::sync::Arc;
use std::time::Duration;
use std::{
env,
fs,
io,
};
use amzn_codewhisperer_client::types::SubscriptionStatus;
use clap::Args;
use command::{
Command,
PromptsSubcommand,
ToolsSubcommand,
};
use consts::{
CONTEXT_FILES_MAX_SIZE,
CONTEXT_WINDOW_SIZE,
DUMMY_TOOL_NAME,
};
use context::ContextManager;
pub use conversation_state::ConversationState;
use conversation_state::TokenWarningLevel;
use crossterm::style::{
Attribute,
Color,
Stylize,
};
use crossterm::{
cursor,
execute,
queue,
style,
terminal,
};
use dialoguer::{
Error as DError,
Select,
};
use eyre::{
ErrReport,
Result,
bail,
};
use hooks::{
Hook,
HookTrigger,
};
use input_source::InputSource;
use message::{
AssistantMessage,
AssistantToolUse,
ToolUseResult,
ToolUseResultBlock,
};
use parse::{
ParseState,
interpret_markdown,
};
use parser::{
RecvErrorKind,
ResponseParser,
};
use regex::Regex;
use serde_json::Map;
use spinners::{
Spinner,
Spinners,
};
use thiserror::Error;
use time::OffsetDateTime;
use token_counter::{
TokenCount,
TokenCounter,
};
use tokio::signal::ctrl_c;
use tool_manager::{
GetPromptError,
LoadingRecord,
McpServerConfig,
PromptBundle,
ToolManager,
ToolManagerBuilder,
};
use tools::gh_issue::GhIssueContext;
use tools::{
OutputKind,
QueuedTool,
Tool,
ToolOrigin,
ToolPermissions,
ToolSpec,
};
use tracing::{
debug,
error,
info,
trace,
warn,
};
use unicode_width::UnicodeWidthStr;
use util::images::RichImageBlock;
use util::shared_writer::{
NullWriter,
SharedWriter,
};
use util::ui::draw_box;
use util::{
animate_output,
drop_matched_context_files,
play_notification_bell,
};
use uuid::Uuid;
use winnow::Partial;
use winnow::stream::Offset;
use crate::api_client::clients::SendMessageOutput;
use crate::api_client::model::{
ChatResponseStream,
Tool as FigTool,
ToolResultStatus,
};
use crate::api_client::{
ApiClientError,
Client,
StreamingClient,
};
use crate::auth::AuthError;
use crate::auth::builder_id::is_idc_user;
use crate::database::Database;
use crate::database::settings::Setting;
use crate::mcp_client::{
Prompt,
PromptGetResult,
};
use crate::platform::Context;
use crate::telemetry::core::ToolUseEventBuilder;
use crate::telemetry::{
ReasonCode,
TelemetryResult,
TelemetryThread,
get_error_reason,
};
use crate::util::system_info::is_remote;
#[derive(Debug, Clone, PartialEq, Eq, Default, Args)]
pub struct ChatArgs {
/// (Deprecated, use --trust-all-tools) Enabling this flag allows the model to execute
/// all commands without first accepting them.
#[arg(short, long, hide = true)]
pub accept_all: bool,
/// Print the first response to STDOUT without interactive mode. This will fail if the
/// prompt requests permissions to use a tool, unless --trust-all-tools is also used.
#[arg(long)]
pub no_interactive: bool,
/// Resumes the previous conversation from this directory.
#[arg(short, long)]
pub resume: bool,
/// The first question to ask
pub input: Option<String>,
/// 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>>,
/// Additional MCP configuration files (paths separated by OS path separator)
#[arg(
long,
value_delimiter = if cfg!(windows) { ';' } else { ':' },
value_name = "PATHS"
)]
pub mcp_config_paths: Option<Vec<String>>,
}
impl ChatArgs {
pub async fn execute(self, database: &mut Database, telemetry: &TelemetryThread) -> Result<ExitCode> {
let ctx = Context::new();
let stdin = std::io::stdin();
// no_interactive flag or part of a pipe
let interactive = !self.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 = self.input.unwrap_or_default();
stdin.lock().read_to_string(&mut input)?;
Some(input)
} else {
self.input
};
let mut output = match interactive {
true => SharedWriter::stderr(),
false => SharedWriter::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(database).await?,
};
let mcp_server_configs = match McpServerConfig::load_config(&ctx, &mut output, self.mcp_config_paths.as_deref())
.await
{
Ok(config) => {
if interactive && !database.settings.get_bool(Setting::McpLoadedBefore).unwrap_or(false) {
execute!(
output,
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"
)
)?;
}
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(Arc::clone(&ctx), None).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
},
}
}
// 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
};
// if let Some(ref id) = model_id {
// database.set_last_used_model_id(id.clone())?;
// }
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 tool_manager_output: Box<dyn Write + Send + Sync + 'static> = if interactive {
Box::new(output.clone())
} else {
Box::new(NullWriter {})
};
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)
.interactive(interactive)
.build(telemetry, tool_manager_output)
.await?;
let tool_config = tool_manager.load_tools(database, &mut output).await?;
let mut tool_permissions = ToolPermissions::new(tool_config.len());
let trust_tools = self.trust_tools.map(|mut tools| {
if tools.len() == 1 && tools[0].is_empty() {
tools.pop();
}
tools
});
if self.accept_all || self.trust_all_tools {
tool_permissions.trust_all = true;
for tool in tool_config.values() {
tool_permissions.trust_tool(&tool.name);
}
// Deprecation notice for --accept-all users
if self.accept_all && interactive {
queue!(
output,
style::SetForegroundColor(Color::Yellow),
style::Print("\n--accept-all, -a is deprecated. Use --trust-all-tools instead."),
style::SetForegroundColor(Color::Reset),
)?;
}
} else if let Some(trusted) = trust_tools.map(|vec| vec.into_iter().collect::<HashSet<_>>()) {
// --trust-all-tools takes precedence over --trust-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);
}
}
}
let mut chat = ChatContext::new(
ctx,
database,
&conversation_id,
output,
input,
InputSource::new(database, prompt_request_sender, prompt_response_receiver)?,
interactive,
self.resume,
client,
|| terminal::window_size().map(|s| s.columns.into()).ok(),
tool_manager,
self.profile,
model_id,
tool_config,
tool_permissions,
)
.await?;
let result = chat.try_chat(database, telemetry).await.map(|_| ExitCode::SUCCESS);
drop(chat); // Explicit drop for clarity
result
}
}
/// Help text for the compact command
fn compact_help_text() -> String {
color_print::cformat!(
r#"
<magenta,em>Conversation Compaction</magenta,em>
The <em>/compact</em> command summarizes the conversation history to free up context space
while preserving essential information. This is useful for long-running conversations
that may eventually reach memory constraints.
<cyan!>Usage</cyan!>
<em>/compact</em> <black!>Summarize the conversation and clear history</black!>
<em>/compact [prompt]</em> <black!>Provide custom guidance for summarization</black!>
<cyan!>When to use</cyan!>
• When you see the memory constraint warning message
• When a conversation has been running for a long time
• Before starting a new topic within the same session
• After completing complex tool operations
<cyan!>How it works</cyan!>
• Creates an AI-generated summary of your conversation
• Retains key information, code, and tool executions in the summary
• Clears the conversation history to free up space
• The assistant will reference the summary context in future responses
"#
)
}
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; 2] = [
// 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."},
];
pub struct ModelOption {
pub name: &'static str,
pub model_id: &'static str,
}
pub const MODEL_OPTIONS: [ModelOption; 3] = [
ModelOption {
name: "claude-4-sonnet",
model_id: "CLAUDE_SONNET_4_20250514_V1_0",
},
ModelOption {
name: "claude-3.7-sonnet",
model_id: "CLAUDE_3_7_SONNET_20250219_V1_0",
},
ModelOption {
name: "claude-3.5-sonnet",
model_id: "CLAUDE_3_5_SONNET_20241022_V2_0",
},
];
pub const DEFAULT_MODEL_ID: &str = "CLAUDE_3_7_SONNET_20250219_V1_0";
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 <em>•</em> <green!>ctrl + s</green!> fuzzy search</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
</black!>"};
const HELP_TEXT: &str = color_print::cstr! {"
<magenta,em>q</magenta,em> (Amazon Q Chat)
<cyan,em>Commands:</cyan,em>
<em>/clear</em> <black!>Clear the conversation history</black!>
<em>/issue</em> <black!>Report an issue or make a feature request</black!>
<em>/editor</em> <black!>Open $EDITOR (defaults to vi) to compose a prompt</black!>
<em>/help</em> <black!>Show this help dialogue</black!>
<em>/quit</em> <black!>Quit the application</black!>
<em>/compact</em> <black!>Summarize the conversation to free up context space</black!>
<em>help</em> <black!>Show help for the compact command</black!>
<em>[prompt]</em> <black!>Optional custom prompt to guide summarization</black!>
<em>/tools</em> <black!>View and manage tools and permissions</black!>
<em>help</em> <black!>Show an explanation for the trust command</black!>
<em>trust</em> <black!>Trust a specific tool or tools for the session</black!>
<em>untrust</em> <black!>Revert a tool or tools to per-request confirmation</black!>
<em>trustall</em> <black!>Trust all tools (equivalent to deprecated /acceptall)</black!>
<em>reset</em> <black!>Reset all tools to default permission levels</black!>
<em>/mcp</em> <black!>See mcp server loaded</black!>
<em>/model</em> <black!>Select a model for the current conversation session</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>/prompts</em> <black!>View and retrieve prompts</black!>
<em>help</em> <black!>Show prompts help</black!>
<em>list</em> <black!>List or search available prompts</black!>
<em>get</em> <black!>Retrieve and send a prompt</black!>
<em>/context</em> <black!>Manage context files and hooks for the chat session</black!>
<em>help</em> <black!>Show context help</black!>
<em>show</em> <black!>Display current context rules 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>hooks</em> <black!>View and manage context hooks</black!>
<em>/usage</em> <black!>Show current session's context window usage</black!>
<em>/load</em> <black!>Load conversation state from a JSON file</black!>
<em>/save</em> <black!>Save conversation state to a JSON file</black!>
<em>/subscribe</em> <black!>Upgrade to a Q Developer Pro subscription for increased query limits</black!>
<em>[--manage]</em> <black!>View and manage your existing subscription on AWS</black!>
<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!>
"};
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 SUBSCRIBE_TITLE_TEXT: &str = color_print::cstr! { "<white!,bold>Subscribe to Q Developer Pro</white!,bold>" };
const SUBSCRIBE_TEXT: &str = color_print::cstr! { "During the upgrade, you'll be asked to link your Builder ID to the AWS account that will be billed the monthly subscription fee.
Need help? Visit our subscription support page> <blue!>https://docs.aws.amazon.com/console/amazonq/upgrade-builder-id</blue!>" };
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." };
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(#[from] crate::api_client::ApiClientError),
#[error("{0}")]
Auth(#[from] AuthError),
#[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 --trust-all-tools to automatically approve tools."
)]
NonInteractiveToolApproval,
#[error(transparent)]
GetPromptError(#[from] GetPromptError),
}
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::NonInteractiveToolApproval => "NonInteractiveToolApprovalError".to_string(),
ChatError::GetPromptError(_) => "GetPromptError".to_string(),
ChatError::Auth(_) => "AuthError".to_string(),
}
}
}
pub struct ChatContext {
ctx: Arc<Context>,
/// The [Write] destination for printing conversation text.
output: SharedWriter,
initial_input: Option<String>,
/// Whether we're starting a new conversation or continuing an old one.
existing_conversation: bool,
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,
/// 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>,
}
impl ChatContext {
#[allow(clippy::too_many_arguments)]
pub async fn new(
ctx: Arc<Context>,
database: &mut Database,
conversation_id: &str,
output: SharedWriter,
mut input: Option<String>,
input_source: InputSource,
interactive: bool,
resume_conversation: bool,
client: StreamingClient,
terminal_width_provider: fn() -> Option<usize>,
tool_manager: ToolManager,
profile: Option<String>,
model_id: Option<String>,
tool_config: HashMap<String, ToolSpec>,
tool_permissions: ToolPermissions,
) -> Result<Self> {
let ctx_clone = Arc::clone(&ctx);
let output_clone = output.clone();
let mut existing_conversation = false;
let valid_model_id = match model_id {
Some(id) => Some(id),
None => 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())
})
.or_else(|| Some(DEFAULT_MODEL_ID.to_owned())),
};
let conversation_state = if resume_conversation {
let prior = std::env::current_dir()
.ok()
.and_then(|cwd| database.get_conversation_by_path(cwd).ok())
.flatten();
// Only restore conversations where there were actual messages.
// Prevents edge case where user clears conversation with --new, then exits without chatting.
if prior.as_ref().is_some_and(|cs| !cs.history().is_empty()) {
let mut cs = prior.unwrap();
existing_conversation = true;
cs.reload_serialized_state(Arc::clone(&ctx), Some(output.clone())).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
} else {
ConversationState::new(
ctx_clone,
conversation_id,
tool_config,
profile,
Some(output_clone),
tool_manager,
valid_model_id,
)
.await
}
} else {
ConversationState::new(
ctx_clone,
conversation_id,
tool_config,
profile,
Some(output_clone),
tool_manager,
valid_model_id,
)
.await
};
Ok(Self {
ctx,
output,
initial_input: input,
existing_conversation,
input_source,
interactive,
client,
terminal_width_provider,
spinner: None,
tool_permissions,
conversation_state,
tool_use_telemetry_events: HashMap::new(),
tool_use_status: ToolUseStatus::Idle,
failed_request_ids: Vec::new(),
pending_prompts: VecDeque::new(),
})
}
}
impl Drop for ChatContext {
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();
}
}
/// 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>>,
/// Tracks the next tool in tool_uses that needs user acceptance.
pending_tool_index: Option<usize>,
/// 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,
tool_uses: Option<Vec<QueuedTool>>,
pending_tool_index: Option<usize>,
},
/// Validate the list of tool uses provided by the model.
ValidateTools(Vec<AssistantToolUse>),
/// Execute the list of tools.
ExecuteTools(Vec<QueuedTool>),
/// Consume the response stream and display to the user.
HandleResponseStream(SendMessageOutput),
/// Compact the chat history.
CompactHistory {
tool_uses: Option<Vec<QueuedTool>>,
pending_tool_index: Option<usize>,
/// 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,
/// Whether or not to show the /compact help text.
help: bool,
},
/// Exit the chat.
Exit,
}
impl Default for ChatState {
fn default() -> Self {
Self::PromptUser {
tool_uses: None,
pending_tool_index: None,
skip_printing_tools: false,
}
}
}
impl ChatContext {
/// Opens the user's preferred editor to compose a prompt
fn open_editor(initial_text: Option<String>) -> Result<String, ChatError> {
// Create a temporary file with a unique name
let temp_dir = std::env::temp_dir();
let file_name = format!("q_prompt_{}.md", Uuid::new_v4());
let temp_file_path = temp_dir.join(file_name);
// Get the editor from environment variable or use a default
let editor_cmd = env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
// Parse the editor command to handle arguments
let mut parts =
shlex::split(&editor_cmd).ok_or_else(|| ChatError::Custom("Failed to parse EDITOR command".into()))?;
if parts.is_empty() {
return Err(ChatError::Custom("EDITOR environment variable is empty".into()));
}
let editor_bin = parts.remove(0);
// Write initial content to the file if provided
let initial_content = initial_text.unwrap_or_default();
fs::write(&temp_file_path, &initial_content)
.map_err(|e| ChatError::Custom(format!("Failed to create temporary file: {}", e).into()))?;
// Open the editor with the parsed command and arguments
let mut cmd = ProcessCommand::new(editor_bin);
// Add any arguments that were part of the EDITOR variable
for arg in parts {
cmd.arg(arg);
}
// Add the file path as the last argument
let status = cmd
.arg(&temp_file_path)
.status()
.map_err(|e| ChatError::Custom(format!("Failed to open editor: {}", e).into()))?;
if !status.success() {
return Err(ChatError::Custom("Editor exited with non-zero status".into()));
}
// Read the content back
let content = fs::read_to_string(&temp_file_path)
.map_err(|e| ChatError::Custom(format!("Failed to read temporary file: {}", e).into()))?;
// Clean up the temporary file
let _ = fs::remove_file(&temp_file_path);
Ok(content.trim().to_string())
}
async fn try_chat(&mut self, database: &mut Database, telemetry: &TelemetryThread) -> Result<()> {
let is_small_screen = self.terminal_width() < GREETING_BREAK_POINT;
if self.interactive && 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.output, 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.output,
style::Print("💡 ".to_string()),
style::Print(tip),
style::Print("\n")
)?;
} else {
draw_box(
self.output.clone(),
"Did you know?",
tip,
GREETING_BREAK_POINT,
Color::DarkGrey,
)?;
}
execute!(
self.output,
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.output, style::Print("\n"), style::SetForegroundColor(Color::Reset))?;
}
if self.interactive && self.all_tools_trusted() {
queue!(
self.output,
style::Print(format!(
"{}{TRUST_ALL_TEXT}\n\n",
if !is_small_screen { "\n" } else { "" }
))
)?;
}
self.output.flush()?;
let mut next_state = Some(ChatState::PromptUser {
tool_uses: None,
pending_tool_index: None,
skip_printing_tools: true,
});
if self.interactive {
if let Some(ref id) = self.conversation_state.model {
if let Some(model_option) = MODEL_OPTIONS.iter().find(|option| option.model_id == *id) {
execute!(
self.output,
style::SetForegroundColor(Color::Cyan),
style::Print(format!("🤖 You are chatting with {}\n", model_option.name)),
style::SetForegroundColor(Color::Reset),
style::Print("\n")
)
.expect("Failed to write model information to terminal");
}
}
}
if let Some(user_input) = self.initial_input.take() {
next_state = Some(ChatState::HandleInput {
input: user_input,
tool_uses: None,
pending_tool_index: None,
});
}
loop {
debug_assert!(next_state.is_some());
let chat_state = next_state.take().unwrap_or_default();
let ctrl_c_stream = ctrl_c();
debug!(?chat_state, "changing to state");
// Update conversation state with new tool information
self.conversation_state.update_state(false).await;
let result = match chat_state {
ChatState::PromptUser {
tool_uses,
pending_tool_index,
skip_printing_tools,
} => {
// Cannot prompt in non-interactive mode no matter what.
if !self.interactive {
return Ok(());
}
self.prompt_user(database, tool_uses, pending_tool_index, skip_printing_tools)
.await
},
ChatState::HandleInput {
input,
tool_uses,
pending_tool_index,
} => {
let tool_uses_clone = tool_uses.clone();
tokio::select! {
res = self.handle_input(telemetry, database, input, tool_uses, pending_tool_index) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: tool_uses_clone })
}
},
ChatState::CompactHistory {
tool_uses,
pending_tool_index,
prompt,
show_summary,
help,
} => {
let tool_uses_clone = tool_uses.clone();
tokio::select! {
res = self.compact_history(telemetry, database, tool_uses, pending_tool_index, prompt, show_summary, help) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: tool_uses_clone })
}
},
ChatState::ExecuteTools(tool_uses) => {
let tool_uses_clone = tool_uses.clone();
tokio::select! {
res = self.tool_use_execute(database, telemetry, tool_uses) => res,