-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaiwb
More file actions
executable file
·3669 lines (3143 loc) · 112 KB
/
aiwb
File metadata and controls
executable file
·3669 lines (3143 loc) · 112 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
#!/usr/bin/env bash
# aiwb - AIworkbench: Multi-Model AI Orchestration Platform
# Version: 2.0.0
# Universal compatibility: Linux, macOS, Termux
# License: GPL-3.0
set -o pipefail
# ============================================================================
# CWD SAFETY (Termux/Android)
# ============================================================================
# When spawned from a bot or after an Android app switch the original CWD may
# no longer exist, causing pwd/getcwd to fail. Fix it early.
if ! pwd >/dev/null 2>&1; then
cd "${HOME}" 2>/dev/null || cd / 2>/dev/null || true
fi
# ============================================================================
# INTERRUPT HANDLING
# ============================================================================
# Global flag to track if we're in an API call
AIWB_IN_API_CALL=0
# Cleanup function for graceful exit
cleanup_on_interrupt() {
echo ""
echo ""
echo "Interrupted! Cleaning up..."
# Kill all background jobs (more reliable than pkill, especially in Termux)
local bg_jobs=$(jobs -p 2>/dev/null)
if [[ -n "$bg_jobs" ]]; then
# First try graceful termination
kill $bg_jobs 2>/dev/null || true
# Give processes 0.5s to exit gracefully
sleep 0.5
# Force kill any remaining processes
kill -9 $bg_jobs 2>/dev/null || true
fi
# Also try pkill as backup for any orphaned curl processes
pkill -P $$ curl 2>/dev/null || true
# Clean up temp files (respect $TMPDIR for Termux)
rm -f "${TMPDIR:-/tmp}"/aiwb_curl_* 2>/dev/null || true
echo "Goodbye!"
exit 130 # Standard exit code for SIGINT
}
# Set up trap for Ctrl+C (SIGINT) and Ctrl+Z (SIGTSTP)
trap cleanup_on_interrupt INT TERM
# ============================================================================
# BOOTSTRAP & LIBRARY LOADING
# ============================================================================
# ============================================================================
# BOOTSTRAP & LIBRARIES
# ============================================================================
# 1. Resolve where this script is actually located
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
# 2. Define Library Directory relative to script
LIB_DIR="${SCRIPT_DIR}/lib"
AIWB_LIB_DIR="${AIWB_LIB_DIR:-$LIB_DIR}"
# 3. Source all libraries found (with deduplication)
# We check LIB_DIR first (standard install), then fallback to local
declare -A seen_paths
for path in "$LIB_DIR" "$AIWB_LIB_DIR" "$HOME/.local/bin/lib"; do
# Resolve to absolute path and deduplicate
if [[ -d "$path" ]]; then
abs_path=$(cd "$path" 2>/dev/null && pwd)
if [[ -n "$abs_path" ]] && [[ -z "${seen_paths[$abs_path]:-}" ]]; then
seen_paths[$abs_path]=1
for lib in "$abs_path"/*.sh; do
if [[ -f "$lib" ]]; then
source "$lib"
fi
done
fi
fi
done
unset seen_paths abs_path
# Safety: clear AIWB_HEADLESS unless this invocation is actually 'aiwb headless'.
# Prevents a leaked AIWB_HEADLESS=1 in the caller's environment from silently
# disabling the TUI for interactive sessions.
if [[ "${1:-}" != "headless" ]]; then
unset AIWB_HEADLESS
fi
# ============================================================================
# INITIALIZATION
# ============================================================================
# Check dependencies
check_dependencies() {
local missing=()
for cmd in bash jq curl; do
have "$cmd" || missing+=("$cmd")
done
if [[ ${#missing[@]} -gt 0 ]]; then
err "Missing required dependencies: ${missing[*]}"
echo ""
echo "Install with:"
if is_termux; then
echo " pkg install ${missing[*]}"
elif is_macos; then
echo " brew install ${missing[*]}"
else
echo " sudo apt install ${missing[*]} # Debian/Ubuntu"
echo " sudo pacman -S ${missing[*]} # Arch"
echo " sudo dnf install ${missing[*]} # Fedora"
fi
exit "$E_DEPENDENCY"
fi
# Optional but recommended
if ! have gum; then
debug "gum not installed - using fallback UI"
fi
}
# Initialize workspace and config
initialize() {
debug "Initializing AIWB..."
check_dependencies
debug "After check_dependencies..."
init_workspace
debug "After init_workspace..."
load_config
debug "After load_config..."
load_session
debug "After load_session..."
debug "About to load keys..."
load_keys || true
debug "After load keys..."
# Auto-fix CRLF if on Termux
if is_termux && [[ -d "$HOME/.local/bin" ]]; then
fix_crlf_scripts
fi
# Skip automatic git detection to avoid delays in Termux
# Users can manually scan repos with /scanrepo or /smartscan commands
AIWB_REPO_ENABLED=false
debug "Skipped detect_repo for faster startup"
}
# Fix CRLF line endings (Termux compatibility)
fix_crlf_scripts() {
local bin_dir="$HOME/.local/bin"
local fixed=0
for script in "$bin_dir"/*.sh; do
[[ -f "$script" ]] || continue
if grep -q $'\r' "$script" 2>/dev/null; then
sed -i 's/\r$//' "$script"
((fixed++))
fi
done
if ((fixed > 0)); then
debug "Fixed CRLF in $fixed scripts"
hash -r
fi
}
# ============================================================================
# COMMANDS
# ============================================================================
# Show help
cmd_help() {
ui_header "AIWB - AI Workbench v2.0"
cat <<'EOF'
A multi-model AI orchestration platform for the command line.
USAGE:
aiwb [command] [options]
MODE-BASED WORKFLOWS (Recommended! 🎯):
Start interactive session, then use modes:
aiwb # Start interactive
> /make # Generate from scratch
> /tweak # Modify existing code
> /debug # Find and fix bugs
Inside each mode:
prompt <text> Set text instructions
instruct <file.md> Load from file
model Choose AI model
uploads <files/dirs> Add context
check [instructions] Configure verification
status Show mode status
run Execute with cost dialog
QUICK COMMANDS:
quick <description> One-shot generation with auto-verify
wizard Interactive guided workflow
improve <suggestion> Improve last output
STANDARD COMMANDS:
(no command) Start interactive chat
chat Interactive chat mode
generate <task> Generate for a task
verify <task> Verify/review content
refine <task> Multi-iteration loop
CONFIGURATION:
keys Manage API keys
settings Configure provider/model
status Show overall status
doctor Check system health
REPOSITORY SCANNING:
scanrepo Deep scan entire repository for full context
smartscan Quick scan of key files (configs, docs, main files)
GITHUB (like Claude Code):
github Interactive GitHub menu
github status Show git status
github clone <repo> Clone a repository
github commit <msg> Commit changes
github push Push to remote
github pull Pull from remote
github sync Sync with remote (fetch, pull/push as needed)
github pr create Create pull request
github issue create Create issue
UTILITY:
history Session history
costs Cost breakdown
templates Browse templates
security-audit Security audit
OPTIONS:
--provider <name> Use specific provider (gemini/claude/openai/groq/xai)
--model <name> Use specific model
--debug Enable debug output
--help, -h Show this help
--version, -v Show version
EXAMPLES:
# Repository analysis
cd my-repo && aiwb scanrepo # Deep scan
cd my-repo && aiwb smartscan # Quick overview
# Mode-based (powerful and flexible!)
aiwb
> /make
make> prompt "Create REST API for users"
make> model # Choose Claude
make> uploads ./docs/ ./src/models/
make> check "Focus on security"
make> run
# Quick one-liners
aiwb quick "Create a password generator"
aiwb wizard
aiwb improve "Add error handling"
# Setup
aiwb keys
aiwb settings
Get started: aiwb wizard (beginners) or aiwb + /make (power users)
Learn more: https://github.com/juanitto-maker/AIworkbench
EOF
}
# Main interactive chat interface
cmd_chat() {
clear 2>/dev/null || true # Don't fail if TERM not set
ui_logo
# Show status
ui_show_status
echo ""
# Check if keys are set
local provider
provider="$(config_get model_provider)"
if ! has_api_key "$provider"; then
echo ""
echo "⚠️ No API key found for $provider."
echo " Please set up your API keys to use AIWB."
echo ""
echo " Run: aiwb keys"
echo " Or use /keys command in chat"
echo ""
fi
# Check for existing context from previous session
if type context_state_exists &>/dev/null && context_state_exists; then
local created_at
created_at=$(context_state_get "created_at" 2>/dev/null || echo "")
if [[ -n "$created_at" ]]; then
local created_epoch now_epoch age_days age_msg
created_epoch=$(date -d "$created_at" +%s 2>/dev/null || date -j -f "%Y-%m-%dT%H:%M:%S" "${created_at:0:19}" +%s 2>/dev/null || echo "0")
now_epoch=$(date +%s)
age_days=$(( (now_epoch - created_epoch) / 86400 ))
if [[ $age_days -eq 0 ]]; then
age_msg="today"
elif [[ $age_days -eq 1 ]]; then
age_msg="yesterday"
else
age_msg="$age_days days ago"
fi
echo ""
warn "Found context from previous session ($age_msg)"
if ui_confirm "Resume with previous context?" "yes"; then
# Get list of available context files
local -a available_files
mapfile -t available_files < <(context_state_list_files)
if [[ ${#available_files[@]} -gt 0 ]]; then
echo ""
echo "Select which context files to load:"
echo ""
# Show file selection UI
local -a selected_files
mapfile -t selected_files < <(ui_select_context_files "${available_files[@]}")
# Load selected files
if [[ ${#selected_files[@]} -gt 0 ]]; then
context_state_load_into_mode "${selected_files[@]}"
echo ""
context_state_show
else
echo "No files selected, starting with empty context"
fi
# Suggest /context command (dimmed)
echo ""
echo -e "\033[2m💡 Tip: Use /context command to add more files later\033[0m"
else
echo "No context files found in previous session"
fi
fi
echo ""
fi
fi
# Quick security check (silent if no issues)
# Disabled automatic check on startup to avoid false positives
# Users can run: aiwb security audit
# if type audit_git_exposure &>/dev/null; then
# # Run git exposure check silently - only outputs if issues found
# audit_git_exposure 2>/dev/null || true
# fi
# Start chat loop
chat_loop
}
# Rotate old log files to save storage
rotate_logs() {
local logs_dir="$1"
local max_logs="${2:-10}" # Keep only last 10 logs by default
local max_size="${3:-10485760}" # 10MB max per log
# Remove logs older than max count
local logs=($(ls -t "$logs_dir"/chat_*.log 2>/dev/null))
if [[ ${#logs[@]} -gt $max_logs ]]; then
for ((i=max_logs; i<${#logs[@]}; i++)); do
rm -f "${logs[$i]}" 2>/dev/null
done
fi
# Truncate logs larger than max size
for log in "$logs_dir"/chat_*.log; do
[[ ! -f "$log" ]] && continue
local size=$(stat -c%s "$log" 2>/dev/null || stat -f%z "$log" 2>/dev/null || echo 0)
if [[ $size -gt $max_size ]]; then
# Keep beginning and end for context (500 lines each)
head -500 "$log" > "$log.tmp"
echo "... [log truncated - $(date)] ..." >> "$log.tmp"
tail -500 "$log" >> "$log.tmp"
mv "$log.tmp" "$log"
fi
done
}
# Chat loop
chat_loop() {
local workspace logs_dir
workspace="$(get_workspace)"
logs_dir="$workspace/logs"
local chat_log="$logs_dir/chat_$(date +%Y%m%d_%H%M%S).log"
# Rotate old logs to save space
rotate_logs "$logs_dir" "$AIWB_LOG_RETENTION" "$AIWB_MAX_LOG_SIZE"
msg "Chat started. Type /help for commands or /exit to quit."
echo ""
while true; do
local input
# Get input - Lazy Gum: terminal stays scrollable until user starts typing
if [[ -t 0 ]] && [[ "${AIWB_TEST_MODE:-0}" != "1" ]] && $GUM_AVAILABLE; then
# Show minimal prompt - terminal is free to scroll
printf "\n${DIM}[Scroll freely, or press any key to type...]${RESET}\n"
# Wait for first keystroke without locking terminal
local first_char
read -n1 -s first_char || continue
# Clear the prompt line
echo -ne "\r\033[K\033[1A\r\033[K"
# Now activate gum with the first character pre-filled
if [[ -n "$first_char" ]]; then
input=$(gum input --value "$first_char" --placeholder "Message or /command..." --width 80) || continue
else
# If first char was just Enter, show gum empty
input=$(gum input --placeholder "Message or /command..." --width 80) || continue
fi
else
# Use safe_read for piped input or Termux compatibility
printf "\033[0m> " # Reset colors before prompt
safe_read input || continue
fi
[[ -z "$input" ]] && continue
# Log input
echo "[$(date -Iseconds)] USER: $input" >> "$chat_log"
# Display user input
echo -e "\n${GREEN}${BOLD}User:${RESET} $input"
# Handle commands
if [[ "$input" == /* ]]; then
handle_slash_command "$input"
local cmd_exit=$?
# If slash command was interrupted, exit chat loop
if [[ $cmd_exit -eq 130 ]]; then
cleanup_on_interrupt
fi
else
# Send to AI with smart routing (auto-detects intent for chat-first workflow)
# Fallback to basic chat if routed version fails
local response_output
if type handle_chat_message_routed &>/dev/null; then
response_output=$(handle_chat_message_routed "$input") || response_output=$(handle_chat_message "$input")
else
response_output=$(handle_chat_message "$input")
fi
local chat_exit=$?
# If interrupted, exit chat loop
if [[ $chat_exit -eq 130 ]]; then
cleanup_on_interrupt
fi
# Only process output if not interrupted
if [[ $chat_exit -eq 0 ]]; then
# Display already happened in handle_chat_message (to stderr)
# response_output contains only the response text for logging
# Log response with truncation for large responses
local response_lines=$(echo "$response_output" | wc -l)
if [[ $response_lines -gt $AIWB_RESPONSE_LINES_THRESHOLD ]]; then
# Log only first 50 and last 50 lines for very long responses
{
echo "$response_output" | head -50
echo "... [truncated $(($response_lines - 100)) lines] ..."
echo "$response_output" | tail -50
} >> "$chat_log"
else
echo "$response_output" >> "$chat_log"
fi
fi
fi
# No gap - messages flow continuously for maximum screen usage
done
}
# Handle slash commands
handle_slash_command() {
local cmd="$1"
shift || true
# Extract command and arguments
local base_cmd="${cmd%% *}"
local args="${cmd#* }"
[[ "$args" == "$base_cmd" ]] && args=""
case "$base_cmd" in
/help)
show_chat_help
;;
/make)
# Check if this is the old quick command or new mode
if [[ -n "$args" ]]; then
# Old style: /make "description"
cmd_make "$args"
else
# New style: enter make mode
mode_loop "make"
fi
;;
/tweak)
mode_loop "tweak"
;;
/debug)
mode_loop "debug"
;;
/keys)
cmd_keys
;;
/models)
cmd_models
;;
/status)
cmd_status_overview
;;
/context)
cmd_context "$args"
;;
/estimate)
cmd_estimate
;;
/generate)
cmd_generate
;;
/verify)
cmd_verify "$args"
;;
/refine)
cmd_refine
;;
/history)
cmd_history
;;
/costs)
cmd_costs
;;
/costreset)
cmd_costreset
;;
/github|/gh)
cmd_github "$args"
;;
/edit)
cmd_edit "$args"
;;
/repo)
cmd_repo "$args"
;;
/scanrepo)
cmd_scanrepo
;;
/smartscan)
cmd_smartscan
;;
/contextload)
cmd_contextload
;;
/contextsave)
cmd_contextsave
;;
/contextshow)
cmd_contextshow
;;
/contextclear)
cmd_contextclear
;;
/contextrefresh)
cmd_contextrefresh
;;
/contextremove)
cmd_contextremove
;;
/quick)
cmd_quick "$args"
;;
/wizard)
cmd_wizard
;;
/improve)
cmd_improve "$args"
;;
/templates)
cmd_templates
;;
/swarm)
cmd_swarm "$args"
;;
/clear)
clear 2>/dev/null || true
ui_logo
;;
/exit|/quit)
# Require explicit confirmation to exit
local confirm_exit
if $GUM_AVAILABLE; then
# Force user to make explicit choice - affirmative required
if gum confirm "Are you sure you want to exit?" --affirmative="Yes, exit" --negative="No, stay"; then
msg "Goodbye!"
exit 0
else
info "Exit cancelled"
fi
else
# Fallback: require explicit 'yes' response
confirm_exit=$(ui_input "Type 'yes' to exit, or press Enter to cancel:")
if [[ "$confirm_exit" == "yes" ]]; then
msg "Goodbye!"
exit 0
else
info "Exit cancelled"
fi
fi
;;
*)
warn "Unknown command: $base_cmd"
echo "Type /help for available commands"
;;
esac
}
# Show chat help
show_chat_help() {
cat <<'EOF'
CODE EDITING (Like Claude Code!):
/edit <file> <task> Edit a specific file with AI
/edit <task> Smart edit (AI finds files to modify)
/repo Show current repository info
/repo none Disable repo mode
/scanrepo Deep scan current folder (works in ANY directory!)
/smartscan Quick scan (configs, docs, main files only)
Just type what you want changed, and AI will edit your files directly!
Example: "Add dark mode to the settings page"
CONTEXT MANAGEMENT:
/contextshow Show current context state
/contextload Load saved context into session
/contextsave Save current context to state
/contextclear Clear all context and start fresh
/contextrefresh Re-scan repository and update context
/contextremove Remove specific file from context
MODE-BASED WORKFLOWS:
/make Generate code from scratch (enter mode)
/tweak Modify/update existing code (enter mode)
/debug Find and fix errors (enter mode)
QUICK COMMANDS:
/quick <description> One-shot generation with auto-verify
/wizard Interactive guided workflow
/improve <suggestion> Improve last output
/templates Browse and use templates
GITHUB:
/github Interactive GitHub menu
/github status Show git status
/github commit Commit changes
/github push Push to remote
/github pull Pull from remote
/github sync Sync with remote (fetch, pull/push as needed)
/github pr create Create pull request
MANAGEMENT:
/status Show overall status
/history Show chat history
/costs Show cost breakdown
/costreset Reset cost counter to $0.00
/swarm Configure swarm mode (multi-agent processing)
Interactive menu to:
- Toggle swarm on/off
- Select strategy (auto/mapreduce/hierarchical)
- Configure worker models
- Configure aggregator models
- Set worker count
CONFIGURATION:
/keys Manage API keys
/models Configure provider/model
/clear Clear screen
/help Show this help
/exit Quit
WORKFLOW:
1. cd into your repo
2. Run: aiwb
3. Ask for changes: "Add feature X to file Y"
4. Review diff and confirm
5. /github commit "message"
6. /github push
EOF
}
# ============================================================================
# STATUS FOOTER HELPERS
# ============================================================================
# Get context summary for status display
get_context_summary() {
# Show ACTUAL context being used (MODE_UPLOADS), not just what's in .context_state
# This ensures the footer accurately reflects what the API will receive
if [[ ${#MODE_UPLOADS[@]} -gt 0 ]]; then
local file_count=${#MODE_UPLOADS[@]}
local image_count=0
# Count images if get_context_images is available
if type get_context_images &>/dev/null; then
while IFS= read -r img; do
[[ -n "$img" ]] && ((image_count++))
done < <(get_context_images)
fi
if [[ $image_count -gt 0 ]]; then
echo "$file_count file(s) ($image_count image(s))"
else
echo "$file_count file(s)"
fi
else
# No in-memory context loaded, but check if persistent context exists (not loaded)
if type context_state_exists &>/dev/null && context_state_exists; then
local scan_count
scan_count=$(context_state_get "last_scan.file_count" 2>/dev/null)
if [[ -n "$scan_count" && "$scan_count" != "null" && "$scan_count" != "0" ]]; then
# Show that context exists but is not loaded
echo "none (saved: $scan_count files - use /contextload)"
else
echo "none"
fi
else
echo "none"
fi
fi
}
# Get total session cost
get_session_cost() {
local workspace logs_dir usage_log
workspace="$(get_workspace 2>/dev/null)" || workspace="$HOME/.aiwb/workspace"
logs_dir="$workspace/logs"
usage_log="$logs_dir/usage.jsonl"
if [[ ! -f "$usage_log" ]]; then
echo "0.00"
return
fi
# Sum costs from current session (today's entries)
local total_cost
if command -v jq &>/dev/null; then
total_cost=$(jq -s 'map(.cost) | add // 0' "$usage_log" 2>/dev/null)
# Ensure we have a valid number, default to 0 if empty or invalid
if [[ -z "$total_cost" ]] || [[ ! "$total_cost" =~ ^[0-9]*\.?[0-9]+$ ]]; then
total_cost="0"
fi
# If cost is > 0 but < 0.01, show minimum of 0.01
if command -v bc &>/dev/null; then
if (( $(echo "$total_cost > 0" | bc -l 2>/dev/null) )) && (( $(echo "$total_cost < 0.01" | bc -l 2>/dev/null) )); then
echo "0.01"
else
printf "%.2f" "$total_cost" 2>/dev/null || echo "0.00"
fi
else
printf "%.2f" "$total_cost" 2>/dev/null || echo "0.00"
fi
else
echo "0.00"
fi
}
# Get message count for current session
get_message_count() {
local workspace logs_dir
workspace="$(get_workspace 2>/dev/null)" || workspace="$HOME/.aiwb/workspace"
logs_dir="$workspace/logs"
# Count "USER:" lines in most recent chat log
local latest_log
latest_log=$(ls -t "$logs_dir"/chat_*.log 2>/dev/null | head -1)
if [[ -f "$latest_log" ]]; then
grep -c "^\\[.*\\] USER:" "$latest_log" 2>/dev/null || echo "0"
else
echo "0"
fi
}
# Get last response cost
get_last_response_cost() {
local workspace logs_dir
workspace="$(get_workspace 2>/dev/null)" || workspace="$HOME/.aiwb/workspace"
logs_dir="$workspace/logs"
local usage_log="$logs_dir/usage.jsonl"
if [[ ! -f "$usage_log" ]]; then
echo "0.00"
return
fi
# Get the last entry's cost
local last_cost
if command -v jq &>/dev/null; then
last_cost=$(tail -1 "$usage_log" | jq -r '.cost // 0' 2>/dev/null)
# Ensure we have a valid number, default to 0 if empty or invalid
if [[ -z "$last_cost" ]] || [[ ! "$last_cost" =~ ^[0-9]*\.?[0-9]+$ ]]; then
last_cost="0"
fi
# If cost is > 0 but < 0.01, show minimum of 0.01
if command -v bc &>/dev/null; then
if (( $(echo "$last_cost > 0" | bc -l 2>/dev/null) )) && (( $(echo "$last_cost < 0.01" | bc -l 2>/dev/null) )); then
echo "0.01"
else
printf "%.2f" "$last_cost" 2>/dev/null || echo "0.00"
fi
else
printf "%.2f" "$last_cost" 2>/dev/null || echo "0.00"
fi
else
echo "0.00"
fi
}
# Show status footer after AI response
show_status_footer() {
local provider model
provider="$(config_get model_provider)"
model="$(config_get model_name)"
# Get terminal width (default 80 for narrow screens)
local term_width
term_width=$(tput cols 2>/dev/null || echo "80")
# Build model display (provider/model)
local model_display="${provider}/${model}"
# Get context summary
local context_summary
context_summary=$(get_context_summary)
# Get cost stats
local session_cost message_count last_cost
session_cost=$(get_session_cost)
last_cost=$(get_last_response_cost)
message_count=$(get_message_count)
# Line 1: Model only
local line1_plain="Model: ${model_display}"
if [[ ${#line1_plain} -gt $term_width ]]; then
local max_len=$((term_width - 3))
local truncated="${line1_plain:0:$max_len}..."
line1="${truncated}"
else
line1="Model: ${BOLD}${model_display}${RESET}"
fi
# Line 2: Context only
local line2_plain="Context: ${context_summary}"
if [[ ${#line2_plain} -gt $term_width ]]; then
local max_len=$((term_width - 3))
local truncated="${line2_plain:0:$max_len}..."
line2="${truncated}"
else
line2="Context: ${DIM}${context_summary}${RESET}"
fi
# Line 3: Cost (last + session total) + messages
local cost_color="${GREEN}"
local session_color="${GREEN}"
if command -v bc &>/dev/null; then
# Color last response cost
if (( $(echo "$last_cost > 0.10" | bc -l 2>/dev/null) )); then
cost_color="${RED}"
elif (( $(echo "$last_cost > 0.01" | bc -l 2>/dev/null) )); then
cost_color="${YELLOW}"
fi
# Color session total
if (( $(echo "$session_cost > 1.00" | bc -l 2>/dev/null) )); then
session_color="${RED}"
elif (( $(echo "$session_cost > 0.10" | bc -l 2>/dev/null) )); then
session_color="${YELLOW}"
fi
fi
local line3_plain="Cost: \$${last_cost} this | \$${session_cost} total | Msgs: ${message_count} | /status"
if [[ ${#line3_plain} -gt $term_width ]]; then
local max_len=$((term_width - 3))
local truncated="${line3_plain:0:$max_len}..."
line3="${truncated}"
else
line3="Cost: ${cost_color}\$${last_cost}${RESET} this | ${session_color}\$${session_cost}${RESET} total | Msgs: ${message_count} | ${DIM}/status${RESET}"
fi
# Print all 3 lines using printf for proper color handling
printf "%b\n" "$line1"
printf "%b\n" "$line2"
printf "%b\n" "$line3"
}
# Handle chat message
handle_chat_message() {
local message="$1"
local provider model
provider="$(config_get model_provider)"
model="$(config_get model_name)"
# Build message with context using centralized function
# This ensures chat respects MODE_UPLOADS and context clearing
local enhanced_message
enhanced_message=$(build_prompt_with_context "$message" "false")
# Check if swarm mode should be used
local response
local exit_code=0
if [[ "$SWARM_ENABLED" = "true" ]]; then
# Estimate tokens to see if swarm is worth it
local tokens=$(estimate_tokens "$enhanced_message")
local min_tokens="${SWARM_MIN_TOKENS:-1000}"
# Force swarm or check if context is large enough
if [[ "$SWARM_FORCE" = "true" ]] || (( tokens >= min_tokens )); then
# Show swarm activation
echo "" >&2
echo -e "${CYAN}🐝 Activating Swarm Mode${RESET}" >&2
echo -e "${DIM}Strategy: $SWARM_STRATEGY | Workers: $SWARM_WORKERS | Context: ${tokens} tokens (min: ${min_tokens})${RESET}" >&2
echo "" >&2
# Try swarm execution
if type swarm_execute &>/dev/null; then
# Swarm execute will output progress to stderr
response=$(swarm_execute "$enhanced_message" "chat" 2>&1)
exit_code=$?
# If swarm failed or returned 1 (fallback), use standard mode
if [[ $exit_code -ne 0 ]]; then
echo -e "${YELLOW}⚠ Swarm mode unavailable, falling back to standard mode${RESET}" >&2
echo "" >&2
ui_blink "Thinking..."
response=$(call_api "$enhanced_message" "$provider" "$model")
exit_code=$?
ui_clear_line
fi
else
# Swarm not available, use standard
ui_blink "Thinking..."
response=$(call_api "$enhanced_message" "$provider" "$model")
exit_code=$?
ui_clear_line
fi
else
# Context too small for swarm
echo -e "${DIM}📝 Using standard mode (context: ${tokens} tokens, need ${min_tokens}+ for swarm)${RESET}" >&2
ui_blink "Thinking..."
response=$(call_api "$enhanced_message" "$provider" "$model")
exit_code=$?
ui_clear_line
fi