-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathmod.rs
More file actions
4065 lines (3814 loc) · 181 KB
/
Copy pathmod.rs
File metadata and controls
4065 lines (3814 loc) · 181 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
pub mod cli;
mod command;
mod consts;
mod context;
mod conversation_state;
mod hooks;
mod input_source;
pub mod mcp;
mod message;
mod parse;
mod parser;
mod prompt;
mod server_messenger;
#[cfg(unix)]
mod skim_integration;
mod token_counter;
mod tool_manager;
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,
};
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 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 rand::distr::{
Alphanumeric,
SampleString,
};
use regex::Regex;
use serde_json::Map;
use spinners::{
Spinner,
Spinners,
};
use thiserror::Error;
use token_counter::{
TokenCount,
TokenCounter,
};
use tokio::signal::ctrl_c;
use tool_manager::{
GetPromptError,
McpServerConfig,
PromptBundle,
ToolManager,
ToolManagerBuilder,
};
use tools::gh_issue::GhIssueContext;
use tools::{
OutputKind,
QueuedTool,
Tool,
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,
region_check,
};
use uuid::Uuid;
use winnow::Partial;
use winnow::stream::Offset;
use crate::api_client::StreamingClient;
use crate::api_client::clients::SendMessageOutput;
use crate::api_client::model::{
ChatResponseStream,
Tool as FigTool,
ToolResultStatus,
};
use crate::database::Database;
use crate::database::settings::Setting;
use crate::mcp_client::{
Prompt,
PromptGetResult,
};
use crate::platform::Context;
use crate::telemetry::TelemetryThread;
use crate::telemetry::core::ToolUseEventBuilder;
use crate::util::CHAT_BINARY_NAME;
/// 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>"};
const ROTATING_TIPS: [&str; 11] = [
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."},
];
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>/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>/import</em> <black!>Import conversation state from a JSON file</black!>
<em>/export</em> <black!>Export conversation state to a JSON file</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!>
"};
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 = " ↳ ";
pub async fn launch_chat(database: &mut Database, telemetry: &TelemetryThread, args: cli::Chat) -> Result<ExitCode> {
let trust_tools = args.trust_tools.map(|mut tools| {
if tools.len() == 1 && tools[0].is_empty() {
tools.pop();
}
tools
});
chat(
database,
telemetry,
args.input,
args.no_interactive,
args.accept_all,
args.profile,
args.trust_all_tools,
trust_tools,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn chat(
database: &mut Database,
telemetry: &TelemetryThread,
input: Option<String>,
no_interactive: bool,
accept_all: bool,
profile: Option<String>,
trust_all_tools: bool,
trust_tools: Option<Vec<String>>,
) -> Result<ExitCode> {
if !crate::util::system_info::in_cloudshell() && !crate::auth::is_logged_in(database).await {
bail!(
"You are not logged in, please log in with {}",
format!("{CHAT_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 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(&mut output).await {
Ok(config) => {
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"
)
)?;
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) = 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
},
}
}
let conversation_id = Alphanumeric.sample_string(&mut rand::rng(), 9);
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).await?;
let mut tool_permissions = ToolPermissions::new(tool_config.len());
if accept_all || 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 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,
client,
|| terminal::window_size().map(|s| s.columns.into()).ok(),
tool_manager,
profile,
tool_config,
tool_permissions,
)
.await?;
let result = chat.try_chat(database, telemetry).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] crate::api_client::ApiClientError),
#[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),
}
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,
client: StreamingClient,
terminal_width_provider: fn() -> Option<usize>,
tool_manager: ToolManager,
profile: 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 conversation_state = match std::env::current_dir()
.ok()
.and_then(|cwd| database.get_conversation_by_path(cwd).ok())
.flatten()
{
Some(mut prior) => {
existing_conversation = true;
prior
.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()));
prior.tool_manager = tool_manager;
prior
},
None => {
ConversationState::new(
ctx_clone,
conversation_id,
tool_config,
profile,
Some(output_clone),
tool_manager,
)
.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 current_tip_index = database.get_increment_rotating_tip().unwrap_or(0) % ROTATING_TIPS.len();
let tip = ROTATING_TIPS[current_tip_index];
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 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().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, 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, 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,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: Some(tool_uses_clone) })
}
},
ChatState::ValidateTools(tool_uses) => {
tokio::select! {
res = self.validate_tools(telemetry, tool_uses) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: None })
}
},
ChatState::HandleResponseStream(response) => tokio::select! {
res = self.handle_response(database, telemetry, response) => res,
Ok(_) = ctrl_c_stream => Err(ChatError::Interrupted { tool_uses: None })
},
ChatState::Exit => return Ok(()),
};
next_state = Some(self.handle_state_execution_result(database, result).await?);
}
}
/// Handles the result of processing a [ChatState], returning the next [ChatState] to change
/// to.
async fn handle_state_execution_result(
&mut self,
database: &mut Database,
result: Result<ChatState, ChatError>,
) -> Result<ChatState, ChatError> {
// Remove non-ASCII and ANSI characters.
let re = Regex::new(r"((\x9B|\x1B\[)[0-?]*[ -\/]*[@-~])|([^\x00-\x7F]+)").unwrap();
match result {
Ok(state) => Ok(state),
Err(e) => {
macro_rules! print_err {
($prepend_msg:expr, $err:expr) => {{
queue!(
self.output,
style::SetAttribute(Attribute::Bold),
style::SetForegroundColor(Color::Red),
)?;
let report = eyre::Report::from($err);
let text = re
.replace_all(&format!("{}: {:?}\n", $prepend_msg, report), "")
.into_owned();
queue!(self.output, style::Print(&text),)?;
self.conversation_state.append_transcript(text);
execute!(
self.output,
style::SetAttribute(Attribute::Reset),
style::SetForegroundColor(Color::Reset),
)?;
}};
}
macro_rules! print_default_error {
($err:expr) => {
print_err!("Amazon Q is having trouble responding right now", $err);
};
}
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.
match inter {
Some(tool_uses) if !tool_uses.is_empty() => {
self.conversation_state.abandon_tool_use(
tool_uses,
"The user interrupted the tool execution.".to_string(),
);
let _ = self.conversation_state.as_sendable_conversation_state(false).await;
self.conversation_state.push_assistant_message(
AssistantMessage::new_response(
None,
"Tool uses were interrupted, waiting for the next user prompt".to_string(),
),
database,
);
},
_ => (),
}
},
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.
crate::api_client::ApiClientError::ContextWindowOverflow => {
let history_too_small = self
.conversation_state
.backend_conversation_state(false, true)
.await
.history
.len()
< 2;
if history_too_small {
print_err!(
"Your conversation is too large - try reducing the size of
the context being passed",
err
);
return Ok(ChatState::PromptUser {
tool_uses: None,
pending_tool_index: None,
skip_printing_tools: false,
});
}
return Ok(ChatState::CompactHistory {
tool_uses: None,
pending_tool_index: None,
prompt: None,
show_summary: false,
help: false,
});
},
crate::api_client::ApiClientError::QuotaBreach(msg) => {
print_err!(msg, err);
},
_ => {
print_default_error!(err);
},
},
_ => {
print_default_error!(e);
},
}
self.conversation_state.enforce_conversation_invariants();
self.conversation_state.reset_next_user_message();
Ok(ChatState::PromptUser {
tool_uses: None,
pending_tool_index: None,
skip_printing_tools: false,
})
},
}
}
/// 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,
telemetry: &TelemetryThread,
tool_uses: Option<Vec<QueuedTool>>,
pending_tool_index: Option<usize>,
custom_prompt: Option<String>,
show_summary: bool,
help: bool,