bootstrap: contain install artifacts in .runtime/, provision SimpleX gateway

Move every installed artifact into a gitignored .runtime/ tree inside the
checkout (venv, SemIf engine, GGUF, HF cache, simplex-chat binary/profile,
rendered systemd units) so an end user can find and debug the whole stack in
one place. Pin simplex-chat v7.0.3 in config.example.json (url+sha256) and
have bootstrap download it, render semif-simplex.service + semif-gateway.service
from scripts/systemd/ templates, symlink them into the user unit dir, and
enable them. Add --simplex-allowed-users/--simplex-home-channel/--simplex-display-name
flags and write the gateway block into config.json. Add the AGENTS.md
containment rule.
This commit is contained in:
Denton Social committed 2026-09-26 17:23:37 -05:00
1 parent 6ab4d94423
commit 483c51f559
6 files changed
+291 -91

No files matched your search

+3
View File
@@ -1,6 +1,9 @@
__pycache__/ __pycache__/
*.pyc *.pyc
.venv/ .venv/
# Repo-contained install artifacts (venv, SemIf engine, GGUF, HF cache,
# simplex-chat binary/profile, rendered systemd units). See bootstrap.sh.
.runtime/
data/decisions.jsonl data/decisions.jsonl
data/runs.jsonl data/runs.jsonl
data/categories.json data/categories.json
+59 -26
View File
@@ -136,9 +136,9 @@ Integration tests run on the staging machine `jarvis` (see "### jarvis (staging)
- Canonical repo lives on Gitea: `git.manyworlds.fit`, **SSH on port 222** - Canonical repo lives on Gitea: `git.manyworlds.fit`, **SSH on port 222**
(`ssh://git@git.manyworlds.fit:222/gabby/semif-agent.git`). Key (`ssh://git@git.manyworlds.fit:222/gabby/semif-agent.git`). Key
`~/.ssh/id_ed25519` is registered there. The staging machine `jarvis` runs `~/.ssh/id_ed25519` is registered there. The staging machine `jarvis` runs
from a manual clone at `~/semif-agent` (`scripts/bootstrap.sh` provisions from a manual clone at `~/repos/semif-agent` (`scripts/bootstrap.sh` provisions
everything else and never re-clones the agent repo); the old box working copy everything else and never re-clones the agent repo); the old box working copy
is at `~/repos/semif-agent` (its editable install still points at the moved is also at `~/repos/semif-agent` (its editable install still points at the moved
`~/semif-agent`, so `import semif_agent` is broken there — moot, guppy runs `~/semif-agent`, so `import semif_agent` is broken there — moot, guppy runs
ollama only now); the dev machine at `~/Repos/semif-agent`. Push/pull from ollama only now); the dev machine at `~/Repos/semif-agent`. Push/pull from
Gitea — never rsync/tar the code. Gitea — never rsync/tar the code.
@@ -338,17 +338,27 @@ unit tests (24) + box integration tests (2).
### jarvis (staging) ### jarvis (staging)
- Provision a fresh Ubuntu machine into a running staging box: clone - Provision a fresh Ubuntu machine into a running staging box: clone
`semif-agent` to `~/semif-agent` first (register its SSH key on Gitea), then `semif-agent` to a checkout (jarvis keeps it at `~/repos/semif-agent`; the
script derives all paths from wherever it is run, so any path works — just
register its SSH key on Gitea first), then
`scripts/bootstrap.sh --peer-ollama http://192.168.8.181:11434`. `scripts/bootstrap.sh --peer-ollama http://192.168.8.181:11434`.
The script must be run from a checkout — it reads pins from that checkout's The script must be run from a checkout — it reads pins from that checkout's
`config.example.json` and never re-clones the agent repo (only the SemIf `config.example.json` and never re-clones the agent repo (only the SemIf
engine). Idempotent and rerunnable; every stage no-ops on existing state, so engine and the simplex-chat binary). Idempotent and rerunnable; every stage
it also boots an unknown-state machine. It installs **no ollama** — llm + no-ops on existing state, so it also boots an unknown-state machine. It
codegen both point at guppy. installs **no ollama** — llm + codegen both point at guppy.
- All pins are read from `config.example.json`'s `engine` block: `semif_repo` - **All installation artifacts live inside the checkout under a gitignored
(public GitHub `TheoLeeCJ/SemIf`), `semif_ref` (pinned commit the box runs), `.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`,
`gguf_url`/`gguf_sha256` (verified after download), and the HF tokenizer `simplex/`, `systemd/`), so an end user can find and debug the whole stack in
`source`/`revision`. The python dep pins live in `requirements/staging.txt` one tree. Only operationally-forced artifacts live outside: the SSH key
(`~/.ssh`) and the real systemd user dir + linger (the rendered units are
stored in `.runtime/systemd/` and symlinked into `~/.config/systemd/user/`).
See the "Code principles" containment rule.
- All pins are read from `config.example.json`: the `engine` block
(`semif_repo` public GitHub `TheoLeeCJ/SemIf`, `semif_ref` pinned commit,
`gguf_url`/`gguf_sha256`, HF tokenizer `source`/`revision`) and the
`simplex_chat` block (`version`, `bin_url`, `sha256`, `port`,
`display_name`). The python dep pins live in `requirements/staging.txt`
(committed, one versioned artifact — jarvis, guppy, and any future box all (committed, one versioned artifact — jarvis, guppy, and any future box all
provision from it). **Maintenance**: bump the pins in `config.example.json` / provision from it). **Maintenance**: bump the pins in `config.example.json` /
`requirements/staging.txt`, rerun the script, re-run the integration tests. `requirements/staging.txt`, rerun the script, re-run the integration tests.
@@ -358,17 +368,26 @@ unit tests (24) + box integration tests (2).
that we intentionally do not install — the llama.cpp CPU path doesn't need that we intentionally do not install — the llama.cpp CPU path doesn't need
them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Same as the box; them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Same as the box;
do not "fix" them by installing torch. do not "fix" them by installing torch.
- Generates `~/semif-agent/config.json` with `codegen.timeout: 3600` (codegen - Generates `config.json` with `codegen.timeout: 3600` (codegen now travels the
now travels the LAN) and a backup of any prior file. `--threads N` overrides LAN), a repo-relative `.runtime/models` GGUF path, and a backup of any prior
engine threads; `--copy-data SRC` rsyncs guppy's `data/` for continuity; file. `--threads N` overrides engine threads; `--copy-data SRC` rsyncs guppy's
`--public-dashboard` binds the dashboard to `0.0.0.0`. `data/` for continuity; `--public-dashboard` binds the dashboard to `0.0.0.0`.
It also enables the SimpleX gateway (`gateway.simplex.enabled = true`,
`ws_url` from `simplex_chat.port`) and renders/enables the two user services
`semif-simplex.service` (the pinned `simplex-chat` daemon, headless on
`simplex_chat.port`) and `semif-gateway.service`
(`.runtime/venv/bin/python -m semif_agent.cli gateway`). `--simplex-allowed-users
CSV` / `--simplex-home-channel ID` / `--simplex-display-name NAME` populate
the allowlist/fallback/identity; with an empty allowlist the gateway denies
everyone (the safe default until the human adds their contact id).
- Run / verify on jarvis: - Run / verify on jarvis:
```sh ```sh
cd ~/semif-agent && export HF_HOME=~/hf REPO=~/repos/semif-agent && cd "$REPO" && export HF_HOME="$REPO/.runtime/hf"
~/semif-venv/bin/python -m semif_agent.cli run # REPL "$REPO/.runtime/venv/bin/python" -m semif_agent.cli run # REPL
~/semif-venv/bin/python -m semif_agent.cli dream # cost report "$REPO/.runtime/venv/bin/python" -m semif_agent.cli dream # cost report
~/semif-venv/bin/python -m pytest tests/integration -q -s # ~100s, background+poll "$REPO/.runtime/venv/bin/python" -m pytest tests/integration -q -s # ~100s, background+poll
~/semif-venv/bin/python -m semif_agent.cli dashboard --port 8765 "$REPO/.runtime/venv/bin/python" -m semif_agent.cli dashboard --port 8765
systemctl --user status semif-simplex semif-gateway # gateway stack
``` ```
- First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source - First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source
(~10 min on 6 cores); reruns are fast no-ops. (~10 min on 6 cores); reruns are fast no-ops.
@@ -550,18 +569,23 @@ unit tests (24) + box integration tests (2).
[--dashboard]` builds the normal scheduler (engine lazy) and runs the [--dashboard]` builds the normal scheduler (engine lazy) and runs the
configured `gateway.simplex` adapter in the foreground. `--dashboard` configured `gateway.simplex` adapter in the foreground. `--dashboard`
co-serves the browser UI from a daemon thread. Config lives under co-serves the browser UI from a daemon thread. Config lives under
`gateway.simplex` in `config.json`; `enabled` defaults false. The gateway is `gateway.simplex` in `config.json`; `enabled` defaults false. On a
its own process — the REPL and the gateway are independent front ends onto bootstrap-provisioned box `scripts/bootstrap.sh` renders and enables the
the same on-disk logs/registry (do not run two scheduler processes over one `semif-simplex.service` daemon (pinned `simplex-chat`, profile under
skill store concurrently). `.runtime/simplex/`, port from `simplex_chat.port`) and the
`semif-gateway.service` agent process, so the gateway runs headless across
logout/reboot. The gateway is its own process — the REPL and the gateway are
independent front ends onto the same on-disk logs/registry (do not run two
scheduler processes over one skill store concurrently).
- **Transport contract** (`gateway/base.py`): `GatewayAdapter.run(on_inbound, - **Transport contract** (`gateway/base.py`): `GatewayAdapter.run(on_inbound,
outbound_queue)` blocks, delivering `InboundMessage`s and draining a stdlib outbound_queue)` blocks, delivering `InboundMessage`s and draining a stdlib
`queue.Queue[OutboundMessage | None]`. Scheduler work is synchronous and can `queue.Queue[OutboundMessage | None]`. Scheduler work is synchronous and can
block on the decision engine, so the adapter bridges it off its event loop block on the decision engine, so the adapter bridges it off its event loop
(`asyncio.to_thread`) and puts replies on the queue. A second platform means (`asyncio.to_thread`) and puts replies on the queue. A second platform means
a new adapter subclass; the service is unchanged. a new adapter subclass; the service is unchanged.
- **SimpleX adapter** (`gateway/simplex.py`): connects to `simplex-chat -p - **SimpleX adapter** (`gateway/simplex.py`): connects to the local
5225` at `gateway.simplex.ws_url`, XML-JSON WebSocket protocol `simplex-chat` daemon at `gateway.simplex.ws_url` (default port 5226, pinning
`simplex_chat.port`), XML-JSON WebSocket protocol
(`{"corrId","cmd"}` → `{"corrId","resp"}` / events). `websockets` is (`{"corrId","cmd"}` → `{"corrId","resp"}` / events). `websockets` is
**lazy-imported**; `check_requirements()` returns an install hint and the **lazy-imported**; `check_requirements()` returns an install hint and the
gateway refuses to start without it, so the core stays importable on a gateway refuses to start without it, so the core stays importable on a
@@ -819,6 +843,15 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
the config step at first fire, never in SKILL.md. the config step at first fire, never in SKILL.md.
### Code principles ### Code principles
- **Contain installation artifacts in the repo.** Everything a machine installs
to run the agent (python venv, SemIf engine clone, GGUF, HF cache, the
simplex-chat binary/profile, rendered systemd units) lives inside the checkout
under a gitignored `.runtime/` tree — never scattered across `$HOME`. An end
user must be able to find and debug the whole stack with as few steps as
possible. Only artifacts that operationally cannot live there are outside
(`~/.ssh/id_ed25519`; the real systemd user dir + linger, which the repo units
are symlinked into). `scripts/bootstrap.sh` owns this layout; derive paths from
the checkout, never hardcode `$HOME`.
- **No mocking.** The decision engine is always real SemIf; the LLM is always a - **No mocking.** The decision engine is always real SemIf; the LLM is always a
real endpoint. Pure unit tests touch data-structure math only (queue ordering, real endpoint. Pure unit tests touch data-structure math only (queue ordering,
dream cost, contract serialization). Engine-dependent behavior is verified by dream cost, contract serialization). Engine-dependent behavior is verified by
@@ -837,7 +870,7 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
- CLI subcommands must not crash when the engine is unavailable — `submit` - CLI subcommands must not crash when the engine is unavailable — `submit`
catches `EngineUnavailable` and returns `("error", ...)`. catches `EngineUnavailable` and returns `("error", ...)`.
- Keep deps stdlib-only in the core; heavy deps live on the staging venv - Keep deps stdlib-only in the core; heavy deps live on the staging venv
(`~/semif-venv`, provisioned by `scripts/bootstrap.sh`). (`.runtime/venv`, provisioned by `scripts/bootstrap.sh`).
## Testing ## Testing
+10 -2
View File
@@ -72,11 +72,19 @@
"log": "data/decisions.jsonl", "log": "data/decisions.jsonl",
"trace": "data/runs.jsonl", "trace": "data/runs.jsonl",
"category_registry": "data/categories.json", "category_registry": "data/categories.json",
"simplex_chat": {
"_comment": "Pinned simplex-chat daemon that the messenger gateway talks to. bootstrap.sh downloads this exact binary (sha256 verified) into .runtime/bin/, runs it headless on `port` with its profile in .runtime/simplex/, and renders the semif-simplex.service unit from it. Bump version/bin_url/sha256 together. The gateway's ws_url (gateway.simplex.ws_url) must match `port`.",
"version": "v7.0.3",
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0",
"port": 5226,
"display_name": "semif"
},
"gateway": { "gateway": {
"_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (simplex-chat -p 5225) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.", "_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (see `simplex_chat` above) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.",
"simplex": { "simplex": {
"enabled": false, "enabled": false,
"ws_url": "ws://127.0.0.1:5225", "ws_url": "ws://127.0.0.1:5226",
"allowed_users": [], "allowed_users": [],
"allow_all_users": false, "allow_all_users": false,
"auto_accept": true, "auto_accept": true,
+185 -63
View File
@@ -7,17 +7,28 @@
# #
# Must be run from a semif-agent checkout (it reads pins from this checkout's # Must be run from a semif-agent checkout (it reads pins from this checkout's
# config.example.json); the checkout is used as-is and never re-cloned — only # config.example.json); the checkout is used as-is and never re-cloned — only
# the SemIf engine is fetched. Clone the agent repo to ~/semif-agent first # the SemIf engine and the simplex-chat binary are fetched. Clone the agent
# (its SSH key must be registered on Gitea). # repo first (its SSH key must be registered on Gitea).
# #
# Pins (SemIf git commit, GGUF url+sha256) are read from config.example.json's # Every installation artifact lives INSIDE this checkout under .runtime/
# engine block and the python dep pins from requirements/staging.txt — both # (gitignored), so an end user can find and debug the whole stack in one tree:
# committed in this repo and the single source of truth; bump those there and # .runtime/venv/ python venv .runtime/models/ GGUF
# rerun to upgrade. # .runtime/engine/ SemIf engine clone .runtime/hf/ HF cache
# .runtime/bin/ simplex-chat binary .runtime/simplex/ simplex profile
# .runtime/systemd/ rendered unit files (symlinked into ~/.config/systemd/user)
# Only artifacts that operationally must live elsewhere are outside: the SSH
# key (~/.ssh) and the real systemd user dir/linger.
#
# Pins (SemIf commit, GGUF url+sha256, simplex-chat url+sha256) are read from
# config.example.json's engine/simplex_chat blocks, and the python dep pins
# from requirements/staging.txt — all committed here and the single source of
# truth; bump those and rerun to upgrade.
# #
# Usage: # Usage:
# scripts/bootstrap.sh [--peer-ollama URL] [--threads N] [--copy-data SRC] # scripts/bootstrap.sh [--peer-ollama URL] [--threads N] [--copy-data SRC]
# [--public-dashboard] [-h] # [--public-dashboard]
# [--simplex-allowed-users CSV] [--simplex-home-channel X]
# [--simplex-display-name NAME] [-h]
# #
# Run as the human user; sudo is used internally for system bits. # Run as the human user; sudo is used internally for system bits.
set -euo pipefail set -euo pipefail
@@ -26,15 +37,21 @@ PEER_OLLAMA="http://192.168.8.181:11434"
THREADS="" THREADS=""
COPY_DATA="" COPY_DATA=""
PUBLIC_DASHBOARD=0 PUBLIC_DASHBOARD=0
SIMPLEX_ALLOWED_USERS=""
SIMPLEX_HOME_CHANNEL=""
SIMPLEX_DISPLAY_NAME=""
usage() { usage() {
sed -n '2,12p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' sed -n '2,31p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
echo echo
echo " --peer-ollama URL remote ollama API for llm+codegen (default: $PEER_OLLAMA)" echo " --peer-ollama URL remote ollama API for llm+codegen (default: $PEER_OLLAMA)"
echo " --threads N engine threads for config.json (default: config.example value)" echo " --threads N engine threads for config.json (default: config.example value)"
echo " --copy-data SRC rsync SRC (e.g. abby@box:~/repos/semif-agent/data) to data/ — opt-in" echo " --copy-data SRC rsync SRC (e.g. abby@box:~/repos/semif-agent/data) to data/ — opt-in"
echo " --public-dashboard bind dashboard to 0.0.0.0 instead of 127.0.0.1" echo " --public-dashboard bind dashboard to 0.0.0.0 instead of 127.0.0.1"
echo " -h this help" echo " --simplex-allowed-users CSV comma-separated contactIds/display names the gateway accepts"
echo " --simplex-home-channel ID gateway fallback channel for unsolicited messages"
echo " --simplex-display-name NAME simplex-chat bot display name (default: config.example value)"
echo " -h this help"
exit "${1:-0}" exit "${1:-0}"
} }
@@ -44,6 +61,9 @@ while [[ $# -gt 0 ]]; do
--threads) THREADS="$2"; shift 2 ;; --threads) THREADS="$2"; shift 2 ;;
--copy-data) COPY_DATA="$2"; shift 2 ;; --copy-data) COPY_DATA="$2"; shift 2 ;;
--public-dashboard) PUBLIC_DASHBOARD=1; shift ;; --public-dashboard) PUBLIC_DASHBOARD=1; shift ;;
--simplex-allowed-users) SIMPLEX_ALLOWED_USERS="$2"; shift 2 ;;
--simplex-home-channel) SIMPLEX_HOME_CHANNEL="$2"; shift 2 ;;
--simplex-display-name) SIMPLEX_DISPLAY_NAME="$2"; shift 2 ;;
-h|--help) usage 0 ;; -h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;; *) echo "unknown option: $1" >&2; usage 1 ;;
esac esac
@@ -52,26 +72,44 @@ done
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EXAMPLE="$REPO_ROOT/config.example.json" EXAMPLE="$REPO_ROOT/config.example.json"
RUNTIME="$REPO_ROOT/.runtime"
VENV="$RUNTIME/venv"
ENGINE="$RUNTIME/engine"
MODELS="$RUNTIME/models"
HF_CACHE="$RUNTIME/hf"
TOOLDIR="$RUNTIME/bin"
SIMPLEX_DB="$RUNTIME/simplex"
UNITS="$RUNTIME/systemd"
USER_UNITS="$HOME/.config/systemd/user"
PYTHON="$VENV/bin/python"
PIP="$VENV/bin/pip"
if [[ ! -f "$EXAMPLE" ]]; then if [[ ! -f "$EXAMPLE" ]]; then
echo "config.example.json not found at $EXAMPLE — run from a semif-agent checkout" >&2 echo "config.example.json not found at $EXAMPLE — run from a semif-agent checkout" >&2
exit 1 exit 1
fi fi
# --- read pins from config.example.json ------------------------------------ # --- read pins from config.example.json ------------------------------------
read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV < <( read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \
SIMPLEX_BIN_URL SIMPLEX_SHA256 SIMPLEX_PORT SIMPLEX_DISPLAY < <(
python3 - "$EXAMPLE" <<'PY' python3 - "$EXAMPLE" <<'PY'
import json, sys import json, sys
cfg = json.load(open(sys.argv[1])) cfg = json.load(open(sys.argv[1]))
e = cfg["engine"] e = cfg["engine"]
s = cfg.get("simplex_chat", {})
print( print(
" ".join( " ".join(
[ [
e.get("semif_repo", ""), str(e.get("semif_repo", "")),
e.get("semif_ref", ""), str(e.get("semif_ref", "")),
e.get("gguf_url", ""), str(e.get("gguf_url", "")),
e.get("gguf_sha256", ""), str(e.get("gguf_sha256", "")),
e.get("source", ""), str(e.get("source", "")),
e.get("revision", ""), str(e.get("revision", "")),
str(s.get("bin_url", "")),
str(s.get("sha256", "")),
str(s.get("port", "")),
str(s.get("display_name", "")),
] ]
) )
) )
@@ -82,10 +120,22 @@ if [[ -z "$SEMIF_REPO" || -z "$SEMIF_REF" || -z "$GGUF_URL" || -z "$GGUF_SHA256"
echo "engine pins missing in $EXAMPLE (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2 echo "engine pins missing in $EXAMPLE (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2
exit 1 exit 1
fi fi
if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" || -z "$SIMPLEX_PORT" ]]; then
echo "simplex_chat pins missing in $EXAMPLE (bin_url/sha256/port)" >&2
exit 1
fi
echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | peer $PEER_OLLAMA" if [[ -n "$SIMPLEX_DISPLAY_NAME" ]]; then
SIMPLEX_DISPLAY="$SIMPLEX_DISPLAY_NAME"
fi
SIMPLEX_DISPLAY="${SIMPLEX_DISPLAY:-semif}"
# --- stage 0: system prereqs ------------------------------------------------- echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex-chat sha256 ${SIMPLEX_SHA256:0:12}… | peer $PEER_OLLAMA"
echo "== runtime tree: $RUNTIME"
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$UNITS" "$USER_UNITS"
# --- stage 0: system prereqs + linger ----------------------------------------
PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake) PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake)
missing=() missing=()
for p in "${PKGS[@]}"; do for p in "${PKGS[@]}"; do
@@ -97,6 +147,13 @@ if [[ ${#missing[@]} -gt 0 ]]; then
sudo apt-get install -y "${missing[@]}" sudo apt-get install -y "${missing[@]}"
fi fi
if command -v loginctl >/dev/null 2>&1; then
if [[ "$(loginctl show-user "$USER" 2>/dev/null | sed -n 's/^Linger=//p')" != "yes" ]]; then
echo "== enabling linger for $USER (services survive logout/reboot)"
sudo loginctl enable-linger "$USER"
fi
fi
# --- stage 1: python ---------------------------------------------------------- # --- stage 1: python ----------------------------------------------------------
PY=python3 PY=python3
if ! "$PY" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)' 2>/dev/null; then if ! "$PY" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)' 2>/dev/null; then
@@ -116,39 +173,35 @@ if [[ ! -f ~/.ssh/id_ed25519 ]]; then
cat ~/.ssh/id_ed25519.pub cat ~/.ssh/id_ed25519.pub
fi fi
AGENT_DIR="$REPO_ROOT" git -C "$REPO_ROOT" pull --ff-only || true
git -C "$AGENT_DIR" pull --ff-only || true
if [[ ! -d ~/semif/.git ]]; then if [[ ! -d "$ENGINE/.git" ]]; then
echo "== cloning SemIf engine from $SEMIF_REPO" echo "== cloning SemIf engine from $SEMIF_REPO into $ENGINE"
git clone "$SEMIF_REPO" ~/semif git clone "$SEMIF_REPO" "$ENGINE"
fi fi
if [[ "$(git -C ~/semif rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then if [[ "$(git -C "$ENGINE" rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then
echo "== pinning SemIf engine to $SEMIF_REF" echo "== pinning SemIf engine to $SEMIF_REF"
git -C ~/semif fetch origin git -C "$ENGINE" fetch origin
git -C ~/semif checkout "$SEMIF_REF" git -C "$ENGINE" checkout "$SEMIF_REF"
fi fi
# --- stage 3: venv + deps ------------------------------------------------------- # --- stage 3: venv + deps -------------------------------------------------------
if [[ ! -d ~/semif-venv ]]; then if [[ ! -x "$PYTHON" ]]; then
echo "== creating ~/semif-venv" echo "== creating venv at $VENV"
"$PY" -m venv ~/semif-venv "$PY" -m venv "$VENV"
fi fi
PIP=~/semif-venv/bin/pip echo "== installing engine deps into $VENV"
echo "== installing engine deps into venv"
"$PIP" install --upgrade pip setuptools wheel "$PIP" install --upgrade pip setuptools wheel
"$PIP" install -e ~/semif --no-deps "$PIP" install -e "$ENGINE" --no-deps
CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 "$PIP" install -r "$REPO_ROOT/requirements/staging.txt" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 "$PIP" install -r "$REPO_ROOT/requirements/staging.txt"
"$PIP" install -e "$AGENT_DIR" --no-deps "$PIP" install -e "$REPO_ROOT" --no-deps
# --- stage 4: GGUF -------------------------------------------------------------- # --- stage 4: GGUF --------------------------------------------------------------
GGUF_DIR=~/models
GGUF_NAME="$(basename "$GGUF_URL")" GGUF_NAME="$(basename "$GGUF_URL")"
GGUF="$GGUF_DIR/$GGUF_NAME" GGUF="$MODELS/$GGUF_NAME"
mkdir -p "$GGUF_DIR"
sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; } sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; }
if ! sha_ok; then if ! sha_ok; then
echo "== downloading GGUF ($GGUF_NAME)" echo "== downloading GGUF ($GGUF_NAME) into $MODELS"
rm -f "$GGUF" "$GGUF.tmp" rm -f "$GGUF" "$GGUF.tmp"
curl -fL --retry 3 -o "$GGUF.tmp" "$GGUF_URL" curl -fL --retry 3 -o "$GGUF.tmp" "$GGUF_URL"
mv "$GGUF.tmp" "$GGUF" mv "$GGUF.tmp" "$GGUF"
@@ -157,26 +210,45 @@ sha_ok || { echo "GGUF sha256 mismatch: expected $GGUF_SHA256" >&2; exit 1; }
echo "== GGUF verified ($GGUF)" echo "== GGUF verified ($GGUF)"
# --- stage 5: HF tokenizer cache -------------------------------------------------- # --- stage 5: HF tokenizer cache --------------------------------------------------
export HF_HOME="$HOME/hf" export HF_HOME="$HF_CACHE"
mkdir -p "$HF_HOME" mkdir -p "$HF_CACHE"
echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV" echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV into $HF_CACHE"
~/semif-venv/bin/python - "$HF_SOURCE" "$HF_REV" <<'PY' "$PYTHON" - "$HF_SOURCE" "$HF_REV" <<'PY'
import sys import sys
from transformers import AutoTokenizer from transformers import AutoTokenizer
AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2]) AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2])
PY PY
# --- stage 6: config.json ----------------------------------------------------------- # --- stage 6: simplex-chat daemon binary -------------------------------------------
SIMPLEX_BIN="$TOOLDIR/simplex-chat"
simplex_ok() {
[[ -f "$SIMPLEX_BIN" ]] && [[ "$(sha256sum "$SIMPLEX_BIN" | cut -d' ' -f1)" == "$SIMPLEX_SHA256" ]]
}
if ! simplex_ok; then
echo "== downloading simplex-chat into $SIMPLEX_BIN"
rm -f "$SIMPLEX_BIN" "$SIMPLEX_BIN.tmp"
curl -fL --retry 3 -o "$SIMPLEX_BIN.tmp" "$SIMPLEX_BIN_URL"
mv "$SIMPLEX_BIN.tmp" "$SIMPLEX_BIN"
chmod +x "$SIMPLEX_BIN"
fi
simplex_ok || { echo "simplex-chat sha256 mismatch: expected $SIMPLEX_SHA256" >&2; exit 1; }
echo "== simplex-chat verified ($SIMPLEX_BIN)"
# --- stage 7: config.json -----------------------------------------------------------
if [[ -f "$REPO_ROOT/config.json" ]]; then if [[ -f "$REPO_ROOT/config.json" ]]; then
cp "$REPO_ROOT/config.json" "$REPO_ROOT/config.json.bak.$(date +%s)" cp "$REPO_ROOT/config.json" "$REPO_ROOT/config.json.bak.$(date +%s)"
fi fi
echo "== writing config.json (llm/codegen -> $PEER_OLLAMA)" echo "== writing config.json (llm/codegen -> $PEER_OLLAMA, runtime -> $RUNTIME)"
python3 - "$REPO_ROOT/config.example.json" "$REPO_ROOT/config.json" "$THREADS" "$PEER_OLLAMA" "$([ "$PUBLIC_DASHBOARD" = 1 ] && echo 0.0.0.0 || echo 127.0.0.1)" <<'PY' python3 - "$REPO_ROOT/config.example.json" "$REPO_ROOT/config.json" "$THREADS" "$PEER_OLLAMA" \
"$([ "$PUBLIC_DASHBOARD" = 1 ] && echo 0.0.0.0 || echo 127.0.0.1)" \
"$REPO_ROOT" "$SIMPLEX_ALLOWED_USERS" "$SIMPLEX_HOME_CHANNEL" "$SIMPLEX_DISPLAY" <<'PY'
import json, os, sys import json, os, sys
example, out, threads, peer, dash_host = sys.argv[1:] (example, out, threads, peer, dash_host, repo,
allowed_csv, home_channel, display) = sys.argv[1:]
cfg = json.load(open(example)) cfg = json.load(open(example))
eng = cfg["engine"] eng = cfg["engine"]
eng["gguf"] = os.path.join(os.path.expanduser("~"), "models", os.path.basename(eng["gguf_url"])) runtime = os.path.join(repo, ".runtime")
eng["gguf"] = os.path.join(runtime, "models", os.path.basename(eng["gguf_url"]))
if threads and threads != "__example__": if threads and threads != "__example__":
eng["threads"] = int(threads) eng["threads"] = int(threads)
# The clients hit {base_url}/chat/completions on ollama's OpenAI-compat path, # The clients hit {base_url}/chat/completions on ollama's OpenAI-compat path,
@@ -188,21 +260,52 @@ if not base_url.endswith("/v1"):
cfg["llm"]["base_url"] = base_url cfg["llm"]["base_url"] = base_url
cfg["codegen"]["base_url"] = base_url cfg["codegen"]["base_url"] = base_url
cfg["codegen"]["timeout"] = 3600 cfg["codegen"]["timeout"] = 3600
cfg.setdefault("simplex_chat", {})["display_name"] = display
cfg.setdefault("dashboard", {})["port"] = 8765 cfg.setdefault("dashboard", {})["port"] = 8765
cfg["dashboard"]["host"] = dash_host cfg["dashboard"]["host"] = dash_host
allowed = [u.strip() for u in allowed_csv.split(",") if u.strip()]
simplex = cfg.setdefault("gateway", {}).setdefault("simplex", {})
simplex["enabled"] = True
simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}"
simplex["allowed_users"] = allowed
simplex["home_channel"] = home_channel
json.dump(cfg, open(out, "w"), indent=2) json.dump(cfg, open(out, "w"), indent=2)
PY PY
# --- stage 7: optional data copy ----------------------------------------------------- # --- stage 8: systemd user units -----------------------------------------------------
if [[ -n "$COPY_DATA" ]]; then render_unit() {
echo "== rsync data from $COPY_DATA" local src="$1" dst="$2"
mkdir -p "$AGENT_DIR/data" sed -e "s|@REPO@|$REPO_ROOT|g" \
rsync -a "$COPY_DATA/" "$AGENT_DIR/data/" -e "s|@PORT@|$SIMPLEX_PORT|g" \
-e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" "$src" > "$dst"
}
echo "== rendering systemd user units into $UNITS"
for unit in semif-simplex.service semif-gateway.service; do
render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$UNITS/$unit"
ln -sf "$UNITS/$unit" "$USER_UNITS/$unit"
done
if command -v systemctl >/dev/null 2>&1; then
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
if systemctl --user daemon-reload 2>/dev/null; then
systemctl --user enable --now semif-simplex.service semif-gateway.service 2>/dev/null \
&& echo "== enabled semif-simplex.service semif-gateway.service" \
|| echo "WARN: could not enable user services (run: systemctl --user enable --now semif-simplex semif-gateway)" >&2
else
echo "WARN: systemctl --user unavailable; units are at $USER_UNITS" >&2
fi
fi fi
# --- stage 8: verify -------------------------------------------------------------------- # --- stage 9: optional data copy -----------------------------------------------------
if [[ -n "$COPY_DATA" ]]; then
echo "== rsync data from $COPY_DATA"
mkdir -p "$REPO_ROOT/data"
rsync -a "$COPY_DATA/" "$REPO_ROOT/data/"
fi
# --- stage 10: verify -------------------------------------------------------------------
echo "== verifying imports" echo "== verifying imports"
~/semif-venv/bin/python -c "import semif_phase1, semif_agent; print('engine + agent import OK')" "$PYTHON" -c "import semif_phase1, semif_agent; print('engine + agent import OK')"
echo "== peer ollama check ($PEER_OLLAMA)" echo "== peer ollama check ($PEER_OLLAMA)"
PEER_TAGS="$(curl -sf --max-time 5 "$PEER_OLLAMA/api/tags" || true)" PEER_TAGS="$(curl -sf --max-time 5 "$PEER_OLLAMA/api/tags" || true)"
# The OpenAI-compat chat path is what llm/codegen actually hit; a bare reachable # The OpenAI-compat chat path is what llm/codegen actually hit; a bare reachable
@@ -224,9 +327,28 @@ else
echo "WARN: peer /api/tags shows no qwen38-iq3s" >&2 echo "WARN: peer /api/tags shows no qwen38-iq3s" >&2
fi fi
echo if command -v systemctl >/dev/null 2>&1; then
echo "Done. Next steps:" echo "== gateway services"
echo " cd ~/semif-agent" systemctl --user is-active semif-simplex.service 2>/dev/null | sed 's/^/ semif-simplex: /' || true
echo " HF_HOME=~/hf ~/semif-venv/bin/python -m semif_agent.cli run" systemctl --user is-active semif-gateway.service 2>/dev/null | sed 's/^/ semif-gateway: /' || true
echo " HF_HOME=~/hf ~/semif-venv/bin/python -m pytest tests/integration -q -s (box needs real engine+LLM)" fi
echo " HF_HOME=~/hf ~/semif-venv/bin/python -m semif_agent.cli dashboard --port 8765"
cat <<EOF
Done. Next steps:
cd "$REPO_ROOT"
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli run
HF_HOME="$HF_CACHE" "$PYTHON" -m pytest tests/integration -q -s (needs real engine+LLM)
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli dashboard --port 8765
SimpleX gateway:
- The bot runs as systemd user services 'semif-simplex' (daemon, port $SIMPLEX_PORT) and
'semif-gateway' (agent). Check them with:
systemctl --user status semif-simplex semif-gateway
journalctl --user -u semif-gateway -f
- Add this bot as a contact in your SimpleX app (its address is printed by the
daemon), then put your contactId/display name in config.json
gateway.simplex.allowed_users (discover the id from a 'gateway_denied' trace
event or the daemon's /contacts) and reply. With an empty allowlist the
gateway rejects everyone — that is the safe default.
EOF
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=SemIf agent messenger gateway (SimpleX)
After=network-online.target semif-simplex.service
Wants=network-online.target semif-simplex.service
[Service]
Type=simple
WorkingDirectory=@REPO@
Environment=HF_HOME=@REPO@/.runtime/hf
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=semif-gateway
[Install]
WantedBy=default.target
+16
View File
@@ -0,0 +1,16 @@
[Unit]
Description=SemIf agent SimpleX Chat daemon
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=@REPO@/.runtime/bin/simplex-chat -p @PORT@ -d @REPO@/.runtime/simplex -k "" --headless --user-display-name "@DISPLAY_NAME@"
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=semif-simplex
[Install]
WantedBy=default.target