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/<name>/ with a pack.json manifest + skills/<category>/<leaf>/.
  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.<name>.enabled -> bridges.<bridge>.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 <key>";
  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).
This commit is contained in:
gabby committed 2026-10-13 14:20:35 +00:00
1 parent b953475bf7
commit 78b4621ba0
115 files changed
+1701 -398

No files matched your search

+1 -1
View File
@@ -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
+1 -1
View File
@@ -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)
+144 -28
View File
@@ -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 <key>"` 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 <key>"` 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":
+527
View File
@@ -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 <key>"`` 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.<name>`` 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>`` 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 <key>"`` 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.<name>`` block (bridge
packs) or ``packs.<name>`` (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 <pack>_<key>"`` 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 <key>'."
)
_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/<name>.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
+2 -1
View File
@@ -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.
"""
+187
View File
@@ -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.<name>.enabled`` wins. Otherwise a bridge pack follows
its bridge's ``bridges.<bridge>.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
+10 -2
View File
@@ -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
+26 -43
View File
@@ -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/<name>/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