A third decision-engine provider alongside the local SemIf GGUF and the remote Winnow server: `engine.provider == "ollama"` talks to ollama's native `/v1/systemone` route via `semif_agent/ollama_systemone.py`. It reuses the Winnow DecisionRequest -> choice mapping and the same strict distribution validation over exactly the requested option ids, and adds the edges only ollama has: - no `/health`: `warm()` probes `GET /api/version` + `POST /api/show`, which also proves the model is pulled and advertises the `decision` capability; - `engine.ollama.context_tokens: 0` follows the model's real `num_ctx` from `/api/show`; - `keep_alive` rides on the request, criteria descriptions use the ollama subset `string | null`, and a choice question needs >= 2 options; - decision models do not generate text, so `generate()` raises `EngineUnavailable` (use `llm.provider == "ollama"` for chat). Every failure is an `EngineUnavailable` (fatal, like the local engine) and the engine lock still serializes on the single-slot server. `cli.build_engine` selects it, the setup interview and `--answers` accept it, and the install plan skips the engine clone/GGUF/tokenizer for it. Docs, config.example.json, and tests updated.
899 lines
33 KiB
Python
899 lines
33 KiB
Python
"""First-run setup: the bootstrap interview, config generation, and the plan.
|
|
|
|
``scripts/bootstrap.sh`` 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).
|
|
|
|
Which packs exist is owned by a dedicated *pack index* repo (``semif-packs``),
|
|
not this checkout; bootstrap fetches it and passes ``--pack-index FILE`` so the
|
|
interview offers exactly the packs the index lists. Config generation still reads
|
|
each pack's ``pack.json`` from the cloned ``packs/`` tree, so bootstrap runs setup
|
|
in two passes: ``--answers-out FILE`` collects the answers (no packs needed),
|
|
bootstrap clones only the selected packs, then a second pass writes the config.
|
|
|
|
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", "ollama")
|
|
#: New-skill creation modes.
|
|
AUTHORING_MODES = ("deny", "ask", "allow")
|
|
|
|
# The capability packs the wizard offers come from the pack index repo
|
|
# (`semif-packs`), passed as `--pack-index FILE` (see `load_pack_index`); the
|
|
# index is the single source of truth for which packs exist. With no index the
|
|
# interview offers essentials only (see `run_interview`).
|
|
|
|
#: 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 | ollama
|
|
winnow_base_url: str = ""
|
|
winnow_model: str = ""
|
|
winnow_api_key: str = ""
|
|
#: Ollama's native System One route (`engine.ollama`).
|
|
ollama_base_url: str = ""
|
|
ollama_model: str = ""
|
|
ollama_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)
|
|
|
|
# LXMF gateway: transcribe Sideband push-to-talk voice messages into
|
|
# commands (install `requirements/transcribe.txt`; faster-whisper only) and
|
|
# reply to a voice chat with a Piper voice message (install
|
|
# `requirements/tts.txt`; piper-tts + PyAV).
|
|
lxmf_voice: bool = False
|
|
lxmf_voice_reply: bool = True
|
|
|
|
# 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 load_pack_index(path: str | Path | None) -> list[tuple[str, str]]:
|
|
"""The interview's pack choices ``(key, label)`` from a pack-index JSON file.
|
|
|
|
The index repo (``semif-packs``) owns which packs exist; bootstrap clones it
|
|
and passes ``--pack-index FILE``. Each entry is ``{name, url, title?,
|
|
description?}``; the label is ``"<title> — <description>"`` (or the name).
|
|
Returns ``[]`` for a missing/unreadable index — the interview then offers
|
|
essentials only.
|
|
"""
|
|
if not path:
|
|
return []
|
|
try:
|
|
data = json.loads(Path(path).read_text())
|
|
except (OSError, ValueError):
|
|
return []
|
|
choices: list[tuple[str, str]] = []
|
|
for entry in data.get("packs", []) or []:
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
name = str(entry.get("name", "")).strip()
|
|
if not name:
|
|
continue
|
|
title = str(entry.get("title") or name).strip()
|
|
desc = str(entry.get("description") or "").strip()
|
|
choices.append((name, f"{title} — {desc}" if desc else title))
|
|
return choices
|
|
|
|
|
|
def run_interview(
|
|
*,
|
|
input_fn: Callable[[str], str] = input,
|
|
output: Callable[[str], None] = print,
|
|
interactive: bool = True,
|
|
prefill: Answers | None = None,
|
|
pack_choices: Sequence[tuple[str, str]] | 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. ``pack_choices`` is the offered pack
|
|
list (from the pack index); empty means essentials only.
|
|
"""
|
|
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 or an Ollama System One decision model."
|
|
)
|
|
answers.engine_provider = _ask_choice(
|
|
input_fn,
|
|
output,
|
|
"engine",
|
|
[
|
|
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
|
|
("winnow", "remote Winnow decision server"),
|
|
("ollama", "remote Ollama System One model (/v1/systemone)"),
|
|
],
|
|
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
|
|
)
|
|
elif answers.engine_provider == "ollama":
|
|
answers.ollama_base_url = _ask_text(
|
|
input_fn, output, " ollama base URL", "http://127.0.0.1:11434"
|
|
)
|
|
model = ""
|
|
while not model:
|
|
model = _ask_text(
|
|
input_fn, output, " ollama System One model (required)"
|
|
)
|
|
if not model:
|
|
output(" engine.ollama.model is required.")
|
|
answers.ollama_model = model
|
|
answers.ollama_api_key = _ask_text(
|
|
input_fn,
|
|
output,
|
|
" ollama API key (blank for a local server)",
|
|
"",
|
|
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("")
|
|
# The Ollama System One decision model does not generate text, so it
|
|
# cannot back the small `llm` task; only a real endpoint can.
|
|
_collect_llm(
|
|
input_fn,
|
|
output,
|
|
answers,
|
|
label="llm",
|
|
allow_semif=answers.engine_provider != "ollama",
|
|
)
|
|
output("")
|
|
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False)
|
|
|
|
# 3. Capability packs (the offered list comes from the pack index; the
|
|
# always-on base pack is never offered — it is included automatically).
|
|
output("")
|
|
output("Capabilities (skill packs)")
|
|
choices = [c for c in (pack_choices or []) if c[0] != BASE_PACK]
|
|
if choices:
|
|
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)",
|
|
choices,
|
|
default=[p for p in answers.packs if p != BASE_PACK],
|
|
)
|
|
else:
|
|
output(
|
|
" No pack index was provided, so only essentials (time, timers,\n"
|
|
" calculator) will be enabled. Pass --pack-index FILE to choose packs."
|
|
)
|
|
|
|
# 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,
|
|
)
|
|
|
|
# 5b. LXMF voice messages (Sideband push-to-talk).
|
|
if "lxmf" in answers.gateways:
|
|
output("")
|
|
output("LXMF voice messages")
|
|
output(
|
|
" Sideband can send push-to-talk voice messages. The agent can\n"
|
|
" transcribe them into commands, and reply to a voice chat with a\n"
|
|
" synthesized voice message (Piper)."
|
|
)
|
|
mode = _ask_choice(
|
|
input_fn,
|
|
output,
|
|
"lxmf voice",
|
|
[
|
|
("off", "ignore voice messages"),
|
|
("transcribe", "transcribe to commands, reply with text"),
|
|
("reply", "transcribe, and reply with a synthesized voice"),
|
|
],
|
|
3,
|
|
)
|
|
answers.lxmf_voice = mode in ("transcribe", "reply")
|
|
answers.lxmf_voice_reply = mode == "reply"
|
|
|
|
# 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"
|
|
)
|
|
elif answers.engine_provider == "ollama":
|
|
ollama = engine.setdefault("ollama", {})
|
|
if answers.ollama_base_url:
|
|
ollama["base_url"] = answers.ollama_base_url
|
|
ollama["model"] = answers.ollama_model
|
|
_set_secret_or_literal(
|
|
ollama, "api_key", answers.ollama_api_key, "engine_ollama_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)
|
|
# Sideband voice messages are transcribed only when the LXMF gateway is on
|
|
# and the answer opted in; needs faster-whisper (requirements/transcribe.txt).
|
|
# A voice reply adds Piper + PyAV (requirements/tts.txt).
|
|
voice_block = gateway.setdefault("lxmf", {}).setdefault("voice", {})
|
|
voice_block["enabled"] = bool("lxmf" in answers.gateways and answers.lxmf_voice)
|
|
voice_block["reply_with_voice"] = bool(answers.lxmf_voice_reply)
|
|
|
|
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.engine_provider == "ollama" and answers.ollama_api_key:
|
|
secrets["engine_ollama_api_key"] = answers.ollama_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,
|
|
# Packs that ship their own python deps (packs/<name>/requirements.txt);
|
|
# bootstrap pip-installs each. See PACKGEN.md, "Pack python deps".
|
|
"pack_requirements": [
|
|
p.name for p in packs if p.name in answers.packs and p.requirements_file
|
|
],
|
|
"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,
|
|
# faster-whisper only (no microphone stack): transcribe Sideband voice
|
|
# messages when the LXMF gateway is on and the answer opted in.
|
|
"install_transcribe": "lxmf" in answers.gateways and bool(answers.lxmf_voice),
|
|
# Piper + PyAV (no microphone stack): reply to a voice chat with a
|
|
# synthesized voice message when the LXMF gateway handles voice and the
|
|
# answer wants voice replies.
|
|
"install_lxmf_tts": (
|
|
"lxmf" in answers.gateways
|
|
and bool(answers.lxmf_voice)
|
|
and bool(answers.lxmf_voice_reply)
|
|
),
|
|
}
|
|
|
|
|
|
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,
|
|
"pack_requirements": [
|
|
p.name for p in packs if p.name in enabled and p.requirements_file
|
|
],
|
|
"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,
|
|
"install_transcribe": bool(
|
|
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
|
|
.get("voice", {}) or {})
|
|
.get("enabled")
|
|
),
|
|
"install_lxmf_tts": bool(
|
|
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
|
|
.get("voice", {}) or {})
|
|
.get("enabled")
|
|
)
|
|
and bool(
|
|
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
|
|
.get("voice", {}) or {})
|
|
.get("reply_with_voice", True)
|
|
),
|
|
}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# 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,
|
|
answers_out: str | None = None,
|
|
pack_index: str | None = None,
|
|
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. In
|
|
``answers_out`` mode it collects the answers and writes them as JSON to that
|
|
path (no config, no packs needed) — the bootstrap phase that precedes cloning
|
|
the selected packs. ``pack_index`` is the pack-index file whose entries the
|
|
interview offers (see `load_pack_index`).
|
|
"""
|
|
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
|
|
|
|
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
|
|
|
|
choices = load_pack_index(pack_index)
|
|
|
|
# Answers-only pass: collect and persist the answers, then stop. Bootstrap
|
|
# uses this to learn which packs to clone before config generation needs them.
|
|
if answers_out is not None:
|
|
if interview and not yes:
|
|
answers = run_interview(
|
|
input_fn=input_fn, output=output, interactive=True,
|
|
prefill=prefill, pack_choices=choices,
|
|
)
|
|
else:
|
|
answers = prefill or Answers.minimal()
|
|
out_path = Path(answers_out)
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
out_path.write_text(json.dumps(answers.to_dict(), indent=2) + "\n")
|
|
output("")
|
|
output("== answers captured")
|
|
_print_summary(answers, output)
|
|
return 0
|
|
|
|
if config_path.exists() and not force:
|
|
output(f"{config_path} already exists; leaving it alone (use --force)")
|
|
return 1
|
|
|
|
if interview and not yes:
|
|
answers = run_interview(
|
|
input_fn=input_fn, output=output, interactive=True,
|
|
prefill=prefill, pack_choices=choices,
|
|
)
|
|
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 '?'})"
|
|
if answers.engine_provider == "winnow"
|
|
else f"remote Ollama System One ({answers.ollama_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))
|