-
Notifications
You must be signed in to change notification settings - Fork 24
/
shell.go
2129 lines (1814 loc) · 61.4 KB
/
shell.go
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
package butterfish
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode"
"github.com/bakks/butterfish/prompt"
"github.com/bakks/butterfish/util"
"github.com/sashabaranov/go-openai/jsonschema"
"github.com/bakks/tiktoken-go"
"github.com/mitchellh/go-ps"
"golang.org/x/term"
)
// The default models to use for autosuggest and prompt generation
// These are the models that are used if we can't find the given model
// in Tiktoken
// These models are used specifically for counting tokens to pack into
// the prompt context
const DEFAULT_AUTOSUGGEST_ENCODER = "gpt-3.5-turbo-instruct"
const DEFAULT_PROMPT_ENCODER = "gpt-4-turbo"
const ESC_CUP = "\x1b[6n" // Request the cursor position
const ESC_UP = "\x1b[%dA"
const ESC_RIGHT = "\x1b[%dC"
const ESC_LEFT = "\x1b[%dD"
const ESC_CLEAR = "\x1b[0K"
const CLEAR_COLOR = "\x1b[0m"
// Special characters that we wrap the shell's command prompt in (PS1) so
// that we can detect where it starts and ends.
const PROMPT_PREFIX = "\033Q"
const PROMPT_SUFFIX = "\033R"
const PROMPT_PREFIX_ESCAPED = "\\033Q"
const PROMPT_SUFFIX_ESCAPED = "\\033R"
const EMOJI_DEFAULT = "🐠"
const EMOJI_GOAL = "🟦"
const EMOJI_GOAL_UNSAFE = "⚡"
var ps1Regex = regexp.MustCompile(" ([0-9]+)" + PROMPT_SUFFIX)
var ps1FullRegex = regexp.MustCompile(EMOJI_DEFAULT + " ([0-9]+)" + PROMPT_SUFFIX)
var DarkShellColorScheme = &ShellColorScheme{
Prompt: "\x1b[38;5;154m",
PromptGoal: "\x1b[38;5;200m",
PromptGoalUnsafe: "\x1b[38;5;9m",
Command: "\x1b[0m",
Autosuggest: "\x1b[38;5;241m",
Answer: "\x1b[38;5;221m",
AnswerHighlight: "\x1b[38;5;204m",
GoalMode: "\x1b[38;5;51m",
Error: "\x1b[38;5;196m",
}
var LightShellColorScheme = &ShellColorScheme{
Prompt: "\x1b[38;5;28m",
PromptGoal: "\x1b[38;5;200m",
PromptGoalUnsafe: "\x1b[38;5;9m",
Command: "\x1b[0m",
Autosuggest: "\x1b[38;5;241m",
Answer: "\x1b[38;5;221m",
AnswerHighlight: "\x1b[38;5;204m",
GoalMode: "\x1b[38;5;18m",
Error: "\x1b[38;5;196m",
}
func RunShell(ctx context.Context, config *ButterfishConfig) error {
envVars := []string{"BUTTERFISH_SHELL=1"}
ptmx, ptyCleanup, err := ptyCommand(ctx, envVars, []string{config.ShellBinary})
if err != nil {
return err
}
defer ptyCleanup()
bf, err := NewButterfish(ctx, config)
if err != nil {
return err
}
//fmt.Println("Starting butterfish shell")
bf.ShellMultiplexer(ptmx, ptmx, os.Stdin, os.Stdout)
return nil
}
const (
historyTypePrompt = iota
historyTypeShellInput
historyTypeShellOutput
historyTypeLLMOutput
historyTypeFunctionOutput
historyTypeToolOutput
)
// Turn history type enum to a string
func HistoryTypeToString(historyType int) string {
switch historyType {
case historyTypePrompt:
return "Prompt"
case historyTypeShellInput:
return "Shell Input"
case historyTypeShellOutput:
return "Shell Output"
case historyTypeLLMOutput:
return "LLM Output"
case historyTypeFunctionOutput:
return "Function Output"
default:
return "Unknown"
}
}
type Tokenization struct {
InputLength int // the unprocessed length of the pretokenized plus truncated content
NumTokens int // number of tokens in the data
Data string // tokenized and truncated content
}
// HistoryBuffer keeps a content buffer, plus an enum of the type of content
// (user prompt, shell output, etc), plus a cache of tokenizations of the
// content. Tokenizations are cached for specific encodings, for example
// newer models use a different encoding than older models.
type HistoryBuffer struct {
Type int
Content *ShellBuffer
FunctionName string
FunctionParams string
// This is to cache tokenization plus truncation of the content
// It maps from encoding name to the tokenization of the output
Tokenizations map[string]Tokenization
}
func (this *HistoryBuffer) SetTokenization(encoding string, inputLength int, numTokens int, data string) {
if this.Tokenizations == nil {
this.Tokenizations = make(map[string]Tokenization)
}
this.Tokenizations[encoding] = Tokenization{
InputLength: inputLength,
NumTokens: numTokens,
Data: data,
}
}
func (this *HistoryBuffer) GetTokenization(encoding string, length int) (string, int, bool) {
if this.Tokenizations == nil {
this.Tokenizations = make(map[string]Tokenization)
}
tokenization, ok := this.Tokenizations[encoding]
if !ok {
return "", 0, false
}
if tokenization.InputLength != length {
return "", 0, false
}
return tokenization.Data, tokenization.NumTokens, true
}
// ShellHistory keeps a record of past shell history and LLM interaction in
// a slice of HistoryBuffer objects. You can add a new block, append to
// the last block, and get the the last n bytes of the history as an array of
// HistoryBlocks.
type ShellHistory struct {
Blocks []*HistoryBuffer
mutex sync.Mutex
}
func NewShellHistory() *ShellHistory {
return &ShellHistory{
Blocks: make([]*HistoryBuffer, 0),
}
}
func (this *ShellHistory) add(historyType int, block string) {
buffer := NewShellBuffer()
buffer.Write(block)
this.Blocks = append(this.Blocks, &HistoryBuffer{
Type: historyType,
Content: buffer,
})
}
func (this *ShellHistory) Append(historyType int, data string) {
this.mutex.Lock()
defer this.mutex.Unlock()
// if data is empty, we don't want to add a new block
if len(data) == 0 {
return
}
numBlocks := len(this.Blocks)
// if we have a block already, and it matches the type, append to it
if numBlocks > 0 {
lastBlock := this.Blocks[numBlocks-1]
if lastBlock.Type == historyType {
lastBlock.Content.Write(data)
return
}
}
// if the history type doesn't match we fall through and add a new block
this.add(historyType, data)
}
func (this *ShellHistory) AddFunctionCall(name, params string) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.Blocks = append(this.Blocks, &HistoryBuffer{
Type: historyTypeLLMOutput,
FunctionName: name,
FunctionParams: params,
Content: NewShellBuffer(),
})
}
func (this *ShellHistory) AppendFunctionOutput(name, data string) {
this.mutex.Lock()
defer this.mutex.Unlock()
// if data is empty, we don't want to add a new block
if len(data) == 0 {
return
}
numBlocks := len(this.Blocks)
var lastBlock *HistoryBuffer
// if we have a block already, and it matches the type, append to it
if numBlocks > 0 {
lastBlock = this.Blocks[numBlocks-1]
if lastBlock.Type == historyTypeFunctionOutput && lastBlock.FunctionName == name {
lastBlock.Content.Write(data)
return
}
}
// if the history type doesn't match we fall through and add a new block
this.add(historyTypeFunctionOutput, data)
lastBlock = this.Blocks[numBlocks]
lastBlock.FunctionName = name
}
// Go back in history for a certain number of bytes.
func (this *ShellHistory) GetLastNBytes(numBytes int, truncateLength int) []util.HistoryBlock {
this.mutex.Lock()
defer this.mutex.Unlock()
var blocks []util.HistoryBlock
for i := len(this.Blocks) - 1; i >= 0 && numBytes > 0; i-- {
block := this.Blocks[i]
content := sanitizeTTYString(block.Content.String())
if len(content) > truncateLength {
content = content[:truncateLength]
}
if len(content) > numBytes {
break // we don't want a weird partial line so we bail out here
}
blocks = append(blocks, util.HistoryBlock{
Type: block.Type,
Content: content,
})
numBytes -= len(content)
}
// reverse the blocks slice
for i := len(blocks)/2 - 1; i >= 0; i-- {
opp := len(blocks) - 1 - i
blocks[i], blocks[opp] = blocks[opp], blocks[i]
}
return blocks
}
func (this *ShellHistory) IterateBlocks(cb func(block *HistoryBuffer) bool) {
this.mutex.Lock()
defer this.mutex.Unlock()
for i := len(this.Blocks) - 1; i >= 0; i-- {
cont := cb(this.Blocks[i])
if !cont {
break
}
}
}
// This is not thread safe
func (this *ShellHistory) LogRecentHistory() {
blocks := this.GetLastNBytes(2000, 512)
log.Printf("Recent history: =======================================")
builder := strings.Builder{}
for _, block := range blocks {
builder.WriteString(fmt.Sprintf("%s: %s\n", HistoryTypeToString(block.Type), block.Content))
}
log.Printf(builder.String())
log.Printf("=======================================")
}
func HistoryBlocksToString(blocks []util.HistoryBlock) string {
var sb strings.Builder
for i, block := range blocks {
if i > 0 {
sb.WriteString("\n")
}
sb.WriteString(block.Content)
}
return sb.String()
}
const (
stateNormal = iota
stateShell
statePrompting
statePromptResponse
)
var stateNames = []string{
"Normal",
"Shell",
"Prompting",
"PromptResponse",
}
type AutosuggestResult struct {
Command string
Suggestion string
}
type ShellColorScheme struct {
Prompt string
PromptGoal string
PromptGoalUnsafe string
Error string
Command string
Autosuggest string
Answer string
AnswerHighlight string
GoalMode string
}
type ShellState struct {
Butterfish *ButterfishCtx
ParentOut io.Writer
ChildIn io.Writer
Sigwinch chan os.Signal
// set based on model
PromptMaxTokens int
AutosuggestMaxTokens int
// The current state of the shell
State int
GoalMode bool
GoalModeBuffer string
GoalModeGoal string
GoalModeUnsafe bool
ActiveFunction string
PromptSuffixCounter int
ChildOutReader chan *byteMsg
ParentInReader chan *byteMsg
CursorPosChan chan *cursorPosition
PromptOutputChan chan *util.CompletionResponse
PrintErrorChan chan error
AutosuggestChan chan *AutosuggestResult
History *ShellHistory
PromptAnswerWriter io.Writer
StyleWriter *util.StyleCodeblocksWriter
Prompt *ShellBuffer
PromptResponseCancel context.CancelFunc
Command *ShellBuffer
TerminalWidth int
Color *ShellColorScheme
LastTabPassthrough time.Time
parentInBuffer []byte
// these are used to estimate number of tokens
AutosuggestEncoder *tiktoken.Tiktoken
PromptEncoder *tiktoken.Tiktoken
// autosuggest config
AutosuggestEnabled bool
LastAutosuggest string
AutosuggestCtx context.Context
AutosuggestCancel context.CancelFunc
AutosuggestBuffer *ShellBuffer
}
func (this *ShellState) setState(state int) {
if this.State == state {
return
}
if this.Butterfish.Config.Verbose > 1 {
log.Printf("State change: %s -> %s", stateNames[this.State], stateNames[state])
}
this.State = state
}
func clearByteChan(r <-chan *byteMsg, timeout time.Duration) {
// then wait for timeout
target := 2
seen := 0
for {
select {
case <-time.After(timeout):
return
case msg := <-r:
// if msg.Data includes \n we break
if bytes.Contains(msg.Data, []byte("\n")) {
seen++
if seen >= target {
return
}
}
continue
}
}
}
func (this *ShellState) GetCursorPosition() (int, int) {
// send the cursor position request
this.ParentOut.Write([]byte(ESC_CUP))
// we wait 5s, if we haven't gotten a response by then we likely have a bug
timeout := time.After(5000 * time.Millisecond)
var pos *cursorPosition
// the parent in reader watches for these responses, set timeout and
// panic if we don't get a response
select {
case <-timeout:
panic(`Timeout waiting for cursor position response, this means that either:
- Butterfish has frozen due to a bug.
- You're using a terminal emulator that doesn't work well with butterfish.
Please submit an issue to https://github.com/bakks/butterfish.`)
case pos = <-this.CursorPosChan:
}
// it's possible that we have a stale response, so we loop on the channel
// until we get the most recent one
for {
select {
case pos = <-this.CursorPosChan:
continue
default:
return pos.Row, pos.Column
}
}
}
// This sets the PS1 shell variable, which is the prompt that the shell
// displays before each command.
// We need to be able to parse the child shell's prompt to determine where
// it starts, ends, exit code, and allow customization to show the user that
// we're inside butterfish shell. The PS1 is roughly the following:
// PS1 := promptPrefix $PS1 ShellCommandPrompt $? promptSuffix
func (this *ButterfishCtx) SetPS1(childIn io.Writer) {
shell := this.Config.ParseShell()
var ps1 string
switch shell {
case "bash", "sh":
// the \[ and \] are bash-specific and tell bash to not count the enclosed
// characters when calculating the cursor position
ps1 = "PS1=$'\\[%s\\]'$PS1$'%s\\[ $?%s\\] '\n"
case "zsh":
// the %%{ and %%} are zsh-specific and tell zsh to not count the enclosed
// characters when calculating the cursor position
ps1 = "PS1=$'%%{%s%%}'$PS1$'%s%%{ %%?%s%%} '\n"
default:
log.Printf("Unknown shell %s, Butterfish is going to leave the PS1 alone. This means that you won't get a custom prompt in Butterfish, and Butterfish won't be able to parse the exit code of the previous command, used for certain features. Create an issue at https://github.com/bakks/butterfish.", shell)
return
}
promptIcon := ""
if !this.Config.ShellLeavePromptAlone {
promptIcon = EMOJI_DEFAULT
}
fmt.Fprintf(childIn,
ps1,
PROMPT_PREFIX_ESCAPED,
promptIcon,
PROMPT_SUFFIX_ESCAPED)
}
// Given a string of terminal output, identify terminal prompts based on the
// custom PS1 escape sequences we set.
// Returns:
// - The last exit code/status seen in the string (i.e. will be non-zero if
// previous command failed.
// - The number of prompts identified in the string.
// - The string with the special prompt escape sequences removed.
func ParsePS1(data string, regex *regexp.Regexp, currIcon string) (int, int, string) {
matches := regex.FindAllStringSubmatch(data, -1)
if len(matches) == 0 {
return 0, 0, data
}
lastStatus := 0
prompts := 0
for _, match := range matches {
var err error
lastStatus, err = strconv.Atoi(match[1])
if err != nil {
log.Printf("Error parsing PS1 match: %s", err)
}
prompts++
}
// Remove matches of suffix
cleaned := regex.ReplaceAllString(data, currIcon)
// Remove the prefix
cleaned = strings.ReplaceAll(cleaned, PROMPT_PREFIX, "")
return lastStatus, prompts, cleaned
}
func (this *ShellState) ParsePS1(data string) (int, int, string) {
var regex *regexp.Regexp
if this.Butterfish.Config.ShellLeavePromptAlone {
regex = ps1Regex
} else {
regex = ps1FullRegex
}
currIcon := ""
if !this.Butterfish.Config.ShellLeavePromptAlone {
if this.GoalMode {
if this.GoalModeUnsafe {
currIcon = EMOJI_GOAL_UNSAFE
} else {
currIcon = EMOJI_GOAL
}
} else {
currIcon = EMOJI_DEFAULT
}
}
return ParsePS1(data, regex, currIcon)
}
// zsh appears to use this sequence to clear formatting and the rest of the line
// before printing a prompt
var ZSH_CLEAR_REGEX = regexp.MustCompile("^\x1b\\[1m\x1b\\[3m%\x1b\\[23m\x1b\\[1m\x1b\\[0m\x20+\x0d\x20\x0d")
func (this *ShellState) FilterChildOut(data string) bool {
if len(data) > 0 && strings.HasPrefix(data, "\x1b[1m") && ZSH_CLEAR_REGEX.MatchString(data) {
return true
}
return false
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func (this *ButterfishCtx) ShellMultiplexer(
childIn io.Writer, childOut io.Reader,
parentIn io.Reader, parentOut io.Writer) {
this.SetPS1(childIn)
colorScheme := DarkShellColorScheme
if !this.Config.ShellColorDark {
colorScheme = LightShellColorScheme
}
log.Printf("Starting shell multiplexer")
childOutReader := make(chan *byteMsg, 8)
parentInReader := make(chan *byteMsg, 8)
// This is a buffered channel so that we don't block reading input when
// pushing a new position
parentPositionChan := make(chan *cursorPosition, 128)
termWidth, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
panic(err)
}
carriageReturnWriter := util.NewReplaceWriter(parentOut, "\n", "\r\n")
styleCodeblocksWriter := util.NewStyleCodeblocksWriter(carriageReturnWriter,
termWidth, colorScheme.Answer, colorScheme.AnswerHighlight)
sigwinch := make(chan os.Signal, 1)
signal.Notify(sigwinch, syscall.SIGWINCH)
promptMaxTokens := min(
NumTokensForModel(this.Config.ShellPromptModel),
this.Config.ShellMaxPromptTokens)
autoSuggestMaxTokens := min(
NumTokensForModel(this.Config.ShellAutosuggestModel),
this.Config.ShellMaxPromptTokens)
shellState := &ShellState{
Butterfish: this,
ParentOut: parentOut,
ChildIn: childIn,
Sigwinch: sigwinch,
State: stateNormal,
ChildOutReader: childOutReader,
ParentInReader: parentInReader,
CursorPosChan: parentPositionChan,
PrintErrorChan: make(chan error, 8),
History: NewShellHistory(),
PromptOutputChan: make(chan *util.CompletionResponse),
PromptAnswerWriter: styleCodeblocksWriter,
StyleWriter: styleCodeblocksWriter,
Command: NewShellBuffer(),
Prompt: NewShellBuffer(),
TerminalWidth: termWidth,
AutosuggestEnabled: this.Config.ShellAutosuggestEnabled,
AutosuggestChan: make(chan *AutosuggestResult),
Color: colorScheme,
parentInBuffer: []byte{},
PromptMaxTokens: promptMaxTokens,
AutosuggestMaxTokens: autoSuggestMaxTokens,
}
shellState.Prompt.SetTerminalWidth(termWidth)
shellState.Prompt.SetColor(colorScheme.Prompt)
go readerToChannel(childOut, childOutReader)
go readerToChannelWithPosition(parentIn, parentInReader, parentPositionChan)
// clear out any existing output to hide the PS1 export stuff
clearByteChan(childOutReader, 1000*time.Millisecond)
// start
shellState.Mux()
}
func (this *ShellState) Errorf(format string, args ...any) {
this.PrintErrorChan <- fmt.Errorf(format, args...)
}
func (this *ShellState) PrintError(err error) {
this.PrintErrorChan <- err
}
// We're asking GPT to generate bash commands, which can use some escapes
// like \' which aren't valid JSON but are valid bash. This function identifies
// those and adds an extra escape so that the JSON is valid.
func AddDoubleEscapesForJSON(s string) string {
s = strings.ReplaceAll(s, "\\", "\\\\")
return s
}
type CommandParams struct {
Cmd string `json:"cmd"`
}
var commandRegex = regexp.MustCompile("^\\s*\\{\\s*\"cmd\"\\s*:\\s*\"(.*)\"\\s*\\}\\s*$")
// Parse the arguments from the command function returned in a Chat completion.
// We parse this with a regex rather than unmarshalling because the command
// may contain unescaped quotes, which would cause the unmarshal to fail.
func parseCommandParams(params string) (string, error) {
// get cmd value using commandRegex
matches := commandRegex.FindStringSubmatch(params)
if len(matches) != 2 {
return "", fmt.Errorf("Unable to parse command params: %s", params)
}
cmd := matches[1]
// check for an uneven number of quotes
if strings.Count(cmd, "\"")%2 == 1 {
log.Printf("Uneven number of double quotes in command: %s", cmd)
}
if strings.Count(cmd, "'")%2 == 1 {
log.Printf("Uneven number of single quotes in command: %s", cmd)
}
return cmd, nil
}
type UserInputParams struct {
Question string `json:"question"`
}
func parseUserInputParams(params string) (string, error) {
// unmarshal UserInputParams from FunctionParameters
var userInputParams UserInputParams
err := json.Unmarshal([]byte(params), &userInputParams)
return userInputParams.Question, err
}
type FinishParams struct {
Success bool `json:"success"`
}
func parseFinishParams(params string) (bool, error) {
// unmarshal FinishParams from FunctionParameters
var finishParams FinishParams
err := json.Unmarshal([]byte(params), &finishParams)
return finishParams.Success, err
}
// TODO add a diagram of streams here
func (this *ShellState) Mux() {
log.Printf("Started shell mux")
childOutBuffer := []byte{}
for {
select {
case <-this.Butterfish.Ctx.Done():
return
case err := <-this.PrintErrorChan:
log.Printf("Error: %s", err.Error())
this.History.Append(historyTypeShellOutput, err.Error())
fmt.Fprintf(this.ParentOut, "%s%s", this.Color.Error, err.Error())
this.setState(stateNormal)
fmt.Fprintf(this.ChildIn, "\n")
// The CursorPosChan produces cursor positions seen in the parent input,
// which have then been cleaned from the incoming text. If we find a
// position in this case it means that a child process has requested
// the cursor position (rather than butterfish shell), and so we re-add
// the position to the child input. The other case is when we call
// GetCursorPosition(), which blocks this process until we get a valid
// position.
case pos := <-this.CursorPosChan:
fmt.Fprintf(this.ChildIn, "\x1b[%d;%dR", pos.Row, pos.Column)
// the terminal window resized and we got a SIGWINCH
case <-this.Sigwinch:
termWidth, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
log.Printf("Error getting terminal size after SIGWINCH: %s", err)
}
if this.Butterfish.Config.Verbose > 0 {
log.Printf("Got SIGWINCH with new width %d", termWidth)
}
this.TerminalWidth = termWidth
this.Prompt.SetTerminalWidth(termWidth)
this.StyleWriter.SetTerminalWidth(termWidth)
if this.AutosuggestBuffer != nil {
this.AutosuggestBuffer.SetTerminalWidth(termWidth)
}
if this.Command != nil {
this.Command.SetTerminalWidth(termWidth)
}
// We received an autosuggest result from the autosuggest goroutine
case result := <-this.AutosuggestChan:
// request cursor position
_, col := this.GetCursorPosition()
var buffer *ShellBuffer
// figure out which buffer we're autocompleting
switch this.State {
case statePrompting:
buffer = this.Prompt
case stateShell, stateNormal:
buffer = this.Command
case statePromptResponse:
continue
default:
log.Printf("Got autosuggest result in unexpected state %d", this.State)
continue
}
this.ShowAutosuggest(buffer, result, col-1, this.TerminalWidth)
// We got an LLM prompt response, handle the response by adding to history,
// calling functions returned, etc.
case output := <-this.PromptOutputChan:
historyData := output.Completion
if historyData != "" {
this.History.Append(historyTypeLLMOutput, historyData)
}
if output.FunctionName != "" {
this.History.AddFunctionCall(output.FunctionName, output.FunctionParameters)
}
// If there is child output waiting to be printed, print that now
if len(childOutBuffer) > 0 {
this.ParentOut.Write(childOutBuffer)
this.History.Append(historyTypeShellOutput, string(childOutBuffer))
childOutBuffer = []byte{}
}
// Get a new prompt
this.ChildIn.Write([]byte("\n"))
if this.GoalMode {
this.ActiveFunction = output.FunctionName
this.GoalModeFunction(output)
if this.GoalMode {
continue
}
}
this.RequestAutosuggest(0, "")
this.setState(stateNormal)
this.ParentInputLoop([]byte{})
case childOutMsg := <-this.ChildOutReader:
if childOutMsg == nil {
log.Println("Child out reader closed")
this.Butterfish.Cancel()
return
}
if this.Butterfish.Config.Verbose > 2 {
log.Printf("Child out: %x", string(childOutMsg.Data))
}
lastStatus, prompts, childOutStr := this.ParsePS1(string(childOutMsg.Data))
this.PromptSuffixCounter += prompts
if prompts > 0 && this.State == stateNormal && !this.GoalMode {
// If we get a prompt and we're at the start of a command
// then we should request autosuggest
newAutosuggestDelay := this.Butterfish.Config.ShellNewlineAutosuggestTimeout
if newAutosuggestDelay >= 0 {
this.RequestAutosuggest(newAutosuggestDelay, "")
}
}
// If we're actively printing a response we buffer child output
if this.State == statePromptResponse {
// In goal mode we throw it away
if !this.GoalMode {
childOutBuffer = append(childOutBuffer, childOutStr...)
}
continue
}
endOfFunctionCall := false
if this.GoalMode {
this.GoalModeBuffer += childOutStr
if this.PromptSuffixCounter >= 2 {
// this means that since starting to collect command function call
// output, we've seen two prompts, which means the function call
// is done and we can send the response back to the model
endOfFunctionCall = true
}
} else if this.ActiveFunction != "" {
this.ActiveFunction = ""
}
// If we're getting child output while typing in a shell command, this
// could mean the user is paging through old commands, or doing a tab
// completion, or something unknown, so we don't want to add to history.
if this.State != stateShell && !this.FilterChildOut(string(childOutMsg.Data)) {
if this.ActiveFunction != "" {
this.History.AppendFunctionOutput(this.ActiveFunction, childOutStr)
} else {
this.History.Append(historyTypeShellOutput, childOutStr)
}
}
// If the user is in shell mode and presses tab, and we're not doing a
// butterfish autocomplete, then we want to edit the command buffer with
// whatever the shell outputs immediately after tab. We treat stuff
// printed in a 50ms window as part of the tab completion.
var AUTOSUGGEST_TAB_WINDOW = 50 * time.Millisecond
timestamp := time.Now()
if this.State == stateShell {
timeSinceTab := timestamp.Sub(this.LastTabPassthrough)
if timeSinceTab < AUTOSUGGEST_TAB_WINDOW {
if this.Butterfish.Config.Verbose > 1 {
log.Printf("Time since tab: %s, adding to command: %s",
timeSinceTab, childOutStr)
}
this.Command.Write(childOutStr)
this.RefreshAutosuggest([]byte(childOutStr), this.Command, this.Color.Command)
}
}
this.ParentOut.Write([]byte(childOutStr))
if endOfFunctionCall {
// move cursor to the beginning of the line and clear the line
fmt.Fprintf(this.ParentOut, "\r%s", ESC_CLEAR)
var status string
if this.ActiveFunction == "command" {
status = fmt.Sprintf("Exit Code: %d\n", lastStatus)
}
this.GoalModeFunctionResponse(status)
this.ActiveFunction = ""
this.GoalModeBuffer = ""
this.PromptSuffixCounter = 0
}
case parentInMsg := <-this.ParentInReader:
if parentInMsg == nil {
log.Println("Parent in reader closed")
this.Butterfish.Cancel()
return
}
this.ParentInputLoop(parentInMsg.Data)
}
}
}
func (this *ShellState) ParentInputLoop(data []byte) {
if this.Butterfish.Config.Verbose > 2 {
log.Printf("Parent in: %x", data)
}
// include any cached data
if len(this.parentInBuffer) > 0 {
data = append(this.parentInBuffer, data...)
this.parentInBuffer = []byte{}
}
if len(data) == 0 {
return
}
// If we've started an ANSI escape sequence, it might not be complete
// yet, so we need to cache it and wait for the next message
if incompleteAnsiSequence(data) {
this.parentInBuffer = append(this.parentInBuffer, data...)
return
}
for {
// The InputFromParent function consumes bytes from the passed in data
// buffer and returns unprocessed bytes, so we loop and continue to
// pass data in, if available
leftover := this.ParentInput(this.Butterfish.Ctx, data)
if leftover == nil || len(leftover) == 0 {
break
}
if len(leftover) == len(data) {
// nothing was consumed, we buffer and try again later
this.parentInBuffer = append(this.parentInBuffer, leftover...)
break
}
// go again with the leftover data
data = leftover
}
}
func (this *ShellState) ParentInput(ctx context.Context, data []byte) []byte {
hasCarriageReturn := bytes.Contains(data, []byte{'\r'})
switch this.State {
case statePromptResponse:
// Ctrl-C while receiving prompt
// We're buffering the input right now so we check both the first and last
// bytes for Ctrl-C
if data[0] == 0x03 || data[len(data)-1] == 0x03 {
log.Printf("Canceling prompt response")
this.PromptResponseCancel()
this.PromptResponseCancel = nil
this.GoalMode = false
this.setState(stateNormal)
if data[0] == 0x03 {
return data[1:]
} else {
return data[:len(data)-1]
}
}
// If we're in the middle of a prompt response we ignore all other input
return data
case stateNormal:
if HasRunningChildren() {
// If we have running children then the shell is running something,
// so just forward the input.
this.ChildIn.Write(data)
return nil
}
if data[0] == 0x03 {