#!/usr/bin/env bash # gbrain one-line installer. # # f="$(mktemp)" && curl -fsSL https://raw.githubusercontent.com/garrytan/gbrain/stable/scripts/install.sh -o "$f" && bash "$f" # # Installs the gbrain release binary for darwin-arm64 or linux-x64 (glibc) into ~/.local/bin (or --prefix), then # creates a keyless local brain (PGLite, no embedding provider) unless one exists; with --setup, gbrain setup # claude-code or codex does that (keyless unless the user already accepted providers) and connects the agent. It needs no Bun, no git and # no API key. # # Trust: before any downloaded byte is unpacked or run, its SHA-256 must appear as a subject of a build-provenance # attestation from this repository's release workflow on master (the same check src/core/binary-self-update.ts runs), # read from the GitHub attestation API. No attestation, a rate-limited API or a mismatch stops the install with nothing # changed. Set GH_TOKEN (or GITHUB_TOKEN) to read the API with your token instead of the shared 60-an-hour limit. # # Flags: # --prefix DIR install directory (default ~/.local/bin) # --version vX.Y.Z.W install this release instead of the latest stable one # --setup HARNESS also run gbrain setup claude-code|codex # --import-history let setup import recent past sessions (setup --history latest) # --unattended never read the terminal; setup runs with stdin closed and --history none unless --import-history # --no-init install the binary only; create no brain (without --setup) # --json print one JSON document on stdout (progress and child output go to stderr) # --uninstall remove the installed binary; brains under ~/.gbrain stay # # Exit codes. The installer's own failures use 20-26, outside gbrain's exit-code registry (src/core/exit-codes.ts): # 20 unsupported platform, 21 download failed, 22 provenance unavailable (retry or set GH_TOKEN), 23 provenance or # version check failed, 24 install directory not writable, 25 init failed, 26 setup failed. 0 is success and 2 a # usage error. A gbrain child's registry code passes through unchanged with its JSON as "child": 2, 3 (the user must # answer), 10 (accepted, still pending), 13 and 14 (harness verify or cleanup pending), 75 (migrations running). # # Test seams: GBRAIN_INSTALL_RELEASES_URL (default https://github.com/garrytan/gbrain/releases), # GBRAIN_INSTALL_STABLE_URL (default https://raw.githubusercontent.com/garrytan/gbrain/stable), # GBRAIN_INSTALL_STABLE_RECORD_URL (default https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json) and # GBRAIN_INSTALL_ATTESTATION_API (default https://api.github.com/repos/garrytan/gbrain/attestations). set -u # Everything runs inside main, so a download cut off mid-script runs nothing. main() { BUILDER='https://github.com/garrytan/gbrain/.github/workflows/release.yml@refs/heads/master' RELEASES="${GBRAIN_INSTALL_RELEASES_URL:-https://github.com/garrytan/gbrain/releases}" STABLE="${GBRAIN_INSTALL_STABLE_URL:-https://raw.githubusercontent.com/garrytan/gbrain/stable}" STABLE_RECORD="${GBRAIN_INSTALL_STABLE_RECORD_URL:-https://raw.githubusercontent.com/garrytan/gbrain/stable-record/stable.json}" GITHUB_ATTEST_API='https://api.github.com/repos/garrytan/gbrain/attestations' ATTEST_API="${GBRAIN_INSTALL_ATTESTATION_API:-$GITHUB_ATTEST_API}" BUN_ALTERNATIVE='bun install -g github:garrytan/gbrain#stable' prefix="$HOME/.local/bin" want='' harness='' import_history=0 unattended=0 no_init=0 json=0 uninstall=0 tmp='' json_str() { printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr '\n\t\r' ' ')" } say() { printf '%s\n' "$*" >&2; } # fail EXIT CODE MESSAGE FIX [CHILD_EXIT] fail() { if [ "$json" = 1 ]; then child=null [ -n "${6:-}" ] && child="$(child_doc "$tmp/$6.json")" printf '{"ok":false,"exit":%s,"code":%s,"message":%s,"fix":%s,"child_exit":%s,"child":%s}\n' "$1" "$(json_str "$2")" "$(json_str "$3")" "$(json_str "$4")" "${5:-null}" "$child" fi say "gbrain install: $2: $3" [ -n "$4" ] && say "Fix: $4" exit "$1" } cleanup() { [ -n "$tmp" ] && rm -rf "$tmp"; } trap cleanup EXIT while [ $# -gt 0 ]; do case "$1" in --prefix) [ $# -ge 2 ] || fail 2 usage '--prefix needs a directory' ''; prefix="$2"; shift ;; --version) [ $# -ge 2 ] || fail 2 usage '--version needs a release such as v0.60.785.0' ''; want="$2"; shift ;; --setup) [ $# -ge 2 ] || fail 2 usage '--setup needs claude-code or codex' ''; harness="$2"; shift ;; --import-history) import_history=1 ;; --unattended) unattended=1 ;; --no-init) no_init=1 ;; --json) json=1 ;; --uninstall) uninstall=1 ;; -h|--help) say 'Usage: install.sh [--prefix DIR] [--version vX.Y.Z.W] [--setup claude-code|codex] [--import-history] [--unattended] [--no-init] [--json] [--uninstall]'; say 'Docs: https://github.com/garrytan/gbrain/blob/stable/INSTALL_FOR_AGENTS.md'; exit 0 ;; *) fail 2 usage "unknown flag $1" 'run with --help for the flags' ;; esac shift done case "$harness" in ''|claude-code|codex) ;; *) fail 2 usage "--setup takes claude-code or codex, not $harness" "run gbrain setup $harness yourself after the install" ;; esac [ "$import_history" = 1 ] && [ -z "$harness" ] && fail 2 usage '--import-history needs --setup claude-code or --setup codex' '' case "$prefix" in /*) ;; *) fail 2 usage "--prefix needs an absolute path, not $prefix" '' ;; esac bin="$prefix/gbrain" brain_home="${GBRAIN_HOME:-$HOME}/.gbrain" if [ "$uninstall" = 1 ]; then if [ -e "$bin" ]; then rm -f "$bin" || fail 24 prefix_not_writable "could not remove $bin" "remove it yourself: rm $bin" say "Removed $bin. Your brains under $brain_home are unchanged." else say "No gbrain at $bin; nothing to remove." fi [ "$json" = 1 ] && printf '{"ok":true,"uninstalled":%s}\n' "$(json_str "$bin")" exit 0 fi command -v curl >/dev/null 2>&1 || fail 21 download_failed 'curl is not installed' 'install curl, then run this again' os="$(uname -s)" arch="$(uname -m)" target='' case "$os/$arch" in Darwin/arm64) target=darwin-arm64 ;; Darwin/x86_64) [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = 1 ] && target=darwin-arm64 ;; Linux/x86_64|Linux/amd64) if ldd --version 2>&1 | grep -qi musl || [ -e /lib/ld-musl-x86_64.so.1 ]; then target=''; else target=linux-x64; fi ;; esac [ -n "$target" ] || fail 20 unsupported_platform "no gbrain release binary for $os $arch (published: macOS on Apple silicon, Linux x86-64 with glibc)" "install with Bun instead: $BUN_ALTERNATIVE" if command -v sha256sum >/dev/null 2>&1; then sha256() { sha256sum "$1" | cut -d' ' -f1; } elif command -v shasum >/dev/null 2>&1; then sha256() { shasum -a 256 "$1" | cut -d' ' -f1; } else fail 23 provenance_failed 'neither sha256sum nor shasum is installed, so the download cannot be checked' 'install coreutils, then run this again' fi if printf 'YQ==' | base64 -d >/dev/null 2>&1; then b64d() { base64 -d; }; else b64d() { base64 -D; }; fi # Release tag: the one asked for, else the VERSION the stable ref holds. GitHub's Latest badge can sit on another # release (after a rollback, or while stable trails a newer Latest), so it is never the source. if [ -n "$want" ]; then case "$want" in v*) tag="$want" ;; *) tag="v$want" ;; esac else stable="$(curl -fsSL --connect-timeout 20 --max-time 60 "$STABLE/VERSION" 2>/dev/null)" || fail 21 download_failed "could not read $STABLE/VERSION" 'check your network, then run this again' tag="v$(printf '%s' "$stable" | tr -d '[:space:]')" fi printf '%s' "$tag" | grep -Eq '^v[0-9]+(\.[0-9]+){2,3}$' || fail 21 download_failed "could not read a release version (got '$tag')" 'pass --version v from https://github.com/garrytan/gbrain/releases' version="${tag#v}" base="$RELEASES/download/$tag" asset="gbrain-$target" mkdir -p "$prefix" 2>/dev/null && [ -w "$prefix" ] || fail 24 prefix_not_writable "cannot write to $prefix" 'pass --prefix with a directory you own, such as --prefix "$HOME/bin"' tmp="$(mktemp -d "$prefix/.gbrain-install.XXXXXX" 2>/dev/null)" || fail 24 prefix_not_writable "cannot create a staging directory in $prefix" 'pass --prefix with a directory you own' if [ -t 2 ] && [ "$json" = 0 ]; then progress='-#'; else progress='-sS'; fi fetch() { curl -fL --retry 2 --connect-timeout 20 --max-time 1800 --speed-limit 1024 --speed-time 60 "$progress" -o "$2" "$1"; } # attested FILE NAME: 0 when the file's SHA-256 is a subject named NAME of a SLSA provenance statement from BUILDER, # 22 when the attestation API gave no answer, 23 when it answered without one. A token only goes to GitHub (or a # loopback test server), and only through a header file, never on curl's command line. attested() { digest="$(sha256 "$1")" code='' printf '%s' "$digest" | grep -Eq '^[0-9a-f]{64}$' || return 23 token='' if [ "$ATTEST_API" = "$GITHUB_ATTEST_API" ] || printf '%s' "$ATTEST_API" | grep -Eq '^http://127\.0\.0\.1:[0-9]+(/[^@]*)?$'; then token="${GH_TOKEN:-${GITHUB_TOKEN:-}}"; fi for auth in yes no; do if [ "$auth" = yes ]; then [ -n "$token" ] || continue code="$(curl -sS -o "$tmp/attestations.json" -w '%{http_code}' --connect-timeout 20 --max-time 60 -H 'Accept: application/vnd.github+json' -H @<(printf 'Authorization: Bearer %s\n' "$token") "$ATTEST_API/sha256:$digest" 2>/dev/null)" else code="$(curl -sS -o "$tmp/attestations.json" -w '%{http_code}' --connect-timeout 20 --max-time 60 -H 'Accept: application/vnd.github+json' "$ATTEST_API/sha256:$digest" 2>/dev/null)" fi [ "$code" = 200 ] && break done [ "$code" = 404 ] && return 23 [ "$code" = 200 ] || return 22 tr -d '\n' < "$tmp/attestations.json" | grep -o '"payload": *"[^"]*"' | sed -e 's/^"payload": *"//' -e 's/"$//' | while read -r payload; do printf '%s' "$payload" | b64d 2>/dev/null | tr -d ' \t\r\n'; printf '\n'; done > "$tmp/statements" awk -v name="$2" -v digest="$digest" -v builder="$BUILDER" ' index($0, "\"predicateType\":\"https://slsa.dev/provenance/v1\"") && index($0, "\"builder\":{\"id\":\"" builder "\"") { s = $0; sub(/^.*"subject":\[/, "", s); sub(/\].*$/, "", s); depth = 0; el = "" for (i = 1; i <= length(s); i++) { c = substr(s, i, 1) if (c == "{") depth++ if (depth > 0) el = el c if (c == "}" && --depth == 0) { if (index(el, "\"name\":\"" name "\"") && index(el, "\"sha256\":\"" digest "\"")) ok = 1; el = "" } } } END { exit ok ? 0 : 1 }' "$tmp/statements" || return 23 } # verify FILE NAME: stop the install unless the file is attested. verify() { attested "$1" "$2" && return 0 rc=$? [ "$rc" = 22 ] && fail 22 provenance_unavailable "the GitHub attestation API answered HTTP $code for $2, so its origin could not be checked; nothing was installed" 'set GH_TOKEN to a GitHub token (no scopes needed) or wait an hour, then run this again' [ "$code" = 404 ] && fail 23 provenance_failed "$2 (sha256 $digest) has no build attestation from the gbrain release workflow" 'do not run this file; download again later, or report it at https://github.com/garrytan/gbrain/issues' fail 23 provenance_failed "$2 (sha256 $digest) is not attested by $BUILDER" 'do not run this file; report it at https://github.com/garrytan/gbrain/issues' } # reports_version FILE: the binary exits 0 and its --version names exactly this release. reports_version() { out="$("$1" --version 2>/dev/null)" || return 1; [ "${out##* }" = "$version" ]; } [ -d "$bin" ] && fail 24 prefix_not_writable "$bin is a directory, so gbrain cannot be installed there" 'move that directory away, or pass --prefix with another directory' # newer A B: version A is later than version B, compared part by part as numbers. newer() { awk -v a="$1" -v b="$2" 'BEGIN { split(a, x, "."); split(b, y, "."); for (i = 1; i <= 4; i++) { if (x[i] + 0 > y[i] + 0) exit 0; if (x[i] + 0 < y[i] + 0) exit 1 } exit 1 }'; } # known_bad VERSION: the stable record withdrew this build, as gbrain's own update check reads it. known_bad() { curl -fsSL --connect-timeout 20 --max-time 60 "$STABLE_RECORD" 2>/dev/null | tr -d ' \t\r\n' | grep -o '"known_bad":\[[^]]*\]' | grep -qF "\"$1\""; } # An attested binary already here is kept when it is this release or a newer one (an alpha build, say), unless # --version asked for a specific release or the stable record withdrew it: replacing it with an older build could # run under a brain it migrated. via='' if [ -x "$bin" ] && [ -z "$want" ] && attested "$bin" "$asset"; then have="$("$bin" --version 2>/dev/null)" && have="${have##* }" || have='' if [ "$have" = "$version" ]; then via=existing say "gbrain $version is already installed at $bin." elif printf '%s' "$have" | grep -Eq '^[0-9]+(\.[0-9]+){2,3}$' && newer "$have" "$version"; then if known_bad "$have"; then say "gbrain $have at $bin was withdrawn from the stable channel, so it is replaced with the stable release $version." else via=existing say "gbrain $have at $bin is newer than the stable release $version, so it was kept (pass --version $version to install that one)." version="$have" fi fi fi if [ -z "$via" ]; then say "Downloading gbrain $version for $target..." mkdir "$tmp/x" if command -v tar >/dev/null 2>&1 && { [ "$os" = Darwin ] || command -v xz >/dev/null 2>&1; } && fetch "$base/$asset.tar.xz" "$tmp/$asset.tar.xz" 2>/dev/null; then verify "$tmp/$asset.tar.xz" "$asset.tar.xz" if tar -xJf "$tmp/$asset.tar.xz" --no-same-owner -C "$tmp/x" gbrain 2>/dev/null && [ -f "$tmp/x/gbrain" ] && [ ! -L "$tmp/x/gbrain" ]; then via=archive else rm -rf "$tmp/x" && mkdir "$tmp/x" fi fi if [ -z "$via" ]; then fetch "$base/$asset" "$tmp/x/gbrain" || fail 21 download_failed "could not download $base/$asset" 'check your network, then run this again' verify "$tmp/x/gbrain" "$asset" via=raw fi chmod 755 "$tmp/x/gbrain" reports_version "$tmp/x/gbrain" || fail 23 version_mismatch "the attested download does not report version $version" 'run this again; if it repeats, report it at https://github.com/garrytan/gbrain/issues' mv -f "$tmp/x/gbrain" "$bin" || fail 24 prefix_not_writable "could not move gbrain into $bin" 'pass --prefix with a directory you own' say "Installed gbrain $version at $bin ($via download, provenance verified)." fi on_path=false case ":$PATH:" in *":$prefix:"*) on_path=true ;; *) say "Add it to your PATH: export PATH=\"$prefix:\$PATH\"" ;; esac child_doc() { if [ -s "$1" ] && grep -q '^{' "$1"; then awk '/^[{]/ { doc = "" } { doc = doc $0 } END { print doc }' "$1"; else printf 'null'; fi; } # relay_child EXIT STAGE: gbrain's registry codes mean something specific to the caller, so they pass through as is. relay_child() { case "$1" in 2) what=child_usage; why='it refused its arguments; read its message above' ;; 3) what=needs_user; why='it needs your answer; read its message above' ;; 10) what=pending; why='it accepted work that is still pending; follow the receipt it printed' ;; 13) what=harness_pending_verify; why='the agent connection is written and waits for its check; follow the step it printed' ;; 14) what=harness_cleanup_pending; why='a cleanup step is still pending; follow the step it printed' ;; 75) what=migrations_running; why='another gbrain process is migrating this brain; run the same command again shortly' ;; *) return 0 ;; esac [ "$json" = 1 ] && printf '{"ok":false,"exit":%s,"code":%s,"stage":%s,"path":%s,"child_exit":%s,"child":%s}\n' "$1" "$(json_str "$what")" "$(json_str "$2")" "$(json_str "$bin")" "$1" "$(child_doc "$tmp/$2.json")" say "gbrain $2 exited $1: $why." exit "$1" } # With --setup, setup owns brain creation (it keeps an existing brain and writes its own receipt); it stays keyless by # default and keeps a provider choice the user already made, so no --no-providers here. Without --setup, a keyless # PGLite init runs here unless a brain exists. brain=skipped has_brain=0 [ -f "$brain_home/config.json" ] && grep -Eq '"(engine|database_path|database_url)"' "$brain_home/config.json" && has_brain=1 if [ "$has_brain" = 0 ] && [ -n "${GBRAIN_DATABASE_URL:-}${DATABASE_URL:-}" ] && { [ -n "$harness" ] || [ "$no_init" = 0 ]; }; then say 'A database URL is set in this shell, so no brain was created and no agent was connected: gbrain would point at that database.' say "Create a local brain with: env -u DATABASE_URL -u GBRAIN_DATABASE_URL $bin init --pglite --no-embedding" [ -n "$harness" ] && say "Then connect it with: env -u DATABASE_URL -u GBRAIN_DATABASE_URL $bin setup $harness --gbrain-bin $bin" elif [ -n "$harness" ]; then brain=setup elif [ "$no_init" = 0 ]; then if [ "$has_brain" = 1 ]; then brain=kept say "Keeping your existing brain at $brain_home." else say 'Creating a keyless local brain (PGLite, no embedding provider)...' if [ "$json" = 1 ]; then "$bin" init --pglite --no-embedding --non-interactive --json < /dev/null > "$tmp/init.json" else "$bin" init --pglite --no-embedding --non-interactive < /dev/null fi rc=$? relay_child "$rc" init [ "$rc" = 0 ] || fail 25 init_failed "gbrain init exited $rc" "$bin init --pglite --no-embedding" "$rc" init brain=created fi fi setup_doc=null init_doc=null [ "$json" = 1 ] && [ "$brain" = created ] && init_doc="$(child_doc "$tmp/init.json")" if [ "$brain" = setup ]; then say "Connecting $harness..." set -- setup "$harness" --gbrain-bin "$bin" if [ "$import_history" = 1 ]; then set -- "$@" --history latest; elif [ "$unattended" = 1 ]; then set -- "$@" --history none; fi input=/dev/null if [ "$unattended" = 0 ] && (exec < /dev/tty) 2>/dev/null; then input=/dev/tty; fi if [ "$json" = 1 ]; then "$bin" "$@" --json < "$input" > "$tmp/setup.json" else "$bin" "$@" < "$input" fi rc=$? relay_child "$rc" setup [ "$rc" = 0 ] || fail 26 setup_failed "gbrain setup $harness exited $rc" "$bin setup $harness --gbrain-bin $bin" "$rc" setup [ "$json" = 1 ] && setup_doc="$(child_doc "$tmp/setup.json")" fi if [ "$json" = 1 ]; then printf '{"ok":true,"version":%s,"path":%s,"via":%s,"on_path":%s,"brain":%s,"init_result":%s,"setup":%s,"setup_result":%s,"seconds":%s}\n' \ "$(json_str "$version")" "$(json_str "$bin")" "$(json_str "$via")" "$on_path" "$(json_str "$brain")" "$init_doc" \ "$([ -n "$harness" ] && json_str "$harness" || printf 'null')" "$setup_doc" "$SECONDS" else say '' say "Done in ${SECONDS}s. Try it:" say ' gbrain remember "my favourite editor is vim"' say ' gbrain query "what editor do I use?"' [ -z "$harness" ] && say 'Connect an agent: gbrain setup claude-code (or: gbrain setup codex)' fi exit 0 } main "$@"