Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
Β·1303 lines (1206 loc) Β· 48.8 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
Β·1303 lines (1206 loc) Β· 48.8 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 sh
# install.sh β Simplicio Runtime: instalador do binΓ‘rio com readiness fail-closed
#
# A polΓtica de distribuiΓ§Γ£o exige que uma release aprovada traga Mapper, Dev
# CLI, Loop, Fast, Prompt e Sprint no binΓ‘rio, login Google habilitado e chave
# pΓΊblica de updates. O instalador recusa releases que nΓ£o provem esses campos;
# nΓ£o reescreve projetos Python como Rust nem baixa repositΓ³rios irmΓ£os.
#
# curl -fsSL https://raw.githubusercontent.com/simpletibr/simplicio/master/install.sh | sh
#
# Idempotent subcommands:
# sh install.sh --doctor # health check, safe to re-run
# sh install.sh --uninstall # removes the binary, preserves user data
#
# Environment variables:
# SIMPLICIO_VERSION - pin a specific version (default: latest)
# SIMPLICIO_BIN_DIR - custom MCP binary directory (default: ~/.simplicio/bin)
# SIMPLICIO_MCP_URL - local HTTP MCP URL exposed to stdio servers
# SIMPLICIO_ALLOW_UNVERIFIED - "1" to proceed even if no checksum is
# published for this target (default: refuse)
# SIMPLICIO_BUNDLE_DIR - bundle report directory (default: ~/.simplicio)
#
# Host plugins are deliberately outside this installer transaction. The
# Runtime/MCP/hook install completes first; a separate explicit consent flow
# owned by `simplicio host-plugins` may be started afterwards.
#
# Asset naming follows distribution/targets.json (the canonical target
# triplet table for the whole ecosystem): id "macos-arm64" -> asset
# "simplicio-macos-arm64", id "macos-x64" -> "simplicio-macos-x64", id
# "linux-x64" -> "simplicio-linux-x64". Drift between this script, the
# release workflow and simplicio-update-manifest.json is caught by
# scripts/verify_distribution_consistency.py in CI.
set -eu
REPO="simpletibr/simplicio"
GITHUB="https://github.com/$REPO"
ED25519_PUBLIC_KEY="t9n5AmQT2VUVR4LJ0mjQ07C0lEPIMG7oCJGc/5kR4/U="
ED25519_HELPER_URL="https://raw.githubusercontent.com/$REPO/master/scripts/verify_ed25519.py"
ED25519_HELPER_SHA256="837b5355a72837e33a130629409e9d284b37880129b309edc8fa81f6777e60eb"
PUBLIC_ROUTE_REF="68b4c7f7ac27d07624ffa4ddf0673a43e180c3e5"
PUBLIC_ROUTE_URL="https://raw.githubusercontent.com/$REPO/$PUBLIC_ROUTE_REF/codex/mcp-route.sh"
PUBLIC_ROUTE_SHA256="d91200cae4816c79fe0c903fc6eedc01835a557827e8d3d0480304f3bdce5118"
BIN_NAME="simplicio"
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
SIMPLICIO_MCP_URL="${SIMPLICIO_MCP_URL:-http://127.0.0.1:8787/mcp}"
BIN_DIR="${SIMPLICIO_BIN_DIR:-$HOME/.simplicio/bin}"
DEST_PATH="$BIN_DIR/$BIN_NAME"
INSTALL_TRANSACTION_ACTIVE="false"
PREVIOUS_PATH=""
PURGE_DIR="${SIMPLICIO_BUNDLE_DIR:-$HOME/.simplicio}"
AUTH_FILE="$PURGE_DIR/login.json"
INSTALL_RECEIPT="$PURGE_DIR/install-receipt.json"
INSTALL_STAGE="preflight"
INSTALL_EFFECT_STARTED="false"
RUNTIME_INSTALLED="false"
MCP_REGISTERED="false"
HOOK_INSTALLED="false"
HOST_PLUGINS_STATE="unavailable"
HOST_PLUGINS_COMMAND=""
HOST_PLUGINS_REASON="Runtime host-plugins capability was not checked"
AUTH_FILE_WAS_PRESENT="false"
if [ -e "$AUTH_FILE" ]; then
AUTH_FILE_WAS_PRESENT="true"
fi
info() { printf "${CYAN}==>${NC} %s\n" "$*"; }
ok() { printf "${GREEN} β${NC} %s\n" "$*"; }
warn() { printf "${YELLOW} β ${NC} %s\n" "$*"; }
json_escape() {
# POSIX od is available before Python and lets the fallback produce valid
# JSON even when a user-controlled path contains a newline or control byte.
for json_byte in $(printf '%s' "$1" | od -An -tu1 -v); do
case "$json_byte" in
8) printf '%s' '\b' ;;
9) printf '%s' '\t' ;;
10) printf '%s' '\n' ;;
12) printf '%s' '\f' ;;
13) printf '%s' '\r' ;;
34) printf '%s' '\"' ;;
92) printf '%s' "\\\\" ;;
[0-9]|[12][0-9]|3[01]) printf '\\u%04x' "$json_byte" ;;
*)
json_octal="$(printf '%03o' "$json_byte")"
printf '%b' "\\$json_octal"
;;
esac
done
}
render_install_receipt() {
receipt_status="$1"
receipt_exit_code="$2"
receipt_failure_code="$3"
receipt_failure_reason="$4"
if command -v python3 >/dev/null 2>&1; then
if RECEIPT_STATUS="$receipt_status" \
RECEIPT_EXIT_CODE="$receipt_exit_code" \
RECEIPT_STAGE="$INSTALL_STAGE" \
RECEIPT_FAILURE_CODE="$receipt_failure_code" \
RECEIPT_FAILURE_REASON="$receipt_failure_reason" \
RECEIPT_RUNTIME_INSTALLED="$RUNTIME_INSTALLED" \
RECEIPT_MCP_REGISTERED="$MCP_REGISTERED" \
RECEIPT_HOOK_INSTALLED="$HOOK_INSTALLED" \
RECEIPT_HOST_PLUGINS_STATE="$HOST_PLUGINS_STATE" \
RECEIPT_HOST_PLUGINS_COMMAND="$HOST_PLUGINS_COMMAND" \
RECEIPT_HOST_PLUGINS_REASON="$HOST_PLUGINS_REASON" \
python3 - <<'PY'
import json
import os
def env_bool(name):
return os.environ.get(name) == "true"
failure_code = os.environ.get("RECEIPT_FAILURE_CODE", "")
failure = None
if failure_code:
failure = {
"code": failure_code,
"reason": os.environ.get("RECEIPT_FAILURE_REASON", ""),
}
receipt = {
"schema": "simplicio-install-receipt/v1",
"status": os.environ["RECEIPT_STATUS"],
"exit_code": int(os.environ["RECEIPT_EXIT_CODE"]),
"stage": os.environ["RECEIPT_STAGE"],
"failure": failure,
"runtime": {"installed": env_bool("RECEIPT_RUNTIME_INSTALLED")},
"mcp": {"registered": env_bool("RECEIPT_MCP_REGISTERED")},
"hook": {"installed": env_bool("RECEIPT_HOOK_INSTALLED")},
"host_plugins": {
"state": os.environ["RECEIPT_HOST_PLUGINS_STATE"],
"owner": "simplicio-runtime",
"command": os.environ.get("RECEIPT_HOST_PLUGINS_COMMAND") or None,
"mutated": False,
"reason": os.environ["RECEIPT_HOST_PLUGINS_REASON"],
},
}
print(json.dumps(receipt, ensure_ascii=False, separators=(",", ":")))
PY
then
return 0
fi
fi
# Pre-Python failures still get valid JSON through the byte-safe POSIX
# fallback above, without relying on the missing prerequisite.
if [ -n "$receipt_failure_code" ]; then
receipt_failure="{\"code\":\"$(json_escape "$receipt_failure_code")\",\"reason\":\"$(json_escape "$receipt_failure_reason")\"}"
else
receipt_failure="null"
fi
if [ -n "$HOST_PLUGINS_COMMAND" ]; then
receipt_host_command="\"$(json_escape "$HOST_PLUGINS_COMMAND")\""
else
receipt_host_command="null"
fi
printf '{"schema":"simplicio-install-receipt/v1","status":"%s","exit_code":%s,"stage":"%s","failure":%s,"runtime":{"installed":%s},"mcp":{"registered":%s},"hook":{"installed":%s},"host_plugins":{"state":"%s","owner":"simplicio-runtime","command":%s,"mutated":false,"reason":"%s"}}\n' \
"$(json_escape "$receipt_status")" \
"$receipt_exit_code" \
"$(json_escape "$INSTALL_STAGE")" \
"$receipt_failure" \
"$RUNTIME_INSTALLED" \
"$MCP_REGISTERED" \
"$HOOK_INSTALLED" \
"$(json_escape "$HOST_PLUGINS_STATE")" \
"$receipt_host_command" \
"$(json_escape "$HOST_PLUGINS_REASON")"
}
persist_install_receipt() {
receipt_status="$1"
receipt_exit_code="$2"
receipt_failure_code="$3"
receipt_failure_reason="$4"
if ! mkdir -p "$PURGE_DIR"; then
return 1
fi
receipt_tmp="$INSTALL_RECEIPT.tmp.$$"
if ! (umask 077; render_install_receipt "$receipt_status" "$receipt_exit_code" "$receipt_failure_code" "$receipt_failure_reason" >"$receipt_tmp"); then
rm -f "$receipt_tmp"
return 1
fi
if ! chmod 0600 "$receipt_tmp" || ! mv -f "$receipt_tmp" "$INSTALL_RECEIPT"; then
rm -f "$receipt_tmp"
return 1
fi
}
fail_install() {
failure_code="$1"
shift
failure_reason="$*"
failure_status="failed"
if [ "$INSTALL_EFFECT_STARTED" = "true" ]; then
failure_status="partial"
fi
if ! persist_install_receipt "$failure_status" 1 "$failure_code" "$failure_reason"; then
render_install_receipt "$failure_status" 1 "$failure_code" "$failure_reason" >&2
fi
printf "${RED} β${NC} %s\n" "$failure_reason" >&2
exit 1
}
err() {
fail_install "${INSTALL_STAGE}_failed" "$*"
}
rollback_install() {
if [ "$INSTALL_TRANSACTION_ACTIVE" = "true" ]; then
if [ -n "$PREVIOUS_PATH" ] && [ -e "$PREVIOUS_PATH" ]; then
mv -f "$PREVIOUS_PATH" "$DEST_PATH"
else
rm -f "$DEST_PATH"
fi
INSTALL_TRANSACTION_ACTIVE="false"
fi
}
# βββ Detect platform (canonical os/arch naming, matches distribution/targets.json) ββ
detect_platform() {
case "$(uname -m)" in
x86_64|amd64) ARCH="x64" ;;
aarch64|arm64) ARCH="arm64" ;;
*) err "Arquitetura nΓ£o suportada: $(uname -m)" ;;
esac
case "$(uname -s)" in
Darwin) OS="macos" ;;
Linux) OS="linux" ;;
*) err "Sistema nΓ£o suportado: $(uname -s)" ;;
esac
}
sha256_of() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | awk '{print $1}'
elif command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$1" | awk '{print $1}'
else
err "Precisa de sha256sum ou shasum para verificar a integridade do download"
fi
}
HOOK_FAILURE_CODE=""
HOOK_FAILURE_REASON=""
hook_sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | awk '{print $1}'
elif command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$1" | awk '{print $1}'
else
return 1
fi
}
reconcile_public_route_overlay() {
HOOK_FAILURE_CODE=""
HOOK_FAILURE_REASON=""
hook_dir="$PURGE_DIR/hooks"
hook_path="$hook_dir/mcp-route.sh"
if [ -f "$hook_path" ]; then
if ! hook_current_sha="$(hook_sha256 "$hook_path")"; then
HOOK_FAILURE_CODE="hook_checksum_tool_missing"
HOOK_FAILURE_REASON="Could not calculate SHA256 for existing hook: $hook_path"
return 1
fi
if [ "$hook_current_sha" = "$PUBLIC_ROUTE_SHA256" ]; then
return 0
fi
fi
if ! mkdir -p "$hook_dir"; then
HOOK_FAILURE_CODE="hook_directory_create_failed"
HOOK_FAILURE_REASON="Could not create hook directory: $hook_dir"
return 1
fi
hook_tmp="$hook_dir/.mcp-route.sh.download-$$"
hook_capture_dir="$(mktemp -d "${TMPDIR:-/tmp}/simplicio-hook.XXXXXX")" || {
HOOK_FAILURE_CODE="hook_output_capture_failed"
HOOK_FAILURE_REASON="Could not create bounded hook download capture"
return 1
}
hook_stdout="$hook_capture_dir/stdout"
hook_stderr="$hook_capture_dir/stderr"
hook_stdout_fifo="$hook_capture_dir/stdout.fifo"
hook_stderr_fifo="$hook_capture_dir/stderr.fifo"
hook_code_path="$hook_capture_dir/code"
hook_reason_path="$hook_capture_dir/reason"
if ! mkfifo "$hook_stdout_fifo" "$hook_stderr_fifo"; then
rm -f "$hook_tmp" "$hook_stdout_fifo" "$hook_stderr_fifo" || true
rmdir "$hook_capture_dir" 2>/dev/null || true
HOOK_FAILURE_CODE="hook_output_capture_failed"
HOOK_FAILURE_REASON="Could not create bounded hook download streams"
return 1
fi
if command -v curl >/dev/null 2>&1; then
hook_downloader="curl"
elif command -v wget >/dev/null 2>&1; then
hook_downloader="wget"
else
rm -f "$hook_tmp" "$hook_stdout_fifo" "$hook_stderr_fifo" || true
rmdir "$hook_capture_dir" 2>/dev/null || true
HOOK_FAILURE_CODE="hook_downloader_missing"
HOOK_FAILURE_REASON="Neither curl nor wget is available to download the public hook"
return 1
fi
capture_stream_bounded "$hook_stdout" "$hook_stdout.truncated" 8192 <"$hook_stdout_fifo" &
hook_stdout_pid=$!
capture_stream_bounded "$hook_stderr" "$hook_stderr.truncated" 8192 <"$hook_stderr_fifo" &
hook_stderr_pid=$!
if [ "$hook_downloader" = "curl" ]; then
if curl -fsSL "$PUBLIC_ROUTE_URL" -o "$hook_tmp" >"$hook_stdout_fifo" 2>"$hook_stderr_fifo"; then
hook_download_exit=0
else
hook_download_exit=$?
fi
else
if wget -q "$PUBLIC_ROUTE_URL" -O "$hook_tmp" >"$hook_stdout_fifo" 2>"$hook_stderr_fifo"; then
hook_download_exit=0
else
hook_download_exit=$?
fi
fi
if wait "$hook_stdout_pid"; then hook_stdout_ok=true; else hook_stdout_ok=false; fi
if wait "$hook_stderr_pid"; then hook_stderr_ok=true; else hook_stderr_ok=false; fi
rm -f "$hook_stdout_fifo" "$hook_stderr_fifo" || true
if [ "$hook_stdout_ok" != "true" ] || [ "$hook_stderr_ok" != "true" ]; then
HOOK_FAILURE_CODE="hook_output_capture_failed"
HOOK_FAILURE_REASON="Hook download output could not be drained safely"
hook_download_exit=125
elif [ "$hook_download_exit" -ne 0 ]; then
if python3 - "$hook_stdout" "$hook_stderr" "$hook_code_path" "$hook_reason_path" "$hook_download_exit" <<'PY'
import json
import os
import sys
marker = "\n...[output truncated at 8192 bytes]"
def captured(path):
with open(path, "rb") as handle:
text = handle.read(8192).decode("utf-8", errors="replace")
return text + (marker if os.path.exists(path + ".truncated") else "")
stdout = captured(sys.argv[1])
stderr = captured(sys.argv[2])
payload = None
for candidate in [stdout.strip(), *reversed([line.strip() for line in stdout.splitlines() if line.strip()])]:
try:
decoded = json.loads(candidate)
except (TypeError, ValueError):
continue
if isinstance(decoded, dict):
payload = decoded
break
failure = payload.get("failure") if isinstance(payload, dict) else None
error = payload.get("error") if isinstance(payload, dict) else None
failure = failure if isinstance(failure, dict) else {}
error_object = error if isinstance(error, dict) else {}
code = failure.get("code") or (payload.get("code") if payload else None) or (payload.get("error_code") if payload else None) or error_object.get("code") or "hook_download_failed"
reason = failure.get("reason") or (payload.get("reason") if payload else None) or (payload.get("message") if payload else None) or error_object.get("reason") or error_object.get("message") or (error if isinstance(error, str) else None)
if not isinstance(reason, str) or not reason:
reason = stderr.strip() or stdout.strip() or f"Hook download failed with exit code {sys.argv[5]}"
with open(sys.argv[3], "w", encoding="utf-8", newline="") as handle:
handle.write(str(code))
with open(sys.argv[4], "w", encoding="utf-8", newline="") as handle:
handle.write(reason[:8192])
PY
then
capture_sentinel="__SIMPLICIO_CAPTURE_EOF__"
HOOK_FAILURE_CODE="$(cat "$hook_code_path"; printf '%s' "$capture_sentinel")"
HOOK_FAILURE_CODE="${HOOK_FAILURE_CODE%"$capture_sentinel"}"
HOOK_FAILURE_REASON="$(cat "$hook_reason_path"; printf '%s' "$capture_sentinel")"
HOOK_FAILURE_REASON="${HOOK_FAILURE_REASON%"$capture_sentinel"}"
else
HOOK_FAILURE_CODE="hook_download_failed"
HOOK_FAILURE_REASON="Hook download failed with exit code $hook_download_exit"
fi
fi
rm -f "$hook_stdout" "$hook_stderr" "$hook_stdout.truncated" "$hook_stderr.truncated" "$hook_code_path" "$hook_reason_path" || true
rmdir "$hook_capture_dir" 2>/dev/null || true
if [ "$hook_download_exit" -ne 0 ]; then
rm -f "$hook_tmp" || true
return 1
fi
if ! hook_download_sha="$(hook_sha256 "$hook_tmp")"; then
rm -f "$hook_tmp" || true
HOOK_FAILURE_CODE="hook_checksum_failed"
HOOK_FAILURE_REASON="Could not calculate SHA256 for downloaded hook"
return 1
fi
if [ "$hook_download_sha" != "$PUBLIC_ROUTE_SHA256" ]; then
rm -f "$hook_tmp" || true
HOOK_FAILURE_CODE="hook_checksum_mismatch"
HOOK_FAILURE_REASON="Downloaded hook SHA256 mismatch: expected $PUBLIC_ROUTE_SHA256, got $hook_download_sha"
return 1
fi
if ! grep -q 'simplicio-hook-version: 3240-v12' "$hook_tmp"; then
rm -f "$hook_tmp" || true
HOOK_FAILURE_CODE="hook_marker_missing"
HOOK_FAILURE_REASON="Downloaded hook is missing simplicio-hook-version: 3240-v12"
return 1
fi
if ! chmod 0755 "$hook_tmp"; then
rm -f "$hook_tmp" || true
HOOK_FAILURE_CODE="hook_permission_failed"
HOOK_FAILURE_REASON="Could not make downloaded hook executable: $hook_tmp"
return 1
fi
if ! mv -f "$hook_tmp" "$hook_path"; then
rm -f "$hook_tmp" || true
HOOK_FAILURE_CODE="hook_activation_failed"
HOOK_FAILURE_REASON="Could not activate verified hook at $hook_path"
return 1
fi
return 0
}
verify_ed25519_signature() {
binary_path="$1"
signature="$2"
public_key="$3"
expected_sha256="$4"
helper_path="$5"
release_version="$6"
release_target="$7"
if [ -z "$signature" ] || [ -z "$public_key" ] || [ -z "$expected_sha256" ]; then
return 1
fi
if ! command -v python3 >/dev/null 2>&1; then
return 1
fi
if [ "$(sha256_of "$binary_path")" != "$expected_sha256" ]; then
return 1
fi
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$ED25519_HELPER_URL" -o "$helper_path" || return 1
elif command -v wget >/dev/null 2>&1; then
wget -q "$ED25519_HELPER_URL" -O "$helper_path" || return 1
else
return 1
fi
if [ "$(sha256_of "$helper_path")" != "$ED25519_HELPER_SHA256" ]; then
return 1
fi
python3 "$helper_path" \
--public-key "$public_key" \
--signature "$signature" \
--sha256 "$expected_sha256" \
--version "$release_version" \
--target "$release_target" >/dev/null 2>&1
}
verify_runtime_contract() {
binary_path="$1"
if [ ! -x "$binary_path" ] || ! command -v python3 >/dev/null 2>&1; then
return 1
fi
"$binary_path" version --json 2>/dev/null | python3 -c '
import json, sys
try:
payload = json.load(sys.stdin)
except Exception:
raise SystemExit(1)
distribution = ((payload.get("auto_update") or {}).get("distribution") or {})
identity = payload.get("identity") or {}
security = payload.get("security") or ((payload.get("auto_update") or {}).get("security") or {})
ready = (
distribution.get("source_code_distributed") is True
and identity.get("enabled") is True
and identity.get("login_enabled") is True
and security.get("signature_required") is True
and security.get("public_key_configured") is True
)
raise SystemExit(0 if ready else 1)
' >/dev/null 2>&1
}
report_runtime_contract() {
binary_path="$1"
if [ ! -x "$binary_path" ] || ! command -v python3 >/dev/null 2>&1; then
warn "nΓ£o foi possΓvel ler o contrato de readiness do Runtime"
return 0
fi
"$binary_path" version --json 2>/dev/null | python3 -c '
import json, sys
try:
payload = json.load(sys.stdin)
except Exception:
print("contrato de readiness ausente ou invΓ‘lido")
raise SystemExit(0)
distribution = ((payload.get("auto_update") or {}).get("distribution") or {})
identity = payload.get("identity") or {}
security = payload.get("security") or ((payload.get("auto_update") or {}).get("security") or {})
checks = {
"source_code_distributed": distribution.get("source_code_distributed"),
"identity.enabled": identity.get("enabled"),
"identity.login_enabled": identity.get("login_enabled"),
"security.signature_required": security.get("signature_required"),
"security.public_key_configured": security.get("public_key_configured"),
}
for key, value in checks.items():
if value is not True:
print("readiness ausente: %s=%s" % (key, value))
' >&2 || true
}
verify_active_login() {
if [ ! -x "$DEST_PATH" ] || ! command -v python3 >/dev/null 2>&1; then
return 1
fi
"$DEST_PATH" auth status --json 2>/dev/null | python3 -c '
import json, sys
try:
payload = json.load(sys.stdin)
except Exception:
raise SystemExit(1)
identity = payload.get("identity") or {}
entitlement = payload.get("entitlement") or {}
session_verification = payload.get("session_verification") or {}
identity_email = identity.get("email") or (payload.get("user") or {}).get("email")
active = (
identity.get("enabled") is True
and identity.get("login_enabled") is True
and identity.get("status") == "active"
and bool(identity_email)
and entitlement.get("updates_allowed") is True
and session_verification.get("verified") is True
and session_verification.get("cached") is False
)
raise SystemExit(0 if active else 1)
'
}
report_login_state() {
if verify_active_login; then
ok "sessΓ£o Google verificada de forma fresh e entitlement vΓ‘lido"
return 0
fi
warn "sessΓ£o Google nΓ£o verificada de forma fresh (ausente, cacheada ou sem entitlement); rode: ${DEST_PATH} auth login"
return 0
}
capture_stream_bounded() {
capture_output_path="$1"
capture_truncated_path="$2"
capture_limit="$3"
python3 -c '
import os
import sys
output_path, truncated_path, raw_limit = sys.argv[1:]
limit = int(raw_limit)
remaining = limit
truncated = False
with open(output_path, "wb") as output:
while True:
chunk = sys.stdin.buffer.read(65536)
if not chunk:
break
kept_length = 0
if remaining:
kept = chunk[:remaining]
output.write(kept)
remaining -= len(kept)
kept_length = len(kept)
if len(chunk) > kept_length:
truncated = True
if truncated:
with open(truncated_path, "wb"):
pass
' "$capture_output_path" "$capture_truncated_path" "$capture_limit"
}
MCP_FAILURE_CODE=""
MCP_FAILURE_REASON=""
verify_mcp_tools() {
binary_path="$1"
MCP_FAILURE_CODE=""
MCP_FAILURE_REASON=""
if [ ! -x "$binary_path" ]; then
MCP_FAILURE_CODE="mcp_binary_missing"
MCP_FAILURE_REASON="Runtime binary is missing or not executable: $binary_path"
return 1
fi
capture_dir="$(mktemp -d "${TMPDIR:-/tmp}/simplicio-mcp-register.XXXXXX")" || {
MCP_FAILURE_CODE="mcp_output_capture_failed"
MCP_FAILURE_REASON="Could not create a bounded capture directory for Runtime MCP registration output"
return 1
}
stdout_path="$capture_dir/stdout"
stderr_path="$capture_dir/stderr"
stdout_fifo="$capture_dir/stdout.fifo"
stderr_fifo="$capture_dir/stderr.fifo"
code_path="$capture_dir/code"
reason_path="$capture_dir/reason"
if ! mkfifo "$stdout_fifo" "$stderr_fifo"; then
rm -f "$stdout_fifo" "$stderr_fifo"
rmdir "$capture_dir" 2>/dev/null || true
MCP_FAILURE_CODE="mcp_output_capture_failed"
MCP_FAILURE_REASON="Could not create bounded Runtime MCP output streams"
return 1
fi
capture_stream_bounded "$stdout_path" "$stdout_path.truncated" 8192 <"$stdout_fifo" &
stdout_drain_pid=$!
capture_stream_bounded "$stderr_path" "$stderr_path.truncated" 8192 <"$stderr_fifo" &
stderr_drain_pid=$!
if SIMPLICIO_MCP_URL="$SIMPLICIO_MCP_URL" "$binary_path" mcp register --binary "$binary_path" --json >"$stdout_fifo" 2>"$stderr_fifo"; then
mcp_exit_code=0
else
mcp_exit_code=$?
fi
if wait "$stdout_drain_pid"; then stdout_drain_ok=true; else stdout_drain_ok=false; fi
if wait "$stderr_drain_pid"; then stderr_drain_ok=true; else stderr_drain_ok=false; fi
rm -f "$stdout_fifo" "$stderr_fifo"
if [ "$stdout_drain_ok" != "true" ] || [ "$stderr_drain_ok" != "true" ]; then
rm -f "$stdout_path" "$stderr_path" "$stdout_path.truncated" "$stderr_path.truncated" "$code_path" "$reason_path"
rmdir "$capture_dir" 2>/dev/null || true
MCP_FAILURE_CODE="mcp_output_capture_failed"
MCP_FAILURE_REASON="Runtime MCP output could not be drained safely"
return 1
fi
if [ "$mcp_exit_code" -eq 0 ]; then
rm -f "$stdout_path" "$stderr_path" "$stdout_path.truncated" "$stderr_path.truncated" "$code_path" "$reason_path"
rmdir "$capture_dir" 2>/dev/null || true
# InicializaΓ§Γ£o determinΓstica de memΓ³ria, seed e reuse
"$binary_path" memory steward migrate --json >/dev/null 2>&1 || true
"$binary_path" memory steward seed --json >/dev/null 2>&1 || true
"$binary_path" memory init --json >/dev/null 2>&1 || true
return 0
fi
if python3 - "$stdout_path" "$stderr_path" "$code_path" "$reason_path" "$mcp_exit_code" <<'PY'
import json
import os
import sys
LIMIT = 8192
TRUNCATED = "\n...[output truncated at 8192 bytes]"
def read_bounded(path):
with open(path, "rb") as handle:
payload = handle.read(LIMIT)
truncated = os.path.exists(path + ".truncated")
text = payload.decode("utf-8", errors="replace")
return text + (TRUNCATED if truncated else "")
def text_value(value):
if isinstance(value, str) and value:
return value
if value is not None and not isinstance(value, (dict, list)):
return str(value)
return ""
stdout = read_bounded(sys.argv[1])
stderr = read_bounded(sys.argv[2])
payload = None
candidates = [stdout.strip()]
candidates.extend(line.strip() for line in reversed(stdout.splitlines()) if line.strip())
for candidate in candidates:
try:
decoded = json.loads(candidate)
except (TypeError, ValueError):
continue
if isinstance(decoded, dict):
payload = decoded
break
failure = payload.get("failure") if isinstance(payload, dict) else None
error = payload.get("error") if isinstance(payload, dict) else None
failure = failure if isinstance(failure, dict) else {}
error_object = error if isinstance(error, dict) else {}
code = (
text_value(failure.get("code"))
or (text_value(payload.get("code")) if payload else "")
or (text_value(payload.get("error_code")) if payload else "")
or text_value(error_object.get("code"))
or "mcp_registration_failed"
)
reason = (
text_value(failure.get("reason"))
or (text_value(payload.get("reason")) if payload else "")
or (text_value(payload.get("message")) if payload else "")
or text_value(error_object.get("reason"))
or text_value(error_object.get("message"))
or (text_value(error) if not isinstance(error, dict) else "")
)
if not reason:
fallback = []
if stderr.strip():
fallback.append(stderr.strip())
if stdout.strip() and stdout.strip() not in fallback:
fallback.append(stdout.strip())
reason = "\n".join(fallback)
if not reason:
reason = f"Runtime MCP registration failed with exit code {sys.argv[5]}"
# An optional host integration (for example the isolated Hermes runtime) must
# not abort an otherwise successful install.
optional_failed = []
if isinstance(payload, dict) and text_value(payload.get("status")) == "failed":
optional_failed = [
key
for key, value in payload.items()
if isinstance(value, dict) and text_value(value.get("status")) == "failed"
]
if optional_failed and optional_failed == ["hermes"]:
code = "optional_host_failed"
reason = "optional host integration failed: " + ", ".join(optional_failed)
reason_bytes = reason.encode("utf-8")
if len(reason_bytes) > LIMIT:
reason = reason_bytes[:LIMIT].decode("utf-8", errors="ignore") + TRUNCATED
with open(sys.argv[3], "w", encoding="utf-8", newline="") as handle:
handle.write(code)
with open(sys.argv[4], "w", encoding="utf-8", newline="") as handle:
handle.write(reason)
PY
then
capture_sentinel="__SIMPLICIO_CAPTURE_EOF__"
MCP_FAILURE_CODE="$(cat "$code_path"; printf '%s' "$capture_sentinel")"
MCP_FAILURE_CODE="${MCP_FAILURE_CODE%"$capture_sentinel"}"
MCP_FAILURE_REASON="$(cat "$reason_path"; printf '%s' "$capture_sentinel")"
MCP_FAILURE_REASON="${MCP_FAILURE_REASON%"$capture_sentinel"}"
if [ "$MCP_FAILURE_CODE" = "optional_host_failed" ]; then
warn "integraΓ§Γ£o opcional de host nΓ£o concluΓda ($MCP_FAILURE_REASON); instalaΓ§Γ£o continua"
rm -f "$stdout_path" "$stderr_path" "$stdout_path.truncated" "$stderr_path.truncated" "$code_path" "$reason_path"
rmdir "$capture_dir" 2>/dev/null || true
"$binary_path" memory steward migrate --json >/dev/null 2>&1 || true
"$binary_path" memory steward seed --json >/dev/null 2>&1 || true
"$binary_path" memory init --json >/dev/null 2>&1 || true
return 0
fi
else
MCP_FAILURE_CODE="mcp_registration_failed"
capture_sentinel="__SIMPLICIO_CAPTURE_EOF__"
MCP_FAILURE_REASON="$(head -c 8192 "$stderr_path"; printf '%s' "$capture_sentinel")"
MCP_FAILURE_REASON="${MCP_FAILURE_REASON%"$capture_sentinel"}"
if [ -z "$MCP_FAILURE_REASON" ]; then
MCP_FAILURE_REASON="$(head -c 8192 "$stdout_path"; printf '%s' "$capture_sentinel")"
MCP_FAILURE_REASON="${MCP_FAILURE_REASON%"$capture_sentinel"}"
fi
if [ -z "$MCP_FAILURE_REASON" ]; then
MCP_FAILURE_REASON="Runtime MCP registration failed with exit code $mcp_exit_code"
fi
fi
rm -f "$stdout_path" "$stderr_path" "$stdout_path.truncated" "$stderr_path.truncated" "$code_path" "$reason_path"
rmdir "$capture_dir" 2>/dev/null || true
return 1
}
probe_host_plugins_capability() {
HOST_PLUGINS_STATE="unavailable"
HOST_PLUGINS_COMMAND=""
HOST_PLUGINS_REASON="Runtime host-plugins capability is unavailable"
if [ ! -x "$DEST_PATH" ]; then
HOST_PLUGINS_REASON="Runtime binary is missing; host-plugins capability was not checked"
return 1
fi
host_capture_dir="$(mktemp -d "${TMPDIR:-/tmp}/simplicio-host-plugins.XXXXXX")" || {
HOST_PLUGINS_REASON="Could not create bounded host-plugins capability capture"
return 1
}
host_stdout="$host_capture_dir/stdout"
host_stderr="$host_capture_dir/stderr"
host_stdout_fifo="$host_capture_dir/stdout.fifo"
host_stderr_fifo="$host_capture_dir/stderr.fifo"
if ! mkfifo "$host_stdout_fifo" "$host_stderr_fifo"; then
rm -f "$host_stdout_fifo" "$host_stderr_fifo"
rmdir "$host_capture_dir" 2>/dev/null || true
HOST_PLUGINS_REASON="Could not create bounded host-plugins capability streams"
return 1
fi
capture_stream_bounded "$host_stdout" "$host_stdout.truncated" 8192 <"$host_stdout_fifo" &
host_stdout_pid=$!
capture_stream_bounded "$host_stderr" "$host_stderr.truncated" 8192 <"$host_stderr_fifo" &
host_stderr_pid=$!
if "$DEST_PATH" host-plugins --help >"$host_stdout_fifo" 2>"$host_stderr_fifo"; then
host_exit_code=0
else
host_exit_code=$?
fi
if wait "$host_stdout_pid"; then host_stdout_ok=true; else host_stdout_ok=false; fi
if wait "$host_stderr_pid"; then host_stderr_ok=true; else host_stderr_ok=false; fi
rm -f "$host_stdout_fifo" "$host_stderr_fifo"
host_contract_valid=false
if [ "$host_exit_code" -eq 0 ] && [ "$host_stdout_ok" = "true" ] && [ "$host_stderr_ok" = "true" ]; then
if python3 - "$host_stdout" "$host_stderr" <<'PY'
import sys
help_text = "\n".join(
open(path, "rb").read(8192).decode("utf-8", errors="replace")
for path in sys.argv[1:]
)
required = (
"simplicio.host-plugins/cli-v1",
"simplicio host-plugins plan",
"simplicio host-plugins apply",
"simplicio host-plugins pending",
"simplicio host-plugins reconcile",
)
raise SystemExit(0 if all(marker in help_text for marker in required) else 1)
PY
then
host_contract_valid=true
fi
fi
if [ "$host_contract_valid" = "true" ]; then
HOST_PLUGINS_STATE="pending_consent"
HOST_PLUGINS_COMMAND="simplicio host-plugins plan --all"
HOST_PLUGINS_REASON="Host plugins require separate explicit user consent."
host_supported=true
else
if [ "$host_exit_code" -eq 0 ] && [ "$host_stdout_ok" = "true" ] && [ "$host_stderr_ok" = "true" ]; then
host_diagnostic="Runtime returned exit code 0 without the required simplicio.host-plugins/cli-v1 contract marker and commands"
else
capture_sentinel="__SIMPLICIO_CAPTURE_EOF__"
host_diagnostic="$(cat "$host_stderr"; printf '%s' "$capture_sentinel")"
host_diagnostic="${host_diagnostic%"$capture_sentinel"}"
if [ -z "$host_diagnostic" ]; then
host_diagnostic="$(cat "$host_stdout"; printf '%s' "$capture_sentinel")"
host_diagnostic="${host_diagnostic%"$capture_sentinel"}"
fi
if [ -z "$host_diagnostic" ]; then
host_diagnostic="Runtime exited with code $host_exit_code"
fi
fi
HOST_PLUGINS_REASON="Runtime host-plugins capability unavailable: $host_diagnostic"
host_supported=false
fi
rm -f "$host_stdout" "$host_stderr" "$host_stdout.truncated" "$host_stderr.truncated"
rmdir "$host_capture_dir" 2>/dev/null || true
[ "$host_supported" = "true" ]
}
report_host_plugin_consent() {
if [ "$HOST_PLUGINS_STATE" = "pending_consent" ]; then
info "plugins de hosts aguardam consentimento separado; nenhum plugin de host foi alterado"
info "revise o plano somente pelo Runtime: $DEST_PATH host-plugins plan --all"
else
warn "capacidade host-plugins indisponΓvel neste Runtime; nenhum plugin de host foi alterado"
fi
}
# βββ --doctor: idempotent, read-only health check ββββββββββββββββββββββββββ
run_doctor() {
info "simplicio doctor"
status=0
if [ -x "$DEST_PATH" ]; then
ok "binΓ‘rio presente: $DEST_PATH"
else
warn "binΓ‘rio ausente em $DEST_PATH"
status=1
fi
case ":$PATH:" in
*":$BIN_DIR:"*) ok "$BIN_DIR estΓ‘ no PATH" ;;
*) warn "$BIN_DIR nΓ£o estΓ‘ no PATH (sessΓ£o atual)" ;;
esac
if [ -x "$DEST_PATH" ]; then
if "$DEST_PATH" version >/dev/null 2>&1; then
ok "binΓ‘rio executa corretamente"
else
warn "binΓ‘rio presente mas falhou ao executar"
status=1
fi
if verify_runtime_contract "$DEST_PATH"; then
ok "contrato de release do Runtime verificado"
else
warn "release nΓ£o estΓ‘ pronta para distribuiΓ§Γ£o (bundle/login/chave de updates)"
report_runtime_contract "$DEST_PATH"
status=1
fi
if verify_active_login; then
ok "sessΓ£o Google verificada de forma fresh e entitlement vΓ‘lido"
else
warn "sessΓ£o Google nΓ£o verificada de forma fresh (ausente, cacheada, expirada, revogada ou sem entitlement)"
status=1
fi
if "$DEST_PATH" memory status --json >/dev/null 2>&1; then
ok "memΓ³ria neural verificada e operacional"
else
warn "memΓ³ria neural nΓ£o inicializada β executando bootstrap/migrations/seed"
"$DEST_PATH" memory steward migrate --json >/dev/null 2>&1 || true
"$DEST_PATH" memory steward seed --json >/dev/null 2>&1 || true
"$DEST_PATH" memory init --json >/dev/null 2>&1 || true
fi
fi
if [ "$status" -eq 0 ]; then
ok "simplicio estΓ‘ saudΓ‘vel"
else
warn "simplicio tem problemas β rode o instalador novamente"
fi
exit "$status"
}
# βββ --uninstall: idempotent removal, safe to run repeatedly ββββββββββββββ
run_uninstall() {
info "simplicio uninstall"
if [ -e "$DEST_PATH" ]; then
rm -f "$DEST_PATH"
ok "removido $DEST_PATH"
else
ok "jΓ‘ estava removido (nada em $DEST_PATH)"
fi
if [ "${UNINSTALL_MODE:-keep-data}" = "purge" ]; then
if [ "${SIMPLICIO_CONFIRM_PURGE:-}" != "1" ]; then
err "purge exige SIMPLICIO_CONFIRM_PURGE=1; dados nΓ£o foram removidos"
fi
if [ -d "$PURGE_DIR" ]; then
for _entry in "$PURGE_DIR"/* "$PURGE_DIR"/.[!.]*; do
[ -e "$_entry" ] || continue
_name="$(basename "$_entry")"
[ "$_name" = ".env" ] && continue
rm -rf "$_entry"
done
fi
if [ "$AUTH_FILE_WAS_PRESENT" = "true" ]; then
warn "estado de login desapareceu durante o purge explΓcito"
fi
ok "dados do Simplicio removidos; .env do provedor foi preservado"
else
ok "dados do usuΓ‘rio em \$HOME/.simplicio foram preservados (--keep-data)"
fi
warn "se vocΓͺ adicionou $BIN_DIR ao PATH no seu ~/.zshrc ou ~/.bashrc, remova a linha manualmente"
exit 0
}
case "${1:-}" in
--doctor) run_doctor ;;
--uninstall)
case "${2:-}" in
""|--keep-data) UNINSTALL_MODE="keep-data" ;;
--purge) UNINSTALL_MODE="purge" ;;
*) err "opΓ§Γ£o de uninstall desconhecida: ${2}" ;;
esac
run_uninstall ;;
esac
printf '%b' "${GREEN}"
cat << "EOF"
ββββββββββββββββββββββββββββββββββββββββ
β Simplicio Runtime β
β Seu assistente pessoal digital β
ββββββββββββββββββββββββββββββββββββββββ
EOF
printf '%b' "${NC}"
echo ""
# βββ 1. Detect platform ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
INSTALL_STAGE="platform_detection"
detect_platform
info "Plataforma detectada: $OS-$ARCH"
# βββ 2. Instalar simplicio binary (staged download + SHA256 + atomic swap) ββ
INSTALL_STAGE="runtime_install"
info "Instalando Simplicio Runtime..."
mkdir -p "$BIN_DIR" || err "nΓ£o foi possΓvel criar o diretΓ³rio do Runtime: $BIN_DIR"
# A plain re-run means "update to latest". Only skip the download when the
# caller explicitly pins the version already installed; otherwise an older
# healthy Runtime would incorrectly look current forever.