bootstrap: seed config.json once; move refs to committed pins.json

config.json is now per-machine USER config that no code writes: bootstrap
seeds it from config.example.json only when absent, then reads every
per-machine value from it. Flags override those values for the run only and
are never written back.

External refs (engine commit, GGUF url+sha256, HF tokenizer revision,
simplex-chat version/url+sha256) move out of config into a committed,
code-owned pins.json, so a git pull bump propagates on the next bootstrap
run instead of being frozen per machine. The agent reads engine
source/revision from pins.json and derives the GGUF path from engine.gguf_url
under .runtime/models/ (an explicit engine.gguf in config.json overrides it).

- config.example.json: drop all refs; ship the provisioned defaults
  (codegen.timeout 3600, gateway/bridge enabled, dashboard 127.0.0.1)
- scripts/bootstrap.sh: seed config.json if absent, read pins from pins.json
  and per-machine values from config.json, never write config.json; drop the
  flags that only existed to populate config.json; US-delimit read fields so
  empty values do not shift later fields
- semif_agent/cli.py: add load_pins / build_engine_config; load_config
  hard-errors when config.json is missing
- tests/integration + README/AGENTS updated
This commit is contained in:
gabby committed 2026-10-02 19:47:56 +00:00
1 parent 38cba33bbf
commit 43ece0cfd6
7 files changed
+294 -257

No files matched your search

+45 -34
View File
@@ -220,10 +220,16 @@ values are yours to choose.
## Git / sync ## Git / sync
- Push/pull from your git remote — never rsync/tar the code. - Push/pull from your git remote — never rsync/tar the code.
- **`config.json` is gitignored and per-machine** (hosts use different - **`config.json` is gitignored, per-machine, and required** (hosts use
engine/LLM paths and models). Copy `config.example.json` to `config.json` and different LLM/codegen endpoints and models). `scripts/bootstrap.sh` seeds it
edit. `data/decisions.jsonl`, `data/runs.jsonl`, and `data/drafts/` are from `config.example.json` once (only when absent) and **nothing writes it
runtime artifacts and gitignored too. afterwards — only a human edits `config.json`**. `data/decisions.jsonl`,
`data/runs.jsonl`, and `data/drafts/` are runtime artifacts and gitignored too.
- **`pins.json` is committed and code-owned** — the single home for every
external ref (SemIf commit, GGUF url+sha256, HF tokenizer revision,
simplex-chat version/url+sha256). These are bumped by a git change and picked
up on the next bootstrap run; they are deliberately NOT in `config.json` (a
ref replaced on every update is not per-machine user config).
- Decision rows logged before the `run_id` threading landed show up under - Decision rows logged before the `run_id` threading landed show up under
run_id `"?"` in the dashboard — that's expected, not a bug. run_id `"?"` in the dashboard — that's expected, not a bug.
@@ -453,16 +459,19 @@ CLI, unit tests (24) + integration tests (2).
### Provisioning (`scripts/bootstrap.sh`) ### Provisioning (`scripts/bootstrap.sh`)
- 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 a checkout (register its SSH key on your git host first), then run
`scripts/bootstrap.sh --llm-url <local-ollama> --codegen-url <codegen-ollama> `scripts/bootstrap.sh`. With no `config.json` yet it seeds one from
--llm-model <small-model> --codegen-model <code-capable-model>`. `config.example.json`; edit that to set `llm.model`/`codegen.model` and the
The script must be run from a checkout — it reads pins from that checkout's endpoints. Flags (`--llm-url`, `--codegen-url`, `--llm-model`,
`config.example.json` and never re-clones the agent repo (only the SemIf `--codegen-model`) override the values read from `config.json` **for that run
engine and the simplex-chat binary). Idempotent and rerunnable; every stage only** and are never written back. The script must be run from a checkout —
no-ops on existing state, so it also boots an unknown-state machine. It it reads pins from that checkout's `pins.json` and never re-clones the agent
installs **no ollama**: `llm` is the local ollama (bootstrap pulls repo (only the SemIf engine and the simplex-chat binary). Idempotent and
`llm.model`), `codegen` may point at a peer host. It WARNs (never auto-pulls) rerunnable; every stage no-ops on existing state, so it also boots an
if the remote codegen host is missing its model. unknown-state machine. It installs **no ollama**: `llm` is the local ollama
(bootstrap pulls `llm.model` if configured), `codegen` may point at a peer
host. It WARNs (never auto-pulls) if the remote codegen host is missing its
model, and WARNs if `llm.model`/`codegen.model` are unset.
- **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/`), so an end user can find and debug the whole stack in `simplex/`, `systemd/`), so an end user can find and debug the whole stack in
@@ -470,39 +479,41 @@ CLI, unit tests (24) + integration tests (2).
(`~/.ssh`) and the real systemd user dir + linger (the rendered units are (`~/.ssh`) and the real systemd user dir + linger (the rendered units are
stored in `.runtime/systemd/` and symlinked into `~/.config/systemd/user/`). stored in `.runtime/systemd/` and symlinked into `~/.config/systemd/user/`).
See the "Code principles" containment rule. See the "Code principles" containment rule.
- All pins are read from `config.example.json`: the `engine` block - All pins are read from the committed `pins.json`: the `engine` block
(`semif_repo` public GitHub `TheoLeeCJ/SemIf`, `semif_ref` pinned commit, (`semif_repo` public GitHub `TheoLeeCJ/SemIf`, `semif_ref` pinned commit,
`gguf_url`/`gguf_sha256`, HF tokenizer `source`/`revision`) and the `gguf_url`/`gguf_sha256`, HF tokenizer `source`/`revision`) and the
`simplex_chat` block (`version`, `bin_url`, `sha256`, `port`, `simplex_chat` block (`version`, `bin_url`, `sha256`). Per-machine
`display_name`). The python dep pins live in `requirements/staging.txt` `simplex_chat` ports/display names stay in `config.json`. The python dep pins
(committed, one versioned artifact — every host provisions from it). live in `requirements/staging.txt` (committed, one versioned artifact — every
**Maintenance**: bump the pins in `config.example.json` / host provisions from it). The agent reads `engine.source`/`revision` from
`requirements/staging.txt`, rerun the script, re-run the integration tests. `pins.json` and derives the GGUF path from `engine.gguf_url` under
The script never guesses. `.runtime/models/` (an explicit `engine.gguf` in `config.json` overrides it).
**Maintenance**: bump the pins in `pins.json` / `requirements/staging.txt`,
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.
- Generates `config.json` with `llm.base_url` = `--llm-url`, `codegen.base_url` - Seeds `config.json` from `config.example.json` (only when absent) and **never
= `--codegen-url` (`codegen.timeout: 3600` for a LAN), the model names from writes it again** — only a human edits `config.json`. `config.example.json`
`--llm-model`/`--codegen-model`, a repo-relative `.runtime/models` GGUF path, ships the provisioned defaults, so a seeded `config.json` already has
and a backup of any prior file. `--threads N` overrides engine threads; `codegen.timeout: 3600`, the SimpleX gateway enabled
`--copy-data SRC` rsyncs a prior host's `data/` for continuity; (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the
`--public-dashboard` binds the dashboard to `0.0.0.0`. standalone forwarding bridge enabled (`bridges.simplex.enabled = true`,
It also enables the SimpleX gateway (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.forward_port`, top-level `simplex_bridge_url`);
`ws_url` from `simplex_chat.port`) and the standalone forwarding bridge the operator sets `llm.model`/`llm.base_url` and `codegen.model`/
(`bridges.simplex.enabled = true`, `ws_url` from `simplex_chat.forward_port`, `codegen.base_url`. Bootstrap renders/enables four user services:
top-level `simplex_bridge_url`), rendering/enabling 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`), `semif-gateway.service`
(`.runtime/venv/bin/python -m semif_agent.cli gateway`), (`.runtime/venv/bin/python -m semif_agent.cli gateway`),
`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`) and `semif-bridge.service`
(`.runtime/venv/bin/python -m semif_agent.cli bridge`). `--simplex-allowed-users (`.runtime/venv/bin/python -m semif_agent.cli bridge`). The gateway allowlist
CSV` / `--simplex-home-channel ID` / `--simplex-display-name NAME` populate (`gateway.simplex.allowed_users`) and fallback (`home_channel`) are
the gateway allowlist/fallback/identity; 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.
Bootstrap then runs `scripts/simplex-address.py` to create/print the command Bootstrap then runs `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 downloads the 2.8G GGUF and builds `llama-cpp-python` from source
+31 -18
View File
@@ -384,7 +384,8 @@ tests/ stdlib unit tests + tests/integration (real engine + LLM)
SKILL.md the contract fed to the skill-body codegen model SKILL.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
AGENTS.md the operational guide (read this before touching code) AGENTS.md the operational guide (read this before touching code)
config.example.json per-machine config template config.example.json per-machine config template (seeded to config.json once)
pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs
local/ gitignored: this deployment's notes (hosts, addresses, models) local/ gitignored: this deployment's notes (hosts, addresses, models)
``` ```
@@ -418,13 +419,14 @@ build enables it), not ollama.
On a fresh Ubuntu machine, from a checkout of this repo: On a fresh Ubuntu machine, from a checkout of this repo:
```sh ```sh
scripts/bootstrap.sh \ scripts/bootstrap.sh
--llm-url http://127.0.0.1:11434 \
--codegen-url http://<codegen-host>:11434 \
--llm-model <small-model> \
--codegen-model <code-capable-model>
``` ```
With no `config.json` yet, the script seeds one from `config.example.json`; edit
it to set `llm.model`/`codegen.model` (and the endpoints). Flags override those
values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`,
`--codegen-model` — and are never written back to `config.json`.
The script is idempotent (every stage no-ops on existing state) and: The script is idempotent (every stage no-ops on existing state) and:
1. installs system prereqs + enables linger; 1. installs system prereqs + enables linger;
@@ -435,18 +437,22 @@ The script is idempotent (every stage no-ops on existing state) and:
4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`; 4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`;
5. pre-fetches the HF tokenizer into `.runtime/hf/`; 5. pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads and sha256-verifies the pinned `simplex-chat` binary; 6. downloads and sha256-verifies the pinned `simplex-chat` binary;
7. writes `config.json` (paths, LLM/codegen URLs, dashboard, SimpleX); 7. seeds `config.json` from `config.example.json` **only if it does not already
exist** — it never rewrites `config.json` (only a human edits that file);
8. renders and enables systemd **user** units: 8. renders and enables systemd **user** units:
`semif-simplex` (bot daemon), `semif-gateway` (agent gateway), `semif-simplex` (bot daemon), `semif-gateway` (agent gateway),
`semif-simplex-forward` (the bridge's own daemon), `semif-bridge`; `semif-simplex-forward` (the bridge's own daemon), `semif-bridge`;
9. prints the bot's SimpleX contact address. 9. prints the bot's SimpleX contact address.
Useful flags: `--threads N`, `--public-dashboard`, `--copy-data SRC`, Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`,
`--simplex-allowed-users CSV`, `--simplex-home-channel ID`, `--copy-data SRC`) override the values read from `config.json` for that run only.
`--simplex-display-name NAME`. Run `scripts/bootstrap.sh -h` for the full list. Run `scripts/bootstrap.sh -h` for the full list.
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`, 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. 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)
@@ -458,22 +464,29 @@ 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`, `requirements/staging.txt`, GGUF,
tokenizer cache), then copy `config.example.json` to `config.json` and adjust tokenizer cache), then create `config.json` from the template and adjust paths:
paths.
### Configuration
`config.json` is **gitignored and per-machine**. Copy the template and edit:
```sh ```sh
cp config.example.json config.json cp config.example.json config.json
``` ```
### Configuration
`config.json` is **gitignored, per-machine, and required** — the agent refuses
to start without it. `scripts/bootstrap.sh` seeds it from `config.example.json`
once; afterwards only a human edits it (nothing writes `config.json`). Pinned
external refs live in the committed `pins.json`, so `config.json` holds only
per-machine settings:
```sh
cp config.example.json config.json # if not already created by bootstrap
```
Key blocks: Key blocks:
| Block | What it controls | | Block | What it controls |
| --- | --- | | --- | --- |
| `engine` | SemIf source/revision, GGUF path, context, threads | | `engine` | per-machine engine settings: backend, context, threads, optional GGUF path override (refs come from `pins.json`) |
| `llm` | small model endpoint that authors new category/skill title + description | | `llm` | small model endpoint that authors new category/skill title + description |
| `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget |
| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
@@ -483,7 +496,7 @@ Key blocks:
| `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call | | `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call |
| `simplex_chat` | pinned simplex-chat binary + gateway/forward ports | | `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port | | `dashboard` | bind host/port |
`llm.model` and `codegen.model` are **required** (no default): set each to a `llm.model` and `codegen.model` are **required** (no default): set each to a
+9 -18
View File
@@ -1,5 +1,5 @@
{ {
"_comment": "Per-machine config. config.json is gitignored; copy this file to config.json and adjust paths. Every machine keeps its own config.json.", "_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json.",
"tau": 0.6, "tau": 0.6,
"max_reentries": 3, "max_reentries": 3,
"creation_approval": false, "creation_approval": false,
@@ -10,19 +10,13 @@
}, },
"queue": {"max_size": 100, "age_rate": 0.01}, "queue": {"max_size": 100, "age_rate": 0.01},
"engine": { "engine": {
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
"backend": "llamacpp", "backend": "llamacpp",
"source": "Qwen/Qwen3.5-4B",
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a",
"gguf": ".runtime/models/Qwen3.5-4B-Q4_K_M.gguf",
"gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
"gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983",
"semif_repo": "https://github.com/TheoLeeCJ/SemIf.git",
"semif_ref": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37",
"context_tokens": 4096, "context_tokens": 4096,
"threads": 8 "threads": 8
}, },
"llm": { "llm": {
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).", "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama", "provider": "ollama",
"base_url": "http://localhost:11434/v1", "base_url": "http://localhost:11434/v1",
"model": "", "model": "",
@@ -41,14 +35,14 @@
"disable_thinking": true "disable_thinking": true
}, },
"codegen": { "codegen": {
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap sets base_url from --codegen-url); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).", "_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama", "provider": "ollama",
"base_url": "http://localhost:11434/v1", "base_url": "http://localhost:11434/v1",
"model": "", "model": "",
"api_key": "", "api_key": "",
"api_key_env": "", "api_key_env": "",
"user_agent": "", "user_agent": "",
"timeout": 1200, "timeout": 3600,
"stream": true, "stream": true,
"idle_warn": 60, "idle_warn": 60,
"idle_timeout": 180, "idle_timeout": 180,
@@ -104,10 +98,7 @@
"trace": "data/runs.jsonl", "trace": "data/runs.jsonl",
"category_registry": "data/categories.json", "category_registry": "data/categories.json",
"simplex_chat": { "simplex_chat": {
"_comment": "Pinned simplex-chat daemon(s). The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh downloads this exact binary (sha256 verified) into .runtime/bin/ and renders both units. Bump version/bin_url/sha256 together. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.", "_comment": "Per-machine simplex-chat daemon settings. The pinned binary (version/bin_url/sha256) lives in the committed pins.json, not here. The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh renders both units from these values. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
"version": "v7.0.3",
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0",
"port": 5226, "port": 5226,
"display_name": "semif", "display_name": "semif",
"forward_port": 5228, "forward_port": 5228,
@@ -117,7 +108,7 @@
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.", "_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
"simplex": { "simplex": {
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills use the top-level `simplex_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", "_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills use the top-level `simplex_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
"enabled": false, "enabled": true,
"host": "127.0.0.1", "host": "127.0.0.1",
"port": 5227, "port": 5227,
"token": "", "token": "",
@@ -131,7 +122,7 @@
"gateway": { "gateway": {
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.", "_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.",
"simplex": { "simplex": {
"enabled": false, "enabled": true,
"ws_url": "ws://127.0.0.1:5226", "ws_url": "ws://127.0.0.1:5226",
"allowed_users": [], "allowed_users": [],
"allow_all_users": false, "allow_all_users": false,
@@ -142,5 +133,5 @@
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
} }
}, },
"dashboard": {"port": 8765, "host": "0.0.0.0"} "dashboard": {"port": 8765, "host": "127.0.0.1"}
} }
+16
View File
@@ -0,0 +1,16 @@
{
"_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, and the simplex-chat binary. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run. They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.",
"engine": {
"semif_repo": "https://github.com/TheoLeeCJ/SemIf.git",
"semif_ref": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37",
"gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
"gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983",
"source": "Qwen/Qwen3.5-4B",
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
},
"simplex_chat": {
"version": "v7.0.3",
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
}
}
+132 -164
View File
@@ -6,10 +6,17 @@
# title/description model runs on this machine's local ollama (bootstrap pulls # title/description model runs on this machine's local ollama (bootstrap pulls
# it); codegen may point at a remote ollama host. This script installs NO ollama. # it); codegen may point at a remote ollama host. This script installs NO ollama.
# #
# Must be run from a semif-agent checkout (it reads pins from this checkout's # Must be run from a semif-agent checkout. The checkout is used as-is and never
# config.example.json); the checkout is used as-is and never re-cloned — only # re-cloned — only the SemIf engine and the simplex-chat binary are fetched.
# the SemIf engine and the simplex-chat binary are fetched. Clone the agent # Clone the agent repo first (its SSH key must be registered on your git host).
# repo first (its SSH key must be registered on your git host). #
# config.json is the per-machine USER config and this script NEVER writes it. It
# seeds config.json from config.example.json only when config.json is absent,
# then reads every per-machine value from config.json; only a human edits
# config.json afterwards. Pinned external refs (SemIf commit, GGUF url+sha256,
# HF tokenizer revision, simplex-chat version/url+sha256) live in the committed
# pins.json and the python dep pins in requirements/staging.txt — bump those
# (via git) and rerun to upgrade.
# #
# 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:
@@ -20,45 +27,31 @@
# 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.
# #
# Pins (SemIf commit, GGUF url+sha256, simplex-chat url+sha256) are read from # Flags override the values read from config.json FOR THIS RUN ONLY; nothing is
# config.example.json's engine/simplex_chat blocks, and the python dep pins # written back to config.json.
# from requirements/staging.txt — all committed here and the single source of
# truth; bump those and rerun to upgrade.
# #
# Usage: # Usage:
# scripts/bootstrap.sh --llm-url URL --codegen-url URL --llm-model MODEL # scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL]
# --codegen-model MODEL [--threads N] [--copy-data SRC] # [--codegen-model MODEL] [--copy-data SRC] [-h]
# [--public-dashboard] [--simplex-allowed-users CSV]
# [--simplex-home-channel X] [--simplex-display-name NAME] [-h]
# #
# Run as the human user; sudo is used internally for system bits. # Run as the human user; sudo is used internally for system bits.
set -euo pipefail set -euo pipefail
LLM_URL="http://127.0.0.1:11434" LLM_URL=""
CODEGEN_URL="" CODEGEN_URL=""
LLM_MODEL="" LLM_MODEL=""
CODEGEN_MODEL="" CODEGEN_MODEL=""
THREADS=""
COPY_DATA="" COPY_DATA=""
PUBLIC_DASHBOARD=0
SIMPLEX_ALLOWED_USERS=""
SIMPLEX_HOME_CHANNEL=""
SIMPLEX_DISPLAY_NAME=""
usage() { usage() {
sed -n '2,32p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' sed -n '2,35p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
echo echo
echo " --llm-url URL ollama API for the small title/description model (default: $LLM_URL; this machine)" echo " --llm-url URL override llm.base_url from config.json for this run (else config.json, else http://127.0.0.1:11434)"
echo " --codegen-url URL ollama API for codegen skill bodies (required; may be remote)" echo " --codegen-url URL override codegen.base_url from config.json for this run"
echo " --llm-model MODEL model the llm endpoint serves (required; pulled if the local ollama lacks it)" echo " --llm-model MODEL override llm.model from config.json for this run (pulled if the local ollama lacks it)"
echo " --codegen-model MODEL code-capable model the codegen endpoint serves (required)" echo " --codegen-model MODEL override codegen.model from config.json for this run"
echo " --threads N engine threads for config.json (default: config.example value)" 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 " -h this help"
echo " --public-dashboard bind dashboard to 0.0.0.0 instead of 127.0.0.1"
echo " --simplex-allowed-users CSV comma-separated contactIds/display names the gateway accepts"
echo " --simplex-home-channel ID gateway fallback channel for unsolicited messages"
echo " --simplex-display-name NAME simplex-chat bot display name (default: config.example value)"
echo " -h this help"
exit "${1:-0}" exit "${1:-0}"
} }
@@ -68,12 +61,7 @@ while [[ $# -gt 0 ]]; do
--codegen-url) CODEGEN_URL="$2"; shift 2 ;; --codegen-url) CODEGEN_URL="$2"; shift 2 ;;
--llm-model) LLM_MODEL="$2"; shift 2 ;; --llm-model) LLM_MODEL="$2"; shift 2 ;;
--codegen-model) CODEGEN_MODEL="$2"; shift 2 ;; --codegen-model) CODEGEN_MODEL="$2"; shift 2 ;;
--threads) THREADS="$2"; shift 2 ;;
--copy-data) COPY_DATA="$2"; shift 2 ;; --copy-data) COPY_DATA="$2"; shift 2 ;;
--public-dashboard) PUBLIC_DASHBOARD=1; shift ;;
--simplex-allowed-users) SIMPLEX_ALLOWED_USERS="$2"; shift 2 ;;
--simplex-home-channel) SIMPLEX_HOME_CHANNEL="$2"; shift 2 ;;
--simplex-display-name) SIMPLEX_DISPLAY_NAME="$2"; shift 2 ;;
-h|--help) usage 0 ;; -h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;; *) echo "unknown option: $1" >&2; usage 1 ;;
esac esac
@@ -81,6 +69,8 @@ done
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EXAMPLE="$REPO_ROOT/config.example.json" EXAMPLE="$REPO_ROOT/config.example.json"
CONFIG="$REPO_ROOT/config.json"
PINS="$REPO_ROOT/pins.json"
RUNTIME="$REPO_ROOT/.runtime" RUNTIME="$REPO_ROOT/.runtime"
VENV="$RUNTIME/venv" VENV="$RUNTIME/venv"
@@ -98,70 +88,85 @@ if [[ ! -f "$EXAMPLE" ]]; then
echo "config.example.json not found at $EXAMPLE — run from a semif-agent checkout" >&2 echo "config.example.json not found at $EXAMPLE — run from a semif-agent checkout" >&2
exit 1 exit 1
fi fi
if [[ ! -f "$PINS" ]]; then
echo "pins.json not found at $PINS — run from a semif-agent checkout" >&2
exit 1
fi
# --- read pins from config.example.json ------------------------------------ # config.json is per-machine USER config. Seed it once from the template, then
read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \ # never write it again — only a human edits config.json.
SIMPLEX_BIN_URL SIMPLEX_SHA256 SIMPLEX_PORT SIMPLEX_DISPLAY \ if [[ ! -f "$CONFIG" ]]; then
SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY EXAMPLE_LLM_MODEL \ echo "== seeding config.json from config.example.json (edit it to configure this machine)"
EXAMPLE_CODEGEN_MODEL < <( cp "$EXAMPLE" "$CONFIG"
python3 - "$EXAMPLE" <<'PY' fi
# --- 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).
IFS=$'\x1f' read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \
SIMPLEX_BIN_URL SIMPLEX_SHA256 < <(
python3 - "$PINS" <<'PY'
import json, sys import json, sys
cfg = json.load(open(sys.argv[1])) pins = json.load(open(sys.argv[1]))
e = cfg["engine"] e = pins["engine"]
s = cfg.get("simplex_chat", {}) s = pins.get("simplex_chat", {})
print( print("\x1f".join([
" ".join( str(e.get("semif_repo", "")),
[ str(e.get("semif_ref", "")),
str(e.get("semif_repo", "")), str(e.get("gguf_url", "")),
str(e.get("semif_ref", "")), str(e.get("gguf_sha256", "")),
str(e.get("gguf_url", "")), str(e.get("source", "")),
str(e.get("gguf_sha256", "")), str(e.get("revision", "")),
str(e.get("source", "")), str(s.get("bin_url", "")),
str(e.get("revision", "")), str(s.get("sha256", "")),
str(s.get("bin_url", "")), ]))
str(s.get("sha256", "")),
str(s.get("port", "")),
str(s.get("display_name", "")),
str(s.get("forward_port", "")),
str(s.get("forward_display_name", "")),
str(cfg.get("llm", {}).get("model", "")),
str(cfg.get("codegen", {}).get("model", "")),
]
)
)
PY PY
) )
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 $EXAMPLE (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" || -z "$SIMPLEX_PORT" ]]; then if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then
echo "simplex_chat pins missing in $EXAMPLE (bin_url/sha256/port)" >&2 echo "simplex_chat pins missing in $PINS (bin_url/sha256)" >&2
exit 1 exit 1
fi fi
# Model names are deployment-specific and user-supplied: prefer the CLI flag, # --- read per-machine values from config.json (flags override for this run) --
# else fall back to config.example.json. There is deliberately no default. IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_CODEGEN_URL CFG_CODEGEN_MODEL \
LLM_MODEL="${LLM_MODEL:-$EXAMPLE_LLM_MODEL}" SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <(
CODEGEN_MODEL="${CODEGEN_MODEL:-$EXAMPLE_CODEGEN_MODEL}" python3 - "$CONFIG" <<'PY'
if [[ -z "$CODEGEN_URL" ]]; then import json, sys
echo "--codegen-url is required (the ollama API for codegen skill bodies)" >&2 cfg = json.load(open(sys.argv[1]))
exit 1 s = cfg.get("simplex_chat", {})
fi def strip_v1(u):
if [[ -z "$LLM_MODEL" ]]; then u = str(u or "").rstrip("/")
echo "--llm-model is required (or set llm.model in config.example.json)" >&2 return u[:-3] if u.endswith("/v1") else u
exit 1 print("\x1f".join([
fi strip_v1(cfg.get("llm", {}).get("base_url")),
if [[ -z "$CODEGEN_MODEL" ]]; then str(cfg.get("llm", {}).get("model", "") or ""),
echo "--codegen-model is required (or set codegen.model in config.example.json)" >&2 strip_v1(cfg.get("codegen", {}).get("base_url")),
exit 1 str(cfg.get("codegen", {}).get("model", "") or ""),
fi str(s.get("port", "")),
str(s.get("display_name", "") or ""),
str(s.get("forward_port", "")),
str(s.get("forward_display_name", "") or ""),
]))
PY
)
if [[ -n "$SIMPLEX_DISPLAY_NAME" ]]; then # A flag overrides config.json for this run only; config.json is never touched.
SIMPLEX_DISPLAY="$SIMPLEX_DISPLAY_NAME" LLM_URL="${LLM_URL:-${CFG_LLM_URL:-http://127.0.0.1:11434}}"
CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}"
LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}"
CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}"
if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then
echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2
exit 1
fi fi
SIMPLEX_DISPLAY="${SIMPLEX_DISPLAY:-semif}" SIMPLEX_DISPLAY="${SIMPLEX_DISPLAY:-semif}"
SIMPLEX_FORWARD_DISPLAY="${SIMPLEX_FORWARD_DISPLAY:-semif-forward}"
# Native ollama API bases (no /v1) for tags/pull; the clients use /v1. # Native ollama API bases (no /v1) for tags/pull; the clients use /v1.
LLM_API="${LLM_URL%/v1}"; LLM_API="${LLM_API%/}" LLM_API="${LLM_URL%/v1}"; LLM_API="${LLM_API%/}"
@@ -274,57 +279,9 @@ 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)"
# --- stage 7: config.json ----------------------------------------------------------- # config.json is USER config: seeded above if absent, read for per-machine values,
if [[ -f "$REPO_ROOT/config.json" ]]; then # and never written by this script. Edit config.json to change endpoints, models,
cp "$REPO_ROOT/config.json" "$REPO_ROOT/config.json.bak.$(date +%s)" # ports, the dashboard bind, or the gateway allowlist.
fi
echo "== writing config.json (llm -> $LLM_URL, codegen -> $CODEGEN_URL, runtime -> $RUNTIME)"
python3 - "$REPO_ROOT/config.example.json" "$REPO_ROOT/config.json" "$THREADS" "$LLM_URL" "$CODEGEN_URL" \
"$([ "$PUBLIC_DASHBOARD" = 1 ] && echo 0.0.0.0 || echo 127.0.0.1)" \
"$REPO_ROOT" "$SIMPLEX_ALLOWED_USERS" "$SIMPLEX_HOME_CHANNEL" "$SIMPLEX_DISPLAY" \
"$LLM_MODEL" "$CODEGEN_MODEL" <<'PY'
import json, os, sys
(example, out, threads, llm_url, codegen_url, dash_host, repo,
allowed_csv, home_channel, display, llm_model, codegen_model) = sys.argv[1:]
cfg = json.load(open(example))
eng = cfg["engine"]
runtime = os.path.join(repo, ".runtime")
eng["gguf"] = os.path.join(runtime, "models", os.path.basename(eng["gguf_url"]))
if threads and threads != "__example__":
eng["threads"] = int(threads)
# The clients hit {base_url}/chat/completions on ollama's OpenAI-compat path,
# which lives under /v1. The native API (/api/tags, /api/show) has no /v1.
def v1(url):
url = url.rstrip("/")
return url if url.endswith("/v1") else url + "/v1"
cfg["llm"]["base_url"] = v1(llm_url)
cfg["llm"]["model"] = llm_model
cfg["codegen"]["base_url"] = v1(codegen_url)
cfg["codegen"]["model"] = codegen_model
cfg["codegen"]["timeout"] = 3600
cfg.setdefault("simplex_chat", {})["display_name"] = display
cfg.setdefault("dashboard", {})["port"] = 8765
cfg["dashboard"]["host"] = dash_host
allowed = [u.strip() for u in allowed_csv.split(",") if u.strip()]
simplex = cfg.setdefault("gateway", {}).setdefault("simplex", {})
simplex["enabled"] = True
simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}"
simplex["allowed_users"] = allowed
simplex["home_channel"] = home_channel
# The standalone SimpleX forwarding bridge owns its own daemon/profile
# (simplex_chat.forward_port), separate from the command gateway, and serves the
# invite-link / read / send HTTP API skills use. Expose its URL as the top-level
# `simplex_bridge_url` so the data-contract config search auto-populates it, and
# mirror its optional shared secret as `simplex_bridge_token` for the auth header.
bridge = cfg.setdefault("bridges", {}).setdefault("simplex", {})
bridge_port = int(bridge.get("port", 5227))
bridge["enabled"] = True
bridge["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('forward_port', 5228)}"
cfg["simplex_bridge_url"] = f"http://127.0.0.1:{bridge_port}"
cfg["simplex_bridge_token"] = bridge.get("token", "") or ""
simplex.pop("bridge", None) # legacy key; forwarding is a separate service now
json.dump(cfg, open(out, "w"), indent=2)
PY
# --- stage 8: systemd user units ----------------------------------------------------- # --- stage 8: systemd user units -----------------------------------------------------
render_unit() { render_unit() {
@@ -433,43 +390,51 @@ echo "== verifying imports"
# The small self-assessment model runs on this machine's local ollama; ensure it # The small self-assessment model runs on this machine's local ollama; ensure it
# is pulled so assess/elicitation/fidelity work without a remote dependency. # is pulled so assess/elicitation/fidelity work without a remote dependency.
echo "== llm ollama ($LLM_API), model $LLM_MODEL" if [[ -z "$LLM_MODEL" ]]; then
if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then echo "WARN: llm.model is not set in config.json — set it (and codegen.model) before starting the agent" >&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
else else
LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)" echo "== llm ollama ($LLM_API), model $LLM_MODEL"
if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then
echo "llm model $LLM_MODEL: present" 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
else else
echo "== pulling llm model $LLM_MODEL from $LLM_API" LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)"
if ! curl -sf --max-time 3600 "$LLM_API/api/pull" -H 'Content-Type: application/json' \ if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then
-d "{\"model\":\"$LLM_MODEL\",\"stream\":false}" >/dev/null; then echo "llm model $LLM_MODEL: present"
echo "WARN: /api/pull failed; trying the ollama CLI" >&2 else
if command -v ollama >/dev/null 2>&1; then echo "== pulling llm model $LLM_MODEL from $LLM_API"
ollama pull "$LLM_MODEL" || echo "WARN: could not pull $LLM_MODEL" >&2 if ! curl -sf --max-time 3600 "$LLM_API/api/pull" -H 'Content-Type: application/json' \
else -d "{\"model\":\"$LLM_MODEL\",\"stream\":false}" >/dev/null; then
echo "WARN: could not pull $LLM_MODEL (no ollama CLI)" >&2 echo "WARN: /api/pull failed; trying the ollama CLI" >&2
if command -v ollama >/dev/null 2>&1; then
ollama pull "$LLM_MODEL" || echo "WARN: could not pull $LLM_MODEL" >&2
else
echo "WARN: could not pull $LLM_MODEL (no ollama CLI)" >&2
fi
fi fi
fi fi
fi # The OpenAI-compat chat path is what llm actually hits; probe it explicitly.
# The OpenAI-compat chat path is what llm actually hits; probe it explicitly. LLM_V1_OK="$(curl -sf --max-time 60 "$LLM_V1/chat/completions" -H 'Content-Type: application/json' \
LLM_V1_OK="$(curl -sf --max-time 60 "$LLM_V1/chat/completions" -H 'Content-Type: application/json' \ -d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false,\"options\":{\"num_predict\":1}}" || true)"
-d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false,\"options\":{\"num_predict\":1}}" || true)" if grep -qE 'chatcmpl|"choices"' <<<"$LLM_V1_OK"; then
if grep -qE 'chatcmpl|"choices"' <<<"$LLM_V1_OK"; then echo "llm /v1/chat/completions ($LLM_MODEL): OK"
echo "llm /v1/chat/completions ($LLM_MODEL): OK" else
else echo "WARN: local llm /v1/chat/completions returned no completion" >&2
echo "WARN: local llm /v1/chat/completions returned no completion" >&2 fi
fi fi
fi fi
# Codegen is the larger model, possibly on a remote host. Warn only — never auto-pull. # Codegen is the larger model, possibly on a remote host. Warn only — never auto-pull.
echo "== codegen ollama ($CODEGEN_API)" if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then
CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)" echo "== codegen ollama ($CODEGEN_API)"
if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)"
echo "codegen serves $CODEGEN_MODEL: OK" if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then
echo "codegen serves $CODEGEN_MODEL: OK"
else
echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2
fi
else else
echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2 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
@@ -483,6 +448,9 @@ fi
cat <<EOF cat <<EOF
Done. Next steps: Done. Next steps:
1. Edit config.json — set llm.model/llm.base_url and codegen.model/codegen.base_url.
bootstrap.sh seeded config.json from config.example.json (if it was absent)
and NEVER rewrites it; only you edit config.json.
cd "$REPO_ROOT" cd "$REPO_ROOT"
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)
+52 -11
View File
@@ -116,28 +116,69 @@ def _provider_endpoint(cfg: dict, default_base: str) -> dict:
def load_config(path: str = "config.json") -> dict: def load_config(path: str = "config.json") -> dict:
"""Load config.json and anchor its runtime paths to the checkout root. """Load config.json and anchor its runtime paths to the checkout root.
config.json is the per-machine user config and is required: bootstrap.sh
seeds it from config.example.json once, and only a human edits it. There is
no in-code fallback — a missing config.json is a hard error.
Path-valued keys (`skill_seeds`, `skill_bodies`, `category_registry`, `log`, Path-valued keys (`skill_seeds`, `skill_bodies`, `category_registry`, `log`,
`trace`) resolve against REPO_ROOT, not the process cwd, so a fresh clone `trace`) resolve against REPO_ROOT, not the process cwd, so a fresh clone
loads its committed seeds and writes runtime artifacts into the checkout no loads its committed seeds and writes runtime artifacts into the checkout no
matter where the CLI is invoked from. Absolute values pass through untouched. matter where the CLI is invoked from. Absolute values pass through untouched.
""" """
config = json.loads(Path(path).read_text()) config_path = Path(path)
if not config_path.is_file():
raise SystemExit(
f"config.json not found at {config_path} — run scripts/bootstrap.sh "
f"to seed it from config.example.json, then configure it"
)
config = json.loads(config_path.read_text())
for key in _PATH_KEYS: for key in _PATH_KEYS:
config[key] = _anchor_path(config.get(key) or _PATH_DEFAULTS[key]) config[key] = _anchor_path(config.get(key) or _PATH_DEFAULTS[key])
return config return config
def build_scheduler(config: dict) -> tuple[Scheduler, dict]: def load_pins(path: str | None = None) -> dict:
engine = SemIfEngine( """Load the committed pin manifest (pins.json) that owns every external ref.
EngineConfig(
backend=config.get("engine", {}).get("backend", "llamacpp"), Pins are code, not per-machine config: the SemIf engine commit, GGUF
source=config.get("engine", {}).get("source", ""), url+sha256, HF tokenizer revision, and simplex-chat version/url+sha256 live
revision=config.get("engine", {}).get("revision", ""), in pins.json so a `git pull` bump propagates on the next bootstrap run
gguf=config.get("engine", {}).get("gguf", ""), instead of being frozen in each machine's config.json.
context_tokens=int(config.get("engine", {}).get("context_tokens", 4096)), """
threads=config.get("engine", {}).get("threads"), pins_path = Path(path) if path else REPO_ROOT / "pins.json"
) if not pins_path.is_file():
raise SystemExit(f"pins.json not found at {pins_path}")
return json.loads(pins_path.read_text())
def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
"""Engine settings for a run: per-machine tuning from config.json, pinned
refs from pins.json.
`engine.backend`/`context_tokens`/`threads` are per-machine config. The
tokenizer source/revision and the GGUF are pins; the GGUF path is derived
from the pin's filename under `.runtime/models/`, unless config.json sets an
explicit `engine.gguf` override.
"""
pins = load_pins() if pins is None else pins
eng = config.get("engine", {}) or {}
pin_eng = pins.get("engine", {}) or {}
override = eng.get("gguf")
gguf = _anchor_path(override) if override else str(
REPO_ROOT / ".runtime" / "models" / os.path.basename(pin_eng.get("gguf_url", ""))
) )
return EngineConfig(
backend=eng.get("backend", "llamacpp"),
source=pin_eng.get("source", ""),
revision=pin_eng.get("revision", ""),
gguf=gguf,
context_tokens=int(eng.get("context_tokens", 4096)),
threads=eng.get("threads"),
)
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
engine = SemIfEngine(build_engine_config(config))
llm_cfg = config.get("llm", {}) or {} llm_cfg = config.get("llm", {}) or {}
llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower() llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient
+9 -12
View File
@@ -12,7 +12,13 @@ import time
import pytest import pytest
from semif_agent.cli import _opt_float, _required_model, build_scheduler, load_config from semif_agent.cli import (
_opt_float,
_required_model,
build_engine_config,
build_scheduler,
load_config,
)
from semif_agent.codegen import ( from semif_agent.codegen import (
CodegenClient, CodegenClient,
generate_skill_body, generate_skill_body,
@@ -40,18 +46,9 @@ from semif_agent.skills import (
def require_real(config: dict): def require_real(config: dict):
from semif_agent.engine import SemIfEngine, EngineConfig from semif_agent.engine import SemIfEngine
engine = SemIfEngine( engine = SemIfEngine(build_engine_config(config))
EngineConfig(
backend=config.get("engine", {}).get("backend", "llamacpp"),
source=config.get("engine", {}).get("source", ""),
revision=config.get("engine", {}).get("revision", ""),
gguf=config.get("engine", {}).get("gguf", ""),
context_tokens=int(config.get("engine", {}).get("context_tokens", 4096)),
threads=config.get("engine", {}).get("threads"),
)
)
try: try:
engine._ensure_loaded() engine._ensure_loaded()
except EngineUnavailable as exc: except EngineUnavailable as exc: