-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsashi
More file actions
executable file
·1000 lines (953 loc) · 38.6 KB
/
sashi
File metadata and controls
executable file
·1000 lines (953 loc) · 38.6 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
# SASHI v3.2.3 — Local-first AI orchestration layer
# Inference: ollama run (native streaming, model stays hot)
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/.env" 2>/dev/null || true
# Termux override: use lighter model on Android
_OS_TYPE="$(uname -o 2>/dev/null || echo unknown)"
[[ "$_OS_TYPE" == "Android" ]] && source "$SCRIPT_DIR/.env.termux" 2>/dev/null || true
source "$SCRIPT_DIR/lib/sh/banner.sh" 2>/dev/null || true
source "$SCRIPT_DIR/lib/sh/usb-monitor.sh" 2>/dev/null || true
source "$SCRIPT_DIR/lib/sh/wifi-debug.sh" 2>/dev/null || true
source "$SCRIPT_DIR/lib/sh/file-ops.sh" 2>/dev/null || true
source "$SCRIPT_DIR/lib/sh/llm-write.sh" 2>/dev/null || true
VERSION="3.2.3"
DB_PATH="${SASHI_DB:-$SCRIPT_DIR/db/history.db}"
MODEL="${LOCAL_MODEL:-llama3.2}"
OLLAMA_API="${OLLAMA_HOST:-http://localhost:11434}"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Error reporting — always writes to stderr with component context
sashi_err() { echo -e "${RED}[sashi]${NC} $*" >&2; }
sashi_warn() { echo -e "${YELLOW}[sashi]${NC} $*" >&2; }
# Check ollama once per invocation
check_ollama() {
curl -s --connect-timeout 1 "$OLLAMA_API/api/tags" &>/dev/null
}
show_help() {
sashi_banner 2>/dev/null || true
cat << EOF
$(echo -e "${BLUE}SASHI${NC}") v$VERSION - Local-first AI (llama3.2 via ollama run)
Usage: sashi <command> [prompt]
Commands:
ask <prompt> Quick question (local llama)
code <prompt> Code generation (local llama)
local <prompt> Same as ask
online <prompt> Cloud query (OpenRouter free models)
cloud <prompt> Alias for online
chat Interactive chat (ollama run)
history Show query history
status System status + model availability
models List available models
gmail <cmd> Gmail access (search/recent/export)
voice [opts] Voice input (--gui, --continuous)
8b <prompt> Query via sashi-llama-8b (8B model, better quality)
kanban [board|state|backlog|open|wip|closed] Kanban board
write <file> <prompt> Run llama, write output to file
wallog [N] Modelfile git log ↔ SQL WAL changelog (default 10 entries)
probe [sync|list|recommend|export|write|status] gRPC probe commands
grpc [start|stop|status|restart] Manage gRPC server daemons
android-studio [project_path] Sashi Android Studio — terminal IDE (Android/Kotlin/Flutter)
adb [status|devices|wireless|shell|logcat|install|push|pull] Android device tools
usb [scan|watch|storage|details|tree|search|export] USB device detection
wifi [init|connect|scan|status|logcat|shell|disconnect] ADB WiFi wireless debug
hf <prompt> HuggingFace Inference API (online, free tier)
help Show this help
Pipe support:
cat file.py | sashi code 'explain this'
git diff | sashi code 'review this'
Speed: Uses 'ollama run' (native streaming, model stays hot)
EOF
}
# Async query logging — non-blocking, injection-safe via env vars + single-quoted heredoc
log_query() {
local model="$1" prompt="$2" resp_len="$3" duration="$4"
{
SASHI_LOG_DB="$DB_PATH" \
SASHI_LOG_MODEL="$model" \
SASHI_LOG_PROMPT="$prompt" \
SASHI_LOG_RESP_LEN="$resp_len" \
SASHI_LOG_DURATION="$duration" \
python3 << 'PYEOF' 2>/dev/null
import sqlite3, os
db = os.environ['SASHI_LOG_DB']
model = os.environ['SASHI_LOG_MODEL']
prompt = os.environ['SASHI_LOG_PROMPT']
resp_len = int(os.environ.get('SASHI_LOG_RESP_LEN', 0))
duration = int(os.environ.get('SASHI_LOG_DURATION', 0))
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS queries (
id INTEGER PRIMARY KEY,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
model TEXT, prompt TEXT,
response_length INTEGER, duration_ms INTEGER)''')
c.execute('INSERT INTO queries (model, prompt, response_length, duration_ms) VALUES (?, ?, ?, ?)',
(model, prompt, resp_len, duration))
conn.commit()
conn.close()
PYEOF
} &
}
# Core query function - uses ollama run (proven fast on low-end hardware)
# ollama run streams tokens natively + keeps model loaded in memory
llama_query() {
local prompt="[Today: $(date +%Y-%m-%d)] $1"
local start_time=$(date +%s%3N)
if ! check_ollama; then
echo -e "${RED}Ollama not running. Start with: ollama-up${NC}"
return 1
fi
local response
if ! response=$(timeout 60 ollama run "$MODEL" "$prompt" 2>&1); then
local exit_code=$?
if [[ $exit_code -eq 124 ]]; then
sashi_err "Inference timed out after 60s (model: $MODEL)"
else
sashi_err "Inference failed (exit $exit_code): $response"
fi
return 1
fi
local duration=$(( $(date +%s%3N) - start_time ))
echo "$response"
log_query "$MODEL" "$prompt" "${#response}" "$duration"
}
# Code-specific query with system context
code_query() {
local prompt="You are a coding assistant. Be concise. $1"
llama_query "$prompt"
}
# HuggingFace Inference API query (free tier)
hf_query() {
local prompt="$1"
local model="${HF_MODEL:-meta-llama/Llama-3.2-3B-Instruct}"
local api_url="https://api-inference.huggingface.co/models/${model}/v1/chat/completions"
local start_time=$(date +%s%3N)
echo -e "${BLUE}HuggingFace${NC} ($model)"
local escaped_prompt
escaped_prompt=$(printf '%s' "$prompt" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))')
local auth_header="Content-Type: application/json"
if [ -n "$HF_TOKEN" ]; then
auth_header="Authorization: Bearer $HF_TOKEN"
fi
curl -sN --max-time 30 --connect-timeout 5 "$api_url" \
-H "Content-Type: application/json" \
${HF_TOKEN:+-H "Authorization: Bearer $HF_TOKEN"} \
-d "{\"model\":\"$model\",\"messages\":[{\"role\":\"user\",\"content\":$escaped_prompt}],\"stream\":true,\"max_tokens\":512}" \
2>/dev/null | while IFS= read -r line; do
line="${line#data: }"
[ "$line" = "[DONE]" ] && break
[ -z "$line" ] && continue
printf '%s' "$line" | python3 -c 'import sys,json
try:
d=json.load(sys.stdin)
c=d.get("choices",[{}])[0].get("delta",{}).get("content","")
if c: print(c,end="",flush=True)
except: pass' 2>/dev/null
done
echo ""
local duration=$(( $(date +%s%3N) - start_time ))
log_query "huggingface:$model" "$prompt" "0" "$duration"
}
# Online query via OpenRouter (free cloud models), falls back to HuggingFace
online_query() {
local prompt="$1"
if [ -z "$OPENROUTER_API_KEY" ]; then
echo -e "${YELLOW}OpenRouter not configured — trying HuggingFace...${NC}"
hf_query "$prompt"
return $?
fi
local model="${OPENROUTER_MODEL:-meta-llama/llama-3.1-8b-instruct:free}"
local start_time=$(date +%s%3N)
echo -e "${BLUE}Cloud${NC} ($model)"
# Escape prompt for JSON
local escaped_prompt
escaped_prompt=$(printf '%s' "$prompt" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))')
curl -sN --max-time 30 --connect-timeout 5 \
https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"model\":\"$model\",\"messages\":[{\"role\":\"user\",\"content\":$escaped_prompt}],\"stream\":true}" \
2>/dev/null | while IFS= read -r line; do
# SSE format: data: {...}
line="${line#data: }"
[ "$line" = "[DONE]" ] && break
[ -z "$line" ] && continue
local content
content=$(echo "$line" | python3 -c 'import sys,json
try:
d=json.load(sys.stdin)
c=d.get("choices",[{}])[0].get("delta",{}).get("content","")
if c: print(c,end="")
except: pass' 2>/dev/null)
[ -n "$content" ] && printf '%s' "$content"
done
echo ""
local duration=$(( $(date +%s%3N) - start_time ))
log_query "openrouter:$model" "$prompt" "0" "$duration"
}
_grpc_pid_check() {
local name="$1" port="$2" pidfile="$3"
if [ -f "$pidfile" ]; then
local pid
pid=$(cat "$pidfile" 2>/dev/null)
if kill -0 "$pid" 2>/dev/null; then
echo -e " $name ${GREEN}running${NC} pid=$pid :$port"
return 0
fi
fi
echo -e " $name ${RED}stopped${NC} :$port"
return 1
}
show_status() {
echo -e "${BLUE}SASHI System Status${NC} v$VERSION"
echo "===================="
echo -e "Mode: ${GREEN}Local-first (zero cloud costs)${NC}"
echo -e "Model: $MODEL"
if check_ollama; then
echo -e "Ollama: ${GREEN}Running${NC}"
else
echo -e "Ollama: ${RED}Stopped${NC}"
fi
if [ -n "$OPENROUTER_API_KEY" ]; then
echo -e "Online: ${GREEN}Configured${NC} (${OPENROUTER_MODEL:-meta-llama/llama-3.1-8b-instruct:free})"
else
echo -e "Online: ${YELLOW}OpenRouter: unset${NC} → HuggingFace fallback ${GREEN}ready${NC}"
fi
# USB/WiFi status
if type usb_statusline &>/dev/null; then
echo -e "USB: $(usb_statusline)"
fi
if type wifi_statusline &>/dev/null; then
echo -e "WiFi ADB: $(wifi_statusline)"
fi
# Detect environment
if [[ "$_OS_TYPE" == "Android" ]]; then
echo -e "Env: Termux (Android) — $(uname -a)"
else
echo -e "Env: $(uname -a)"
fi
echo ""
echo "gRPC Servers:"
_grpc_pid_check "kanban-pmo" "${GRPC_KANBAN_PORT:-50051}" "/tmp/sashi-grpc-kanban.pid"
_grpc_pid_check "probe " "${GRPC_PROBE_PORT:-50052}" "/tmp/sashi-grpc-probe.pid"
echo ""
echo "Local Models:"
ollama list 2>/dev/null || echo " (none)"
echo ""
echo "Query Stats:"
python3 << PYEOF 2>/dev/null || echo " No history yet"
import sqlite3
conn = sqlite3.connect('$DB_PATH')
c = conn.cursor()
c.execute('SELECT COUNT(*) FROM queries')
total = c.fetchone()[0]
c.execute('SELECT model, COUNT(*), AVG(duration_ms) FROM queries GROUP BY model')
by_model = c.fetchall()
print(f' Total: {total}')
for m, cnt, avg in by_model:
print(f' {m}: {cnt} queries, avg {int(avg or 0)}ms')
PYEOF
echo ""
echo "Latest Changes:"
CHANGELOG="$SCRIPT_DIR/CHANGELOG.md"
if [ -f "$CHANGELOG" ]; then
# Extract lines from first ## heading down to the blank line before second ##
awk '/^## v/{found++} found==1{print " "$0} found==2{exit}' "$CHANGELOG" | head -15
echo -e " ${BLUE}Full changelog: sashi changelog | ~/Desktop/SASHI-CHANGELOG.md${NC}"
else
echo " (no CHANGELOG.md)"
fi
}
show_history() {
python3 << 'PYEOF'
import sqlite3, os
conn = sqlite3.connect(os.path.expanduser('~/ollama-local/db/history.db'))
c = conn.cursor()
c.execute('SELECT id, timestamp, model, substr(prompt, 1, 50), duration_ms FROM queries ORDER BY id DESC LIMIT 20')
rows = c.fetchall()
if rows:
print(f"{'ID':<4} {'Time':<20} {'Model':<12} {'Prompt':<50} {'ms':<6}")
print('-' * 96)
for r in rows:
prompt = (r[3] or '').replace('\n', ' ')[:47]
if len(r[3] or '') > 47:
prompt += '...'
print(f"{r[0]:<4} {r[1]:<20} {r[2]:<12} {prompt:<50} {r[4] or 0:<6}")
else:
print('No history yet')
PYEOF
}
interactive_chat() {
echo -e "${BLUE}SASHI Chat${NC} ($MODEL via ollama run)"
echo "Type 'exit' to quit, or just use the native ollama interface"
echo "=============================="
ollama run "$MODEL"
}
# Environment detection (Termux, Linux, etc.)
detect_environment() {
if [[ "$_OS_TYPE" == "Android" ]]; then
SASHI_ENV="termux"
if curl -s --connect-timeout 1 http://localhost:11434/api/tags > /dev/null 2>&1; then
SASHI_ROUTE="local"
elif [ -n "$OPENROUTER_API_KEY" ]; then
SASHI_ROUTE="online"
else
SASHI_ROUTE="offline"
fi
else
SASHI_ENV="linux"
SASHI_ROUTE="local"
fi
}
# Read stdin if available
STDIN_DATA=""
[ ! -t 0 ] && STDIN_DATA=$(cat -)
# Main command routing
case "${1:-help}" in
ask)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { echo "Usage: sashi ask <prompt>"; exit 1; }
llama_query "$prompt"
;;
code)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$*" ] && [ -z "$STDIN_DATA" ] && { echo "Usage: sashi code <prompt>"; exit 1; }
code_query "$prompt"
;;
local)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { echo "Usage: sashi local <prompt>"; exit 1; }
llama_query "$prompt"
;;
online|cloud)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { echo "Usage: sashi online <prompt>"; exit 1; }
online_query "$prompt"
;;
chat)
interactive_chat
;;
history)
show_history
;;
status)
show_status
;;
changelog)
CHANGELOG="$SCRIPT_DIR/CHANGELOG.md"
if [ -f "$CHANGELOG" ]; then
cat "$CHANGELOG"
else
echo "No CHANGELOG.md found at $CHANGELOG"
fi
;;
file)
shift
if ! type fops_info &>/dev/null; then
source "$SCRIPT_DIR/lib/sh/file-ops.sh" || { echo "file-ops.sh not found"; exit 1; }
fi
subcmd="${1:-help}"; shift 2>/dev/null || true
case "$subcmd" in
read) fops_read "$@" ;;
write) fops_write "$@" ;;
append) fops_append "$@" ;;
parse)
fmt="${1:-auto}"; shift 2>/dev/null || true
path="${1:-}"; shift 2>/dev/null || true
case "$fmt" in
csv) fops_parse_csv "$path" "$@" ;;
json) fops_parse_json "$path" "$@" ;;
jsonl) fops_parse_jsonl "$path" "$@" ;;
text) fops_parse_text "$path" "$@" ;;
auto) fops_detect_op "$path" && fops_info "$path" ;;
*) fops_parse_text "$fmt" "$@" ;;
esac ;;
copy) fops_copy "$@" ;;
move) fops_move "$@" ;;
delete) fops_delete "$@" ;;
batch) fops_batch "$@" ;;
check) fops_check_corrupt "$@" ;;
recover) fops_recover "$@" ;;
info) fops_info "$@" ;;
stream) fops_stream "$@" ;;
split) fops_split "$@" ;;
join) fops_join "$@" ;;
rotate) fops_rotate "$@" ;;
detect) fops_detect_op "$@" ;;
help|--help|-h|*)
echo ""
echo " sashi file — File Operations (v3.2.2)"
echo ""
echo " READING"
echo " sashi file read <path> [enc] [head_n] size-aware, encoding-safe"
echo " sashi file stream <path> [filter] real-time tail -f"
echo ""
echo " WRITING"
echo " sashi file write <path> <content> [--backup] atomic (tmp→mv)"
echo " sashi file append <path> <content> [max_mb] flock concurrent-safe"
echo " sashi file rotate <path> [keep_n] log rotation"
echo ""
echo " PARSING"
echo " sashi file parse csv <path> [col] [delim]"
echo " sashi file parse json <path> [jq-query]"
echo " sashi file parse jsonl <path> [head_n]"
echo " sashi file parse text <path> [stats|head|tail|grep]"
echo " sashi file parse auto <path> detect + info"
echo ""
echo " FILE SYSTEM OPS"
echo " sashi file copy <src> <dst> [verify=1] rsync + sha256 verify"
echo " sashi file move <src> <dst> cross-device safe"
echo " sashi file delete <path> [trash|shred|force|dry]"
echo ""
echo " BATCH"
echo " sashi file batch <op> <find-pattern> [parallel] [args]"
echo " ops: parse|hash|stat|chmod|chown|gzip|copy|delete"
echo ""
echo " ERROR HANDLING"
echo " sashi file check <path> corrupt/integrity check"
echo " sashi file recover <path> [backup|git|truncate]"
echo " sashi file detect <path> op-type + size class"
echo ""
echo " PERFORMANCE"
echo " sashi file split <path> [lines|size] [val] split large files"
echo " sashi file join <pattern> <out> join split parts"
echo " sashi file info <path> full info card"
echo ""
;;
esac
;;
wallog)
shift
LIMIT="${1:-10}"
DB="$SCRIPT_DIR/db/history.db"
BOLD="\033[1m" CYAN="\033[36m" YELLOW="\033[33m" GREEN="\033[32m" DIM="\033[2m" NC="\033[0m"
echo -e "\n${BOLD}${CYAN}══ Modelfile Changes (git log) ══${NC}"
cd "$SCRIPT_DIR" && {
git log --oneline --follow -- Modelfile.fast 2>/dev/null | sed 's/^/ [fast] /'
git log --oneline --follow -- Modelfile.8b 2>/dev/null | sed 's/^/ [ 8b ] /'
} | sort -k3 -r | head -"$LIMIT" \
| while read -r line; do
hash=$(echo "$line" | awk '{print $2}')
rest=$(echo "$line" | cut -d' ' -f3-)
tag=$(echo "$line" | awk '{print $1}')
echo -e " ${tag} ${YELLOW}${hash}${NC} ${rest}"
done
echo -e "\n${BOLD}${CYAN}══ SQL changelog table (history.db) ══${NC}"
if [ -f "$DB" ]; then
sqlite3 -separator ' | ' "$DB" \
"SELECT version, date, summary FROM changelog ORDER BY id DESC LIMIT ${LIMIT};" 2>/dev/null \
| while IFS='|' read -r line; do
echo -e " ${GREEN}${line}${NC}"
done || echo -e " ${DIM}(no rows)${NC}"
else
echo -e " ${DIM}DB not found: $DB${NC}"
fi
echo -e "\n${BOLD}${CYAN}══ SQL commits table (history.db) ══${NC}"
if [ -f "$DB" ]; then
sqlite3 -separator ' | ' "$DB" \
"SELECT hash, version_tag, timestamp, message FROM commits ORDER BY id DESC LIMIT ${LIMIT};" 2>/dev/null \
| while IFS='|' read -r line; do
echo -e " ${DIM}${line}${NC}"
done || echo -e " ${DIM}(no rows)${NC}"
fi
echo -e "\n${BOLD}${CYAN}══ WAL checkpoint status ══${NC}"
if [ -f "$DB" ]; then
result=$(sqlite3 "$DB" "PRAGMA wal_checkpoint(PASSIVE);" 2>/dev/null)
echo -e " ${DIM}checkpoint(busy|log|checkpointed): ${result}${NC}"
wal_size=$(stat -c%s "${DB}-wal" 2>/dev/null || echo 0)
echo -e " ${DIM}WAL file size: ${wal_size} bytes${NC}"
fi
echo ""
;;
models)
ollama list 2>/dev/null || echo "Ollama not running"
;;
gmail)
shift
"$SCRIPT_DIR/mcp/gmail/tools/gmail-cli" "$@"
;;
voice)
shift
case "${1:---help}" in
--gui|-g)
"$SCRIPT_DIR/mcp/voice/tools/voice-gui"
;;
--continuous|-c)
"$SCRIPT_DIR/mcp/voice/tools/voice-input" --continuous
;;
--install)
"$SCRIPT_DIR/mcp/voice/tools/install-voice"
;;
--help|-h)
echo "Voice commands:"
echo " sashi voice Single voice prompt"
echo " sashi voice --continuous Continuous listening"
echo " sashi voice --gui Desktop GUI"
echo " sashi voice --install Install dependencies"
;;
*)
"$SCRIPT_DIR/mcp/voice/tools/voice-input" "$@"
;;
esac
;;
help|--help|-h)
show_help
;;
8b)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { echo "Usage: sashi 8b <prompt>"; exit 1; }
prompt="[Today: $(date +%Y-%m-%d)] $prompt"
if ! check_ollama; then
echo -e "${RED}Ollama not running. Start with: ollama-up${NC}"
exit 1
fi
if ! timeout 90 ollama run sashi-llama-8b "$prompt"; then
[[ $? -eq 124 ]] && sashi_err "8B inference timed out after 90s"
exit 1
fi
;;
kanban)
shift
subcmd="${1:-board}"
shift || true
KANBAN_DIR="$HOME/kanban-pmo/kanban"
case "$subcmd" in
board)
echo "=== Kanban Board ==="
for col in backlog open wip closed; do
count=$(ls "$KANBAN_DIR/$col/"*.md 2>/dev/null | wc -l)
printf " %-10s %s cards\n" "$col" "$count"
done
;;
state)
echo "=== Kanban State ==="
for col in backlog open wip closed; do
echo "[$col]"
ls "$KANBAN_DIR/$col/"*.md 2>/dev/null | xargs -I{} basename {} .md | sed 's/^/ /'
done
echo "=== DB ==="
sqlite3 "$DB_PATH" "SELECT COUNT(*) || ' history rows'" 2>/dev/null || echo " DB not available"
;;
backlog|open|wip|closed)
echo "=== $subcmd ==="
for f in "$KANBAN_DIR/$subcmd/"*.md; do
[[ -f "$f" ]] && basename "$f" .md | sed 's/^/ /'
done
;;
*)
echo "Usage: sashi kanban [board|state|backlog|open|wip|closed]"
;;
esac
;;
write)
shift
subcmd="${1:-help}"
# detect if first arg is a flag or subcommand
case "$subcmd" in
--read|-r)
shift
infile="$1"; outfile="$2"; shift 2
llmw_process "$infile" "$outfile" "$@"
;;
--append|-a)
shift
llmw_append "$@"
;;
--batch|-b)
shift
llmw_batch "$@"
;;
--fmt|-f)
shift
llmw_write_fmt "$@"
;;
--pipe|-p)
shift
llmw_pipe "$@"
;;
--safe|-s)
shift
llmw_safe_write "$@"
;;
help|--help|-h)
echo ""
echo " sashi write — LLM File Write System (v3.2.2)"
echo ""
echo " sashi write <file> <prompt> prompt → file (atomic)"
echo " sashi write --read <in> <out> <prompt> read file → llama → write"
echo " sashi write --append <file> <prompt> append AI output to file"
echo " sashi write --batch <glob> <dir> <prompt> process multiple files"
echo " sashi write --fmt <json|csv|md|sh> <out> <prompt> format-validated"
echo " sashi write --pipe <out> <prompt> cat file | sashi write --pipe"
echo " sashi write --safe <file> <prompt> retry with fallback model"
echo ""
;;
*)
# default: original behaviour — sashi write <file> <prompt>
outfile="$subcmd"; shift
prompt="$*"
[[ -z "$outfile" || -z "$prompt" ]] && {
bash "$0" write help; exit 1; }
llmw_write "$outfile" "$prompt"
;;
esac
;;
probe)
shift
subcmd="${1:-status}"
shift || true
GRPC_PORT="${GRPC_PORT:-50051}"
GENERATED_DIR="$HOME/kanban-pmo/generated"
case "$subcmd" in
sync)
repo_name="${1:-}"
python3 - "$repo_name" "$GRPC_PORT" "$GENERATED_DIR" << 'PYEOF'
import sys
sys.path.insert(0, sys.argv[3])
import grpc, kanban_pb2, kanban_pb2_grpc
channel = grpc.insecure_channel(f"localhost:{sys.argv[2]}")
stub = kanban_pb2_grpc.ProbeSyncStub(channel)
try:
resp = stub.SyncRepo(kanban_pb2.SyncRepoRequest(repo_name=sys.argv[1], force=False),
timeout=90)
if resp.ok:
print(f"ok files_synced={resp.files_synced}")
else:
print(f"err {resp.error}", file=sys.stderr)
sys.exit(1)
except grpc.RpcError as e:
print(f"gRPC error: {e.code()} {e.details()}", file=sys.stderr)
sys.exit(1)
PYEOF
;;
write)
target_path="${1:-}"
shift || true
content="${*:-$(cat -)}"
[[ -z "$target_path" ]] && { echo "Usage: sashi probe write <path> <content>"; exit 1; }
python3 - "$target_path" "$content" "$GRPC_PORT" "$GENERATED_DIR" << 'PYEOF'
import sys
sys.path.insert(0, sys.argv[4])
import grpc, kanban_pb2, kanban_pb2_grpc
channel = grpc.insecure_channel(f"localhost:{sys.argv[3]}")
stub = kanban_pb2_grpc.ProbeSyncStub(channel)
try:
resp = stub.FsWrite(kanban_pb2.FsWriteRequest(target_path=sys.argv[1], content=sys.argv[2]),
timeout=10)
if resp.ok:
print(f"ok written={resp.written_path}")
else:
print(f"err {resp.error}", file=sys.stderr)
sys.exit(1)
except grpc.RpcError as e:
print(f"gRPC error: {e.code()} {e.details()}", file=sys.stderr)
sys.exit(1)
PYEOF
;;
status)
python3 - "$GRPC_PORT" "$GENERATED_DIR" << 'PYEOF'
import sys
sys.path.insert(0, sys.argv[2])
import grpc, kanban_pb2, kanban_pb2_grpc
channel = grpc.insecure_channel(f"localhost:{sys.argv[1]}")
try:
grpc.channel_ready_future(channel).result(timeout=2)
print(f"gRPC server reachable on :{sys.argv[1]}")
except grpc.FutureTimeoutError:
print(f"gRPC server not reachable on :{sys.argv[1]} — start with: python3 ~/kanban-pmo/server/grpc_server.py", file=sys.stderr)
sys.exit(1)
PYEOF
;;
list)
# List repos tracked by probe server :50052
python3 - "$GRPC_PORT" "$GENERATED_DIR" << 'PYEOF'
import sys
sys.path.insert(0, '/home/' + __import__('os').environ['USER'] + '/persist-memory-probe/webhooks/grpc/generated')
import grpc, probe_pb2, probe_pb2_grpc
ch = grpc.insecure_channel('localhost:50052')
try:
grpc.channel_ready_future(ch).result(timeout=2)
except grpc.FutureTimeoutError:
print('probe server not running on :50052', file=sys.stderr); sys.exit(1)
resp = probe_pb2_grpc.RepoServiceStub(ch).ListRepos(probe_pb2.Empty(), timeout=15)
for r in resp.repos:
flag = '!' if r.uncommitted else ' '
print(f" {flag} {r.name:<25s} {r.branch:<12s} uncommitted={r.uncommitted}")
PYEOF
;;
recommend)
op="${*:-push code}"
python3 - "$op" << 'PYEOF'
import sys
sys.path.insert(0, '/home/' + __import__('os').environ['USER'] + '/persist-memory-probe/webhooks/grpc/generated')
import grpc, probe_pb2, probe_pb2_grpc
ch = grpc.insecure_channel('localhost:50052')
try:
grpc.channel_ready_future(ch).result(timeout=2)
except grpc.FutureTimeoutError:
print('probe server not running on :50052', file=sys.stderr); sys.exit(1)
op = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else 'push code'
rec = probe_pb2_grpc.CredentialServiceStub(ch).GetRecommendation(
probe_pb2.OperationRequest(operation=op), timeout=5)
print(f"type: {rec.credential_type}")
print(f"reason: {rec.reason}")
print(f"example: {rec.example_command}")
PYEOF
;;
export)
limit="${1:-0}"
python3 - "$limit" << 'PYEOF'
import sys
sys.path.insert(0, '/home/' + __import__('os').environ['USER'] + '/persist-memory-probe/webhooks/grpc/generated')
import grpc, probe_pb2, probe_pb2_grpc
ch = grpc.insecure_channel('localhost:50052')
try:
grpc.channel_ready_future(ch).result(timeout=2)
except grpc.FutureTimeoutError:
print('probe server not running on :50052', file=sys.stderr); sys.exit(1)
limit = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 0
examples = probe_pb2_grpc.TrainingServiceStub(ch).ExportTrainingData(
probe_pb2.ExportRequest(include_base=True, limit=limit), timeout=15)
count = 0
for ex in examples:
print(ex.jsonl)
count += 1
print(f'# {count} examples', file=sys.stderr)
PYEOF
;;
*)
echo "Usage: sashi probe [sync [repo]|list|recommend <op>|export [N]|write <path> <content>|status]"
;;
esac
;;
grpc)
shift
subcmd="${1:-status}"
shift || true
KANBAN_PID="/tmp/sashi-grpc-kanban.pid"
PROBE_PID="/tmp/sashi-grpc-probe.pid"
GRPC_KANBAN_PORT="${GRPC_KANBAN_PORT:-50051}"
GRPC_PROBE_PORT="${GRPC_PROBE_PORT:-50052}"
_grpc_port_free() {
local port="$1"
! ss -tlnp 2>/dev/null | grep -q ":${port} " && \
! lsof -iTCP:"$port" -sTCP:LISTEN &>/dev/null
}
_grpc_start() {
local name="$1" script="$2" pidfile="$3" port="$4"
if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile" 2>/dev/null)" 2>/dev/null; then
echo -e " $name ${YELLOW}already running${NC} (pid=$(cat "$pidfile"))"
return
fi
if ! _grpc_port_free "$port"; then
sashi_err "Port $port already in use — cannot start $name"
return 1
fi
GRPC_BIND="127.0.0.1" nohup python3 "$script" > "/tmp/sashi-grpc-${name}.log" 2>&1 &
echo $! > "$pidfile"
sleep 1
if kill -0 "$(cat "$pidfile" 2>/dev/null)" 2>/dev/null; then
echo -e " $name ${GREEN}started${NC} pid=$(cat "$pidfile") :${port} (localhost only)"
else
echo -e " $name ${RED}failed to start${NC} — check /tmp/sashi-grpc-${name}.log"
fi
}
_grpc_stop() {
local name="$1" pidfile="$2"
if [ -f "$pidfile" ]; then
local pid
pid=$(cat "$pidfile" 2>/dev/null)
if kill -0 "$pid" 2>/dev/null; then
kill "$pid" && rm -f "$pidfile"
echo -e " $name ${YELLOW}stopped${NC}"
else
rm -f "$pidfile"
echo -e " $name was not running"
fi
else
echo -e " $name not running"
fi
}
case "$subcmd" in
start)
echo "Starting gRPC servers..."
_grpc_start "kanban" "$HOME/kanban-pmo/server/grpc_server.py" "$KANBAN_PID" "$GRPC_KANBAN_PORT"
_grpc_start "probe" "$HOME/persist-memory-probe/webhooks/grpc/probe_server.py" "$PROBE_PID" "$GRPC_PROBE_PORT"
;;
stop)
echo "Stopping gRPC servers..."
_grpc_stop "kanban" "$KANBAN_PID"
_grpc_stop "probe" "$PROBE_PID"
;;
restart)
echo "Restarting gRPC servers..."
_grpc_stop "kanban" "$KANBAN_PID"
_grpc_stop "probe" "$PROBE_PID"
sleep 1
_grpc_start "kanban" "$HOME/kanban-pmo/server/grpc_server.py" "$KANBAN_PID" "$GRPC_KANBAN_PORT"
_grpc_start "probe" "$HOME/persist-memory-probe/webhooks/grpc/probe_server.py" "$PROBE_PID" "$GRPC_PROBE_PORT"
;;
status)
echo "gRPC Servers:"
_grpc_pid_check "kanban-pmo" "$GRPC_KANBAN_PORT" "$KANBAN_PID"
_grpc_pid_check "probe " "$GRPC_PROBE_PORT" "$PROBE_PID"
;;
logs)
echo "=== kanban log ==="
tail -20 /tmp/sashi-grpc-kanban.log 2>/dev/null || echo " (no log)"
echo "=== probe log ==="
tail -20 /tmp/sashi-grpc-probe.log 2>/dev/null || echo " (no log)"
;;
*)
echo "Usage: sashi grpc [start|stop|restart|status|logs]"
;;
esac
;;
android-studio|ide)
shift
PROJECT="${1:-$HOME/projects/hello-android}"
exec python3 "$SCRIPT_DIR/mcp/ide/sashi-ide" "$PROJECT"
;;
adb)
shift
ADB_BIN="$HOME/Android/platform-tools/adb"
if [[ ! -x "$ADB_BIN" ]]; then
echo "adb not installed — run: bash ~/ollama-local/scripts/android-setup.sh"
exit 1
fi
ADB_CMD="${1:-status}"
case "$ADB_CMD" in
status)
echo -e "\n${BLUE}=== USB Devices ===${NC}"
lsusb
echo -e "\n${BLUE}=== ADB Devices ===${NC}"
"$ADB_BIN" devices -l
;;
devices)
"$ADB_BIN" devices -l
;;
shell)
shift
"$ADB_BIN" shell "$@"
;;
logcat)
shift
"$ADB_BIN" logcat "$@"
;;
install)
shift
[[ -z "$1" ]] && { echo "Usage: sashi adb install <file.apk>"; exit 1; }
"$ADB_BIN" install "$1"
;;
push)
shift
[[ -z "$2" ]] && { echo "Usage: sashi adb push <local> <remote>"; exit 1; }
"$ADB_BIN" push "$1" "$2"
;;
pull)
shift
[[ -z "$1" ]] && { echo "Usage: sashi adb pull <remote> [local]"; exit 1; }
"$ADB_BIN" pull "$@"
;;
wireless)
shift
PORT="${1:-5555}"
echo "Switching device to TCP mode on port $PORT..."
"$ADB_BIN" tcpip "$PORT"
IP=$("$ADB_BIN" shell ip route | awk '/wlan0/ {print $9}' | head -1)
if [[ -n "$IP" ]]; then
echo "Device IP: $IP"
echo "Connecting wirelessly..."
"$ADB_BIN" connect "$IP:$PORT"
echo "You can now unplug USB. Run: sashi adb status"
else
echo "Could not auto-detect IP."
echo "Run: sashi adb shell ip route"
echo "Then: adb connect <phone-ip>:$PORT"
fi
;;
*)
echo "Usage: sashi adb [status|devices|wireless|shell|logcat|install|push|pull]"
;;
esac
;;
usb)
shift
subcmd="${1:-scan}"
shift || true
if ! type usb_list &>/dev/null; then
echo -e "${RED}USB library not loaded${NC}"
exit 1
fi
case "$subcmd" in
scan|list) usb_list ;;
watch) usb_watch_events "${1:-0}" ;;
storage) usb_storage ;;
details) usb_details "${1:-}" ;;
tree) usb_tree ;;
search) usb_search "${1:-}" ;;
export) usb_export "${1:-}" ;;
monitor) usb_watch_events 0 ;;
*)
echo "Usage: sashi usb [scan|watch|storage|details|tree|search|export|monitor]"
echo " scan List all USB devices with vendor names"
echo " watch Monitor plug/unplug events (Ctrl+C to stop)"
echo " storage Show USB storage devices + mount points"
echo " details Verbose info: sashi usb details <vid:pid>"
echo " tree USB device hierarchy"
echo " search Search by name: sashi usb search samsung"
echo " export Export snapshot to JSONL"
;;
esac
;;
wifi)
shift
subcmd="${1:-status}"
shift || true
if ! type wifi_adb_status &>/dev/null; then
echo -e "${RED}WiFi library not loaded${NC}"
exit 1
fi
case "$subcmd" in
init) wifi_adb_init "${1:-}" ;;
connect) wifi_adb_connect "${1:-}" "${2:-}" ;;
scan) wifi_adb_scan ;;
status) wifi_adb_status ;;
logcat) wifi_adb_logcat "${1:-}" ;;
shell) wifi_adb_shell "$@" ;;
disconnect) wifi_adb_disconnect "${1:-}" ;;
*)
echo "Usage: sashi wifi [init|connect|scan|status|logcat|shell|disconnect]"
echo " init Enable WiFi ADB (USB must be plugged in first)"
echo " connect <ip> Connect to device at IP"
echo " scan Scan LAN for Android devices"
echo " status Show connected wireless devices"
echo " logcat [tag] Stream logcat over WiFi"
echo " shell [cmd] ADB shell over WiFi"
echo " disconnect Disconnect all wireless ADB"
;;
esac
;;
hf)
shift
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { echo "Usage: sashi hf <prompt>"; exit 1; }
hf_query "$prompt"
;;
*)
prompt="${STDIN_DATA}${STDIN_DATA:+ }$*"
[ -z "$prompt" ] && { show_help; exit 1; }
llama_query "$prompt"
;;
esac