diff --git a/AGENTS.md b/AGENTS.md index 786493b..b400939 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,8 +68,9 @@ capability is a new bridge, not a gateway feature. cli.py argparse: run (REPL / --script), dream, skills, status, relabel, dashboard, gateway (command intake), bridge (standalone third-party API bridges), check-config (validate config/ - against the core + pack schemas), config-init (seed the split - config/ + secrets.json) + against the core + pack schemas), setup (first-run interview -> + split config/ + secrets.json + install plan), config-init (seed + the schema-default split config/ + secrets.json) config.py layered per-machine config: config.json is a thin index (`{"include": [...]}`) over config/core.json + config/gateway.json + config/bridges.json + config/packs/.json, deep-merged in @@ -382,8 +383,9 @@ values are yours to choose. endpoints and models). `config.json` is an index (`{"include": [...]}`); `config/core.json` + `config/gateway.json` + `config/bridges.json` + `config/packs/.json` hold the values, and `secrets.json` holds - credentials referenced as `"!secret "`. `scripts/bootstrap.sh` seeds the - split config once (via `config-init`, only when `config.json` is absent) and + credentials referenced as `"!secret "`. `scripts/bootstrap.sh` generates the + split config once from the setup interview (via `setup`, only when + `config.json` is absent, or `--reconfigure`) and **nothing writes it afterwards — only a human edits it**. The committed `config.example.json` is GENERATED from the core schema (`semif_agent/config.py`) and each pack's `config` schema — regenerate it with @@ -769,17 +771,20 @@ CLI, unit tests (24) + integration tests (2). containment rule; prefer bootstrap.) - SemIf hard-pins `torch==2.10.0`, `numpy==2.2.6`, etc. The llamacpp path does **not** need torch (torch is imported lazily inside `direct.score`). Install - with `--no-deps` and bring only what's needed — the committed manifest - `requirements/staging.txt` is the single source of truth: + with `--no-deps` and bring only what's needed — the committed + `requirements/engine.txt` holds the local-engine pins (the union file + `staging.txt` includes it): `pip install -e --no-deps`, then - `CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/staging.txt` + `CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/engine.txt` (numpy 2.3.5, transformers 5.17.0, tokenizers 0.23.2, huggingface-hub 1.31.0, - llama-cpp-python 0.3.35, pytest). GPU offload is **opt-in**: set + llama-cpp-python 0.3.35). GPU offload is **opt-in**: set `engine.gpu_layers` and run `bootstrap.sh --gpu vulkan|rocm|cuda` (with `--gpu auto`, detection picks a backend when `engine.gpu_layers` is set), which installs the Vulkan build prereqs (`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only - host keeps the default CPU wheel — a GPU build is slower on CPU. + host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose + `engine.provider` is `"winnow"` installs none of this (no clone, no GGUF, no + tokenizer, no engine deps). - **Expected pip warnings:** pip reports "dependency conflicts" against semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging @@ -817,15 +822,25 @@ CLI, unit tests (24) + integration tests (2). (`check-config --write-example config.example.json`); secret keys are emitted as `"!secret "`, never a real value. `check-config` validates a live config (type mismatches and missing secrets are errors; unknown keys warn). -- **Seeding.** `config-init` writes the split layout + an empty `secrets.json` - from the schemas (bootstrap calls it once, only when `config.json` is absent); - afterwards only a human edits it. `scripts/config_merge.py` is the stdlib-only - merger bootstrap uses before the venv exists. +- **Seeding.** `setup` (`semif_agent/setup.py`, the `cli setup` subcommand) + runs the first-run interview and writes the split layout + `secrets.json` from + the answers; `config-init` writes the schema defaults with no interview. + Bootstrap calls `setup` once, only when `config.json` is absent (or + `--reconfigure`); afterwards only a human edits it. `scripts/config_merge.py` + is the stdlib-only merger bootstrap uses before the venv exists. +- **The install plan.** `setup` also emits a JSON *plan* (`.runtime/bootstrap-plan.json`) + that bootstrap reads to install only what the answers require: the local + engine clone/GGUF/tokenizer, `requirements/engine.txt` vs `transports.txt`, + the simplex-chat binary, the Playwright stack, the voice stack, and which + systemd units to render. `plan_from_config` derives the same plan from an + existing config on a rerun. The plan's `gateway_platforms` excludes `voice` + (foreground-only), which is what the `semif-gateway.service` unit runs. ### ollama - `bootstrap.sh` installs **no ollama**: it expects the target host to already run one for `llm` (and pulls `llm.model` into it), while `codegen` may be - remote. Point `--llm-url`/`--codegen-url` at the right daemons. + remote. The `llm`/`codegen` endpoints are set in the setup interview (or by + editing `config.json`); a host that leaves authoring `deny` needs neither. - If generation hangs with no log output, restart the ollama service — the GPU runner can wedge. - **A local reasoning model needs thinking off for `llm`.** A reasoning model @@ -847,24 +862,26 @@ CLI, unit tests (24) + integration tests (2). - Provision a fresh Ubuntu machine into a running host: clone `semif-agent` to a checkout (register its SSH key on your git host first), then run - `scripts/bootstrap.sh`. With no `config.json` yet it seeds the split config - (`config-init` writes `config/core.json`, `config/gateway.json`, - `config/bridges.json`, `config/packs/*.json`, the `config.json` index, and an - empty `secrets.json`); edit those to set `llm.model`/`codegen.model` and the - endpoints, and put credentials in `secrets.json`. Flags (`--llm-url`, - `--codegen-url`, `--llm-model`, - `--codegen-model`) override the values read from the merged config **for that run - only** and are never written back. `--voice` additionally installs the - optional voice-gateway stack (`requirements/voice.txt` + system - `libportaudio2` + `alsa-utils`) and downloads its models into `.runtime/voice/` via - `scripts/voice-models.py`. The script must be run from a checkout — - it reads pins from that checkout's `pins.json` and never re-clones the agent - repo (only the SemIf engine and the simplex-chat binary). Idempotent and - rerunnable; every stage no-ops on existing state, so it also boots an - unknown-state machine. It installs **no ollama**: `llm` is the local ollama - (bootstrap pulls `llm.model` if configured), `codegen` may point at a peer - host. It WARNs (never auto-pulls) if the remote codegen host is missing its - model, and WARNs if `llm.model`/`codegen.model` are unset. + `scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview** + (`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split + config from the answers — decision engine (local SemIf 4B or remote Winnow), + new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability + packs, gateways, and timezone — then installs only what those answers require + (the install *plan* drives every conditional stage). `--yes` takes the minimum + working defaults unattended; `--answers FILE` replays a saved answer set; + `--reconfigure` re-runs the interview and rewrites `config/` + `secrets.json`. + `--voice` / `--browser` additionally install those optional stacks + (`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`; + `requirements/browser.txt` + a browser) even when the plan did not pick them. + The script must be run from a checkout — it reads pins from that checkout's + `pins.json` and never re-clones the agent repo (only the SemIf engine and the + simplex-chat binary). Idempotent and rerunnable; every stage no-ops on existing + state, so it also boots an unknown-state machine (a rerun SKIPS the interview + and uses the existing config). It installs **no ollama**: `llm` is the local + ollama (bootstrap pulls `llm.model` when configured), `codegen` may point at a + peer host. It WARNs (never auto-pulls) if the codegen host is missing its + model, and WARNs only when authoring is enabled but `llm.model`/`codegen.model` + are unset. - **All installation artifacts live inside the checkout under a gitignored `.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`, `simplex/`, `systemd/`, and `voice/` for the optional voice models), so an @@ -880,45 +897,50 @@ CLI, unit tests (24) + integration tests (2). `bin_url`/`sha256`; bootstrap selects by `uname -m`, `arm64` normalized to `aarch64`). Per-machine `simplex_chat` ports/display names stay in `config.json`. The python dep pins - live in `requirements/staging.txt` (committed, one versioned artifact — every - host provisions from it). The agent reads `engine.source`/`revision` from + live in `requirements/` split by concern (committed): `core.txt` (the test + runner, always), `engine.txt` (the local decision engine), `transports.txt` + (websockets/lxmf), plus the optional `voice.txt`/`browser.txt`; `staging.txt` + is the union of the non-hardware files. Bootstrap installs only the subset the + plan requires. The agent reads `engine.source`/`revision` from `pins.json` and derives the GGUF path from `engine.gguf_url` under `.runtime/models/` (an explicit `engine.gguf` in `config.json` overrides it). - **Maintenance**: bump the pins in `pins.json` / `requirements/staging.txt`, + **Maintenance**: bump the pins in `pins.json` / `requirements/`, rerun the script, re-run the integration tests. The script never guesses. - pip prints **expected** "dependency conflict" warnings at install time (semif-phase1 declares torch/accelerate/protobuf/sentencepiece/numpy 2.2.6 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). Do not "fix" them by installing torch. -- Seeds the split config (`config-init`: `config/core.json`, +- Generates the split config from the interview (`setup`: `config/core.json`, `config/gateway.json`, `config/bridges.json`, `config/packs/*.json`, the - `config.json` index, and an empty `secrets.json`) only when `config.json` is - absent, and **never writes it again** — only a human edits it. The committed - `config.example.json` is GENERATED from the core + pack schemas and ships the - provisioned defaults, so a seeded config already has - `codegen.timeout: 3600`, the SimpleX gateway enabled - (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the - standalone forwarding bridge enabled (`bridges.simplex.enabled = true`, - `ws_url` from `simplex_chat.forward_port`) and - the LLM bridge enabled (`bridges.llm.enabled = true`; it reuses the `llm` - model); - the operator sets `llm.model`/`llm.base_url` and `codegen.model`/ - `codegen.base_url`, and puts credentials in `secrets.json`. Bootstrap renders/enables four user services: + `config.json` index, and `secrets.json`) when `config.json` is absent (or + `--reconfigure`), and **never writes it again otherwise** — only a human edits + it. The committed `config.example.json` is GENERATED from the core + pack + schemas and ships the provisioned defaults. The generated config reflects the + answers: the minimum path enables only `essentials`, `llm.provider = "semif"`, + an empty `codegen.model` (no authoring), and every gateway/bridge off; the + maximum path enables the chosen packs, gateways, a remote engine, and the + `llm`/`codegen` endpoints with credentials in `secrets.json`. Bootstrap + renders/enables **only the user services the plan needs**: `semif-simplex.service` (the command `simplex-chat` bot daemon, - `--create-bot-display-name` on `simplex_chat.port`), `semif-gateway.service` - (`.runtime/venv/bin/python -m semif_agent.cli gateway`), + `--create-bot-display-name` on `simplex_chat.port`, when the simplex gateway is + on), `semif-gateway.service` + (`.runtime/venv/bin/python -m semif_agent.cli gateway --platform `; voice is excluded — it is foreground-only), `semif-simplex-forward.service` (the bridge's **own** daemon/profile on - `simplex_chat.forward_port`) and `semif-bridge.service` - (`.runtime/venv/bin/python -m semif_agent.cli bridge`). The gateway allowlist + `simplex_chat.forward_port`, when the simplex pack is on) and + `semif-bridge.service` + (`.runtime/venv/bin/python -m semif_agent.cli bridge`, when any bridge pack is + on); a reconfigure retires units it no longer needs. The gateway allowlist (`gateway.simplex.allowed_users`) and fallback (`home_channel`) are `config.json` fields the operator edits; with an empty allowlist the gateway denies everyone (the safe default until the human adds their contact id). `--copy-data SRC` rsyncs a prior host's `data/` for continuity. Bootstrap then runs `packs/simplex/scripts/simplex-address.py` to create/print the command bot's contact address (and the forwarding bot's, via `--ws-url`). -- First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source - (~10 min on 6 cores); reruns are fast no-ops. +- First run of the minimum path still downloads the 2.8G GGUF and builds + `llama-cpp-python` from source (~10 min on 6 cores); a remote-engine host skips + both, and reruns are fast no-ops. - Per-host run/verify commands and addresses: `local/ENVIRONMENT.md`. ### codegen (skill bodies) @@ -926,7 +948,14 @@ CLI, unit tests (24) + integration tests (2). under `codegen` in config.json (your configured code-capable model — larger/slower than `llm`). Title + description for new skills come from the separate small `llm` provider (its own endpoint/model, shared transport in - `provider.py`); only the runnable code body uses codegen. + `provider.py`); only the runnable code body uses codegen. **Both are optional**: + an empty `codegen.model` means "no authoring path" — `build_codegen_client` + returns `None`, the scheduler guards every create door, and a host that leaves + `new_skill_creation` at `deny` (the minimum path) starts with neither endpoint + configured. `build_llm_client` likewise returns `None` for a non-`semif` + provider with no model. With authoring enabled the setup interview requires the + endpoints; a hand-edited config that enables authoring without them fails + cleanly (a traced `authoring_unavailable`, not a crash). - **Local engine as the `llm` provider: `"semif"`** (`provider.SemIfEngineClient` + `llm.SemIfLLMClient`). Set `llm.provider = "semif"` to generate the title/description (and any other `llm` text: gateway result cleanup, the LLM @@ -1475,7 +1504,7 @@ CLI, unit tests (24) + integration tests (2). the live voice pipeline against a real microphone are live-integration concerns. - **Deps.** `websockets` and `lxmf`/`rns` are pinned in - `requirements/staging.txt` (staging only); both are lazy-imported and the core + `requirements/transports.txt` (staging only); both are lazy-imported and the core stays stdlib-only. The voice stack is pinned separately in `requirements/voice.txt` (hardware-dependent: `sounddevice`, `openwakeword`, `faster-whisper`, `piper-tts`, `onnxruntime`, `webrtcvad-wheels`, plus the diff --git a/README.md b/README.md index 1ffcc03..0cec852 100644 --- a/README.md +++ b/README.md @@ -409,7 +409,9 @@ packs/ skill packs, each cloned from its own repo (pack.) into this gitignored dir — each ships its own bridge/ — see packs.json + PACKGEN.md scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in -requirements/ staging.txt — the pinned engine deps +requirements/ core.txt (test runner), engine.txt (local decision engine), + transports.txt (websockets/lxmf), voice.txt, browser.txt + (staging.txt = the union of the non-hardware files) tests/ stdlib unit tests + tests/integration (real engine + LLM) CODEGEN.md the contract fed to the skill-body codegen model TESTGEN.md the contract fed to the test/contract codegen model @@ -429,30 +431,37 @@ local/ gitignored: this deployment's notes (hosts, addresses, model ## Installation The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf -decision engine, a pinned GGUF, and an OpenAI-compatible endpoint for codegen. -`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree -in the checkout. +decision engine (local or remote). `scripts/bootstrap.sh` provisions what this +machine needs inside a gitignored `.runtime/` tree in the checkout — and only +what it needs, based on the answers to a short first-run interview. -### Prerequisites: ollama models +### Prerequisites: the decision engine, and optional models -Two OpenAI-compatible endpoints (usually ollama), which may be on different -machines: +The **decision engine** routes every request. It runs one of two ways, chosen in +the interview: + +- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the + default and the whole minimum path. +- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider == + "winnow"`). The local engine clone, GGUF, and tokenizer are then skipped. + +The local engine is CPU by default; to offload it to a GPU, set +`engine.gpu_layers` in `config.json` and run +`scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because it +is slower on CPU). + +**Skill authoring is opt-in** (`new_skill_creation`: `deny` by default). When it +is off, no `llm`/`codegen` endpoint is needed at all — the agent only runs the +shipped packs. When it is on, two OpenAI-compatible endpoints are required +(usually ollama, possibly on different machines): -- **`codegen`** — a large, code-capable model that writes skill bodies. This is - slow and ideally on a beefier host. - **`llm`** — a small, fast model that authors the title + description of a - newly created category/skill. Deliberately its own endpoint/model, so it can - stay local even when `codegen` is remote; it uses the same provider transport - (`provider.py`) and an unreachable endpoint is graceful (the request is not - re-dispatched), never fatal. Its `provider` can be `"ollama"` (default), + newly created category/skill. Its `provider` can be `"ollama"` (default), `"opencode"` (the hosted Console API), or `"semif"` — the already-loaded decision engine model generates in-process, with no endpoint and no - `llm.model` at all (see the `llm.semif` block in `config.json`). - -The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU -by default; to offload it to a GPU, set `engine.gpu_layers` in `config.json` and -run `scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because -it is slower on CPU). + `llm.model` at all. +- **`codegen`** — a large, code-capable model that writes skill bodies. This is + slow and ideally on a beefier host. ### Option A: one-command provisioning (`bootstrap.sh`) @@ -462,44 +471,57 @@ On a fresh Ubuntu machine, from a checkout of this repo: scripts/bootstrap.sh ``` -With no `config.json` yet, the script seeds the split config (`config-init` -writes `config/core.json`, `config/gateway.json`, `config/bridges.json`, -`config/packs/*.json`, the `config.json` index, and an empty `secrets.json`); -edit those to set `llm.model`/`codegen.model` (and the endpoints), and put -credentials in `secrets.json`. Flags override those -values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`, -`--codegen-model` — and are never written back to the config. +On a fresh machine the script **asks a few questions** and writes this machine's +config from the answers: -The script is idempotent (every stage no-ops on existing state) and: +1. **Decision engine** — local SemIf 4B, or a remote Winnow server (URL/model/key). +2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the + `llm` + `codegen` endpoints and credentials. +3. **Capabilities** — the shipped skill packs to enable: SimpleX, browser, + Nextcloud, Outlook (the `essentials` pack is always on). +4. **Gateways** — how you talk to the agent: SimpleX, LXMF, voice (or none — + REPL + dashboard only). +5. **Timezone** — an IANA name for timers and reported times. + +It then installs **only what those answers require**. Both ends of the spectrum +are reachable by the end of a run: + +- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers, + calculator). No account, no network, no gateway, no heavy downloads. +- **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen` + endpoints, and all gateways. + +Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE` +replays a saved answer set (JSON matching the `setup` fields). The script is +idempotent — on a rerun the interview is **skipped** and the existing config is +used; pass `--reconfigure` to re-run it. `--voice` / `--browser` additionally +install those optional stacks even if the plan did not pick them. + +The script: 1. installs system prereqs + enables linger; -2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine; -3. creates `.runtime/venv` and installs the pinned deps from - `requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since - the llama.cpp path never imports torch); -4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`; -5. pre-fetches the HF tokenizer into `.runtime/hf/`; -6. downloads and sha256-verifies the pinned `simplex-chat` binary; -7. seeds the split config (`config-init`) **only if `config.json` does not - already exist** — it never rewrites it (only a human edits it); -8. renders and enables systemd **user** units: - `semif-simplex` (bot daemon), `semif-gateway` (agent gateway), - `semif-simplex-forward` (the bridge's own daemon), `semif-bridge`; -9. prints the bot's SimpleX contact address. +2. clones/updates the skill packs, then runs the setup interview and writes + `config/` + `secrets.json` (first run or `--reconfigure`); +3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the + SemIf engine; +4. creates `.runtime/venv` and installs only the needed dep files: + `requirements/core.txt` always, `engine.txt` for a local engine, + `transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` / + `browser.txt` for those stacks); +5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/` + and pre-fetches the HF tokenizer into `.runtime/hf/`; +6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a + SimpleX gateway or the simplex pack is selected; +7. renders and enables only the systemd **user** units the answers need + (`semif-simplex` bot daemon, `semif-gateway` agent, `semif-simplex-forward` + bridge daemon, `semif-bridge`), retiring any a reconfigure dropped; +8. prints the SimpleX contact address(es) when those services are active. -Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`, -`--copy-data SRC`) override the values read from `config.json` for that run only. -`--voice` additionally installs the optional voice-gateway stack -(`requirements/voice.txt` + system PortAudio) and downloads its models (the -openWakeWord models into the venv under `.runtime/venv`, the Piper voice into -`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache). -Run `scripts/bootstrap.sh -h` for the full list. - -It installs **no ollama**; it expects one for `llm` and pulls `llm.model`, -warning (never auto-pulling) if the remote codegen host is missing its model. -Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision, -simplex-chat version/url+sha256) live in the committed `pins.json`, not in -`config.json`. +Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it +pulls `llm.model` from the target host's ollama when configured, and never +auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF +tokenizer revision, simplex-chat version/url+sha256) live in the committed +`pins.json`, not in `config.json`. ### Option B: core only (stdlib) @@ -510,11 +532,12 @@ python3 -m pytest tests/ -q --ignore=tests/integration ``` For a full install on a machine you manage, follow the same steps bootstrap -performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF, -tokenizer cache), then seed the split config and adjust paths: +performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF, +tokenizer cache), then generate the split config: ```sh -python -m semif_agent.cli config-init # writes config/ + secrets.json +python -m semif_agent.cli setup --interview # or --yes / --answers FILE +python -m semif_agent.cli config-init # schema defaults, no interview ``` ### Configuration @@ -524,11 +547,13 @@ refuses to start without it. `config.json` is a thin **index** (`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments under `config/` hold the values and are deep-merged in order. Credentials live in the gitignored `secrets.json` and are referenced from any fragment as -`"!secret "` (there is no `api_key_env`). `scripts/bootstrap.sh` seeds the -split config once via `config-init`; afterwards only a human edits it. +`"!secret "` (there is no `api_key_env`). `scripts/bootstrap.sh` runs +`setup` to generate the split config from your answers; afterwards only a human +edits it (`--reconfigure` re-runs the interview). ```sh -python -m semif_agent.cli config-init # seed config/ + secrets.json (once) +python -m semif_agent.cli setup --interview # generate config/ from answers +python -m semif_agent.cli config-init # seed schema defaults (no interview) python -m semif_agent.cli check-config # validate against the schemas ``` @@ -572,9 +597,12 @@ host/port/token, so there is no duplicate top-level key to keep in sync. A bridg with no block (or no port) leaves the variable unresolved and the operator is asked for it. -`llm.model` and `codegen.model` are **required** (no default): set each to a -model its endpoint serves. A missing model fails fast at startup with a clear -config error rather than sending a request to a model that isn't there. +`llm.model` and `codegen.model` are **required only when authoring is enabled** +(`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves. +An empty `codegen.model` means "no authoring path" — the minimum config leaves it +empty and the agent simply runs the shipped packs. With authoring on, a missing +model fails fast at startup with a clear config error rather than sending a +request to a model that isn't there. Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`, `data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too. @@ -590,6 +618,7 @@ Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`, All subcommands go through the CLI: ```sh +python -m semif_agent.cli setup --interview # generate config/ from answers python -m semif_agent.cli run # interactive REPL python -m semif_agent.cli run --script inputs.jsonl python -m semif_agent.cli dream # cost report diff --git a/requirements/core.txt b/requirements/core.txt new file mode 100644 index 0000000..201e7f4 --- /dev/null +++ b/requirements/core.txt @@ -0,0 +1,7 @@ +# Core agent deps (the agent itself is stdlib-only; this is the test runner). +# +# Every host installs this. The decision engine, messaging transports, voice, +# and browser stacks are separate, optional files (engine.txt, transports.txt, +# voice.txt, browser.txt) so a host installs only what its answers require. +# `staging.txt` includes all of them for a full provision. +pytest diff --git a/requirements/engine.txt b/requirements/engine.txt new file mode 100644 index 0000000..3ce4680 --- /dev/null +++ b/requirements/engine.txt @@ -0,0 +1,18 @@ +# Local decision-engine deps (SemIf / llama.cpp, CPU path). +# +# Only needed on a host whose `engine.provider` is the local SemIf GGUF. A host +# pointed at a remote Winnow decision server (engine.provider == "winnow") +# installs neither this file nor the SemIf engine clone / GGUF / tokenizer. +# +# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/ +# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend +# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no +# cp314 wheel (source build fails). So semif-phase1 is installed with +# `--no-deps` and exactly this set is brought in instead. The pins match the +# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's +# declared version) so the pip resolver stays quiet about it. +numpy==2.3.5 +transformers==5.17.0 +tokenizers==0.23.2 +huggingface-hub==1.31.0 +llama-cpp-python==0.3.35 diff --git a/requirements/staging.txt b/requirements/staging.txt index aadd8bf..35d8a5d 100644 --- a/requirements/staging.txt +++ b/requirements/staging.txt @@ -1,23 +1,13 @@ -# Staging-machine engine deps (CPU llama.cpp path). +# Full provision: every dependency this repo can need, for a host that runs the +# local decision engine, all messaging transports, the voice gateway, and the +# browser bridge. This is the union of the per-concern files below; a +# `scripts/bootstrap.sh` run installs only the subset its answers require, so +# prefer those files (engine.txt, transports.txt, voice.txt, browser.txt) when +# provisioning by hand. # -# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/ -# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend -# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no -# cp314 wheel (source build fails). So semif-phase1 is installed with -# `--no-deps` and exactly this set is brought in instead. The pins match the -# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's -# declared version) so the pip resolver stays quiet about it. -numpy==2.3.5 -transformers==5.17.0 -tokenizers==0.23.2 -huggingface-hub==1.31.0 -llama-cpp-python==0.3.35 -pytest -# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the -# gateway refuses to start without it. Not needed by the decision engine. -websockets==15.0.1 -# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway -# refuses to start without it. Runs in-process — there is no daemon binary. -# rns pulls cryptography + pyserial transitively (resolved by pip). -lxmf==1.2.0 -rns==1.5.7 \ No newline at end of file +# Voice and browser stacks are hardware/optional and are NOT included here — +# install them with `scripts/bootstrap.sh --voice` / `--browser` (or +# `pip install -r requirements/voice.txt` / `browser.txt`). +-r core.txt +-r engine.txt +-r transports.txt diff --git a/requirements/transports.txt b/requirements/transports.txt new file mode 100644 index 0000000..8f740ec --- /dev/null +++ b/requirements/transports.txt @@ -0,0 +1,13 @@ +# Messaging transport deps (SimpleX + LXMF gateways/bridges). +# +# Only needed on a host that enables the SimpleX gateway or bridge (which uses +# `websockets` against its simplex-chat daemon) or the LXMF gateway (in-process +# `lxmf`/`rns`). Both are lazy-imported, so a host without them still runs every +# other front end; the gateway refuses to start with an install hint. +# +# `websockets` is shared by the command gateway and the forwarding bridge (the +# neutral `semif_agent/simplex_ws.py`). `lxmf` pulls `rns` (Reticulum) and +# cryptography transitively; both are pinned so the resolver stays quiet. +websockets==15.0.1 +lxmf==1.2.0 +rns==1.5.7 diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 107a7d9..29b2cce 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -1,10 +1,23 @@ #!/usr/bin/env bash # Provision a new Ubuntu machine into a running semif-agent host. # -# Idempotent: safe to rerun; every stage no-ops on already-provisioned state, -# so it can also bootstrap a machine of unknown state. The small -# title/description model runs on this machine's local ollama (bootstrap pulls -# it); codegen may point at a remote ollama host. This script installs NO ollama. +# First run asks a few questions and writes this machine's config from the +# answers (see `python -m semif_agent.cli setup`): the decision engine (local +# SemIf 4B or a remote Winnow server), whether the agent may author new skills, +# which capability packs to enable, and which gateways to run. Bootstrap then +# installs ONLY what those answers require — a REPL-only host never downloads +# the simplex-chat binary, Playwright, or the voice stack. +# +# The two ends of the spectrum are both reachable by the end of a run: +# * minimum — local SemIf 4B + the `essentials` pack (canned replies, +# time/timers, calculator). No account, no network, no gateway. +# * maximum — every pack (SimpleX, browser, Nextcloud, Outlook), a remote +# Winnow decision engine, remote `llm`/`codegen` endpoints, and all gateways. +# +# Idempotent: safe to rerun; every stage no-ops on already-provisioned state. On +# a rerun the interview is SKIPPED and the existing config is used — pass +# `--reconfigure` to re-run it. This script installs NO ollama; a local `llm` +# pulls its model from the target host's ollama, and `codegen` may be remote. # # Must be run from a semif-agent checkout. The checkout is used as-is and never # re-cloned — only the SemIf engine, the simplex-chat binary, and the skill @@ -13,15 +26,13 @@ # named pack. on the same host (see packs.json) into the gitignored # packs/ directory. # -# config.json is the per-machine USER config (a thin index over config/*.json) -# and this script NEVER rewrites it. It seeds the split config via `config-init` -# (config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json, -# the config.json index, and an empty secrets.json) only when config.json is -# absent, then reads every per-machine value from the merged config; only a human -# edits it afterwards. Pinned external refs (SemIf commit, GGUF url+sha256, -# HF tokenizer revision, simplex-chat version/url+sha256) live in the committed -# pins.json and the python dep pins in requirements/staging.txt — bump those -# (via git) and rerun to upgrade. +# config.json is the per-machine USER config (a thin index over config/*.json). +# This script seeds it from the interview the FIRST time (or with +# --reconfigure), then reads every per-machine value from it; only a human edits +# it afterwards. Pinned external refs (SemIf commit, GGUF url+sha256, HF +# tokenizer revision, simplex-chat version/url+sha256) live in the committed +# pins.json and the python dep pins in requirements/ — bump those (via git) and +# rerun to upgrade. # # Every installation artifact lives INSIDE this checkout under .runtime/ # (gitignored), so an end user can find and debug the whole stack in one tree: @@ -32,21 +43,17 @@ # Only artifacts that operationally must live elsewhere are outside: the SSH # key (~/.ssh) and the real systemd user dir/linger. # -# Flags override the values read from the merged config FOR THIS RUN ONLY; -# nothing is written back to the config. -# # Usage: -# scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL] -# [--codegen-model MODEL] [--copy-data SRC] [--voice] -# [--browser] [--gpu MODE] [--pack-base URL] [-h] +# scripts/bootstrap.sh [--reconfigure] [--yes | --answers FILE] +# [--copy-data SRC] [--voice] [--browser] +# [--gpu MODE] [--pack-base URL] [-h] # # Run as the human user; sudo is used internally for system bits. set -euo pipefail -LLM_URL="" -CODEGEN_URL="" -LLM_MODEL="" -CODEGEN_MODEL="" +RECONFIGURE=0 +YES=0 +ANSWERS_FILE="" COPY_DATA="" VOICE=0 BROWSER=0 @@ -56,13 +63,12 @@ PACK_BASE="" usage() { sed -n '2,/^set -euo pipefail/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//' echo - echo " --llm-url URL override llm.base_url from config.json for this run (else config.json, else http://127.0.0.1:11434)" - echo " --codegen-url URL override codegen.base_url from config.json for this run" - echo " --llm-model MODEL override llm.model from config.json for this run (pulled if the local ollama lacks it)" - echo " --codegen-model MODEL override codegen.model from config.json for this run" + echo " --reconfigure re-run the setup interview and rewrite config/ (default: use existing config)" + echo " --yes non-interactive: take the minimum working defaults (no prompts)" + echo " --answers FILE non-interactive: read answers from a JSON file (see 'python -m semif_agent.cli setup --help')" echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in" - echo " --voice install the optional voice-gateway stack + download its models" - echo " --browser install the optional browser-bridge stack (Playwright + Chromium)" + echo " --voice also install the optional voice-gateway stack + models" + echo " --browser also install the optional browser-bridge stack (Playwright + Chromium)" echo " --gpu MODE decision-engine llama.cpp backend: auto (default; a GPU build only when engine.gpu_layers is set), vulkan, rocm, cuda, cpu" echo " --pack-base URL base URL of the skill-pack repos (default: derived from this checkout's origin remote)" echo " -h this help" @@ -71,10 +77,9 @@ usage() { while [[ $# -gt 0 ]]; do case "$1" in - --llm-url) LLM_URL="$2"; shift 2 ;; - --codegen-url) CODEGEN_URL="$2"; shift 2 ;; - --llm-model) LLM_MODEL="$2"; shift 2 ;; - --codegen-model) CODEGEN_MODEL="$2"; shift 2 ;; + --reconfigure) RECONFIGURE=1; shift ;; + --yes) YES=1; shift ;; + --answers) ANSWERS_FILE="$2"; shift 2 ;; --copy-data) COPY_DATA="$2"; shift 2 ;; --voice) VOICE=1; shift ;; --browser) BROWSER=1; shift ;; @@ -100,6 +105,7 @@ SIMPLEX_DB="$RUNTIME/simplex" UNITS="$RUNTIME/systemd" USER_UNITS="$HOME/.config/systemd/user" BROWSERS="$RUNTIME/browser" +PLAN="$RUNTIME/bootstrap-plan.json" PYTHON="$VENV/bin/python" PIP="$VENV/bin/pip" @@ -117,9 +123,8 @@ fi # gitignored packs/ directory; the agent loads every pack under skill_packs # (default "packs"). The list lives in the committed packs.json; each repo is a # sibling of this checkout's origin remote (pack.) unless --pack-base -# overrides the base. This runs BEFORE the config is seeded so config-init sees -# the packs and generates their config/packs/*.json fragments. Idempotent: -# clone when absent, fast-forward when present. +# overrides the base. This runs BEFORE the interview so setup sees every pack +# and can offer it. Idempotent: clone when absent, fast-forward when present. PACK_MANIFEST="$REPO_ROOT/packs.json" if [[ -f "$PACK_MANIFEST" ]]; then if [[ -z "$PACK_BASE" ]]; then @@ -163,26 +168,95 @@ PY fi fi -# config.json is per-machine USER config. Seed it once (as a thin index plus the -# split config/ fragments + secrets.json), then never write it again — only a -# human edits it. The committed config.example.json is GENERATED from the pack + -# core schemas; see `python -m semif_agent.cli check-config --write-example`. -if [[ ! -f "$CONFIG" ]]; then - echo "== seeding config/ + secrets.json (edit them to configure this machine)" - PYTHONPATH="$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -m semif_agent.cli config-init --path "$CONFIG" \ - || { echo "config-init failed; falling back to a flat config.json from the example" >&2; cp "$EXAMPLE" "$CONFIG"; } +# --- configure this machine (interview -> config/ + secrets.json) -------------- +# On a fresh machine (or --reconfigure) ask the setup questions and generate the +# split config from the answers; otherwise use the existing config. Either way +# emit a machine-readable install plan that drives the conditional stages below. +mkdir -p "$RUNTIME" +setup_args=(--path "$CONFIG" --plan-out "$PLAN") +if [[ -n "$ANSWERS_FILE" ]]; then + if [[ ! -f "$ANSWERS_FILE" ]]; then + echo "answers file not found: $ANSWERS_FILE" >&2 + exit 1 + fi + setup_args+=(--answers "$ANSWERS_FILE") +elif [[ "$YES" = 1 ]]; then + setup_args+=(--yes) +elif [[ -t 0 && -t 1 ]]; then + setup_args+=(--interview) +else + echo "== no terminal for the setup interview; using the minimum defaults (--yes)" >&2 + setup_args+=(--yes) fi +run_setup() { + PYTHONPATH="$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -m semif_agent.cli setup "$@" +} + +if [[ ! -f "$CONFIG" || "$RECONFIGURE" = 1 ]]; then + if [[ "$RECONFIGURE" = 1 && -f "$CONFIG" ]]; then + echo "== reconfiguring $CONFIG (rewriting config/ + secrets.json)" + setup_args+=(--force) + else + echo "== configuring this machine" + fi + run_setup "${setup_args[@]}" || { echo "setup failed" >&2; exit 1; } +else + echo "== using existing $CONFIG (pass --reconfigure to change it)" + run_setup --path "$CONFIG" --plan-only --plan-out "$PLAN" \ + || { echo "could not derive the install plan from $CONFIG" >&2; exit 1; } +fi + +# Read the plan (install decisions) and the merged config (per-machine values). +# The ASCII unit separator (\x1f) delimits fields so an empty value never shifts +# the fields after it. +IFS=$'\x1f' read -r PLAN_ENGINE PLAN_AUTHORING PLAN_PACKS PLAN_GATEWAYS \ + PLAN_GATEWAY_PLATFORMS PLAN_BRIDGE_PACKS PLAN_INSTALL_ENGINE PLAN_BRIDGE_SVC \ + PLAN_GATEWAY_SVC PLAN_SIMPLEX_BIN PLAN_SIMPLEX_FWD PLAN_BROWSER PLAN_VOICE < <( + python3 - "$PLAN" <<'PY' +import json, sys +p = json.load(open(sys.argv[1])) +def flag(key): + return "1" if p.get(key) else "0" +print("\x1f".join([ + str(p.get("engine_provider", "")), + str(p.get("authoring", "")), + ",".join(p.get("packs", [])), + ",".join(p.get("gateways", [])), + ",".join(p.get("gateway_platforms", [])), + ",".join(p.get("bridge_packs", [])), + flag("install_engine"), + flag("install_bridge_service"), + flag("install_gateway_service"), + flag("install_simplex_binary"), + flag("install_simplex_forward"), + flag("install_browser"), + flag("install_voice"), +])) +PY +) + +# The optional-stack flags force an install even when the plan did not pick it +# (e.g. a scripted pre-seed); enabling it in config is still the operator's call. +[[ "$VOICE" = 1 ]] && PLAN_VOICE=1 +[[ "$BROWSER" = 1 ]] && PLAN_BROWSER=1 + +# Messaging transports (websockets / lxmf) are needed by the SimpleX gateway or +# bridge and the LXMF gateway. +NEED_TRANSPORTS=0 +[[ "$PLAN_SIMPLEX_BIN" = 1 ]] && NEED_TRANSPORTS=1 +[[ ",$PLAN_GATEWAYS," == *",lxmf,"* ]] && NEED_TRANSPORTS=1 + +echo "== plan: engine=$PLAN_ENGINE | authoring=$PLAN_AUTHORING | packs=$PLAN_PACKS" +echo " gateways=${PLAN_GATEWAYS:-none} | install: engine=$PLAN_INSTALL_ENGINE transports=$NEED_TRANSPORTS bridge=$PLAN_BRIDGE_SVC gateway=$PLAN_GATEWAY_SVC browser=$PLAN_BROWSER voice=$PLAN_VOICE" + # The live config may be split (config.json includes config/*.json); merge it so # the reads below see one flat object. Stdlib-only, so it works before the venv. MERGED_CONFIG="$RUNTIME/config.merged.json" -mkdir -p "$RUNTIME" python3 "$REPO_ROOT/scripts/config_merge.py" "$CONFIG" > "$MERGED_CONFIG" \ || { echo "could not read $CONFIG" >&2; exit 1; } # --- read pins from the committed pins.json --------------------------------- -# The ASCII unit separator (\x1f) delimits fields so an empty value never -# shifts the fields after it (space-splitting collapses runs of whitespace). # The simplex-chat binary is per-arch: normalize `uname -m` to a pins key. SIMPLEX_ARCH="$(uname -m)" case "$SIMPLEX_ARCH" in @@ -211,22 +285,27 @@ print("\x1f".join([ PY ) -if [[ -z "$SEMIF_REPO" || -z "$SEMIF_REF" || -z "$GGUF_URL" || -z "$GGUF_SHA256" ]]; then - echo "engine pins missing in $PINS (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2 - exit 1 +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + if [[ -z "$SEMIF_REPO" || -z "$SEMIF_REF" || -z "$GGUF_URL" || -z "$GGUF_SHA256" ]]; then + echo "engine pins missing in $PINS (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2 + exit 1 + fi fi -if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then +if [[ "$PLAN_SIMPLEX_BIN" = 1 ]] && [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then echo "simplex_chat pins missing in $PINS for arch '$SIMPLEX_ARCH' (assets..bin_url/sha256)" >&2 exit 1 fi -# --- read per-machine values from config.json (flags override for this run) -- +# --- read per-machine values from config.json ---------------------------------- IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_LLM_PROVIDER CFG_CODEGEN_URL CFG_CODEGEN_MODEL \ + CFG_CODEGEN_PROVIDER CFG_ENGINE_PROVIDER CFG_WINNOW_URL CFG_WINNOW_MODEL \ SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <( python3 - "$MERGED_CONFIG" <<'PY' import json, sys cfg = json.load(open(sys.argv[1])) s = cfg.get("simplex_chat", {}) +eng = cfg.get("engine", {}) +win = eng.get("winnow", {}) def strip_v1(u): u = str(u or "").rstrip("/") return u[:-3] if u.endswith("/v1") else u @@ -236,6 +315,10 @@ print("\x1f".join([ str(cfg.get("llm", {}).get("provider", "ollama") or "ollama").lower(), strip_v1(cfg.get("codegen", {}).get("base_url")), str(cfg.get("codegen", {}).get("model", "") or ""), + str(cfg.get("codegen", {}).get("provider", "ollama") or "ollama").lower(), + str(eng.get("provider", "semif") or "semif").lower(), + strip_v1(win.get("base_url")), + str(win.get("model", "") or ""), str(s.get("port", "")), str(s.get("display_name", "") or ""), str(s.get("forward_port", "")), @@ -244,12 +327,15 @@ print("\x1f".join([ PY ) -# A flag overrides config.json for this run only; config.json is never touched. -LLM_URL="${LLM_URL:-${CFG_LLM_URL:-http://127.0.0.1:11434}}" -CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}" -LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}" -CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}" -LLM_PROVIDER="${LLM_PROVIDER:-${CFG_LLM_PROVIDER:-ollama}}" +LLM_URL="${CFG_LLM_URL:-http://127.0.0.1:11434}" +LLM_MODEL="$CFG_LLM_MODEL" +LLM_PROVIDER="${CFG_LLM_PROVIDER:-ollama}" +CODEGEN_URL="$CFG_CODEGEN_URL" +CODEGEN_MODEL="$CFG_CODEGEN_MODEL" +CODEGEN_PROVIDER="${CFG_CODEGEN_PROVIDER:-ollama}" +ENGINE_PROVIDER="${CFG_ENGINE_PROVIDER:-semif}" +WINNOW_URL="$CFG_WINNOW_URL" +WINNOW_MODEL="$CFG_WINNOW_MODEL" if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2 @@ -264,11 +350,11 @@ CODEGEN_API="${CODEGEN_URL%/v1}"; CODEGEN_API="${CODEGEN_API%/}" with_v1() { local u="${1%/}"; [[ "$u" == */v1 ]] && printf '%s' "$u" || printf '%s/v1' "$u"; } LLM_V1="$(with_v1 "$LLM_URL")" -echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex-chat sha256 ${SIMPLEX_SHA256:0:12}…" -if [[ "$LLM_PROVIDER" == "semif" ]]; then - echo "== llm semif (in-process engine model) | codegen $CODEGEN_URL" +echo "== pins: simplex-chat sha256 ${SIMPLEX_SHA256:0:12}… | gguf ${GGUF_SHA256:0:12}…" +if [[ "$ENGINE_PROVIDER" = "winnow" ]]; then + echo "== decision engine: remote Winnow ($WINNOW_URL, model ${WINNOW_MODEL:-?})" else - echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL" + echo "== decision engine: local SemIf @ $SEMIF_REF" fi echo "== runtime tree: $RUNTIME" @@ -304,35 +390,40 @@ if ! "$PY" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) els fi echo "== python: $("$PY" --version)" -# --- stage 2: ssh key + SemIf engine clone ------------------------------------ +# --- stage 2: ssh key + SemIf engine clone (local engine only) ---------------- mkdir -p ~/.ssh if [[ ! -f ~/.ssh/id_ed25519 ]]; then - echo "== generating ~/.ssh/id_ed25519 (register this key on Gitea for the agent repo)" + echo "== generating ~/.ssh/id_ed25519 (register this key on your git host for the agent repo)" ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 cat ~/.ssh/id_ed25519.pub fi git -C "$REPO_ROOT" pull --ff-only || true -if [[ ! -d "$ENGINE/.git" ]]; then - echo "== cloning SemIf engine from $SEMIF_REPO into $ENGINE" - git clone "$SEMIF_REPO" "$ENGINE" -fi -if [[ "$(git -C "$ENGINE" rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then - echo "== pinning SemIf engine to $SEMIF_REF" - git -C "$ENGINE" fetch origin - git -C "$ENGINE" checkout "$SEMIF_REF" +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + if [[ ! -d "$ENGINE/.git" ]]; then + echo "== cloning SemIf engine from $SEMIF_REPO into $ENGINE" + git clone "$SEMIF_REPO" "$ENGINE" + fi + if [[ "$(git -C "$ENGINE" rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then + echo "== pinning SemIf engine to $SEMIF_REF" + git -C "$ENGINE" fetch origin + git -C "$ENGINE" checkout "$SEMIF_REF" + fi +else + echo "== remote decision engine selected; skipping the local engine clone" fi -# --- stage 2b: pick the llama.cpp GPU backend --------------------------------- -# The decision engine scores the GGUF through llama.cpp, which runs on CPU -# unless llama-cpp-python was built with a GPU backend. A GPU-enabled build is -# opt-in: llama.cpp's Vulkan backend splits the compute graph across CPU and -# Vulkan even with `n_gpu_layers=0`, roughly doubling CPU latency, so a CPU-only -# host must not get one. `--gpu ` forces a build; `--gpu auto` (the -# default) builds a GPU backend only when config.json asks for offload -# (`engine.gpu_layers` nonzero). -CONFIG_GPU_LAYERS="$(python3 - "$MERGED_CONFIG" <<'PY' +# --- stage 2b: pick the llama.cpp GPU backend (local engine only) ------------- +# A GPU-enabled build is opt-in: llama.cpp's Vulkan backend splits the compute +# graph across CPU and Vulkan even with `n_gpu_layers=0`, roughly doubling CPU +# latency, so a CPU-only host must not get one. `--gpu ` forces a build; +# `--gpu auto` (default) builds a GPU backend only when config.json asks for +# offload (`engine.gpu_layers` nonzero). +GPU_BACKEND=cpu +CONFIG_GPU_LAYERS=0 +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + CONFIG_GPU_LAYERS="$(python3 - "$MERGED_CONFIG" <<'PY' import json, sys try: print(int(json.load(open(sys.argv[1])).get("engine", {}).get("gpu_layers", 0) or 0)) @@ -340,37 +431,38 @@ except Exception: print(0) PY )" -detect_gpu_backend() { - if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi >/dev/null 2>&1; then - echo cuda; return - fi - if [[ -d /opt/rocm ]]; then - echo rocm; return - fi - if command -v glslc >/dev/null 2>&1 && compgen -G "/usr/share/vulkan/icd.d/*.json" >/dev/null; then - echo vulkan; return - fi - echo cpu -} -case "$GPU_MODE" in - cpu) GPU_BACKEND=cpu ;; - vulkan|rocm|cuda) GPU_BACKEND="$GPU_MODE" ;; - auto) - if [[ "$CONFIG_GPU_LAYERS" != 0 ]]; then - GPU_BACKEND="$(detect_gpu_backend)" - else - GPU_BACKEND=cpu + detect_gpu_backend() { + if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi >/dev/null 2>&1; then + echo cuda; return fi - ;; - *) echo "unknown --gpu mode: $GPU_MODE (want auto, vulkan, rocm, cuda, cpu)" >&2; exit 2 ;; -esac + if [[ -d /opt/rocm ]]; then + echo rocm; return + fi + if command -v glslc >/dev/null 2>&1 && compgen -G "/usr/share/vulkan/icd.d/*.json" >/dev/null; then + echo vulkan; return + fi + echo cpu + } + case "$GPU_MODE" in + cpu) GPU_BACKEND=cpu ;; + vulkan|rocm|cuda) GPU_BACKEND="$GPU_MODE" ;; + auto) + if [[ "$CONFIG_GPU_LAYERS" != 0 ]]; then + GPU_BACKEND="$(detect_gpu_backend)" + else + GPU_BACKEND=cpu + fi + ;; + *) echo "unknown --gpu mode: $GPU_MODE (want auto, vulkan, rocm, cuda, cpu)" >&2; exit 2 ;; + esac + echo "== decision-engine llama.cpp backend: $GPU_BACKEND (engine.gpu_layers=$CONFIG_GPU_LAYERS)" +fi case "$GPU_BACKEND" in vulkan) LLAMA_CMAKE_ARGS="-DGGML_VULKAN=on" ;; rocm) LLAMA_CMAKE_ARGS="-DGGML_HIP=on" ;; cuda) LLAMA_CMAKE_ARGS="-DGGML_CUDA=on" ;; *) LLAMA_CMAKE_ARGS="" ;; esac -echo "== decision-engine llama.cpp backend: $GPU_BACKEND (engine.gpu_layers=$CONFIG_GPU_LAYERS)" if [[ "$GPU_BACKEND" = vulkan ]]; then VULKAN_PKGS=(libvulkan-dev glslc spirv-headers glslang-tools) @@ -388,31 +480,42 @@ if [[ ! -x "$PYTHON" ]]; then echo "== creating venv at $VENV" "$PY" -m venv "$VENV" fi -echo "== installing engine deps into $VENV" +echo "== installing core deps into $VENV" "$PIP" install --upgrade pip setuptools wheel -"$PIP" install -e "$ENGINE" --no-deps -CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \ - "$PIP" install -r "$REPO_ROOT/requirements/staging.txt" +"$PIP" install -r "$REPO_ROOT/requirements/core.txt" -# Make the installed llama-cpp-python match the requested backend: pip ships a -# CPU wheel and its wheel cache hands it back even when CMAKE_ARGS asks for a -# GPU backend, so force a source build whenever offload support disagrees. -installed_gpu=no -"$PYTHON" -c 'import llama_cpp, sys; sys.exit(0 if llama_cpp.llama_supports_gpu_offload() else 1)' 2>/dev/null && installed_gpu=yes -want_gpu=yes -[[ "$GPU_BACKEND" = cpu ]] && want_gpu=no -if [[ "$installed_gpu" != "$want_gpu" ]]; then - LLAMA_PIN="$(grep -m1 -E '^llama-cpp-python==' "$REPO_ROOT/requirements/staging.txt")" - echo "== rebuilding llama-cpp-python for the $GPU_BACKEND backend ($LLAMA_PIN)" +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + echo "== installing engine deps (llama.cpp CPU/GPU path)" + "$PIP" install -e "$ENGINE" --no-deps CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \ - "$PIP" install --no-deps --force-reinstall --no-cache-dir --no-binary llama-cpp-python "$LLAMA_PIN" + "$PIP" install -r "$REPO_ROOT/requirements/engine.txt" + + # Make the installed llama-cpp-python match the requested backend: pip ships a + # CPU wheel and its wheel cache hands it back even when CMAKE_ARGS asks for a + # GPU backend, so force a source build whenever offload support disagrees. + installed_gpu=no + "$PYTHON" -c 'import llama_cpp, sys; sys.exit(0 if llama_cpp.llama_supports_gpu_offload() else 1)' 2>/dev/null && installed_gpu=yes + want_gpu=yes + [[ "$GPU_BACKEND" = cpu ]] && want_gpu=no + if [[ "$installed_gpu" != "$want_gpu" ]]; then + LLAMA_PIN="$(grep -m1 -E '^llama-cpp-python==' "$REPO_ROOT/requirements/engine.txt")" + echo "== rebuilding llama-cpp-python for the $GPU_BACKEND backend ($LLAMA_PIN)" + CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \ + "$PIP" install --no-deps --force-reinstall --no-cache-dir --no-binary llama-cpp-python "$LLAMA_PIN" + fi fi + +if [[ "$NEED_TRANSPORTS" = 1 ]]; then + echo "== installing messaging transport deps (websockets / lxmf)" + "$PIP" install -r "$REPO_ROOT/requirements/transports.txt" +fi + "$PIP" install -e "$REPO_ROOT" --no-deps -# --- stage 3b: optional voice-gateway stack (--voice) -------------------------- +# --- stage 3b: optional voice-gateway stack ------------------------------------ # Hardware-dependent: only the host with a microphone/speaker needs it. The # stack is lazy-imported, so a host without it still runs every other front end. -if [[ "$VOICE" = 1 ]]; then +if [[ "$PLAN_VOICE" = 1 ]]; then # libportaudio2 is the I/O backend sounddevice needs; alsa-utils provides # amixer/alsamixer/alsactl so the operator can unmute and set the mic/speaker # levels (PortAudio itself has no volume control). @@ -434,12 +537,12 @@ if [[ "$VOICE" = 1 ]]; then "$PIP" install --no-deps openwakeword==0.6.0 fi -# --- stage 3c: optional browser-bridge stack (--browser) ----------------------- +# --- stage 3c: optional browser-bridge stack ----------------------------------- # Playwright + its Chromium binaries. Optional: lazy-imported, so a host without # it still runs every other bridge. Browsers go under the checkout's # .runtime/browser (the containment rule); the bridge sets PLAYWRIGHT_BROWSERS_PATH # to the same path at launch. -if [[ "$BROWSER" = 1 ]]; then +if [[ "$PLAN_BROWSER" = 1 ]]; then echo "== installing browser-bridge deps into $VENV" "$PIP" install -r "$REPO_ROOT/requirements/browser.txt" BROWSER_ENGINE="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true @@ -471,73 +574,100 @@ PY fi fi -# --- stage 4: GGUF -------------------------------------------------------------- -GGUF_NAME="$(basename "$GGUF_URL")" -GGUF="$MODELS/$GGUF_NAME" -sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; } -if ! sha_ok; then - echo "== downloading GGUF ($GGUF_NAME) into $MODELS" - rm -f "$GGUF" "$GGUF.tmp" - curl -fL --retry 3 -o "$GGUF.tmp" "$GGUF_URL" - mv "$GGUF.tmp" "$GGUF" -fi -sha_ok || { echo "GGUF sha256 mismatch: expected $GGUF_SHA256" >&2; exit 1; } -echo "== GGUF verified ($GGUF)" +# --- stage 4: GGUF (local engine only) ------------------------------------------ +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + GGUF_NAME="$(basename "$GGUF_URL")" + GGUF="$MODELS/$GGUF_NAME" + sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; } + if ! sha_ok; then + echo "== downloading GGUF ($GGUF_NAME) into $MODELS" + rm -f "$GGUF" "$GGUF.tmp" + curl -fL --retry 3 -o "$GGUF.tmp" "$GGUF_URL" + mv "$GGUF.tmp" "$GGUF" + fi + sha_ok || { echo "GGUF sha256 mismatch: expected $GGUF_SHA256" >&2; exit 1; } + echo "== GGUF verified ($GGUF)" -# --- stage 5: HF tokenizer cache -------------------------------------------------- -export HF_HOME="$HF_CACHE" -mkdir -p "$HF_CACHE" -echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV into $HF_CACHE" -"$PYTHON" - "$HF_SOURCE" "$HF_REV" <<'PY' + # --- stage 5: HF tokenizer cache --- + export HF_HOME="$HF_CACHE" + mkdir -p "$HF_CACHE" + echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV into $HF_CACHE" + "$PYTHON" - "$HF_SOURCE" "$HF_REV" <<'PY' import sys from transformers import AutoTokenizer AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2]) PY +else + echo "== remote decision engine: no GGUF/tokenizer to fetch" +fi -# --- stage 5b: optional voice models (--voice) ---------------------------------- +# --- stage 5b: optional voice models ------------------------------------------- # Downloads the openWakeWord models (into the venv) + the Piper voice (into # .runtime/voice/tts) and warms the faster-whisper model into the HF cache. -# Reads gateway.voice from config.json -# so the models match the configured names. Best-effort: a download failure -# warns (the gateway reports the missing model at startup) rather than aborting. -if [[ "$VOICE" = 1 ]]; then +# Reads gateway.voice from config.json so the models match the configured names. +# Best-effort: a download failure warns (the gateway reports the missing model at +# startup) rather than aborting. +if [[ "$PLAN_VOICE" = 1 ]]; then echo "== downloading voice models (openWakeWord + Piper + faster-whisper)" HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" --config "$MERGED_CONFIG" \ || echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2 fi -# --- 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" +# --- stage 6: simplex-chat daemon binary (only when needed) -------------------- +if [[ "$PLAN_SIMPLEX_BIN" = 1 ]]; then + 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)" +else + echo "== SimpleX not selected; skipping the simplex-chat binary" fi -simplex_ok || { echo "simplex-chat sha256 mismatch: expected $SIMPLEX_SHA256" >&2; exit 1; } -echo "== simplex-chat verified ($SIMPLEX_BIN)" -# config.json is USER config: seeded above if absent, read for per-machine values, -# and never written by this script. Edit config.json to change endpoints, models, -# ports, the dashboard bind, or the gateway allowlist. - -# --- stage 8: systemd user units ----------------------------------------------------- +# --- stage 8: systemd user units (only the ones the answers need) -------------- render_unit() { local src="$1" dst="$2" sed -e "s|@REPO@|$REPO_ROOT|g" \ -e "s|@PORT@|$SIMPLEX_PORT|g" \ -e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" \ -e "s|@FORWARD_PORT@|$SIMPLEX_FORWARD_PORT|g" \ - -e "s|@FORWARD_DISPLAY@|$SIMPLEX_FORWARD_DISPLAY|g" "$src" > "$dst" + -e "s|@FORWARD_DISPLAY@|$SIMPLEX_FORWARD_DISPLAY|g" \ + -e "s|@PLATFORMS@|$PLAN_GATEWAY_PLATFORMS|g" "$src" > "$dst" } -echo "== rendering systemd user units into $UNITS" + +WANTED_UNITS=() +[[ "$PLAN_GATEWAY_SVC" = 1 ]] && WANTED_UNITS+=(semif-gateway.service) +[[ ",$PLAN_GATEWAYS," == *",simplex,"* ]] && WANTED_UNITS+=(semif-simplex.service) +[[ "$PLAN_SIMPLEX_FWD" = 1 ]] && WANTED_UNITS+=(semif-simplex-forward.service) +[[ "$PLAN_BRIDGE_SVC" = 1 ]] && WANTED_UNITS+=(semif-bridge.service) +ALL_UNITS=(semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service) + +unit_wanted() { local u="$1"; for w in "${WANTED_UNITS[@]:-}"; do [[ "$w" = "$u" ]] && return 0; done; return 1; } + +echo "== rendering systemd user units into $UNITS (wanted: ${WANTED_UNITS[*]:-none})" UNIT_CHANGED=0 ACTIVE_BEFORE="" -for unit in semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service; do +for unit in "${ALL_UNITS[@]}"; do + if ! unit_wanted "$unit"; then + # A reconfigure can drop a component; retire its unit if it was installed. + if [[ -L "$USER_UNITS/$unit" || -f "$UNITS/$unit" ]]; then + if command -v systemctl >/dev/null 2>&1; then + export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" + systemctl --user disable --now "$unit" 2>/dev/null || true + fi + rm -f "$USER_UNITS/$unit" + echo " $unit: retired (no longer selected)" + fi + continue + fi tmp="$UNITS/$unit.new" render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$tmp" if [[ ! -f "$UNITS/$unit" ]] || ! cmp -s "$tmp" "$UNITS/$unit"; then @@ -553,12 +683,12 @@ for unit in semif-simplex.service semif-simplex-forward.service semif-gateway.se fi done -if command -v systemctl >/dev/null 2>&1; then +if command -v systemctl >/dev/null 2>&1 && [[ ${#WANTED_UNITS[@]} -gt 0 ]]; 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-simplex-forward.service semif-gateway.service semif-bridge.service 2>/dev/null \ - && echo "== enabled semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service" \ - || echo "WARN: could not enable user services (run: systemctl --user enable --now semif-simplex semif-simplex-forward semif-gateway semif-bridge)" >&2 + systemctl --user enable --now "${WANTED_UNITS[@]}" 2>/dev/null \ + && echo "== enabled ${WANTED_UNITS[*]}" \ + || echo "WARN: could not enable user services (run: systemctl --user enable --now ${WANTED_UNITS[*]})" >&2 # Apply a changed unit to services that were already running (enable --now # leaves active units untouched). A daemon restart is safe: the simplex # profile persists and the gateway reconnects. @@ -574,7 +704,7 @@ if command -v systemctl >/dev/null 2>&1; then fi fi -# --- stage 8b: SimpleX bot contact address ------------------------------------------- +# --- stage 8b: SimpleX bot contact address ------------------------------------- SIMPLEX_ADDRESS="" if command -v systemctl >/dev/null 2>&1; then export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" @@ -593,7 +723,7 @@ if command -v systemctl >/dev/null 2>&1; then fi fi -# --- stage 8c: forwarding bridge contact address -------------------------------------- +# --- stage 8c: forwarding bridge contact address ------------------------------- # The forwarding bridge owns a second daemon/profile; its own contact link is the # one `simplex.connect_link` shows. Print it too so the user can share it. BRIDGE_FORWARD_WS="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true @@ -619,30 +749,43 @@ if [[ -n "$BRIDGE_FORWARD_WS" ]] && command -v systemctl >/dev/null 2>&1; then fi fi -# --- stage 9: optional data copy ----------------------------------------------------- +# --- 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 + pull the local self-assessment model ------------------------- +# --- stage 10: verify imports + the configured endpoints ------------------------ echo "== verifying imports" -"$PYTHON" -c "import semif_phase1, semif_agent; print('engine + agent import OK')" +if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then + "$PYTHON" -c "import semif_phase1, semif_agent; print('engine + agent import OK')" +else + "$PYTHON" -c "import semif_agent; print('agent import OK')" +fi -# The small self-assessment model runs on this machine's local ollama; ensure it -# is pulled so assess/fidelity work without a remote dependency. -# With llm.provider == "semif" the loaded decision engine generates the text -# in-process, so no ollama model/endpoint is involved. -if [[ "$LLM_PROVIDER" == "semif" ]]; then +# The decision engine is always real: a remote Winnow server must be reachable at +# runtime (there is no fallback), so surface its address here. +if [[ "$ENGINE_PROVIDER" = "winnow" ]]; then + echo "== decision engine: remote Winnow at ${WINNOW_URL:-?} (model ${WINNOW_MODEL:-?}) — must be reachable at runtime" +fi + +# The `llm` (title/description + gateway cleanup) model. `semif` runs in-process +# on the loaded decision model; a local ollama is pulled; hosted endpoints are +# only reported. Authoring is off when the mode is `deny`. +if [[ "$LLM_PROVIDER" = "semif" ]]; then echo "== llm provider semif: the loaded engine model generates text in-process (no ollama pull/probe)" +elif [[ "$PLAN_AUTHORING" = "deny" ]]; then + echo "== skill authoring is disabled; the llm/codegen endpoints are not required" +elif [[ "$LLM_PROVIDER" = "opencode" ]]; then + echo "== llm: hosted OpenCode Console ($LLM_URL, model ${LLM_MODEL:-?})" elif [[ -z "$LLM_MODEL" ]]; then - echo "WARN: llm.model is not set in config.json — set it (and codegen.model) before starting the agent" >&2 + echo "WARN: llm.model is not set in config.json — authoring needs it" >&2 else echo "== llm ollama ($LLM_API), model $LLM_MODEL" if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then echo "WARN: no local ollama at $LLM_API — install/run ollama and pull $LLM_MODEL" >&2 - echo " (bootstrap installs no ollama; only codegen is remote)" >&2 + echo " (bootstrap installs no ollama; only codegen may be remote)" >&2 else LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)" if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then @@ -670,8 +813,15 @@ else fi fi -# Codegen is the larger model, possibly on a remote host. Warn only — never auto-pull. -if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then +# Codegen writes skill bodies; only needed when authoring is enabled. Warn only — +# never auto-pull. +if [[ "$PLAN_AUTHORING" = "deny" ]]; then + : # authoring disabled; no codegen endpoint required +elif [[ -z "$CODEGEN_MODEL" ]]; then + echo "WARN: new_skill_creation is enabled but codegen.model is unset — authoring will not run" >&2 +elif [[ "$CODEGEN_PROVIDER" = "opencode" ]]; then + echo "== codegen: hosted OpenCode Console ($CODEGEN_URL, model $CODEGEN_MODEL)" +elif [[ -n "$CODEGEN_URL" ]]; then echo "== codegen ollama ($CODEGEN_API)" CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)" if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then @@ -679,26 +829,28 @@ if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then else echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2 fi -else - echo "WARN: codegen.base_url/model is not set in config.json — set it before starting the agent" >&2 fi if command -v systemctl >/dev/null 2>&1; then - echo "== gateway + bridge services" - systemctl --user is-active semif-simplex.service 2>/dev/null | sed 's/^/ semif-simplex: /' || true - systemctl --user is-active semif-gateway.service 2>/dev/null | sed 's/^/ semif-gateway: /' || true - systemctl --user is-active semif-simplex-forward.service 2>/dev/null | sed 's/^/ semif-simplex-forward: /' || true - systemctl --user is-active semif-bridge.service 2>/dev/null | sed 's/^/ semif-bridge: /' || true + echo "== services" + for unit in "${ALL_UNITS[@]}"; do + state="$(systemctl --user is-active "$unit" 2>/dev/null || true)" + [[ -n "$state" ]] && echo " ${unit%.service}: $state" + done fi cat < DecisionEngine: return SemIfEngine(build_engine_config(config, pins)) -def build_codegen_client(config: dict) -> CodegenClient: +def build_codegen_client(config: dict) -> CodegenClient | None: """Build the codegen client from the `codegen` config block. `provider` selects the class (`opencode` -> the Console client, which adds bearer auth and a User-Agent) and the endpoint/auth come from `_provider_endpoint`. Shared by `build_scheduler` and the integration tests so both exercise the configured provider rather than assuming ollama. + + Returns ``None`` when no `codegen.model` is configured: skill authoring is + an opt-in capability, so a host that only runs the shipped packs (the + minimum path) needs no codegen endpoint and the app must not fail without + one. The scheduler guards every authoring path against a missing client. """ codegen_cfg = config.get("codegen", {}) or {} + model = str(codegen_cfg.get("model") or "").strip() + if not model: + return None deg_cfg = codegen_cfg.get("degeneration", {}) or {} provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower() client_cls = ConsoleCodegenClient if provider == "opencode" else CodegenClient @@ -267,7 +276,7 @@ def build_codegen_client(config: dict) -> CodegenClient: ) return client_cls( base_url=endpoint["base_url"], - model=_required_model(codegen_cfg, "codegen"), + model=model, timeout=float(codegen_cfg.get("timeout", 1200.0)), stream=bool(codegen_cfg.get("stream", False)), idle_warn=float(codegen_cfg.get("idle_warn", 60.0)), @@ -293,7 +302,7 @@ def build_codegen_client(config: dict) -> CodegenClient: ) -def build_llm_client(config: dict, engine): +def build_llm_client(config: dict, engine) -> LLMClient | None: """Build the `llm` title/description client from the `llm` config block. `provider` selects the backend: `"semif"` drives the already-loaded SemIf @@ -301,6 +310,9 @@ def build_llm_client(config: dict, engine): needed), `"opencode"` the hosted Console client, and anything else the default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests so both exercise the configured provider rather than assuming ollama. + + Returns ``None`` when a non-`semif` provider has no `model`: the `llm` client + is only needed for skill authoring and gateway result cleanup, both optional. """ llm_cfg = config.get("llm", {}) or {} provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower() @@ -311,11 +323,14 @@ def build_llm_client(config: dict, engine): temperature=float(semif_cfg.get("temperature", 0.0)), max_tokens=int(semif_cfg.get("max_tokens", 256)), ) + model = str(llm_cfg.get("model") or "").strip() + if not model: + return None llm_cls = ConsoleLLMClient if provider == "opencode" else LLMClient endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1") return llm_cls( base_url=endpoint["base_url"], - model=_required_model(llm_cfg, "llm"), + model=model, timeout=float(llm_cfg.get("timeout", 600.0)), stream=bool(llm_cfg.get("stream", False)), idle_warn=float(llm_cfg.get("idle_warn", 30.0)), @@ -347,6 +362,21 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: codegen_cfg = config.get("codegen", {}) deg_cfg = codegen_cfg.get("degeneration", {}) or {} codegen = build_codegen_client(config) + if str(config.get("new_skill_creation", "deny") or "deny").lower() != "deny": + if codegen is None: + print( + "WARN: new_skill_creation is enabled but codegen.model is not " + "set — skill authoring will not run. Set codegen.model (and " + "base_url) to enable it.", + file=sys.stderr, + ) + if llm is None: + print( + "WARN: new_skill_creation is enabled but llm.model is not set — " + "skill authoring will not run. Set llm.model (and base_url), or " + "llm.provider 'semif' to use the decision model.", + file=sys.stderr, + ) def make_degeneration_check(run_id: str): """2-option SemIf decision (continue/stop) that aborts a degenerating @@ -1056,10 +1086,42 @@ def config_init(path: str = "config.json") -> int: return 0 +def _setup_command(args) -> int: + """Run the first-run interview (or emit the install plan) — see `setup.py`.""" + config_path = Path(args.path) + if not config_path.is_absolute(): + config_path = REPO_ROOT / config_path + packs = load_packs({"skill_packs": _anchor_pack_roots({})}) + return run_bootstrap_setup( + root=config_path.parent, + path=config_path, + packs=packs, + interview=args.interview, + yes=args.yes, + answers_file=args.answers, + plan_only=args.plan_only, + plan_out=args.plan_out, + force=args.force, + ) + + +def _load_config_tolerant(path: str) -> dict: + """Load the config, or ``{}`` when it is missing/invalid. + + Used for parser defaults (dashboard bind) before the subcommand is known. + Runtime commands still require a real config: `main` re-loads it fatally + after the config-independent subcommands return. + """ + try: + return load_config(path) + except SystemExit: + return {} + + def main(argv: list[str] | None = None) -> int: argv = list(argv) if argv is not None else list(sys.argv[1:]) config_path = _extract_config_path(argv) - config = load_config(config_path) + defaults = _load_config_tolerant(config_path) parser = argparse.ArgumentParser(prog="semif-agent") parser.add_argument("--config", default="config.json") sub = parser.add_subparsers(dest="command") @@ -1086,15 +1148,64 @@ def main(argv: list[str] | None = None) -> int: ) ci_p.add_argument("--path", default="config.json", help="config index path to seed") + setup_p = sub.add_parser( + "setup", + help="first-run interview: generate config/ from your answers", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "answers JSON fields (all optional; --answers FILE):\n" + " engine_provider (semif|winnow), winnow_base_url, winnow_model,\n" + " winnow_api_key\n" + " new_skill_creation (deny|ask|allow)\n" + " llm_provider (semif|ollama|opencode|openai), llm_base_url,\n" + " llm_model, llm_api_key\n" + " codegen_provider, codegen_base_url, codegen_model, codegen_api_key\n" + " packs (list of: essentials, simplex, browser, nextcloud, outlook)\n" + " gateways (list of: simplex, lxmf, voice), timezone\n" + " nextcloud_url, nextcloud_username, nextcloud_app_password,\n" + " outlook_client_id" + ), + ) + setup_p.add_argument("--path", default="config.json", help="config index path to seed") + setup_p.add_argument( + "--interview", action="store_true", help="ask the setup questions interactively" + ) + setup_p.add_argument( + "--yes", + action="store_true", + help="non-interactive: take the minimum working defaults", + ) + setup_p.add_argument( + "--answers", default=None, metavar="FILE", help="JSON answers file (non-interactive)" + ) + setup_p.add_argument( + "--plan-out", + default=None, + metavar="PATH", + help="write the install plan JSON to PATH (for scripts/bootstrap.sh)", + ) + setup_p.add_argument( + "--plan-only", + action="store_true", + help="read the existing config and emit the plan; write nothing", + ) + setup_p.add_argument( + "--force", action="store_true", help="overwrite an existing config" + ) + relabel_p = sub.add_parser("relabel", help="human override of a decision label") relabel_p.add_argument("id") relabel_p.add_argument("outcome") dash_p = sub.add_parser("dashboard", help="run the local browser dashboard") - dash_p.add_argument("--port", type=int, default=int(config.get("dashboard", {}).get("port", 8765))) + dash_p.add_argument( + "--port", + type=int, + default=int(defaults.get("dashboard", {}).get("port", 8765)), + ) dash_p.add_argument( "--host", - default=str(config.get("dashboard", {}).get("host", "127.0.0.1")), + default=str(defaults.get("dashboard", {}).get("host", "127.0.0.1")), help="bind address (0.0.0.0 to expose on the LAN)", ) dash_p.add_argument( @@ -1130,7 +1241,11 @@ def main(argv: list[str] | None = None) -> int: return check_config(config_path, write_example=args.write_example) if args.command == "config-init": return config_init(args.path) + if args.command == "setup": + return _setup_command(args) + # Runtime commands need a real config; this is fatal when it is missing. + config = defaults or load_config(config_path) scheduler, config = build_scheduler(config) if args.command == "run": diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index ab1e327..ee1fc5e 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -833,6 +833,8 @@ class Scheduler: inside it and hands off to the codegen body worker. On failure the request is not re-dispatched and the user is told. """ + if self.llm is None: + return self._authoring_unavailable(request, None) self._queue_draft(request, None, "category") return DispatchResult( kind="create_category", @@ -855,6 +857,8 @@ class Scheduler: """ if self._category_locked(category): return self._blocked_create(request, category) + if self.llm is None: + return self._authoring_unavailable(request, category) pending = request.meta.get("awaiting_skill_body") if pending is not None: category_pending, name = pending @@ -875,6 +879,27 @@ class Scheduler: ), ) + def _authoring_unavailable( + self, request: Request, category: str | None + ) -> DispatchResult: + """The create door is open but no `llm` model is configured. + + A deterministic configuration fact (traced), surfaced as a plain failure + so the user is not left waiting on a body that will never land. The + setup wizard prevents this by requiring an `llm` endpoint when authoring + is enabled, but a hand-edited config can still reach it. + """ + with self._lock: + self.trace.append( + "authoring_unavailable", request.id, category=category + ) + message = ( + "I can't write a new skill on this host — skill authoring is not " + "configured (no llm endpoint)." + ) + self._notify_outbox(request.id, message) + return DispatchResult(kind="error", summary=message) + # ---- new-skill creation modes (deterministic per-category create door) ---- def _category_mode(self, category: str) -> str: diff --git a/semif_agent/setup.py b/semif_agent/setup.py new file mode 100644 index 0000000..a5ea8b0 --- /dev/null +++ b/semif_agent/setup.py @@ -0,0 +1,712 @@ +"""First-run setup: the bootstrap interview, config generation, and the plan. + +``scripts/bootstrap.sh`` clones the packs, then calls this module (via +``python -m semif_agent.cli setup``) to ask the few questions that make a fresh +machine work — which decision engine, whether the agent may author new skills, +which capability packs, and which gateways — and to write the split ``config/`` +plus ``secrets.json`` from the answers. It also emits a machine-readable *plan* +so bootstrap installs **only what the answers require** (no simplex-chat binary +for a REPL-only host, no Playwright for a host that did not pick the browser +pack, no voice stack without the voice gateway). + +The two ends of the spectrum are both reachable here: + +* **Minimum** — the local SemIf 4B decision engine + the ``essentials`` pack + (canned replies, time/timers, calculator). No account, no network, no gateway. +* **Maximum** — every pack (SimpleX, browser, Nextcloud, Outlook), a remote + Winnow decision engine, remote ``llm``/``codegen`` endpoints, and all + gateways (SimpleX, LXMF, voice). + +The module is pure stdlib and takes injectable ``input_fn``/``output`` so the +interview is unit-testable without a TTY. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Iterable, Sequence + +from .config import ( + DEFAULT_SECRETS_FILE, + default_config, + load_secrets, + write_split_config, +) +from .packs import SkillPack, pack_enabled + +#: ``llm``/``codegen`` providers the wizard can emit. +PROVIDERS = ("semif", "ollama", "opencode", "openai") +#: ``engine`` providers. +ENGINE_PROVIDERS = ("semif", "winnow") +#: New-skill creation modes. +AUTHORING_MODES = ("deny", "ask", "allow") + +#: Capability packs the wizard offers (essentials is always included). +PACK_CHOICES: tuple[tuple[str, str], ...] = ( + ("simplex", "SimpleX messaging (read/send messages, show your contact link)"), + ("browser", "Browser automation (Playwright: open/read/click/fill a site)"), + ("nextcloud", "Nextcloud (calendar, tasks, files, contacts, notes)"), + ("outlook", "Outlook / Microsoft 365 (mail, calendar, To Do, OneDrive)"), +) +#: Gateway platforms the wizard offers. +GATEWAY_CHOICES: tuple[tuple[str, str], ...] = ( + ("simplex", "SimpleX command gateway (DM the bot to run tasks)"), + ("lxmf", "LXMF / Reticulum command gateway (in-process, no daemon)"), + ("voice", "Voice gateway (wake word + speech, needs a microphone)"), +) + +#: The always-on pack: the built-in local utilities. +BASE_PACK = "essentials" + + +@dataclass +class Answers: + """The wizard's answers, and the source of truth for the generated config.""" + + # Decision engine. + engine_provider: str = "semif" # semif | winnow + winnow_base_url: str = "" + winnow_model: str = "" + winnow_api_key: str = "" + + # New-skill authoring: deny | ask | allow. + new_skill_creation: str = "deny" + + # The small `llm` (title/description) provider. `semif` reuses the loaded + # decision model in-process, so the minimum path needs no endpoint at all. + llm_provider: str = "semif" + llm_base_url: str = "" + llm_model: str = "" + llm_api_key: str = "" + + # The `codegen` (skill-body) provider. Empty model == not configured; the + # agent then has no authoring path (which is the minimum path's intent). + codegen_provider: str = "ollama" + codegen_base_url: str = "" + codegen_model: str = "" + codegen_api_key: str = "" + + # Capability packs to enable (essentials is always included). + packs: list[str] = field(default_factory=lambda: [BASE_PACK]) + + # Gateway platforms to enable. + gateways: list[str] = field(default_factory=list) + + # IANA timezone; empty uses the host zone. + timezone: str = "" + + # Nextcloud connection (optional; collected only when the pack is picked). + nextcloud_url: str = "" + nextcloud_username: str = "" + nextcloud_app_password: str = "" + + # Outlook public-client id (not a secret). + outlook_client_id: str = "" + + def __post_init__(self) -> None: + self.engine_provider = _norm(self.engine_provider, ENGINE_PROVIDERS, "semif") + self.new_skill_creation = _norm( + self.new_skill_creation, AUTHORING_MODES, "deny" + ) + self.llm_provider = _norm(self.llm_provider, PROVIDERS, "semif") + self.codegen_provider = _norm(self.codegen_provider, PROVIDERS, "ollama") + self.packs = _clean_list(self.packs) + self.gateways = _clean_list(self.gateways) + self.normalize() + + def normalize(self) -> "Answers": + """Ensure the always-on base pack is present (idempotent).""" + if BASE_PACK not in self.packs: + self.packs.insert(0, BASE_PACK) + return self + + @classmethod + def minimal(cls) -> "Answers": + """The minimum working path: local engine, no authoring, essentials only.""" + return cls() + + @classmethod + def from_dict(cls, data: dict) -> "Answers": + """Build answers from a JSON object (an ``--answers FILE`` payload).""" + fields = {f for f in cls.__dataclass_fields__} # type: ignore[attr-defined] + return cls(**{k: v for k, v in (data or {}).items() if k in fields}) + + def to_dict(self) -> dict: + return { + f: getattr(self, f) for f in self.__dataclass_fields__ # type: ignore[attr-defined] + } + + +def _norm(value: str, allowed: Sequence[str], default: str) -> str: + value = str(value or "").strip().lower() + return value if value in allowed else default + + +def _clean_list(values: Iterable[str] | None) -> list[str]: + out: list[str] = [] + for value in values or []: + token = str(value).strip().lower() + if token and token not in out: + out.append(token) + return out + + +# --------------------------------------------------------------------------- # +# Interview +# --------------------------------------------------------------------------- # + + +def _ask_text( + input_fn: Callable[[str], str], + output: Callable[[str], None], + prompt: str, + default: str = "", + *, + secret: bool = False, +) -> str: + suffix = f" [{default}]" if default else "" + try: + raw = input_fn(f"{prompt}{suffix}: ").strip() + except EOFError: + raw = "" + return raw or default + + +def _ask_choice( + input_fn: Callable[[str], str], + output: Callable[[str], None], + prompt: str, + options: Sequence[tuple[str, str]], + default_index: int = 1, +) -> str: + for index, (_, label) in enumerate(options, 1): + marker = " (default)" if index == default_index else "" + output(f" {index}) {label}{marker}") + while True: + raw = _ask_text(input_fn, output, prompt, str(default_index)) + if raw.isdigit() and 1 <= int(raw) <= len(options): + return options[int(raw) - 1][0] + output(f" please enter a number between 1 and {len(options)}") + + +def _ask_multi( + input_fn: Callable[[str], str], + output: Callable[[str], None], + prompt: str, + options: Sequence[tuple[str, str]], + default: Iterable[str] = (), +) -> list[str]: + letters = {chr(ord("a") + i): key for i, (key, _) in enumerate(options)} + for index, (_, label) in enumerate(options): + output(f" {chr(ord('a') + index)}) {label}") + default = list(default) + default_str = ",".join( + chr(ord("a") + i) for i, (key, _) in enumerate(options) if key in default + ) + raw = _ask_text(input_fn, output, prompt, default_str) + if not raw: + return [] + picked: list[str] = [] + for token in raw.replace(" ", "").split(","): + key = letters.get(token.lower()) + if key and key not in picked: + picked.append(key) + return picked + + +def _ask_provider( + input_fn: Callable[[str], str], + output: Callable[[str], None], + label: str, + default: str, + *, + allow_semif: bool = True, +) -> str: + options: list[tuple[str, str]] = [] + if allow_semif: + options.append(("semif", "the loaded decision engine (in-process, no endpoint)")) + options += [ + ("ollama", "a local ollama endpoint"), + ("opencode", "the hosted OpenCode Console"), + ("openai", "another OpenAI-compatible endpoint"), + ] + default_index = next( + (i for i, (key, _) in enumerate(options, 1) if key == default), 1 + ) + output(f" Which endpoint should {label} use?") + return _ask_choice(input_fn, output, f"{label} provider", options, default_index) + + +def _collect_llm( + input_fn: Callable[[str], str], + output: Callable[[str], None], + answers: Answers, + *, + label: str, + allow_semif: bool, +) -> None: + """Ask for an OpenAI-compatible endpoint and record it on `answers`.""" + provider = _ask_provider( + input_fn, output, label, answers.llm_provider, allow_semif=allow_semif + ) + setattr(answers, f"{label}_provider", provider) + if provider == "semif": + setattr(answers, f"{label}_model", "") + setattr(answers, f"{label}_base_url", "") + setattr(answers, f"{label}_api_key", "") + return + if provider == "opencode": + base_default = "https://opencode.ai/inference/openai/v1" + elif provider == "ollama": + base_default = "http://localhost:11434/v1" + else: + base_default = "" + setattr( + answers, + f"{label}_base_url", + _ask_text(input_fn, output, f"{label} base URL", base_default), + ) + model = "" + while not model: + model = _ask_text(input_fn, output, f"{label} model (required)") + if not model: + output(f" {label}.model is required; the agent fails fast without it.") + setattr(answers, f"{label}_model", model) + key = _ask_text( + input_fn, output, f"{label} API key (blank for none)", "", secret=True + ) + setattr(answers, f"{label}_api_key", key) + + +def run_interview( + *, + input_fn: Callable[[str], str] = input, + output: Callable[[str], None] = print, + interactive: bool = True, + prefill: Answers | None = None, +) -> Answers: + """Run the setup interview and return the answers. + + ``interactive=False`` returns the prefill (or the minimum path) without + prompting — the ``--yes`` behaviour. + """ + answers = prefill or Answers.minimal() + if not interactive: + return answers + + output("") + output("== SemIf agent setup ==") + output( + "This writes this machine's config. Press Enter to accept the default\n" + "shown in [brackets]. Nothing is installed that your answers don't need." + ) + + # 1. Decision engine. + output("") + output("Decision engine") + output( + " The decision engine routes every request. It runs locally on the\n" + " pinned SemIf 4B GGUF by default (no network), or against a remote\n" + " Winnow /v1/systemone server." + ) + answers.engine_provider = _ask_choice( + input_fn, + output, + "engine", + [ + ("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"), + ("winnow", "remote Winnow decision server"), + ], + 1, + ) + if answers.engine_provider == "winnow": + answers.winnow_base_url = _ask_text( + input_fn, output, " winnow base URL", "http://127.0.0.1:8091" + ) + model = "" + while not model: + model = _ask_text(input_fn, output, " winnow model (required)") + if not model: + output(" engine.winnow.model is required.") + answers.winnow_model = model + answers.winnow_api_key = _ask_text( + input_fn, output, " winnow API key (blank for none)", "", secret=True + ) + + # 2. Skill authoring. + output("") + output("Skill authoring") + output( + " May the agent write brand-new skills when no shipped skill fits?\n" + " This needs two endpoints: a small `llm` to name the skill and a\n" + " code-capable `codegen` to write its body." + ) + mode = _ask_choice( + input_fn, + output, + "authoring", + [ + ("deny", "no — use the shipped skills only (recommended)"), + ("ask", "ask me before each new skill"), + ("allow", "yes — write new skills automatically"), + ], + 1, + ) + answers.new_skill_creation = mode + if mode != "deny": + output("") + _collect_llm(input_fn, output, answers, label="llm", allow_semif=True) + output("") + _collect_llm(input_fn, output, answers, label="codegen", allow_semif=False) + + # 3. Capability packs. + output("") + output("Capabilities (skill packs)") + output( + " Essentials (time, timers, calculator) is always included. Enable more\n" + " packs by their letter; separate several with commas (e.g. a,c)." + ) + answers.packs = _ask_multi( + input_fn, + output, + "packs (blank for essentials only)", + PACK_CHOICES, + default=[p for p in answers.packs if p != BASE_PACK], + ) + + # 4. Pack-specific connection details. + if "nextcloud" in answers.packs: + output("") + output("Nextcloud connection (blank to fill in later)") + answers.nextcloud_url = _ask_text( + input_fn, output, " Nextcloud URL", answers.nextcloud_url + ) + answers.nextcloud_username = _ask_text( + input_fn, output, " Nextcloud username", answers.nextcloud_username + ) + answers.nextcloud_app_password = _ask_text( + input_fn, + output, + " Nextcloud app password", + answers.nextcloud_app_password, + secret=True, + ) + if "outlook" in answers.packs: + output("") + output("Outlook / Microsoft 365") + output( + " Register an Entra ID public-client app and paste its application\n" + " (client) id; run packs/outlook/scripts/outlook-auth.py once after." + ) + answers.outlook_client_id = _ask_text( + input_fn, output, " Outlook client id", answers.outlook_client_id + ) + + # 5. Gateways. + output("") + output("Gateways (how you talk to the agent)") + output( + " You can always use the terminal REPL and dashboard. Optionally reach\n" + " the agent over a messenger or the local microphone too." + ) + answers.gateways = _ask_multi( + input_fn, + output, + "gateways (blank for none)", + GATEWAY_CHOICES, + default=answers.gateways, + ) + + # 6. Timezone. + output("") + answers.timezone = _ask_text( + input_fn, + output, + "Timezone (IANA name, e.g. America/Chicago; blank for the host zone)", + answers.timezone, + ) + return answers.normalize() + + +# --------------------------------------------------------------------------- # +# Config generation +# --------------------------------------------------------------------------- # + + +def _set_secret_or_literal(block: dict, key: str, value: str, secret_key: str) -> None: + """Write ``!secret `` when a value is present, else an empty literal.""" + block[key] = f"!secret {secret_key}" if value else "" + + +def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict: + """The merged config dict for these answers (defaults + overrides).""" + answers.normalize() + config = default_config(packs) + + # Decision engine. + engine = config.setdefault("engine", {}) + engine["provider"] = answers.engine_provider + if answers.engine_provider == "winnow": + winnow = engine.setdefault("winnow", {}) + if answers.winnow_base_url: + winnow["base_url"] = answers.winnow_base_url + winnow["model"] = answers.winnow_model + _set_secret_or_literal( + winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key" + ) + + # Authoring mode. + config["new_skill_creation"] = answers.new_skill_creation + + # `llm`: semif reuses the loaded engine; anything else needs an endpoint. + llm = config.setdefault("llm", {}) + llm["provider"] = answers.llm_provider + if answers.llm_provider == "semif": + llm["model"] = "" + llm["api_key"] = "" + else: + if answers.llm_base_url: + llm["base_url"] = answers.llm_base_url + llm["model"] = answers.llm_model + _set_secret_or_literal(llm, "api_key", answers.llm_api_key, "llm_api_key") + + # `codegen`: an empty model means "not configured" (no authoring path). + codegen = config.setdefault("codegen", {}) + if answers.codegen_model: + codegen["provider"] = answers.codegen_provider + if answers.codegen_base_url: + codegen["base_url"] = answers.codegen_base_url + codegen["model"] = answers.codegen_model + _set_secret_or_literal( + codegen, "api_key", answers.codegen_api_key, "codegen_api_key" + ) + else: + codegen["model"] = "" + codegen["api_key"] = "" + + if answers.timezone: + config["timezone"] = answers.timezone + + # Packs: enable exactly the chosen ones (essentials always on). + for pack in packs: + enabled = pack.name in answers.packs + if pack.bridges: + config.setdefault("bridges", {}).setdefault(pack.bridges[0], {})[ + "enabled" + ] = enabled + else: + config.setdefault("packs", {}).setdefault(pack.name, {})["enabled"] = enabled + + # The shared LLM bridge is only useful when a bridge-owning pack is on. + bridge_packs = [p for p in packs if p.bridges and p.name in answers.packs] + config.setdefault("bridges", {}).setdefault("llm", {})["enabled"] = bool( + bridge_packs + ) + + # Nextcloud / Outlook connection details. + if "nextcloud" in answers.packs: + nc = config["bridges"].setdefault("nextcloud", {}) + if answers.nextcloud_url: + nc["url"] = answers.nextcloud_url + if answers.nextcloud_username: + nc["username"] = answers.nextcloud_username + _set_secret_or_literal( + nc, "app_password", answers.nextcloud_app_password, "nextcloud_app_password" + ) + if "outlook" in answers.packs: + config["bridges"].setdefault("outlook", {})["client_id"] = ( + answers.outlook_client_id + ) + + # Gateways. + gateway = config.setdefault("gateway", {}) + for platform in ("simplex", "lxmf", "voice"): + gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways + gateway.setdefault("humanize", {})["enabled"] = bool(answers.gateways) + + return config + + +def build_secrets(answers: Answers) -> dict: + """The secrets to store for these answers (only keys that were provided).""" + secrets: dict[str, str] = {} + if answers.engine_provider == "winnow" and answers.winnow_api_key: + secrets["engine_winnow_api_key"] = answers.winnow_api_key + if answers.llm_provider != "semif" and answers.llm_api_key: + secrets["llm_api_key"] = answers.llm_api_key + if answers.codegen_api_key: + secrets["codegen_api_key"] = answers.codegen_api_key + if "nextcloud" in answers.packs and answers.nextcloud_app_password: + secrets["nextcloud_app_password"] = answers.nextcloud_app_password + return secrets + + +def write_secrets(root: str | Path, secrets: dict, *, merge: bool = True) -> Path: + """Write ``secrets.json`` under `root`, merging with any existing entries.""" + path = Path(root) / DEFAULT_SECRETS_FILE + current = load_secrets(path) if merge else {} + current.update({k: v for k, v in secrets.items() if v}) + path.write_text(json.dumps(current, indent=2) + "\n") + return path + + +# --------------------------------------------------------------------------- # +# Install plan +# --------------------------------------------------------------------------- # + + +def build_plan(answers: Answers, packs: Sequence[SkillPack]) -> dict: + """What bootstrap should install for these answers. + + Drives the conditional stages so a REPL-only host never downloads the + simplex-chat binary, Playwright, or the voice stack. + """ + answers.normalize() + bridge_packs = [ + p.name for p in packs if p.bridges and p.name in answers.packs + ] + daemon_gateways = [g for g in answers.gateways if g != "voice"] + return { + "engine_provider": answers.engine_provider, + "authoring": answers.new_skill_creation, + "packs": list(answers.packs), + "bridge_packs": bridge_packs, + "gateways": list(answers.gateways), + # Platforms the systemd gateway unit runs (voice is foreground-only). + "gateway_platforms": daemon_gateways, + "install_engine": answers.engine_provider == "semif", + "install_bridge_service": bool(bridge_packs), + "install_gateway_service": bool(daemon_gateways), + "install_simplex_binary": ("simplex" in answers.packs) + or ("simplex" in answers.gateways), + "install_simplex_forward": "simplex" in answers.packs, + "install_browser": "browser" in answers.packs, + "install_voice": "voice" in answers.gateways, + } + + +def plan_from_config(config: dict, packs: Sequence[SkillPack]) -> dict: + """Derive the same plan from an already-merged config (a rerun).""" + gateways = [ + platform + for platform in ("simplex", "lxmf", "voice") + if ((config.get("gateway", {}) or {}).get(platform, {}) or {}).get("enabled") + ] + enabled = [p.name for p in packs if pack_enabled(config, p)] + bridge_packs = [p.name for p in packs if p.bridges and p.name in enabled] + daemon_gateways = [g for g in gateways if g != "voice"] + engine_provider = str( + (config.get("engine", {}) or {}).get("provider", "semif") or "semif" + ).lower() + return { + "engine_provider": engine_provider, + "authoring": str(config.get("new_skill_creation", "deny") or "deny"), + "packs": enabled, + "bridge_packs": bridge_packs, + "gateways": gateways, + "gateway_platforms": daemon_gateways, + "install_engine": engine_provider == "semif", + "install_bridge_service": bool(bridge_packs), + "install_gateway_service": bool(daemon_gateways), + "install_simplex_binary": ("simplex" in enabled) or ("simplex" in gateways), + "install_simplex_forward": "simplex" in enabled, + "install_browser": "browser" in enabled, + "install_voice": "voice" in gateways, + } + + +# --------------------------------------------------------------------------- # +# Top-level entry used by the CLI +# --------------------------------------------------------------------------- # + + +def run_setup( + *, + root: str | Path, + path: str | Path, + packs: Sequence[SkillPack], + interview: bool = False, + yes: bool = False, + answers_file: str | None = None, + plan_only: bool = False, + plan_out: str | None = None, + force: bool = False, + input_fn: Callable[[str], str] = input, + output: Callable[[str], None] = print, +) -> int: + """Seed (or re-seed) the split config from an interview, or emit a plan. + + Returns a process exit code. In ``plan_only`` mode it reads the existing + config and writes the derived plan without touching anything. + """ + config_path = Path(path) + + if plan_only: + from .config import load_config_file + + try: + raw = load_config_file(config_path) + except Exception as exc: # noqa: BLE001 - surfaced as a clean error + output(f"could not read {config_path}: {exc}") + return 1 + plan = plan_from_config(raw, packs) + _emit_plan(plan, plan_out, output) + return 0 + + if config_path.exists() and not force: + output(f"{config_path} already exists; leaving it alone (use --force)") + return 1 + + prefill = None + if answers_file: + try: + prefill = Answers.from_dict(json.loads(Path(answers_file).read_text())) + except (OSError, ValueError) as exc: + output(f"could not read answers file {answers_file}: {exc}") + return 1 + + if interview and not yes: + answers = run_interview( + input_fn=input_fn, output=output, interactive=True, prefill=prefill + ) + else: + answers = prefill or Answers.minimal() + + config = build_config(answers, packs) + written = write_split_config(Path(root), config, packs) + secrets_path = write_secrets(Path(root), build_secrets(answers), merge=True) + plan = build_plan(answers, packs) + + output("") + output("== config written") + output(f" {len(written)} files under {Path(root) / 'config'}") + output(f" {secrets_path.name} (credentials)") + _print_summary(answers, output) + _emit_plan(plan, plan_out, output) + return 0 + + +def _print_summary(answers: Answers, output: Callable[[str], None]) -> None: + output( + " engine: " + + ( + "local SemIf 4B" + if answers.engine_provider == "semif" + else f"remote Winnow ({answers.winnow_model or '?'})" + ) + ) + output(f" authoring: {answers.new_skill_creation}") + output(f" packs: {', '.join(answers.packs)}") + output(f" gateways: {', '.join(answers.gateways) or 'none (REPL + dashboard)'}") + if answers.timezone: + output(f" timezone: {answers.timezone}") + + +def _emit_plan(plan: dict, plan_out: str | None, output: Callable[[str], None]) -> None: + if plan_out: + Path(plan_out).parent.mkdir(parents=True, exist_ok=True) + Path(plan_out).write_text(json.dumps(plan, indent=2) + "\n") + else: + output("PLAN " + json.dumps(plan)) diff --git a/tests/test_setup.py b/tests/test_setup.py new file mode 100644 index 0000000..b84e9fb --- /dev/null +++ b/tests/test_setup.py @@ -0,0 +1,311 @@ +"""The first-run setup interview: answers -> split config, secrets, install plan. + +These exercise the two ends of the spectrum the bootstrap must support: + +* **minimum** — local SemIf 4B + the ``essentials`` pack, no gateway, no + authoring, no ``llm``/``codegen`` endpoint, nothing heavy to install; +* **maximum** — every pack, all gateways, a remote Winnow engine, remote + ``llm``/``codegen`` endpoints, and every conditional install enabled. + +The interview is driven with a scripted ``input_fn`` (no TTY); config +generation is validated with the real pack schemas. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from semif_agent.config import load_config_file, validate_config +from semif_agent.packs import load_packs +from semif_agent.setup import ( + Answers, + build_config, + build_plan, + build_secrets, + plan_from_config, + run_interview, + run_setup, +) + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +def _packs(): + return load_packs({"skill_packs": str(REPO_ROOT / "packs")}) + + +def _scripted(answers): + """An input_fn that yields `answers` in order and raises past the end.""" + it = iter(answers) + + def _input(prompt: str) -> str: + try: + return next(it) + except StopIteration: + raise AssertionError(f"unexpected prompt: {prompt!r}") from None + + return _input + + +def _silent(_: str) -> None: + pass + + +# --------------------------------------------------------------------------- # +# Minimum path +# --------------------------------------------------------------------------- # + + +def test_minimal_config_is_essentials_only_with_no_endpoints(): + config = build_config(Answers.minimal(), _packs()) + assert config["engine"]["provider"] == "semif" + assert config["new_skill_creation"] == "deny" + # llm reuses the loaded engine; codegen is deliberately unconfigured. + assert config["llm"]["provider"] == "semif" + assert config["codegen"]["model"] == "" + # essentials on, every other pack off. + assert config["packs"]["essentials"]["enabled"] is True + for bridge in ("simplex", "nextcloud", "outlook", "browser"): + assert config["bridges"][bridge]["enabled"] is False + # no gateway, and the shared llm bridge (only useful to a bridge pack) off. + assert config["gateway"]["simplex"]["enabled"] is False + assert config["gateway"]["lxmf"]["enabled"] is False + assert config["gateway"]["voice"]["enabled"] is False + assert config["bridges"]["llm"]["enabled"] is False + # The generated config passes schema validation. + assert validate_config(config, _packs()) == [] + + +def test_minimum_plan_installs_nothing_heavy(): + plan = build_plan(Answers.minimal(), _packs()) + assert plan["install_engine"] is True + assert plan["install_bridge_service"] is False + assert plan["install_gateway_service"] is False + assert plan["install_simplex_binary"] is False + assert plan["install_simplex_forward"] is False + assert plan["install_browser"] is False + assert plan["install_voice"] is False + assert plan["packs"] == ["essentials"] + + +# --------------------------------------------------------------------------- # +# Maximum path +# --------------------------------------------------------------------------- # + + +def test_maximum_config_enables_everything(): + answers = Answers( + engine_provider="winnow", + winnow_base_url="http://10.0.0.5:8091", + winnow_model="winnow-1", + winnow_api_key="wk", + new_skill_creation="allow", + llm_provider="ollama", + llm_model="small", + codegen_provider="opencode", + codegen_model="coder", + codegen_api_key="sk", + packs=["simplex", "browser", "nextcloud", "outlook"], + gateways=["simplex", "lxmf", "voice"], + nextcloud_app_password="nc", + nextcloud_url="https://cloud.example.com", + outlook_client_id="client", + ) + config = build_config(answers, _packs()) + assert config["engine"]["provider"] == "winnow" + assert config["engine"]["winnow"]["model"] == "winnow-1" + assert config["engine"]["winnow"]["api_key"] == "!secret engine_winnow_api_key" + assert config["new_skill_creation"] == "allow" + assert config["llm"]["model"] == "small" + assert config["codegen"]["model"] == "coder" + assert config["codegen"]["api_key"] == "!secret codegen_api_key" + assert config["bridges"]["simplex"]["enabled"] is True + assert config["bridges"]["browser"]["enabled"] is True + assert config["bridges"]["llm"]["enabled"] is True + assert config["gateway"]["voice"]["enabled"] is True + assert config["gateway"]["humanize"]["enabled"] is True + assert config["bridges"]["nextcloud"]["app_password"] == ( + "!secret nextcloud_app_password" + ) + assert validate_config(config, _packs()) == [] + + plan = build_plan(answers, _packs()) + assert plan["install_engine"] is False + assert plan["install_simplex_binary"] is True + assert plan["install_simplex_forward"] is True + assert plan["install_browser"] is True + assert plan["install_voice"] is True + assert plan["install_bridge_service"] is True + assert plan["install_gateway_service"] is True + + secrets = build_secrets(answers) + assert secrets["engine_winnow_api_key"] == "wk" + assert secrets["codegen_api_key"] == "sk" + assert secrets["nextcloud_app_password"] == "nc" + # llm has no key configured, so no llm_api_key entry. + assert "llm_api_key" not in secrets + + +def test_simplex_gateway_without_pack_still_needs_the_binary(): + answers = Answers(gateways=["simplex"]) + plan = build_plan(answers, _packs()) + assert plan["install_simplex_binary"] is True + assert plan["install_simplex_forward"] is False + assert plan["install_gateway_service"] is True + assert plan["install_bridge_service"] is False + + +def test_voice_only_gateway_is_foreground_not_a_service(): + answers = Answers(gateways=["voice"]) + plan = build_plan(answers, _packs()) + # Voice is foreground-only: no systemd gateway unit, no daemon platforms. + assert plan["install_voice"] is True + assert plan["install_gateway_service"] is False + assert plan["gateway_platforms"] == [] + assert plan["install_simplex_binary"] is False + + +def test_gateway_platforms_exclude_voice(): + answers = Answers(gateways=["simplex", "voice"]) + plan = build_plan(answers, _packs()) + assert plan["gateway_platforms"] == ["simplex"] + assert plan["install_gateway_service"] is True + + +# --------------------------------------------------------------------------- # +# Interview branching +# --------------------------------------------------------------------------- # + + +def test_interview_collects_authoring_endpoints_and_packs(): + # engine=1(local); authoring=2(ask); llm provider=1(semif); + # codegen provider=1(ollama); codegen base URL='' (default); + # codegen model='my-coder'; codegen key=''; packs='a,c' (simplex+nextcloud); + # nextcloud url/user/pass; gateways='b' (lxmf); timezone. + script = _scripted( + [ + "1", # engine: local semif + "2", # authoring: ask + "1", # llm provider: semif (in-process) + "1", # codegen provider: ollama + "", # codegen base URL: default + "my-coder", # codegen model + "", # codegen api key + "a,c", # packs: simplex + nextcloud + "https://nc.example", # nextcloud url + "bob", # nextcloud username + "pw", # nextcloud app password + "b", # gateways: lxmf + "Europe/Paris", # timezone + ] + ) + answers = run_interview(input_fn=script, output=_silent) + assert answers.engine_provider == "semif" + assert answers.new_skill_creation == "ask" + assert answers.llm_provider == "semif" + assert answers.codegen_provider == "ollama" + assert answers.codegen_model == "my-coder" + assert answers.packs == ["essentials", "simplex", "nextcloud"] + assert answers.nextcloud_url == "https://nc.example" + assert answers.gateways == ["lxmf"] + assert answers.timezone == "Europe/Paris" + + +def test_interview_non_interactive_returns_minimum(): + answers = run_interview(interactive=False, output=_silent) + assert answers.new_skill_creation == "deny" + assert answers.packs == ["essentials"] + assert answers.gateways == [] + + +# --------------------------------------------------------------------------- # +# run_setup: files, secrets, plan, idempotency +# --------------------------------------------------------------------------- # + + +def test_run_setup_writes_split_config_and_secrets(tmp_path): + plan_out = tmp_path / "plan.json" + code = run_setup( + root=tmp_path, + path=tmp_path / "config.json", + packs=_packs(), + yes=True, + plan_out=str(plan_out), + output=_silent, + ) + assert code == 0 + assert (tmp_path / "config" / "core.json").is_file() + assert (tmp_path / "config" / "packs" / "essentials.json").is_file() + assert (tmp_path / "secrets.json").is_file() + plan = json.loads(plan_out.read_text()) + assert plan["packs"] == ["essentials"] + # The written index reloads to the answered values. + reloaded = load_config_file(tmp_path / "config.json") + assert reloaded["engine"]["provider"] == "semif" + assert reloaded["codegen"]["model"] == "" + assert reloaded["packs"]["essentials"]["enabled"] is True + + +def test_run_setup_answers_file_and_secrets_merge(tmp_path): + answers = { + "new_skill_creation": "allow", + "llm_provider": "ollama", + "llm_model": "small", + "codegen_provider": "ollama", + "codegen_model": "coder", + "codegen_api_key": "sk-codegen", + } + answers_path = tmp_path / "answers.json" + answers_path.write_text(json.dumps(answers)) + # A pre-existing secret must survive a merge. + (tmp_path / "secrets.json").write_text(json.dumps({"codegen_api_key": "old"})) + + code = run_setup( + root=tmp_path, + path=tmp_path / "config.json", + packs=_packs(), + answers_file=str(answers_path), + output=_silent, + ) + assert code == 0 + secrets = json.loads((tmp_path / "secrets.json").read_text()) + assert secrets["codegen_api_key"] == "sk-codegen" + reloaded = load_config_file(tmp_path / "config.json") + assert reloaded["new_skill_creation"] == "allow" + assert reloaded["codegen"]["model"] == "coder" + + +def test_run_setup_refuses_to_overwrite_without_force(tmp_path): + run_setup( + root=tmp_path, path=tmp_path / "config.json", packs=_packs(), + yes=True, output=_silent, + ) + code = run_setup( + root=tmp_path, path=tmp_path / "config.json", packs=_packs(), + yes=True, output=_silent, + ) + assert code == 1 + # --force re-seeds. + code = run_setup( + root=tmp_path, path=tmp_path / "config.json", packs=_packs(), + yes=True, force=True, output=_silent, + ) + assert code == 0 + + +def test_plan_only_matches_build_plan(tmp_path): + answers = Answers(packs=["simplex"], gateways=["simplex"]) + run_setup( + root=tmp_path, path=tmp_path / "config.json", packs=_packs(), + answers_file=_answers_file(tmp_path, answers), output=_silent, + ) + reloaded = load_config_file(tmp_path / "config.json") + derived = plan_from_config(reloaded, _packs()) + assert derived == build_plan(answers, _packs()) + + +def _answers_file(tmp_path: Path, answers: Answers) -> str: + path = tmp_path / "answers-in.json" + path.write_text(json.dumps(answers.to_dict())) + return str(path)