From 78b4621ba0f77a15478193b6bb45283c689e04bb Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 13 Oct 2026 14:20:35 +0000 Subject: [PATCH] Abstract seeds into modular skill packs + split config Group committed starter skills into packs (semif_agent/packs.py) that bind a concern to its categories, bridge(s), requirements, and config schema: - seeds/ -> packs// with a pack.json manifest + skills///. Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and essentials (time + calculator, no bridge). - PackRegistry discovers packs (a root with no manifest is one implicit pack); merge_packs loads every enabled pack. Pack enable is one switch (packs..enabled -> bridges..enabled -> enabled_by_default); disabling a pack drops its categories (incl. generated bodies) and its bridge. - CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay). Adopt a Home-Assistant-style layered config (semif_agent/config.py): - config.json is a thin index ({"include": [...]}) over config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged. - Secrets live in the gitignored secrets.json, referenced as "!secret "; api_key_env is removed. - CORE_SCHEMA + each pack's config schema own defaults and GENERATE the committed config.example.json; new `check-config` (validate + --write-example) and `config-init` (seed the split layout) commands. - scripts/config_merge.py (stdlib) lets bootstrap read the merged config. Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge), new tests/test_config.py. All unit tests pass (772). --- .gitignore | 2 + AGENTS.md | 204 +++++-- CODEGEN.md | 2 +- README.md | 72 ++- config.example.json | 215 ++++--- packs/browser/pack.json | 26 + .../skills}/browser/open_page/contract.json | 0 .../skills}/browser/open_page/manifest.json | 0 .../skills}/browser/open_page/skill.py | 0 .../skills}/browser/open_page/skill.test.py | 0 .../skills}/browser/read_page/contract.json | 0 .../skills}/browser/read_page/manifest.json | 0 .../skills}/browser/read_page/skill.py | 0 .../skills}/browser/read_page/skill.test.py | 0 .../skills}/browser/screenshot/contract.json | 0 .../skills}/browser/screenshot/manifest.json | 0 .../skills}/browser/screenshot/skill.py | 0 .../skills}/browser/screenshot/skill.test.py | 0 packs/essentials/pack.json | 15 + .../calculator/calculate/contract.json | 0 .../calculator/calculate/manifest.json | 0 .../skills}/calculator/calculate/skill.py | 0 .../calculator/calculate/skill.test.py | 0 .../skills}/time/date/contract.json | 0 .../skills}/time/date/manifest.json | 0 .../essentials/skills}/time/date/skill.py | 0 .../skills}/time/date/skill.test.py | 0 .../essentials/skills}/time/now/contract.json | 0 .../essentials/skills}/time/now/manifest.json | 0 .../essentials/skills}/time/now/skill.py | 0 .../essentials/skills}/time/now/skill.test.py | 0 .../skills}/time/set_alarm/contract.json | 0 .../skills}/time/set_alarm/manifest.json | 0 .../skills}/time/set_alarm/skill.py | 0 .../skills}/time/set_alarm/skill.test.py | 0 .../skills}/time/set_timer/contract.json | 0 .../skills}/time/set_timer/manifest.json | 0 .../skills}/time/set_timer/skill.py | 0 .../skills}/time/set_timer/skill.test.py | 0 packs/nextcloud/pack.json | 25 + .../nextcloud/create_event/contract.json | 0 .../nextcloud/create_event/manifest.json | 0 .../skills}/nextcloud/create_event/skill.py | 0 .../nextcloud/create_event/skill.test.py | 0 .../nextcloud/create_task/contract.json | 0 .../nextcloud/create_task/manifest.json | 0 .../skills}/nextcloud/create_task/skill.py | 0 .../nextcloud/create_task/skill.test.py | 0 .../nextcloud/next_event/contract.json | 0 .../nextcloud/next_event/manifest.json | 0 .../skills}/nextcloud/next_event/skill.py | 0 .../nextcloud/next_event/skill.test.py | 0 packs/outlook/pack.json | 26 + .../outlook/create_event/contract.json | 0 .../outlook/create_event/manifest.json | 0 .../skills}/outlook/create_event/skill.py | 0 .../outlook/create_event/skill.test.py | 0 .../skills}/outlook/create_task/contract.json | 0 .../skills}/outlook/create_task/manifest.json | 0 .../skills}/outlook/create_task/skill.py | 0 .../skills}/outlook/create_task/skill.test.py | 0 .../outlook/list_contacts/contract.json | 0 .../outlook/list_contacts/manifest.json | 0 .../skills}/outlook/list_contacts/skill.py | 0 .../outlook/list_contacts/skill.test.py | 0 .../skills}/outlook/list_files/contract.json | 0 .../skills}/outlook/list_files/manifest.json | 0 .../skills}/outlook/list_files/skill.py | 0 .../skills}/outlook/list_files/skill.test.py | 0 .../skills}/outlook/next_event/contract.json | 0 .../skills}/outlook/next_event/manifest.json | 0 .../skills}/outlook/next_event/skill.py | 0 .../skills}/outlook/next_event/skill.test.py | 0 .../outlook/next_message/contract.json | 0 .../outlook/next_message/manifest.json | 0 .../skills}/outlook/next_message/skill.py | 0 .../outlook/next_message/skill.test.py | 0 .../outlook/send_message/contract.json | 0 .../outlook/send_message/manifest.json | 0 .../skills}/outlook/send_message/skill.py | 0 .../outlook/send_message/skill.test.py | 0 packs/simplex/pack.json | 26 + .../simplex/connect_link/contract.json | 0 .../simplex/connect_link/manifest.json | 0 .../skills}/simplex/connect_link/skill.py | 0 .../simplex/connect_link/skill.test.py | 0 .../simplex/next_message/contract.json | 0 .../simplex/next_message/manifest.json | 0 .../skills}/simplex/next_message/skill.py | 0 .../simplex/next_message/skill.test.py | 0 .../simplex/send_message/contract.json | 0 .../simplex/send_message/manifest.json | 0 .../skills}/simplex/send_message/skill.py | 0 .../simplex/send_message/skill.test.py | 0 scripts/bootstrap.sh | 54 +- scripts/config_merge.py | 49 ++ scripts/tune_navigation.py | 2 +- semif_agent/bridges/nextcloud.py | 2 +- semif_agent/bridges/registry.py | 2 +- semif_agent/cli.py | 172 +++++- semif_agent/config.py | 527 ++++++++++++++++++ semif_agent/console.py | 3 +- semif_agent/packs.py | 187 +++++++ semif_agent/scheduler.py | 12 +- semif_agent/skills.py | 69 +-- tests/test_codegen_privacy.py | 2 +- tests/test_config.py | 114 ++++ tests/test_console.py | 13 +- tests/test_dashboard_api.py | 2 +- tests/test_gateway.py | 2 +- tests/test_housekeeping.py | 2 +- tests/test_input_channel.py | 2 +- tests/test_packs.py | 154 +++++ tests/test_seed_skills.py | 88 --- tests/test_skills.py | 28 +- 115 files changed, 1701 insertions(+), 398 deletions(-) create mode 100644 packs/browser/pack.json rename {seeds => packs/browser/skills}/browser/open_page/contract.json (100%) rename {seeds => packs/browser/skills}/browser/open_page/manifest.json (100%) rename {seeds => packs/browser/skills}/browser/open_page/skill.py (100%) rename {seeds => packs/browser/skills}/browser/open_page/skill.test.py (100%) rename {seeds => packs/browser/skills}/browser/read_page/contract.json (100%) rename {seeds => packs/browser/skills}/browser/read_page/manifest.json (100%) rename {seeds => packs/browser/skills}/browser/read_page/skill.py (100%) rename {seeds => packs/browser/skills}/browser/read_page/skill.test.py (100%) rename {seeds => packs/browser/skills}/browser/screenshot/contract.json (100%) rename {seeds => packs/browser/skills}/browser/screenshot/manifest.json (100%) rename {seeds => packs/browser/skills}/browser/screenshot/skill.py (100%) rename {seeds => packs/browser/skills}/browser/screenshot/skill.test.py (100%) create mode 100644 packs/essentials/pack.json rename {seeds => packs/essentials/skills}/calculator/calculate/contract.json (100%) rename {seeds => packs/essentials/skills}/calculator/calculate/manifest.json (100%) rename {seeds => packs/essentials/skills}/calculator/calculate/skill.py (100%) rename {seeds => packs/essentials/skills}/calculator/calculate/skill.test.py (100%) rename {seeds => packs/essentials/skills}/time/date/contract.json (100%) rename {seeds => packs/essentials/skills}/time/date/manifest.json (100%) rename {seeds => packs/essentials/skills}/time/date/skill.py (100%) rename {seeds => packs/essentials/skills}/time/date/skill.test.py (100%) rename {seeds => packs/essentials/skills}/time/now/contract.json (100%) rename {seeds => packs/essentials/skills}/time/now/manifest.json (100%) rename {seeds => packs/essentials/skills}/time/now/skill.py (100%) rename {seeds => packs/essentials/skills}/time/now/skill.test.py (100%) rename {seeds => packs/essentials/skills}/time/set_alarm/contract.json (100%) rename {seeds => packs/essentials/skills}/time/set_alarm/manifest.json (100%) rename {seeds => packs/essentials/skills}/time/set_alarm/skill.py (100%) rename {seeds => packs/essentials/skills}/time/set_alarm/skill.test.py (100%) rename {seeds => packs/essentials/skills}/time/set_timer/contract.json (100%) rename {seeds => packs/essentials/skills}/time/set_timer/manifest.json (100%) rename {seeds => packs/essentials/skills}/time/set_timer/skill.py (100%) rename {seeds => packs/essentials/skills}/time/set_timer/skill.test.py (100%) create mode 100644 packs/nextcloud/pack.json rename {seeds => packs/nextcloud/skills}/nextcloud/create_event/contract.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_event/manifest.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_event/skill.py (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_event/skill.test.py (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_task/contract.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_task/manifest.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_task/skill.py (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/create_task/skill.test.py (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/next_event/contract.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/next_event/manifest.json (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/next_event/skill.py (100%) rename {seeds => packs/nextcloud/skills}/nextcloud/next_event/skill.test.py (100%) create mode 100644 packs/outlook/pack.json rename {seeds => packs/outlook/skills}/outlook/create_event/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/create_event/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/create_event/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/create_event/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/create_task/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/create_task/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/create_task/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/create_task/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/list_contacts/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/list_contacts/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/list_contacts/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/list_contacts/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/list_files/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/list_files/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/list_files/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/list_files/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/next_event/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/next_event/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/next_event/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/next_event/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/next_message/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/next_message/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/next_message/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/next_message/skill.test.py (100%) rename {seeds => packs/outlook/skills}/outlook/send_message/contract.json (100%) rename {seeds => packs/outlook/skills}/outlook/send_message/manifest.json (100%) rename {seeds => packs/outlook/skills}/outlook/send_message/skill.py (100%) rename {seeds => packs/outlook/skills}/outlook/send_message/skill.test.py (100%) create mode 100644 packs/simplex/pack.json rename {seeds => packs/simplex/skills}/simplex/connect_link/contract.json (100%) rename {seeds => packs/simplex/skills}/simplex/connect_link/manifest.json (100%) rename {seeds => packs/simplex/skills}/simplex/connect_link/skill.py (100%) rename {seeds => packs/simplex/skills}/simplex/connect_link/skill.test.py (100%) rename {seeds => packs/simplex/skills}/simplex/next_message/contract.json (100%) rename {seeds => packs/simplex/skills}/simplex/next_message/manifest.json (100%) rename {seeds => packs/simplex/skills}/simplex/next_message/skill.py (100%) rename {seeds => packs/simplex/skills}/simplex/next_message/skill.test.py (100%) rename {seeds => packs/simplex/skills}/simplex/send_message/contract.json (100%) rename {seeds => packs/simplex/skills}/simplex/send_message/manifest.json (100%) rename {seeds => packs/simplex/skills}/simplex/send_message/skill.py (100%) rename {seeds => packs/simplex/skills}/simplex/send_message/skill.test.py (100%) create mode 100644 scripts/config_merge.py create mode 100644 semif_agent/config.py create mode 100644 semif_agent/packs.py create mode 100644 tests/test_config.py create mode 100644 tests/test_packs.py delete mode 100644 tests/test_seed_skills.py diff --git a/.gitignore b/.gitignore index 2a56077..30780b8 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ data/skills/ data/drafts/ .pytest_cache/ config.json +config/ +secrets.json *.log # Machine-specific material: deployment notes (hostnames, addresses, SSH, # model choices), GPU offload probe, benchmark harness. Deliberately not part diff --git a/AGENTS.md b/AGENTS.md index 07d66c4..f2e5104 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,20 @@ capability is a new bridge, not a gateway feature. ``` cli.py argparse: run (REPL / --script), dream, skills, status, relabel, dashboard, gateway (command intake), bridge (standalone - third-party API bridges) + third-party API bridges), check-config (validate config/ + against the core + pack schemas), config-init (seed the split + config/ + secrets.json) +config.py layered per-machine config: config.json is a thin index + (`{"include": [...]}`) over config/core.json + config/gateway.json + + config/bridges.json + config/packs/.json, deep-merged in + order; `"!secret "` resolves from the gitignored + secrets.json; the core schema owns defaults and, with each + pack's `config` schema, GENERATES config.example.json + (check-config --write-example) and validates a live config +packs.py SkillPack + PackRegistry: discovers packs/ (a `pack.json` + manifest + skills///), binds a concern to its + categories, bridge(s), requirements, and config schema; + merge_packs loads every enabled pack into the tree scheduler.py no up-front gate: every input is dispatched -> FIFO queue when busy; a skill run paused for input (needs_input) keeps `current` busy; `answer` routes straight to @@ -122,8 +135,10 @@ skills.py tree + registry (hardcoded built-ins: the closed `response` canned (skill.py, skill.test.py, contract.json, config.json) and materialize_skill / merge_skill_store hot-load runnable skills from data/skills/; - merge_seed_store loads committed starter skills from seeds/ with - their recorded config read from data/skills/; + merge_packs (semif_agent/packs.py) loads committed pack skills + from packs//skills/ with their recorded config read from + data/skills/ (each pack bundles its concern, category scope, + bridge, and config schema); ActionResult.needs_input pauses a run for human input; Skill.integration / integration_source read the body's INTEGRATION declaration (or infer it); Skill.contract is read @@ -291,7 +306,7 @@ bridges/ standalone third-party API bridges (SimpleX, the LLM bridge, and Notes (OCS) behind one JSON surface, so bodies never speak DAV/OCS; no service daemon (stdlib-only), connection from `bridges.nextcloud` with a fallback to the top-level - `nextcloud_*` values the nextcloud seeds use. + `nextcloud_*` values the nextcloud pack skills use. outlook.py + outlook_client.py: OutlookBridge — the user's Microsoft account (Outlook / Microsoft 365) over Microsoft Graph: mail, calendar events, Microsoft To Do tasks, contacts, and @@ -359,11 +374,20 @@ values are yours to choose. ## Git / sync - Push/pull from your git remote — never rsync/tar the code. -- **`config.json` is gitignored, per-machine, and required** (hosts use - different LLM/codegen endpoints and models). `scripts/bootstrap.sh` seeds it - from `config.example.json` once (only when absent) and **nothing writes it - afterwards — only a human edits `config.json`**. `data/decisions.jsonl`, - `data/runs.jsonl`, and `data/drafts/` are runtime artifacts and gitignored too. +- **`config.json` (a thin index), the `config/` fragments, and `secrets.json` are + gitignored, per-machine, and required** (hosts use different LLM/codegen + endpoints and models). `config.json` is an index (`{"include": [...]}`); + `config/core.json` + `config/gateway.json` + `config/bridges.json` + + `config/packs/.json` hold the values, and `secrets.json` holds + credentials referenced as `"!secret "`. `scripts/bootstrap.sh` seeds the + split config once (via `config-init`, only when `config.json` is absent) and + **nothing writes it afterwards — only a human edits it**. The committed + `config.example.json` is GENERATED from the core schema + (`semif_agent/config.py`) and each pack's `config` schema — regenerate it with + `python -m semif_agent.cli check-config --write-example config.example.json` + after changing a schema; validate a live config with `check-config`. + `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 @@ -762,6 +786,29 @@ CLI, unit tests (24) + integration tests (2). into `.runtime/models/` by bootstrap. Load ~34s; score ~0.9s/decision on CPU at 8 threads. +### configuration (split + secrets) + +- **Three layers, mirroring Home Assistant.** Declarative structure is committed + (`pack.json` manifests + the core schema); per-machine values are the split + config; secrets are a separate gitignored file. `config.json` is a **thin + index** (`{"include": ["config/core.json", "config/gateway.json", + "config/bridges.json", "config/packs/.json", ...]}`); fragments are + deep-merged in order (later wins). `semif_agent/config.py` owns the loader. +- **Secrets.** A value written as `"!secret "` resolves from the gitignored + `secrets.json` at load (the analog of HA's `!secret`). A missing key resolves + to `""` at load (so startup never hard-fails) and is reported by `check-config`. + **`api_key_env` is gone** — `secrets.json` is the one place credentials live. +- **Schema owns defaults.** `semif_agent/config.py` `CORE_SCHEMA` (core sections) + plus each pack's `config` schema (bridge blocks) own every default. The + committed `config.example.json` is GENERATED from them + (`check-config --write-example config.example.json`); secret keys are emitted + as `"!secret "`, never a real value. `check-config` validates a live + config (type mismatches and missing secrets are errors; unknown keys warn). +- **Seeding.** `config-init` writes the split layout + an empty `secrets.json` + from the schemas (bootstrap calls it once, only when `config.json` is absent); + afterwards only a human edits it. `scripts/config_merge.py` is the stdlib-only + merger bootstrap uses before the venv exists. + ### ollama - `bootstrap.sh` installs **no ollama**: it expects the target host to already run one for `llm` (and pulls `llm.model` into it), while `codegen` may be @@ -787,10 +834,13 @@ CLI, unit tests (24) + integration tests (2). - Provision a fresh Ubuntu machine into a running host: clone `semif-agent` to a checkout (register its SSH key on your git host first), then run - `scripts/bootstrap.sh`. With no `config.json` yet it seeds one from - `config.example.json`; edit that to set `llm.model`/`codegen.model` and the - endpoints. Flags (`--llm-url`, `--codegen-url`, `--llm-model`, - `--codegen-model`) override the values read from `config.json` **for that run + `scripts/bootstrap.sh`. With no `config.json` yet it seeds the split config + (`config-init` writes `config/core.json`, `config/gateway.json`, + `config/bridges.json`, `config/packs/*.json`, the `config.json` index, and an + empty `secrets.json`); edit those to set `llm.model`/`codegen.model` and the + endpoints, and put credentials in `secrets.json`. Flags (`--llm-url`, + `--codegen-url`, `--llm-model`, + `--codegen-model`) override the values read from the merged config **for that run only** and are never written back. `--voice` additionally installs the optional voice-gateway stack (`requirements/voice.txt` + system `libportaudio2` + `alsa-utils`) and downloads its models into `.runtime/voice/` via @@ -828,9 +878,12 @@ CLI, unit tests (24) + integration tests (2). that we intentionally do not install — the llama.cpp CPU path doesn't need them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Do not "fix" them by installing torch. -- Seeds `config.json` from `config.example.json` (only when absent) and **never - writes it again** — only a human edits `config.json`. `config.example.json` - ships the provisioned defaults, so a seeded `config.json` already has +- Seeds the split config (`config-init`: `config/core.json`, + `config/gateway.json`, `config/bridges.json`, `config/packs/*.json`, the + `config.json` index, and an empty `secrets.json`) only when `config.json` is + absent, and **never writes it again** — only a human edits it. The committed + `config.example.json` is GENERATED from the core + pack schemas and ships the + provisioned defaults, so a seeded config already has `codegen.timeout: 3600`, the SimpleX gateway enabled (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the standalone forwarding bridge enabled (`bridges.simplex.enabled = true`, @@ -838,7 +891,7 @@ CLI, unit tests (24) + integration tests (2). the LLM bridge enabled (`bridges.llm.enabled = true`; it reuses the `llm` model); the operator sets `llm.model`/`llm.base_url` and `codegen.model`/ - `codegen.base_url`. Bootstrap renders/enables four user services: + `codegen.base_url`, and puts credentials in `secrets.json`. Bootstrap renders/enables four user services: `semif-simplex.service` (the command `simplex-chat` bot daemon, `--create-bot-display-name` on `simplex_chat.port`), `semif-gateway.service` (`.runtime/venv/bin/python -m semif_agent.cli gateway`), @@ -881,8 +934,8 @@ CLI, unit tests (24) + integration tests (2). inference API instead of local ollama: set `llm.provider` / `codegen.provider` to `"opencode"` (default `"ollama"`), set `model` to a **Chat Completions** family id (`kimi-k2.7-code`, `glm-5.3`, `deepseek-v4.1-flash`, `qwen3.8-max`, - the free models, …), and give `api_key` (literal) or `api_key_env` (env var - name — preferred). `build_scheduler` maps `"opencode"` → `ConsoleLLMClient` / + the free models, …), and set `api_key` to `"!secret "` with the key in + `secrets.json` (a literal `api_key` also works). `build_scheduler` maps `"opencode"` → `ConsoleLLMClient` / `ConsoleCodegenClient`, which keep the existing error contracts (`LLMError` / `CodegenError` / `DegenerationError`) and the same opt-in sampler behavior (none sent unless configured). The `OpenAICompatClient` @@ -922,39 +975,49 @@ CLI, unit tests (24) + integration tests (2). check** (inline fixtures, loopback `http.server` for HTTP bodies, no external network) that never certifies the live integration — only a real run does. The body owns no data; everything comes from the runner via `ctx.config`. -- **Seed skills.** `seeds///` ships a real starter integration in - the exact generated-skill folder format (`skill.py`, `contract.json`, - `skill.test.py`, plus `manifest.json` with the description). `merge_seed_store` - loads them into every tree at startup; recorded config (credentials collected - at first fire) is written to the runtime store `data/skills/`, so the committed - seed never holds secrets, and a generated body with the same name replaces the - seed. `nextcloud.create_event` is the authoritative worked example (CalDAV PUT; - derives the title/date/time from the query, asks for missing fields and - resumes, resolves the target calendar with a SemIf choice over the owned - calendars — a strong winner is used, otherwise the configured default); - `nextcloud.next_event` is the read counterpart (Nextcloud CalDAV, recurring - events expanded server-side); `nextcloud.create_task` +- **Skill packs.** `packs//` bundles a concern with its skills: a + `pack.json` manifest (name, concern, `categories` → descriptions, `bridges` + referenced by name, `requires`, and a `config` schema) plus + `skills///` in the exact generated-skill folder format + (`skill.py`, `contract.json`, `skill.test.py`, plus `manifest.json` with the + description). `semif_agent/packs.py` discovers them (`PackRegistry`, scanning + `skill_packs` roots for `*/pack.json`; a root with no manifest is one implicit + pack), and `merge_packs` loads every **enabled** pack into the tree at startup. + Pack enable is one switch: an explicit `packs..enabled`, else a bridge + pack follows `bridges..enabled`, else `enabled_by_default`. Disabling a + pack drops its categories entirely (including generated bodies authored into + one) and stops its bridge. Recorded config (credentials collected at first + fire) is written to the runtime store `data/skills/`, so the committed pack + never holds secrets, and a generated body with the same name replaces the pack + skill. The shipped packs: `nextcloud`, `simplex`, `outlook`, `browser` (each + owning its bridge), and `essentials` (the built-in local utilities `time` + + `calculator`; no bridge). `nextcloud.create_event` is the authoritative worked + example (CalDAV PUT; derives the title/date/time from the query, asks for + missing fields and resumes, resolves the target calendar with a SemIf choice + over the owned calendars — a strong winner is used, otherwise the configured + default); `nextcloud.next_event` is the read counterpart (Nextcloud CalDAV, + recurring events expanded server-side); `nextcloud.create_task` adds a task to a Nextcloud task list through the Nextcloud bridge (`GET /tasklists` for a VTODO-capable target, `POST /tasks` to create it, the LLM bridge to phrase the summary/description); `simplex.next_message` (read via the forwarding bridge), `simplex.send_message` (send to a contact resolved over the bridge's contact list), and `simplex.connect_link` (show/create the forwarding - bot's contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and - `time.set_alarm` are the local time utilities (`compute` transport, empty - contract) — they read the host clock and schedule on `ctx.timers`. Local time - is the top-level `timezone` config value (an IANA name such as - `America/Chicago`; `timers.local_now`/`resolve_timezone` resolve it via + bot's contact link) are the messenger pack skills; `time.now`, `time.date`, + `time.set_timer`, and `time.set_alarm` are the local time utilities (`compute` + transport, empty contract) — they read the host clock and schedule on + `ctx.timers`. Local time is the top-level `timezone` config value (an IANA name + such as `America/Chicago`; `timers.local_now`/`resolve_timezone` resolve it via `zoneinfo`), falling back to the host's own timezone when it is empty or unknown; `TimerService` formats due/fired times in that zone too. The nextcloud - seeds derive "now" the same way, so a request time is parsed in the user's - zone rather than the host's; `calculator.calculate` is the local-arithmetic - seed (`compute` transport, empty contract): bounded to two operands and one - operator, the operator is a SemIf choice over addition/subtraction/ - multiplication/division/exponents/squares/cubes/square roots/cube roots/ - fractions/percentages, SemIf picks the operands when the request offers more - numbers than the operator consumes, and the answer is spelled out in words for - the ear (an inexact result is announced as "approximately ..."); - `tests/test_seed_skills.py` keeps them honest. + pack skills derive "now" the same way, so a request time is parsed in the + user's zone rather than the host's; `calculator.calculate` is the + local-arithmetic skill (`compute` transport, empty contract): bounded to two + operands and one operator, the operator is a SemIf choice over addition/ + subtraction/multiplication/division/exponents/squares/cubes/square roots/cube + roots/fractions/percentages, SemIf picks the operands when the request offers + more numbers than the operator consumes, and the answer is spelled out in words + for the ear (an inexact result is announced as "approximately ..."); + `tests/test_packs.py` keeps every pack skill honest. - **Contract provenance.** Each authored body records the CODEGEN.md revision it was written against. `skill_contract_ref()` (`codegen.py`) returns `{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read @@ -1377,8 +1440,8 @@ CLI, unit tests (24) + integration tests (2). exercises `SimplexBridge` over a real loopback server (peek/pop, recipient resolution, outbound routing, token/body validation, `/address` success/503/502, daemon close on stop, catalog/`describe_bridges()`). - `tests/test_seed_skills.py` hermetically tests every - `seeds///` package, including `simplex.next_message`, + `tests/test_packs.py` hermetically tests every + `packs//skills///` package, including `simplex.next_message`, `simplex.send_message`, and `simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop with injected fake engines (wake gating, endpointing, half-duplex, @@ -1399,13 +1462,46 @@ CLI, unit tests (24) + integration tests (2). installs it and downloads the models (openWakeWord into the venv package dir, the Piper voice into `.runtime/voice/tts`, faster-whisper into `.runtime/hf`). +### skill packs (bundles) + +- **What they are.** A pack bundles a concern/product with the skills that serve + it, in `packs//`: a `pack.json` manifest plus + `skills///` folders (the exact generated-skill format). The + manifest binds the pieces that used to be scattered by convention: + `concern`/`title`, `categories` (id -> scope description, feeding + `CATEGORY_DESCRIPTIONS`), `bridges` (names referencing `bridges/registry.py` + `CATALOG` — bridge *code* stays in `bridges/`, isolation is non-negotiable), + `requires` (optional deps like `playwright`), `enabled_by_default`, and a + `config` schema. `semif_agent/packs.py` discovers them (`PackRegistry`, which + scans the `skill_packs` roots for `*/pack.json`; a root with no manifest is one + implicit pack, so a plain skills directory works) and `merge_packs` loads every + **enabled** pack at startup. +- **Enable is one switch.** `pack_enabled` resolves: an explicit + `packs..enabled`, else a bridge pack follows its + `bridges..enabled`, else `enabled_by_default`. Disabling a pack drops + its categories entirely (including any generated body authored into one) and + stops its bridge — a host never offers a skill whose bridge is off. The switch + lives in the pack's `config/packs/.json` fragment. +- **Config is pack-owned.** A pack's `config` schema (key -> `type`/`default`/ + `doc`/`secret`) owns its defaults and drives both `config.example.json` + generation and `check-config` validation. Bridge packs map the schema onto + `bridges.`; a bridge-less pack (e.g. `essentials`) maps onto + `packs.`. Shared, skill-less bridges (the LLM bridge) live in + `semif_agent/config.py` `SHARED_BRIDGE_SCHEMA`. +- **Shipped packs.** `nextcloud`, `simplex`, `outlook`, `browser` (each owning + its bridge) and `essentials` (the built-in local utilities `time` + + `calculator`; no bridge). Adding a concern means adding a pack, not editing + `skills.py`. + ### bridges (third-party API services) - **What they are.** A bridge service is a standalone process that stands up a simple, secure localhost HTTP layer in front of one third-party system so a codegen-authored skill body never speaks that system's native protocol. SimpleX is the first; adding a service means adding a class to - `bridges/registry.py` `CATALOG` and a `config.example.json` block. The catalog + `bridges/registry.py` `CATALOG`, a `pack.json` whose `config` schema carries + its block (see `semif_agent/packs.py`; a shared, skill-less bridge like the + LLM bridge goes in the core `SHARED_BRIDGE_SCHEMA` instead). The catalog (`BridgeInfo`: name, service, description, URL config var, other config vars with one-line docs, auth header + token config var, and endpoints with request/response/error shapes) is injected into every codegen prompt @@ -1454,7 +1550,7 @@ CLI, unit tests (24) + integration tests (2). skill config. Skills reach a bridge with the ordinary `http` transport, so their hermetic tests are loopback HTTP like any other HTTP body. `simplex.next_message`, `simplex.send_message`, and `simplex.connect_link` are - the seeds. + the pack skills. - **LLM bridge** (`bridges/llm.py`). A generic `POST /chat` `{"messages": [{"role","content"}, ...], "max_tokens"?: int}` -> `{"text": ""}` (plus `GET /health`, `400` bad body, `502` model @@ -1482,7 +1578,7 @@ CLI, unit tests (24) + integration tests (2). and `verify_tls`/`timeout`); `build_bridge` passes the top-level `nextcloud_url`/`nextcloud_username`/`nextcloud_app_password`/ `nextcloud_default_calendar`/`nextcloud_default_addressbook` as a fallback, so - the same account the nextcloud seeds collect is configured once and a block value + the same account the nextcloud pack skills collect is configured once and a block value wins. Bodies reach it via the derived `nextcloud_bridge_url` (+ optional `nextcloud_bridge_token`); the `BridgeInfo` declares only those two config vars. Routes (reads `GET`, mutations `POST`): files (`/files`, `/files/stat`, @@ -1569,7 +1665,7 @@ CLI, unit tests (24) + integration tests (2). `/goto`, `/click` (selector or visible text), `/fill`, `/press`, `/select`, `/wait`, `/back`, `/forward`, `/reset`. Bodies reach it via the derived `browser_bridge_url` (+ optional `browser_bridge_token`). Three - `seeds/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). + `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). `tests/test_browser_bridge.py` exercises the routes over a loopback HTTP server with an injected fake driver (no browser, no Playwright needed). @@ -1605,7 +1701,7 @@ covered. Deferred follow-ups: pinned v7.0.3 **does** have `/_read chat @`, `/_read chat items @ `, and `/_read user `; an earlier note claiming v7 had no mark-read command was wrong.) -- [x] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The +- [x] **3. `simplex.send_message` pack skill** (`packs/simplex/skills/simplex/send_message/`). The outbound counterpart to `simplex.next_message`: resolves the recipient with a SemIf sub-decision over the bridge's `/contacts` (falling back to the configured default contact), writes the message from the request or the LLM @@ -1626,7 +1722,7 @@ covered. Deferred follow-ups: `bridges/outlook_client.py`). Shipped: the `OutlookBridge` exposes mail, calendar, Microsoft To Do, contacts, and OneDrive over one JSON surface in front of Graph; OAuth2 device-code + refresh (`scripts/outlook-auth.py`, tokens - under `.runtime/outlook/token.json`); seven `seeds/outlook/*` skills + under `.runtime/outlook/token.json`); seven `packs/outlook/skills/outlook/*` skills (`next_message`, `send_message` confirm-gated, `next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing Outlook app-registration guidance in the docs, and a mail-send seed that @@ -1638,7 +1734,7 @@ covered. Deferred follow-ups: with a persistent profile; optional heavy dep installed via `requirements/browser.txt` + `bootstrap.sh --browser`, lazy so a missing browser is a per-call 503 and never aborts the other bridges; the async API - runs on one dedicated event-loop thread. Three `seeds/browser/*` skills + runs on one dedicated event-loop thread. Three `packs/browser/skills/browser/*` skills (`open_page`, `read_page`, `screenshot`). Deferred: arbitrary JS `evaluate`, file upload/download, multiple tabs/contexts, and a per-URL allowlist. diff --git a/CODEGEN.md b/CODEGEN.md index facc5b5..81c2aa9 100644 --- a/CODEGEN.md +++ b/CODEGEN.md @@ -21,7 +21,7 @@ A skill is three things: talks to and how) and the `CONTRACT` constant (the values the runner must provide). -The committed seed `seeds/nextcloud/create_event/` is the **authoritative worked +The committed seed `packs/nextcloud/skills/nextcloud/create_event/` is the **authoritative worked example** of all three. Read its `manifest.json`, its `skill.py` (which declares `INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new body should look and behave like it. diff --git a/README.md b/README.md index 17340d8..44bfd2d 100644 --- a/README.md +++ b/README.md @@ -401,14 +401,20 @@ semif_agent/ gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud, Outlook, browser) -seeds/ committed starter skills (nextcloud, simplex, outlook, browser) + config.py layered config: index includes + !secret + schema/example + packs.py SkillPack + PackRegistry (bundles skills by concern/bridge) +packs/ committed skill packs: nextcloud, simplex, outlook, browser, + essentials (a pack.json manifest + skills///) scripts/ bootstrap.sh, simplex-address.py, systemd/*.in requirements/ staging.txt — the pinned engine deps tests/ stdlib unit tests + tests/integration (real engine + LLM) CODEGEN.md the contract fed to the skill-body codegen model TESTGEN.md the contract fed to the test/contract codegen model AGENTS.md the operational guide (read this before touching code) -config.example.json per-machine config template (seeded to config.json once) +config.json per-machine config INDEX ({"include": [...]}); seeded once +config/ split config fragments (core, gateway, bridges, packs/*) +secrets.json gitignored credentials, referenced as "!secret " +config.example.json GENERATED per-machine config reference (from the schemas) pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs local/ gitignored: this deployment's notes (hosts, addresses, models) ``` @@ -451,10 +457,13 @@ On a fresh Ubuntu machine, from a checkout of this repo: scripts/bootstrap.sh ``` -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 +With no `config.json` yet, the script seeds the split config (`config-init` +writes `config/core.json`, `config/gateway.json`, `config/bridges.json`, +`config/packs/*.json`, the `config.json` index, and an empty `secrets.json`); +edit those to set `llm.model`/`codegen.model` (and the endpoints), and put +credentials in `secrets.json`. Flags override those values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`, -`--codegen-model` — and are never written back to `config.json`. +`--codegen-model` — and are never written back to the config. The script is idempotent (every stage no-ops on existing state) and: @@ -466,8 +475,8 @@ The script is idempotent (every stage no-ops on existing state) and: 4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`; 5. pre-fetches the HF tokenizer into `.runtime/hf/`; 6. downloads and sha256-verifies the pinned `simplex-chat` binary; -7. seeds `config.json` from `config.example.json` **only if it does not already - exist** — it never rewrites `config.json` (only a human edits that file); +7. seeds the split config (`config-init`) **only if `config.json` does not + already exist** — it never rewrites it (only a human edits it); 8. renders and enables systemd **user** units: `semif-simplex` (bot daemon), `semif-gateway` (agent gateway), `semif-simplex-forward` (the bridge's own daemon), `semif-bridge`; @@ -497,24 +506,38 @@ python3 -m pytest tests/ -q --ignore=tests/integration For a full install on a machine you manage, follow the same steps bootstrap performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF, -tokenizer cache), then create `config.json` from the template and adjust paths: +tokenizer cache), then seed the split config and adjust paths: ```sh -cp config.example.json config.json +python -m semif_agent.cli config-init # writes config/ + secrets.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: +The per-machine config is **gitignored, per-machine, and required** — the agent +refuses to start without it. `config.json` is a thin **index** +(`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments +under `config/` hold the values and are deep-merged in order. Credentials live in +the gitignored `secrets.json` and are referenced from any fragment as +`"!secret "` (there is no `api_key_env`). `scripts/bootstrap.sh` seeds the +split config once via `config-init`; afterwards only a human edits it. ```sh -cp config.example.json config.json # if not already created by bootstrap +python -m semif_agent.cli config-init # seed config/ + secrets.json (once) +python -m semif_agent.cli check-config # validate against the schemas ``` +The committed `config.example.json` is **generated** from the core schema +(`semif_agent/config.py`) and each pack's `config` schema; regenerate it after +changing a schema: + +```sh +python -m semif_agent.cli check-config --write-example config.example.json +``` + +Pinned external refs live in the committed `pins.json`, so the config holds only +per-machine settings. + Key blocks: | Block | What it controls | @@ -525,7 +548,7 @@ Key blocks: | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | | `tau` | decision threshold; `max_reentries` requeue bound | | `queue` | `max_size` | -| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | +| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | | `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url | @@ -777,7 +800,7 @@ plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly in the same `semif-bridge` process. The connection (base URL, username, app password) is configured in `bridges.nextcloud` and falls back to the top-level `nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` / -`nextcloud_default_calendar` the nextcloud seeds use, so the account is +`nextcloud_default_calendar` the nextcloud pack skills use, so the account is configured once. Skills call it at the address derived from `bridges.nextcloud` (`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface: @@ -843,7 +866,7 @@ POST /files/write {"path","content","encoding"?,"overwrite"?} A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure (transport, HTTP error, or a bad reply) is `502` — never a fabricated success. -Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`, +Seven `packs/outlook/skills/outlook/*` skills ship (`next_message`, `send_message`, `next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`); `send_message` composes the message through the LLM bridge and asks for confirmation before it sends. @@ -890,7 +913,7 @@ POST /back | /forward {"timeout"?} POST /reset {"purge"?} # close; purge deletes the profile ``` -Three `seeds/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). +Three `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). ### Dream report @@ -927,10 +950,11 @@ bodies, no external network, no `mock_data.json`. Passing it proves the code runs, not that the live integration works. That is what the real run and the repair loop are for. -**Seeds** (`seeds/`) ship real starter integrations in the exact generated -folder format, plus a `manifest.json`. `merge_seed_store` loads them into every -tree at startup; recorded config is written to the runtime store, so the -committed seed never holds secrets. +**Packs** (`packs//`) ship real starter integrations in the exact generated +folder format, plus a `manifest.json` and a `pack.json` manifest binding the +concern to its categories, bridge, and config schema. `merge_packs` loads every +enabled pack into the tree at startup; recorded config is written to the runtime +store, so the committed pack never holds secrets. - `nextcloud.create_event` — create an event on Nextcloud CalDAV (the authoritative worked example); resolves the target calendar with a SemIf @@ -993,7 +1017,7 @@ logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` / contract → test → auto-run → re-dispatch); tiered config + first-fire collection; runtime repair loop; the closed `response` canned tree; real integrations with `INTEGRATION` declarations; the SimpleX command gateway and the -standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message +standalone SimpleX bridge + pack skills (contact-list refresh, daemon-backed message history / true unread); the LXMF gateway; and the voice gateway (wake word + speech-to-text + text-to-speech). diff --git a/config.example.json b/config.example.json index 9f7f488..180fc61 100644 --- a/config.example.json +++ b/config.example.json @@ -1,35 +1,27 @@ { - "_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. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.", "tau": 0.6, "max_reentries": 3, "query_recall_window": 30, - "_query_recall_window_comment": "Seconds a completed run stays recallable to a follow-up request in the same chat/source. A follow-up within the window is given the previous run's ledger as 'previous request' context (and bodies can reuse its result via last_result), so a reference like \"send it to Sam\" resolves against what the agent just did. 0 disables recall entirely. Measured from the previous run's completion; only the last completed real skill run per source is remembered (canned responses and housekeeping meta skills are never recalled).", "new_skill_creation": "allow", - "_new_skill_creation_comment": "Global new-skill creation mode: \"allow\" (create without asking), \"deny\" (never author new skills/categories), or \"ask\" (author only after the human approves the proposal). A category can override this in data/skills//config.json with its own \"new_skill_creation\" value; the built-in housekeeping and response categories are always denied in code.", "verbosity": "result", - "_verbosity_comment": "How much of a completed request to surface. \"result\" (default): only the final answer — an end user does not care which skills ran or which decisions were made. \"query\": also show each intermediate step of a chained request (its query + run-ledger entry). \"decision\": also show every SemIf decision (phase + selected option + probabilities) for a step — a debugging view.", "chain": { - "_comment": "Chained multi-step completion. When a run's outcome assessment says more work is needed, the request is re-dispatched with a compact run ledger and routed to the logical next skill, until the request is satisfied, fails into repair, or the chain is capped by max_reentries. result_chars is the ONE shared speakable budget applied to every skill's output (its result string and its ledger entry): a result is read in a chat message or heard as speech, so it is truncated to this many characters at a word boundary. A long product of a skill belongs in a file I/O side effect, not the result string (see CODEGEN.md/TESTGEN.md). The voice front end (gateway.voice.max_speak_chars) and the humanizer (gateway.humanize.max_chars) are downstream caps and should not exceed it.", "result_chars": 300 }, "assess": { - "_comment": "Thresholds for the three-way assess:outcome decision (is there additional work to be done to satisfy the request?): done (request satisfied), continue (the step worked but more work is needed; route the next step), failed (the step errored; offer repair). Verdict precedence is failed > done > continue, so a confident success/failure is honored and continue — the over-trigger — only wins when the model is genuinely unsure. Separate from the top-level tau so completion tuning does not move assessment/fidelity.", "done_tau": 0.5, "fail_tau": 0.5 }, "timezone": "", "navigation": { - "_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then decides what the winner does for the request — same (it performs the next action the request needs), part (the request needs more than one action and this skill performs one required part), or different (a new leaf is authored) (phase navigate:intent, P(same)+P(part) >= intent_tau). All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.", "intent_tau": 0.6, "category_tau": 0.75, "action_tau": 0.5, "softmax_bypass_tau": 0.5 }, - "queue": {"max_size": 100}, + "queue": { + "max_size": 100 + }, "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.", - "_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).", - "_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.", "provider": "semif", "backend": "llamacpp", "context_tokens": 4096, @@ -38,25 +30,22 @@ "gpu_device": null, "gpu_split": 0, "winnow": { - "_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). context_tokens must mirror the server's --ctx-size: generated skill bodies are sized from the active engine's context so a fidelity decision can always ingest one whole. timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.", "base_url": "http://127.0.0.1:8091", "model": "", "context_tokens": 32768, - "api_key": "", - "api_key_env": "", + "api_key": "!secret engine_winnow_api_key", "timeout": 120, "retries": 0, "user_agent": "semif-agent", "extra_headers": {} - } + }, + "gguf": "" }, "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 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), \"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), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).", "provider": "ollama", "base_url": "http://localhost:11434/v1", "model": "", - "api_key": "", - "api_key_env": "", + "api_key": "!secret llm_api_key", "user_agent": "", "timeout": 600, "stream": false, @@ -69,18 +58,15 @@ "frequency_penalty": 0.0, "disable_thinking": true, "semif": { - "_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.", "temperature": 0.0, "max_tokens": 256 } }, "codegen": { - "_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= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). The state carries the WHOLE body (never a prefix) plus a deterministic operation inventory and the de-identified goal, and asks the positive question (is there a concrete operation that realizes the goal?). tau is this gate's own threshold, separate from the top-level tau. Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle (inventory + findings included), bounded by max_attempts; a still-fake body is accepted but traced, never a hard authoring failure.", "enabled": true, "max_attempts": 1, "tau": 0.6 }, "repair": { - "_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.", "enabled": true, "max_attempts": 1 }, "test_timeout": 30, "test_max_attempts": 3, - "_artifact_budget_comment": "Generated artifacts are ingested WHOLE by a decision (the fidelity gate reads the entire skill body), so each is size-bounded. max_body_tokens/max_test_tokens are hard ceilings; 0 derives each from the ACTIVE decision engine's context (engine.context_tokens for the local GGUF, engine.winnow.context_tokens for Winnow) minus decision_reserve_tokens — the headroom for everything else in the fidelity state (goal, description, integration, findings, operation inventory, question, options, engine prefill margin). A positive value overrides the derivation: lower it if you don't want to wait on a long fidelity evaluation, raise it if your engine has a larger window. chars_per_token above converts the token budget to the char limit the parser enforces; a body over budget is rejected (ArtifactTooLong) and the codegen retry ladder asks for a shorter one.", "max_body_tokens": 0, "max_test_tokens": 0, "decision_reserve_tokens": 1024, "contract_search": { - "_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills//config.json). Logged as phase config:search.", "enabled": true }, "degeneration": { - "_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.", "enabled": true, "threshold": 0.9, "interval": 8000, @@ -133,96 +113,23 @@ } }, "skill_bodies": "data/skills", - "skill_seeds": "seeds", "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", "category_registry": "data/categories.json", "simplex_chat": { - "_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`.", "port": 5226, "display_name": "semif", "forward_port": 5228, "forward_display_name": "semif-forward" }, - "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": { - "_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 call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", - "enabled": true, - "host": "127.0.0.1", - "port": 5227, - "token": "", - "max_inbox": 100, - "ws_url": "ws://127.0.0.1:5228", - "user_id": 1, - "auto_accept": true, - "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} - }, - "llm": { - "_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.", - "enabled": true, - "host": "127.0.0.1", - "port": 5229, - "token": "" - }, - "nextcloud": { - "_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the nextcloud seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", - "enabled": true, - "host": "127.0.0.1", - "port": 5230, - "token": "", - "url": "", - "username": "", - "app_password": "", - "default_calendar": "", - "default_task_calendar": "", - "default_addressbook": "", - "verify_tls": true, - "timeout": 30 - }, - "outlook": { - "_comment": "Outlook bridge: the user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — over one uniform local JSON API, so skill bodies never speak Graph or OAuth. No service daemon and no extra dependency (Graph is plain HTTPS); it runs inside the same `semif-bridge` process as the other enabled bridges. Authorization is the OAuth2 device code flow: register an Entra ID public-client app, put its `client_id` here, run `scripts/outlook-auth.py` once, and the tokens are stored (0600) under `.runtime/outlook/token.json` (override with `token_path`). `tenant` is usually `common` (personal + work accounts). `default_calendar`/`default_task_list`/`default_mail_folder` are used when a request names none; `default_timezone` (IANA name) labels created events/tasks whose start has no offset. `verify_tls` false skips certificate verification. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Disabled by default because it needs a client id + an authorization run first.", - "enabled": false, - "host": "127.0.0.1", - "port": 5231, - "token": "", - "client_id": "", - "tenant": "common", - "default_calendar": "", - "default_task_list": "", - "default_mail_folder": "inbox", - "default_timezone": "UTC", - "verify_tls": true, - "timeout": 30 - }, - "browser": { - "_comment": "Browser bridge: real browser automation via Playwright — open a URL, read a page's text/links, take a screenshot, and click/fill/press/select to complete a flow — behind one uniform local JSON API, so skill bodies never bundle a browser stack. Disabled by default because it needs the optional Playwright deps + browser binaries: install with `scripts/bootstrap.sh --browser` (browsers land under .runtime/browser). The bridge keeps a PERSISTENT profile under .runtime/browser/profile, so logins/cookies survive across calls and restarts (POST /reset with purge=true wipes it); `engine` is chromium|firefox|webkit and `headless` false shows the window. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. A missing Playwright/browser is a 503 install hint, never a startup failure (the other bridges keep running). Set `channel` (e.g. chrome/msedge) or `executable_path` (a browser binary) to use an already-installed browser and skip Playwright's managed download entirely; `executable_path` wins if both are set.", - "enabled": false, - "host": "127.0.0.1", - "port": 5232, - "token": "", - "engine": "chromium", - "headless": true, - "channel": "", - "executable_path": "", - "profile_dir": "", - "browsers_path": "", - "screenshot_dir": "", - "default_timeout": 30, - "max_text_chars": 20000 - } - }, "gateway": { - "_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform 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`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.", "humanize": { - "_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `: — ` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.", "enabled": true, "timeout": 20.0, "max_tokens": 200, "max_chars": 600 }, "simplex": { - "_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. 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. Groups/attachments are not supported.", "enabled": true, "ws_url": "ws://127.0.0.1:5226", "allowed_users": [], @@ -231,10 +138,13 @@ "home_channel": "", "reply_prefix": "", "text_batch_delay": 0.8, - "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} + "reconnect": { + "initial": 1.0, + "max": 60.0, + "jitter": 0.2 + } }, "lxmf": { - "_comment": "LXMF (Reticulum) command adapter. Runs IN-PROCESS — there is no external daemon; `pip install lxmf` provides the transport (optional, lazy-imported; the gateway refuses to start with an install hint). The bot's reachable address is its LXMF delivery destination hash (32 hex chars), printed on connect. config_dir/storage_path hold Reticulum's config and the persisted identity under .runtime/lxmf/ so the address is stable across restarts (empty = the .runtime/lxmf defaults). allowed_users entries match the peer's LXMF address (32 hex chars) or a best-effort display name; default is deny-all unless allow_all_users is set. desired_method is 'direct' (reliable link) or 'opportunistic' (single packet). propagation_node is an optional LXMF propagation-node address (hex) for store-and-forward.", "enabled": false, "allowed_users": [], "allow_all_users": false, @@ -250,7 +160,6 @@ "text_batch_delay": 0.8 }, "voice": { - "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. The wake word is required before every command and is held while the scheduler is still running the current request, so a new command cannot start until it reaches a result. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.", "enabled": false, "chat_id": "voice", "display_name": "voice", @@ -260,18 +169,25 @@ "max_speak_chars": 600, "listen_timeout_s": 3.0, "cue": { - "_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; submit_notes is a short multi-note 'bling' played once the utterance is transcribed (each entry [frequency_hz, duration_ms], separated by note_gap_ms of silence). Set submit_notes to [] and submit_frequency > 0 for the older single submit beep, or leave both empty/0 for no submit sound. volume is 0..1.", "enabled": true, "frequency": 880, "duration_ms": 120, "volume": 0.9, "submit_frequency": 0, "submit_duration_ms": 100, - "submit_notes": [[1046.5, 70], [1568.0, 90]], + "submit_notes": [ + [ + 1046.5, + 70 + ], + [ + 1568.0, + 90 + ] + ], "note_gap_ms": 20 }, "wake": { - "_comment": "model is an openWakeWord name/path. The default 'hey_computer' is a pinned community model whose scores run lower than the official models (measured ~0.26-0.82 on the phrase, <0.02 on negatives), so threshold 0.2 is tuned for it; the official models (e.g. hey_mycroft) score ~0.99 and are fine at 0.5.", "model": "hey_computer", "threshold": 0.2, "inference_framework": "onnx", @@ -291,7 +207,6 @@ "volume": 1.0 }, "audio": { - "_comment": "Capture-stream watchdog: read_timeout_s is how long a frame read waits before it counts as a stall; when the stream stalls continuously for stall_timeout_s (a wedged PortAudio/ALSA callback stops delivering frames) the input is closed and reopened so the voice front end recovers instead of hanging forever. 0 for either restores the old blocking read with no recovery.", "input_device": "", "output_device": "", "sample_rate": 16000, @@ -303,7 +218,6 @@ "stall_timeout_s": 5.0 }, "vad": { - "_comment": "Endpointing. silence_ms is the trailing-silence endpoint once a command is underway. The wake detector can fire inside the wake phrase (and the cue beep follows), so the first speech captured is the phrase's tail, not the command: until min_command_ms of speech is in hand the endpoint uses initial_silence_ms instead, so a natural pause before the command does not end the capture. min_speech_ms rejects a blip; max_utterance_s caps a runaway.", "silence_ms": 500, "min_speech_ms": 120, "max_utterance_s": 30, @@ -311,8 +225,87 @@ "initial_silence_ms": 1500, "aggressiveness": 2, "energy_threshold": 200.0 + }, + "follow_up_window_s": 0.0 + } + }, + "dashboard": { + "port": 8765, + "host": "127.0.0.1" + }, + "skill_packs": "packs", + "secrets_file": "secrets.json", + "_comment": "GENERATED from the core schema (semif_agent/config.py) and each pack's pack.json `config` schema \u2014 do not hand-edit; edit a pack's schema or the core schema. This is the reference example; the live per-machine config is split under config/ (see config.json's include list) and secrets live in the gitignored secrets.json, referenced as '!secret '.", + "bridges": { + "llm": { + "enabled": true, + "host": "127.0.0.1", + "port": 5229, + "token": "!secret llm_token" + }, + "browser": { + "enabled": false, + "host": "127.0.0.1", + "port": 5232, + "token": "!secret browser_token", + "engine": "chromium", + "headless": true, + "channel": "", + "executable_path": "", + "profile_dir": "", + "browsers_path": "", + "screenshot_dir": "", + "default_timeout": 30.0, + "max_text_chars": 20000 + }, + "nextcloud": { + "enabled": true, + "host": "127.0.0.1", + "port": 5230, + "token": "!secret nextcloud_token", + "url": "", + "username": "", + "app_password": "!secret nextcloud_app_password", + "default_calendar": "", + "default_task_calendar": "", + "default_addressbook": "", + "verify_tls": true, + "timeout": 30 + }, + "outlook": { + "enabled": false, + "host": "127.0.0.1", + "port": 5231, + "token": "!secret outlook_token", + "client_id": "", + "tenant": "common", + "token_path": ".runtime/outlook/token.json", + "default_calendar": "", + "default_task_list": "", + "default_mail_folder": "inbox", + "default_timezone": "UTC", + "verify_tls": true, + "timeout": 30 + }, + "simplex": { + "enabled": true, + "host": "127.0.0.1", + "port": 5227, + "token": "!secret simplex_token", + "max_inbox": 100, + "ws_url": "ws://127.0.0.1:5228", + "user_id": 1, + "auto_accept": true, + "reconnect": { + "initial": 1.0, + "max": 60.0, + "jitter": 0.2 } } }, - "dashboard": {"port": 8765, "host": "127.0.0.1"} -} \ No newline at end of file + "packs": { + "essentials": { + "enabled": true + } + } +} diff --git a/packs/browser/pack.json b/packs/browser/pack.json new file mode 100644 index 0000000..f37f8ee --- /dev/null +++ b/packs/browser/pack.json @@ -0,0 +1,26 @@ +{ + "name": "browser", + "title": "Browser", + "concern": "Real browser automation (Playwright): open a web page, read its text or links, take a screenshot, and click, type, or fill forms to carry out a task on a website.", + "categories": { + "browser": "Browser automation: opening a web page, reading its text or links, taking a screenshot, and clicking, typing, or filling forms to carry out a task on a website." + }, + "bridges": ["browser"], + "requires": ["playwright"], + "enabled_by_default": false, + "config": { + "enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs the optional Playwright deps + browser binaries (scripts/bootstrap.sh --browser)."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5232, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "engine": {"type": "str", "default": "chromium", "doc": "chromium | firefox | webkit."}, + "headless": {"type": "bool", "default": true, "doc": "false shows the browser window (to sign in once)."}, + "channel": {"type": "str", "default": "", "doc": "Use an already-installed browser channel (chrome/msedge) and skip Playwright's download."}, + "executable_path": {"type": "str", "default": "", "doc": "Use a specific browser binary; wins over channel."}, + "profile_dir": {"type": "str", "default": "", "doc": "Persistent profile directory (logins survive across calls)."}, + "browsers_path": {"type": "str", "default": "", "doc": "PLAYWRIGHT_BROWSERS_PATH override."}, + "screenshot_dir": {"type": "str", "default": "", "doc": "Where screenshots are saved."}, + "default_timeout": {"type": "float", "default": 30.0, "doc": "Default navigation/action timeout (seconds)."}, + "max_text_chars": {"type": "int", "default": 20000, "doc": "Bound on returned page text."} + } +} diff --git a/seeds/browser/open_page/contract.json b/packs/browser/skills/browser/open_page/contract.json similarity index 100% rename from seeds/browser/open_page/contract.json rename to packs/browser/skills/browser/open_page/contract.json diff --git a/seeds/browser/open_page/manifest.json b/packs/browser/skills/browser/open_page/manifest.json similarity index 100% rename from seeds/browser/open_page/manifest.json rename to packs/browser/skills/browser/open_page/manifest.json diff --git a/seeds/browser/open_page/skill.py b/packs/browser/skills/browser/open_page/skill.py similarity index 100% rename from seeds/browser/open_page/skill.py rename to packs/browser/skills/browser/open_page/skill.py diff --git a/seeds/browser/open_page/skill.test.py b/packs/browser/skills/browser/open_page/skill.test.py similarity index 100% rename from seeds/browser/open_page/skill.test.py rename to packs/browser/skills/browser/open_page/skill.test.py diff --git a/seeds/browser/read_page/contract.json b/packs/browser/skills/browser/read_page/contract.json similarity index 100% rename from seeds/browser/read_page/contract.json rename to packs/browser/skills/browser/read_page/contract.json diff --git a/seeds/browser/read_page/manifest.json b/packs/browser/skills/browser/read_page/manifest.json similarity index 100% rename from seeds/browser/read_page/manifest.json rename to packs/browser/skills/browser/read_page/manifest.json diff --git a/seeds/browser/read_page/skill.py b/packs/browser/skills/browser/read_page/skill.py similarity index 100% rename from seeds/browser/read_page/skill.py rename to packs/browser/skills/browser/read_page/skill.py diff --git a/seeds/browser/read_page/skill.test.py b/packs/browser/skills/browser/read_page/skill.test.py similarity index 100% rename from seeds/browser/read_page/skill.test.py rename to packs/browser/skills/browser/read_page/skill.test.py diff --git a/seeds/browser/screenshot/contract.json b/packs/browser/skills/browser/screenshot/contract.json similarity index 100% rename from seeds/browser/screenshot/contract.json rename to packs/browser/skills/browser/screenshot/contract.json diff --git a/seeds/browser/screenshot/manifest.json b/packs/browser/skills/browser/screenshot/manifest.json similarity index 100% rename from seeds/browser/screenshot/manifest.json rename to packs/browser/skills/browser/screenshot/manifest.json diff --git a/seeds/browser/screenshot/skill.py b/packs/browser/skills/browser/screenshot/skill.py similarity index 100% rename from seeds/browser/screenshot/skill.py rename to packs/browser/skills/browser/screenshot/skill.py diff --git a/seeds/browser/screenshot/skill.test.py b/packs/browser/skills/browser/screenshot/skill.test.py similarity index 100% rename from seeds/browser/screenshot/skill.test.py rename to packs/browser/skills/browser/screenshot/skill.test.py diff --git a/packs/essentials/pack.json b/packs/essentials/pack.json new file mode 100644 index 0000000..f147679 --- /dev/null +++ b/packs/essentials/pack.json @@ -0,0 +1,15 @@ +{ + "name": "essentials", + "title": "Essentials", + "concern": "The built-in local utilities the agent ships with that need no account, network, or bridge: time and date, timers and alarms, and arithmetic.", + "categories": { + "time": "Time and date utilities: telling the current time or date, setting countdown timers, and setting alarms.", + "calculator": "Arithmetic: evaluating a numeric expression the user asks for — addition, subtraction, multiplication, division, powers and exponents, squares, cubes, square roots, cube roots, fractions, and percentages." + }, + "bridges": [], + "requires": [], + "enabled_by_default": true, + "config": { + "enabled": {"type": "bool", "default": true, "doc": "Load the built-in local utility skills (time, calculator)."} + } +} diff --git a/seeds/calculator/calculate/contract.json b/packs/essentials/skills/calculator/calculate/contract.json similarity index 100% rename from seeds/calculator/calculate/contract.json rename to packs/essentials/skills/calculator/calculate/contract.json diff --git a/seeds/calculator/calculate/manifest.json b/packs/essentials/skills/calculator/calculate/manifest.json similarity index 100% rename from seeds/calculator/calculate/manifest.json rename to packs/essentials/skills/calculator/calculate/manifest.json diff --git a/seeds/calculator/calculate/skill.py b/packs/essentials/skills/calculator/calculate/skill.py similarity index 100% rename from seeds/calculator/calculate/skill.py rename to packs/essentials/skills/calculator/calculate/skill.py diff --git a/seeds/calculator/calculate/skill.test.py b/packs/essentials/skills/calculator/calculate/skill.test.py similarity index 100% rename from seeds/calculator/calculate/skill.test.py rename to packs/essentials/skills/calculator/calculate/skill.test.py diff --git a/seeds/time/date/contract.json b/packs/essentials/skills/time/date/contract.json similarity index 100% rename from seeds/time/date/contract.json rename to packs/essentials/skills/time/date/contract.json diff --git a/seeds/time/date/manifest.json b/packs/essentials/skills/time/date/manifest.json similarity index 100% rename from seeds/time/date/manifest.json rename to packs/essentials/skills/time/date/manifest.json diff --git a/seeds/time/date/skill.py b/packs/essentials/skills/time/date/skill.py similarity index 100% rename from seeds/time/date/skill.py rename to packs/essentials/skills/time/date/skill.py diff --git a/seeds/time/date/skill.test.py b/packs/essentials/skills/time/date/skill.test.py similarity index 100% rename from seeds/time/date/skill.test.py rename to packs/essentials/skills/time/date/skill.test.py diff --git a/seeds/time/now/contract.json b/packs/essentials/skills/time/now/contract.json similarity index 100% rename from seeds/time/now/contract.json rename to packs/essentials/skills/time/now/contract.json diff --git a/seeds/time/now/manifest.json b/packs/essentials/skills/time/now/manifest.json similarity index 100% rename from seeds/time/now/manifest.json rename to packs/essentials/skills/time/now/manifest.json diff --git a/seeds/time/now/skill.py b/packs/essentials/skills/time/now/skill.py similarity index 100% rename from seeds/time/now/skill.py rename to packs/essentials/skills/time/now/skill.py diff --git a/seeds/time/now/skill.test.py b/packs/essentials/skills/time/now/skill.test.py similarity index 100% rename from seeds/time/now/skill.test.py rename to packs/essentials/skills/time/now/skill.test.py diff --git a/seeds/time/set_alarm/contract.json b/packs/essentials/skills/time/set_alarm/contract.json similarity index 100% rename from seeds/time/set_alarm/contract.json rename to packs/essentials/skills/time/set_alarm/contract.json diff --git a/seeds/time/set_alarm/manifest.json b/packs/essentials/skills/time/set_alarm/manifest.json similarity index 100% rename from seeds/time/set_alarm/manifest.json rename to packs/essentials/skills/time/set_alarm/manifest.json diff --git a/seeds/time/set_alarm/skill.py b/packs/essentials/skills/time/set_alarm/skill.py similarity index 100% rename from seeds/time/set_alarm/skill.py rename to packs/essentials/skills/time/set_alarm/skill.py diff --git a/seeds/time/set_alarm/skill.test.py b/packs/essentials/skills/time/set_alarm/skill.test.py similarity index 100% rename from seeds/time/set_alarm/skill.test.py rename to packs/essentials/skills/time/set_alarm/skill.test.py diff --git a/seeds/time/set_timer/contract.json b/packs/essentials/skills/time/set_timer/contract.json similarity index 100% rename from seeds/time/set_timer/contract.json rename to packs/essentials/skills/time/set_timer/contract.json diff --git a/seeds/time/set_timer/manifest.json b/packs/essentials/skills/time/set_timer/manifest.json similarity index 100% rename from seeds/time/set_timer/manifest.json rename to packs/essentials/skills/time/set_timer/manifest.json diff --git a/seeds/time/set_timer/skill.py b/packs/essentials/skills/time/set_timer/skill.py similarity index 100% rename from seeds/time/set_timer/skill.py rename to packs/essentials/skills/time/set_timer/skill.py diff --git a/seeds/time/set_timer/skill.test.py b/packs/essentials/skills/time/set_timer/skill.test.py similarity index 100% rename from seeds/time/set_timer/skill.test.py rename to packs/essentials/skills/time/set_timer/skill.test.py diff --git a/packs/nextcloud/pack.json b/packs/nextcloud/pack.json new file mode 100644 index 0000000..bfb7de3 --- /dev/null +++ b/packs/nextcloud/pack.json @@ -0,0 +1,25 @@ +{ + "name": "nextcloud", + "title": "Nextcloud", + "concern": "The user's Nextcloud account: calendar events and scheduling, to-do tasks, files, contacts, and notes.", + "categories": { + "nextcloud": "Nextcloud productivity: the user's calendar events and scheduling (reading or changing events and reminders) and the user's to-do tasks and task lists." + }, + "bridges": ["nextcloud"], + "requires": [], + "enabled_by_default": true, + "config": { + "enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5230, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "url": {"type": "str", "default": "", "doc": "Nextcloud base URL, e.g. https://cloud.example.com."}, + "username": {"type": "str", "default": "", "doc": "Nextcloud username."}, + "app_password": {"type": "str", "default": "", "secret": true, "doc": "Nextcloud app password (Settings > Security > Devices & sessions), not the account password."}, + "default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none and the account has several."}, + "default_task_calendar": {"type": "str", "default": "", "doc": "VTODO-capable task list used when a request names none."}, + "default_addressbook": {"type": "str", "default": "", "doc": "Addressbook used when a request names none."}, + "verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification (self-signed hosts)."}, + "timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."} + } +} diff --git a/seeds/nextcloud/create_event/contract.json b/packs/nextcloud/skills/nextcloud/create_event/contract.json similarity index 100% rename from seeds/nextcloud/create_event/contract.json rename to packs/nextcloud/skills/nextcloud/create_event/contract.json diff --git a/seeds/nextcloud/create_event/manifest.json b/packs/nextcloud/skills/nextcloud/create_event/manifest.json similarity index 100% rename from seeds/nextcloud/create_event/manifest.json rename to packs/nextcloud/skills/nextcloud/create_event/manifest.json diff --git a/seeds/nextcloud/create_event/skill.py b/packs/nextcloud/skills/nextcloud/create_event/skill.py similarity index 100% rename from seeds/nextcloud/create_event/skill.py rename to packs/nextcloud/skills/nextcloud/create_event/skill.py diff --git a/seeds/nextcloud/create_event/skill.test.py b/packs/nextcloud/skills/nextcloud/create_event/skill.test.py similarity index 100% rename from seeds/nextcloud/create_event/skill.test.py rename to packs/nextcloud/skills/nextcloud/create_event/skill.test.py diff --git a/seeds/nextcloud/create_task/contract.json b/packs/nextcloud/skills/nextcloud/create_task/contract.json similarity index 100% rename from seeds/nextcloud/create_task/contract.json rename to packs/nextcloud/skills/nextcloud/create_task/contract.json diff --git a/seeds/nextcloud/create_task/manifest.json b/packs/nextcloud/skills/nextcloud/create_task/manifest.json similarity index 100% rename from seeds/nextcloud/create_task/manifest.json rename to packs/nextcloud/skills/nextcloud/create_task/manifest.json diff --git a/seeds/nextcloud/create_task/skill.py b/packs/nextcloud/skills/nextcloud/create_task/skill.py similarity index 100% rename from seeds/nextcloud/create_task/skill.py rename to packs/nextcloud/skills/nextcloud/create_task/skill.py diff --git a/seeds/nextcloud/create_task/skill.test.py b/packs/nextcloud/skills/nextcloud/create_task/skill.test.py similarity index 100% rename from seeds/nextcloud/create_task/skill.test.py rename to packs/nextcloud/skills/nextcloud/create_task/skill.test.py diff --git a/seeds/nextcloud/next_event/contract.json b/packs/nextcloud/skills/nextcloud/next_event/contract.json similarity index 100% rename from seeds/nextcloud/next_event/contract.json rename to packs/nextcloud/skills/nextcloud/next_event/contract.json diff --git a/seeds/nextcloud/next_event/manifest.json b/packs/nextcloud/skills/nextcloud/next_event/manifest.json similarity index 100% rename from seeds/nextcloud/next_event/manifest.json rename to packs/nextcloud/skills/nextcloud/next_event/manifest.json diff --git a/seeds/nextcloud/next_event/skill.py b/packs/nextcloud/skills/nextcloud/next_event/skill.py similarity index 100% rename from seeds/nextcloud/next_event/skill.py rename to packs/nextcloud/skills/nextcloud/next_event/skill.py diff --git a/seeds/nextcloud/next_event/skill.test.py b/packs/nextcloud/skills/nextcloud/next_event/skill.test.py similarity index 100% rename from seeds/nextcloud/next_event/skill.test.py rename to packs/nextcloud/skills/nextcloud/next_event/skill.test.py diff --git a/packs/outlook/pack.json b/packs/outlook/pack.json new file mode 100644 index 0000000..96c91bb --- /dev/null +++ b/packs/outlook/pack.json @@ -0,0 +1,26 @@ +{ + "name": "outlook", + "title": "Outlook", + "concern": "The user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph: mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files.", + "categories": { + "outlook": "Outlook / Microsoft 365: the user's mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files." + }, + "bridges": ["outlook"], + "requires": [], + "enabled_by_default": false, + "config": { + "enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs an Entra ID client id and an authorization run first."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5231, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "client_id": {"type": "str", "default": "", "doc": "Entra ID public-client app id (not a secret)."}, + "tenant": {"type": "str", "default": "common", "doc": "Entra tenant: common | organizations | consumers | a tenant id."}, + "token_path": {"type": "str", "default": ".runtime/outlook/token.json", "doc": "Where scripts/outlook-auth.py stores the tokens (0600)."}, + "default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none."}, + "default_task_list": {"type": "str", "default": "", "doc": "Microsoft To Do list used when a request names none."}, + "default_mail_folder": {"type": "str", "default": "inbox", "doc": "Mail folder read by default."}, + "default_timezone": {"type": "str", "default": "UTC", "doc": "IANA zone for created events/tasks whose start has no offset."}, + "verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification."}, + "timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."} + } +} diff --git a/seeds/outlook/create_event/contract.json b/packs/outlook/skills/outlook/create_event/contract.json similarity index 100% rename from seeds/outlook/create_event/contract.json rename to packs/outlook/skills/outlook/create_event/contract.json diff --git a/seeds/outlook/create_event/manifest.json b/packs/outlook/skills/outlook/create_event/manifest.json similarity index 100% rename from seeds/outlook/create_event/manifest.json rename to packs/outlook/skills/outlook/create_event/manifest.json diff --git a/seeds/outlook/create_event/skill.py b/packs/outlook/skills/outlook/create_event/skill.py similarity index 100% rename from seeds/outlook/create_event/skill.py rename to packs/outlook/skills/outlook/create_event/skill.py diff --git a/seeds/outlook/create_event/skill.test.py b/packs/outlook/skills/outlook/create_event/skill.test.py similarity index 100% rename from seeds/outlook/create_event/skill.test.py rename to packs/outlook/skills/outlook/create_event/skill.test.py diff --git a/seeds/outlook/create_task/contract.json b/packs/outlook/skills/outlook/create_task/contract.json similarity index 100% rename from seeds/outlook/create_task/contract.json rename to packs/outlook/skills/outlook/create_task/contract.json diff --git a/seeds/outlook/create_task/manifest.json b/packs/outlook/skills/outlook/create_task/manifest.json similarity index 100% rename from seeds/outlook/create_task/manifest.json rename to packs/outlook/skills/outlook/create_task/manifest.json diff --git a/seeds/outlook/create_task/skill.py b/packs/outlook/skills/outlook/create_task/skill.py similarity index 100% rename from seeds/outlook/create_task/skill.py rename to packs/outlook/skills/outlook/create_task/skill.py diff --git a/seeds/outlook/create_task/skill.test.py b/packs/outlook/skills/outlook/create_task/skill.test.py similarity index 100% rename from seeds/outlook/create_task/skill.test.py rename to packs/outlook/skills/outlook/create_task/skill.test.py diff --git a/seeds/outlook/list_contacts/contract.json b/packs/outlook/skills/outlook/list_contacts/contract.json similarity index 100% rename from seeds/outlook/list_contacts/contract.json rename to packs/outlook/skills/outlook/list_contacts/contract.json diff --git a/seeds/outlook/list_contacts/manifest.json b/packs/outlook/skills/outlook/list_contacts/manifest.json similarity index 100% rename from seeds/outlook/list_contacts/manifest.json rename to packs/outlook/skills/outlook/list_contacts/manifest.json diff --git a/seeds/outlook/list_contacts/skill.py b/packs/outlook/skills/outlook/list_contacts/skill.py similarity index 100% rename from seeds/outlook/list_contacts/skill.py rename to packs/outlook/skills/outlook/list_contacts/skill.py diff --git a/seeds/outlook/list_contacts/skill.test.py b/packs/outlook/skills/outlook/list_contacts/skill.test.py similarity index 100% rename from seeds/outlook/list_contacts/skill.test.py rename to packs/outlook/skills/outlook/list_contacts/skill.test.py diff --git a/seeds/outlook/list_files/contract.json b/packs/outlook/skills/outlook/list_files/contract.json similarity index 100% rename from seeds/outlook/list_files/contract.json rename to packs/outlook/skills/outlook/list_files/contract.json diff --git a/seeds/outlook/list_files/manifest.json b/packs/outlook/skills/outlook/list_files/manifest.json similarity index 100% rename from seeds/outlook/list_files/manifest.json rename to packs/outlook/skills/outlook/list_files/manifest.json diff --git a/seeds/outlook/list_files/skill.py b/packs/outlook/skills/outlook/list_files/skill.py similarity index 100% rename from seeds/outlook/list_files/skill.py rename to packs/outlook/skills/outlook/list_files/skill.py diff --git a/seeds/outlook/list_files/skill.test.py b/packs/outlook/skills/outlook/list_files/skill.test.py similarity index 100% rename from seeds/outlook/list_files/skill.test.py rename to packs/outlook/skills/outlook/list_files/skill.test.py diff --git a/seeds/outlook/next_event/contract.json b/packs/outlook/skills/outlook/next_event/contract.json similarity index 100% rename from seeds/outlook/next_event/contract.json rename to packs/outlook/skills/outlook/next_event/contract.json diff --git a/seeds/outlook/next_event/manifest.json b/packs/outlook/skills/outlook/next_event/manifest.json similarity index 100% rename from seeds/outlook/next_event/manifest.json rename to packs/outlook/skills/outlook/next_event/manifest.json diff --git a/seeds/outlook/next_event/skill.py b/packs/outlook/skills/outlook/next_event/skill.py similarity index 100% rename from seeds/outlook/next_event/skill.py rename to packs/outlook/skills/outlook/next_event/skill.py diff --git a/seeds/outlook/next_event/skill.test.py b/packs/outlook/skills/outlook/next_event/skill.test.py similarity index 100% rename from seeds/outlook/next_event/skill.test.py rename to packs/outlook/skills/outlook/next_event/skill.test.py diff --git a/seeds/outlook/next_message/contract.json b/packs/outlook/skills/outlook/next_message/contract.json similarity index 100% rename from seeds/outlook/next_message/contract.json rename to packs/outlook/skills/outlook/next_message/contract.json diff --git a/seeds/outlook/next_message/manifest.json b/packs/outlook/skills/outlook/next_message/manifest.json similarity index 100% rename from seeds/outlook/next_message/manifest.json rename to packs/outlook/skills/outlook/next_message/manifest.json diff --git a/seeds/outlook/next_message/skill.py b/packs/outlook/skills/outlook/next_message/skill.py similarity index 100% rename from seeds/outlook/next_message/skill.py rename to packs/outlook/skills/outlook/next_message/skill.py diff --git a/seeds/outlook/next_message/skill.test.py b/packs/outlook/skills/outlook/next_message/skill.test.py similarity index 100% rename from seeds/outlook/next_message/skill.test.py rename to packs/outlook/skills/outlook/next_message/skill.test.py diff --git a/seeds/outlook/send_message/contract.json b/packs/outlook/skills/outlook/send_message/contract.json similarity index 100% rename from seeds/outlook/send_message/contract.json rename to packs/outlook/skills/outlook/send_message/contract.json diff --git a/seeds/outlook/send_message/manifest.json b/packs/outlook/skills/outlook/send_message/manifest.json similarity index 100% rename from seeds/outlook/send_message/manifest.json rename to packs/outlook/skills/outlook/send_message/manifest.json diff --git a/seeds/outlook/send_message/skill.py b/packs/outlook/skills/outlook/send_message/skill.py similarity index 100% rename from seeds/outlook/send_message/skill.py rename to packs/outlook/skills/outlook/send_message/skill.py diff --git a/seeds/outlook/send_message/skill.test.py b/packs/outlook/skills/outlook/send_message/skill.test.py similarity index 100% rename from seeds/outlook/send_message/skill.test.py rename to packs/outlook/skills/outlook/send_message/skill.test.py diff --git a/packs/simplex/pack.json b/packs/simplex/pack.json new file mode 100644 index 0000000..4b90a2d --- /dev/null +++ b/packs/simplex/pack.json @@ -0,0 +1,26 @@ +{ + "name": "simplex", + "title": "SimpleX", + "concern": "SimpleX messaging through the forwarding bridge: reading incoming messages, sending messages to contacts, and showing the user's contact link.", + "categories": { + "simplex": "SimpleX messaging: reading incoming messages, sending messages to contacts, and showing the user's contact link." + }, + "bridges": ["simplex"], + "requires": [], + "enabled_by_default": true, + "config": { + "enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5227, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "max_inbox": {"type": "int", "default": 100, "doc": "Bound on the in-memory inbound-message buffer."}, + "ws_url": {"type": "str", "default": "ws://127.0.0.1:5228", "doc": "The bridge's OWN simplex-chat daemon WebSocket URL (must match simplex_chat.forward_port)."}, + "user_id": {"type": "int", "default": 1, "doc": "Daemon user id the bridge acts as."}, + "auto_accept": {"type": "bool", "default": true, "doc": "Auto-accept inbound contact requests."}, + "reconnect": { + "initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."}, + "max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."}, + "jitter": {"type": "float", "default": 0.2, "doc": "Reconnect jitter fraction."} + } + } +} diff --git a/seeds/simplex/connect_link/contract.json b/packs/simplex/skills/simplex/connect_link/contract.json similarity index 100% rename from seeds/simplex/connect_link/contract.json rename to packs/simplex/skills/simplex/connect_link/contract.json diff --git a/seeds/simplex/connect_link/manifest.json b/packs/simplex/skills/simplex/connect_link/manifest.json similarity index 100% rename from seeds/simplex/connect_link/manifest.json rename to packs/simplex/skills/simplex/connect_link/manifest.json diff --git a/seeds/simplex/connect_link/skill.py b/packs/simplex/skills/simplex/connect_link/skill.py similarity index 100% rename from seeds/simplex/connect_link/skill.py rename to packs/simplex/skills/simplex/connect_link/skill.py diff --git a/seeds/simplex/connect_link/skill.test.py b/packs/simplex/skills/simplex/connect_link/skill.test.py similarity index 100% rename from seeds/simplex/connect_link/skill.test.py rename to packs/simplex/skills/simplex/connect_link/skill.test.py diff --git a/seeds/simplex/next_message/contract.json b/packs/simplex/skills/simplex/next_message/contract.json similarity index 100% rename from seeds/simplex/next_message/contract.json rename to packs/simplex/skills/simplex/next_message/contract.json diff --git a/seeds/simplex/next_message/manifest.json b/packs/simplex/skills/simplex/next_message/manifest.json similarity index 100% rename from seeds/simplex/next_message/manifest.json rename to packs/simplex/skills/simplex/next_message/manifest.json diff --git a/seeds/simplex/next_message/skill.py b/packs/simplex/skills/simplex/next_message/skill.py similarity index 100% rename from seeds/simplex/next_message/skill.py rename to packs/simplex/skills/simplex/next_message/skill.py diff --git a/seeds/simplex/next_message/skill.test.py b/packs/simplex/skills/simplex/next_message/skill.test.py similarity index 100% rename from seeds/simplex/next_message/skill.test.py rename to packs/simplex/skills/simplex/next_message/skill.test.py diff --git a/seeds/simplex/send_message/contract.json b/packs/simplex/skills/simplex/send_message/contract.json similarity index 100% rename from seeds/simplex/send_message/contract.json rename to packs/simplex/skills/simplex/send_message/contract.json diff --git a/seeds/simplex/send_message/manifest.json b/packs/simplex/skills/simplex/send_message/manifest.json similarity index 100% rename from seeds/simplex/send_message/manifest.json rename to packs/simplex/skills/simplex/send_message/manifest.json diff --git a/seeds/simplex/send_message/skill.py b/packs/simplex/skills/simplex/send_message/skill.py similarity index 100% rename from seeds/simplex/send_message/skill.py rename to packs/simplex/skills/simplex/send_message/skill.py diff --git a/seeds/simplex/send_message/skill.test.py b/packs/simplex/skills/simplex/send_message/skill.test.py similarity index 100% rename from seeds/simplex/send_message/skill.test.py rename to packs/simplex/skills/simplex/send_message/skill.test.py diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 55f79ea..a6e7302 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -10,10 +10,12 @@ # re-cloned — only the SemIf engine and the simplex-chat binary are fetched. # Clone the agent 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, +# config.json is the per-machine USER config (a thin index over config/*.json) +# and this script NEVER rewrites it. It seeds the split config via `config-init` +# (config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json, +# the config.json index, and an empty secrets.json) only when config.json is +# absent, then reads every per-machine value from the merged config; only a human +# edits it afterwards. Pinned external refs (SemIf commit, GGUF url+sha256, # HF tokenizer revision, simplex-chat version/url+sha256) live in the committed # pins.json and the python dep pins in requirements/staging.txt — bump those # (via git) and rerun to upgrade. @@ -27,8 +29,8 @@ # Only artifacts that operationally must live elsewhere are outside: the SSH # key (~/.ssh) and the real systemd user dir/linger. # -# Flags override the values read from config.json FOR THIS RUN ONLY; nothing is -# written back to config.json. +# Flags override the values read from the merged config FOR THIS RUN ONLY; +# nothing is written back to the config. # # Usage: # scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL] @@ -104,13 +106,23 @@ if [[ ! -f "$PINS" ]]; then exit 1 fi -# config.json is per-machine USER config. Seed it once from the template, then -# never write it again — only a human edits config.json. +# config.json is per-machine USER config. Seed it once (as a thin index plus the +# split config/ fragments + secrets.json), then never write it again — only a +# human edits it. The committed config.example.json is GENERATED from the pack + +# core schemas; see `python -m semif_agent.cli check-config --write-example`. if [[ ! -f "$CONFIG" ]]; then - echo "== seeding config.json from config.example.json (edit it to configure this machine)" - cp "$EXAMPLE" "$CONFIG" + echo "== seeding config/ + secrets.json (edit them to configure this machine)" + PYTHONPATH="$REPO_ROOT${PYTHONPATH:+:$PYTHONPATH}" python3 -m semif_agent.cli config-init --path "$CONFIG" \ + || { echo "config-init failed; falling back to a flat config.json from the example" >&2; cp "$EXAMPLE" "$CONFIG"; } fi +# The live config may be split (config.json includes config/*.json); merge it so +# the reads below see one flat object. Stdlib-only, so it works before the venv. +MERGED_CONFIG="$RUNTIME/config.merged.json" +mkdir -p "$RUNTIME" +python3 "$REPO_ROOT/scripts/config_merge.py" "$CONFIG" > "$MERGED_CONFIG" \ + || { echo "could not read $CONFIG" >&2; exit 1; } + # --- read pins from the committed pins.json --------------------------------- # The ASCII unit separator (\x1f) delimits fields so an empty value never # shifts the fields after it (space-splitting collapses runs of whitespace). @@ -154,7 +166,7 @@ fi # --- read per-machine values from config.json (flags override for this run) -- IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_LLM_PROVIDER CFG_CODEGEN_URL CFG_CODEGEN_MODEL \ SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <( - python3 - "$CONFIG" <<'PY' + python3 - "$MERGED_CONFIG" <<'PY' import json, sys cfg = json.load(open(sys.argv[1])) s = cfg.get("simplex_chat", {}) @@ -263,7 +275,7 @@ fi # host must not get one. `--gpu ` forces a build; `--gpu auto` (the # default) builds a GPU backend only when config.json asks for offload # (`engine.gpu_layers` nonzero). -CONFIG_GPU_LAYERS="$(python3 - "$CONFIG" <<'PY' +CONFIG_GPU_LAYERS="$(python3 - "$MERGED_CONFIG" <<'PY' import json, sys try: print(int(json.load(open(sys.argv[1])).get("engine", {}).get("gpu_layers", 0) or 0)) @@ -373,7 +385,7 @@ fi if [[ "$BROWSER" = 1 ]]; then echo "== installing browser-bridge deps into $VENV" "$PIP" install -r "$REPO_ROOT/requirements/browser.txt" - BROWSER_ENGINE="$("$PYTHON" - "$CONFIG" <<'PY' 2>/dev/null || true + BROWSER_ENGINE="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true import json, sys try: cfg = json.load(open(sys.argv[1])) @@ -433,7 +445,7 @@ PY # warns (the gateway reports the missing model at startup) rather than aborting. if [[ "$VOICE" = 1 ]]; then echo "== downloading voice models (openWakeWord + Piper + faster-whisper)" - HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" --config "$CONFIG" \ + HF_HOME="$HF_CACHE" "$PYTHON" "$REPO_ROOT/scripts/voice-models.py" --config "$MERGED_CONFIG" \ || echo "WARN: voice model download failed; re-run scripts/voice-models.py" >&2 fi @@ -527,7 +539,7 @@ fi # --- stage 8c: forwarding bridge contact address -------------------------------------- # The forwarding bridge owns a second daemon/profile; its own contact link is the # one `simplex.connect_link` shows. Print it too so the user can share it. -BRIDGE_FORWARD_WS="$("$PYTHON" - "$REPO_ROOT/config.json" <<'PY' 2>/dev/null || true +BRIDGE_FORWARD_WS="$("$PYTHON" - "$MERGED_CONFIG" <<'PY' 2>/dev/null || true import json, sys try: cfg = json.load(open(sys.argv[1])) @@ -625,9 +637,11 @@ fi cat < dict: + for key, value in extra.items(): + if isinstance(value, dict) and isinstance(base.get(key), dict): + _deep_merge(base[key], value) + else: + base[key] = value + return base + + +def merge(path: Path, seen: set[Path] | None = None) -> dict: + seen = seen if seen is not None else set() + resolved = path.resolve() + if resolved in seen: + raise SystemExit(f"config include cycle at {path}") + seen.add(resolved) + data = json.loads(path.read_text()) + includes = data.pop("include", None) + merged: dict = {} + if includes: + for entry in includes: + inc = Path(entry) + if not inc.is_absolute(): + inc = path.parent / inc + _deep_merge(merged, merge(inc, seen)) + return _deep_merge(merged, data) + + +if __name__ == "__main__": + source = Path(sys.argv[1] if len(sys.argv) > 1 else "config.json") + print(json.dumps(merge(source))) diff --git a/scripts/tune_navigation.py b/scripts/tune_navigation.py index 4e3e2fe..0bf7e12 100644 --- a/scripts/tune_navigation.py +++ b/scripts/tune_navigation.py @@ -26,7 +26,7 @@ a host with the pinned engine: .runtime/venv/bin/python scripts/tune_navigation.py .runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6 -The tree is whatever the host currently has loaded (committed seeds + the runtime +The tree is whatever the host currently has loaded (committed packs + the runtime `data/skills/`), so an expectation naming a skill that is not present is reported as N/A rather than counted wrong. Labels are hand-written ground truth; self-labeled decision rows are not evidence. Nothing is written to the runtime diff --git a/semif_agent/bridges/nextcloud.py b/semif_agent/bridges/nextcloud.py index 34ed7c8..0146904 100644 --- a/semif_agent/bridges/nextcloud.py +++ b/semif_agent/bridges/nextcloud.py @@ -11,7 +11,7 @@ There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-on (`urllib` + `xml.etree`) and starts instantly. The connection comes from `bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook), falling back to the top-level `nextcloud_url`/`nextcloud_username`/ -`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud seeds +`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud pack's skills already use, so the same account is configured in one place. The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate diff --git a/semif_agent/bridges/registry.py b/semif_agent/bridges/registry.py index 2347126..e817e83 100644 --- a/semif_agent/bridges/registry.py +++ b/semif_agent/bridges/registry.py @@ -114,7 +114,7 @@ def build_bridge( `llm` is the scheduler's configured language-model client, handed to the LLM bridge so it reuses the top-level `llm` endpoint/model instead of duplicating that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a - fallback, so the same account the nextcloud seeds use is configured once. Other + fallback, so the same account the nextcloud pack's skills use is configured once. Other bridges ignore both. """ bridge_class = _class_for(name) diff --git a/semif_agent/cli.py b/semif_agent/cli.py index ca06f9b..38c51bc 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -23,6 +23,17 @@ from pathlib import Path from .dream import dream as run_dream from .codegen import CodegenClient +from .config import ( + ConfigError, + DEFAULT_SECRETS_FILE, + generate_example_config, + load_config_file, + load_secrets, + missing_secret_refs, + resolve_secrets, + validate_config, + write_split_config, +) from .console import ( OPENCODE_BASE_URL, ConsoleCodegenClient, @@ -33,6 +44,7 @@ from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine from .winnow import WinnowConfig, WinnowEngine from .llm import LLMClient, SemIfLLMClient from .log import DecisionLog +from .packs import load_packs from .scheduler import Scheduler from .skills import tree_summary from .trace import TraceLog @@ -43,7 +55,7 @@ REPO_ROOT = Path(__file__).resolve().parent.parent DEFAULT_WINNOW_URL = "http://127.0.0.1:8091" _PATH_KEYS = ( - "skill_seeds", + "skill_packs", "skill_bodies", "category_registry", "deleted_skills", @@ -51,7 +63,7 @@ _PATH_KEYS = ( "trace", ) _PATH_DEFAULTS = { - "skill_seeds": "seeds", + "skill_packs": "packs", "skill_bodies": "data/skills", "category_registry": "data/categories.json", "deleted_skills": "data/deleted_skills.json", @@ -66,18 +78,14 @@ def _anchor_path(value: str) -> str: def _resolve_api_key(cfg: dict) -> str: - """Service-account key for an authenticated provider. + """The configured API key. - A literal `api_key` wins; otherwise `api_key_env` names an environment - variable (preferred, so the secret never lands in config.json). + Secrets live in the gitignored `secrets.json` and are resolved to a literal + by `load_config` (a `"!secret "` value becomes its value); a literal key + in the block also works. There is deliberately no `api_key_env` — secrets.json + is the one place credentials live. """ - key = cfg.get("api_key") or "" - if key: - return str(key) - env = cfg.get("api_key_env") - if env: - return os.environ.get(str(env), "") - return "" + return str(cfg.get("api_key") or "") def _opt_float(value) -> float | None: @@ -112,8 +120,9 @@ def _provider_endpoint(cfg: dict, default_base: str) -> dict: `provider` selects the class (`opencode` → the Console client) and the base URL default: an explicit `base_url` always wins, else the Console URL for - `opencode` and `default_base` (ollama) otherwise. Auth comes from - `api_key`/`api_key_env`; `extra_headers` passes through for custom schemes. + `opencode` and `default_base` (ollama) otherwise. Auth comes from `api_key` + (a literal or a `!secret` value already resolved by `load_config`); + `extra_headers` passes through for custom schemes. """ provider = str(cfg.get("provider", "ollama") or "ollama").lower() base_url = cfg.get("base_url") or ( @@ -128,26 +137,35 @@ def _provider_endpoint(cfg: dict, default_base: str) -> dict: def load_config(path: str = "config.json") -> dict: - """Load config.json and anchor its runtime paths to the checkout root. + """Load the per-machine config and anchor its runtime paths to the checkout. - 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. + config.json is a thin index (`{"include": ["config/core.json", ...]}`); each + included fragment is deep-merged in order (later wins). Secrets are written + as `"!secret "` and resolved from the gitignored secrets file (default + `secrets.json` beside the index). The config is required: bootstrap seeds it + once and only a human edits it — there is no in-code fallback. - Path-valued keys (`skill_seeds`, `skill_bodies`, `category_registry`, `log`, + Path-valued keys (`skill_packs`, `skill_bodies`, `category_registry`, `log`, `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 packs and writes runtime artifacts into the checkout no matter where the CLI is invoked from. Absolute values pass through untouched. """ 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()) + try: + config = load_config_file(config_path) + except ConfigError as exc: + raise SystemExit(str(exc)) + secrets_path = config.get("secrets_file") or DEFAULT_SECRETS_FILE + secrets_path = Path(secrets_path) + if not secrets_path.is_absolute(): + secrets_path = config_path.parent / secrets_path + config = resolve_secrets(config, load_secrets(secrets_path)) for key in _PATH_KEYS: - config[key] = _anchor_path(config.get(key) or _PATH_DEFAULTS[key]) + value = config.get(key) + if isinstance(value, list): + config[key] = [_anchor_path(str(item)) for item in value] + else: + config[key] = _anchor_path(str(value or _PATH_DEFAULTS[key])) return config @@ -956,9 +974,86 @@ def run_bridge(scheduler: Scheduler, config: dict, name: str | None = None) -> i ) +def _anchor_pack_roots(raw: dict) -> list[str]: + """The pack roots from a raw (un-anchored) config, resolved against REPO_ROOT.""" + roots = raw.get("skill_packs") or "packs" + if isinstance(roots, (str, Path)): + roots = [roots] + anchored = [] + for root in roots: + path = Path(str(root)) + anchored.append(str(path if path.is_absolute() else REPO_ROOT / path)) + return anchored + + +def check_config(path: str = "config.json", write_example: str | None = None) -> int: + """Validate the split config against the core + pack schemas. + + With `write_example`, regenerate the committed `config.example.json` from + the schemas (the pack manifests + the core schema) instead of validating. + Validation reports type mismatches, unknown keys, and any `!secret` + reference missing from the secrets file. + """ + config_path = Path(path) + try: + raw = load_config_file(config_path) + except ConfigError as exc: + print(exc, file=sys.stderr) + return 1 + packs = load_packs({**raw, "skill_packs": _anchor_pack_roots(raw)}) + if write_example is not None: + example = generate_example_config(packs) + Path(write_example).write_text(json.dumps(example, indent=2) + "\n") + print(f"wrote {write_example} ({len(packs)} packs)") + return 0 + secrets_path = raw.get("secrets_file") or DEFAULT_SECRETS_FILE + secrets_path = Path(secrets_path) + if not secrets_path.is_absolute(): + secrets_path = config_path.parent / secrets_path + secrets = load_secrets(secrets_path) + problems = validate_config(raw, packs) + problems += [ + f"secret {key!r} referenced but missing from {secrets_path}" + for key in missing_secret_refs(raw, secrets) + ] + errors = [p for p in problems if not p.startswith("warning: ")] + for problem in problems: + print(f"config: {problem}", file=sys.stderr) + if errors: + return 1 + print(f"config ok: {len(packs)} packs validated") + return 0 + + +def config_init(path: str = "config.json") -> int: + """Seed a fresh split config + empty secrets file. Never overwrites. + + Writes ``config/core.json``, ``config/gateway.json``, ``config/bridges.json``, + ``config/packs/*.json`` and the ``config.json`` index from the schemas, plus + an empty ``secrets.json``. A human then edits the fragments and fills in the + secrets. + """ + config_path = Path(path) + if config_path.exists(): + print(f"{config_path} already exists; leaving it alone", file=sys.stderr) + return 1 + packs = load_packs({"skill_packs": _anchor_pack_roots({})}) + example = generate_example_config(packs) + written = write_split_config(config_path.parent, example, packs) + secrets_path = config_path.parent / DEFAULT_SECRETS_FILE + if not secrets_path.exists(): + secrets_path.write_text("{}\n") + print( + f"seeded {len(written)} config files under {config_path.parent or '.'}/ " + f"and {secrets_path.name}; edit them, then run `check-config`" + ) + return 0 + + def main(argv: list[str] | None = None) -> int: argv = list(argv) if argv is not None else list(sys.argv[1:]) - config = load_config(_extract_config_path(argv)) + config_path = _extract_config_path(argv) + config = load_config(config_path) parser = argparse.ArgumentParser(prog="semif-agent") parser.add_argument("--config", default="config.json") sub = parser.add_subparsers(dest="command") @@ -970,6 +1065,21 @@ def main(argv: list[str] | None = None) -> int: sub.add_parser("skills", help="list the skill tree") sub.add_parser("status", help="show current process and queue") + cc_p = sub.add_parser( + "check-config", help="validate config/ against the core + pack schemas" + ) + cc_p.add_argument( + "--write-example", + metavar="PATH", + default=None, + help="write the generated config.example.json to PATH and exit", + ) + + ci_p = sub.add_parser( + "config-init", help="seed a fresh split config/ + secrets.json (never overwrites)" + ) + ci_p.add_argument("--path", default="config.json", help="config index path to seed") + relabel_p = sub.add_parser("relabel", help="human override of a decision label") relabel_p.add_argument("id") relabel_p.add_argument("outcome") @@ -1009,6 +1119,12 @@ def main(argv: list[str] | None = None) -> int: ) args = parser.parse_args(argv) + + if args.command == "check-config": + return check_config(config_path, write_example=args.write_example) + if args.command == "config-init": + return config_init(args.path) + scheduler, config = build_scheduler(config) if args.command == "run": diff --git a/semif_agent/config.py b/semif_agent/config.py new file mode 100644 index 0000000..846341d --- /dev/null +++ b/semif_agent/config.py @@ -0,0 +1,527 @@ +"""Layered per-machine configuration. + +Mirrors Home Assistant's split-config model: + +* ``config.json`` is a **thin index** — ``{"include": ["config/core.json", + "config/packs/nextcloud.json", ...]}``. Each included file is an ordinary + config fragment; fragments are deep-merged in order (later wins). +* Secrets live in a gitignored ``secrets.json`` and are referenced from any + fragment with a ``"!secret "`` string, resolved at load (the analog of + HA's ``!secret`` tag). ``api_key_env`` is gone — every secret is a + ``secrets.json`` entry. +* Each skill pack ships its own config **schema** (``pack.json`` ``config``), + which owns the pack's defaults and drives both ``config.example.json`` + generation and ``check-config`` validation. + +The loader never hard-fails on a missing secret (a ``!secret`` with no entry +resolves to ``""``, matching the old empty-key behaviour); ``validate_config`` +is where a missing secret is reported. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Iterator + +SECRET_PREFIX = "!secret " +DEFAULT_SECRETS_FILE = "secrets.json" + +#: Core (non-pack) config schema. A section is a nested dict; a leaf is a dict +#: with a ``default`` key, or a bare scalar shorthand for ``{"default": ...}``. +#: ``doc`` documents the key (emitted as a ``_comment`` in the example), and +#: ``secret: true`` marks a value that must come from ``secrets.json``. +CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': 'Assessment accept threshold.'}, + 'max_reentries': {'default': 3, + 'type': 'int', + 'doc': 'Max times a `continue` step may re-enter routing for one request.'}, + 'query_recall_window': {'default': 30, + 'type': 'int', + 'doc': "Seconds a completed run's ledger stays recallable for a follow-up " + 'in the same chat (0 disables).'}, + 'new_skill_creation': {'default': 'allow', + 'type': 'str', + 'doc': 'Global tri-state new-skill mode: allow | deny | ask (a category ' + 'config overrides it).'}, + 'verbosity': {'default': 'result', + 'type': 'str', + 'doc': 'REPL reply verbosity: result | query | decision.'}, + 'chain': {'result_chars': {'default': 300, 'type': 'int'}}, + 'assess': {'done_tau': {'default': 0.5, 'type': 'float'}, + 'fail_tau': {'default': 0.5, 'type': 'float'}}, + 'timezone': {'default': '', + 'type': 'str', + 'doc': 'IANA zone (e.g. America/Chicago) the agent reports local time in; empty uses ' + 'the host zone.'}, + 'navigation': {'intent_tau': {'default': 0.6, 'type': 'float'}, + 'category_tau': {'default': 0.75, 'type': 'float'}, + 'action_tau': {'default': 0.5, 'type': 'float'}, + 'softmax_bypass_tau': {'default': 0.5, 'type': 'float'}}, + 'queue': {'max_size': {'default': 100, 'type': 'int'}}, + 'engine': {'provider': {'default': 'semif', 'type': 'str'}, + 'backend': {'default': 'llamacpp', 'type': 'str'}, + 'context_tokens': {'default': 4096, 'type': 'int'}, + 'threads': {'default': 8, 'type': 'int'}, + 'gpu_layers': {'default': 0, 'type': 'int'}, + 'gpu_device': {'default': None, 'type': 'null'}, + 'gpu_split': {'default': 0, 'type': 'int'}, + 'winnow': {'base_url': {'default': 'http://127.0.0.1:8091', 'type': 'str'}, + 'model': {'default': '', 'type': 'str'}, + 'context_tokens': {'default': 32768, 'type': 'int'}, + 'api_key': {'default': '', 'type': 'str', 'secret': True}, + 'timeout': {'default': 120, 'type': 'int'}, + 'retries': {'default': 0, 'type': 'int'}, + 'user_agent': {'default': 'semif-agent', 'type': 'str'}, + 'extra_headers': {'default': {}, 'type': 'dict'}}, + 'gguf': {'default': '', 'type': 'str'}}, + 'llm': {'provider': {'default': 'ollama', 'type': 'str'}, + 'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'}, + 'model': {'default': '', 'type': 'str'}, + 'api_key': {'default': '', 'type': 'str', 'secret': True}, + 'user_agent': {'default': '', 'type': 'str'}, + 'timeout': {'default': 600, 'type': 'int'}, + 'stream': {'default': False, 'type': 'bool'}, + 'idle_warn': {'default': 30, 'type': 'int'}, + 'idle_timeout': {'default': 120, 'type': 'int'}, + 'context_window': {'default': 0, 'type': 'int'}, + 'temperature': {'default': 0.2, 'type': 'float'}, + 'top_p': {'default': 0.9, 'type': 'float'}, + 'presence_penalty': {'default': 0.0, 'type': 'float'}, + 'frequency_penalty': {'default': 0.0, 'type': 'float'}, + 'disable_thinking': {'default': True, 'type': 'bool'}, + 'semif': {'temperature': {'default': 0.0, 'type': 'float'}, + 'max_tokens': {'default': 256, 'type': 'int'}}}, + 'codegen': {'provider': {'default': 'ollama', 'type': 'str'}, + 'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'}, + 'model': {'default': '', 'type': 'str'}, + 'api_key': {'default': '', 'type': 'str', 'secret': True}, + 'user_agent': {'default': '', 'type': 'str'}, + 'timeout': {'default': 3600, 'type': 'int'}, + 'stream': {'default': True, 'type': 'bool'}, + 'idle_warn': {'default': 60, 'type': 'int'}, + 'idle_timeout': {'default': 180, 'type': 'int'}, + 'context_window': {'default': 0, 'type': 'int'}, + 'smart_limit': {'default': 250000, 'type': 'int'}, + 'warn_limit': {'default': 500000, 'type': 'int'}, + 'max_fill_ratio': {'default': 0.9, 'type': 'float'}, + 'warn_fill_ratio': {'default': 0.7, 'type': 'float'}, + 'max_output': {'default': 0.85, 'type': 'float'}, + 'chars_per_token': {'default': 4.0, 'type': 'float'}, + 'temperature': {'default': 1, 'type': 'int'}, + 'top_p': {'default': 0.95, 'type': 'float'}, + 'presence_penalty': {'default': 0, 'type': 'int'}, + 'frequency_penalty': {'default': 1, 'type': 'int'}, + 'max_attempts': {'default': 3, 'type': 'int'}, + 'approval': {'wait_timeout': {'default': 900, 'type': 'int'}}, + 'fidelity': {'enabled': {'default': True, 'type': 'bool'}, + 'max_attempts': {'default': 1, 'type': 'int'}, + 'tau': {'default': 0.6, 'type': 'float'}}, + 'repair': {'enabled': {'default': True, 'type': 'bool'}, + 'max_attempts': {'default': 1, 'type': 'int'}}, + 'test_timeout': {'default': 30, 'type': 'int'}, + 'test_max_attempts': {'default': 3, 'type': 'int'}, + 'max_body_tokens': {'default': 0, 'type': 'int'}, + 'max_test_tokens': {'default': 0, 'type': 'int'}, + 'decision_reserve_tokens': {'default': 1024, 'type': 'int'}, + 'contract_search': {'enabled': {'default': True, 'type': 'bool'}}, + 'degeneration': {'enabled': {'default': True, 'type': 'bool'}, + 'threshold': {'default': 0.9, 'type': 'float'}, + 'interval': {'default': 8000, 'type': 'int'}, + 'window': {'default': 2000, 'type': 'int'}, + 'min_chars': {'default': 4000, 'type': 'int'}}}, + 'skill_bodies': {'default': 'data/skills', 'type': 'str'}, + 'log': {'default': 'data/decisions.jsonl', 'type': 'str'}, + 'trace': {'default': 'data/runs.jsonl', 'type': 'str'}, + 'category_registry': {'default': 'data/categories.json', 'type': 'str'}, + 'simplex_chat': {'port': {'default': 5226, 'type': 'int'}, + 'display_name': {'default': 'semif', 'type': 'str'}, + 'forward_port': {'default': 5228, 'type': 'int'}, + 'forward_display_name': {'default': 'semif-forward', 'type': 'str'}}, + 'gateway': {'humanize': {'enabled': {'default': True, 'type': 'bool'}, + 'timeout': {'default': 20.0, 'type': 'float'}, + 'max_tokens': {'default': 200, 'type': 'int'}, + 'max_chars': {'default': 600, 'type': 'int'}}, + 'simplex': {'enabled': {'default': True, 'type': 'bool'}, + 'ws_url': {'default': 'ws://127.0.0.1:5226', 'type': 'str'}, + 'allowed_users': {'default': [], 'type': 'list'}, + 'allow_all_users': {'default': False, 'type': 'bool'}, + 'auto_accept': {'default': True, 'type': 'bool'}, + 'home_channel': {'default': '', 'type': 'str'}, + 'reply_prefix': {'default': '', 'type': 'str'}, + 'text_batch_delay': {'default': 0.8, 'type': 'float'}, + 'reconnect': {'initial': {'default': 1.0, 'type': 'float'}, + 'max': {'default': 60.0, 'type': 'float'}, + 'jitter': {'default': 0.2, 'type': 'float'}}}, + 'lxmf': {'enabled': {'default': False, 'type': 'bool'}, + 'allowed_users': {'default': [], 'type': 'list'}, + 'allow_all_users': {'default': False, 'type': 'bool'}, + 'display_name': {'default': 'semif', 'type': 'str'}, + 'announce_interval': {'default': 3600, 'type': 'int'}, + 'stamp_cost': {'default': 8, 'type': 'int'}, + 'desired_method': {'default': 'direct', 'type': 'str'}, + 'propagation_node': {'default': '', 'type': 'str'}, + 'config_dir': {'default': '', 'type': 'str'}, + 'storage_path': {'default': '', 'type': 'str'}, + 'home_channel': {'default': '', 'type': 'str'}, + 'reply_prefix': {'default': '', 'type': 'str'}, + 'text_batch_delay': {'default': 0.8, 'type': 'float'}}, + 'voice': {'enabled': {'default': False, 'type': 'bool'}, + 'chat_id': {'default': 'voice', 'type': 'str'}, + 'display_name': {'default': 'voice', 'type': 'str'}, + 'home_channel': {'default': 'voice', 'type': 'str'}, + 'reply_prefix': {'default': '', 'type': 'str'}, + 'result_only': {'default': True, 'type': 'bool'}, + 'max_speak_chars': {'default': 600, 'type': 'int'}, + 'listen_timeout_s': {'default': 3.0, 'type': 'float'}, + 'cue': {'enabled': {'default': True, 'type': 'bool'}, + 'frequency': {'default': 880, 'type': 'int'}, + 'duration_ms': {'default': 120, 'type': 'int'}, + 'volume': {'default': 0.9, 'type': 'float'}, + 'submit_frequency': {'default': 0, 'type': 'int'}, + 'submit_duration_ms': {'default': 100, 'type': 'int'}, + 'submit_notes': {'default': [[1046.5, 70], [1568.0, 90]], + 'type': 'list'}, + 'note_gap_ms': {'default': 20, 'type': 'int'}}, + 'wake': {'model': {'default': 'hey_computer', 'type': 'str'}, + 'threshold': {'default': 0.2, 'type': 'float'}, + 'inference_framework': {'default': 'onnx', 'type': 'str'}, + 'model_dir': {'default': '', 'type': 'str'}}, + 'stt': {'model': {'default': 'base.en', 'type': 'str'}, + 'device': {'default': 'cpu', 'type': 'str'}, + 'compute_type': {'default': 'int8', 'type': 'str'}, + 'language': {'default': 'en', 'type': 'str'}}, + 'tts': {'voice': {'default': 'en_US-lessac-medium', 'type': 'str'}, + 'voice_dir': {'default': '', 'type': 'str'}, + 'speaker_id': {'default': 0, 'type': 'int'}, + 'length_scale': {'default': 1.0, 'type': 'float'}, + 'volume': {'default': 1.0, 'type': 'float'}}, + 'audio': {'input_device': {'default': '', 'type': 'str'}, + 'output_device': {'default': '', 'type': 'str'}, + 'sample_rate': {'default': 16000, 'type': 'int'}, + 'frame_ms': {'default': 80, 'type': 'int'}, + 'capture_sample_rate': {'default': 0, 'type': 'int'}, + 'output_sample_rate': {'default': 0, 'type': 'int'}, + 'dc_removal': {'default': True, 'type': 'bool'}, + 'read_timeout_s': {'default': 1.0, 'type': 'float'}, + 'stall_timeout_s': {'default': 5.0, 'type': 'float'}}, + 'vad': {'silence_ms': {'default': 500, 'type': 'int'}, + 'min_speech_ms': {'default': 120, 'type': 'int'}, + 'max_utterance_s': {'default': 30, 'type': 'int'}, + 'min_command_ms': {'default': 700, 'type': 'int'}, + 'initial_silence_ms': {'default': 1500, 'type': 'int'}, + 'aggressiveness': {'default': 2, 'type': 'int'}, + 'energy_threshold': {'default': 200.0, 'type': 'float'}}, + 'follow_up_window_s': {'default': 0.0, 'type': 'float'}}}, + 'dashboard': {'port': {'default': 8765, 'type': 'int'}, + 'host': {'default': '127.0.0.1', 'type': 'str'}}, + 'skill_packs': {'default': 'packs', + 'type': 'str', + 'doc': 'Path to the packs directory (scanned for */pack.json) or a list of pack ' + 'roots.'}, + 'secrets_file': {'default': 'secrets.json', + 'type': 'str', + 'doc': 'Path to the gitignored secrets file, relative to config.json.'}} + + +#: Bridges that are not owned by any pack — shared services a pack may call. +#: They still live under ``bridges.`` so ``derived_config_vars`` and +#: ``run_bridges`` find them, and they are validated/generated like pack bridges. +SHARED_BRIDGE_SCHEMA: dict[str, Any] = { + "llm": { + "enabled": {"type": "bool", "default": True, "doc": "Run the generic LLM bridge (a POST /chat in front of the configured `llm` model)."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5229, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": True, "doc": "Shared secret required in the X-Semif-Token header when set."}, + }, +} + + +class ConfigError(Exception): + """A malformed or inconsistent configuration.""" + + +def read_json_object(path: Path) -> dict: + if not path.is_file(): + raise ConfigError(f"config file not found: {path}") + try: + data = json.loads(path.read_text()) + except ValueError as exc: + raise ConfigError(f"invalid JSON in {path}: {exc}") from exc + if not isinstance(data, dict): + raise ConfigError(f"config file must be a JSON object: {path}") + return data + + +def deep_merge(base: dict, extra: dict) -> dict: + """Merge `extra` into `base` in place; dicts recurse, everything else wins.""" + for key, value in extra.items(): + if isinstance(value, dict) and isinstance(base.get(key), dict): + deep_merge(base[key], value) + else: + base[key] = value + return base + + +def load_config_file(path: str | Path, _seen: set[Path] | None = None) -> dict: + """Load one config file, following its top-level ``include`` list. + + Includes are resolved relative to the including file and merged first, so a + file's own keys override anything it includes. Cycles are an error. + """ + config_path = Path(path) + resolved = config_path.resolve() + seen = _seen if _seen is not None else set() + if resolved in seen: + raise ConfigError(f"config include cycle at {config_path}") + seen.add(resolved) + data = read_json_object(config_path) + includes = data.pop("include", None) + merged: dict = {} + if includes: + if not isinstance(includes, list): + raise ConfigError(f"`include` must be a list in {config_path}") + for entry in includes: + inc_path = Path(entry) + if not inc_path.is_absolute(): + inc_path = config_path.parent / inc_path + deep_merge(merged, load_config_file(inc_path, seen)) + deep_merge(merged, data) + return merged + + +def load_secrets(path: str | Path | None) -> dict: + """Load the gitignored secrets file. Absent or malformed yields ``{}``.""" + if not path: + return {} + secrets_path = Path(path) + if not secrets_path.is_file(): + return {} + try: + data = json.loads(secrets_path.read_text()) + except ValueError: + return {} + return data if isinstance(data, dict) else {} + + +def iter_secret_refs(value: Any) -> Iterator[str]: + """Every ``!secret `` key referenced anywhere in a config value.""" + if isinstance(value, str) and value.startswith(SECRET_PREFIX): + yield value[len(SECRET_PREFIX):].strip() + elif isinstance(value, dict): + for item in value.values(): + yield from iter_secret_refs(item) + elif isinstance(value, list): + for item in value: + yield from iter_secret_refs(item) + + +def resolve_secrets(value: Any, secrets: dict) -> Any: + """Replace every ``"!secret "`` string with its value (missing -> "").""" + if isinstance(value, str) and value.startswith(SECRET_PREFIX): + return secrets.get(value[len(SECRET_PREFIX):].strip(), "") + if isinstance(value, dict): + return {key: resolve_secrets(item, secrets) for key, item in value.items()} + if isinstance(value, list): + return [resolve_secrets(item, secrets) for item in value] + return value + + +def _schema_defaults(schema: dict) -> dict: + """Build a defaults dict from a (possibly nested) schema.""" + out: dict = {} + for key, spec in schema.items(): + if isinstance(spec, dict) and "default" not in spec: + out[key] = _schema_defaults(spec) + elif isinstance(spec, dict): + out[key] = spec["default"] + else: + out[key] = spec + return out + + +def default_config(packs=None) -> dict: + """The full default config: core schema defaults + every pack's defaults. + + A pack's ``config`` schema maps onto its ``bridges.`` block (bridge + packs) or ``packs.`` (bridge-less packs). Used by bootstrap to seed a + fresh split config and by ``generate_example_config``. + """ + config = _schema_defaults(CORE_SCHEMA) + config.setdefault("bridges", {}).update(_schema_defaults(SHARED_BRIDGE_SCHEMA)) + for pack in packs or []: + block = _schema_defaults(pack.config) + if pack.bridges: + config.setdefault("bridges", {})[pack.bridges[0]] = block + else: + config.setdefault("packs", {}).setdefault(pack.name, {})["enabled"] = block.pop("enabled", True) + return config + + +def generate_example_config(packs=None) -> dict: + """The committed ``config.example.json``: defaults with ``!secret`` refs. + + A secret-typed key is emitted as ``"!secret _"`` so the example + never carries a real credential. The example is a flat (un-split) mirror of + the live ``config/`` layout, for reference and for bootstrap to seed from. + """ + config = _schema_defaults(CORE_SCHEMA) + config["_comment"] = ( + "GENERATED from the core schema (semif_agent/config.py) and each pack's " + "pack.json `config` schema — do not hand-edit; edit a pack's schema or " + "the core schema. This is the reference example; the live per-machine " + "config is split under config/ (see config.json's include list) and " + "secrets live in the gitignored secrets.json, referenced as " + "'!secret '." + ) + _mark_secrets(config, CORE_SCHEMA, "") + shared = _schema_defaults(SHARED_BRIDGE_SCHEMA) + for name, spec in SHARED_BRIDGE_SCHEMA.items(): + _mark_secrets(shared[name], spec, f"{name}_") + config.setdefault("bridges", {}).update(shared) + for pack in packs or []: + block = _schema_defaults(pack.config) + _mark_secrets(block, pack.config, f"{pack.name}_") + if pack.bridges: + config.setdefault("bridges", {})[pack.bridges[0]] = block + else: + config.setdefault("packs", {}).setdefault(pack.name, {})["enabled"] = block.pop("enabled", True) + return config + + +def _mark_secrets(values: dict, schema: dict, prefix: str, path: str = "") -> None: + for key, spec in schema.items(): + if not isinstance(spec, dict): + continue + if "default" in spec: + if spec.get("secret"): + values[key] = f"{SECRET_PREFIX}{prefix}{path}{key}" + elif isinstance(values.get(key), dict): + _mark_secrets(values[key], spec, prefix, f"{path}{key}_") + + +def _type_name(value: Any) -> str: + if value is None: + return "null" + if isinstance(value, bool): + return "bool" + if isinstance(value, int): + return "int" + if isinstance(value, float): + return "float" + if isinstance(value, str): + return "str" + if isinstance(value, list): + return "list" + if isinstance(value, dict): + return "dict" + return type(value).__name__ + + +def _check_schema(values: dict, schema: dict, path: str, problems: list[str]) -> None: + for key, spec in schema.items(): + if not isinstance(spec, dict) or "default" not in spec: + if isinstance(spec, dict): + child = values.get(key) + if isinstance(child, dict): + _check_schema(child, spec, f"{path}{key}.", problems) + continue + if key not in values: + continue + expected = spec.get("type") + actual = _type_name(values[key]) + if expected and actual != expected: + # int/float are interchangeable for numeric knobs. + numeric = {expected, actual} <= {"int", "float"} + if not numeric: + problems.append(f"{path}{key}: expected {expected}, got {actual}") + # Unknown keys are a warning (the schema documents the code's keys; a config + # may legitimately carry forward a key the schema hasn't caught up to). + known = set(schema) + for key in values: + if key.startswith("_") or key == "include": + continue + if key not in known: + problems.append(f"warning: {path}{key}: unknown config key") + + +def validate_config(config: dict, packs=None) -> list[str]: + """Validate a merged config against the core + pack schemas. + + Returns a list of human-readable problems (empty == valid). Secret refs are + checked against ``secrets.json`` so a missing credential is reported here + rather than silently resolving to "". + """ + problems: list[str] = [] + # `bridges` and `packs` are pack-owned; they are validated per pack below. + core = {k: v for k, v in config.items() if k not in ("bridges", "packs")} + _check_schema(core, CORE_SCHEMA, "", problems) + bridges = config.get("bridges", {}) or {} + for name, spec in SHARED_BRIDGE_SCHEMA.items(): + block = bridges.get(name) + if isinstance(block, dict): + _check_schema(block, spec, f"bridges.{name}.", problems) + for pack in packs or []: + if pack.bridges: + block = (config.get("bridges", {}) or {}).get(pack.bridges[0]) + if isinstance(block, dict): + _check_schema(block, pack.config, f"bridges.{pack.bridges[0]}.", problems) + else: + block = (config.get("packs", {}) or {}).get(pack.name) + if isinstance(block, dict): + _check_schema(block, {"enabled": pack.config.get("enabled", True)}, f"packs.{pack.name}.", problems) + return problems + + +def missing_secret_refs(config: dict, secrets: dict) -> list[str]: + """Secret keys referenced by the config but absent from secrets.json.""" + return sorted({key for key in iter_secret_refs(config) if key not in secrets}) + + +def split_config(config: dict, packs=None) -> dict[str, dict]: + """Split a merged config into the ``config/`` layout. + + Returns a map of relative path -> fragment. Core keys go to + ``config/core.json``; ``gateway`` to ``config/gateway.json``; bridges not + owned by a pack to ``config/bridges.json``; each pack's bridge block and + enable flag to ``config/packs/.json``; and ``config.json`` becomes the + thin index listing them in order. + """ + owner = {bridge: pack.name for pack in (packs or []) for bridge in pack.bridges} + by_name = {pack.name: pack for pack in (packs or [])} + files: dict[str, dict] = {} + core = { + key: value + for key, value in config.items() + if key not in ("bridges", "gateway", "packs", "_comment") + } + files["config/core.json"] = core + if config.get("gateway"): + files["config/gateway.json"] = {"gateway": config["gateway"]} + bridges = config.get("bridges", {}) or {} + shared = {name: block for name, block in bridges.items() if name not in owner} + if shared: + files["config/bridges.json"] = {"bridges": shared} + pack_cfg = config.get("packs", {}) or {} + for name, pack in by_name.items(): + fragment: dict = {} + owned = {bridge: bridges[bridge] for bridge in pack.bridges if bridge in bridges} + if owned: + fragment["bridges"] = owned + if pack_cfg.get(name): + fragment["packs"] = {name: pack_cfg[name]} + if fragment: + files[f"config/packs/{name}.json"] = fragment + files["config.json"] = {"include": list(files)} + return files + + +def write_split_config(root: str | Path, config: dict, packs=None) -> list[str]: + """Write the ``config/`` layout under `root`; returns the paths written.""" + base = Path(root) + written = [] + for rel, fragment in split_config(config, packs).items(): + target = base / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(fragment, indent=2) + "\n") + written.append(str(target)) + return written diff --git a/semif_agent/console.py b/semif_agent/console.py index fffe9b4..a400b14 100644 --- a/semif_agent/console.py +++ b/semif_agent/console.py @@ -17,7 +17,8 @@ models use different wire formats and would need their own adapters. ``build_scheduler`` selects these classes from ``llm.provider`` / ``codegen.provider`` (``"opencode"`` vs the default ``"ollama"``) and passes -``api_key`` (or ``api_key_env``). The error contracts are preserved: the `llm` +``api_key`` (a literal or a ``!secret`` value already resolved by +``load_config``). The error contracts are preserved: the `llm` variant still raises ``LLMError`` and the codegen variant ``CodegenError`` / ``DegenerationError``, so existing callers keep catching their own types. """ diff --git a/semif_agent/packs.py b/semif_agent/packs.py new file mode 100644 index 0000000..75e6de0 --- /dev/null +++ b/semif_agent/packs.py @@ -0,0 +1,187 @@ +"""Skill packs: bundles of skills associated with a concern, product, or bridge. + +A pack is a folder with a ``pack.json`` manifest and a ``skills/`` store:: + + packs/nextcloud/ + pack.json + skills/nextcloud/{create_event,create_task,next_event}/ + +The manifest binds the pieces that used to be scattered by convention — the +concern, its category descriptions, the bridge(s) it talks to, its runtime +requirements, and its config schema/defaults — so "the Nextcloud product, its +bridge, its skills, and its settings" are one thing. Bridge *code* stays in +``semif_agent/bridges`` (isolation is non-negotiable); a pack references a +bridge by name. + +A pack can be enabled/disabled as a unit: disabling it drops its categories from +the tree and stops its bridge (see ``pack_enabled``). This is the same switch +for skills and the bridge, so a host never offers a skill whose bridge is off. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path + +from .skills import CATEGORY_DESCRIPTIONS, SkillStore, merge_seed_store + +MANIFEST = "pack.json" + + +@dataclass +class SkillPack: + """One concern/product bundle: manifest metadata + its skill store.""" + + name: str + title: str + concern: str + categories: dict[str, str] = field(default_factory=dict) + bridges: tuple[str, ...] = () + requires: tuple[str, ...] = () + enabled_by_default: bool = True + config: dict = field(default_factory=dict) + path: Path = field(default_factory=Path) + store: SkillStore = field(default_factory=SkillStore) + + def category_names(self) -> list[str]: + return list(self.categories) or sorted( + {category for category, _ in self.store.list_skills()} + ) + + +def _parse_pack(manifest_path: Path) -> SkillPack: + data = json.loads(manifest_path.read_text()) + root = manifest_path.parent + name = str(data.get("name") or root.name).strip() + categories = { + str(key): str(value) + for key, value in (data.get("categories") or {}).items() + } + return SkillPack( + name=name, + title=str(data.get("title") or name), + concern=str(data.get("concern") or data.get("description") or "").strip(), + categories=categories, + bridges=tuple(str(b) for b in (data.get("bridges") or [])), + requires=tuple(str(r) for r in (data.get("requires") or [])), + enabled_by_default=bool(data.get("enabled_by_default", True)), + config=dict(data.get("config") or {}), + path=root, + store=SkillStore(str(root / "skills")), + ) + + +class PackRegistry: + """Discovers packs from one or more roots. + + A root is either a single pack directory (contains ``pack.json``), a + directory of packs (each subdirectory with a ``pack.json``), or a plain + skills directory (no manifest — treated as one manifest-less pack whose + store is the root itself). + """ + + def __init__(self, roots): + if isinstance(roots, (str, Path)): + roots = [roots] + self.roots = [Path(root) for root in roots] + self._packs: list[SkillPack] | None = None + + def discover(self) -> list[SkillPack]: + if self._packs is not None: + return self._packs + packs: list[SkillPack] = [] + seen: set[str] = set() + for root in self.roots: + for pack in self._packs_from_root(root): + if pack.name in seen: + continue + seen.add(pack.name) + packs.append(pack) + self._packs = packs + return packs + + @staticmethod + def _packs_from_root(root: Path) -> list[SkillPack]: + if (root / MANIFEST).is_file(): + return [_parse_pack(root / MANIFEST)] + if root.is_dir(): + child_manifests = sorted( + child / MANIFEST + for child in root.iterdir() + if child.is_dir() and (child / MANIFEST).is_file() + ) + if child_manifests: + return [_parse_pack(manifest) for manifest in child_manifests] + # A plain skills directory: one implicit, manifest-less pack. + if any(child.is_dir() for child in root.iterdir()): + return [ + SkillPack( + name=root.name or "pack", + title=root.name or "pack", + concern="", + path=root, + store=SkillStore(str(root)), + ) + ] + return [] + + def get(self, name: str) -> SkillPack | None: + return next((p for p in self.discover() if p.name == name), None) + + +def load_packs(config: dict) -> list[SkillPack]: + """Discover every pack from the ``skill_packs`` config root(s).""" + roots = config.get("skill_packs") or "packs" + return PackRegistry(roots).discover() + + +def pack_enabled(config: dict, pack: SkillPack) -> bool: + """Is this pack enabled? One switch governs skills *and* its bridge. + + An explicit ``packs..enabled`` wins. Otherwise a bridge pack follows + its bridge's ``bridges..enabled`` (the historical switch), and a + bridge-less pack falls back to ``enabled_by_default``. + """ + override = (config.get("packs", {}) or {}).get(pack.name) + if isinstance(override, dict) and "enabled" in override: + return bool(override["enabled"]) + if pack.bridges: + block = (config.get("bridges", {}) or {}).get(pack.bridges[0], {}) or {} + return bool(block.get("enabled", pack.enabled_by_default)) + return pack.enabled_by_default + + +def disabled_categories(config: dict, packs: list[SkillPack]) -> set[str]: + """Categories owned by a disabled pack (dropped from the tree).""" + cats: set[str] = set() + for pack in packs: + if not pack_enabled(config, pack): + cats.update(pack.category_names()) + return cats + + +def merge_packs( + tree: dict, + packs: list[SkillPack], + config: dict, + config_store: SkillStore | None = None, +) -> int: + """Load every enabled pack's skills into the tree. Returns the count. + + A disabled pack contributes nothing; a later pass drops any of its + categories that a generated body may have added (see the scheduler). + """ + loaded = 0 + for pack in packs: + if not pack_enabled(config, pack): + continue + descriptions = {**CATEGORY_DESCRIPTIONS, **pack.categories} + loaded += merge_seed_store( + tree, + pack.store, + config_store, + category_descriptions=descriptions, + origin="seed", + ) + return loaded diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 3b82e74..bc85931 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -38,6 +38,7 @@ from .engine import DecisionEngine, EngineUnavailable from .llm import LLMClient from .log import DecisionLog from .provider import ProviderError +from .packs import disabled_categories, load_packs, merge_packs from .queue import RequestQueue from .skill import SkillRunner from .timers import TimerService @@ -411,7 +412,9 @@ class Scheduler: registry_path = config.get("category_registry", "data/categories.json") self.registry = CategoryRegistry(registry_path) self.body_store = SkillStore(config.get("skill_bodies", "data/skills")) - self.seed_store = SkillStore(config.get("skill_seeds", "seeds")) + # Packs bundle committed starter skills with their concern, category + # scope, bridge, and config schema. A disabled pack contributes nothing. + self.packs = load_packs(config) # Deletions are durable: a tombstone suppresses a seed (or a generated # body of the same name) on every future load. Derived from the registry # path when not configured, so a test store is self-contained. @@ -420,9 +423,14 @@ class Scheduler: ) self.deleted = DeletedSkills(deleted_path) merge_registry(self.tree, self.registry.read()) - merge_seed_store(self.tree, self.seed_store, self.body_store) + merge_packs(self.tree, self.packs, config, self.body_store) merge_skill_store(self.tree, self.body_store, self.registry.read()) apply_tombstones(self.tree, self.deleted) + # A disabled pack's categories are dropped entirely — including any + # generated body authored into one — so the tree never offers a skill + # whose pack (and bridge) is off. + for category in disabled_categories(config, self.packs): + self.tree.pop(category, None) self.timers = TimerService(trace=self.trace, timezone=config.get("timezone")) self.ctx = ActionContext( engine=self.engine, config=config, timers=self.timers, admin=self diff --git a/semif_agent/skills.py b/semif_agent/skills.py index cccb0b2..279cc43 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -68,9 +68,9 @@ class Skill: integration: dict = field(default_factory=dict) integration_source: str = "unknown" category_description: str = "" - # Where the leaf came from: "builtin" (hardcoded), "seed" (committed starter - # package), or "generated" (codegen-authored). Built-ins are protected from - # delete/restart/regen; seeds and generated leaves are deletable (durably, + # Where the leaf came from: "builtin" (hardcoded), "seed" (a committed pack + # skill), or "generated" (codegen-authored). Built-ins are protected from + # delete/restart/regen; pack and generated leaves are deletable (durably, # via a tombstone). origin: str = "generated" @@ -310,10 +310,10 @@ class SkillStore: class DeletedSkills: """A persisted set of deleted skill refs (`category.name`). - Seeds reload from the committed `seeds/` tree on every startup, so deleting - one from the running tree would be undone on the next boot. Recording the - ref here suppresses it (and any generated body of the same name) at load - time, making deletion durable. Restoring a skill means removing its ref. + Committed pack skills reload from `packs/` on every startup, so deleting one + from the running tree would be undone on the next boot. Recording the ref + here suppresses it (and any generated body of the same name) at load time, + making deletion durable. Restoring a skill means removing its ref. """ def __init__(self, path: str = "data/deleted_skills.json"): @@ -496,6 +496,8 @@ def merge_seed_store( tree: dict[str, list[Skill]], seed_store: SkillStore, config_store: SkillStore | None = None, + category_descriptions: dict[str, str] | None = None, + origin: str = "seed", ) -> int: """Load committed starter skills from a read-only seed store into the tree. @@ -504,8 +506,11 @@ def merge_seed_store( its description), so it is inspectable and testable exactly like a codegen body. `config_store` is the runtime store (`data/skills`): recorded answers — credentials collected at first fire — live there, never in the committed - seed folder. Returns the number of skills loaded. + seed folder. `category_descriptions` supplies each category's scope (a + pack's manifest, merged over the built-in defaults); `origin` labels where + the leaf came from. Returns the number of skills loaded. """ + descriptions = category_descriptions if category_descriptions is not None else CATEGORY_DESCRIPTIONS loaded = 0 for category, name in seed_store.list_skills(): directory = seed_store.dir(category, name) @@ -533,8 +538,8 @@ def merge_seed_store( contract=contract, integration=integration, integration_source=integration_source, - category_description=CATEGORY_DESCRIPTIONS.get(category, ""), - origin="seed", + category_description=descriptions.get(category, ""), + origin=origin, ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): @@ -718,40 +723,18 @@ _CANNED_RESPONSES = [ _RESPONSE_MESSAGES = {f"response.{name}": message for name, _, message in _CANNED_RESPONSES} -# Built-in category descriptions. A category level that offers only bare names -# carries no signal (real runs sent "book a flight to japan" to the `simplex` -# bucket 0.49 vs create_category 0.12); giving the model the category's scope -# flips that to create_category 0.87 vs simplex 0.02. Authored categories carry -# their own description from the registry; this is the seed for the built-ins and -# the fallback for a legacy entry with no description. +# Built-in category descriptions. Authored categories carry their own +# description from the registry, and pack categories carry theirs from the +# pack manifest (`packs//pack.json` -> `categories`); this dict is only +# the seed for the two hardcoded built-in categories below. A category level +# that offers only bare names carries no signal (real runs sent "book a flight +# to japan" to the `simplex` bucket 0.49 vs create_category 0.12); giving the +# model the category's scope flips that to create_category 0.87 vs simplex 0.02. CATEGORY_DESCRIPTIONS: dict[str, str] = { "response": ( "Anything that is not a request to perform an action or produce a result: " "greetings, thanks, acknowledgements, chit-chat, and off-topic statements." ), - "nextcloud": ( - "Nextcloud productivity: the user's calendar events and scheduling " - "(reading or changing events and reminders) and the user's to-do tasks " - "and task lists." - ), - "simplex": ( - "SimpleX messaging: reading incoming messages, sending messages to " - "contacts, and showing the user's contact link." - ), - "time": ( - "Time and date utilities: telling the current time or date, setting " - "countdown timers, and setting alarms." - ), - "calculator": ( - "Arithmetic: evaluating a numeric expression the user asks for — " - "addition, subtraction, multiplication, division, powers and exponents, " - "squares, cubes, square roots, cube roots, fractions, and percentages." - ), - "browser": ( - "Browser automation: opening a web page, reading its text or links, " - "taking a screenshot, and clicking, typing, or filling forms to carry " - "out a task on a website." - ), "housekeeping": ( "Agent self-maintenance: deleting, reconfiguring, regenerating, and " "cancelling the agent's own skills." @@ -763,10 +746,10 @@ def build_skills(config: dict) -> list[Skill]: """The hardcoded built-ins: internal behaviors only. Real integrations do not live here — they are authored by the codegen - pipeline into `data/skills/` or shipped as seed skill packages under - `seeds/`. A fabricated built-in here shadows the authoring path for a real - one (navigation routes to it), so keep this list to behaviors that need no - external service. + pipeline into `data/skills/` or shipped as skill packs under `packs/` + (see `semif_agent.packs`). A fabricated built-in here shadows the authoring + path for a real one (navigation routes to it), so keep this list to behaviors + that need no external service. The `response` category is a closed tree of canned replies (see CANNED_CATEGORIES): it is the catchall for inputs that are not tasks, and it diff --git a/tests/test_codegen_privacy.py b/tests/test_codegen_privacy.py index 78afe7b..53a5d4d 100644 --- a/tests/test_codegen_privacy.py +++ b/tests/test_codegen_privacy.py @@ -175,7 +175,7 @@ def _scheduler(tmp_path) -> Scheduler: "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..7870875 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,114 @@ +"""The layered config: index includes, !secret resolution, and schema validation. + +These exercise the Home-Assistant-style split directly: config.json is a thin +index over fragments, secrets live in a separate file referenced as +``"!secret "``, and the core + pack schemas own defaults and validate a +live config. +""" + +import json +from pathlib import Path + +from semif_agent.config import ( + ConfigError, + generate_example_config, + iter_secret_refs, + load_config_file, + load_secrets, + missing_secret_refs, + resolve_secrets, + split_config, + validate_config, + write_split_config, +) +from semif_agent.packs import load_packs + + +def _write(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) + + +def test_index_includes_deep_merge_later_wins(tmp_path): + _write(tmp_path / "config" / "core.json", {"tau": 0.6, "queue": {"max_size": 10}}) + _write(tmp_path / "config" / "gateway.json", {"gateway": {"simplex": {"enabled": True}}}) + _write( + tmp_path / "config.json", + {"include": ["config/core.json", "config/gateway.json"]}, + ) + config = load_config_file(tmp_path / "config.json") + assert config["tau"] == 0.6 + assert config["queue"]["max_size"] == 10 + assert config["gateway"]["simplex"]["enabled"] is True + + +def test_include_cycle_is_an_error(tmp_path): + _write(tmp_path / "a.json", {"include": ["b.json"]}) + _write(tmp_path / "b.json", {"include": ["a.json"]}) + try: + load_config_file(tmp_path / "a.json") + except ConfigError as exc: + assert "cycle" in str(exc) + else: + raise AssertionError("expected a cycle error") + + +def test_secret_resolution_and_missing_refs(tmp_path): + _write(tmp_path / "secrets.json", {"nextcloud_app_password": "s3cret"}) + secrets = load_secrets(tmp_path / "secrets.json") + config = { + "bridges": {"nextcloud": {"app_password": "!secret nextcloud_app_password"}}, + "llm": {"api_key": "!secret absent_key"}, + } + assert list(iter_secret_refs(config)) == ["nextcloud_app_password", "absent_key"] + resolved = resolve_secrets(config, secrets) + assert resolved["bridges"]["nextcloud"]["app_password"] == "s3cret" + # A missing secret resolves to "" at load (startup never hard-fails) ... + assert resolved["llm"]["api_key"] == "" + # ... and is reported by the validator. + assert missing_secret_refs(config, secrets) == ["absent_key"] + + +def test_generate_example_marks_secrets_and_never_leaks_values(tmp_path): + packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")}) + example = generate_example_config(packs) + # Every secret-typed key is a !secret ref, never a value. + assert example["codegen"]["api_key"] == "!secret codegen_api_key" + assert example["bridges"]["nextcloud"]["app_password"] == "!secret nextcloud_app_password" + assert example["bridges"]["nextcloud"]["token"] == "!secret nextcloud_token" + # The pack's non-secret defaults are present. + assert example["bridges"]["nextcloud"]["port"] == 5230 + assert example["packs"]["essentials"]["enabled"] is True + + +def test_validate_config_reports_types_unknowns_and_secrets(tmp_path): + _write(tmp_path / "secrets.json", {}) + config = { + "tau": "not-a-number", + "totally_unknown_key": 1, + "codegen": {"api_key": "!secret codegen_api_key"}, + } + problems = validate_config(config, packs=[]) + assert any("tau: expected float" in p for p in problems) + assert any("warning: totally_unknown_key: unknown config key" in p for p in problems) + assert "codegen_api_key" in missing_secret_refs(config, load_secrets(tmp_path / "secrets.json")) + + +def test_split_then_load_roundtrip(tmp_path): + packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")}) + merged = generate_example_config(packs) + written = write_split_config(tmp_path, merged, packs) + assert any(p.endswith("config/core.json") for p in written) + assert any(p.endswith("config/packs/nextcloud.json") for p in written) + # The written index reloads to the same core values. + reloaded = load_config_file(tmp_path / "config.json") + assert reloaded["tau"] == merged["tau"] + assert reloaded["bridges"]["nextcloud"]["port"] == 5230 + + +def test_split_config_places_shared_bridge_outside_packs(tmp_path): + packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")}) + merged = generate_example_config(packs) + files = split_config(merged, packs) + assert "bridges" in files["config/bridges.json"] + assert "llm" in files["config/bridges.json"]["bridges"] diff --git a/tests/test_console.py b/tests/test_console.py index a977ce5..0abcb1c 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -235,13 +235,11 @@ def test_list_models_parses_catalog(): def test_provider_endpoint_selects_console_and_resolves_key(monkeypatch): from semif_agent import cli - monkeypatch.setenv("MY_CONSOLE_KEY", "envkey") console = cli._provider_endpoint( - {"provider": "opencode", "api_key_env": "MY_CONSOLE_KEY"}, - "http://localhost:11434/v1", + {"provider": "opencode"}, "http://localhost:11434/v1" ) assert console["base_url"] == OPENCODE_BASE_URL - assert console["api_key"] == "envkey" + assert console["api_key"] == "" ollama = cli._provider_endpoint({"provider": "ollama"}, "http://localhost:11434/v1") assert ollama["base_url"] == "http://localhost:11434/v1" @@ -250,6 +248,13 @@ def test_provider_endpoint_selects_console_and_resolves_key(monkeypatch): literal = cli._provider_endpoint({"provider": "opencode", "api_key": "lit"}, "x") assert literal["api_key"] == "lit" + # api_key_env is gone: it is ignored, never resolved from the environment. + monkeypatch.setenv("MY_CONSOLE_KEY", "envkey") + legacy = cli._provider_endpoint( + {"provider": "opencode", "api_key_env": "MY_CONSOLE_KEY"}, "x" + ) + assert legacy["api_key"] == "" + explicit = cli._provider_endpoint( {"provider": "opencode", "base_url": "https://example.test/v1"}, "x" ) diff --git a/tests/test_dashboard_api.py b/tests/test_dashboard_api.py index c784257..46d5ca0 100644 --- a/tests/test_dashboard_api.py +++ b/tests/test_dashboard_api.py @@ -34,7 +34,7 @@ def build_scheduler(tmp_path, engine=None): log=log, config={ "skills": {}, - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), "skill_bodies": str(tmp_path / "skills"), "category_registry": str(tmp_path / "categories.json"), "deleted_skills": str(tmp_path / "deleted_skills.json"), diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 0533673..560e667 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -36,7 +36,7 @@ def build_scheduler(tmp_path): engine=engine, llm=llm, log=log, - config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")}, + config={"skills": {}, "skill_packs": str(tmp_path / "seeds")}, trace=trace, ) diff --git a/tests/test_housekeeping.py b/tests/test_housekeeping.py index 7dfeb69..6a91756 100644 --- a/tests/test_housekeeping.py +++ b/tests/test_housekeeping.py @@ -55,7 +55,7 @@ def _scheduler(tmp_path, choices=None, default="success"): "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), "deleted_skills": str(tmp_path / "deleted_skills.json"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), diff --git a/tests/test_input_channel.py b/tests/test_input_channel.py index 54d9635..dc39d7c 100644 --- a/tests/test_input_channel.py +++ b/tests/test_input_channel.py @@ -26,7 +26,7 @@ def build_scheduler(tmp_path, choices=None): engine=engine, llm=llm, log=log, - config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")}, + config={"skills": {}, "skill_packs": str(tmp_path / "seeds")}, trace=trace, ) diff --git a/tests/test_packs.py b/tests/test_packs.py new file mode 100644 index 0000000..055153b --- /dev/null +++ b/tests/test_packs.py @@ -0,0 +1,154 @@ +"""The committed pack skills are real, inspectable, and hermetically tested. + +A pack ships starter integrations in the repo in the CODEGEN.md folder format, +grouped by concern under ``packs//skills///``. These tests +keep every pack skill honest: the declared integration must match the code, the +contract must cover what the body reads, and the hermetic mechanics test must +pass. They are not proof of the live integration — only a real run against the +user's service is (see AGENTS.md). +""" + +import json +import os +from pathlib import Path + +import pytest + +from semif_agent.codegen import ( + integration_findings, + parse_contract, + parse_integration, + run_skill_test, +) +from semif_agent.packs import ( + disabled_categories, + load_packs, + merge_packs, + pack_enabled, +) + +PACKS = Path(__file__).resolve().parent.parent / "packs" +SKILL_DIRS = sorted(path.parent for path in PACKS.glob("*/skills/*/*/skill.py")) + + +def seed_id(seed: Path) -> str: + return f"{seed.parent.name}.{seed.name}" + + +def test_pack_manifests_are_valid(): + packs = load_packs({"skill_packs": str(PACKS)}) + assert {p.name for p in packs} >= { + "nextcloud", + "simplex", + "outlook", + "browser", + "essentials", + } + for pack in packs: + assert pack.concern, f"{pack.name} must declare a concern" + assert pack.categories, f"{pack.name} must declare its categories" + + +def test_pack_enabled_resolution(): + packs = {p.name: p for p in load_packs({"skill_packs": str(PACKS)})} + # A bridge pack follows its bridge's enabled flag. + assert pack_enabled({"bridges": {"nextcloud": {"enabled": False}}}, packs["nextcloud"]) is False + assert pack_enabled({"bridges": {"nextcloud": {"enabled": True}}}, packs["nextcloud"]) is True + # An explicit packs..enabled wins over the bridge flag. + assert ( + pack_enabled( + {"bridges": {"nextcloud": {"enabled": False}}, "packs": {"nextcloud": {"enabled": True}}}, + packs["nextcloud"], + ) + is True + ) + # A bridge-less pack uses enabled_by_default. + assert pack_enabled({}, packs["essentials"]) is True + assert pack_enabled({"packs": {"essentials": {"enabled": False}}}, packs["essentials"]) is False + # browser defaults off (needs the optional deps). + assert pack_enabled({}, packs["browser"]) is False + + +def test_merge_packs_loads_enabled_and_skips_disabled(): + packs = load_packs({"skill_packs": str(PACKS)}) + tree: dict = {} + config = {"bridges": {"nextcloud": {"enabled": True}, "outlook": {"enabled": False}}} + merge_packs(tree, packs, config) + assert "nextcloud" in tree + assert "time" in tree and "calculator" in tree # the essentials pack + assert "outlook" not in tree # disabled pack contributes nothing + assert "browser" not in tree + assert disabled_categories(config, packs) >= {"outlook", "browser"} + # A pack skill is labeled `seed` (a committed starter), not `generated`. + assert all(s.origin == "seed" for s in tree["nextcloud"]) + # The pack's category description rides on the skill (feeds navigation). + assert tree["nextcloud"][0].category_description + + +def test_manifestless_pack_root_is_one_implicit_pack(tmp_path): + directory = tmp_path / "my_skills" / "widgets" / "frobnicate" + directory.mkdir(parents=True) + (directory / "skill.py").write_text("def act(ctx, request):\n return None\n") + packs = load_packs({"skill_packs": str(tmp_path / "my_skills")}) + assert len(packs) == 1 + assert ("widgets", "frobnicate") in packs[0].store.list_skills() + + +def test_expected_seeds_exist(): + ids = {seed_id(seed) for seed in SKILL_DIRS} + assert "nextcloud.next_event" in ids + assert "nextcloud.create_event" in ids + assert "simplex.next_message" in ids + assert "simplex.send_message" in ids + assert "simplex.connect_link" in ids + assert "time.now" in ids + assert "time.date" in ids + assert "time.set_timer" in ids + assert "time.set_alarm" in ids + assert "nextcloud.create_task" in ids + assert "calculator.calculate" in ids + assert "browser.open_page" in ids + assert "browser.read_page" in ids + assert "browser.screenshot" in ids + + +@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS]) +def test_seed_declares_a_real_integration(seed): + code = (seed / "skill.py").read_text() + integration = parse_integration(code) + assert integration["service"] + assert integration["transport"] + assert integration_findings(integration, "declared", code) == [] + + +@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS]) +def test_seed_contract_is_flat_and_covered_by_declaration(seed): + code = (seed / "skill.py").read_text() + contract = parse_contract(code) + integration = parse_integration(code) + assert set(integration["config_vars"]) == set(contract) + mirror = json.loads((seed / "contract.json").read_text()) + assert mirror == contract, "contract.json must mirror the CONTRACT constant" + if integration["transport"] == "compute": + # A local compute skill acts on the machine itself and needs no + # configuration; an empty contract is legitimate. + return + assert contract, "an external-integration seed must declare a CONTRACT constant" + for name, description in contract.items(): + assert name.islower() and " " not in name, name + assert isinstance(description, str) and description.strip() + + +@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS]) +def test_seed_has_manifest_description(seed): + manifest = json.loads((seed / "manifest.json").read_text()) + assert manifest["description"].strip() + + +@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS]) +def test_seed_hermetic_test_passes(seed, monkeypatch): + root = str(seed.parents[4]) + existing = os.environ.get("PYTHONPATH", "") + monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing) + passed, output = run_skill_test(seed, timeout=30) + assert passed, output diff --git a/tests/test_seed_skills.py b/tests/test_seed_skills.py deleted file mode 100644 index e7dc98b..0000000 --- a/tests/test_seed_skills.py +++ /dev/null @@ -1,88 +0,0 @@ -"""The committed seed skills are real, inspectable, and hermetically tested. - -A seed is a starter integration shipped in the repo in the CODEGEN.md folder -format. These tests keep every seed honest: the declared integration must match -the code, the contract must cover what the body reads, and the hermetic -mechanics test must pass. They are not proof of the live integration — only a -real run against the user's service is (see AGENTS.md). -""" - -import json -import os -from pathlib import Path - -import pytest - -from semif_agent.codegen import ( - integration_findings, - parse_contract, - parse_integration, - run_skill_test, -) - -SEEDS = Path(__file__).resolve().parent.parent / "seeds" -SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py")) - - -def seed_id(seed: Path) -> str: - return f"{seed.parent.name}.{seed.name}" - - -def test_expected_seeds_exist(): - ids = {seed_id(seed) for seed in SEED_DIRS} - assert "nextcloud.next_event" in ids - assert "nextcloud.create_event" in ids - assert "simplex.next_message" in ids - assert "simplex.send_message" in ids - assert "simplex.connect_link" in ids - assert "time.now" in ids - assert "time.date" in ids - assert "time.set_timer" in ids - assert "time.set_alarm" in ids - assert "nextcloud.create_task" in ids - assert "calculator.calculate" in ids - assert "browser.open_page" in ids - assert "browser.read_page" in ids - assert "browser.screenshot" in ids - - -@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) -def test_seed_declares_a_real_integration(seed): - code = (seed / "skill.py").read_text() - integration = parse_integration(code) - assert integration["service"] - assert integration["transport"] - assert integration_findings(integration, "declared", code) == [] - - -@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) -def test_seed_contract_is_flat_and_covered_by_declaration(seed): - code = (seed / "skill.py").read_text() - contract = parse_contract(code) - integration = parse_integration(code) - assert set(integration["config_vars"]) == set(contract) - mirror = json.loads((seed / "contract.json").read_text()) - assert mirror == contract, "contract.json must mirror the CONTRACT constant" - if integration["transport"] == "compute": - # A local compute skill acts on the machine itself and needs no - # configuration; an empty contract is legitimate. - return - assert contract, "an external-integration seed must declare a CONTRACT constant" - for name, description in contract.items(): - assert name.islower() and " " not in name, name - assert isinstance(description, str) and description.strip() - - -@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) -def test_seed_has_manifest_description(seed): - manifest = json.loads((seed / "manifest.json").read_text()) - assert manifest["description"].strip() - - -@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) -def test_seed_hermetic_test_passes(seed, monkeypatch): - root = str(seed.parents[2]) - existing = os.environ.get("PYTHONPATH", "") - monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing) - passed, output = run_skill_test(seed, timeout=30) - assert passed, output diff --git a/tests/test_skills.py b/tests/test_skills.py index f95d45d..e955826 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -143,7 +143,7 @@ def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosit "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), } if verbosity is not None: config["verbosity"] = verbosity @@ -561,7 +561,7 @@ def test_merge_seed_store_falls_back_to_name_and_body_store_wins(tmp_path): def test_scheduler_loads_committed_seed_skills(tmp_path): """The real seed package ships in the tree at startup with its manifest description and declared integration.""" - seed_root = Path(__file__).resolve().parent.parent / "seeds" + seed_root = Path(__file__).resolve().parent.parent / "packs" scheduler = Scheduler( engine=SemIfEngine(EngineConfig()), llm=LLMClient(base_url="http://localhost:1/v1", model="test"), @@ -569,7 +569,7 @@ def test_scheduler_loads_committed_seed_skills(tmp_path): config={ "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(seed_root), + "skill_packs": str(seed_root), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) @@ -586,20 +586,20 @@ def test_scheduler_loads_committed_seed_skills(tmp_path): def test_load_config_anchors_runtime_paths_to_checkout(tmp_path): """Path-valued config keys resolve against the checkout, not the cwd, so a - fresh clone finds its committed seeds from anywhere; absolute paths pass + fresh clone finds its committed packs from anywhere; absolute paths pass through untouched.""" config_file = tmp_path / "config.json" config_file.write_text( json.dumps( { - "skill_seeds": "seeds", + "skill_packs": "packs", "skill_bodies": "data/skills", "log": "/absolute/decisions.jsonl", } ) ) config = load_config(str(config_file)) - assert config["skill_seeds"] == str(REPO_ROOT / "seeds") + assert config["skill_packs"] == str(REPO_ROOT / "packs") assert config["skill_bodies"] == str(REPO_ROOT / "data/skills") assert config["category_registry"] == str(REPO_ROOT / "data/categories.json") assert config["log"] == "/absolute/decisions.jsonl" @@ -607,7 +607,7 @@ def test_load_config_anchors_runtime_paths_to_checkout(tmp_path): def test_committed_seeds_load_from_a_foreign_cwd(tmp_path, monkeypatch): - """A fresh checkout's seeds come from the anchored `seeds/` path even when + """A fresh checkout's packs come from the anchored `packs/` path even when the process runs from an unrelated directory (the zero-skills regression: relative paths resolved against cwd, so the tree was only response.reject and navigation fell into the codegen loop).""" @@ -615,7 +615,7 @@ def test_committed_seeds_load_from_a_foreign_cwd(tmp_path, monkeypatch): config_file.write_text( json.dumps( { - "skill_seeds": "seeds", + "skill_packs": "packs", "skill_bodies": str(tmp_path / "skills"), "category_registry": str(tmp_path / "categories.json"), "log": str(tmp_path / "decisions.jsonl"), @@ -1168,7 +1168,7 @@ def test_dispatch_action_tau_controls_catchall_routing(tmp_path): "navigation": {"action_tau": action_tau}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) @@ -1212,7 +1212,7 @@ def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path): "navigation": {"intent_tau": intent_tau}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) @@ -1350,7 +1350,7 @@ def test_dispatch_confident_leaf_winner_still_runs_intent_guard(tmp_path): "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) @@ -1396,7 +1396,7 @@ def test_dispatch_create_category_queues_draft_and_is_not_fatal(tmp_path): "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=trace, ) @@ -2499,7 +2499,7 @@ def test_chain_continues_then_completes(tmp_path): "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), ) @@ -2585,7 +2585,7 @@ def test_compound_request_runs_part_step_then_chains(tmp_path): "skills": {}, "category_registry": str(tmp_path / "categories.json"), "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), + "skill_packs": str(tmp_path / "seeds"), }, trace=TraceLog(str(tmp_path / "runs.jsonl")), )