-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshoop.sh
More file actions
executable file
·1198 lines (1104 loc) · 40.7 KB
/
Copy pathshoop.sh
File metadata and controls
executable file
·1198 lines (1104 loc) · 40.7 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
#!/bin/bash
# shoop — a coding agent in bash
# usage: shoop "fix the bug in main.go"
# shoop resume <id-or-name> ["new prompt"]
# shoop sessions | list | ls
# shoop config [show|edit]
# shoop undo
SHOOP_VERSION="0.3.3"
set -euo pipefail
for _c in jq curl awk; do command -v "$_c" >/dev/null 2>&1 || { echo "error: $_c is required" >&2; exit 1; }; done
unset _c
# --- Bash 3.2 shims (macOS) ---
# shellcheck disable=SC2329
(( BASH_VERSINFO[0] >= 4 )) || {
mapfile() {
local _t=0 _var=MAPFILE _i=0 _line
while [[ "${1:-}" == -* ]]; do case "$1" in -t) _t=1 ;; esac; shift; done
[[ -n "${1:-}" ]] && _var=$1
while IFS= read -r _line || [[ -n "$_line" ]]; do
eval "${_var}[$_i]=\"\$_line\""
((_i++)) || true
done
}
readarray() { mapfile "$@"; }
}
# --- util ---
slugify() {
printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | \
sed 's/[^a-z0-9]/-/g; s/--*/-/g; s/^-//; s/-$//' | cut -c1-40
}
# --- providers ---
PROVIDER=""
REWRITE_MODEL=""
select_provider() {
local name="$1"
PROVIDER="$name"
case "$name" in
openrouter)
API="https://openrouter.ai/api/v1/chat/completions"
MODEL="openai/gpt-5.4-mini"
REWRITE_MODEL=""
;;
zai)
API="https://api.z.ai/api/coding/paas/v4/chat/completions"
MODEL="glm-5.1"
REWRITE_MODEL="glm-5-turbo"
;;
*)
echo "error: unknown provider: $name" >&2
exit 1
;;
esac
}
select_provider openrouter
# --- config ---
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/shoop"
CONFIG="$CONFIG_DIR/config"
SESSION_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/shoop/sessions"
if [[ ! -f "$CONFIG" ]]; then
mkdir -p "$CONFIG_DIR" && chmod 700 "$CONFIG_DIR"
cat > "$CONFIG" <<'EOF'
MODEL=openai/gpt-5.4-mini
API=https://openrouter.ai/api/v1/chat/completions
API_KEY=
MAX_TURNS=25
CONFIRM=1
REWRITE=1
FORMAT_CMD=
CHECKPOINT=0
EOF
chmod 600 "$CONFIG"
fi
# migrate config: append any keys missing from older config files
_config_defaults=(REWRITE=1 FORMAT_CMD= CHECKPOINT=0)
for _kv in "${_config_defaults[@]}"; do
_k="${_kv%%=*}"
grep -qE "^${_k}=" "$CONFIG" 2>/dev/null || printf '%s\n' "$_kv" >> "$CONFIG"
done
unset _kv _k _config_defaults
# safe config loading — only accept known KEY=VALUE, never source
while IFS='=' read -r key value || [[ -n "$key" ]]; do
key="${key%%[[:space:]]*}"
value="${value#"${value%%[^[:space:]]*}"}"
value="${value%"${value##*[^[:space:]]}"}"
case "$key" in
MODEL) MODEL="$value" ;;
API) API="$value" ;;
API_KEY) API_KEY="$value" ;;
MAX_TURNS) MAX_TURNS="$value" ;;
CONFIRM) CONFIRM="$value" ;;
REWRITE) REWRITE="$value" ;;
FORMAT_CMD) FORMAT_CMD="$value" ;;
CHECKPOINT) CHECKPOINT="$value" ;;
esac
done < "$CONFIG"
# env overrides config — precedence: flag > env > config > default
MODEL="${MODEL:-openai/gpt-5.4-mini}"
API="${API:-https://openrouter.ai/api/v1/chat/completions}"
MAX_TURNS="${MAX_TURNS:-25}"
[[ "$MAX_TURNS" =~ ^[0-9]+$ ]] || MAX_TURNS=25
CONFIRM="${SHOOP_CONFIRM:-${CONFIRM:-1}}"
[[ "$CONFIRM" =~ ^[0-9]$ ]] || CONFIRM=1
REWRITE="${SHOOP_REWRITE:-${REWRITE:-1}}"
[[ "$REWRITE" =~ ^[0-9]$ ]] || REWRITE=1
FORMAT_CMD="${FORMAT_CMD:-}"
CHECKPOINT="${SHOOP_CHECKPOINT:-${CHECKPOINT:-0}}"
[[ "$CHECKPOINT" =~ ^[0-9]$ ]] || CHECKPOINT=0
API_KEY="${SHOOP_API_KEY:-${API_KEY:-${OPENROUTER_API_KEY:-${ZAI_API_KEY:-}}}}"
RAW=0
# --- capabilities ---
if command -v timeout >/dev/null 2>&1; then
TIMEOUT_CMD=timeout
elif command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_CMD=gtimeout
else
TIMEOUT_CMD=
fi
if command -v lynx >/dev/null 2>&1; then
_html2text() { lynx -dump -nolist; }
HAS_HTML2TEXT=1
elif command -v w3m >/dev/null 2>&1; then
_html2text() { w3m -dump; }
HAS_HTML2TEXT=1
else
HAS_HTML2TEXT=0
fi
# --- path safety ---
WORKDIR=$(pwd -P)
resolve_path() {
local p="$1"
[[ "$p" != /* ]] && p="$WORKDIR/$p"
if command -v grealpath >/dev/null 2>&1; then
grealpath -m "$p"
elif realpath -m / 2>/dev/null | grep -q /; then
realpath -m "$p"
else
# portable fallback: resolve existing parent, append rest
local dir base
dir=$(dirname "$p")
base=$(basename "$p")
if [[ -d "$dir" ]]; then
(cd "$dir" && printf '%s/%s' "$(pwd -P)" "$base")
else
printf '%s' "$p"
fi
fi
}
check_path() {
local p="$1" resolved
resolved=$(resolve_path "$p")
case "$resolved" in
*/.git/*|*/.ssh/*|*/.aws/*|*/.gnupg/*|*/.env|*/.env.*)
echo "[blocked: sensitive path — $p → $resolved]" ; return 1 ;;
esac
if [[ "$resolved" == */../* || "$resolved" == */.. ]]; then
echo "[blocked: unresolvable '..' — $p → $resolved]"
return 1
fi
if [[ -L "$resolved" ]]; then
local target
target=$(resolve_path "$(readlink "$resolved")")
if [[ "$target" == */../* || "$target" == */.. ]]; then
echo "[blocked: symlink unresolvable — $p → $target]"
return 1
fi
if [[ "$target" != "$WORKDIR"/* && "$target" != "$WORKDIR" ]]; then
echo "[blocked: symlink escape — $p → $target (outside $WORKDIR)]"
return 1
fi
fi
[[ "$resolved" == "$WORKDIR"/* || "$resolved" == "$WORKDIR" ]] && return 0
echo "[blocked: path escape — $p → $resolved (outside $WORKDIR)]"
return 1
}
require_path() {
local msg
msg=$(check_path "$1" 2>&1) || { reject_tool "${msg:-[blocked: path check failed]}"; return 1; }
}
is_binary() {
local p="$1"
[[ "$(file -b --mime-encoding "$p" 2>/dev/null)" == "binary" ]] && return 0
[[ "$(file -I "$p" 2>/dev/null)" == *"charset=binary"* ]] && return 0
return 1
}
# --- session persistence ---
mkdir -p "$SESSION_DIR" && chmod 700 "$SESSION_DIR"
SESSION_ID=$(date +%Y%m%d-%H%M%S)-$$
SESSION_SLUG=""
save_session() {
local tmp fname="$SESSION_ID"
[[ -n "$SESSION_SLUG" ]] && fname="${SESSION_ID}--${SESSION_SLUG}"
tmp=$(mktemp "$SESSION_DIR/.tmp-XXXXXX")
printf '%s' "$messages" > "$tmp"
sync "$tmp" 2>/dev/null || true
mv "$tmp" "$SESSION_DIR/$fname.json"
}
# --- tracking ---
_reads="" _writes="" _cmds=0
# --- tools ---
tools='[
{
"type": "function",
"function": {
"name": "run_shell",
"description": "Run a bash command (always requires user confirmation). Returns stdout/stderr (first 200 lines), prefixed with [exit: N].",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "bash command to execute"},
"timeout": {"type": "integer", "description": "max seconds (default: 30)"}
},
"required": ["command"]
}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read file contents with line numbers. Reads entire file by default. Omit start_line/end_line unless you need a specific range.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "file path to read"},
"start_line": {"type": "integer", "description": "first line (1-indexed, default: 1)"},
"end_line": {"type": "integer", "description": "last line (default: start_line+199)"}
},
"required": ["path"]
}
}
},
{
"type": "function",
"function": {
"name": "write_file",
"description": "Write content to a file (creates parent dirs). Shows diff for existing files.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "file path to write"},
"content": {"type": "string", "description": "file content"}
},
"required": ["path", "content"]
}
}
},
{
"type": "function",
"function": {
"name": "search_files",
"description": "Search file contents with grep. Returns file:line:match. Max 100 results.",
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "grep regex pattern"},
"path": {"type": "string", "description": "directory to search (default: .)"},
"include": {"type": "string", "description": "file glob filter, e.g. *.go"},
"context_lines": {"type": "integer", "description": "lines of context around matches (default: 0)"},
"case_insensitive": {"type": "boolean", "description": "case-insensitive search (default: false)"}
},
"required": ["pattern"]
}
}
},
{
"type": "function",
"function": {
"name": "replace_in_file",
"description": "Replace exact text in a file. Safer and cheaper than rewriting via write_file. old_text must match exactly (including whitespace/indentation). Replaces first occurrence only.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "file path"},
"old_text": {"type": "string", "description": "exact text to find (must exist in file)"},
"new_text": {"type": "string", "description": "replacement text"}
},
"required": ["path", "old_text", "new_text"]
}
}
},
{
"type": "function",
"function": {
"name": "list_dir",
"description": "List directory contents with type indicators. No confirmation needed.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "directory to list (default: .)"},
"depth": {"type": "integer", "description": "max depth (default: 3)"}
}
}
}
},
{
"type": "function",
"function": {
"name": "web_fetch",
"description": "Fetch a URL and return its text content. Use for reading documentation, issues, or API references.",
"parameters": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "URL to fetch (must be http:// or https://)"}
},
"required": ["url"]
}
}
}
]'
system_prompt="You are a coding assistant in a bash agent loop.
Working directory: $WORKDIR
OS: $(uname -s) $(uname -m)
Prefer replace_in_file for targeted edits, search_files/list_dir for exploration, run_shell for execution. Read before modifying. Prefer --dry-run before destructive ops.
Tool output is capped at 200 lines — use read_file line ranges for large files.
User confirms mutations — if denied, ask what to change. If a tool fails, diagnose before retrying.
Explain your plan briefly, then act."
# --- parse flags ---
_need_arg() { [[ -n "$2" ]] || { echo "shoop: $1 requires a value" >&2; exit 1; }; }
while [[ $# -gt 0 ]]; do
case "$1" in
--model) _need_arg "$1" "${2:-}"; MODEL="$2"; shift 2 ;;
--api) _need_arg "$1" "${2:-}"; API="$2"; shift 2 ;;
--key) _need_arg "$1" "${2:-}"; API_KEY="$2"; shift 2 ;;
--zai) select_provider zai; API_KEY="${ZAI_API_KEY:-$API_KEY}"; shift ;;
--raw) RAW=1; shift ;;
--no-rewrite) REWRITE=0; shift ;;
--no-confirm) CONFIRM=0; shift ;;
--checkpoint) CHECKPOINT=1; shift ;;
*) break ;;
esac
done
# --- api ---
require_api_key() {
if [[ -z "$API_KEY" ]]; then
echo "error: no API key found" >&2
echo " add API_KEY=<key> to $CONFIG" >&2
echo " or export SHOOP_API_KEY, OPENROUTER_API_KEY, or ZAI_API_KEY" >&2
exit 1
fi
}
call_api() {
local payload="$1" resp http_code body auth_file api_error
# auth_file holds the bearer header so the API key never appears in process args.
# Cleaned up immediately after curl completes — no RETURN trap (which leaks globally).
auth_file=$(mktemp)
printf 'Authorization: Bearer %s' "$API_KEY" > "$auth_file"
resp=$(curl -s -w '\n%{http_code}' "$API" \
-H @"$auth_file" \
-H "Content-Type: application/json" \
-d "$payload")
rm -f "$auth_file"
http_code="${resp##*$'\n'}"
body="${resp%$'\n'"$http_code"}"
if [ "$http_code" -lt 200 ] || [ "$http_code" -ge 300 ]; then
echo "API error (HTTP $http_code): $body" >&2
return 1
fi
api_error=$(printf '%s' "$body" | jq -r '.error.message // empty')
if [ -n "$api_error" ]; then
echo "API error: $api_error" >&2
return 1
fi
printf '%s' "$body"
}
build_chat_payload() {
case "$PROVIDER" in
openrouter|zai)
jq -n \
--arg model "$MODEL" \
--argjson messages "$messages" \
--argjson tools "$tools" \
'{model: $model, messages: $messages, tools: $tools, parallel_tool_calls: false}'
;;
*)
echo "error: unsupported provider mode: $PROVIDER" >&2
exit 1
;;
esac
}
parse_chat_response() {
local response_json="$1" raw_parse
raw_parse=$(printf '%s' "$response_json" | jq -r '
.choices[0].message as $m |
[(.usage.total_tokens // 0),
($m.tool_calls // [] | length),
($m.content // ""),
($m | @json)] | join("\u001f")
')
if [[ -z "$raw_parse" || "$raw_parse" != *$'\x1f'* ]]; then
echo "error: failed to parse API response" >&2
echo "$response_json" >&2
exit 1
fi
IFS=$'\x1f' read -d '' -r parsed_tokens parsed_tool_count parsed_content parsed_message_json _rest <<< "$raw_parse" || true
}
# --- prompt rewriter ---
rewrite_system='Rewrite this prompt for a coding agent with tools: shell execution, file read/write/replace, grep search, directory listing, and web fetch.
Structure as: Context (what exists), Role (expert stance), Intent (specific goal), Specs (constraints/requirements), Plan (suggested approach).
Preserve intent exactly — do not add requirements the user did not state.
If the prompt is already specific and actionable, return it unchanged.
No longer than 3x the original length or 200 words (whichever is smaller).
Output the rewritten prompt only.'
build_rewrite_payload() {
local raw_prompt="$1"
local rw_model="${REWRITE_MODEL:-$MODEL}"
jq -n \
--arg model "$rw_model" \
--arg sys "$rewrite_system" \
--arg user "$raw_prompt" \
'{model: $model, max_tokens: 1200,
messages: [{role: "system", content: $sys}, {role: "user", content: $user}]}'
}
rewrite_prompt() {
local raw_prompt="$1"
local payload rw_resp rw_text rw_err
payload=$(build_rewrite_payload "$raw_prompt")
rw_err=$(mktemp)
rw_resp=$(call_api "$payload" 2>"$rw_err") || { cat "$rw_err" >&2; rm -f "$rw_err"; return 1; }
rm -f "$rw_err"
rw_text=$(printf '%s' "$rw_resp" | jq -r '.choices[0].message.content // empty')
if [[ -z "$rw_text" ]]; then
echo "rewrite: empty response from API" >&2
return 1
fi
printf '%s' "$rw_text"
}
# stdin support: read prompt from pipe when no args remain
if [[ $# -eq 0 && ! -t 0 ]]; then
_stdin=$(cat)
[[ -n "$_stdin" ]] && set -- "$_stdin"
fi
# die_ambiguous_sessions <query> <file...> — print matching sessions and exit 1
die_ambiguous_sessions() {
local query=$1; shift
echo "multiple sessions match '$query':" >&2
local f _p
for f in "$@"; do
_p=$(jq -r '.[1].content // ""' "$f" 2>/dev/null | head -1 | cut -c1-60)
printf ' %s %s\n' "$(basename "$f" .json)" "$_p" >&2
done
echo "use a more specific name or ID" >&2
exit 1
}
# find_session <query> — locate session file by exact/substring/content search; echoes path
find_session() {
local query=$1
# Strategy 1: exact match (with and without slug suffix)
local exact="$SESSION_DIR/${query}.json"
if [[ -f "$exact" ]]; then
echo "$exact"
return 0
fi
# also check slug-suffixed exact matches
local f
while IFS= read -r f; do
[[ -f "$f" ]] && { echo "$f"; return 0; }
done < <(shopt -s nullglob; printf '%s\n' "$SESSION_DIR"/*--"${query}".json)
# Strategy 2: substring match on filename
local matches=()
while IFS= read -r f; do
[[ -f "$f" ]] || continue
[[ "$(basename "$f")" == *"$query"* ]] && matches+=("$f")
done < <(shopt -s nullglob; printf '%s\n' "$SESSION_DIR"/*.json)
if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
(( ${#matches[@]} > 1 )) && die_ambiguous_sessions "$query" "${matches[@]}"
# Strategy 3: content search (first user message)
local _fp
matches=()
while IFS= read -r f; do
[[ -f "$f" ]] || continue
_fp=$(jq -r '.[1].content // ""' "$f" 2>/dev/null)
[[ "$_fp" == *"$query"* ]] && matches+=("$f")
done < <(shopt -s nullglob; printf '%s\n' "$SESSION_DIR"/*.json)
if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
(( ${#matches[@]} > 1 )) && die_ambiguous_sessions "$query" "${matches[@]}"
echo "error: no session matching '$query'" >&2
return 1
}
# --- subcommands ---
case "${1:-}" in
config|--config)
case "${2:-}" in
show|print)
sed 's/^\(API_KEY=\).\{1,\}$/\1***/' "$CONFIG"
exit 0 ;;
edit) ;;
"")
if [[ ! -t 1 ]]; then
sed 's/^\(API_KEY=\).\{1,\}$/\1***/' "$CONFIG"
exit 0
fi ;;
*)
echo "usage: shoop config [show|edit]" >&2; exit 1 ;;
esac
echo "$CONFIG"
"${EDITOR:-vi}" "$CONFIG"
exit 0
;;
sessions|--list|list|ls|history)
files=()
while IFS= read -r f; do files+=("$f"); done < <(shopt -s nullglob; printf '%s\n' "$SESSION_DIR"/*.json)
if [ "${#files[@]}" -eq 0 ]; then
echo "no sessions yet — start one with: shoop \"your prompt\"" >&2
exit 0
fi
_seen=""
for f in "${files[@]}"; do
id=$(basename "$f" .json)
ts_id="${id%%--*}"
# deduplicate: skip if same base ID already displayed (double-slug files)
case "$_seen" in *"|$ts_id|"*) continue ;; esac
_seen="${_seen}|$ts_id|"
prompt=$(jq -r '.[1].content // "?"' "$f" 2>/dev/null | head -1 | cut -c1-80)
printf ' %-23s %s\n' "$ts_id" "$prompt"
done
unset _seen
exit 0
;;
resume|--resume)
if [[ -z "${2:-}" ]]; then
echo "usage: shoop resume <session-id-or-name> [\"new prompt\"]" >&2
echo " run 'shoop sessions' to list available" >&2
exit 1
fi
_sf=$(find_session "$2") || exit 1
session_file="$_sf"
SESSION_ID=$(basename "$session_file" .json)
if [[ "$SESSION_ID" == *--* ]]; then
SESSION_SLUG="${SESSION_ID#*--}"
SESSION_ID="${SESSION_ID%%--*}"
fi
messages=$(cat "$session_file")
[[ "$RAW" != "1" ]] && echo "--- resumed $SESSION_ID (model: $MODEL) ---"
# show last assistant message as preview
_last=$(printf '%s' "$messages" | jq -r '[.[] | select(.role == "assistant") | .content // empty] | last // empty')
if [[ "$RAW" != "1" && -n "$_last" ]]; then
_last_lines=$(printf '%s' "$_last" | wc -l | tr -d ' ')
printf '\n last:\n%s\n' "$(printf '%s' "$_last" | head -5)"
(( _last_lines > 5 )) && printf ' [... %d more lines]\n' "$((_last_lines - 5))"
fi
# add continuation prompt — inline arg, interactive, or pipe
if [[ -n "${3:-}" ]]; then
_rp=$(printf '%s' "${*:3}" | jq -Rs .)
messages=$(printf '%s' "$messages" | jq --argjson p "$_rp" '. + [{"role":"user","content":$p}]')
elif [[ -t 0 ]]; then
[[ "$RAW" != "1" ]] && printf '\n'
read -r -p "continue> " _rp < /dev/tty || { [[ "$RAW" != "1" ]] && echo ""; exit 0; }
if [[ -z "$_rp" ]]; then
exit 0
fi
_rp=$(printf '%s' "$_rp" | jq -Rs .)
messages=$(printf '%s' "$messages" | jq --argjson p "$_rp" '. + [{"role":"user","content":$p}]')
fi
[[ "$RAW" != "1" ]] && echo ""
;;
undo|--undo)
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "error: not in a git repository" >&2; exit 1
fi
if ! git diff --quiet HEAD 2>/dev/null || ! git diff --cached --quiet HEAD 2>/dev/null; then
echo "error: uncommitted changes would be lost by undo" >&2
echo " commit or stash your changes first, then retry" >&2
exit 1
fi
head_msg=$(git log -1 --format="%s" 2>/dev/null)
if [[ "$head_msg" != shoop\ checkpoint* ]]; then
echo "error: HEAD is not a shoop checkpoint — cannot undo" >&2
echo " HEAD: $head_msg" >&2; exit 1
fi
git reset HEAD~1 --quiet
echo "checkpoint undone — working tree restored to pre-shoop state"
exit 0
;;
version|--version)
echo "shoop $SHOOP_VERSION"
exit 0
;;
help|--help|-h)
cat <<HELP
shoop $SHOOP_VERSION — a coding agent in bash
usage:
shoop [flags] "your prompt"
echo "prompt" | shoop read prompt from stdin
shoop resume <id> ["prompt"] resume a saved session
shoop sessions list saved sessions
shoop config [show|edit] view or edit config file
shoop undo revert the last shoop checkpoint commit
flags:
--model NAME model to use (current: $MODEL)
--api URL API endpoint (default: from config)
--key KEY API key (default: from config/env)
--zai use z.ai coding API with ZAI_API_KEY
--raw print only assistant text; useful for pipelines
--no-rewrite skip CRISP prompt enhancement
--no-confirm skip confirmation for write/replace/fetch (run_shell always confirms)
--checkpoint git-commit working tree before agent runs
--version show version
api keys (checked in order):
SHOOP_API_KEY > config API_KEY > OPENROUTER_API_KEY > ZAI_API_KEY
HELP
exit 0
;;
-*)
echo "unknown flag: $1 — run 'shoop help' for usage" >&2
exit 1
;;
"")
echo "usage: shoop \"your prompt\" — run 'shoop help' for more" >&2
exit 1
;;
*)
# catch likely command typos — only on strict prefix truncation (e.g. "sess" → "sessions")
# Earlier heuristic (same-first-3 within ±2) false-positived on words like "helper" → "help".
if [[ "$1" =~ ^[a-z]{3,}$ ]]; then
for _known in sessions resume config undo help; do
if [[ ${#1} -lt ${#_known} && "${_known:0:${#1}}" == "$1" ]]; then
echo "shoop: '$1' is not a known command — did you mean '$_known'?" >&2
echo " to run as a prompt: shoop \"$1\"" >&2
exit 1
fi
done
unset _known
fi
raw_input="$1"
SESSION_SLUG=$(slugify "$raw_input")
require_api_key
if [ "$REWRITE" = "1" ]; then
if enhanced=$(rewrite_prompt "$raw_input"); then
if [[ "$RAW" != "1" ]]; then
printf '\033[2m%s\033[0m\n' "$raw_input"
printf ' ↓ rewritten ↓\n'
printf '%s\n\n' "$enhanced"
fi
raw_input="$enhanced"
else
echo "note: prompt rewrite failed, using original" >&2
fi
fi
prompt=$(printf '%s' "$raw_input" | jq -Rs .)
system=$(printf '%s' "$system_prompt" | jq -Rs .)
messages="[{\"role\":\"system\",\"content\":$system},{\"role\":\"user\",\"content\":$prompt}]"
if [[ "$RAW" != "1" ]]; then
echo "--- shoop $SESSION_ID (model: $MODEL) ---"
echo ""
fi
;;
esac
require_api_key
# --- git checkpoint ---
if [[ "$CHECKPOINT" = "1" ]] && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
if [[ -n "$(git status --porcelain)" ]]; then
if git add -A && git commit -m "shoop checkpoint $SESSION_ID" --quiet 2>/dev/null; then
[[ "$RAW" != "1" ]] && echo " [checkpoint: committed working tree before agent run]"
fi
fi
fi
# --- token tracking ---
total_tokens=0
# --- helpers ---
feed_tool_result() {
local cid="$1" res="$2"
messages=$(printf '%s' "$messages" | jq --arg r "$res" --arg cid "$cid" \
'. + [{"role":"tool","tool_call_id":$cid,"content":$r}]')
}
reject_tool() {
result="$1"
[[ "$RAW" != "1" ]] && printf '%s\n\n' "$result"
feed_tool_result "$call_id" "$result"
}
truncate_output() {
local raw="$1" limit="${2:-200}" count keep omitted
[[ -z "$raw" ]] && return
count=$(printf '%s\n' "$raw" | awk 'END {print NR}')
if (( count > limit )); then
keep=$((limit / 4))
omitted=$((count - keep * 2))
printf '%s\n' "$raw" | head -n "$keep"
# inject first error signal from the omitted region
local err_line
err_line=$(printf '%s\n' "$raw" | awk -v s="$((keep+1))" -v e="$((count-keep))" \
'NR>=s && NR<=e && /[Ee]rror|[Ff]ail|[Pp]anic|fatal/ {print NR": "$0; exit}')
if [[ -n "$err_line" ]]; then
printf '\n[... %d lines omitted; first error in gap: %s ...]\n\n' "$omitted" "$err_line"
else
printf '\n[... %d lines omitted ...]\n\n' "$omitted"
fi
printf '%s\n' "$raw" | tail -n "$keep"
else
printf '%s\n' "$raw"
fi
}
run_format_hook() {
[[ -z "${FORMAT_CMD:-}" ]] && return 0
local target="$1"
# FORMAT_CMD is evaluated as a shell string; trust boundary is the user-owned,
# chmod 600 config file. Do NOT accept FORMAT_CMD from any untrusted source.
if bash -c "$FORMAT_CMD \"\$1\"" _ "$target" >/dev/null 2>&1; then
result+=$'\n'"[formatted: $FORMAT_CMD]"
fi
}
confirm_or_skip() {
local prompt_text="$1" deny_msg="$2"
[[ "$CONFIRM" != "1" ]] && return 0
if ! { true </dev/tty; } 2>/dev/null; then
result="[$deny_msg — no terminal]"
[[ "$RAW" != "1" ]] && printf '%s\n\n' "$result"
feed_tool_result "$call_id" "$result"
return 1
fi
local yn
read -r -p "$prompt_text " yn < /dev/tty
[[ "$yn" == "y" || "$yn" == "Y" ]] && return 0
result="[$deny_msg]"
[[ "$RAW" != "1" ]] && printf '%s\n\n' "$result"
feed_tool_result "$call_id" "$result"
return 1
}
# run_with_timeout <secs> <cmd> [args...] — run under timeout if available, else directly
run_with_timeout() {
local secs=$1; shift
if [[ -n "$TIMEOUT_CMD" ]]; then
$TIMEOUT_CMD "$secs" "$@" 2>&1
else
"$@" 2>&1
fi
}
url_host() {
local url="$1" host
host="${url#*://}"
host="${host%%/*}"
if [[ "$host" == \[* ]]; then
host="${host#\[}"
host="${host%%\]*}"
else
host="${host%%:*}"
fi
host=$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]')
printf '%s' "$host"
}
blocked_fetch_host() {
local host="$1"
case "$host" in
localhost|0.0.0.0|::1|fc*|fd*) return 0 ;;
127.*|10.*|169.254.*|192.168.*) return 0 ;;
172.1[6-9].*|172.2[0-9].*|172.3[0-1].*) return 0 ;;
esac
return 1
}
absolute_redirect_url() {
local base="$1" loc="$2" scheme authority path dir
loc="${loc//$'\r'/}"
case "$loc" in
http://*|https://*) printf '%s' "$loc" ;;
//*) scheme="${base%%://*}"; printf '%s:%s' "$scheme" "$loc" ;;
/*) scheme="${base%%://*}"; authority="${base#*://}"; authority="${authority%%/*}"; printf '%s://%s%s' "$scheme" "$authority" "$loc" ;;
*) scheme="${base%%://*}"; authority="${base#*://}"; authority="${authority%%/*}"; path="${base#*://}"; path="${path#*/}"; [[ "$path" == "$base" ]] && path=""; dir="${path%/*}"; [[ "$dir" == "$path" ]] && dir=""; printf '%s://%s/%s%s' "$scheme" "$authority" "${dir:+$dir/}" "$loc" ;;
esac
}
fetch_checked_url() {
local url="$1" fetch_timeout="$2" redirects=0 raw status headers body loc host curl_exit
FETCHED_BODY=""
while true; do
if [[ "$url" != http://* && "$url" != https://* ]]; then
result="[error: URL must start with http:// or https://]"
return 1
fi
host=$(url_host "$url")
if blocked_fetch_host "$host"; then
result="[blocked: URL targets private/loopback/metadata address — $host]"
return 1
fi
curl_exit=0
raw=$(run_with_timeout "$fetch_timeout" curl -sS -i --proto '=https,http' --max-redirs 0 --max-filesize 2097152 --max-time "$fetch_timeout" -A "shoop/$SHOOP_VERSION" "$url" 2>&1) || curl_exit=$?
if (( curl_exit != 0 )); then
result="[error: fetch failed from $url]
$(truncate_output "$raw")"
return 1
fi
status=$(printf '%s' "$raw" | awk '/^HTTP\// {code=$2} END{print code}')
headers="${raw%%$'\r\n\r\n'*}"
[[ "$headers" == "$raw" ]] && headers="${raw%%$'\n\n'*}"
body="${raw#*$'\r\n\r\n'}"
[[ "$body" == "$raw" ]] && body="${raw#*$'\n\n'}"
case "$status" in
301|302|303|307|308)
if (( redirects >= 3 )); then
result="[error: too many redirects from $url]"
return 1
fi
loc=$(printf '%s\n' "$headers" | awk 'tolower($0) ~ /^location:/ {sub(/^[Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]:[[:space:]]*/, ""); print; exit}')
if [[ -z "$loc" ]]; then
result="[error: redirect from $url did not include Location]"
return 1
fi
url=$(absolute_redirect_url "$url" "$loc")
redirects=$((redirects + 1))
;;
*)
FETCHED_BODY="$body"
return 0
;;
esac
done
}
# safe_write <path> <content> <call_id> — TOCTOU-safe atomic write; updates _writes
safe_write() {
local path=$1 content=$2 call_id=$3
local write_target; write_target=$(resolve_path "$path")
if [[ "$write_target" != "$WORKDIR"/* && "$write_target" != "$WORKDIR" ]]; then
reject_tool "[blocked: path escape — $path resolves outside workdir after write]"
return 1
fi
local tmp; tmp=$(mktemp "$(dirname "$write_target")/.shoop-XXXXXX")
printf '%s' "$content" > "$tmp"
mv "$tmp" "$write_target"
_writes="$_writes $path"
}
# trim_messages <keep> — keep system+first-user msg plus last $keep messages
trim_messages() {
local keep=$1
messages=$(printf '%s' "$messages" | jq --argjson k "$keep" '[.[0], .[1]] + .[-$k:]')
}
# manage_context — summarize or trim message history when window fills
manage_context() {
local _msg_count; _msg_count=$(printf '%s' "$messages" | jq 'length')
if (( _msg_count <= 30 )); then
return 0
fi
local _keep=12 _walk=0
# don't split tool_call/result pairs — walk back past any orphaned tool results or assistant+tool_calls
local _boundary_role _has_tc
while (( _walk < 10 )); do
_boundary_role=$(printf '%s' "$messages" | jq -r ".[-$_keep].role")
[[ "$_boundary_role" == "tool" ]] && _keep=$((_keep + 1)) && _walk=$((_walk + 1)) && continue
_has_tc=$(printf '%s' "$messages" | jq -r ".[-$_keep] | if .tool_calls and (.tool_calls | length > 0) then \"yes\" else \"no\" end")
[[ "$_has_tc" == "yes" ]] && _keep=$((_keep + 1)) && _walk=$((_walk + 1)) && continue
break
done
# if boundary walking consumed most messages, just trim — not worth summarizing
if (( _keep >= _msg_count - 4 )); then
trim_messages "$_keep"
printf ' [context: trimmed %d → %d messages]\n' "$_msg_count" "$((2 + _keep))" >&2
return 0
fi
# Line-based cap (not byte-based: head -c mid-UTF-8 can split a multi-byte rune)
local _old_msgs; _old_msgs=$(printf '%s' "$messages" | jq -r \
"[.[2:-$_keep][] | .role + \": \" + (.content // \"[tool call]\" | tostring)] | join(\"\\n\")" 2>/dev/null | head -n 200)
local _sum_payload; _sum_payload=$(jq -n \
--arg model "${REWRITE_MODEL:-$MODEL}" \
--arg hist "$_old_msgs" \
'{model: $model, max_tokens: 400,
messages: [{role: "system", content: "Summarize this agent conversation in under 200 words. Prioritize: exact filenames changed, current state, then remaining work. Note any failures or denied operations. No preamble."},
{role: "user", content: $hist}]}')
local _sum_resp _summary
if _sum_resp=$(call_api "$_sum_payload" 2>/dev/null); then
_summary=$(printf '%s' "$_sum_resp" | jq -r '.choices[0].message.content // empty')
if [[ -n "$_summary" ]]; then
messages=$(printf '%s' "$messages" | jq --arg s "$_summary" --argjson k "$_keep" \
'[.[0], .[1], {"role":"system","content":("Conversation summary:\n" + $s)}] + .[-$k:]')
printf ' [context: summarized %d → %d messages]\n' "$_msg_count" "$(printf '%s' "$messages" | jq 'length')" >&2
else
trim_messages "$_keep"
printf ' [context: trimmed %d → %d messages (summary empty)]\n' "$_msg_count" "$((2 + _keep))" >&2
fi
else
trim_messages "$_keep"
printf ' [context: trimmed %d → %d messages (summary failed)]\n' "$_msg_count" "$((2 + _keep))" >&2
fi
}
# dispatch_tool <tool_name> <tool_args_json> <call_id> — execute tool; sets $result; returns 1 if rejected
dispatch_tool() {
local tool_name=$1 tool_args=$2 call_id=$3
case "$tool_name" in
run_shell)
local cmd cmd_timeout exit_code raw yn _status
cmd=$(printf '%s' "$tool_args" | jq -r '.command')
cmd_timeout=$(printf '%s' "$tool_args" | jq -r '.timeout // 30')
(( cmd_timeout < 1 )) && cmd_timeout=1
(( cmd_timeout > 300 )) && cmd_timeout=300
# run_shell ALWAYS requires confirmation — too dangerous to skip
if ! { true </dev/tty; } 2>/dev/null; then
reject_tool "[blocked: no /dev/tty — run_shell needs an interactive terminal for confirmation]"; return 1
fi
# destructive command warning (non-blocking signal)
case "$cmd" in
*rm\ -rf*|*chmod\ 777*|*curl\ *|*wget\ *|*ssh\ *|*scp\ *)
if [[ "$RAW" = "1" ]]; then
echo "[warning: potentially destructive or network operation]" >&2
else
echo "[warning: potentially destructive or network operation]"
fi ;;
esac
read -r -p "Execute? [y/N] " yn < /dev/tty
if [[ "$yn" != "y" && "$yn" != "Y" ]]; then
reject_tool "[user denied execution]"; return 1
fi
exit_code=0
raw=$(run_with_timeout "$cmd_timeout" bash -c "$cmd") || exit_code=$?
[[ $exit_code -eq 124 ]] && raw+=$'\n[killed: exceeded '"$cmd_timeout"'s timeout]'
_cmds=$((_cmds + 1))
_status="ok"; [[ $exit_code -ne 0 ]] && _status="error"
result="[$_status: exit $exit_code]
$(truncate_output "$raw")"
;;
read_file)
local path start endarg raw total _lines
readarray -t _rf < <(printf '%s' "$tool_args" | jq -r '.path, (.start_line // 1), (.end_line // "")')
path=${_rf[0]} start=${_rf[1]} endarg=${_rf[2]}
if ! require_path "$path"; then return 1
elif [[ ! -e "$path" ]]; then
result="[error: not found — $path]"
elif [[ -f "$path" ]] && is_binary "$path"; then
result="[ok: binary — $(file -b "$path" 2>/dev/null | cut -c1-60), $(( $(wc -c < "$path") )) bytes]"
else
[[ -z "$endarg" ]] && endarg=9999
raw=$(awk -v s="$start" -v e="$endarg" 'NR>=s && NR<=e {printf "%d\t%s\n", NR, $0} NR>e {exit}' "$path" 2>&1) || true
total=$(wc -l < "$path" 2>/dev/null | awk '{print $1}')
_lines=$(printf '%s' "$raw" | grep -c '' 2>/dev/null)
result="[ok: $_lines lines]
$(truncate_output "$raw")"
if [[ "$total" -gt "$endarg" ]]; then
result+=$'\n'"[file has $total lines; showing $start-$endarg — use start_line=$((endarg + 1)) to continue]"
fi
_reads="$_reads $path"
fi
;;
write_file)
local path content
path=$(printf '%s' "$tool_args" | jq -r '.path')