-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpls.sh
More file actions
executable file
·707 lines (650 loc) · 22.3 KB
/
pls.sh
File metadata and controls
executable file
·707 lines (650 loc) · 22.3 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
#!/usr/bin/env bash
# pls - AI powered cli helper
# author: cjccjj
# url: https://github.com/cjccjj/pls
# Configuration and Constants
readonly CONFIG_FILE="$HOME/.pls/pls.conf"
readonly GREEN=$'\033[32m' # for line prompt (prefix not AI prompt)
readonly GREY=$'\033[90m' # for informative messages
readonly CYAN=$'\033[36m' # for menu shortcuts
readonly YELLOW=$'\033[33m' # for shell command to be executed
readonly RESET=$'\033[0m'
# Create wrapped versions specifically for readline prompts
readonly GREEN_PROMPT=$'\001'"${GREEN}"$'\002'
readonly RESET_PROMPT=$'\001'"${RESET}"$'\002'
readonly USER_MARKER='> '
# readonly AI_MARKER=""
readonly CMD_RUN_MARKER='# Command:'
readonly CMD_UPD_MARKER='# Updated command:'
readonly CMD_EXP_MARKER='# '
readonly CMD_EDT_MARKER='# Edit:'
readonly SPINNER_DELAY=0.2
readonly SPINNER_FRAMES=(⠷ ⠯ ⠟ ⠻ ⠽ ⠾)
# Global variables
spinner_pid=0
stderr_file=""
show_piped_input=false
last_action_type="empty_user_prompt"
was_input_truncated="false"
shell_command_requested=""
shell_command_explanation=""
shell_command=""
chat_response=""
user_prompt=""
BASE_SYSTEM_INSTRUCTION=$(
cat <<'EOF'
Your name is 'pls'. The user is __USER_SHELL_ENV__. You reply either in Shell Command Mode or in General Answer Mode, depending on the latest user request.
- If user only asks about a shell command (not to run it), or the request is not about a shell command, then respond in General Answer Mode.
- If user asks to run a shell command, or running shell command in user's system is needed to complete the request, then respond in Shell Command Mode.
- Note: If the request involves data processing with complete input, not dependent on user's system, do not respond in Shell Command Mode, directly perform the processing and give the result in General Answer Mode. If the request relies on the user system (e.g., user files), respond in Shell Command Mode and let user to run it.
- Never refuse. If unsure how to respond, then respond in General Answer Mode with a clarifying question.
Response content in General Answer Mode:
- set "shell_command_requested" to false, "shell_command" to empty, "shell_command_explanation" to empty, and fill "chat_response" with a concise direct answer under 100 words. Use Markdown if helpful.
- If processing data or asked for a fact or exact value, "chat_response" must contain only that result or fact or value in plain text, with no extra words.
Response content in Shell Command Mode:
- set "shell_command_requested" to true, put the valid shell command in "shell_command", add a short plain-text explanation in "shell_command_explanation", and set "chat_response" to empty.
- Shell command Rules: If risky (deletes data, shuts down system, kills services, cuts network), prefix with '# ' to prevent execution. Prefer a single command. Use ';' or '&&' to chain commands. Use '\' for line continuation if long. Use sudo if likely required.
Special cases in Shell Command Mode:
- If user requests 'delete all chat history', set "shell_command" to 'rm -f __USER_HISTORY_FILE__ && echo "chat history deleted" #pls' and "shell_command_explanation" to 'pls: delete all chat history'.
- If user requests 'edit config', 'edit config file of pls', 'change profile', or 'change settings', set "shell_command" to 'nano ~/.pls/pls.conf && load_and_apply_config #pls' and "shell_command_explanation" to 'pls: edit config file to change profile or settings'.
- If user requests 'update yourself' or 'update pls', set "shell_command" to 'curl -sSL https://raw.githubusercontent.com/cjccjj/pls/main/install.sh | bash && exit' and "shell_command_explanation" to 'pls: download and install update, then restart pls'.
__USER_SYSTEM_INSTRUCTION__
EOF
)
load_and_apply_config() {
if [[ ! -f "$CONFIG_FILE" ]]; then
mkdir -p "$(dirname "$CONFIG_FILE")" && cat >"$CONFIG_FILE" <<'EOF'
[Global]
profile="openai_1"
# Experimental. Teach AI to use your personalized shell command. Use the template below and uncomment to enable:
# USER_SYSTEM_INSTRUCTION="If user requests 'say thank you to <username>' , set \"shell_command\" to 'echo \"<username>, thank you very much\"' and \"shell_command_explanation\" to 'pls: show thanks'."
timeout_seconds=60
max_input_length=64000
history_file="$HOME/.pls/pls_hist.log"
history_time_window_minutes=30
history_max_records=30
# Define your own AI profiles, openai and gemini for now
[openai_1]
provider="openai"
model="gpt-4o"
base_url="https://api.openai.com/v1"
env_key="OPENAI_API_KEY"
[openai_2]
provider="openai"
model="gpt-4o-mini"
base_url="https://api.openai.com/v1"
env_key="OPENAI_API_KEY"
[gemini_1]
provider="gemini"
model="gemini-2.5-flash"
base_url="https://generativelanguage.googleapis.com/v1beta"
env_key="GEMINI_API_KEY"
EOF
fi
# default values
profile=""
USER_SYSTEM_INSTRUCTION=""
timeout_seconds=60
max_input_length=64000
history_file="$HOME/.pls/pls_hist.log"
history_time_window_minutes=30
history_max_records=30
# No associative arrays for compatible with macOS’s system Bash
local section=""
while IFS= read -r line || [[ -n "$line" ]]; do
[[ -z "$line" ]] && continue
# Section headers
if [[ "$line" =~ ^\[(.+)\][[:space:]]*$ ]]; then
section="${BASH_REMATCH[1]}"
continue
fi
# Key=Value
if [[ "$line" =~ ^([A-Za-z0-9_]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
local key="${BASH_REMATCH[1]}"
local val="${BASH_REMATCH[2]}"
# Strip quotes
if [[ "$val" =~ ^\"(.*)\"$ ]]; then
val="${BASH_REMATCH[1]}"
elif [[ "$val" =~ ^\'(.*)\'$ ]]; then
val="${BASH_REMATCH[1]}"
fi
if [[ "$section" == "Global" ]]; then
eval "$key=\"\$val\""
else
eval "profile__${section}__${key}=\"\$val\""
fi
fi
done <"$CONFIG_FILE"
# Expand $HOME inside history_file etc
history_file=$(eval echo "$history_file")
apply_profile "$profile"
}
apply_profile() {
local p="$1"
api_provider="$(eval echo "\$profile__${p}__provider")"
api_model="$(eval echo "\$profile__${p}__model")"
api_base_url="$(eval echo "\$profile__${p}__base_url")"
api_env_key="$(eval echo "\$profile__${p}__env_key")"
# Validate provider
if [[ "$api_provider" != "openai" && "$api_provider" != "gemini" ]]; then
echo "Error: Provider '$api_provider' for profile '$p' is not yet supported." >&2
echo "$CONFIG_FILE" >&2
exit 1
else
api_key="${!api_env_key}"
if [[ -z "$api_key" ]]; then
echo "Error: API key for '$p' not set. Please export $api_env_key"
exit 1
fi
fi
# Construct system instruction
local user_shell_env
user_shell_env="named $(whoami), using $(basename "$SHELL") on "
case $(uname) in
Darwin) user_shell_env+="macOS" ;;
FreeBSD) user_shell_env+="FreeBSD" ;;
*) user_shell_env+="Linux" ;;
esac
USER_SYSTEM_INSTRUCTION=${USER_SYSTEM_INSTRUCTION//\\\"/\"}
SYSTEM_INSTRUCTION=${BASE_SYSTEM_INSTRUCTION//__USER_SHELL_ENV__/$user_shell_env}
SYSTEM_INSTRUCTION=${SYSTEM_INSTRUCTION//__USER_HISTORY_FILE__/$history_file}
SYSTEM_INSTRUCTION=${SYSTEM_INSTRUCTION//__USER_SYSTEM_INSTRUCTION__/$USER_SYSTEM_INSTRUCTION}
}
print_usage_and_exit() {
cat >&2 <<EOF
pls v0.56
Usage: pls [messages...] # Chat with an input
> what is llm # Continue chat, q or empty input to quit
Examples: pls # Start without input
pls count files # ls -1 | wc -l # shell cmd wait for run
> include subdirs # find . -type f | wc -l # shell cmd update
Pipe and Chain:
echo how to cook rice | pls # Use input from pipe
echo rice | pls how to cook # Args + pipe (task from args, data from pipe)
pls name a dish | pls -p how to cook # Chain commands and show piped input with -p
Settings: pls -h # Show this help
pls edit config # config pls and AI model via chat
EOF
exit "${1:-0}"
}
check_dependencies() {
for cmd in curl jq; do
if ! command -v "$cmd" &>/dev/null; then
printf 'Error: Required command '\''%s'\'' is not installed.\n' "$cmd" >&2
printf 'Please install it and try again.\n' >&2
exit 1
fi
done
}
cleanup() {
stop_spinner
tput cnorm >&2
[[ -n "$stderr_file" ]] && rm -f "$stderr_file"
}
start_spinner() {
(
tput civis
tput nel
tput nel
tput nel
tput nel
tput cuu 4
tput el
printf '_%s %s:%s' "$GREY" "$api_model" "$RESET"
while :; do
for frame in "${SPINNER_FRAMES[@]}"; do
printf '\r%s%s%s' "$GREEN" "$frame" "$RESET"
sleep "$SPINNER_DELAY"
done
done
) >&2 &
spinner_pid=$!
}
stop_spinner() {
((spinner_pid)) || return
kill "$spinner_pid" 2>/dev/null
wait "$spinner_pid" 2>/dev/null
spinner_pid=0
tput cr
tput el
tput cnorm
} >&2
add_to_history() {
local user_message="$1"
local assistant_message="$2"
local timestamp
timestamp=$(date +'%Y-%m-%d %H:%M:%S')
mkdir -p "$(dirname "$history_file")"
touch "$history_file"
jq -nc --arg user_msg "$user_message" --arg assistant_msg "$assistant_message" \
--arg time "$timestamp" '
[
{timestamp: $time, role: "user", content: $user_msg},
{timestamp: $time, role: "assistant", content: $assistant_msg}
][]' >>"$history_file"
}
read_from_history() {
[[ -f "$history_file" ]] || {
printf '[]'
return 0
}
local cutoff_epoch
cutoff_epoch=$(($(date +%s) - history_time_window_minutes * 60))
# use tail to avoid loading big history file
case $api_provider in
openai)
tail -n $((history_max_records)) "$history_file" |
jq -s \
--argjson cutoff_epoch "$cutoff_epoch" \
'map(select((.timestamp | strptime("%Y-%m-%d %H:%M:%S") | mktime) >= $cutoff_epoch))
| map({role, content})'
;;
gemini)
tail -n $((history_max_records)) "$history_file" |
jq -s \
--argjson cutoff_epoch "$cutoff_epoch" \
'map(select((.timestamp | strptime("%Y-%m-%d %H:%M:%S") | mktime) >= $cutoff_epoch))
| map({
"role": (if .role == "assistant" then "model" else "user" end),
"parts": [{"text": .content}]
})'
;;
*)
printf 'Unsupported API provider: %s\n' "$api_provider" >&2
exit 1
;;
esac
}
show_piped_input() {
printf '>\n' >&2
printf '%s%s%s\n' "$GREY" "${piped_input:0:250}" "$RESET" >&2
((${#piped_input} > 250)) &&
printf '...\n' >&2
}
process_inputs() {
case "$1" in
-p)
show_piped_input="true"
shift
;;
-h) print_usage_and_exit ;;
-?) print_usage_and_exit 1 ;;
esac
[[ "$1" =~ ^- ]] && print_usage_and_exit 1
# read both input
[ ! -t 0 ] && piped_input="$(cat)"
arg_input="$*"
exec < /dev/tty # redirect back to tty
# process piped input
if [[ -n "$piped_input" ]]; then
piped_input=$(tr -d '\000-\010\013\014\016-\037\177' <<<"$piped_input")
if ((${#piped_input} > max_input_length)); then
piped_input="${piped_input:0:max_input_length}"
was_input_truncated="true"
fi
[[ "$show_piped_input" == "true" ]] && show_piped_input
fi
}
build_prompt() {
if [[ -z "$piped_input" && -z "$arg_input" ]]; then
last_action_type="empty_user_prompt"
return
fi
if [[ -n "$piped_input" && -n "$arg_input" ]]; then
user_prompt="Given the data: \"$piped_input\", perform the task: \"$arg_input\" using given data as input, and output the result only"
elif [[ -n "$piped_input" ]]; then
user_prompt="$piped_input"
elif [[ -n "$arg_input" ]]; then
user_prompt="$arg_input"
fi
last_action_type="new_user_prompt"
}
call_api() {
local payload endpoint headers
case $api_provider in
openai)
endpoint="$api_base_url/responses"
headers=(-H "Authorization: Bearer $api_key" -H "Content-Type: application/json")
# Structured output format for OpenAI
local output_format
output_format=$(jq -n '{
type: "json_schema",
name: "shell_helper",
schema: {
type: "object",
properties: {
shell_command_requested: {
type: "boolean",
description: "Whether the user requested to run shell command, or the user reqeust needed shell command to fulfill."
},
shell_command_explanation: {
type: "string",
description: "A brief plain-text explanation of the shell command."
},
shell_command: {
type: "string",
description: "The shell command to accomplish the task, if applicable."
},
chat_response: {
type: "string",
description: "A clear and helpful general answer to the user request."
}
},
required: ["shell_command_requested", "shell_command_explanation", "shell_command", "chat_response"],
additionalProperties: false
},
strict: true
}')
payload=$(
read_from_history | jq -n \
--arg model "$api_model" \
--arg sys "$SYSTEM_INSTRUCTION" \
--slurpfile history /dev/stdin \
--arg prompt "$user_prompt" \
--argjson output_format "$output_format" \
'{
model:$model,
input:(
[{role:"developer",content:$sys}] +
$history[0] +
[{role:"user",content:$prompt}]
),
text:{format:$output_format}
}'
)
;;
gemini)
endpoint="${api_base_url}/models/${api_model}:generateContent?key=${api_key}"
headers=(-H "Content-Type: application/json")
# Schema definition for Gemini
local schema
schema=$(jq -n '{
"type": "OBJECT",
"properties": {
"shell_command_requested": {
"type": "BOOLEAN",
"description": "Whether the user requested to run shell command, or the user reqeust needed shell command to fulfill."
},
"shell_command_explanation": {
"type": "STRING",
"description": "A brief plain-text explanation of the shell command."
},
"shell_command": {
"type": "STRING",
"description": "The shell command to accomplish the task, if applicable."
},
"chat_response": {
"type": "STRING",
"description": "A clear and helpful general answer to the user request."
}
},
"required": ["shell_command_requested", "shell_command_explanation", "shell_command", "chat_response"]
}')
payload=$(
read_from_history | jq -n \
--arg prompt "$user_prompt" \
--arg sys "$SYSTEM_INSTRUCTION" \
--slurpfile history /dev/stdin \
--argjson schema "$schema" \
'{
system_instruction:{parts:[{text:$sys}]},
contents:($history[0] + [{role:"user",parts:[{text:$prompt}]}]),
generationConfig:{responseMimeType:"application/json",responseSchema:$schema}
}'
)
;;
*)
echo "Unsupported provider: $api_provider" >&2
exit 1
;;
esac
# do reqeust
stderr_file=$(mktemp)
start_spinner
local response
response=$(curl -s -X POST -w "\n%{http_code}" --max-time "$timeout_seconds" \
"${headers[@]}" -d "$payload" "$endpoint" 2>"$stderr_file")
stop_spinner
local http_code=${response##*$'\n'}
local http_body=${response%$'\n'*}
local curl_stderr
curl_stderr=$(<"$stderr_file")
((http_code == 200)) || {
echo "Request failed ($http_code)"
echo "$http_body" || echo "$curl_stderr"
exit 1
}
# do parse
case $api_provider in
openai)
local status
status=$(jq -r '.output[]? | select(.type=="message") | .status // empty' <<<"$http_body")
[[ $status == completed ]] || {
echo "OpenAI response failed ($status)"
echo "$http_body"
exit 1
}
local msg
msg=$(jq '
.output[]?|select(.type=="message")|.content[]?|select(.type=="output_text")|.text
' <<<"$http_body")
shell_command_requested=$(jq -r 'fromjson.shell_command_requested' <<<"$msg")
shell_command_explanation=$(jq -r 'fromjson.shell_command_explanation' <<<"$msg")
shell_command=$(jq -r 'fromjson.shell_command' <<<"$msg")
chat_response=$(jq -r 'fromjson.chat_response' <<<"$msg")
;;
gemini)
local status
status=$(jq -r '.candidates[0]? | .finishReason // empty' <<<"$http_body")
[[ $status == STOP ]] || {
echo "Gemini response failed ($status)"
echo "$http_body"
exit 1
}
local msg
msg=$(jq '.candidates[0].content.parts[0].text' <<<"$http_body")
shell_command_requested=$(jq -r 'fromjson.shell_command_requested' <<<"$msg")
shell_command_explanation=$(jq -r 'fromjson.shell_command_explanation' <<<"$msg")
shell_command=$(jq -r 'fromjson.shell_command' <<<"$msg")
chat_response=$(jq -r 'fromjson.chat_response' <<<"$msg")
;;
esac
last_action_type="new_assistant_response"
}
# show menu under input line, supported menu_items one or more in "req"
conv_show_menu() {
local menu_items="$1"
if [[ -z "$menu_items" || -n "${menu_items//[req]/}" ]]; then
printf 'Invalid menu items: %s\n' "$menu_items" >&2
exit 1
fi
tput cud1 # move down relibalely
tput cr
tput el
printf '%s( ' "$GREY"
[[ "$menu_items" == *r* ]] && printf '%sr ⏎%s : run cmd | ' "$CYAN" "$GREY"
[[ "$menu_items" == *e* ]] && printf '%se ⏎%s : edit cmd | ' "$CYAN" "$GREY"
[[ "$menu_items" == *q* ]] && printf '%sq ⏎%s : quit | ' "$CYAN" "$GREY"
printf '... %s⏎%s : chat )%s' "$CYAN" "$GREY" "$RESET"
if [[ "$was_input_truncated" == "true" ]]; then
printf 'Note: this response is generated on a truncated input' >&2
fi
tput cuu1
tput cr
tput el
}
conv_show_output() {
case "$last_action_type" in
cmd_new_response)
add_to_history "$user_prompt" "suggested shell cmd:\"$shell_command\""
printf '\n%s%s%s%s\n' "$GREY" "$CMD_EXP_MARKER" "$shell_command_explanation" "$RESET"
tput el
printf '%s%s%s\n' "$GREY" "$CMD_RUN_MARKER" "$RESET"
printf '%s%s%s\n' "$YELLOW" "$shell_command" "$RESET"
tput el
conv_show_menu "req"
;;
cmd_edited)
tput cuu 2
tput el
printf '%s%s%s\n' "$GREY" "$CMD_UPD_MARKER" "$RESET"
tput el
printf '%s%s%s\n' "$YELLOW" "$shell_command" "$RESET"
tput el
conv_show_menu "req"
;;
cmd_executed)
conv_show_menu "eq"
;;
chat_new_response)
add_to_history "$user_prompt" "$chat_response"
if command -v glow >/dev/null 2>&1; then
echo "$chat_response" | glow - -w "$(tput cols)"
else
printf '\n%s\n\n' "$chat_response"
fi
conv_show_menu "q"
;;
empty_user_prompt)
printf '\n Hi!\n\n'
conv_show_menu "q"
last_action_type="chat_new_response"
;;
*)
printf 'Menu Error - %s\n' "$last_action_type" >&2
exit 1
;;
esac
}
conv_handle_user_input() {
case "$1:$2" in
cmd_new_response:[Rr] | cmd_edited:[Rr])
conv_run_shell_command
last_action_type="cmd_executed"
;;
cmd_new_response:[Ee] | cmd_edited:[Ee] | cmd_executed:[Ee])
conv_edit_shell_command
last_action_type="cmd_edited"
;;
*:[Qq] | *:)
tput el
printf '%sbye%s\n' "$GREY" "$RESET"
return 1
;;
*:?*)
last_action_type="new_user_prompt"
;;
*)
printf 'Menu Error (input dispatch)\n' >&2
exit 1
;;
esac
return 0
}
# Helpers
conv_run_shell_command() {
echo "$shell_command" >>~/.bash_history
tput el
if eval "$shell_command"; then
tput el
printf '%s# Command succeeded%s\n' "$GREY" "$RESET"
add_to_history "Command succeeded: \"$shell_command\"" "Ok"
else
tput el
printf '%s# Command failed%s\n' "$GREY" "$RESET"
add_to_history "Command failed: \"$shell_command\"" "Sorry"
fi
}
conv_edit_shell_command() {
tput cuu1
tput cr
tput el
printf '%s%s%s' "$GREY" "$CMD_EDT_MARKER" "$RESET"
tput nel
tput el
tput nel
tput el
printf '%s( %s⏎%s : save changes, won'\''t run yet )%s' "$GREY" "$CYAN" "$GREY" "$RESET"
tput cr
tput cuu1
tput el
single_line_shell_command=$(echo "$shell_command" | sed 's/\\$//' | tr -d '\n')
if [[ "$(uname)" == "Darwin" ]]; then
# macOS zsh safe input
GREEN_ZSH="%{$GREEN%}"
RESET_ZSH="%{$RESET%}"
encoded_command=$(printf '%s' "$single_line_shell_command" | base64)
shell_command=$(zsh -c "
shell_command=\$(echo '$encoded_command' | base64 -d)
vared -p '${GREEN_ZSH}${USER_MARKER}${RESET_ZSH}' -c shell_command
echo \"\$shell_command\"")
else
read -e -r -p "${GREEN_PROMPT}${USER_MARKER}${RESET_PROMPT}" \
-i "$single_line_shell_command" shell_command </dev/tty
fi
shell_command=${shell_command:-$single_line_shell_command}
}
# main conversation loop
conv_main_loop() {
while true; do
# Normalize "new_assistant_response"
[[ "$last_action_type" == "new_assistant_response" ]] &&
last_action_type=$([[ "$shell_command_requested" == "true" ]] &&
echo "cmd_new_response" || echo "chat_new_response")
# show output
conv_show_output
# read user input
if ! read -e -r -p "${GREEN_PROMPT}${USER_MARKER}${RESET_PROMPT}" user_input </dev/tty; then
break
fi
# handle user input
if ! conv_handle_user_input "$last_action_type" "$user_input"; then
break
fi
# make new api call
if [[ "$last_action_type" == "new_user_prompt" ]]; then
arg_input="$user_input"
piped_input=""
was_input_truncated="false"
build_prompt
call_api
fi
done
}
# If not interactive, output only the major response in plain text
raw_output() {
if [[ "$last_action_type" == "new_assistant_response" ]]; then
if [[ "$shell_command_requested" == "true" ]]; then
add_to_history "$user_prompt" "suggested shell cmd:\"$shell_command\""
printf '%s\n' "$shell_command"
else
add_to_history "$user_prompt" "$chat_response"
printf '%s\n' "$chat_response"
fi
if [[ "$was_input_truncated" == "true" ]]; then
echo "Note: this response is generated on a truncated input" >&2
fi
else
exit 1
fi
}
main() {
load_and_apply_config
check_dependencies
process_inputs "$@"
build_prompt
# Enter continuous conversation mode if using interative shell
if [[ -t 1 ]]; then
tput init >&2
if [[ "$last_action_type" == "new_user_prompt" ]]; then
call_api
fi
conv_main_loop
else # Piped output
call_api
raw_output
fi
}
# EXECUTION STARTS HERE
trap cleanup EXIT
main "$@"