bootstrap: first-run interview + answer-driven config and installs
Bootstrap now asks the questions that make a fresh machine work and installs only what the answers require. `cli setup` (new `semif_agent/setup.py`) runs the interview — decision engine (local SemIf 4B or remote Winnow), new-skill authoring mode (+ llm/codegen endpoints/keys when enabled), capability packs, gateways, timezone — and writes the split config + secrets.json from the answers, plus a machine-readable install plan. Both ends of the spectrum work end to end: the minimum is the local SemIf 4B engine + the essentials pack (canned replies, time/timers, calculator) with no gateway, authoring, or heavy downloads; the maximum enables every pack, a remote engine, remote llm/codegen, and all gateways. `--yes` takes the minimum unattended; `--answers FILE` replays a saved answer set; a rerun skips the interview and `--reconfigure` re-runs it. The plan drives the conditional stages: engine clone/GGUF/tokenizer and requirements/engine.txt only for a local engine; requirements/transports.txt only when a SimpleX/LXMF transport is selected; the simplex-chat binary, Playwright, and the voice stack only when their pack/gateway is on; and only the systemd units the answers need (a reconfigure retires dropped ones). Also fixed: - `config-init`/`setup` could never run on a fresh machine: main() loaded config before parsing the subcommand. Config-independent subcommands now run before the config is required. - codegen was mandatory at startup even with authoring disabled (SystemExit on an empty model); build_codegen_client now returns None, and the scheduler guards every create door. build_llm_client likewise returns None for a non-semif provider with no model. - the gateway unit ran `--platform all`, which would try the foreground-only voice platform in a headless service; it now runs the explicit daemon list. requirements/ is split by concern (core/engine/transports + voice/browser); staging.txt is the union. Docs updated (README, AGENTS). New tests/test_setup.py covers both paths, interview branching, secrets merge, and the plan round-trip.
This commit is contained in:
1 parent
d67ea26f3d
commit
2296801b22
12 files changed
+1714
-311
No files matched your search
@@ -68,8 +68,9 @@ capability is a new bridge, not a gateway feature.
|
|||||||
cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
||||||
dashboard, gateway (command intake), bridge (standalone
|
dashboard, gateway (command intake), bridge (standalone
|
||||||
third-party API bridges), check-config (validate config/
|
third-party API bridges), check-config (validate config/
|
||||||
against the core + pack schemas), config-init (seed the split
|
against the core + pack schemas), setup (first-run interview ->
|
||||||
config/ + secrets.json)
|
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
|
config.py layered per-machine config: config.json is a thin index
|
||||||
(`{"include": [...]}`) over config/core.json + config/gateway.json
|
(`{"include": [...]}`) over config/core.json + config/gateway.json
|
||||||
+ config/bridges.json + config/packs/<name>.json, deep-merged in
|
+ config/bridges.json + config/packs/<name>.json, deep-merged in
|
||||||
@@ -382,8 +383,9 @@ values are yours to choose.
|
|||||||
endpoints and models). `config.json` is an index (`{"include": [...]}`);
|
endpoints and models). `config.json` is an index (`{"include": [...]}`);
|
||||||
`config/core.json` + `config/gateway.json` + `config/bridges.json` +
|
`config/core.json` + `config/gateway.json` + `config/bridges.json` +
|
||||||
`config/packs/<name>.json` hold the values, and `secrets.json` holds
|
`config/packs/<name>.json` hold the values, and `secrets.json` holds
|
||||||
credentials referenced as `"!secret <key>"`. `scripts/bootstrap.sh` seeds the
|
credentials referenced as `"!secret <key>"`. `scripts/bootstrap.sh` generates the
|
||||||
split config once (via `config-init`, only when `config.json` is absent) and
|
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
|
**nothing writes it afterwards — only a human edits it**. The committed
|
||||||
`config.example.json` is GENERATED from the core schema
|
`config.example.json` is GENERATED from the core schema
|
||||||
(`semif_agent/config.py`) and each pack's `config` schema — regenerate it with
|
(`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.)
|
containment rule; prefer bootstrap.)
|
||||||
- SemIf hard-pins `torch==2.10.0`, `numpy==2.2.6`, etc. The llamacpp path does
|
- 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
|
**not** need torch (torch is imported lazily inside `direct.score`). Install
|
||||||
with `--no-deps` and bring only what's needed — the committed manifest
|
with `--no-deps` and bring only what's needed — the committed
|
||||||
`requirements/staging.txt` is the single source of truth:
|
`requirements/engine.txt` holds the local-engine pins (the union file
|
||||||
|
`staging.txt` includes it):
|
||||||
`pip install -e <semif-clone> --no-deps`, then
|
`pip install -e <semif-clone> --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,
|
(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
|
`engine.gpu_layers` and run `bootstrap.sh --gpu vulkan|rocm|cuda` (with
|
||||||
`--gpu auto`, detection picks a backend when `engine.gpu_layers` is set),
|
`--gpu auto`, detection picks a backend when `engine.gpu_layers` is set),
|
||||||
which installs the Vulkan build prereqs
|
which installs the Vulkan build prereqs
|
||||||
(`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only
|
(`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
|
- **Expected pip warnings:** pip reports "dependency conflicts" against
|
||||||
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
|
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
|
||||||
not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging
|
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
|
(`check-config --write-example config.example.json`); secret keys are emitted
|
||||||
as `"!secret <name>"`, never a real value. `check-config` validates a live
|
as `"!secret <name>"`, never a real value. `check-config` validates a live
|
||||||
config (type mismatches and missing secrets are errors; unknown keys warn).
|
config (type mismatches and missing secrets are errors; unknown keys warn).
|
||||||
- **Seeding.** `config-init` writes the split layout + an empty `secrets.json`
|
- **Seeding.** `setup` (`semif_agent/setup.py`, the `cli setup` subcommand)
|
||||||
from the schemas (bootstrap calls it once, only when `config.json` is absent);
|
runs the first-run interview and writes the split layout + `secrets.json` from
|
||||||
afterwards only a human edits it. `scripts/config_merge.py` is the stdlib-only
|
the answers; `config-init` writes the schema defaults with no interview.
|
||||||
merger bootstrap uses before the venv exists.
|
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
|
### ollama
|
||||||
- `bootstrap.sh` installs **no ollama**: it expects the target host to already
|
- `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
|
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
|
- If generation hangs with no log output, restart the ollama service — the GPU
|
||||||
runner can wedge.
|
runner can wedge.
|
||||||
- **A local reasoning model needs thinking off for `llm`.** A reasoning model
|
- **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
|
- 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
|
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
|
`scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview**
|
||||||
(`config-init` writes `config/core.json`, `config/gateway.json`,
|
(`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split
|
||||||
`config/bridges.json`, `config/packs/*.json`, the `config.json` index, and an
|
config from the answers — decision engine (local SemIf 4B or remote Winnow),
|
||||||
empty `secrets.json`); edit those to set `llm.model`/`codegen.model` and the
|
new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability
|
||||||
endpoints, and put credentials in `secrets.json`. Flags (`--llm-url`,
|
packs, gateways, and timezone — then installs only what those answers require
|
||||||
`--codegen-url`, `--llm-model`,
|
(the install *plan* drives every conditional stage). `--yes` takes the minimum
|
||||||
`--codegen-model`) override the values read from the merged config **for that run
|
working defaults unattended; `--answers FILE` replays a saved answer set;
|
||||||
only** and are never written back. `--voice` additionally installs the
|
`--reconfigure` re-runs the interview and rewrites `config/` + `secrets.json`.
|
||||||
optional voice-gateway stack (`requirements/voice.txt` + system
|
`--voice` / `--browser` additionally install those optional stacks
|
||||||
`libportaudio2` + `alsa-utils`) and downloads its models into `.runtime/voice/` via
|
(`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`;
|
||||||
`scripts/voice-models.py`. The script must be run from a checkout —
|
`requirements/browser.txt` + a browser) even when the plan did not pick them.
|
||||||
it reads pins from that checkout's `pins.json` and never re-clones the agent
|
The script must be run from a checkout — it reads pins from that checkout's
|
||||||
repo (only the SemIf engine and the simplex-chat binary). Idempotent and
|
`pins.json` and never re-clones the agent repo (only the SemIf engine and the
|
||||||
rerunnable; every stage no-ops on existing state, so it also boots an
|
simplex-chat binary). Idempotent and rerunnable; every stage no-ops on existing
|
||||||
unknown-state machine. It installs **no ollama**: `llm` is the local ollama
|
state, so it also boots an unknown-state machine (a rerun SKIPS the interview
|
||||||
(bootstrap pulls `llm.model` if configured), `codegen` may point at a peer
|
and uses the existing config). It installs **no ollama**: `llm` is the local
|
||||||
host. It WARNs (never auto-pulls) if the remote codegen host is missing its
|
ollama (bootstrap pulls `llm.model` when configured), `codegen` may point at a
|
||||||
model, and WARNs if `llm.model`/`codegen.model` are unset.
|
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
|
- **All installation artifacts live inside the checkout under a gitignored
|
||||||
`.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`,
|
`.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`,
|
||||||
`simplex/`, `systemd/`, and `voice/` for the optional voice models), so an
|
`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
|
`bin_url`/`sha256`; bootstrap selects by `uname -m`, `arm64` normalized to
|
||||||
`aarch64`). Per-machine
|
`aarch64`). Per-machine
|
||||||
`simplex_chat` ports/display names stay in `config.json`. The python dep pins
|
`simplex_chat` ports/display names stay in `config.json`. The python dep pins
|
||||||
live in `requirements/staging.txt` (committed, one versioned artifact — every
|
live in `requirements/` split by concern (committed): `core.txt` (the test
|
||||||
host provisions from it). The agent reads `engine.source`/`revision` from
|
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
|
`pins.json` and derives the GGUF path from `engine.gguf_url` under
|
||||||
`.runtime/models/` (an explicit `engine.gguf` in `config.json` overrides it).
|
`.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.
|
rerun the script, re-run the integration tests. The script never guesses.
|
||||||
- pip prints **expected** "dependency conflict" warnings at install time
|
- pip prints **expected** "dependency conflict" warnings at install time
|
||||||
(semif-phase1 declares torch/accelerate/protobuf/sentencepiece/numpy 2.2.6
|
(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
|
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
|
them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Do not "fix" them
|
||||||
by installing torch.
|
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/gateway.json`, `config/bridges.json`, `config/packs/*.json`, the
|
||||||
`config.json` index, and an empty `secrets.json`) only when `config.json` is
|
`config.json` index, and `secrets.json`) when `config.json` is absent (or
|
||||||
absent, and **never writes it again** — only a human edits it. The committed
|
`--reconfigure`), and **never writes it again otherwise** — only a human edits
|
||||||
`config.example.json` is GENERATED from the core + pack schemas and ships the
|
it. The committed `config.example.json` is GENERATED from the core + pack
|
||||||
provisioned defaults, so a seeded config already has
|
schemas and ships the provisioned defaults. The generated config reflects the
|
||||||
`codegen.timeout: 3600`, the SimpleX gateway enabled
|
answers: the minimum path enables only `essentials`, `llm.provider = "semif"`,
|
||||||
(`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the
|
an empty `codegen.model` (no authoring), and every gateway/bridge off; the
|
||||||
standalone forwarding bridge enabled (`bridges.simplex.enabled = true`,
|
maximum path enables the chosen packs, gateways, a remote engine, and the
|
||||||
`ws_url` from `simplex_chat.forward_port`) and
|
`llm`/`codegen` endpoints with credentials in `secrets.json`. Bootstrap
|
||||||
the LLM bridge enabled (`bridges.llm.enabled = true`; it reuses the `llm`
|
renders/enables **only the user services the plan needs**:
|
||||||
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:
|
|
||||||
`semif-simplex.service` (the command `simplex-chat` bot daemon,
|
`semif-simplex.service` (the command `simplex-chat` bot daemon,
|
||||||
`--create-bot-display-name` on `simplex_chat.port`), `semif-gateway.service`
|
`--create-bot-display-name` on `simplex_chat.port`, when the simplex gateway is
|
||||||
(`.runtime/venv/bin/python -m semif_agent.cli gateway`),
|
on), `semif-gateway.service`
|
||||||
|
(`.runtime/venv/bin/python -m semif_agent.cli gateway --platform <daemon
|
||||||
|
platforms>`; voice is excluded — it is foreground-only),
|
||||||
`semif-simplex-forward.service` (the bridge's **own** daemon/profile on
|
`semif-simplex-forward.service` (the bridge's **own** daemon/profile on
|
||||||
`simplex_chat.forward_port`) and `semif-bridge.service`
|
`simplex_chat.forward_port`, when the simplex pack is on) and
|
||||||
(`.runtime/venv/bin/python -m semif_agent.cli bridge`). The gateway allowlist
|
`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
|
(`gateway.simplex.allowed_users`) and fallback (`home_channel`) are
|
||||||
`config.json` fields the operator edits; with an empty allowlist the gateway
|
`config.json` fields the operator edits; with an empty allowlist the gateway
|
||||||
denies everyone (the safe default until the human adds their contact id).
|
denies everyone (the safe default until the human adds their contact id).
|
||||||
`--copy-data SRC` rsyncs a prior host's `data/` for continuity.
|
`--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
|
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`).
|
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
|
- First run of the minimum path still downloads the 2.8G GGUF and builds
|
||||||
(~10 min on 6 cores); reruns are fast no-ops.
|
`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`.
|
- Per-host run/verify commands and addresses: `local/ENVIRONMENT.md`.
|
||||||
|
|
||||||
### codegen (skill bodies)
|
### codegen (skill bodies)
|
||||||
@@ -926,7 +948,14 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
under `codegen` in config.json (your configured code-capable model —
|
under `codegen` in config.json (your configured code-capable model —
|
||||||
larger/slower than `llm`). Title + description for new skills come from the
|
larger/slower than `llm`). Title + description for new skills come from the
|
||||||
separate small `llm` provider (its own endpoint/model, shared transport in
|
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`
|
- **Local engine as the `llm` provider: `"semif"`** (`provider.SemIfEngineClient`
|
||||||
+ `llm.SemIfLLMClient`). Set `llm.provider = "semif"` to generate the
|
+ `llm.SemIfLLMClient`). Set `llm.provider = "semif"` to generate the
|
||||||
title/description (and any other `llm` text: gateway result cleanup, the LLM
|
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
|
the live voice pipeline against a real microphone are live-integration
|
||||||
concerns.
|
concerns.
|
||||||
- **Deps.** `websockets` and `lxmf`/`rns` are pinned in
|
- **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
|
stays stdlib-only. The voice stack is pinned separately in
|
||||||
`requirements/voice.txt` (hardware-dependent: `sounddevice`, `openwakeword`,
|
`requirements/voice.txt` (hardware-dependent: `sounddevice`, `openwakeword`,
|
||||||
`faster-whisper`, `piper-tts`, `onnxruntime`, `webrtcvad-wheels`, plus the
|
`faster-whisper`, `piper-tts`, `onnxruntime`, `webrtcvad-wheels`, plus the
|
||||||
|
|||||||
@@ -409,7 +409,9 @@ packs/ skill packs, each cloned from its own repo (pack.<name>)
|
|||||||
into this gitignored dir — each ships its own bridge/ — see
|
into this gitignored dir — each ships its own bridge/ — see
|
||||||
packs.json + PACKGEN.md
|
packs.json + PACKGEN.md
|
||||||
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
|
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)
|
tests/ stdlib unit tests + tests/integration (real engine + LLM)
|
||||||
CODEGEN.md the contract fed to the skill-body codegen model
|
CODEGEN.md the contract fed to the skill-body codegen model
|
||||||
TESTGEN.md the contract fed to the test/contract 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
|
## Installation
|
||||||
|
|
||||||
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
|
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.
|
decision engine (local or remote). `scripts/bootstrap.sh` provisions what this
|
||||||
`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree
|
machine needs inside a gitignored `.runtime/` tree in the checkout — and only
|
||||||
in the checkout.
|
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
|
The **decision engine** routes every request. It runs one of two ways, chosen in
|
||||||
machines:
|
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
|
- **`llm`** — a small, fast model that authors the title + description of a
|
||||||
newly created category/skill. Deliberately its own endpoint/model, so it can
|
newly created category/skill. Its `provider` can be `"ollama"` (default),
|
||||||
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),
|
|
||||||
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
|
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
|
||||||
decision engine model generates in-process, with no endpoint and no
|
decision engine model generates in-process, with no endpoint and no
|
||||||
`llm.model` at all (see the `llm.semif` block in `config.json`).
|
`llm.model` at all.
|
||||||
|
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
|
||||||
The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU
|
slow and ideally on a beefier host.
|
||||||
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).
|
|
||||||
|
|
||||||
### Option A: one-command provisioning (`bootstrap.sh`)
|
### 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
|
scripts/bootstrap.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
With no `config.json` yet, the script seeds the split config (`config-init`
|
On a fresh machine the script **asks a few questions** and writes this machine's
|
||||||
writes `config/core.json`, `config/gateway.json`, `config/bridges.json`,
|
config from the answers:
|
||||||
`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.
|
|
||||||
|
|
||||||
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;
|
1. installs system prereqs + enables linger;
|
||||||
2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine;
|
2. clones/updates the skill packs, then runs the setup interview and writes
|
||||||
3. creates `.runtime/venv` and installs the pinned deps from
|
`config/` + `secrets.json` (first run or `--reconfigure`);
|
||||||
`requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since
|
3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the
|
||||||
the llama.cpp path never imports torch);
|
SemIf engine;
|
||||||
4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`;
|
4. creates `.runtime/venv` and installs only the needed dep files:
|
||||||
5. pre-fetches the HF tokenizer into `.runtime/hf/`;
|
`requirements/core.txt` always, `engine.txt` for a local engine,
|
||||||
6. downloads and sha256-verifies the pinned `simplex-chat` binary;
|
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` /
|
||||||
7. seeds the split config (`config-init`) **only if `config.json` does not
|
`browser.txt` for those stacks);
|
||||||
already exist** — it never rewrites it (only a human edits it);
|
5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
|
||||||
8. renders and enables systemd **user** units:
|
and pre-fetches the HF tokenizer into `.runtime/hf/`;
|
||||||
`semif-simplex` (bot daemon), `semif-gateway` (agent gateway),
|
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
|
||||||
`semif-simplex-forward` (the bridge's own daemon), `semif-bridge`;
|
SimpleX gateway or the simplex pack is selected;
|
||||||
9. prints the bot's SimpleX contact address.
|
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`,
|
Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it
|
||||||
`--copy-data SRC`) override the values read from `config.json` for that run only.
|
pulls `llm.model` from the target host's ollama when configured, and never
|
||||||
`--voice` additionally installs the optional voice-gateway stack
|
auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF
|
||||||
(`requirements/voice.txt` + system PortAudio) and downloads its models (the
|
tokenizer revision, simplex-chat version/url+sha256) live in the committed
|
||||||
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into
|
`pins.json`, not in `config.json`.
|
||||||
`.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`.
|
|
||||||
|
|
||||||
### Option B: core only (stdlib)
|
### 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
|
For a full install on a machine you manage, follow the same steps bootstrap
|
||||||
performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF,
|
performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF,
|
||||||
tokenizer cache), then seed the split config and adjust paths:
|
tokenizer cache), then generate the split config:
|
||||||
|
|
||||||
```sh
|
```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
|
### 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
|
(`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments
|
||||||
under `config/` hold the values and are deep-merged in order. Credentials live in
|
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
|
the gitignored `secrets.json` and are referenced from any fragment as
|
||||||
`"!secret <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` seeds the
|
`"!secret <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` runs
|
||||||
split config once via `config-init`; afterwards only a human edits it.
|
`setup` to generate the split config from your answers; afterwards only a human
|
||||||
|
edits it (`--reconfigure` re-runs the interview).
|
||||||
|
|
||||||
```sh
|
```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
|
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
|
with no block (or no port) leaves the variable unresolved and the operator is
|
||||||
asked for it.
|
asked for it.
|
||||||
|
|
||||||
`llm.model` and `codegen.model` are **required** (no default): set each to a
|
`llm.model` and `codegen.model` are **required only when authoring is enabled**
|
||||||
model its endpoint serves. A missing model fails fast at startup with a clear
|
(`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves.
|
||||||
config error rather than sending a request to a model that isn't there.
|
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`,
|
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
|
||||||
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
|
`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:
|
All subcommands go through the CLI:
|
||||||
|
|
||||||
```sh
|
```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 # interactive REPL
|
||||||
python -m semif_agent.cli run --script inputs.jsonl
|
python -m semif_agent.cli run --script inputs.jsonl
|
||||||
python -m semif_agent.cli dream # cost report
|
python -m semif_agent.cli dream # cost report
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
+12
-22
@@ -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/
|
# Voice and browser stacks are hardware/optional and are NOT included here —
|
||||||
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
|
# install them with `scripts/bootstrap.sh --voice` / `--browser` (or
|
||||||
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
|
# `pip install -r requirements/voice.txt` / `browser.txt`).
|
||||||
# cp314 wheel (source build fails). So semif-phase1 is installed with
|
-r core.txt
|
||||||
# `--no-deps` and exactly this set is brought in instead. The pins match the
|
-r engine.txt
|
||||||
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
|
-r transports.txt
|
||||||
# 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
|
|
||||||
@@ -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
|
||||||
+317
-163
@@ -1,10 +1,23 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Provision a new Ubuntu machine into a running semif-agent host.
|
# Provision a new Ubuntu machine into a running semif-agent host.
|
||||||
#
|
#
|
||||||
# Idempotent: safe to rerun; every stage no-ops on already-provisioned state,
|
# First run asks a few questions and writes this machine's config from the
|
||||||
# so it can also bootstrap a machine of unknown state. The small
|
# answers (see `python -m semif_agent.cli setup`): the decision engine (local
|
||||||
# title/description model runs on this machine's local ollama (bootstrap pulls
|
# SemIf 4B or a remote Winnow server), whether the agent may author new skills,
|
||||||
# it); codegen may point at a remote ollama host. This script installs NO ollama.
|
# 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
|
# 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
|
# re-cloned — only the SemIf engine, the simplex-chat binary, and the skill
|
||||||
@@ -13,15 +26,13 @@
|
|||||||
# named pack.<name> on the same host (see packs.json) into the gitignored
|
# named pack.<name> on the same host (see packs.json) into the gitignored
|
||||||
# packs/ directory.
|
# packs/ directory.
|
||||||
#
|
#
|
||||||
# config.json is the per-machine USER config (a thin index over config/*.json)
|
# 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`
|
# This script seeds it from the interview the FIRST time (or with
|
||||||
# (config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json,
|
# --reconfigure), then reads every per-machine value from it; only a human edits
|
||||||
# the config.json index, and an empty secrets.json) only when config.json is
|
# it afterwards. Pinned external refs (SemIf commit, GGUF url+sha256, HF
|
||||||
# absent, then reads every per-machine value from the merged config; only a human
|
# tokenizer revision, simplex-chat version/url+sha256) live in the committed
|
||||||
# edits it afterwards. Pinned external refs (SemIf commit, GGUF url+sha256,
|
# pins.json and the python dep pins in requirements/ — bump those (via git) and
|
||||||
# HF tokenizer revision, simplex-chat version/url+sha256) live in the committed
|
# rerun to upgrade.
|
||||||
# pins.json and the python dep pins in requirements/staging.txt — bump those
|
|
||||||
# (via git) and rerun to upgrade.
|
|
||||||
#
|
#
|
||||||
# Every installation artifact lives INSIDE this checkout under .runtime/
|
# Every installation artifact lives INSIDE this checkout under .runtime/
|
||||||
# (gitignored), so an end user can find and debug the whole stack in one tree:
|
# (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
|
# Only artifacts that operationally must live elsewhere are outside: the SSH
|
||||||
# key (~/.ssh) and the real systemd user dir/linger.
|
# 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:
|
# Usage:
|
||||||
# scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL]
|
# scripts/bootstrap.sh [--reconfigure] [--yes | --answers FILE]
|
||||||
# [--codegen-model MODEL] [--copy-data SRC] [--voice]
|
# [--copy-data SRC] [--voice] [--browser]
|
||||||
# [--browser] [--gpu MODE] [--pack-base URL] [-h]
|
# [--gpu MODE] [--pack-base URL] [-h]
|
||||||
#
|
#
|
||||||
# Run as the human user; sudo is used internally for system bits.
|
# Run as the human user; sudo is used internally for system bits.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
LLM_URL=""
|
RECONFIGURE=0
|
||||||
CODEGEN_URL=""
|
YES=0
|
||||||
LLM_MODEL=""
|
ANSWERS_FILE=""
|
||||||
CODEGEN_MODEL=""
|
|
||||||
COPY_DATA=""
|
COPY_DATA=""
|
||||||
VOICE=0
|
VOICE=0
|
||||||
BROWSER=0
|
BROWSER=0
|
||||||
@@ -56,13 +63,12 @@ PACK_BASE=""
|
|||||||
usage() {
|
usage() {
|
||||||
sed -n '2,/^set -euo pipefail/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'
|
sed -n '2,/^set -euo pipefail/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'
|
||||||
echo
|
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 " --reconfigure re-run the setup interview and rewrite config/ (default: use existing config)"
|
||||||
echo " --codegen-url URL override codegen.base_url from config.json for this run"
|
echo " --yes non-interactive: take the minimum working defaults (no prompts)"
|
||||||
echo " --llm-model MODEL override llm.model from config.json for this run (pulled if the local ollama lacks it)"
|
echo " --answers FILE non-interactive: read answers from a JSON file (see 'python -m semif_agent.cli setup --help')"
|
||||||
echo " --codegen-model MODEL override codegen.model from config.json for this run"
|
|
||||||
echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in"
|
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 " --voice also install the optional voice-gateway stack + models"
|
||||||
echo " --browser install the optional browser-bridge stack (Playwright + Chromium)"
|
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 " --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 " --pack-base URL base URL of the skill-pack repos (default: derived from this checkout's origin remote)"
|
||||||
echo " -h this help"
|
echo " -h this help"
|
||||||
@@ -71,10 +77,9 @@ usage() {
|
|||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
--llm-url) LLM_URL="$2"; shift 2 ;;
|
--reconfigure) RECONFIGURE=1; shift ;;
|
||||||
--codegen-url) CODEGEN_URL="$2"; shift 2 ;;
|
--yes) YES=1; shift ;;
|
||||||
--llm-model) LLM_MODEL="$2"; shift 2 ;;
|
--answers) ANSWERS_FILE="$2"; shift 2 ;;
|
||||||
--codegen-model) CODEGEN_MODEL="$2"; shift 2 ;;
|
|
||||||
--copy-data) COPY_DATA="$2"; shift 2 ;;
|
--copy-data) COPY_DATA="$2"; shift 2 ;;
|
||||||
--voice) VOICE=1; shift ;;
|
--voice) VOICE=1; shift ;;
|
||||||
--browser) BROWSER=1; shift ;;
|
--browser) BROWSER=1; shift ;;
|
||||||
@@ -100,6 +105,7 @@ SIMPLEX_DB="$RUNTIME/simplex"
|
|||||||
UNITS="$RUNTIME/systemd"
|
UNITS="$RUNTIME/systemd"
|
||||||
USER_UNITS="$HOME/.config/systemd/user"
|
USER_UNITS="$HOME/.config/systemd/user"
|
||||||
BROWSERS="$RUNTIME/browser"
|
BROWSERS="$RUNTIME/browser"
|
||||||
|
PLAN="$RUNTIME/bootstrap-plan.json"
|
||||||
PYTHON="$VENV/bin/python"
|
PYTHON="$VENV/bin/python"
|
||||||
PIP="$VENV/bin/pip"
|
PIP="$VENV/bin/pip"
|
||||||
|
|
||||||
@@ -117,9 +123,8 @@ fi
|
|||||||
# gitignored packs/ directory; the agent loads every pack under skill_packs
|
# 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
|
# (default "packs"). The list lives in the committed packs.json; each repo is a
|
||||||
# sibling of this checkout's origin remote (pack.<name>) unless --pack-base
|
# sibling of this checkout's origin remote (pack.<name>) unless --pack-base
|
||||||
# overrides the base. This runs BEFORE the config is seeded so config-init sees
|
# overrides the base. This runs BEFORE the interview so setup sees every pack
|
||||||
# the packs and generates their config/packs/*.json fragments. Idempotent:
|
# and can offer it. Idempotent: clone when absent, fast-forward when present.
|
||||||
# clone when absent, fast-forward when present.
|
|
||||||
PACK_MANIFEST="$REPO_ROOT/packs.json"
|
PACK_MANIFEST="$REPO_ROOT/packs.json"
|
||||||
if [[ -f "$PACK_MANIFEST" ]]; then
|
if [[ -f "$PACK_MANIFEST" ]]; then
|
||||||
if [[ -z "$PACK_BASE" ]]; then
|
if [[ -z "$PACK_BASE" ]]; then
|
||||||
@@ -163,26 +168,95 @@ PY
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# config.json is per-machine USER config. Seed it once (as a thin index plus the
|
# --- configure this machine (interview -> config/ + secrets.json) --------------
|
||||||
# split config/ fragments + secrets.json), then never write it again — only a
|
# On a fresh machine (or --reconfigure) ask the setup questions and generate the
|
||||||
# human edits it. The committed config.example.json is GENERATED from the pack +
|
# split config from the answers; otherwise use the existing config. Either way
|
||||||
# core schemas; see `python -m semif_agent.cli check-config --write-example`.
|
# emit a machine-readable install plan that drives the conditional stages below.
|
||||||
if [[ ! -f "$CONFIG" ]]; then
|
mkdir -p "$RUNTIME"
|
||||||
echo "== seeding config/ + secrets.json (edit them to configure this machine)"
|
setup_args=(--path "$CONFIG" --plan-out "$PLAN")
|
||||||
PYTHONPATH="$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -m semif_agent.cli config-init --path "$CONFIG" \
|
if [[ -n "$ANSWERS_FILE" ]]; then
|
||||||
|| { echo "config-init failed; falling back to a flat config.json from the example" >&2; cp "$EXAMPLE" "$CONFIG"; }
|
if [[ ! -f "$ANSWERS_FILE" ]]; then
|
||||||
|
echo "answers file not found: $ANSWERS_FILE" >&2
|
||||||
|
exit 1
|
||||||
fi
|
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 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.
|
# the reads below see one flat object. Stdlib-only, so it works before the venv.
|
||||||
MERGED_CONFIG="$RUNTIME/config.merged.json"
|
MERGED_CONFIG="$RUNTIME/config.merged.json"
|
||||||
mkdir -p "$RUNTIME"
|
|
||||||
python3 "$REPO_ROOT/scripts/config_merge.py" "$CONFIG" > "$MERGED_CONFIG" \
|
python3 "$REPO_ROOT/scripts/config_merge.py" "$CONFIG" > "$MERGED_CONFIG" \
|
||||||
|| { echo "could not read $CONFIG" >&2; exit 1; }
|
|| { echo "could not read $CONFIG" >&2; exit 1; }
|
||||||
|
|
||||||
# --- read pins from the committed pins.json ---------------------------------
|
# --- 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.
|
# The simplex-chat binary is per-arch: normalize `uname -m` to a pins key.
|
||||||
SIMPLEX_ARCH="$(uname -m)"
|
SIMPLEX_ARCH="$(uname -m)"
|
||||||
case "$SIMPLEX_ARCH" in
|
case "$SIMPLEX_ARCH" in
|
||||||
@@ -211,22 +285,27 @@ print("\x1f".join([
|
|||||||
PY
|
PY
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
if [[ -z "$SEMIF_REPO" || -z "$SEMIF_REF" || -z "$GGUF_URL" || -z "$GGUF_SHA256" ]]; 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
|
echo "engine pins missing in $PINS (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then
|
fi
|
||||||
|
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.<arch>.bin_url/sha256)" >&2
|
echo "simplex_chat pins missing in $PINS for arch '$SIMPLEX_ARCH' (assets.<arch>.bin_url/sha256)" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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 \
|
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 < <(
|
SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <(
|
||||||
python3 - "$MERGED_CONFIG" <<'PY'
|
python3 - "$MERGED_CONFIG" <<'PY'
|
||||||
import json, sys
|
import json, sys
|
||||||
cfg = json.load(open(sys.argv[1]))
|
cfg = json.load(open(sys.argv[1]))
|
||||||
s = cfg.get("simplex_chat", {})
|
s = cfg.get("simplex_chat", {})
|
||||||
|
eng = cfg.get("engine", {})
|
||||||
|
win = eng.get("winnow", {})
|
||||||
def strip_v1(u):
|
def strip_v1(u):
|
||||||
u = str(u or "").rstrip("/")
|
u = str(u or "").rstrip("/")
|
||||||
return u[:-3] if u.endswith("/v1") else u
|
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(),
|
str(cfg.get("llm", {}).get("provider", "ollama") or "ollama").lower(),
|
||||||
strip_v1(cfg.get("codegen", {}).get("base_url")),
|
strip_v1(cfg.get("codegen", {}).get("base_url")),
|
||||||
str(cfg.get("codegen", {}).get("model", "") or ""),
|
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("port", "")),
|
||||||
str(s.get("display_name", "") or ""),
|
str(s.get("display_name", "") or ""),
|
||||||
str(s.get("forward_port", "")),
|
str(s.get("forward_port", "")),
|
||||||
@@ -244,12 +327,15 @@ print("\x1f".join([
|
|||||||
PY
|
PY
|
||||||
)
|
)
|
||||||
|
|
||||||
# A flag overrides config.json for this run only; config.json is never touched.
|
LLM_URL="${CFG_LLM_URL:-http://127.0.0.1:11434}"
|
||||||
LLM_URL="${LLM_URL:-${CFG_LLM_URL:-http://127.0.0.1:11434}}"
|
LLM_MODEL="$CFG_LLM_MODEL"
|
||||||
CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}"
|
LLM_PROVIDER="${CFG_LLM_PROVIDER:-ollama}"
|
||||||
LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}"
|
CODEGEN_URL="$CFG_CODEGEN_URL"
|
||||||
CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}"
|
CODEGEN_MODEL="$CFG_CODEGEN_MODEL"
|
||||||
LLM_PROVIDER="${LLM_PROVIDER:-${CFG_LLM_PROVIDER:-ollama}}"
|
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
|
if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then
|
||||||
echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2
|
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"; }
|
with_v1() { local u="${1%/}"; [[ "$u" == */v1 ]] && printf '%s' "$u" || printf '%s/v1' "$u"; }
|
||||||
LLM_V1="$(with_v1 "$LLM_URL")"
|
LLM_V1="$(with_v1 "$LLM_URL")"
|
||||||
|
|
||||||
echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex-chat sha256 ${SIMPLEX_SHA256:0:12}…"
|
echo "== pins: simplex-chat sha256 ${SIMPLEX_SHA256:0:12}… | gguf ${GGUF_SHA256:0:12}…"
|
||||||
if [[ "$LLM_PROVIDER" == "semif" ]]; then
|
if [[ "$ENGINE_PROVIDER" = "winnow" ]]; then
|
||||||
echo "== llm semif (in-process engine model) | codegen $CODEGEN_URL"
|
echo "== decision engine: remote Winnow ($WINNOW_URL, model ${WINNOW_MODEL:-?})"
|
||||||
else
|
else
|
||||||
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
|
echo "== decision engine: local SemIf @ $SEMIF_REF"
|
||||||
fi
|
fi
|
||||||
echo "== runtime tree: $RUNTIME"
|
echo "== runtime tree: $RUNTIME"
|
||||||
|
|
||||||
@@ -304,16 +390,17 @@ if ! "$PY" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) els
|
|||||||
fi
|
fi
|
||||||
echo "== python: $("$PY" --version)"
|
echo "== python: $("$PY" --version)"
|
||||||
|
|
||||||
# --- stage 2: ssh key + SemIf engine clone ------------------------------------
|
# --- stage 2: ssh key + SemIf engine clone (local engine only) ----------------
|
||||||
mkdir -p ~/.ssh
|
mkdir -p ~/.ssh
|
||||||
if [[ ! -f ~/.ssh/id_ed25519 ]]; then
|
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
|
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519
|
||||||
cat ~/.ssh/id_ed25519.pub
|
cat ~/.ssh/id_ed25519.pub
|
||||||
fi
|
fi
|
||||||
|
|
||||||
git -C "$REPO_ROOT" pull --ff-only || true
|
git -C "$REPO_ROOT" pull --ff-only || true
|
||||||
|
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
if [[ ! -d "$ENGINE/.git" ]]; then
|
if [[ ! -d "$ENGINE/.git" ]]; then
|
||||||
echo "== cloning SemIf engine from $SEMIF_REPO into $ENGINE"
|
echo "== cloning SemIf engine from $SEMIF_REPO into $ENGINE"
|
||||||
git clone "$SEMIF_REPO" "$ENGINE"
|
git clone "$SEMIF_REPO" "$ENGINE"
|
||||||
@@ -323,15 +410,19 @@ if [[ "$(git -C "$ENGINE" rev-parse HEAD 2>/dev/null)" != "$SEMIF_REF" ]]; then
|
|||||||
git -C "$ENGINE" fetch origin
|
git -C "$ENGINE" fetch origin
|
||||||
git -C "$ENGINE" checkout "$SEMIF_REF"
|
git -C "$ENGINE" checkout "$SEMIF_REF"
|
||||||
fi
|
fi
|
||||||
|
else
|
||||||
|
echo "== remote decision engine selected; skipping the local engine clone"
|
||||||
|
fi
|
||||||
|
|
||||||
# --- stage 2b: pick the llama.cpp GPU backend ---------------------------------
|
# --- stage 2b: pick the llama.cpp GPU backend (local engine only) -------------
|
||||||
# The decision engine scores the GGUF through llama.cpp, which runs on CPU
|
# A GPU-enabled build is opt-in: llama.cpp's Vulkan backend splits the compute
|
||||||
# unless llama-cpp-python was built with a GPU backend. A GPU-enabled build is
|
# graph across CPU and Vulkan even with `n_gpu_layers=0`, roughly doubling CPU
|
||||||
# opt-in: llama.cpp's Vulkan backend splits the compute graph across CPU and
|
# latency, so a CPU-only host must not get one. `--gpu <backend>` forces a build;
|
||||||
# Vulkan even with `n_gpu_layers=0`, roughly doubling CPU latency, so a CPU-only
|
# `--gpu auto` (default) builds a GPU backend only when config.json asks for
|
||||||
# host must not get one. `--gpu <backend>` forces a build; `--gpu auto` (the
|
# offload (`engine.gpu_layers` nonzero).
|
||||||
# default) builds a GPU backend only when config.json asks for offload
|
GPU_BACKEND=cpu
|
||||||
# (`engine.gpu_layers` nonzero).
|
CONFIG_GPU_LAYERS=0
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
CONFIG_GPU_LAYERS="$(python3 - "$MERGED_CONFIG" <<'PY'
|
CONFIG_GPU_LAYERS="$(python3 - "$MERGED_CONFIG" <<'PY'
|
||||||
import json, sys
|
import json, sys
|
||||||
try:
|
try:
|
||||||
@@ -364,13 +455,14 @@ case "$GPU_MODE" in
|
|||||||
;;
|
;;
|
||||||
*) echo "unknown --gpu mode: $GPU_MODE (want auto, vulkan, rocm, cuda, cpu)" >&2; exit 2 ;;
|
*) echo "unknown --gpu mode: $GPU_MODE (want auto, vulkan, rocm, cuda, cpu)" >&2; exit 2 ;;
|
||||||
esac
|
esac
|
||||||
|
echo "== decision-engine llama.cpp backend: $GPU_BACKEND (engine.gpu_layers=$CONFIG_GPU_LAYERS)"
|
||||||
|
fi
|
||||||
case "$GPU_BACKEND" in
|
case "$GPU_BACKEND" in
|
||||||
vulkan) LLAMA_CMAKE_ARGS="-DGGML_VULKAN=on" ;;
|
vulkan) LLAMA_CMAKE_ARGS="-DGGML_VULKAN=on" ;;
|
||||||
rocm) LLAMA_CMAKE_ARGS="-DGGML_HIP=on" ;;
|
rocm) LLAMA_CMAKE_ARGS="-DGGML_HIP=on" ;;
|
||||||
cuda) LLAMA_CMAKE_ARGS="-DGGML_CUDA=on" ;;
|
cuda) LLAMA_CMAKE_ARGS="-DGGML_CUDA=on" ;;
|
||||||
*) LLAMA_CMAKE_ARGS="" ;;
|
*) LLAMA_CMAKE_ARGS="" ;;
|
||||||
esac
|
esac
|
||||||
echo "== decision-engine llama.cpp backend: $GPU_BACKEND (engine.gpu_layers=$CONFIG_GPU_LAYERS)"
|
|
||||||
|
|
||||||
if [[ "$GPU_BACKEND" = vulkan ]]; then
|
if [[ "$GPU_BACKEND" = vulkan ]]; then
|
||||||
VULKAN_PKGS=(libvulkan-dev glslc spirv-headers glslang-tools)
|
VULKAN_PKGS=(libvulkan-dev glslc spirv-headers glslang-tools)
|
||||||
@@ -388,11 +480,15 @@ if [[ ! -x "$PYTHON" ]]; then
|
|||||||
echo "== creating venv at $VENV"
|
echo "== creating venv at $VENV"
|
||||||
"$PY" -m venv "$VENV"
|
"$PY" -m venv "$VENV"
|
||||||
fi
|
fi
|
||||||
echo "== installing engine deps into $VENV"
|
echo "== installing core deps into $VENV"
|
||||||
"$PIP" install --upgrade pip setuptools wheel
|
"$PIP" install --upgrade pip setuptools wheel
|
||||||
|
"$PIP" install -r "$REPO_ROOT/requirements/core.txt"
|
||||||
|
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
|
echo "== installing engine deps (llama.cpp CPU/GPU path)"
|
||||||
"$PIP" install -e "$ENGINE" --no-deps
|
"$PIP" install -e "$ENGINE" --no-deps
|
||||||
CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \
|
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/engine.txt"
|
||||||
|
|
||||||
# Make the installed llama-cpp-python match the requested backend: pip ships a
|
# 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
|
# CPU wheel and its wheel cache hands it back even when CMAKE_ARGS asks for a
|
||||||
@@ -402,17 +498,24 @@ installed_gpu=no
|
|||||||
want_gpu=yes
|
want_gpu=yes
|
||||||
[[ "$GPU_BACKEND" = cpu ]] && want_gpu=no
|
[[ "$GPU_BACKEND" = cpu ]] && want_gpu=no
|
||||||
if [[ "$installed_gpu" != "$want_gpu" ]]; then
|
if [[ "$installed_gpu" != "$want_gpu" ]]; then
|
||||||
LLAMA_PIN="$(grep -m1 -E '^llama-cpp-python==' "$REPO_ROOT/requirements/staging.txt")"
|
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)"
|
echo "== rebuilding llama-cpp-python for the $GPU_BACKEND backend ($LLAMA_PIN)"
|
||||||
CMAKE_ARGS="$LLAMA_CMAKE_ARGS" CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 \
|
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 --no-deps --force-reinstall --no-cache-dir --no-binary llama-cpp-python "$LLAMA_PIN"
|
||||||
fi
|
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
|
"$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
|
# 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.
|
# 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
|
# libportaudio2 is the I/O backend sounddevice needs; alsa-utils provides
|
||||||
# amixer/alsamixer/alsactl so the operator can unmute and set the mic/speaker
|
# amixer/alsamixer/alsactl so the operator can unmute and set the mic/speaker
|
||||||
# levels (PortAudio itself has no volume control).
|
# levels (PortAudio itself has no volume control).
|
||||||
@@ -434,12 +537,12 @@ if [[ "$VOICE" = 1 ]]; then
|
|||||||
"$PIP" install --no-deps openwakeword==0.6.0
|
"$PIP" install --no-deps openwakeword==0.6.0
|
||||||
fi
|
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
|
# Playwright + its Chromium binaries. Optional: lazy-imported, so a host without
|
||||||
# it still runs every other bridge. Browsers go under the checkout's
|
# it still runs every other bridge. Browsers go under the checkout's
|
||||||
# .runtime/browser (the containment rule); the bridge sets PLAYWRIGHT_BROWSERS_PATH
|
# .runtime/browser (the containment rule); the bridge sets PLAYWRIGHT_BROWSERS_PATH
|
||||||
# to the same path at launch.
|
# to the same path at launch.
|
||||||
if [[ "$BROWSER" = 1 ]]; then
|
if [[ "$PLAN_BROWSER" = 1 ]]; then
|
||||||
echo "== installing browser-bridge deps into $VENV"
|
echo "== installing browser-bridge deps into $VENV"
|
||||||
"$PIP" install -r "$REPO_ROOT/requirements/browser.txt"
|
"$PIP" install -r "$REPO_ROOT/requirements/browser.txt"
|
||||||
BROWSER_ENGINE="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true
|
BROWSER_ENGINE="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true
|
||||||
@@ -471,7 +574,8 @@ PY
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- stage 4: GGUF --------------------------------------------------------------
|
# --- stage 4: GGUF (local engine only) ------------------------------------------
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
GGUF_NAME="$(basename "$GGUF_URL")"
|
GGUF_NAME="$(basename "$GGUF_URL")"
|
||||||
GGUF="$MODELS/$GGUF_NAME"
|
GGUF="$MODELS/$GGUF_NAME"
|
||||||
sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; }
|
sha_ok() { [[ -f "$GGUF" ]] && [[ "$(sha256sum "$GGUF" | cut -d' ' -f1)" == "$GGUF_SHA256" ]]; }
|
||||||
@@ -484,7 +588,7 @@ fi
|
|||||||
sha_ok || { echo "GGUF sha256 mismatch: expected $GGUF_SHA256" >&2; exit 1; }
|
sha_ok || { echo "GGUF sha256 mismatch: expected $GGUF_SHA256" >&2; exit 1; }
|
||||||
echo "== GGUF verified ($GGUF)"
|
echo "== GGUF verified ($GGUF)"
|
||||||
|
|
||||||
# --- stage 5: HF tokenizer cache --------------------------------------------------
|
# --- stage 5: HF tokenizer cache ---
|
||||||
export HF_HOME="$HF_CACHE"
|
export HF_HOME="$HF_CACHE"
|
||||||
mkdir -p "$HF_CACHE"
|
mkdir -p "$HF_CACHE"
|
||||||
echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV into $HF_CACHE"
|
echo "== pre-fetching tokenizer $HF_SOURCE @ $HF_REV into $HF_CACHE"
|
||||||
@@ -493,20 +597,24 @@ import sys
|
|||||||
from transformers import AutoTokenizer
|
from transformers import AutoTokenizer
|
||||||
AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2])
|
AutoTokenizer.from_pretrained(sys.argv[1], revision=sys.argv[2])
|
||||||
PY
|
PY
|
||||||
|
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
|
# Downloads the openWakeWord models (into the venv) + the Piper voice (into
|
||||||
# .runtime/voice/tts) and warms the faster-whisper model into the HF cache.
|
# .runtime/voice/tts) and warms the faster-whisper model into the HF cache.
|
||||||
# Reads gateway.voice from config.json
|
# Reads gateway.voice from config.json so the models match the configured names.
|
||||||
# so the models match the configured names. Best-effort: a download failure
|
# Best-effort: a download failure warns (the gateway reports the missing model at
|
||||||
# warns (the gateway reports the missing model at startup) rather than aborting.
|
# startup) rather than aborting.
|
||||||
if [[ "$VOICE" = 1 ]]; then
|
if [[ "$PLAN_VOICE" = 1 ]]; then
|
||||||
echo "== downloading voice models (openWakeWord + Piper + faster-whisper)"
|
echo "== downloading voice models (openWakeWord + Piper + faster-whisper)"
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" --config "$MERGED_CONFIG" \
|
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
|
|| echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- stage 6: simplex-chat daemon binary -------------------------------------------
|
# --- stage 6: simplex-chat daemon binary (only when needed) --------------------
|
||||||
|
if [[ "$PLAN_SIMPLEX_BIN" = 1 ]]; then
|
||||||
SIMPLEX_BIN="$TOOLDIR/simplex-chat"
|
SIMPLEX_BIN="$TOOLDIR/simplex-chat"
|
||||||
simplex_ok() {
|
simplex_ok() {
|
||||||
[[ -f "$SIMPLEX_BIN" ]] && [[ "$(sha256sum "$SIMPLEX_BIN" | cut -d' ' -f1)" == "$SIMPLEX_SHA256" ]]
|
[[ -f "$SIMPLEX_BIN" ]] && [[ "$(sha256sum "$SIMPLEX_BIN" | cut -d' ' -f1)" == "$SIMPLEX_SHA256" ]]
|
||||||
@@ -520,24 +628,46 @@ if ! simplex_ok; then
|
|||||||
fi
|
fi
|
||||||
simplex_ok || { echo "simplex-chat sha256 mismatch: expected $SIMPLEX_SHA256" >&2; exit 1; }
|
simplex_ok || { echo "simplex-chat sha256 mismatch: expected $SIMPLEX_SHA256" >&2; exit 1; }
|
||||||
echo "== simplex-chat verified ($SIMPLEX_BIN)"
|
echo "== simplex-chat verified ($SIMPLEX_BIN)"
|
||||||
|
else
|
||||||
|
echo "== SimpleX not selected; skipping the simplex-chat binary"
|
||||||
|
fi
|
||||||
|
|
||||||
# config.json is USER config: seeded above if absent, read for per-machine values,
|
# --- stage 8: systemd user units (only the ones the answers need) --------------
|
||||||
# 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 -----------------------------------------------------
|
|
||||||
render_unit() {
|
render_unit() {
|
||||||
local src="$1" dst="$2"
|
local src="$1" dst="$2"
|
||||||
sed -e "s|@REPO@|$REPO_ROOT|g" \
|
sed -e "s|@REPO@|$REPO_ROOT|g" \
|
||||||
-e "s|@PORT@|$SIMPLEX_PORT|g" \
|
-e "s|@PORT@|$SIMPLEX_PORT|g" \
|
||||||
-e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" \
|
-e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" \
|
||||||
-e "s|@FORWARD_PORT@|$SIMPLEX_FORWARD_PORT|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
|
UNIT_CHANGED=0
|
||||||
ACTIVE_BEFORE=""
|
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"
|
tmp="$UNITS/$unit.new"
|
||||||
render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$tmp"
|
render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$tmp"
|
||||||
if [[ ! -f "$UNITS/$unit" ]] || ! cmp -s "$tmp" "$UNITS/$unit"; then
|
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
|
fi
|
||||||
done
|
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)}"
|
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
||||||
if systemctl --user daemon-reload 2>/dev/null; then
|
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 \
|
systemctl --user enable --now "${WANTED_UNITS[@]}" 2>/dev/null \
|
||||||
&& echo "== enabled semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service" \
|
&& echo "== enabled ${WANTED_UNITS[*]}" \
|
||||||
|| echo "WARN: could not enable user services (run: systemctl --user enable --now semif-simplex semif-simplex-forward semif-gateway semif-bridge)" >&2
|
|| 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
|
# Apply a changed unit to services that were already running (enable --now
|
||||||
# leaves active units untouched). A daemon restart is safe: the simplex
|
# leaves active units untouched). A daemon restart is safe: the simplex
|
||||||
# profile persists and the gateway reconnects.
|
# profile persists and the gateway reconnects.
|
||||||
@@ -574,7 +704,7 @@ if command -v systemctl >/dev/null 2>&1; then
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- stage 8b: SimpleX bot contact address -------------------------------------------
|
# --- stage 8b: SimpleX bot contact address -------------------------------------
|
||||||
SIMPLEX_ADDRESS=""
|
SIMPLEX_ADDRESS=""
|
||||||
if command -v systemctl >/dev/null 2>&1; then
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
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
|
||||||
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
|
# 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.
|
# 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
|
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
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- stage 9: optional data copy -----------------------------------------------------
|
# --- stage 9: optional data copy -----------------------------------------------
|
||||||
if [[ -n "$COPY_DATA" ]]; then
|
if [[ -n "$COPY_DATA" ]]; then
|
||||||
echo "== rsync data from $COPY_DATA"
|
echo "== rsync data from $COPY_DATA"
|
||||||
mkdir -p "$REPO_ROOT/data"
|
mkdir -p "$REPO_ROOT/data"
|
||||||
rsync -a "$COPY_DATA/" "$REPO_ROOT/data/"
|
rsync -a "$COPY_DATA/" "$REPO_ROOT/data/"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- stage 10: verify + pull the local self-assessment model -------------------------
|
# --- stage 10: verify imports + the configured endpoints ------------------------
|
||||||
echo "== verifying imports"
|
echo "== verifying imports"
|
||||||
|
if [[ "$PLAN_INSTALL_ENGINE" = 1 ]]; then
|
||||||
"$PYTHON" -c "import semif_phase1, semif_agent; print('engine + agent import OK')"
|
"$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
|
# The decision engine is always real: a remote Winnow server must be reachable at
|
||||||
# is pulled so assess/fidelity work without a remote dependency.
|
# runtime (there is no fallback), so surface its address here.
|
||||||
# With llm.provider == "semif" the loaded decision engine generates the text
|
if [[ "$ENGINE_PROVIDER" = "winnow" ]]; then
|
||||||
# in-process, so no ollama model/endpoint is involved.
|
echo "== decision engine: remote Winnow at ${WINNOW_URL:-?} (model ${WINNOW_MODEL:-?}) — must be reachable at runtime"
|
||||||
if [[ "$LLM_PROVIDER" == "semif" ]]; then
|
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)"
|
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
|
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
|
else
|
||||||
echo "== llm ollama ($LLM_API), model $LLM_MODEL"
|
echo "== llm ollama ($LLM_API), model $LLM_MODEL"
|
||||||
if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then
|
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 "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
|
else
|
||||||
LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)"
|
LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)"
|
||||||
if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then
|
if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then
|
||||||
@@ -670,8 +813,15 @@ else
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Codegen is the larger model, possibly on a remote host. Warn only — never auto-pull.
|
# Codegen writes skill bodies; only needed when authoring is enabled. Warn only —
|
||||||
if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then
|
# 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)"
|
echo "== codegen ollama ($CODEGEN_API)"
|
||||||
CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)"
|
CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)"
|
||||||
if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then
|
if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then
|
||||||
@@ -679,26 +829,28 @@ if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then
|
|||||||
else
|
else
|
||||||
echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2
|
echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2
|
||||||
fi
|
fi
|
||||||
else
|
|
||||||
echo "WARN: codegen.base_url/model is not set in config.json — set it before starting the agent" >&2
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if command -v systemctl >/dev/null 2>&1; then
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
echo "== gateway + bridge services"
|
echo "== services"
|
||||||
systemctl --user is-active semif-simplex.service 2>/dev/null | sed 's/^/ semif-simplex: /' || true
|
for unit in "${ALL_UNITS[@]}"; do
|
||||||
systemctl --user is-active semif-gateway.service 2>/dev/null | sed 's/^/ semif-gateway: /' || true
|
state="$(systemctl --user is-active "$unit" 2>/dev/null || true)"
|
||||||
systemctl --user is-active semif-simplex-forward.service 2>/dev/null | sed 's/^/ semif-simplex-forward: /' || true
|
[[ -n "$state" ]] && echo " ${unit%.service}: $state"
|
||||||
systemctl --user is-active semif-bridge.service 2>/dev/null | sed 's/^/ semif-bridge: /' || true
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
|
|
||||||
Done. Next steps:
|
Done. What this machine is configured for:
|
||||||
1. Edit the split config (config/core.json, config/gateway.json,
|
engine: $ENGINE_PROVIDER
|
||||||
config/packs/*.json) — set llm.model/llm.base_url and
|
authoring: $PLAN_AUTHORING
|
||||||
codegen.model/codegen.base_url; put credentials in secrets.json.
|
packs: $PLAN_PACKS
|
||||||
bootstrap.sh seeded the config via config-init (if it was absent)
|
gateways: ${PLAN_GATEWAYS:-none (REPL + dashboard)}
|
||||||
and NEVER rewrites it; only you edit it.
|
|
||||||
|
Next steps:
|
||||||
|
1. Edit the split config if you need to (config/core.json, config/gateway.json,
|
||||||
|
config/packs/*.json); credentials live in secrets.json. To re-run the setup
|
||||||
|
interview instead: scripts/bootstrap.sh --reconfigure
|
||||||
2. Skill packs are cloned from their own repos into packs/ (see packs.json);
|
2. Skill packs are cloned from their own repos into packs/ (see packs.json);
|
||||||
they are gitignored here. Update them with:
|
they are gitignored here. Update them with:
|
||||||
for d in packs/*/; do git -C "\$d" pull --ff-only; done
|
for d in packs/*/; do git -C "\$d" pull --ff-only; done
|
||||||
@@ -706,6 +858,10 @@ Done. Next steps:
|
|||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli run
|
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli run
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m pytest tests/integration -q -s (needs real engine+LLM)
|
HF_HOME="$HF_CACHE" "$PYTHON" -m pytest tests/integration -q -s (needs real engine+LLM)
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli dashboard --port 8765
|
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli dashboard --port 8765
|
||||||
|
EOF
|
||||||
|
|
||||||
|
if [[ ",$PLAN_GATEWAYS," == *",simplex,"* ]]; then
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
SimpleX command gateway (commands only):
|
SimpleX command gateway (commands only):
|
||||||
- Runs as systemd user services 'semif-simplex' (bot daemon, port $SIMPLEX_PORT) and
|
- Runs as systemd user services 'semif-simplex' (bot daemon, port $SIMPLEX_PORT) and
|
||||||
@@ -721,19 +877,26 @@ SimpleX command gateway (commands only):
|
|||||||
gateway rejects everyone — that is the safe default.
|
gateway rejects everyone — that is the safe default.
|
||||||
- The gateway takes commands and replies. It never reads history, shows invite
|
- The gateway takes commands and replies. It never reads history, shows invite
|
||||||
links, or composes messages: that is the forwarding bridge's job.
|
links, or composes messages: that is the forwarding bridge's job.
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ",$PLAN_GATEWAYS," == *",lxmf,"* ]]; then
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
LXMF command gateway (commands only):
|
LXMF command gateway (commands only):
|
||||||
- Runs IN-PROCESS inside the same 'semif-gateway' service (no separate daemon);
|
- Runs IN-PROCESS inside the same 'semif-gateway' service (no separate daemon);
|
||||||
the transport is installed from requirements/staging.txt (lxmf + rns).
|
the transport is installed from requirements/transports.txt (lxmf + rns).
|
||||||
Enable it in config.json with gateway.lxmf.enabled = true, then restart the
|
|
||||||
gateway (the unit runs `gateway --platform all`, so SimpleX + LXMF share one
|
|
||||||
scheduler).
|
|
||||||
- Its LXMF address (32 hex chars) is printed on connect:
|
- Its LXMF address (32 hex chars) is printed on connect:
|
||||||
journalctl --user -u semif-gateway -f
|
journalctl --user -u semif-gateway -f
|
||||||
Add that address as a contact in an LXMF client (Sideband, MeshChatX, ...)
|
Add that address as a contact in an LXMF client (Sideband, MeshChatX, ...)
|
||||||
and put it in gateway.lxmf.allowed_users (discover a sender from a
|
and put it in gateway.lxmf.allowed_users (discover a sender from a
|
||||||
'gateway_denied' trace event). With an empty allowlist it rejects everyone —
|
'gateway_denied' trace event). With an empty allowlist it rejects everyone —
|
||||||
the safe default.
|
the safe default.
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$PLAN_SIMPLEX_FWD" = 1 ]]; then
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
SimpleX forwarding bridge (messaging UX for skills):
|
SimpleX forwarding bridge (messaging UX for skills):
|
||||||
- Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT)
|
- Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT)
|
||||||
@@ -743,35 +906,32 @@ SimpleX forwarding bridge (messaging UX for skills):
|
|||||||
- Skills reach it over HTTP at the address derived from bridges.simplex
|
- Skills reach it over HTTP at the address derived from bridges.simplex
|
||||||
(host/port, default http://127.0.0.1:5227); simplex.connect_link shows its
|
(host/port, default http://127.0.0.1:5227); simplex.connect_link shows its
|
||||||
address and simplex.next_message reads messages sent to it.
|
address and simplex.next_message reads messages sent to it.
|
||||||
|
|
||||||
LLM bridge (generation for skills):
|
|
||||||
- Runs inside the same 'semif-bridge' process. It reuses the top-level `llm`
|
|
||||||
model (configured once) and serves a generic POST /chat; skills call it at
|
|
||||||
the address derived from bridges.llm (default http://127.0.0.1:5229).
|
|
||||||
|
|
||||||
Nextcloud bridge (files/calendar/tasks/contacts/notes for skills):
|
|
||||||
- Runs inside the same 'semif-bridge' process (Nextcloud is plain HTTPS, so
|
|
||||||
there is no separate daemon). Configure the account once in config.json under
|
|
||||||
bridges.nextcloud (url/username/app_password) — or reuse the top-level
|
|
||||||
nextcloud_* values the nextcloud pack skills collect. Skills call it at the address
|
|
||||||
derived from bridges.nextcloud (default http://127.0.0.1:5230).
|
|
||||||
|
|
||||||
Browser bridge (browser automation for skills):
|
|
||||||
- Disabled by default; it needs the optional Playwright stack. Enable it with
|
|
||||||
bridges.browser.enabled = true (install the deps with scripts/bootstrap.sh
|
|
||||||
--browser). It runs inside the same 'semif-bridge' process and keeps a
|
|
||||||
persistent browser profile under .runtime/browser/profile. Skills call it at
|
|
||||||
the address derived from bridges.browser (default http://127.0.0.1:5232).
|
|
||||||
EOF
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
if [[ "$VOICE" = 1 ]]; then
|
if [[ "$PLAN_BRIDGE_SVC" = 1 ]]; then
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
Bridge services (run inside 'semif-bridge'):
|
||||||
|
- LLM bridge: a generic POST /chat in front of the configured `llm` model
|
||||||
|
(address derived from bridges.llm, default http://127.0.0.1:5229).
|
||||||
|
- Nextcloud bridge: files/calendar/tasks/contacts/notes over one JSON surface
|
||||||
|
(configure bridges.nextcloud, default http://127.0.0.1:5230).
|
||||||
|
- Outlook bridge: Microsoft Graph mail/calendar/To Do/OneDrive
|
||||||
|
(configure bridges.outlook; run packs/outlook/scripts/outlook-auth.py once).
|
||||||
|
- Browser bridge: Playwright automation with a persistent profile under
|
||||||
|
.runtime/browser/profile (address derived from bridges.browser, default
|
||||||
|
http://127.0.0.1:5232).
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$PLAN_VOICE" = 1 ]]; then
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
|
|
||||||
Voice command gateway (wake word + speech-to-text + text-to-speech):
|
Voice command gateway (wake word + speech-to-text + text-to-speech):
|
||||||
- The stack is installed and its models downloaded (openWakeWord into the
|
- The stack is installed and its models downloaded (openWakeWord into the
|
||||||
venv, the Piper voice into .runtime/voice/tts, faster-whisper into .runtime/hf).
|
venv, the Piper voice into .runtime/voice/tts, faster-whisper into .runtime/hf).
|
||||||
Enable it in config.json with gateway.voice.enabled = true, then run it in
|
Run it in the foreground (it needs your audio session; it is NOT a systemd unit):
|
||||||
the foreground (it needs your audio session; it is NOT a systemd unit):
|
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli gateway --platform voice
|
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli gateway --platform voice
|
||||||
- Say the wake word (gateway.voice.wake.model, default 'hey_computer' — phrase
|
- Say the wake word (gateway.voice.wake.model, default 'hey_computer' — phrase
|
||||||
"Hey Computer") and speak; the reply is spoken back. The wake word is
|
"Hey Computer") and speak; the reply is spoken back. The wake word is
|
||||||
@@ -782,27 +942,21 @@ Voice command gateway (wake word + speech-to-text + text-to-speech):
|
|||||||
sudo alsactl store
|
sudo alsactl store
|
||||||
List devices with: $PYTHON -c "import sounddevice as sd; print(sd.query_devices())"
|
List devices with: $PYTHON -c "import sounddevice as sd; print(sd.query_devices())"
|
||||||
and put the input/output device indices in gateway.voice.audio.
|
and put the input/output device indices in gateway.voice.audio.
|
||||||
- Re-download / switch models any time with:
|
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" scripts/voice-models.py --config config.json
|
|
||||||
EOF
|
EOF
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$BROWSER" = 1 ]]; then
|
if [[ "$PLAN_BROWSER" = 1 ]]; then
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
|
|
||||||
Browser bridge (browser automation for skills):
|
Browser bridge (browser automation for skills):
|
||||||
- The Playwright stack is installed and the '$BROWSER_ENGINE' browser is under
|
- The Playwright stack is installed and the '$BROWSER_ENGINE' browser is under
|
||||||
$BROWSERS. Enable it in config.json with bridges.browser.enabled = true, then
|
$BROWSERS. It runs inside 'semif-bridge' (no separate daemon) and keeps a
|
||||||
restart the bridge service:
|
persistent profile at .runtime/browser/profile, so a login you do once
|
||||||
systemctl --user restart semif-bridge.service
|
survives across calls and restarts. Set bridges.browser.headless = false to
|
||||||
- It runs inside 'semif-bridge' (no separate daemon) and keeps a persistent
|
watch the window (useful the first time you sign in to a site); POST /reset
|
||||||
profile at .runtime/browser/profile, so a login you do once survives across
|
with purge=true wipes the stored profile.
|
||||||
calls and restarts. Set bridges.browser.headless = false to watch the window
|
- The shipped pack skills are browser.open_page, browser.read_page, and
|
||||||
(useful the first time you sign in to a site); POST /reset with purge=true
|
browser.screenshot.
|
||||||
wipes the stored profile.
|
|
||||||
- Skills call it at the address derived from bridges.browser (host/port,
|
|
||||||
default http://127.0.0.1:5232); the shipped pack skills are browser.open_page,
|
|
||||||
browser.read_page, and browser.screenshot.
|
|
||||||
- If the bridge reports 503, the browser failed to launch — run:
|
- If the bridge reports 503, the browser failed to launch — run:
|
||||||
PLAYWRIGHT_BROWSERS_PATH=$BROWSERS "$PYTHON" -m playwright install $BROWSER_ENGINE
|
PLAYWRIGHT_BROWSERS_PATH=$BROWSERS "$PYTHON" -m playwright install $BROWSER_ENGINE
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Environment=PYTHONUNBUFFERED=1
|
|||||||
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
|
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
|
||||||
# voice mic loop) leaves a trace in the journal instead of hanging silently.
|
# voice mic loop) leaves a trace in the journal instead of hanging silently.
|
||||||
Environment=PYTHONFAULTHANDLER=1
|
Environment=PYTHONFAULTHANDLER=1
|
||||||
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
|
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform @PLATFORMS@
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
StandardOutput=journal
|
StandardOutput=journal
|
||||||
|
|||||||
+122
-7
@@ -46,6 +46,7 @@ from .llm import LLMClient, SemIfLLMClient
|
|||||||
from .log import DecisionLog
|
from .log import DecisionLog
|
||||||
from .packs import load_packs
|
from .packs import load_packs
|
||||||
from .scheduler import Scheduler
|
from .scheduler import Scheduler
|
||||||
|
from .setup import run_setup as run_bootstrap_setup
|
||||||
from .skills import tree_summary
|
from .skills import tree_summary
|
||||||
from .trace import TraceLog
|
from .trace import TraceLog
|
||||||
|
|
||||||
@@ -249,15 +250,23 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
|
|||||||
return SemIfEngine(build_engine_config(config, pins))
|
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.
|
"""Build the codegen client from the `codegen` config block.
|
||||||
|
|
||||||
`provider` selects the class (`opencode` -> the Console client, which adds
|
`provider` selects the class (`opencode` -> the Console client, which adds
|
||||||
bearer auth and a User-Agent) and the endpoint/auth come from
|
bearer auth and a User-Agent) and the endpoint/auth come from
|
||||||
`_provider_endpoint`. Shared by `build_scheduler` and the integration tests
|
`_provider_endpoint`. Shared by `build_scheduler` and the integration tests
|
||||||
so both exercise the configured provider rather than assuming ollama.
|
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 {}
|
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 {}
|
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
|
||||||
provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
|
provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
|
||||||
client_cls = ConsoleCodegenClient if provider == "opencode" else CodegenClient
|
client_cls = ConsoleCodegenClient if provider == "opencode" else CodegenClient
|
||||||
@@ -267,7 +276,7 @@ def build_codegen_client(config: dict) -> CodegenClient:
|
|||||||
)
|
)
|
||||||
return client_cls(
|
return client_cls(
|
||||||
base_url=endpoint["base_url"],
|
base_url=endpoint["base_url"],
|
||||||
model=_required_model(codegen_cfg, "codegen"),
|
model=model,
|
||||||
timeout=float(codegen_cfg.get("timeout", 1200.0)),
|
timeout=float(codegen_cfg.get("timeout", 1200.0)),
|
||||||
stream=bool(codegen_cfg.get("stream", False)),
|
stream=bool(codegen_cfg.get("stream", False)),
|
||||||
idle_warn=float(codegen_cfg.get("idle_warn", 60.0)),
|
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.
|
"""Build the `llm` title/description client from the `llm` config block.
|
||||||
|
|
||||||
`provider` selects the backend: `"semif"` drives the already-loaded SemIf
|
`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
|
needed), `"opencode"` the hosted Console client, and anything else the
|
||||||
default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests
|
default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests
|
||||||
so both exercise the configured provider rather than assuming ollama.
|
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 {}
|
llm_cfg = config.get("llm", {}) or {}
|
||||||
provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
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)),
|
temperature=float(semif_cfg.get("temperature", 0.0)),
|
||||||
max_tokens=int(semif_cfg.get("max_tokens", 256)),
|
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
|
llm_cls = ConsoleLLMClient if provider == "opencode" else LLMClient
|
||||||
endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
||||||
return llm_cls(
|
return llm_cls(
|
||||||
base_url=endpoint["base_url"],
|
base_url=endpoint["base_url"],
|
||||||
model=_required_model(llm_cfg, "llm"),
|
model=model,
|
||||||
timeout=float(llm_cfg.get("timeout", 600.0)),
|
timeout=float(llm_cfg.get("timeout", 600.0)),
|
||||||
stream=bool(llm_cfg.get("stream", False)),
|
stream=bool(llm_cfg.get("stream", False)),
|
||||||
idle_warn=float(llm_cfg.get("idle_warn", 30.0)),
|
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", {})
|
codegen_cfg = config.get("codegen", {})
|
||||||
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
|
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
|
||||||
codegen = build_codegen_client(config)
|
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):
|
def make_degeneration_check(run_id: str):
|
||||||
"""2-option SemIf decision (continue/stop) that aborts a degenerating
|
"""2-option SemIf decision (continue/stop) that aborts a degenerating
|
||||||
@@ -1056,10 +1086,42 @@ def config_init(path: str = "config.json") -> int:
|
|||||||
return 0
|
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:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
argv = list(argv) if argv is not None else list(sys.argv[1:])
|
argv = list(argv) if argv is not None else list(sys.argv[1:])
|
||||||
config_path = _extract_config_path(argv)
|
config_path = _extract_config_path(argv)
|
||||||
config = load_config(config_path)
|
defaults = _load_config_tolerant(config_path)
|
||||||
parser = argparse.ArgumentParser(prog="semif-agent")
|
parser = argparse.ArgumentParser(prog="semif-agent")
|
||||||
parser.add_argument("--config", default="config.json")
|
parser.add_argument("--config", default="config.json")
|
||||||
sub = parser.add_subparsers(dest="command")
|
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")
|
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 = sub.add_parser("relabel", help="human override of a decision label")
|
||||||
relabel_p.add_argument("id")
|
relabel_p.add_argument("id")
|
||||||
relabel_p.add_argument("outcome")
|
relabel_p.add_argument("outcome")
|
||||||
|
|
||||||
dash_p = sub.add_parser("dashboard", help="run the local browser dashboard")
|
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(
|
dash_p.add_argument(
|
||||||
"--host",
|
"--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)",
|
help="bind address (0.0.0.0 to expose on the LAN)",
|
||||||
)
|
)
|
||||||
dash_p.add_argument(
|
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)
|
return check_config(config_path, write_example=args.write_example)
|
||||||
if args.command == "config-init":
|
if args.command == "config-init":
|
||||||
return config_init(args.path)
|
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)
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
if args.command == "run":
|
if args.command == "run":
|
||||||
|
|||||||
@@ -833,6 +833,8 @@ class Scheduler:
|
|||||||
inside it and hands off to the codegen body worker. On failure the
|
inside it and hands off to the codegen body worker. On failure the
|
||||||
request is not re-dispatched and the user is told.
|
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")
|
self._queue_draft(request, None, "category")
|
||||||
return DispatchResult(
|
return DispatchResult(
|
||||||
kind="create_category",
|
kind="create_category",
|
||||||
@@ -855,6 +857,8 @@ class Scheduler:
|
|||||||
"""
|
"""
|
||||||
if self._category_locked(category):
|
if self._category_locked(category):
|
||||||
return self._blocked_create(request, 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")
|
pending = request.meta.get("awaiting_skill_body")
|
||||||
if pending is not None:
|
if pending is not None:
|
||||||
category_pending, name = pending
|
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) ----
|
# ---- new-skill creation modes (deterministic per-category create door) ----
|
||||||
|
|
||||||
def _category_mode(self, category: str) -> str:
|
def _category_mode(self, category: str) -> str:
|
||||||
|
|||||||
@@ -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 <secret_key>`` 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))
|
||||||
@@ -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)
|
||||||
Reference in new issue
Block a user