Compare commits

...
68 Commits
Author SHA1 Message Date
gabby addbe53392 engine: add the ollama System One provider
A third decision-engine provider alongside the local SemIf GGUF and the
remote Winnow server: `engine.provider == "ollama"` talks to ollama's
native `/v1/systemone` route via `semif_agent/ollama_systemone.py`.

It reuses the Winnow DecisionRequest -> choice mapping and the same strict
distribution validation over exactly the requested option ids, and adds
the edges only ollama has:

- no `/health`: `warm()` probes `GET /api/version` + `POST /api/show`,
  which also proves the model is pulled and advertises the `decision`
  capability;
- `engine.ollama.context_tokens: 0` follows the model's real `num_ctx`
  from `/api/show`;
- `keep_alive` rides on the request, criteria descriptions use the ollama
  subset `string | null`, and a choice question needs >= 2 options;
- decision models do not generate text, so `generate()` raises
  `EngineUnavailable` (use `llm.provider == "ollama"` for chat).

Every failure is an `EngineUnavailable` (fatal, like the local engine) and
the engine lock still serializes on the single-slot server.

`cli.build_engine` selects it, the setup interview and `--answers` accept
it, and the install plan skips the engine clone/GGUF/tokenizer for it.
Docs, config.example.json, and tests updated.
2026-11-11 02:57:53 +00:00
gabby 894a85ec2d read-aloud: stream a long text over the voice gateways
A skill that resolves a long text (a book) can hand it to the scheduler's
speech channel and return immediately; the gateway that owns the chat drains it
and streams it with text-to-speech until the user stops it.

- semif_agent/speech.py: SpeechService + ReadAloud. A bounded queue a front end
  drains, plus a per-source streaming predicate (set_stream_check/supports) so a
  skill asks before it posts one. Neutral and stdlib-only.
- semif_agent/reading.py: the bookmarks.json beside the saved books (load/save/
  read a key -> last offset, atomic write) and a deterministic speakable
  chunker at paragraph/sentence boundaries.
- Scheduler owns the channel (scheduler.speech); SkillRunner passes it into
  every run's ActionContext, so a body reaches it as ctx.speech.
- gateway/service: registers stream_ready as the channel's capability
  predicate, and surface() routes a drained read to the platform that owns the
  run (a non-streaming adapter is traced and skipped, never handed a message it
  would drop).
- gateway/voice: streams the saved text through the daemon's Piper voice chunk
  by chunk, writing the bookmark before each chunk; a barge-in "stop" or any new
  command ends it.
- gateway/lxmf: a read goes to a chat that last messaged by voice as a sequence
  of Sideband HQ voice messages (Piper -> Opus/OGG, backpressure so a stop is
  prompt), with the same bookmark-per-chunk resume; a "stop" message or any new
  command interrupts it.
- A run that registers a read is terminal (read_aloud_terminal): the read is the
  answer, so assess:outcome must not re-dispatch the request (which otherwise
  authored a spurious skill).
- config.example.json regenerated with the new voice/lxmf read blocks.
2026-10-17 23:29:53 +00:00
gabby faebe8a53a voice: wake-word barge-in (interrupt a spoken reply)
While a reply is speaking the wake word is still scored, so the user can
interrupt it. On a wake the daemon aborts the playback, mutes further
speech while the interrupt is captured/handled, and hands the following
command to the front end. A bare "stop"/"cancel" aborts the reply and
drops anything queued behind it; anything else runs as a new command.

- voice_transport: AudioIO.play(pcm, rate, stop_event); SoundDeviceAudio
  streams in ~50 ms chunks and aborts the output stream on a stop.
  VoiceDaemon gains barge_in.{enabled,wait_s,threshold} and the
  on_barge_in(active) callback; speak() drops text while muted and plays
  through the interruptible path.
- gateway/voice: tags the interrupt utterance (raw["barge_in"]),
  classifies stop vs new command (_is_stop_command), drops queued replies
  on stop, and unmutes once handled.
- config: gateway.voice.barge_in block; config.example.json regenerated.
- tests: wake-abort, mute release, threshold gate, stop/new-command
  classification, sentinel preservation.
2026-10-17 16:56:44 +00:00
gabby a8ca65a6e4 config.example.json: regenerate with the gutendex pack 2026-10-17 08:19:00 +00:00
gabby a6b8617562 lxmf: re-announce when an interface or peer comes online
The startup announce fires before AutoInterface finishes its peering
handshake, so it reaches no peer; a peer discovered later (or a link that
recovers) would otherwise wait out the whole `announce_interval`.

Replace the blocking `_stop.wait(interval)` announce loop with a tick loop
that announces on the interval, and also immediately after an interface scan
sees a new online transition (AutoInterface reports `online` only after its
peering wait, and every discovered peer is a fresh interface). Each announce
records its time and a `reason` (startup / interval / peer discovered) on the
`lxmf_announced` trace event; a scan error is traced, never fatal.
2026-10-17 07:35:12 +00:00
gabby ec3e6b1b97 skills: read-only catalog for introspection bodies
An ordinary skill body may not reach into the agent (`ctx.admin` is the
housekeeping-only mutation surface), but a body that reports the agent's own
capabilities legitimately needs to see the tree. Add that sanctioned surface:

- `SkillCatalog` (skills.py): a read-only view — `categories()` (id -> scope
  description) and `skills(category)` (leaf names) — over a live provider.
- `ActionContext.catalog`: supplied by the scheduler as a locked tree snapshot,
  passed to every body.
- The runner now passes `admin` only to the `housekeeping` category (it was
  previously handed to every body despite the documented rule); ordinary bodies
  get `catalog` instead.

Consumed by the essentials pack's new `skills.list_categories` /
`skills.list_skills` seeds. Docs (CODEGEN.md, AGENTS.md, README.md) updated;
tests cover the catalog, the catalog/admin split on the run context, and the
new pack seeds.
2026-10-17 07:34:39 +00:00
gabby ed894bd329 lxmf: Sideband voice messages (transcribe + Piper voice replies)
The LXMF gateway now handles Sideband push-to-talk voice messages end to end.

Inbound: a PTT message carries its audio in LXMF.FIELD_AUDIO
(`[audio_mode, bytes]`); `lxmf_transport.parse_audio_field` normalizes it and
the adapter transcribes it into an ordinary command when
`gateway.lxmf.voice.enabled` is set. HQ Opus/OGG goes through faster-whisper
(requirements/transcribe.txt); non-HQ Codec2 through the optional pycodec2
bindings (requirements/codec2.txt). No microphone stack is needed.

Outbound: a chat that last messaged by voice is answered with a synthesized
voice message when `gateway.lxmf.voice.reply_with_voice` is on (the default).
`voice_transport.build_synthesizer` speaks the reply with Piper and
`voice_transport.pcm_to_opus_ogg` encodes it to OGG/Opus (48 kHz, PyAV's
libopus); `lxmf_transport.audio_fields` attaches it as a Sideband HQ PTT
message, with the reply text as the content so a text-only client still sees
it. The reply mode follows the chat's most recent inbound message. A missing
synthesizer or any synthesis/encode failure is traced and the reply falls back
to text. Deps: requirements/tts.txt (piper-tts + PyAV), still no microphone.

Also make LXMF replies result-only (`LxmfAdapter.result_only`, overridable via
`gateway.lxmf.result_only: false`): send the skill's result line, dropping
scheduler bookkeeping and the `<skill>: ok —` wrapper.

Wiring: new config keys under `gateway.lxmf` (result_only) and
`gateway.lxmf.voice` (reply_with_voice, max_speak_chars, reply_bitrate, tts);
regenerated config.example.json; the setup interview asks how to handle voice
messages and the install plan adds `install_lxmf_tts` (bootstrap installs
requirements/tts.txt and downloads the reply voice); cli anchors the LXMF
voice_dir to .runtime/voice/tts.

Tests cover the audio field shape, the outbound queue, the adapter's
voice-chat tracking and synthesis fallbacks, result-only routing, the
synthesis/encode helpers, and the setup plan. Docs updated.
2026-10-17 04:53:51 +00:00
gabby b1a7bfd272 packs: ship python deps with the pack
A pack now owns the python deps its skills/bridge need, at
packs/<name>/requirements.txt (standard pip format). SkillPack.requirements_file
resolves it; the install plan lists the selected/enabled packs that ship one
(setup.build_plan / plan_from_config -> pack_requirements); bootstrap installs
each into .runtime/venv, so a host that never enables a pack installs nothing
for it.

Move the browser deps (Playwright) out of the agent repo's requirements/ into
packs/browser/requirements.txt; the Playwright binary download stays a
browser-specific bootstrap stage. --browser force-adds the pack's deps.

Docs (PACKGEN.md, AGENTS.md, README.md) describe the pattern; tests keep every
pack requirements.txt pinned and consistent with the manifest's requires.
2026-10-14 18:05:56 +00:00
gabby bf071ee529 bootstrap: source packs from a pack-index repo; clone only selected packs
The set of packs is now owned by a dedicated pack index repo (semif-packs) instead of the agent-repo packs.json + the hardcoded setup PACK_CHOICES.

- bootstrap.sh fetches the index, then runs setup in two passes (--answers-out, then clone the selected packs, then write config) so it never clones a pack the user did not choose. essentials is always cloned; +simplex for the simplex gateway's address script; +browser for --browser. Reruns clone only the packs the config references.

- setup gains --answers-out and --pack-index; the interview's pack choices come from the index. PACK_CHOICES removed.

- delete packs.json; update README, PACKGEN.md, the packgen skill, and AGENTS.md.
2026-10-14 16:13:13 +00:00
gabby c57983f1f5 nextcloud: route create_event/next_event through the bridge
The two skills declared the account as flat contract vars
(nextcloud_url/username/app_password/default_calendar), which bootstrap no
longer writes — it stores the account under bridges.nextcloud — so the
runner asked for the URL and credentials on every first fire.

Rewrite both to call the Nextcloud bridge (GET /calendars, POST
/calendars/events, GET /calendars/events) like create_task, so their only
contract vars are the derived nextcloud_bridge_url/_token (+ the LLM bridge
for create_event). Docs and the seed-integration test updated to match.
2026-10-14 04:25:49 +00:00
gabby 2296801b22 bootstrap: first-run interview + answer-driven config and installs
Bootstrap now asks the questions that make a fresh machine work and installs
only what the answers require. `cli setup` (new `semif_agent/setup.py`) runs
the interview — decision engine (local SemIf 4B or remote Winnow), new-skill
authoring mode (+ llm/codegen endpoints/keys when enabled), capability packs,
gateways, timezone — and writes the split config + secrets.json from the
answers, plus a machine-readable install plan.

Both ends of the spectrum work end to end: the minimum is the local SemIf 4B
engine + the essentials pack (canned replies, time/timers, calculator) with no
gateway, authoring, or heavy downloads; the maximum enables every pack, a
remote engine, remote llm/codegen, and all gateways. `--yes` takes the minimum
unattended; `--answers FILE` replays a saved answer set; a rerun skips the
interview and `--reconfigure` re-runs it.

The plan drives the conditional stages: engine clone/GGUF/tokenizer and
requirements/engine.txt only for a local engine; requirements/transports.txt
only when a SimpleX/LXMF transport is selected; the simplex-chat binary,
Playwright, and the voice stack only when their pack/gateway is on; and only
the systemd units the answers need (a reconfigure retires dropped ones).

Also fixed:
- `config-init`/`setup` could never run on a fresh machine: main() loaded
  config before parsing the subcommand. Config-independent subcommands now run
  before the config is required.
- codegen was mandatory at startup even with authoring disabled (SystemExit on
  an empty model); build_codegen_client now returns None, and the scheduler
  guards every create door. build_llm_client likewise returns None for a
  non-semif provider with no model.
- the gateway unit ran `--platform all`, which would try the foreground-only
  voice platform in a headless service; it now runs the explicit daemon list.

requirements/ is split by concern (core/engine/transports + voice/browser);
staging.txt is the union. Docs updated (README, AGENTS). New
tests/test_setup.py covers both paths, interview branching, secrets merge, and
the plan round-trip.
2026-10-14 02:07:18 +00:00
gabby d67ea26f3d docs: finish the bridge-decoupling references
Update the packgen skill workflow, the browser requirements comment, and the
remaining prose to match bridges shipping with their packs (no core CATALOG).
2026-10-13 23:56:56 +00:00
gabby 41c18e6c47 Decouple bridges: ship each with its pack
The core no longer owns concrete bridge implementations. A bridge now ships
inside the pack that declares it (packs/<name>/bridge/<name>.py, plus its
package marker, optional client module, and hermetic test), and the core
registry imports it by convention from the pack's `bridges`.

Core keeps only:
- bridges/base.py: BridgeInfo + BridgeService (shared HTTP/JSON/auth layer),
  plus a new BridgeService.from_config build hook (a bridge that needs the
  scheduler's `llm` client or top-level fallback values declares that itself,
  replacing build_bridge's per-name special-casing) and checkout_root() so a
  pack-relative bridge can still anchor .runtime/ paths;
- bridges/inbox.py: the generic MessagingInbox;
- bridges/llm.py: the one shared, pack-less LLMBridge (CORE_BRIDGES);
- bridges/registry.py: discovery (discover_bridge_classes/known_infos/
  describe_bridges/derived_config_vars/build_bridge/run_bridges) scanning each
  pack's bridge/ dir, plus load_pack_bridge_module/package for tests.

Moved to their packs: simplex, nextcloud (+client), outlook (+client), browser
(+client) — each with its hermetic test. tests/test_bridges.py now covers the
core (shared LLM bridge + registry); tests/test_packs.py runs every pack's
bridge test. Docs (AGENTS.md, PACKGEN.md, README.md) updated.

Packs pushed separately to pack.<name>.
2026-10-13 23:56:06 +00:00
gabby 16e8583921 Move pack-specific scripts into their pack repos
scripts/outlook-auth.py, playwright-browsers.py, and simplex-address.py now
live in pack.outlook/pack.browser/pack.simplex under scripts/. bootstrap.sh,
the Outlook bridge hints, and the docs reference packs/<name>/scripts/; the
Outlook auth helper locates the checkout (and its default token path) by
walking up to the semif_agent package.
2026-10-13 22:21:06 +00:00
gabby 1329de42c4 Bootstrap the skill packs from their own repos; docs for the split
scripts/bootstrap.sh now clones each pack (pack.<name>, listed in the new
committed packs.json) into the gitignored packs/ BEFORE seeding config, so
config-init still generates the pack config fragments; --pack-base overrides
the base derived from the checkout's origin remote. README/AGENTS/PACKGEN/
CODEGEN and the packgen skill describe the per-pack repositories.
2026-10-13 21:55:45 +00:00
gabby 883c51de97 Move skill packs to standalone repositories
Each pack (browser, essentials, nextcloud, outlook, simplex) now lives in its
own repository and is cloned into the gitignored packs/ directory at setup.
packs/ is no longer tracked here.
2026-10-13 21:21:46 +00:00
gabby 0b02a3feac spec: skills may call a plain HTTP API directly; bridges are opt-in
Reframe bridges as a deliberate choice rather than the mandatory path to
any third-party system. A skill body may call a service's own HTTP API
directly with a stdlib transport; a bridge is warranted only when a
simple, repeatable skill file would be inconsistent, inconvenient, or
unsafe — state (especially auth state), sanitized connectivity, or a
native/heavy protocol. When a bridge fronts a service, the body calls the
bridge and must never reach around it.

Updates CODEGEN.md, PACKGEN.md, TESTGEN.md, README.md, AGENTS.md, the
bridges/__init__.py docstring, the codegen BODY_DIRECTIVES + describe_
bridges() prompt strings, and the tests pinning their wording.
2026-10-13 18:13:24 +00:00
gabby f379c0a746 packs: add PACKGEN.md contract + packgen skill
PACKGEN.md is the authoritative spec for a new pack, the sibling of
CODEGEN.md (body) and TESTGEN.md (test): the pack.json manifest, its
config schema and how it maps onto bridges.<name>/packs.<name>, the
enable switch, referencing a bridge by name, authoring a new bridge
(BridgeService + CATALOG + build_bridge + the optional-dep 503 rule),
acceptance criteria, a worked example, and a checklist.

Add a thin OpenCode skill (.opencode/skills/packgen/SKILL.md) that walks
the workflow and points at PACKGEN.md, and cross-link the contract from
AGENTS.md, README.md, CODEGEN.md, and TESTGEN.md.
2026-10-13 15:25:42 +00:00
gabby 711dba2f03 new-skill creation: deny by default, refuse silently
A host now leans on the committed packs: `new_skill_creation` defaults to
`deny` (core schema, generated config.example.json, and the scheduler's unset
fallback), so a fresh bootstrap does not author skills at runtime. A host with
the resources opts in with `allow` (or `ask`).

Under deny, an unmatched request no longer exposes the authoring machinery:
`_blocked_create` answers with a plain refusal (`skills.UNABLE_MESSAGE`, "I'm
sorry, I'm not able to help with that.") instead of an error naming
`new_skill_creation`/`config.json`, and a leftover empty/in-progress leaf in a
denied category refuses the same way rather than telling the user to `restart`
the body write. The block is still traced (`category_create_blocked` /
`skill_create_blocked`) for operators. Routing, decision logging, and the
allow/ask paths are unchanged.

Tests: authoring-mechanics helpers opt in explicitly; the default-deny and
silent-refusal cases are asserted.
2026-10-13 15:01:12 +00:00
gabby 78b4621ba0 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).
2026-10-13 14:20:35 +00:00
gabby b953475bf7 scheduler: surface failed authoring to the front end
A skill-body write or a draft authoring call that fails only printed to
stdout. On the voice gateway that goes to the journal, so the user heard
"authoring a new skill in the background; the request will re-run when it
is ready" and then nothing — the creation had failed silently.

Buffer a user-facing notice on the scheduler outbox (the same path a
post-authoring re-run uses), keyed by the originating run id, so a front
end's drain_outbox() routes it to the chat. Add _brief_error to collapse
and bound the exception text for speech.

Tests assert the notice is routable with the right run id for both the
draft_failed and skill_write_failed paths.
2026-10-12 09:27:52 +00:00
gabby b15a9e1b45 gateway: answer spoken approvals, route off-gate results
New-skill authoring via the voice gateway never completed: STT emits
"Approve." / "Yes." / "retry." with sentence punctuation, but the
approval/repair maps were matched with an exact lookup, so a spoken
answer fell through to submit_request while the pending approval timed
out and nothing was registered.

- gateway/service: normalize the reply before the action lookup
  (`_normalize_action`: lowercase, strip edge punctuation, first-word
  fallback) and broaden the approval/repair vocabularies, so a spoken
  "Approve." / "Yes." / "retry." matches like a typed one.
- scheduler: buffer the replies of a background drain (the codegen
  worker's post-authoring re-run, a repair retry) in an outbox instead
  of returning them into a thread that discards them; a front end's
  `drain_outbox()` routes them, so the answer to the user's own request
  is no longer swallowed.
- cli/dashboard: drain the outbox alongside the queue.
- tests: normalization + spoken approval/repair routing, outbox
  routing, and the async requeue assertion.
2026-10-12 08:14:42 +00:00
gabby 3a5b90b1cb bridges: let the browser bridge use an installed browser
Add `bridges.browser.channel` and `bridges.browser.executable_path` so a host
can point the bridge at an already-installed Chrome/Chromium (a Playwright
channel such as `chrome`/`msedge`, or a specific binary) instead of Playwright's
managed build. `executable_path` wins when both are set. This is the no-download
escape hatch for hosts where the browser CDN is unreachable or unusable.

- `BrowserDriver` carries `channel`/`executable_path` and passes them to
  `launch_persistent_context` when set, so the managed download is skipped.
- `BrowserBridge` reads both from its config block; `config.example.json`
  documents them.
- Verified live: launching an installed Chromium via `executable_path` with an
  empty browsers path drives a real page with no managed download.
2026-10-11 09:46:44 +00:00
gabby e4961ef492 bridges: prime the Playwright browser over IPv4 when the downloader hangs
`playwright install chromium` failed on this host even though the CDN is
reachable. Root cause is Node, not the network: Playwright's bundled downloader
forces `autoSelectFamily` with a custom dual-stack resolver that resolves
`[6, 4]` and interleaves IPv6 first, and this box has an IPv6 address (a ULA)
with no global IPv6 route, so the first IPv6 connection blackholes and Node never
falls back to IPv4 -- the download stalls to the socket timeout. Raising
`PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT` only moved the hang from 30s to 600s;
`curl -4` fetches the same artifact at ~6 MB/s.

Playwright skips a browser whose directory holds an `INSTALLATION_COMPLETE`
marker, so prime the cache over IPv4 and the normal install becomes a no-op.

- `scripts/playwright-browsers.py`: reads the chromium/headless-shell/ffmpeg
  revisions and Chrome-for-Testing versions from Playwright's own
  `browsers.json`, downloads those exact artifacts with `curl -4`, extracts them
  into `PLAYWRIGHT_BROWSERS_PATH/<name>-<revision>/`, and writes the marker.
  Idempotent; prefers `unzip`, falls back to `zipfile` + chmod.
- `bootstrap.sh --browser`: if `playwright install` fails for chromium, fall
  back to the helper (firefox/webkit just warn).

Verified live: after priming, `playwright install chromium` exits 0 and the
browser bridge drives a real Chromium (goto/content/text/links/fill/select/
screenshot) over HTTP.
2026-10-11 09:45:31 +00:00
gabby 6240392632 bridges: browser automation via Playwright
Add a `browser` bridge: real browser automation behind the standard
token-guarded localhost JSON surface, so a codegen-authored skill body never
bundles a browser stack. It opens a URL, reads a page's text or links, takes a
screenshot, and clicks/fills/presses/selects to complete a flow.

Unlike the stdlib-only Nextcloud/Outlook bridges this one owns a browser and
needs a heavy optional dependency, so it is disabled by default and installed
with `scripts/bootstrap.sh --browser` (Playwright pinned in
requirements/browser.txt; the browser binary lands under the checkout's
.runtime/browser, which the driver points PLAYWRIGHT_BROWSERS_PATH at).

- `BrowserBridge` (`bridges/browser.py`) + `BrowserDriver`
  (`bridges/browser_client.py`). A real navigation/timeout/selector failure is a
  502, a missing package/browser a 503 install hint, bad input a 400 -- never a
  fabricated success.
- `check_requirements()` deliberately never blocks: `run_bridges()` aborts all
  bridges when one fails, and this dependency is optional, so a missing
  Playwright must degrade to a per-call 503, not take down the others.
- Playwright's sync API is bound to its creating thread while the bridge serves
  each request on a new one, so the driver runs the async API on one dedicated
  event-loop thread and serializes whole operations behind an asyncio.Lock
  (submitted with run_coroutine_threadsafe).
- Persistent profile under .runtime/browser/profile so logins/cookies survive
  across calls and restarts; POST /reset with purge=true wipes it, and
  headless=false shows the window for a first sign-in. Route set: /health,
  /state, /content, /text, /links, /screenshot, /goto, /click, /fill, /press,
  /select, /wait, /back, /forward, /reset. No arbitrary JS evaluate (out of
  scope for this cut).
- Seeds: `seeds/browser/{open_page,read_page,screenshot}`, each hermetically
  tested against a loopback bridge. A `browser` category description is seeded
  so the leaf softmax has signal.
- `tests/test_browser_bridge.py` exercises the routes over a loopback HTTP
  server with an injected fake driver (no browser or Playwright needed). The
  live browser is a provisioned-host concern: this box could not reach the
  Playwright CDN, so no real-browser run backs it yet.
2026-10-11 09:32:47 +00:00
gabby c010cdb44e dashboard: drain the run queue so a multi-step chain completes
A `continue` assessment re-dispatches the next step onto the queue rather than
running it inline, so a multi-step request only finishes when a front end drains
`Scheduler.run_queue()` -- as the CLI and gateway already do. The dashboard ran
only the first step and left the child stranded in the queue, so a compound
request looked finished when it was not.

- `DashboardHandler._complete` runs the returned reply through `_drain_chain`
  and returns the last reply (intermediate steps are hidden at `result`
  verbosity); `/api/submit` and `/api/answer` use it.
- `/api/answer` now also returns `request_id` (`SchedulerReply.run_id`) so a
  front end can cross-link the resumed run.
- `test_submit_completes_a_multi_step_chain` drives a deterministic two-step
  chain and asserts both steps ran, the reply is the final step, nothing is left
  in the queue, and the runs are linked.
2026-10-11 09:32:44 +00:00
gabby 9757ae893e codegen: fidelity gate reads the whole body; bound artifacts to engine ctx
The fidelity gate truncated the body to 4000 chars, so a body whose real
action sat after its helpers (the common shape) was judged on a prefix with
no action and wrongly returned `reconsider` -- a false reject that wasted a
rewrite and mislabeled a working skill. Live-engine probe: the truncated
state scored reconsider 0.96; the whole body scores accept 0.98.

- Fidelity gate: feed the whole body plus a deterministic operation
  inventory and the de-identified goal; drop the raw request from the state
  (a remote-engine PII path that added no signal). Ask the positive question
  ("is there a concrete operation that realizes the goal?") and give the gate
  its own `codegen.fidelity.tau` instead of the run-assessment tau.
- Artifact size budget: a decision ingests a generated artifact whole, so
  bound it. `parse_skill_body`/`parse_skill_test` reject an over-budget
  artifact (`ArtifactTooLong`); the codegen retry ladder asks for a shorter
  one. The ceiling derives from the active engine's context
  (`DecisionEngine.context_tokens`: `engine.context_tokens` for the local
  GGUF, `engine.winnow.context_tokens` for Winnow) minus
  `codegen.decision_reserve_tokens`; `codegen.max_body_tokens` /
  `max_test_tokens` override (separate limits).
- `codegen.operation_inventory()`: static HTTP-verb/path, CLI, mail, file,
  and timer inventory, resolving the verb at the call site so a thin-helper
  body's real endpoint is visible.
- Docs: AGENTS.md, README.md, CODEGEN.md, config.example.json.
- Tests: unit coverage for the budget, inventory, retry-shortening, and the
  gate state; integration regression `test_fidelity_gate_reads_the_whole_body`
  (real engine) guards the truncation bug.
2026-10-11 07:33:03 +00:00
gabby 1833932f1c codegen: never expose user data to the cloud codegen endpoint
Codegen is the primarily-cloud model, so it must receive only a de-identified,
reusable spec. The trusted local `llm` now authors a `goal` (plus a generic
service/transport) with every user-specific value stripped, and that is the only
task data any codegen prompt ever carries.

- skills: SkillDraft carries `goal` (not `requirements`); generate_skill ->
  generate_skill_spec; the spec prompt/parser ask for a de-identified goal +
  generic service/transport; registry persists `goal`, never request_text.
- codegen: every prompt builder (body, retry, regen, testgen) drops the
  Request/requirements parameters and builds from the spec alone; the whole
  elicitation surface is removed.
- scheduler: the codegen worker runs body -> fidelity -> contract -> test only;
  repair and fidelity evidence bundles are de-identified (failure_kind +
  integration + goal + previous body); approval gate moved to
  codegen.approval.wait_timeout; the question queue is now the repair ask_user
  path only.
- config: drop the codegen.elicitation block; add codegen.approval.
- docs/assets: update AGENTS.md, CODEGEN.md, README.md, docs/flow.md,
  bootstrap comment, static app.js; regenerate docs/flow-authoring.svg.
- tests: add tests/test_codegen_privacy.py (structural + behavioural sentinel
  checks, de-identified repair evidence, registry goal); update/remove the rest.

Purged (no migration): data/decisions.jsonl, data/runs.jsonl, data/categories.json.
2026-10-11 00:52:30 +00:00
gabby def51f81dc recall the previous run's ledger for a follow-up within query_recall_window
A completed real-skill run's ledger is held in memory per origin source
for query_recall_window seconds (default 30, 0 disables). A follow-up
request in the same chat arrives with it as prior_ledger -- rendered as a
'previous request' context block in navigation/assessment state and
exposed to bodies via last_result -- so a reference like 'send it to Sam'
resolves against what the agent just did.

Kept separate from run_ledger: recall is not an in-flight continuation,
so it never skips the actionability guard nor feeds the monotonic-progress
guard. Only terminal real-skill runs are remembered (canned responses and
housekeeping meta skills excluded); the final step is synthesized as a
ledger entry since a single-step run's own run_ledger is empty.
2026-10-10 08:33:59 +00:00
gabby ab0defca1e chain multi-step requests across known skills
Add the run-ledger chained-run path and make a compound request run its
known skills in order instead of authoring one monolithic skill.

- scheduler/skill: `assess:outcome` gains a `continue` verdict; a continued
  step is re-dispatched with a bounded run ledger (max_reentries + a
  monotonic-progress guard), and the ledger is rendered into the routing and
  assessment state.
- navigation leaf guard (`confirm_skill_fit`) becomes same/part/different and
  is ledger-aware, so the first step of a compound request runs instead of
  being rejected into `create_skill` (a real run picked calculator.calculate
  at 0.99 and was rejected into create_skill).
- results flow forward through `request.run_ledger` (`last_result` helper);
  `simplex.send_message` sends the prior step's result rather than asking the
  LLM bridge to recompute it. Documented in CODEGEN.md.
- `assess:outcome` stays the sole continuation authority: the guard only
  decides whether a skill contributes, never forces a continuation (a forced
  continue on `part` overrode a correct `done` on the final step and authored
  a spurious category).
- verbosity levels, structured SchedulerReply fields, and a send_message
  hermetic test for the chained-result path.
2026-10-10 07:25:17 +00:00
gabby 9ba14fdab0 drop new-skill legacy fallbacks; make the simplex-chat pin per-arch
- scheduler: remove the creation_approval and locks.new_skill backward-compat
  reads (and the locks cleanup in set_category_mode). The tri-state
  new_skill_creation mode is now the only source of truth.
- pins.json: simplex_chat now carries an assets map (x86_64 + aarch64) with
  per-arch bin_url/sha256; bootstrap selects by uname -m (arm64 -> aarch64).
  Fixes the Pi (aarch64) fetching the x86_64 binary.
- docs/tests updated.
2026-10-10 01:50:28 +00:00
gabby c5ee87875f scheduler: new-skill creation is a tri-state allow/deny/ask mode
Replace the boolean creation_approval and the per-category boolean
locks.new_skill with a single tri-state new_skill_creation mode: a global
default (allow | deny | ask) with a per-category override in the category
config. allow authors immediately, deny blocks creation, ask gates on human
approval (the old approval path). housekeeping/response stay denied in code.

Surfaces updated: config.example.json, REPL /mode, dashboard
/api/new-skill-modes + /api/new-skill-mode, static UI. The retired booleans
creation_approval (true->ask) and locks.new_skill (true->deny) are still read
as fallbacks so an existing deployment keeps its behaviour.

Docs (AGENTS.md, docs/flow.md) and tests updated.
2026-10-10 01:38:16 +00:00
gabby 88700898be voice: hold the wake word until the scheduler reaches a result
Gate the wake word on the scheduler's single slot being free: a wake that
fires while the current request is still running is ignored (traced
voice_wake_blocked), so a second command cannot start mid-run. The gate is
GatewayService.input_ready (False while a run executes, True when idle or
paused for the user's answer), handed to adapters via set_input_ready; the
voice adapter passes it to VoiceDaemon.input_ready.
2026-10-09 23:52:57 +00:00
gabby ff94ea938c voice: require the wake word for every command
Drop the post-reply follow-up window: capture no longer accepts an utterance
without the wake word after a result, so the front end never keeps listening
on its own. Removes follow_up_window_s from the config/README/AGENTS/bootstrap
docs and updates the tests (a reply no longer arms capture).
2026-10-09 22:34:13 +00:00
gabby a388c292bc voice: play a multi-note bling once the utterance is transcribed
Add a configurable cue.submit_notes sequence ([frequency_hz, duration_ms],
spaced by note_gap_ms) played after STT returns text, falling back to the
single submit_frequency beep when empty. Two-note chime shipped as the
default in config.example.json; README + tests updated.
2026-10-09 22:30:07 +00:00
gabby e2cbf74797 seeds: add calculator.calculate (SemIf-chosen operator, spoken answer)
A local-arithmetic seed 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,
and percentages; SemIf also picks the operands when the request writes
more numbers than the operation consumes, and the body asks for missing
numbers and resumes. Results are spelled out in words for the ear, with
inexact results announced as "approximately ...".

Pure local compute (`compute` transport, empty contract). Adds the
`calculator` category description for navigation, the seed's hermetic
test, a tune_navigation example, and README/AGENTS docs.
2026-10-09 21:45:58 +00:00
gabby fc0beb5798 simplex: mark the reported message read so next_message advances
The bridge only read the daemon's unread state (/_get chats, /_get chat);
nothing wrote the read state, so a persistent-unread message was re-reported
on every call and simplex.next_message never advanced.

v7.0.3 does expose /_read chat @<id> and /_read chat items @<id> <ids>
(the earlier "v7 has no mark-read command" note was wrong). Added:

- SimplexDaemon.mark_read / request_mark_read plus read_command /
  parse_read_response; parse_direct_text_item now carries item_id.
- SimpleX bridge POST /read {"contact","item_ids"} marks exactly the listed
  items read on the bridge's own daemon, reporting ok/error honestly.
- The live inbox entry keeps item_id so /inbox/next hands back the
  consumable id.
- simplex.next_message consumes exactly the item it reported (a failed
  consume is surfaced as an honest note, never a fabricated read failure).

Precise per-item reading leaves the rest of the chat unread.
2026-10-09 11:16:21 +00:00
gabby 4e3e3f767c add previous skill result to semif context for successive requeues 2026-10-09 10:25:57 +00:00
gabby f05e06e6f6 normalize string outputs from time skills 2026-10-09 10:10:21 +00:00
gabby f6ef66b532 voice: tolerate the wake-tail pause; harden the front end
Endpointing fix. The wake detector usually fires inside the wake phrase,
so the first speech captured after it is the phrase's tail (plus the cue
beep echoing back through the mic), not the command. A fixed 500 ms
trailing-silence endpoint then ended the capture during the natural pause
before the command: the utterance held 240-400 ms of speech and STT
returned empty. In a recorded session 18 of 30 wakes dropped the command
that way (only 10 transcribed).

The endpoint now uses a longer silence tolerance (vad.initial_silence_ms,
default 1500) until vad.min_command_ms (default 700) of speech is in
hand, then reverts to vad.silence_ms, so a pause before the command is
tolerated while a real command still ends promptly.

Front-end hardening (the ways it was silently dying or losing work):

- Utterances run on a worker thread, not the audio thread, and a task
  error is traced and spoken rather than propagated, so one bad command
  cannot stop the mic or take the front end down.
- Capture-stream watchdog: read with a timeout and close/reopen the input
  after a sustained stall, so a wedged PortAudio/ALSA callback recovers
  instead of hanging the gateway (traced voice_stream_stalled/reopened).
- faulthandler enabled (CLI + unit) so a fatal signal dumps every
  thread's stack to the journal.
- The scheduler's answer-side entry points (answer, answer_question,
  resolve_repair, answer_approval) are guarded like submit_request: an
  EngineUnavailable is fatal-and-reported and any other resume/repair
  error returns a reply instead of propagating into a front end.
2026-10-09 09:41:00 +00:00
gabby e86ed805ee tests: stop flagging a literal 'the box' as a deployment leak
The machine-descriptor rule matched the Harvard-sentence recording
prompts (scripts/voice-prompts-en.txt: "The box was thrown beside the
parked truck."), where 'the box' is a literal box, not a colloquial dev
machine. Drop the bare phrase; keep the explicit dev/staging markers that
are never generic English.
2026-10-09 09:40:56 +00:00
gabby dcfe5e5fec audio: baseline the internal speaker at full volume on boot and hotplug
PortAudio has no volume control, so a muted ALSA Master silences the voice
gateway's cue and replies, and the mixer resets whenever a sound device is
added/removed. scripts/audio-baseline.sh sets the analog speaker (found by its
'Speaker' control, so a shifting card index does not matter) to 100% unmuted;
scripts/audio-baseline-watch.sh re-applies it on every sound udev event. Both
are driven by systemd user services (audio-baseline.service / -watch.service)
so they run at startup and on hotplug.
2026-10-09 08:19:39 +00:00
gabby ec39a990e4 voice: default wake word to "Hey Computer", capture command after a pause
openWakeWord ships no "computer" model, so pin a community
openWakeWord-compatible ONNX (Apache-2.0, sha256 in pins.json `wake_word`) and
fetch it into .runtime/voice/wake from scripts/voice-models.py. Its scores run
lower than the official models (~0.26-0.82 on the phrase, <0.02 on negatives),
so the seeded wake.threshold is 0.2 (the official models score ~0.99 at 0.5).

Also fix command capture: after the wake word the daemon now waits
listen_timeout_s (default 3s) for the command's speech to begin instead of
assuming it is glued to the wake word, so a natural pause while the cue beep
plays no longer truncates the command.
2026-10-09 08:19:36 +00:00
gabby ae37abbc3f debug tasklist 2026-10-09 02:28:46 +00:00
gabby f1ea9f0c2c seeds: ship simplex.send_message (promoted from the runtime store)
Move the authored simplex.send_simplex_message skill out of data/skills/ into
the committed simplex seed folder as send_message. Expand its CONTRACT to cover
every declared config var (SimpleX bridge + LLM bridge) so it satisfies the seed
contract test, add its manifest.json, and update the navigation tuning labels,
the seed-existence test, the committed-seed tree assertions, the docs, and the
bridge backlog (item 3 shipped).
2026-10-09 00:32:07 +00:00
gabby b8f86849ea seeds: merge calendar and productivity_management into nextcloud
Consolidate the calendar and productivity_management seed categories into one
nextcloud category: create_event/next_event move from calendar, and
create_nextcloud_task becomes create_task (dropping the redundant prefix).
Replace the two CATEGORY_DESCRIPTIONS entries with a single nextcloud
description and update every reference across the repo (docs, bridge comments,
tests, navigation tuning labels, seed docstrings).
2026-10-09 00:23:32 +00:00
gabby e434b9fbe5 bridges: add an Outlook (Microsoft Graph) bridge + seeds
A standalone Outlook bridge in front of Microsoft Graph — mail, calendar
events, Microsoft To Do tasks, contacts, and OneDrive files — so skill
bodies never speak Graph or OAuth directly. Stdlib-only, no daemon (like
Nextcloud), and registered in CATALOG so describe_bridges() feeds it into
every codegen prompt.

Authorization is the OAuth2 device code flow: scripts/outlook-auth.py runs
it once and stores the refresh token 0600 under .runtime/outlook/token.json;
outlook_client.py refreshes on expiry/401, follows @odata.nextLink paging,
and backs off on 429/Retry-After. An unauthenticated route is a 503 (run the
helper), a real Graph failure a 502.

Seven seeds/outlook/* starter skills (next_message, send_message — compose
via the LLM bridge and confirm before sending — next_event, create_event,
create_task, list_contacts, list_files), a bridges.outlook config block, and
tests/test_outlook_bridge.py driving the real client over a loopback server
faking the token endpoint and Graph shapes.
2026-10-08 22:57:18 +00:00
gabby b7d405454a voice: add custom Piper voice training pipeline
Record an LJSpeech dataset from the microphone, fine-tune a Piper voice
from the pinned base checkpoint on a GPU host, and verify every take
against its prompt with Whisper before training.

- semif_agent/voice_train.py: neutral, stdlib-only recording helpers
  (LJSpeech dataset writer, prompt loading, WAV I/O, mic-check level
  math, silence-endpointing capture loop) plus transcript-fidelity
  helpers (normalize_text, word_error_rate, compare_transcript).
- scripts/voice-record.py: interactive + hands-free (--speak-prompts /
  --read-prompts) recording; resumes by prompt id and announces how many
  of the 720 prompts remain, so a resume is never mistaken for a rerun.
- scripts/voice-train.sh: piper1-gpl checkout + venv, warmstart
  fine-tune of the pinned medium checkpoint, ONNX export. Handles
  torch>=2.6 weights_only (PosixPath allowlist), the older checkpoint's
  hyperparameters (--model.warmstart_ckpt, not --ckpt_path), the
  espeakbridge in-place dev build, and piper's validation/test splits
  (needed for the default checkpoint callbacks).
- scripts/voice-verify.py: transcribe-and-compare fidelity check
  (empty/mismatch/review/ok), --json report, --from-json + --prune to
  mark bad takes for re-recording without deleting them.
- pins.json: voice block (piper1-gpl ref + medium base checkpoint).
- voice_transport.py: WhisperTranscriber beam_size/vad_filter knobs;
  SoundDeviceAudio.read(timeout=) so a dropped device ends a take
  instead of hanging.
- AGENTS.md: architecture map + roadmap entries; docs/VOICE-TRAIN.md
  the end-to-end guide; tests/test_voice_record.py the helper tests.
2026-10-08 22:37:34 +00:00
gabby aa25693091 remove unnecessary llm refusal guard 2026-10-08 17:22:57 +00:00
gabby 912417792f seeds: ship create_nextcloud_task as a starter skill
Turn the generated productivity_management.create_nextcloud_task body into
a committed seed in the CODEGEN.md folder format. It goes through the
Nextcloud bridge: GET /tasklists picks a VTODO-capable target (never an
event-only calendar or a Deck board) and POST /tasks creates the task; the
LLM bridge phrases the summary/description. The CONTRACT mirrors the four
bridge config vars the body reads, so the seed passes the integration and
contract checks.

Register productivity_management in CATEGORY_DESCRIPTIONS so the seed's
category is described for navigation, and list the seed in
tests/test_seed_skills.py.
2026-10-08 02:05:31 +00:00
gabby 0005d8f7ee bridges: resolve Nextcloud tasks to VTODO-capable lists
Task operations used the same calendar resolver as events, so a request
that named (or defaulted to) an event-only calendar like "personal" put a
VTODO into a collection that rejects it. Read each collection's CalDAV
supported-calendar-component-set, expose it as `components` on
/calendars, and add GET /tasklists (VTODO-capable calendars, minus
Nextcloud Deck boards).

_resolve_calendar is now component-aware: task routes only target a
VTODO-capable list and reject an event-only calendar with a clear 400;
with no name they try default_task_calendar, then default_calendar when
it also accepts VTODO, then the sole user task list. Add the
default_task_calendar config (top-level nextcloud_default_task_calendar
fallback) and document the routes in the bridge catalog.
2026-10-08 01:56:22 +00:00
gabby 228886f7cd bridges: derive skill config vars from the bridge block
Bridge listener addresses were hand-maintained duplicates of
bridges.<name>.host/port at the top level (simplex_bridge_url,
llm_bridge_url, nextcloud_bridge_url, plus their _token). A host
provisioned before a bridge was added never gained the key, so a skill
for that bridge could not resolve its URL: the contract config search
fell back to 'ask' and a front end captured an unrelated reply as the
value (a voice task request was recorded as nextcloud_bridge_url).

Add bridges.registry.derived_config_vars(config): for every catalog
bridge, derive <name>_bridge_url/<name>_bridge_token from its own
bridges.<name> host/port/token. build_scheduler injects these into the
config the scheduler and ctx.config expose, so the contract config
search finds them and skills read them with no top-level duplicate.
A block with no port contributes no URL, leaving an unconfigured bridge
as an unresolved variable the operator is asked for. Bind-all hosts
normalize to 127.0.0.1.

Remove the six redundant top-level keys from config.example.json and
update README/AGENTS/bootstrap notes. Tests cover derivation, bind-all
normalization, and the unconfigured-bridge skip.
2026-10-08 00:17:53 +00:00
gabby d9cc7e4fed bridges: add a Nextcloud bridge (files, calendars, tasks, contacts, notes)
A standalone bridge wrapping the account's native protocols — WebDAV files,
CalDAV events and tasks, CardDAV contacts, and the OCS Notes API — behind one
token-guarded localhost JSON surface, so a codegen-authored body never speaks
DAV/OCS directly.

- nextcloud_client.py: stdlib-only client (urllib + xml.etree + ssl + base64)
  with Basic auth, DAV/OCS request bodies, and minimal iCalendar/vCard build +
  parse; every failure is a NextcloudError carrying the HTTP status.
- nextcloud.py: NextcloudBridge with no service daemon (check_requirements is
  always (True, None)), ~35 routes (GET reads, POST mutations). Event/task
  updates edit the stored iCalendar in place (preserving VALARM/ATTENDEE) behind
  If-Match; creates use If-None-Match. Missing connection is 503; a real
  Nextcloud failure is 502, never a fabricated success.
- registry: CATALOG entry + build_bridge passes the top-level nextcloud_* values
  as a fallback so the account the calendar seeds collect is configured once.
- config.example.json: bridges.nextcloud block + nextcloud_bridge_url/token.
- docs: README, AGENTS, bridges/__init__, bootstrap closing notes.

Tests drive the real client over a loopback http.server faking Nextcloud's
DAV/OCS shapes. One codegen test's context window was raised because the bridge
catalog injected into every prompt grew the baseline prompt.
2026-10-07 12:17:39 +00:00
gabby e64354e78d docs: align CODEGEN.md/TESTGEN.md with the codebase
CODEGEN.md:
- replace the stale "Manifest schema" (allowed_inputs/actions/cost_budget/
  decision_log_ref, a dotted leaf name) with the real registry shape and note
  the body writer does not author it
- document ctx.timers (and that ctx.admin is built-in-only) and the
  request.meta resume cache, both used by the authoritative seed set
- correct acceptance criteria: INTEGRATION is not hard-rejected (inferred /
  fidelity-gated); note which items the parser actually enforces; compile ->
  ast.parse
- fix the SemIf URL, the structured-state claim (state is a string here), the
  config_vars/CONTRACT relationship, and defer llm_bridge_* names to the catalog

TESTGEN.md:
- separate the only static check (ast.parse) from execution (exit 0); state
  that stdlib-only/inline-fixtures/hermeticity are required but not verified
- clarify contract.json is handed to the test writer as context

README.md: fix the same stale manifest field list.

tests/test_codegen.py: add guards for the runtime surface and against the
stale manifest fields returning.
2026-10-07 11:30:58 +00:00
gabby dff4849947 simplex: honest forwarding — verify sends, disambiguate contacts, read persistent unread
The SimpleX forwarding path could report a failed send as success and could
route to the wrong peer:

- contact_entry dropped the daemon's unique localDisplayName, so two peers
  sharing a profile name ("pepper" / "pepper_1") were indistinguishable; the
  agent's SemIf choice then picked the stale one.
- The bridge's POST /send enqueued the message fire-and-forget and returned
  ok:true; the daemon later marked it sndError (auth), yet the agent reported
  "sent" and assessed success.
- next_message read only the live buffer, missing messages that arrived before
  the bridge started.

Fixes:
- simplex_ws: contact_entry exposes local_name + connected/auth_errors;
  parse_chat_item surfaces the agentError; parse_send_response normalizes a
  /_send reply; add correlated send()/request_send().
- bridges/simplex: resolve disambiguates by id -> local_name/display_name and
  prefers the healthiest peer; send() confirms the real terminal status
  (sndSent/sndRcvd ok, sndError with reason) instead of a false ok; /unread
  carries cached connection health; catalog documents the new fields/status.
- bridges/inbox: carry local_name/connected/auth_errors through the cache.
- seeds/simplex/next_message: fall back to /unread + /history and prefer the
  healthy conversation.
- tests: updated shapes + new coverage for resolution and send verification.
2026-10-07 09:47:26 +00:00
gabby 0efbf218c5 docs: regenerate flow-main.svg (leaf intent guard never bypassed)
Rendered from docs/flow.md with @mermaid-js/mermaid-cli v12 (Chrome
headless): the main pipeline diagram drops the INTENTBYP node and the
leaf_softmax_prob label, matching the navigation change. flow-authoring.svg
is content-identical and was left untouched to avoid a cosmetic re-render
diff.
2026-10-07 09:10:28 +00:00
gabby f1e0de33ca navigation: never bypass the leaf intent guard
The leaf softmax offers only existing skills (create_skill is deliberately
not an option), so a confident winner is "the closest existing skill", never
a statement that it matches. Skipping the intent guard on a confident leaf
softmax winner therefore made codegen unreachable for an unmatched request:
with Winnow as the engine, "send a message to pepper on SimpleX" picked
connect_link (0.86) / next_message (0.995), bypassed the guard, and ran a
read skill instead of authoring simplex.send_message.

Always run confirm_skill_fit at the leaf — it is the sole leaf-level create
door. The category scope bypass stays (create_category is one of its
options, so a confident category winner is meaningful). Drop the now-unused
leaf_softmax_prob meta plumbing; update the docs and the regression test.

Also fix a deployment-hostname leak ("guppy") in winnow.py's docstring that
tripped test_no_env_leaks.
2026-10-07 09:08:13 +00:00
gabby ee7700275c add remote winnow support 2026-10-07 08:12:45 +00:00
gabby 17f16a6bfc engine: opt-in GPU offload for the decision engine
Let the SemIf decision engine run on a GPU via llama.cpp. SemIf's llamacpp
backend is CPU-only by construction (it hardcodes n_gpu_layers=0), so the
agent wraps `_cpu_model_params` for the duration of the load and restores it
after — no patch to the re-cloned engine source.

- `engine.gpu_layers` / `gpu_device` / `gpu_split` in config (default 0 = CPU).
- On the GPU path, force a full cache reset (`llama_memory_clear(mem, True)`):
  SemIf's metadata-only clear leaves stale hybrid-attention state on Vulkan,
  so repeated scores drift (0.08 -> 0.36 -> 0.43) and return wrong
  probabilities.
- Fail loudly when `gpu_layers` is set but the build has no GPU backend.
- bootstrap.sh: opt-in `--gpu auto|vulkan|rocm|cuda|cpu`. A GPU build is
  opt-in because llama.cpp's Vulkan backend splits the graph across CPU and
  Vulkan even at `n_gpu_layers=0`, roughly halving CPU throughput, so a CPU-only
  host must keep the CPU wheel. Detects the backend, installs the Vulkan build
  prereqs, and rebuilds when offload support disagrees (pip's wheel cache
  otherwise serves the CPU wheel back).
- Bump the SemIf pin 1f2dea3 -> 23cf1f3.
- Tests: unit coverage for the config mapping + loader patches; an integration
  test asserting GPU determinism and CPU parity.
- Offload needs the accelerator to itself (~2.9 GiB for the 4B Q4 model): a GPU
  already holding another model makes the engine slower than CPU and can abort
  with `vk::DeviceLostError`.
2026-10-07 05:21:21 +00:00
gabby 4e70a5889e docs: update flow diagrams to current state
flow-main.svg and flow-authoring.svg were stale (authoring from Oct 2,
main predating the actionability guard and the Oct 6-7 changes).

flow-main:
- intake names all front ends (REPL, gateway DM: SimpleX/LXMF/voice,
  dashboard)
- deterministic meta-command route (parse_meta_command -> housekeeping)
  ahead of navigation
- actionability guard at the top of navigation; the category softmax
  offers only real categories + create_category (response is no longer
  an option)
- confident-winner bypass of the scope/intent confirms
  (softmax_bypass_tau)
- intent guard, hard-locked category shortcut, new-skill lock gate,
  awaiting_skill_body guard
- empty/definitive result counts as success; canned and deterministic
  categories skip assessment; act-raises -> repair
- structured SchedulerReply output

flow-authoring:
- split entries: create (draft worker) vs repair/regen/restart (straight
  to the codegen worker)
- approval "no front end" aborts; registration seeds locks.new_skill
- skill_writing/skill_ready traces, regen reason kinds, cancel_build path

flow.md source, prose, and reading-path table updated to match.
2026-10-07 04:02:37 +00:00
gabby e9a7fc73ee scheduler/gateway: carry skill identity structurally, not in action_log
Skill bodies prefixed their own `category.name` into `ActionResult.action_log`,
which duplicated the runner's deterministic summary prefix and leaked the name
into the text the gateways speak. Identity is not data for the output string.

- bodies (seeds, canned replies, housekeeping meta skills) write only the real
  result; the runner already owns the `category.name:` summary prefix
- `run_queue`/`submit_request`/`answer` now return a structured `SchedulerReply`
  (status, text, run_id, skill_ref, result); the gateway reads `skill_ref` and
  `result` from it instead of regex-parsing them back out of the summary
- drop the gateway's `_SKILL_REF`/`_LEADING_RUN_ID` parsing helpers
- fix a latent double-prefix when a failed run had an empty action_log
- CODEGEN.md: generated bodies must not prefix the skill name
2026-10-07 00:30:37 +00:00
gabby d0c1dccffd navigation: skip confirms on a confident softmax; per-skill humanize; 500ms VAD
Four latency/ergonomics changes from the voice-gateway diagnosis:

1. Per-skill humanize override. A skill's own recorded config
   (data/skills/<cat>/<name>/config.json -> {"humanize": bool}) now wins over
   the per-platform and global defaults, so an already-speakable result
   (time.now) can skip the rewrite. The gateway resolves the skill ref from the
   result summary; `_finish_run` now emits `category.name: ok — …` (matching the
   assessment summary) so the ref is available. Missing store/config/key and
   test doubles degrade to the existing platform/global behavior.

2. Example voice endpointing: vad.silence_ms 1000 -> 500 (config.example.json).

3. Confident softmax winners skip their confirm guard. New
   navigation.softmax_bypass_tau (default 0.5): a category winner at/above it
   skips confirm_category_fit (trace `category_scope_bypassed`); a leaf winner
   at/above it is handed to dispatch and skips confirm_skill_fit (trace
   `intent_bypass`). Below the threshold the two-stage confirm is unchanged.
   Assumption tested first on the decision log: 28/28 category and 28/28 leaf
   winners >= 0.5 agreed with their guard.

4. Engine-throughput investigation saved to AGENTS.md "Later / open questions"
   (routing/assessment compute dominates; profile the engine, not the audio).

Tests updated for the bypass threshold and added for the skill-level humanize
override and bypass paths. Full suite: 486 passed, 1 skipped.
2026-10-06 22:33:38 +00:00
gabby 5bb0e9d21d voice gateway: instrument end-to-end latency
Add trace boundaries and timings so the last-word -> first-audio latency can
be split by section:

- voice_transport: emit `voice_speech_end` (the last VAD-speech frame, i.e. the
  true "last word"), `voice_speak_start`, `voice_tts_synth` (Piper duration +
  audio length), and `voice_playback_start` (the instant the first reply
  samples reach the device).
- trace: `TraceLog.append` accepts an explicit `ts` so an event records when it
  happened, not when it was written.
- gateway/voice: trace `gateway_reply_dequeued` at the outbound pump.
- gateway/service: trace `humanize` (duration) and `gateway_reply_queued`; a
  best-effort `_trace` helper tolerates test doubles with no trace log.
- log: persist the engine's per-decision `input_tokens`/`forward_seconds`/
  `total_seconds` (already computed by the backend, previously discarded) into
  the decision row's `extra.timing`.

scripts/voice-latency.py reads data/runs.jsonl and prints a per-interaction
breakdown (endpointing, STT, each SemIf guard, act/assess, humanize, TTS,
playback) plus aggregates.
2026-10-06 22:01:32 +00:00
gabby e426998cf7 llm: add the loaded semif engine as a text-generation provider
Restore SemIfEngine.generate (autoregressive sampling from the loaded
llama.cpp context) and wrap it in provider.SemIfEngineClient, a non-HTTP
sibling of OpenAICompatClient with the same chat() surface. llm.SemIfLLMClient
keeps the LLMError contract so the scheduler's graceful draft_failed path and
the LLM bridge's 502 path are unchanged.

llm.provider now selects "semif" (the in-process decision model, no endpoint
or model needed), "opencode", or the default "ollama"; build_llm_client owns
the choice (build_scheduler delegates). Knobs live under llm.semif
(temperature 0 = greedy, max_tokens). bootstrap skips the ollama llm
warn/pull/probe when provider is semif.

Only the llm task supports it; codegen still needs a real code model.
2026-10-06 21:35:21 +00:00
gabby 1dc0550659 replace urgency priority queue with strict FIFO
Drop the urgency score and interrupt/preempt decisions: intake is now
idle -> dispatch, busy -> append to a bounded FIFO queue (RequestQueue).
The running process always finishes before the next queued request.

- queue.py: UrgencyQueue -> RequestQueue (deque, no weight/age/recency)
- scheduler.py: remove _priority_score, _interrupt_choice, urgency
  constants, and the weight threaded through dispatch/authoring/requeue
- dashboard/static/gateway: drop weight + preempted handling
- tests + docs updated; flow-main.svg regenerated
2026-10-06 20:38:49 +00:00
gabby a354958599 time seeds: report the configured timezone, not the host's
The time seeds resolved "local" via datetime.now().astimezone(), which
returns the host's local zone. On a UTC host that is UTC, so "what time is
it?" answered in UTC. Decouple from the host: add a top-level `timezone`
config value (an IANA name; empty/unknown falls back to host local) and
resolve it through zoneinfo.

- timers.py: add resolve_timezone/local_now; TimerService takes a
  timezone and formats due/fired times in it (Timer carries the tzinfo).
- scheduler.py: pass config["timezone"] into TimerService.
- seeds/time/{now,date,set_alarm}: use local_now(ctx.config).
- seeds/calendar/{create_event,next_event}: derive "now" the same way, so
  a requested time is parsed in the user's zone.
- config.example.json: add `timezone` (empty = host local).
- tests: cover resolve_timezone, local_now, and zone-formatted timers.
- AGENTS.md: document the timezone value.

config.json (gitignored, per-machine) sets timezone to America/Chicago.
2026-10-06 11:26:11 +00:00
gabby 85cdb94dc9 humanize ouputs at gateway 2026-10-06 10:29:57 +00:00
gabby ddbe5f167d assess empty query results as success, not failure
A query skill whose correct answer is "nothing" (no unread SimpleX
messages, no upcoming events) was marked failed by assess:outcome: the
option text framed the decision as literal goal-achievement, so the
model read "no messages" as the goal not being met. The run then
offered a repair and could rewrite a working skill.

Reword the assess:outcome options so a definitive "nothing found /
nothing to do" result counts as success and only an error, refusal, or
unresolved action is failure. Option ids and the question are unchanged,
so the decision-log schema, dream labels, and existing unit tests are
unaffected. Real-engine scores: empty inbox 0.145 -> 0.969, no events
0.132 -> 0.959, while unreachable/HTTP-401/discovery failures stay
failure.

Add an integration regression test and a CODEGEN.md note that an
explicit empty/none result is a successful run.
2026-10-06 09:36:00 +00:00
132 changed files with 20265 additions and 6862 deletions

No files matched your search

+6 -1
View File
@@ -12,10 +12,15 @@ 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
# of the shipped agent.
local/
*.egg-info/
*.bak.*
*.bak.*
# Skill packs live in their own repositories (one per pack) and are cloned into
# packs/<name>/ at setup. They are not tracked here. See PACKGEN.md.
packs/
+66
View File
@@ -0,0 +1,66 @@
---
name: Pack Generation
description: Author a new semif-agent skill pack (its own packs/<name>/ repository) — the pack.json manifest, its skill leaves, its bridge reference, and its config schema. Use when adding a new concern/product bundle as its own pack repo, or when adding a new bridge service to back one.
---
# Pack Generation
This skill walks you through adding a **pack** to semif-agent. The full contract
is the repository file `PACKGEN.md` (at the repo root, i.e. `../../../PACKGEN.md`
relative to this skill). Read it before making changes — it is the source of
truth and this skill is only the workflow.
## When to use
- The user wants a new concern/product bundle (its own `packs/<name>/` repo).
- The user wants a new third-party service backed by a bridge that ships with
its pack (`packs/<name>/bridge/`).
- The user is adding skills that should ship as a pack rather than be
authored at runtime.
## Workflow
1. **Read `PACKGEN.md`** in full.
2. **Decide the concern and categories.** Write one- to two-sentence,
navigation-grade category descriptions — SemIf routes on them.
3. **Bridge check.** If the pack talks to a third-party system, confirm a bridge
already fronts it (a shipped pack's `bridge/`, or the shared LLM bridge). If
not, author the bridge first (see the "Authoring a new bridge" section of
`PACKGEN.md`), ship it under `packs/<name>/bridge/`, and give it a pack config
block.
4. **Create the pack** (its own repository, `pack.<name>`):
`packs/<name>/pack.json` with `name`, `title`, `concern`, `categories`,
`bridges`, `requires`, `enabled_by_default`, and the `config` schema. Model
it on `packs/essentials/pack.json` (bridge-less) or
`packs/simplex/pack.json` (bridge-backed). If the pack needs python deps,
ship them at `packs/<name>/requirements.txt` (pinned, pip format) — never in
the agent repo's `requirements/` (see `PACKGEN.md`, "Pack python deps").
5. **Add each leaf** under `skills/<category>/<leaf>/` — `skill.py`,
`manifest.json`, `contract.json`, `skill.test.py` — following `CODEGEN.md`
and `TESTGEN.md`. Do not restate those rules; follow them. Ship each bridge
under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
6. **Regenerate and validate config:**
`python -m semif_agent.cli check-config --write-example config.example.json`
then `python -m semif_agent.cli check-config`.
7. **Run the tests:**
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
(it runs every pack's skill and bridge tests, including the new ones).
8. **Cross-link** the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
pack).
9. **Verify a real run** against the user's actual service — a passing hermetic
test proves mechanics only, never the live integration.
10. **Register and publish:** add the pack to the `semif-packs` pack-index repo
(an entry in its `packs.json`: name + clone URL, plus title/description for
the interview), then commit and push the pack's own repository
(`pack.<name>`). `scripts/bootstrap.sh` reads the index and clones it into
`packs/`.
## Guardrails
- A pack is declarative, committed in its own repository; never put a credential
in it (secrets live in the gitignored `secrets.json`).
- A bridge **ships with its pack** (`packs/<name>/bridge/`); the core keeps only
the shared contract + discovery. Never widen the gateway.
- `concern` and `categories` are required; every category needs a description.
- Regenerate `config.example.json` from the schema after any schema change; the
example and the live config are never hand-edited.
+1188 -313
View File
File diff suppressed because it is too large. Load diff
+189 -58
View File
@@ -6,22 +6,32 @@ body must be written.
The mocking/testing side of a skill is NOT specified here — it has its own
contract, `TESTGEN.md`. This file is about the runnable body only.
A skill that ships as a committed starter lives inside a **pack**; how a pack
bundles skills, references a bridge, and declares its settings is the separate
contract `PACKGEN.md`.
## What a skill is
Semif-agent is an end-user application: an everyday person asks it to do a task,
and it does that task using a combination of user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based classification engine known as SemIf.
and it does that task using native python modules — including direct HTTP
requests to a service's own API — user-provided data, and, where warranted, a
catalog of basic services known as bridges. A skill is the thing that performs
one of those tasks: it is the leaf in the skill tree that the agent navigates to
when it has resolved a request to a single, concrete action. Navigation is
performed by an llm-based decision engine known as SemIf.
A skill is three things:
1. **A manifest** — the registry entry that makes it navigable and describes
what it does.
1. **A registry entry** — its navigable `name` + `description`, recorded in
`data/categories.json` and mirrored in the running tree.
2. **A code body** — a runnable Python module implementing a single `act`
phase against a real service.
3. **A declaration** — the `INTEGRATION` constant (which real system the body
talks to and how) and the `CONTRACT` constant (the values the runner must
provide).
The committed seed `seeds/calendar/create_event/` is the **authoritative worked
The `nextcloud` pack's create_event skill
(`packs/nextcloud/skills/nextcloud/create_event/`, from its own repo) 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.
@@ -50,7 +60,10 @@ It performs one forward pass and reads the probabilities of the declared answer
tokens directly. It returns a probability for each option — no sentence, no
JSON, no decoding loop, nothing to parse. In effect it is a semantic `if`:
software asks a yes/no/which question in natural language and gets back a typed,
thresholdable number. The `state` may also be a nonempty JSON object or array.
thresholdable number. In this agent the `state` is always a string
(`request.text`, or the query plus a list of candidates); the broader SemIf
project also accepts a nonempty JSON object or array as state, but a body here
must pass a string.
The whole point is that the **question and options arrive with the request**.
Routing, selection, and assessment are not baked into the model or the prompt;
@@ -66,7 +79,7 @@ code.
### SemIf's feature set
SemIf (<https://github.com/TheoLeeCJ/SemIf-OpenJev>) is a broader project than
SemIf (<https://github.com/TheoLeeCJ/SemIf>) is a broader project than
the one call this agent makes. Its full feature set:
- **Runtime-defined decisions** — state, criterion, and option descriptions are
@@ -134,9 +147,10 @@ engine/runtime concerns, not body-level tools: a body makes direct typed
decisions and lets the runner own the model.
Note that the runner's own **assessment** of whether a run succeeded
(`assess:outcome`) is itself a SemIf decision over the body's `action_log`, the
goal, and the resolved inputs. The body does not self-assess; it reports
truthfully and lets SemIf judge.
(`assess:outcome`: is there any additional work to be done to satisfy the
request? → done / continue / failed) is itself a SemIf decision over the body's
`action_log`, the goal, the resolved inputs, and the steps already taken. The
body does not self-assess; it reports truthfully and lets SemIf judge.
### Choosing between deterministic code, SemIf, and LLM text
@@ -159,35 +173,59 @@ Rules:
real candidate set (fetched from the service), include any configured default as
one of the options, and threshold the winner: use it when its probability clears
the skill's confidence threshold, otherwise fall back to the configured default
(see `calendar.create_event` and `simplex.next_message`).
(see `nextcloud.create_event` and `simplex.next_message`).
- **Use the LLM bridge for text, not for routing or assessment.** Generated text
goes through the LLM bridge (`llm_bridge_url`, `llm_bridge_token`) — a generic
`POST /chat` — never by speaking a model's protocol directly. Keep the model
extractive and bounded (see how `calendar.create_event` asks only for a title
and description), and report a real failure when the bridge is down rather than
guessing the text.
goes through the LLM bridge — a generic `POST /chat` whose base URL, token,
and endpoint shapes are in the bridge catalog injected below — never by
speaking a model's protocol directly. Keep the model extractive and bounded
(see how `nextcloud.create_event` asks only for a title and description), and
report a real failure when the bridge is down rather than guessing the text.
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
selects, or assesses; deterministic code never invents a value it cannot
observe. A request input is resolved by SemIf, not by substring matching by
hand; a title is generated by the LLM, not assembled by string concatenation
when it should be written; a date is parsed by code, not asked of a model.
## Manifest schema
**Connectivity is separate from these three sources.** The table is about
*values*, not about how a body reaches a service. A body calls a **plain HTTP
API directly** with a stdlib transport (endpoint and credentials read from
`ctx.config`); a bridge is only for a service that needs state (especially auth
state), a native or heavy protocol, or one sanitized surface. See "Bridge
services" below for when to use one — and the hard rule for a service a bridge
already fronts.
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
## The registry entry
| Field | Meaning |
| -------------------- | -------------------------------------------------------------------- |
| `name` | `category.skill` dotted snake_case id. Lowercase letters, digits, `_` and `.` only (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`). Single purpose. |
| `category` | The top-level category bucket the skill lives under. |
| `description` | One to two sentences: what the skill does, for navigation. |
| `allowed_inputs` | What the skill accepts / needs as input context. |
| `actions` | The concrete actions the skill takes. |
| `cost_budget` | Relative budget for one run; a run that exceeds it fails fast. |
| `decision_log_ref` | Reference to the decision rows this skill logged during a run. |
The body writer does **not** author a manifest. The `llm` provider authors the
leaf's `name` and `description`, and the scheduler records them in
`data/categories.json` (mirrored in the running tree). You are told the chosen
`name` and `description` in the prompt; use them, and never invent or rename the
skill.
Only `name` and `description` are required for a stub; the rest fill in as the
skill is exercised.
The registry is a map of category -> bucket:
```json
{
"<category>": {
"description": "<one to two sentences: the bucket's purpose>",
"skills": [
{
"name": "<leaf_name>",
"description": "<what this leaf does, for navigation>",
"goal": "<the de-identified, reusable action statement>"
}
]
}
}
```
- A leaf `name` is a single snake_case token (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`),
not dotted with the category; the category is the key it lives under, and the
runner joins them as `category.name` only when it builds the run summary.
- `goal` is the de-identified, reusable action statement authored by the local
`llm`; the scheduler records it so a stub can be re-driven later. The
originating request and any user detail are never persisted here, and never
reach the codegen endpoint.
## Code body contract
@@ -261,8 +299,16 @@ def act(ctx, request) -> ActionResult:
"""Perform the real action and return the result + new state."""
```
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and
`ctx.config` (the resolved values for this skill, including its own config).
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine),
`ctx.config` (the resolved values for this skill, including its own config),
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
`ctx.catalog` is a **read-only** view of the agent's own skill tree for an
introspection skill that reports what the agent can do: `ctx.catalog.categories()`
returns a `{category_id: description}` map and `ctx.catalog.skills(category)`
the leaf names inside one category (the `skills.list_categories` /
`skills.list_skills` seeds). `ctx.admin` exists for the built-in housekeeping
meta skills only; an ordinary body must never touch it.
- `request` is the `Request` being handled.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
@@ -363,8 +409,10 @@ INTEGRATION = {
(`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for
skills that perform no external action at all (pure analysis/formatting); an
action skill must not use it.
- `config_vars` — the `ctx.config` keys the body reads for this integration.
Empty list allowed for `compute`.
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
the shipped seeds this is exactly the body's `CONTRACT` key set; an empty
list is allowed for `compute`. Declaring a variable the body never reads is a
mismatch the fidelity check flags.
The auto-run test is a hermetic mechanics check and never exercises the live
service, so this declaration is how the agent knows what the skill was built to
@@ -398,7 +446,7 @@ return ActionResult(..., decisions=[(decision, result)])
options, so the request can override the stored default.
- When the winner is weak (its probability is below the skill's confidence
threshold), fall back to the configured default; with no configured default,
keep the weak winner. See how `calendar.create_event` resolves its calendar.
keep the weak winner. See how `nextcloud.create_event` resolves its calendar.
### Producing the result (output)
@@ -418,15 +466,53 @@ happened:
Rules:
- **Do not prefix the skill name to `action_log` or `new_state`.** The runner
wraps the result in the deterministic summary (`category.name: ok — <detail>`)
and carries the skill ref structurally, so a body writes only the result text
— never `"<category>.<name>: ..."`.
- **Return the real result.** A read/query skill returns the data it fetched; an
action skill reports the service's real response. A generic "done" that omits
the result is a broken output.
- **Never an empty or placeholder output.** If there is genuinely nothing (empty
inbox, no matching event), say so explicitly — that is a real result.
inbox, no matching event), say so explicitly — that is a real result, and a
**`done`** run: the `assess:outcome` step treats a definitive "nothing found /
nothing to do" result as done. Phrase it as the answer the user asked for
("checked the inbox: no unread messages"), not as an absence or an error, so
the assessment does not read a healthy empty result as a failure.
- **Keep the result speakable — it is bounded.** A skill's output is read in a
chat message or heard as speech, so the runner truncates `action_log` /
`new_state` to one shared budget (`chain.result_chars`, ~300 characters /
~20 seconds of speech) and feeds the bounded text to the assessment and the
run ledger. A result longer than that is a bad result. When a skill's real
product is long or structured (a file listing, a document body, a full
thread), write it to the service or a file as a **side effect** and return a
short summary plus a pointer (path / id) — never dump the payload into the
result string.
- **Never claim success you did not observe.** If the action failed, put the
real failure in `action_log` and set `new_state` back to `request.text` (see
the hard requirements).
### Multi-step chains
A request can take more than one action ("calculate 2*10 and send the result to
Pepper"). The runner does not ask one body to satisfy the whole request: it runs
the **next** skill, judges the outcome, and if more work remains re-dispatches
the request with a **run ledger** of the steps already taken. A body may
therefore run as a later step of a chain.
- `request.run_ledger` is a list of `{"query", "skill", "outcome"}` entries, one
per step already taken (empty on a first step). The most recent entry's
`outcome` is the previous step's result — the same bounded text the runner
shows the user.
- **If the request depends on the previous step's result, read it — never
recompute or fabricate it.** `from semif_agent.skills import last_result`
returns `run_ledger[-1]["outcome"]` (or `""`). Do not ask the LLM bridge to
redo a calculation or re-fetch a value an earlier step produced; that would
silently invent a working value. Prefer a literal value the user stated, then
the prior step's result, and only then generate novel text.
- A body still returns only its own step's `action_log` / `new_state`; the
runner owns the ledger and decides whether the chain continues.
### Rules (hard requirements)
- **Perform the real action.** If the skill's purpose involves an external
@@ -480,28 +566,53 @@ Rules:
pause the human's answer arrives on `request.user_input` and `act` is invoked
again from the beginning — re-derive the query and config, consume
`request.user_input`, and do not re-ask a question you already have an answer
for.
for. `request.meta` is a scratch dict carried on the same request across the
pause, so a body can cache a computed value or an already-collected answer
there and reuse it on the resume pass instead of recomputing or re-asking —
see how `nextcloud.create_event` caches the extracted title/description and the
answers it collected.
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
- **Names match the manifest.** The module is imported as its manifest name;
the function is `act` exactly.
- **Keep the body small — it is ingested whole.** The fidelity decision reads
the *entire* body, so a body that exceeds the engine's context budget is
rejected outright (the pipeline retries once with a "make it shorter"
instruction). Delegate **complex** protocol details to a bridge instead of
hand-rolling a client (a simple HTTP call needs no bridge), and keep `act` to
one purpose; a long body is a signal that the integration belongs in a bridge.
- **The function is `act` exactly.** The module is imported under its registered
leaf name; the entry point is a module-level `act(ctx, request)`.
## Bridge services
Some real systems are reached through a **bridge service**: a standalone local
process that stands up a small, token-guarded HTTP API in front of the system
and owns its native protocol and credentials. The concrete catalog of bridges —
which services exist, their base-URL config var, auth, config vars, and the
exact endpoints with their request/response/error shapes — is injected into the
prompt at authoring time (render it with
A body reaches a real service with a stdlib transport. A **plain HTTP API** is
called directly — `urllib.request` / `http.client`, endpoint and credentials read
from `ctx.config` — and needs no bridge. Some systems, however, are reached
through a **bridge service**: a standalone local process that stands up a small,
token-guarded HTTP API in front of the system and owns its native protocol,
credentials, and connection state. Reach for a bridge only when a simple,
repeatable skill file would otherwise be inconsistent, inconvenient, or unsafe:
- **State, especially auth state.** The service needs an OAuth token, a session
cookie, a live daemon connection, a read cursor, or other state a stateless,
re-run-from-the-top `act` cannot own.
- **Sanitized connectivity.** You want one narrow, token-guarded, audited
surface instead of arbitrary bodies speaking the service's raw protocol.
- **A native or heavy protocol.** The service speaks WebSocket/DAV/OCS or needs
a third-party dependency (a browser, a mail client) a one-file stdlib body
must not carry.
When a bridge **does** front a service, the body calls the bridge and must never
reach around it to the service's native protocol — no WebSocket to
`simplex-chat`, no direct daemon access, no DAV/OCS hand-rolling. It calls the
bridge's HTTP API with the base URL from the bridge's config variable, exactly
like any other HTTP integration:
The concrete catalog of bridges — which services exist, their base-URL config
var, auth, config vars, and the exact endpoints with their request/response/error
shapes — is injected into the prompt at authoring time (render it with
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This
section is only the generic pattern; the catalog is the source of truth for the
bridge-specific details.
A body must never speak a service's native protocol directly — no WebSocket to
`simplex-chat`, no direct daemon access. It calls the bridge's HTTP API with the
base URL from the bridge's config variable, exactly like any other HTTP
integration:
```python
INTEGRATION = {
"service": "<the bridge's service id, from the catalog>",
@@ -512,6 +623,9 @@ INTEGRATION = {
Rules:
- **A plain HTTP service needs no bridge.** If the service exposes a normal HTTP
API and needs none of the three triggers above, call it directly with a stdlib
transport; declare its endpoint in `CONTRACT` and read it from `ctx.config`.
- **Read every value from `ctx.config`.** The base URL, any token, and any
default (recipient/contact/target) come from the config vars the catalog
lists. Never hardcode a host, port, or bridge address in the body.
@@ -521,7 +635,7 @@ Rules:
- **Resolve the recipient/target with a SemIf sub-decision.** When more than one
conversation or target is relevant, resolve which one with a
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
contacts or buffered senders), mirroring how `calendar.create_event` picks a
contacts or buffered senders), mirroring how `nextcloud.create_event` picks a
calendar. Use the catalog's default config var as the configured option when
the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the
@@ -539,8 +653,11 @@ Rules:
- Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category.
- Reach a plain HTTP API directly; use a bridge only for a service that needs
state/auth, a native or heavy protocol, or one sanitized surface — and never
reach around a bridge that fronts the service.
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `calendar.create_event` resolves which calendar
sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar
to write to.
- `act` performs the concrete real action and writes a human-readable
`action_log` that the SemIf assessment step can judge. Include what the
@@ -554,11 +671,12 @@ Rules:
A generated skill is accepted only if:
1. It compiles (`compile(..., "exec")` succeeds), imports every name it uses
(`ActionResult` from `semif_agent.skills`; `DecisionRequest`/`Option` from
`semif_agent.decisions` only when it actually builds a sub-decision; each
stdlib module it calls — no `NameError` at run time), and defines `act`.
2. Its `name` matches the manifest regex and its `category` is given.
1. It parses as Python (`ast.parse` succeeds), defines a module-level `act`
function, and imports every name it uses (`ActionResult` from
`semif_agent.skills`; `DecisionRequest`/`Option` from `semif_agent.decisions`
only when it actually builds a sub-decision; each stdlib module it calls — no
`NameError` at run time).
2. Its `name` matches the leaf-name regex and its `category` is given.
3. Its body imports nothing outside the stdlib and the agent package.
4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
5. It is single-purpose and does not duplicate an existing category leaf.
@@ -579,6 +697,19 @@ A generated skill is accepted only if:
11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
and is consistent with the body's `ctx.config` reads and behavior.
12. It does no network, file, or engine work at import time.
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
service's native protocol), resolves recipients with a SemIf sub-decision,
and sends only on explicit user intent.
13. If the service it targets is fronted by a bridge, it calls that bridge over
HTTP (never the service's native protocol); otherwise it may call the
service's HTTP API directly. A messaging skill resolves recipients with a
SemIf sub-decision and sends only on explicit user intent.
14. It is small enough to be ingested whole by the fidelity decision (a body
over the engine's artifact budget is rejected as too long) — delegate
complex protocol details to a bridge rather than hand-rolling them (a simple
HTTP call needs no bridge).
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
body outright. The rest are not statically rejected: a missing or inconsistent
`INTEGRATION` (#11) is inferred and the body is accepted badged `unverified`, a
third-party import (#3) only fails when the module is actually imported, and
import-time work (#12) only shows up when it runs. The fidelity gate rewrites a
body once for these, then accepts it — so treat every item as required, not
optional.
+468
View File
@@ -0,0 +1,468 @@
# PACKGEN.md — the contract for new packs
This file is the authoritative spec for what a **pack** is and how to author a
new one. It is the third sibling of the skill contracts: `CODEGEN.md` governs a
skill's runnable **body**, `TESTGEN.md` governs its **test**, and this file
governs the **pack** that bundles a concern, its skills, its bridge reference,
and its settings into one thing.
Read this before adding a pack. A pack is what makes a new
product/concern a first-class part of the agent instead of scattered edits to
`skills.py` and `config.py`.
## What a pack is
Semif-agent ships a set of starter integrations. Each is a **pack**: a folder
`packs/<name>/` holding a `pack.json` manifest plus a `skills/` store of leaves
in the exact generated-skill format. Each pack lives in its **own repository**
(`pack.<name>`, listed in the `semif-packs` pack-index repo); `scripts/bootstrap.sh`
clones them into the gitignored `packs/<name>/`. The manifest binds the pieces
that would otherwise be scattered by convention:
- the **concern** (what product/job this is) and its **title**;
- its **categories** (the tree buckets it owns, each with a scope description);
- the **bridge(s)** it talks to, referenced by name — and **ships** the bridge
code itself under `bridge/` (see "Authoring a new bridge");
- its **runtime requirements** (optional heavy deps);
- its **enable flag**; and
- its **config schema** (the defaults and validation for its settings).
A pack is loaded by `semif_agent/packs.py` (`PackRegistry` discovers packs,
`merge_packs` loads every **enabled** pack into the tree at startup) and its
`config` schema is read by `semif_agent/config.py` to generate
`config.example.json` and to validate a live config.
Three boundaries must stay crisp:
- A **skill** is one leaf action (`packs/<name>/skills/<category>/<leaf>/`),
governed by `CODEGEN.md`/`TESTGEN.md`. A pack contains skills; it is not one.
- A **bridge** is a standalone process in front of a third-party system,
warranted when the system needs state (especially auth state), a native or
heavy protocol, or one sanitized surface; a system with a plain HTTP API needs
no bridge — its skill calls the API directly. A bridge **ships with its pack**
(`packs/<name>/bridge/`); the core keeps only the shared contract
(`semif_agent/bridges/base.py`) and the discovery registry
(`semif_agent/bridges/registry.py`). The one shared, pack-less bridge is the
**LLM bridge** (a core built-in many packs call). A pack's `bridges` list names
the bridge(s) it ships; a pack never edits core bridge code.
- A pack is **declarative structure**, committed in its own repository.
Per-machine values are the split config; credentials live in `secrets.json`.
A pack repo never holds a secret.
## Folder layout
```
packs/<name>/
pack.json # the manifest (this file's subject)
requirements.txt # optional: the pack's own python deps (pip format)
skills/<category>/<leaf>/
skill.py # the body — CODEGEN.md
manifest.json # {"description": "..."} navigation text
contract.json # mirror of the body's CONTRACT — TESTGEN.md
skill.test.py # hermetic mechanics test — TESTGEN.md
bridge/ # only for a bridge-backed pack (see below)
__init__.py # the pack's bridge package
<bridge>.py # the BridgeService subclass (bridge name)
<bridge>_client.py # optional protocol client (e.g. nextcloud_client.py)
test_<bridge>_bridge.py # hermetic bridge test (loopback HTTP)
scripts/ # optional concern helpers (e.g. an auth or
# setup script), run from the checkout
```
- The `<category>` directory name is the tree bucket; the `<leaf>` directory
name is the leaf's `name`. The runner joins them as `category.name` only in
run summaries.
- Every leaf carries the four artifacts above. Their contents are governed by
`CODEGEN.md` (body + `CONTRACT` + `INTEGRATION`) and `TESTGEN.md`
(test + `contract.json` mirror); do not restate those rules here.
- `bridge/` ships the pack's bridge (one module per name in `bridges`, plus
optional sibling modules it imports relatively). It is absent for a
bridge-less pack. See "Authoring a new bridge".
- `requirements.txt` is the pack's own optional python deps (standard pip
format); it is absent for a stdlib-only pack. See "Pack python deps".
- `manifest.json` holds a single non-empty `description` — the navigation text
SemIf routes on. It is the seed analog of the registry entry a generated
skill gets from the `llm` provider.
- A root with no `pack.json` is treated as **one implicit, manifest-less pack**
whose store is the root itself (a plain skills directory still works), but a
pack repo should always have a manifest.
The shipped packs are the authoritative worked examples: `essentials` is
the minimal bridge-less pack; `nextcloud`, `simplex`, `outlook`, and `browser`
are bridge-backed packs.
## `pack.json` — the manifest
A single JSON object. Fields (from `packs._parse_pack`):
| Field | Type | Required | Meaning |
| -------------------- | --------------- | -------- | ------- |
| `name` | string | no\* | Pack id (snake_case). Defaults to the folder name. |
| `title` | string | no | Human display name. Defaults to `name`. |
| `concern` | string | **yes** | One- to two-sentence statement of the product/job the pack serves. (`description` is accepted as a legacy alias.) |
| `categories` | object | **yes** | `{category_id: scope_description}` — the tree buckets this pack owns. |
| `bridges` | array of string | no | Bridge names this pack ships and talks to. Each name is a `bridge/<name>.py` module in the pack; `simplex`/`llm`/`nextcloud`/`outlook`/`browser` are the shipped names. Empty for a bridge-less pack. |
| `requires` | array of string | no | Optional heavy deps named at a glance (e.g. `playwright`). Informational — the pinned install list is the pack's own `requirements.txt` (see "Pack python deps"), and the code's `check_requirements` is what enforces them at runtime. |
| `enabled_by_default` | bool | no | Default `true`. Whether the pack loads when nothing else decides. |
| `config` | object | no | The pack's config schema (see below). |
\* `name` is optional in the parser but should always be set explicitly.
Rules:
- **`concern` and `categories` are required** (`tests/test_packs.py` fails
without them). A pack with no declared concern is not a pack.
- **Category ids are the tree keys.** They are the same ids the leaf folders
live under (`skills/<category>/<leaf>/`). When `categories` is omitted, the
pack's categories are inferred from the `skills/` subdirectories — but declare
them, because the description is load-bearing.
- **A category description is navigation-critical.** It is what SemIf reads to
route a request into the bucket; a bare id with no description routes badly.
Write one to two sentences naming the concrete jobs the category does.
- **`bridges[0]` owns the config block.** For a bridge pack, the pack's `config`
schema maps onto `bridges.<bridges[0]>`; only the first bridge gets the block
(a pack normally fronts one bridge). Each name in `bridges` must have a
`bridge/<name>.py` module that defines its `BridgeService` subclass.
- Keep the manifest minimal: it binds metadata and settings, nothing executable.
## The config schema
`config` is a nested schema. A **leaf** is a dict with a `default`; a **block**
is a dict without one (recurse). Each leaf spec:
| Key | Type | Meaning |
| --------- | ------ | ------- |
| `type` | string | `bool` \| `int` \| `float` \| `str` \| `list` \| `dict`. Checked by `check-config` (`int`/`float` are interchangeable). |
| `default` | any | The value shipped in `config.example.json` and seeded by `config-init`. Required on a leaf. |
| `doc` | string | One-line plain-language description. Shown in the generated example. |
| `secret` | bool | `true` marks a credential: the example emits `"!secret <pack>_<key>"` instead of a value. |
Example (a bridge-backed pack, mirroring `packs/simplex/pack.json`):
```json
"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."},
"reconnect": {
"initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."},
"max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."}
}
}
```
How the schema maps onto the live config (`config.default_config` /
`generate_example_config`):
- A **bridge pack** (`bridges` non-empty) maps its whole `config` schema onto
the `bridges.<bridges[0]>` block.
- A **bridge-less pack** maps only its `enabled` flag onto
`packs.<name>.enabled`; its other keys are not carried (a bridge-less pack is
configured through its skills' own config, not a pack block).
- Secret leaves become `"!secret <pack>_<key>"` in `config.example.json`, where
`<pack>_` is the pack name prefix (nested keys are prefixed with their path,
e.g. `simplex_reconnect_initial`). Never write a real credential into the
manifest.
Rules:
- Every leaf needs a `default` and a `doc`. A key with no `default` is treated
as a nested block.
- Put **operational** settings here (endpoints, accounts, defaults, timeouts) —
the values a skill body reads from `ctx.config`. Per-request arguments never
belong in config (see `CODEGEN.md`).
- `config.json`, `config/`, and `secrets.json` are gitignored and per-machine.
The manifest is committed structure only.
After changing a schema, regenerate and validate:
```sh
python -m semif_agent.cli check-config --write-example config.example.json
python -m semif_agent.cli check-config
```
`config-init` seeds the split `config/` layout from the schemas (bootstrap runs
it once, only when `config.json` is absent); afterwards only a human edits it.
The generated example and the live config are never hand-edited.
## Pack python deps
A pack owns the python packages its skills and bridge need. Put them in
`packs/<name>/requirements.txt` (standard pip requirements format, pinned) —
**not** in the agent repo's `requirements/`. A pack that is stdlib-only ships no
file.
How the injection works:
- `SkillPack.requirements_file` (`semif_agent/packs.py`) resolves
`packs/<name>/requirements.txt` when it exists.
- The install plan lists those packs: `setup.build_plan` /
`setup.plan_from_config` set `pack_requirements` to the selected/enabled packs
that ship one (`scripts/bootstrap.sh` reads the plan).
- Bootstrap installs each listed pack's file into `.runtime/venv` **after**
cloning the selected packs and creating the venv, and only for packs the host
actually selected (a host that never enables the pack installs nothing). The
`--browser` flag force-adds the browser pack's deps.
Rules:
- **Lazy-import** every heavy dep in the pack's bridge/skills so a host without
the pack still runs — the core stays stdlib-only. A missing dep is a per-call
`503` with an install hint (see "Authoring a new bridge"), never a crash.
- **Pin** the versions (this is a shipped integration, not an app you upgrade in
place). If a dep needs a non-pip step (a downloaded binary, a system package),
ship a helper under `scripts/` and document it in the pack's
`requirements.txt` header — the browser pack's Chromium download is the model.
- `requires` in the manifest is the human-readable summary of the heavy deps;
`requirements.txt` is the authoritative install list. Keep them consistent.
- Never put a credential or a per-machine value in `requirements.txt`; it is
committed structure like the rest of the pack.
## The enable switch
One switch governs the pack's skills **and** its bridge, so a host never offers
a skill whose bridge is off. `packs.pack_enabled` resolves in order:
1. an explicit `packs.<name>.enabled` in config (wins);
2. else, for a bridge pack, `bridges.<bridges[0]>.enabled` (the historical
switch);
3. else `enabled_by_default`.
Disabling a pack drops its categories entirely — including any generated body
authored into one — and stops its bridge. The switch lives in the pack's
`config/packs/<name>.json` fragment (written by `config-init`/`check-config`).
## Referencing a bridge by name
A pack whose skills talk to a third-party system lists that bridge in
`bridges`, **ships** it under `bridge/`, and carries its config block in
`config`. (A pack whose skills reach a plain HTTP API directly needs no bridge:
`bridges` stays empty and each leaf declares the endpoint in its own
`CONTRACT`.) The bridge itself is a `BridgeService` subclass in
`packs/<name>/bridge/<name>.py`; the core registry imports it by convention and
its `BridgeInfo` (name, service, description, URL config var, other config vars,
auth header, endpoints) is injected into every codegen prompt via
`describe_bridges()`, so bodies learn how to reach it without the pack restating
protocol details. The one exception is the shared, pack-less **LLM bridge**
(a core built-in).
Skill-facing config is **derived**, never duplicated: `derived_config_vars`
turns the bridge's `bridges.<name>` block (`host`/`port`/`token`) into the
`<url_config_var>` and `<auth_config_var>` values a body reads from
`ctx.config` (e.g. `simplex_bridge_url`, `simplex_bridge_token`). Bodies call
the bridge over the ordinary `http` transport; their hermetic tests are
loopback HTTP like any other HTTP body.
Rules:
- The bridge block's `enabled`/`host`/`port`/`token` are the pack's config
schema; the URL/token config vars are derived and must not be declared again.
- A pack ships its own bridge and never imports or edits another pack's or the
core's. Gateway isolation is non-negotiable — read/send/address capability is
a bridge, never a gateway feature.
## Authoring a new bridge
A **bridge** is a standalone process that stands up a simple, secure localhost
HTTP layer in front of one third-party system. Author one when a skill body
cannot sanely talk to the system itself — because it holds auth/session state,
needs a native or heavy protocol, or should be reached through one sanitized
surface. A system with a plain HTTP API needs no bridge: its skill calls the API
directly. Adding a bridge means:
1. **Write the bridge class** in the pack's `bridge/<name>.py`, subclassing
`BridgeService` (`semif_agent/bridges/base.py`). Set the `name` attribute and
a module-level/class `INFO = BridgeInfo(...)`. Ship `bridge/__init__.py` (the
package marker) and any sibling modules the bridge imports relatively (e.g.
`bridge/<name>_client.py` for the protocol client):
```python
from semif_agent.bridges.base import BridgeInfo, BridgeService
class WidgetBridge(BridgeService):
name = "widget"
INFO = BridgeInfo(
name="widget",
service="widget_service",
description="The user's Widget account: widgets and their status.",
url_config_var="widget_bridge_url",
endpoints=(
"GET /widgets — list widgets",
"POST /widgets — create a widget",
),
config_vars=("widget_bridge_token",),
config_var_docs=(("widget_bridge_token", "Shared secret for the X-Semif-Token header."),),
auth_header="X-Semif-Token",
auth_config_var="widget_bridge_token",
)
def check_requirements(self) -> tuple[bool, str | None]:
return True, None # stdlib-only
def handle_get(self, path, query): ...
def handle_post(self, path, payload): ...
```
The base class owns the HTTP/JSON/auth plumbing (`start`/`stop`, the
`X-Semif-Token` guard); a subclass implements only its routes. Override
`start`/`stop`/`_stop_transport` only if the bridge owns a service daemon.
Anchor checkout-relative paths (e.g. a token store under `.runtime/`) with
`semif_agent.bridges.base.checkout_root()`, never from the bridge's own
`__file__` — the bridge ships in its pack, so its path is pack-relative.
2. **Declare it** in the pack's `bridges` list and ship its module at
`bridge/<name>.py`. That is what makes it discoverable, describable to
codegen, and runnable via `python -m semif_agent.cli bridge` — there is no
core `CATALOG` to edit.
3. **Carry its config block** in the pack's `config` schema
(`enabled`/`host`/`port`/`token` plus service vars). The schema is what gives
the bridge its config defaults and validation.
4. **Override `BridgeService.from_config`** only when the bridge needs more than
its own block: the scheduler's configured `llm` client (the shared LLM
bridge) or top-level fallback values (like Nextcloud's `nextcloud_*`). A
plain bridge uses the default and needs no override.
5. **Heavy/optional deps:** `check_requirements()` must **never raise** and must
return `(ok, install_hint)`. `run_bridges` aborts **all** bridges when one
reports `ok=False`, so a bridge with an optional dependency (like the
browser) must return `(True, None)` and surface a per-call `503` with an
install hint instead — a missing browser must not take down simplex/llm/
nextcloud. Lazy-import every heavy dep so the core stays stdlib-only.
6. **Report real failures:** a transport/HTTP/bad-reply failure is a `502`, a
missing connection/dep is a `503`, bad input a `400` — never a fabricated
success. The bridge owns its own state (cursors, daemons); bodies keep none.
7. **Test it hermetically:** add `bridge/test_<name>_bridge.py` driving the real
routes over a loopback `http.server` (inject a fake driver where a real
service would be needed). No external network, no real daemon. Import the
bridge through the core registry
(`load_pack_bridge_module("<pack>", "<name>")`) so the test also proves the
pack's bridge is discoverable; `tests/test_packs.py` runs it from the
checkout. `describe_bridges()` picks the new bridge up automatically.
8. **Regenerate** `config.example.json` and run `check-config` (see above), and
document the bridge in `AGENTS.md` (bridges section). Never widen the
gateway for a new capability.
## Acceptance criteria
A new pack is accepted only if:
1. `packs/<name>/pack.json` parses as JSON, declares a non-empty `concern` and
a non-empty `categories` map, and every `bridges` name has a
`bridge/<name>.py` module defining its `BridgeService` subclass.
2. Every leaf under `skills/<category>/<leaf>/` is a complete skill folder
(`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`) satisfying
`CODEGEN.md` and `TESTGEN.md`: a module-level `act`, a flat `CONTRACT` whose
every key is read from `ctx.config`, an `INTEGRATION` consistent with the
code, a non-empty `manifest.json` `description`, and `contract.json` an exact
mirror of the body's `CONTRACT`.
3. The leaf's hermetic mechanics test passes
(`python skill.test.py` from the leaf folder). This proves mechanics only —
only a real run against the user's service proves the integration.
4. Each category id in the manifest is the id its leaves live under, and each
category has a navigation-grade scope description.
5. The `config` schema is well-formed (every leaf has `default` + `doc`; secrets
marked `secret`), maps onto `bridges.<bridges[0]>` (or `packs.<name>` for a
bridge-less pack), and the regenerated `config.example.json` + `check-config`
are clean.
6. A bridge-backed pack ships its bridge test (`bridge/test_<bridge>_bridge.py`)
and it passes hermetically (loopback HTTP, no external network, no daemon).
7. Nothing deployment-specific (hostname, address, username, absolute home
path, local model name) appears in any committed file —
`tests/test_no_env_leaks.py` enforces this for the agent repo; keep a pack
repo clean too. Secrets live in `secrets.json`.
8. If the pack ships a `requirements.txt`, it is pinned, lives with the pack (not
the agent repo's `requirements/`), and its deps are lazy-imported so a host
without the pack is unaffected.
`tests/test_packs.py` enforces items 1–6 and 8 mechanically for every shipped
pack (valid manifest, concern + categories, integration matches code, contract
flat and mirrored, manifest description, hermetic skill test, hermetic bridge
test, pinned pack requirements)
and keeps the shipped pack ids present.
## Worked example — a minimal bridge-less pack
The smallest complete pack needs a manifest and one leaf. `packs/essentials/`
is the committed model; a hypothetical `packs/hello/`:
```
packs/hello/
pack.json
skills/hello/greet/
skill.py
manifest.json
contract.json
skill.test.py
```
`pack.json`:
```json
{
"name": "hello",
"title": "Hello",
"concern": "A trivial local greeting utility that needs no account, network, or bridge.",
"categories": {
"hello": "Greetings: producing a friendly greeting for the user."
},
"bridges": [],
"requires": [],
"enabled_by_default": true,
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load the hello skills."}
}
}
```
`skills/hello/greet/manifest.json`:
```json
{ "description": "Produce a friendly greeting." }
```
The leaf's `skill.py` (a `compute`-transport body — no external action, empty
`CONTRACT`) and `skill.test.py` follow `CODEGEN.md`/`TESTGEN.md`; the shipped
`packs/essentials/skills/time/now/` is the reference for exactly this shape.
For a bridge-backed pack, start from `packs/simplex/pack.json` (bridge
reference + `host`/`port`/`token` + service vars), `packs/simplex/bridge/` (the
bridge module, its package marker, and its hermetic test), and
`packs/simplex/skills/simplex/send_message/` (a body that calls the bridge over
HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/` (its
`bridge/nextcloud.py` overrides `from_config`).
## Checklist
1. Decide the concern and the category ids; write navigation-grade category
descriptions.
2. If a third-party system is involved and it needs state/auth, a native or
heavy protocol, or one sanitized surface, author a bridge first (see
"Authoring a new bridge") and ship it under `bridge/`. A system with a plain
HTTP API needs no bridge — the skill calls it directly.
3. Create the pack (its own repository, `pack.<name>`): `packs/<name>/pack.json`
with `name`, `title`, `concern`, `categories`, `bridges` (if any), `requires`,
`enabled_by_default`, and the `config` schema. If the pack needs python deps,
ship them pinned at `packs/<name>/requirements.txt` (see "Pack python deps").
4. Add each leaf under `skills/<category>/<leaf>/` following `CODEGEN.md` and
`TESTGEN.md` (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`),
and each bridge under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
5. Regenerate and validate config:
`python -m semif_agent.cli check-config --write-example config.example.json`
then `python -m semif_agent.cli check-config`.
6. Run the tests:
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
(it runs every pack's skill and bridge tests, including the new ones).
7. Cross-link the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
pack).
8. Verify a real run against the user's actual service — the only proof the
integration works.
9. Register the pack in the `semif-packs` index repo — add an entry (name + clone
URL, plus title/description for the interview) to its `packs.json` — then push
the pack's own repository (`pack.<name>`); `scripts/bootstrap.sh` reads the
index and clones the pack into `packs/`.
+492 -191
View File
@@ -17,7 +17,7 @@ A successful release of this could be defined by a single question: "Can I use t
- [Why this exists (the reasoning)](#why-this-exists-the-reasoning)
- [How it works](#how-it-works)
- [The scheduler: choose, score, queue, dispatch](#the-scheduler-choose-score-queue-dispatch)
- [The scheduler: queue and dispatch](#the-scheduler-queue-and-dispatch)
- [The skill tree and navigation](#the-skill-tree-and-navigation)
- [The skill run loop](#the-skill-run-loop)
- [Authoring a new skill](#authoring-a-new-skill)
@@ -70,7 +70,7 @@ model entirely:
does.)
- **Simulated Agile patterns.** A skill is a real integration into the active tool chain for end user satisfaction. It takes existing mail
protocols, SimpleX, CalDAV/WebDAV, configured local CLIs, HTTP APIs and your supplied data to produce actions that best fit your query. In the absence of a an existing skill, the skill generation process is activated. Skill generation has four major phases - definition, refinement, coding, testing (unit and integration). Each step in this process has deterministic and probabilistic handling optimized to achieve the stated goal of the user in the context of the platform's core mission.
- **Nothing is gated out up front.** Every input is dispatched and scored.
- **Nothing is gated out up front.** Every input is dispatched.
Inputs that are not requests fall through navigation into the closed `response`
category — a hardcoded tree of canned replies (`greeting`, `thanks`,
`acknowledge`, `farewell`, `affirm`, and the catchall `clarify`). A request no
@@ -88,25 +88,23 @@ model entirely:
## How it works
### The scheduler: choose, score, queue, dispatch
### The scheduler: queue and dispatch
Implemented in `semif_agent/scheduler.py` and `semif_agent/queue.py`:
```
intake (typed input / messenger gateway / scripted)
└─ choice "should this interrupt the current process?" (SemIf)
├─ yes → preempt current, requeue it with state preserved
└─ no → score "how urgent?" critical/high/medium/low (SemIf)
└─ urgency priority queue (weight desc, then FIFO)
├─ idle → dispatch immediately
└─ busy → FIFO queue (arrival order, no priority)
```
- The **queue** is a max-heap by urgency weight, FIFO within equal weight, with
upward ageing so low-priority items cannot starve (`queue.py`).
- The **queue** is a strict first-in-first-out list of pending requests with a
maximum depth (`queue.py`). There is no urgency scoring and no preemption.
- A **skill run paused for input** (`needs_input`) keeps the current slot busy;
an answer routes straight back to the pending run, bypassing
choice/score/navigation.
- A high-priority input can preempt the running process, which re-queues with its
state preserved.
an answer routes straight back to the pending run, bypassing the queue and
navigation.
- The running process always finishes before the next queued request is
dispatched.
- Exactly one execution slot. (Concurrency, when it comes, is SemIf's
shared-state mode for parallel *decisions* — not parallel process execution.)
@@ -129,11 +127,15 @@ choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
- **Leaf.** The leaf softmax picks only among the existing skills (a create
option diluted its probability and let a crowded tree drift into create on a
weak plurality). The picked skill then goes through the **intent guard**
(`confirm_skill_fit`, phase `navigate:intent`): an action comparison at
`navigation.intent_tau` asking whether the skill performs the same action the
request asks for. Same → run it; different → author a new leaf in that
category. An empty (or single-skill) category skips the softmax and goes
straight to the guard.
(`confirm_skill_fit`, phase `navigate:intent`): at `navigation.intent_tau` it
decides what the skill does for the request, given the steps already taken
(the run ledger is part of its state). `same` (it performs the next action the
request needs) or `part` (the request needs more than one action and this
skill performs one required part) → run it; `different` (it does no action the
request asks for) → author a new leaf in that category. The guard only decides
whether the skill contributes; whether more work remains is `assess:outcome`'s
call. An empty (or single-skill) category skips the softmax and goes straight
to the guard.
- Both guards are deliberately permissive; with real descriptions the in-scope
cases score 0.9–1.0, so a borderline over-cover routes into a plausible
category and the leaf guard catches it.
@@ -153,12 +155,18 @@ observe baseline → act → observe outcome → assess
a live candidate set) are returned on `ActionResult.decisions` and logged as
training rows with the run outcome.
- `assess` is a **SemIf decision**, not generation:
- `assess:outcome` — success/failure at `tau`; its state includes the resolved
inputs (secrets redacted) so a wrong resolution is visible.
- `assess:requeue` — on failure, `complete` vs `retry` (bounded by
`max_reentries`).
- `assess:outcome` — is there any *additional work* to satisfy the request?
Three outcomes at threshold precedence `failed > done > continue`: `done`
(request satisfied), `continue` (this step worked but more work is needed →
the scheduler routes the logical next step with a bounded run ledger),
`failed` (the step errored → the repair path). Its state includes the skill
action, the goal, the resolved inputs (secrets redacted), the bounded action
log, and the steps already taken.
- The run summary is **deterministic** (same inputs ⇒ same string):
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
- Every skill's output is bounded to one **speakable budget** (`chain.result_chars`,
~300 chars): the result string and its run-ledger entry. A long product belongs
in a file I/O side effect, not the result (see `CODEGEN.md`).
- A skill can pause for human input two ways: `act` returns `needs_input` (act
re-runs on resume, with `request.user_input` set), or — for a contract
variable the runner cannot satisfy — a **pre-act** pause collects config
@@ -170,24 +178,28 @@ When navigation chooses a create branch, the scheduler queues the draft to a
single-slot `llm` worker and the body write to a separate single-slot codegen
worker. It is **asynchronous**, so the gate stays free while either model thinks:
1. **Stub.** The small `llm` provider (`generate_skill`) authors a title +
description on its own worker. The stub is registered and hot-merged into the
running tree as
soon as it lands; a `skill_writing` trace event is emitted.
2. **Elicitation** (`generate_elicitation`, default on): implementation
questions — which service/account, how to connect, where the credential
comes from, what success looks like. Every front end (REPL, dashboard,
gateway) defers to a question queue and the worker waits
(`codegen.elicitation.wait_timeout`).
3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
1. **Spec.** The small `llm` provider (`generate_skill_spec`) authors a title +
description **and a de-identified, reusable goal** (plus the generic
service/transport) on its own worker. The stub is registered and hot-merged
into the running tree as soon as it lands; a `skill_writing` trace event is
emitted. The goal is the *only* task data codegen is ever shown.
2. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
(`codegen`, your configured code-capable model) writes a single `act` against `CODEGEN.md`,
reading every operational value from `ctx.config` and declaring `INTEGRATION`
(service / transport / config_vars) plus its own flat `CONTRACT`
(variable → description; every key must be read from `ctx.config`).
(variable → description; every key must be read from `ctx.config`). **Privacy:**
codegen is the primarily-cloud model, so it receives only the de-identified
spec — never the user's request, question answers, or run output.
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
static `integration_findings`): is the action real, or simulated? One
corrective regen with the raw evidence bundle, then accept-with-badge
(`unverified`) rather than hard-fail.
static `integration_findings`): does the body contain a concrete,
side-effecting operation that really performs its goal? The state carries the
**whole** body (never a prefix) plus a deterministic operation inventory and
the de-identified goal — never the raw request — and asks the positive
question rather than asking the model to prove a negative. Because a decision
ingests the body whole, generated artifacts are size-bounded
(`max_body_chars`/`max_test_chars`, derived from the engine's context). One
corrective regen with the de-identified evidence bundle (inventory + findings
included), then accept with a trace rather than hard-fail.
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
constant — a flat map of snake_case variable name → semantic description, for
user input and SemIf only; `contract.json` is a persisted mirror.
@@ -200,14 +212,14 @@ worker. It is **asynchronous**, so the gate stays free while either model thinks
`codegen.test_max_attempts`.
On success the body materializes to `data/skills/<category>/<name>/`, is
hot-merged, and **the original request is re-queued** at its scored weight and
re-runs navigation onto the new leaf. On failure the leaf stays a restartable
stub. A whole new category runs the same chain deterministically:
hot-merged, and **the original request is re-queued** and re-runs navigation
onto the new leaf. On failure the leaf stays a restartable stub. A whole new
category runs the same chain deterministically:
`create_category` → `create_skill` → async body → re-dispatch.
A rejected/simulated body is traced (`fidelity_review`), badged `unverified`,
and never blocks authoring. Codegen failures (including timeouts) surface as a
graceful stub and are retryable with `restart <category> <skill>`.
A rejected/simulated body is traced (`fidelity_review`) and never blocks
authoring. Codegen failures (including timeouts) surface as a graceful stub and
are retryable with `restart <category> <skill>`.
### What each model sees
@@ -220,27 +232,26 @@ forward pass. There is no hidden system prompt and no growing conversation:
what you see in the table below is the entire input. Probabilities are
conditional on exactly the supplied options.
A **generative call** (`llm` for titles/descriptions, `codegen` for bodies and
tests) is a built OpenAI-style `messages` list. Its context is assembled from
the request, the tree, the elicitation answers, the runtime **bridge catalog**
(`describe_bridges()`), and — for bodies and tests — the contract files
(`CODEGEN.md`, `TESTGEN.md`).
A **generative call** (`llm` for titles/descriptions/goals, `codegen` for bodies
and tests) is a built OpenAI-style `messages` list. The trusted local `llm`
context is assembled from the request and the tree; the **codegen** context is
assembled only from the de-identified spec (goal + generic service/transport),
the tree, the runtime **bridge catalog** (`describe_bridges()`), and — for bodies
and tests — the contract files (`CODEGEN.md`, `TESTGEN.md`). Codegen never
receives the user's request, question answers, or run output.
#### SemIf decisions
| Phase | File | State injected | Options |
| --- | --- | --- | --- |
| `interrupt:choice` | `scheduler.py:279` | request text + `[current process: <skill>]` | `interrupt` / `defer` |
| `priority:score` | `scheduler.py:296` | request text (+ `[current process: …]` when busy) | critical / high / medium / low |
| `navigate:category` | `skills.py:682` | request text | every category name (+ `create_category`) |
| `navigate:leaf` | `skills.py:736` | request text + current category | every skill name + description (+ `create_skill`) |
| `navigate:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) |
| `navigate:intent` | `skills.py:811` | `Requested action: <text>` + `Action of the existing skill: <description>` | `same` / `different` |
| `assess:outcome` | `skill.py:257` | skill label + goal + action log | `success` / `failure` |
| `assess:requeue` | `skill.py:279` | skill label + goal + action log + `outcome: failed` | `complete` / `retry` |
| `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
| `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` |
| `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` |
| `authoring:fidelity` | `scheduler.py:1836` | skill, goal, description, `INTEGRATION` JSON, static findings, operation inventory, **whole** body (no raw request) | `accept` / `reconsider` |
| `repair:choice` | `scheduler.py:658` | skill, request, integration, truncated failure | `retry` / `repair_skill` / `ask_user` / `no_repair` |
| degeneration watchdog¹ | `cli.py:128` | `[codegen <model>]` + last 2000 chars of the stream | `continue` / `stop` |
| `codegen_regen`¹ | `cli.py:165` | `[testgen <model>]` + last 1200 chars of the test error | `regen_code` / `regen_test` / `regen_contract` |
@@ -252,23 +263,22 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog**
| Call | Client | System context | User context | File |
| --- | --- | --- | --- | --- |
| `generate_category` | `llm` | authoring instruction: propose one broad category, JSON-only | request text + full tree summary | `skills.py:896` |
| `generate_skill` | `llm` | authoring instruction: propose one specific skill, JSON-only | request + category + existing skill names | `skills.py:947` |
| `generate_skill_body` | `codegen` | full **CODEGEN.md** | request, category, name, description, existing skills + tree summary, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:156` |
| body retry | `codegen` | full **CODEGEN.md** | rejection reason, request, category, name, description, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:474` |
| `generate_elicitation` | `codegen` | elicitation instructions + example questions + anti-patterns + `max_questions` | request, category, name, description, existing skills + tree summary, **bridge catalog** | `codegen.py:580` |
| `generate_data_contract` | `codegen` | full **TESTGEN.md** | skill, request, full body code, **bridge catalog** + the contract ask | `codegen.py:833` |
| `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, request, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
| `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, request, description, **raw evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` |
| `generate_skill_spec` | `llm` | authoring instruction: propose one specific skill + a **de-identified goal** and generic service/transport, JSON-only | request + category + existing skill names | `skills.py:947` |
| `generate_skill_body` | `codegen` | full **CODEGEN.md** | **de-identified spec** (goal + description), category, name, existing skills + tree summary, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:156` |
| body retry | `codegen` | full **CODEGEN.md** | rejection reason, de-identified spec (goal + description), integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:474` |
| `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
| `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, de-identified goal + description, **de-identified evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` |
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py:33`): each
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py`): each
known bridge's name, service, description, base-URL config var, auth header +
token var, documented config vars, and endpoints. It is the single runtime
source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic
pattern — so a bridge can be added without touching either contract file.
pattern — so a bridge can be added without touching either contract file (a
bridge ships with its pack; the registry discovers it by convention).
The **raw evidence bundle** handed to a corrective regen carries the request,
description, requirements, the observed failure fields (error, action log, new
state, summary) and the previous body, rendered as-is with no prose diagnosis.
The **evidence bundle** handed to a corrective regen is de-identified: a generic
failure kind, the integration, the goal, and the previous body, rendered as-is
with no prose diagnosis. It carries no request text and no run output.
### Data contracts and tiered config
@@ -333,7 +343,7 @@ fine-tuning loop — it is not yet the fine-tune itself.
to the closed `response` canned tree.
- **Real integrations by construction** — bodies must perform the real action,
read data from `ctx.config`, declare `INTEGRATION`, and report real failures.
- **Async skill authoring** — elicitation → body → fidelity → contract → test →
- **Async skill authoring** — spec → body → fidelity → contract → test →
auto-run, with a SemIf regeneration ladder on test failure. Gate stays free.
- **Tiered config + first-fire collection** — global/category/skill config with
a `record-vs-ask` decision per answer.
@@ -342,14 +352,21 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM,
including Sideband push-to-talk **voice messages** on LXMF (local transcription,
and voice replies synthesized with Piper).
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
of third-party systems, so generated bodies never speak native protocols.
- **Seeds** — shipped real starter skills: `calendar.create_event` (the
authoritative worked example), `calendar.next_event` (Nextcloud CalDAV), and
`simplex.next_message` / `simplex.connect_link`.
- **Standalone bridge services** — an optional token-guarded localhost HTTP
layer for third-party systems that need state/auth, a native protocol, or a
sanitized surface; a plain HTTP API is called directly.
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`,
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer),
and `skills.list_categories` / `skills.list_skills` (report the agent's own
skill categories, or the skills inside a named category).
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed.
@@ -362,38 +379,57 @@ fine-tuning loop — it is not yet the fine-tune itself.
semif_agent/
cli.py argparse: run / dream / skills / status / relabel /
dashboard / gateway / bridge
scheduler.py no up-front gate; choice -> score -> queue -> dispatch;
preempt + requeue; needs_input pauses; async single-slot
scheduler.py no up-front gate; FIFO queue -> dispatch;
needs_input pauses; async single-slot
skill authoring worker; fidelity gate; repair loop
skill.py observe -> act -> observe -> assess; deterministic
summary; pre-act contract collection; resolved-input state
skills.py tree + registry, canned `response` tree, navigation,
create gates, intent guard, tiered config resolution
codegen.py OpenAI-compatible client; body/elicitation/test generation;
codegen.py OpenAI-compatible client; body/test generation;
parse/validate; CONTRACT + INTEGRATION extraction; test runner
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog)
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
llm.py small OpenAI-compatible provider; authors new title + description
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog);
SemIfEngineClient generates text from the in-process engine
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import);
call() scores, generate() samples text
llm.py small provider; authors new title + description
(ollama / opencode / the loaded engine via `semif`)
log.py decisions.jsonl rows {state, question, options, probs, ...}
trace.py runs.jsonl lifecycle events keyed by run_id
dream.py NLL / weighted CE / accuracy / ECE cost report
decisions.py DecisionRequest / Option / DecisionResult / Request dataclasses
queue.py urgency max-heap (weight desc, FIFO, ageing)
queue.py bounded FIFO request queue
dashboard.py stdlib HTTP + JSON API + static UI
static/ dashboard frontend (html/js/css)
simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge)
voice_transport.py neutral voice transport: mic capture, wake word, VAD,
speech-to-text (faster-whisper), text-to-speech (Piper)
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
bridges/ standalone third-party API bridges (SimpleX + the LLM bridge)
seeds/ committed starter skills (calendar, simplex)
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
requirements/ staging.txt — the pinned engine deps
bridges/ bridge contract + discovery (base.py, registry.py, inbox.py,
llm.py); the concrete bridges ship in their packs
config.py layered config: index includes + !secret + schema/example
packs.py SkillPack + PackRegistry (bundles skills by concern/bridge)
packs/ skill packs, each cloned from its own repo (pack.<name>)
into this gitignored dir — each ships its own bridge/ — the
pack list lives in the semif-packs index repo (see PACKGEN.md)
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
requirements/ core.txt (test runner), engine.txt (local decision engine),
transports.txt (websockets/lxmf), voice.txt (microphone
stack), transcribe.txt (faster-whisper, LXMF voice
messages), tts.txt (piper-tts + PyAV, LXMF voice replies),
codec2.txt (pycodec2, LXMF Codec2 PTT);
staging.txt = union of the non-hardware files;
a pack's own deps live with the pack at
packs/<name>/requirements.txt
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
PACKGEN.md the contract for authoring a skill pack (packs/<name>/)
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 <key>"
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)
```
@@ -403,25 +439,43 @@ local/ gitignored: this deployment's notes (hosts, addresses, model
## Installation
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
decision engine, a pinned GGUF, and an OpenAI-compatible endpoint for codegen.
`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree
in the checkout.
decision engine (local or remote). `scripts/bootstrap.sh` provisions what this
machine needs inside a gitignored `.runtime/` tree in the checkout — and only
what it needs, based on the answers to a short first-run interview.
### Prerequisites: ollama models
### Prerequisites: the decision engine, and optional models
Two OpenAI-compatible endpoints (usually ollama), which may be on different
machines:
The **decision engine** routes every request. It runs one of three ways,
chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run
`scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because it
is slower on CPU).
**Skill authoring is opt-in** (`new_skill_creation`: `deny` by default). When it
is off, no `llm`/`codegen` endpoint is needed at all — the agent only runs the
shipped packs. When it is on, two OpenAI-compatible endpoints are required
(usually ollama, possibly on different machines):
- **`llm`** — a small, fast model that authors the title + description of a
newly created category/skill. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no
`llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host.
- **`llm`** — a small, fast model that authors the title + description of a
newly created category/skill. Deliberately its own endpoint/model, so it can
stay local even when `codegen` is remote; it uses the same provider transport
(`provider.py`) and an unreachable endpoint is graceful (the request is not
re-dispatched), never fatal.
The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your
build enables it), not ollama.
### Option A: one-command provisioning (`bootstrap.sh`)
@@ -431,41 +485,63 @@ 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
values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`,
`--codegen-model` — and are never written back to `config.json`.
On a fresh machine the script **asks a few questions** and writes this machine's
config from the answers:
The script is idempotent (every stage no-ops on existing state) and:
1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index
repo (`semif-packs`): SimpleX, browser, Nextcloud, Outlook, Gutendex (the
`essentials` pack is always on). Only the packs you pick are cloned.
4. **Gateways** — how you talk to the agent: SimpleX, LXMF, voice (or none —
REPL + dashboard only).
5. **Timezone** — an IANA name for timers and reported times.
It then installs **only what those answers require**. Both ends of the spectrum
are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator, skill listing). No account, no network, no gateway, no heavy
downloads.
- **maximum** — every pack, a remote Winnow or Ollama System One decision
engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is
idempotent — on a rerun the interview is **skipped** and the existing config is
used; pass `--reconfigure` to re-run it. `--voice` / `--browser` additionally
install those optional stacks even if the plan did not pick them.
The script:
1. installs system prereqs + enables linger;
2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine;
3. creates `.runtime/venv` and installs the pinned deps from
`requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since
the llama.cpp path never imports torch);
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);
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`;
9. prints the bot's SimpleX contact address.
2. clones/updates the skill packs, then runs the setup interview and writes
`config/` + `secrets.json` (first run or `--reconfigure`);
3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the
SemIf engine;
4. creates `.runtime/venv` and installs only the needed dep files:
`requirements/core.txt` always, `engine.txt` for a local engine,
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for
the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
plus `tts.txt` when `voice.reply_with_voice` is on, and `codec2.txt` + system
`libcodec2` best-effort for non-HQ Codec2 PTT — and each selected pack's own
`packs/<name>/requirements.txt` — e.g. the browser pack's Playwright deps);
5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
and pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
SimpleX gateway or the simplex pack is selected;
7. renders and enables only the systemd **user** units the answers need
(`semif-simplex` bot daemon, `semif-gateway` agent, `semif-simplex-forward`
bridge daemon, `semif-bridge`), retiring any a reconfigure dropped;
8. prints the SimpleX contact address(es) when those services are active.
Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`,
`--copy-data SRC`) override the values read from `config.json` for that run only.
`--voice` additionally installs the optional voice-gateway stack
(`requirements/voice.txt` + system PortAudio) and downloads its models (the
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into
`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache).
Run `scripts/bootstrap.sh -h` for the full list.
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`,
warning (never auto-pulling) if the remote codegen host is missing its model.
Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision,
simplex-chat version/url+sha256) live in the committed `pins.json`, not in
`config.json`.
Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it
pulls `llm.model` from the target host's ollama when configured, and never
auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF
tokenizer revision, simplex-chat version/url+sha256) live in the committed
`pins.json`, not in `config.json`.
### Option B: core only (stdlib)
@@ -476,48 +552,78 @@ 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:
performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF,
tokenizer cache), then generate the split config:
```sh
cp config.example.json config.json
python -m semif_agent.cli setup --interview # or --yes / --answers FILE
python -m semif_agent.cli config-init # schema defaults, no interview
```
### 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 <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` runs
`setup` to generate the split config from your answers; afterwards only a human
edits it (`--reconfigure` re-runs the interview).
```sh
cp config.example.json config.json # if not already created by bootstrap
python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli config-init # seed schema defaults (no interview)
python -m semif_agent.cli check-config # validate against the schemas
```
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 |
| --- | --- |
| `engine` | per-machine engine settings: backend, context, threads, optional GGUF path override (refs come from `pins.json`) |
| `llm` | small model endpoint that authors new category/skill title + description |
| `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget |
| `codegen` | skill-body model endpoint, timeouts, sampler, approval gate, fidelity, repair, test, degeneration watchdog, token budget |
| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
| `tau` | decision threshold; `max_reentries` requeue bound |
| `queue` | `max_size`, `age_rate` |
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `queue` | `max_size` |
| `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, follow-up window |
| `gateway.lxmf` | LXMF gateway: allowlist, Reticulum paths, `result_only` replies, Sideband voice transcription (`voice.enabled` + `voice.stt` model) and voice replies (`voice.reply_with_voice` + `voice.tts` voice) |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
| `llm_bridge_url` / `llm_bridge_token` | what skill bodies call for generation |
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
| `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) |
| `bridges.browser` | Browser bridge: host/port/token + Playwright settings (engine/headless/profile dirs) |
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port |
`llm.model` and `codegen.model` are **required** (no default): set each to a
model its endpoint serves. A missing model fails fast at startup with a clear
config error rather than sending a request to a model that isn't there.
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` /
`nextcloud_bridge_url` / `outlook_bridge_url` / `browser_bridge_url` (+ their
`_token`) from
`ctx.config`; each is **derived** at startup from its `bridges.<name>`
host/port/token, so there is no duplicate top-level key to keep in sync. A bridge
with no block (or no port) leaves the variable unresolved and the operator is
asked for it.
`llm.model` and `codegen.model` are **required only when authoring is enabled**
(`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves.
An empty `codegen.model` means "no authoring path" — the minimum config leaves it
empty and the agent simply runs the shipped packs. With authoring on, a missing
model fails fast at startup with a clear config error rather than sending a
request to a model that isn't there.
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
@@ -533,6 +639,7 @@ Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
All subcommands go through the CLI:
```sh
python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli run # interactive REPL
python -m semif_agent.cli run --script inputs.jsonl
python -m semif_agent.cli dream # cost report
@@ -556,7 +663,7 @@ HF_HOME="$REPO/.runtime/hf" "$REPO/.runtime/venv/bin/python" -m semif_agent.cli
Type a request, or one of the meta-commands:
```
busy <text> mark a current process (so preemption can be demonstrated)
busy <text> mark a current process (so the queue can be demonstrated)
idle clear the current process
status current process + queue
skills skill tree
@@ -599,7 +706,7 @@ shares one scheduler/skill store. `--platform` takes a comma-separated list or
python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard]
```
Each platform feeds authorized DM text through the normal gate/score/queue/
Each platform feeds authorized DM text through the normal queue/dispatch
dispatch pipeline. Results, authoring questions and repair offers go back to the
originating chat. Config lives under `gateway.<platform>` in `config.json`;
`enabled` defaults to false. Both transports are **default-deny** — put allowed
@@ -615,7 +722,7 @@ without it). `allowed_users` entries match a numeric contactId or a display
name. The daemon must run in **bot mode** (`simplex-chat -p PORT
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
"chat relay" and yield a relay address, not a user contact address. Add the
bot's contact link to reach it: `scripts/simplex-address.py` shows/creates it
bot's contact link to reach it: `packs/simplex/scripts/simplex-address.py` shows/creates it
(bootstrap prints it), and the gateway prints it once on connect.
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
@@ -629,6 +736,32 @@ matches the peer's LXMF address (32 hex) or a best-effort display name.
and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it.
**Voice commands (Sideband push-to-talk).** Set
`gateway.lxmf.voice.enabled: true` and a Sideband PTT voice message is
transcribed into a command, just like typed text. HQ PTT (Opus/OGG) is decoded
and transcribed by faster-whisper, which needs only `requirements/transcribe.txt`
(installed by the install plan — no microphone, no voice stack). Non-HQ Codec2
PTT is decoded by the optional `pycodec2` bindings (`requirements/codec2.txt`,
installed best-effort alongside the system `libcodec2`); without it a Codec2
message is reported back rather than dropped. The audio is transient and never
leaves the machine. The model is `gateway.lxmf.voice.stt.model` (default
`base.en`).
**Voice replies.** With `gateway.lxmf.voice.reply_with_voice: true` (the
default), a chat that last messaged by voice is answered with a synthesized
voice message: the reply text is spoken with Piper and sent back as a Sideband
HQ push-to-talk message, with the text also carried as the message content so a
text-only client still sees it. A later text message from that chat reverts it to
text replies. This needs only `piper-tts` + PyAV (`requirements/tts.txt`,
installed by the install plan — still no microphone); a missing stack or a
synthesis failure falls back to a text reply rather than dropping it. The voice
is `gateway.lxmf.voice.tts.voice` (default `en_US-lessac-medium`).
**Result-only replies.** The LXMF gateway sends only the skill's result line:
the scheduler's queue/urgency bookkeeping is dropped and the `<skill>: ok —`
wrapper is stripped, so a DM is the answer, not the internals. Override with
`gateway.lxmf.result_only: false` for the full scheduler output.
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges.
@@ -638,7 +771,7 @@ address as a contact in your LXMF client and DM it.
`gateway --platform voice` turns the machine's microphone into a command front
end: an always-on **wake word** (openWakeWord), **speech-to-text**
(faster-whisper), and **text-to-speech** (Piper), all local — no cloud. A spoken
command is fed through the same gate/score/queue/dispatch pipeline as a typed or
command is fed through the same queue/dispatch pipeline as a typed or
messaged one, and every reply is spoken back. It is a normal gateway adapter, so
`needs_input` questions, repair offers, and approvals are spoken and answered by
voice too.
@@ -655,20 +788,34 @@ python -m semif_agent.cli gateway --platform voice
PortAudio has no volume control — use `alsamixer`/`amixer` (then
`sudo alsactl store`) to unmute and set the mic/speaker levels.
- **Models.** `gateway.voice.wake.model` is an openWakeWord model (default
`hey_mycroft`), `stt.model` a faster-whisper size (default `base.en`), and
`hey_computer`, spoken phrase "Hey Computer"), `stt.model` a faster-whisper
size (default `base.en`), and
`tts.voice` a Piper voice (default `en_US-lessac-medium`). Bootstrap downloads
the openWakeWord models into the venv's package dir (under `.runtime/venv`)
and the Piper voice into `.runtime/voice/tts`; the faster-whisper model lands
in the `.runtime/hf` cache.
the official openWakeWord models into the venv's package dir (under
`.runtime/venv`) and the Piper voice into `.runtime/voice/tts`; the
faster-whisper model lands in the `.runtime/hf` cache. openWakeWord ships no
"computer" model, so the default is a **pinned community model**
(openWakeWord-compatible, sha256-checked in `pins.json`) that
`scripts/voice-models.py` fetches into `.runtime/voice/wake`, where the
detector resolves it via `wake.model_dir`. Set `wake.model` to an official
name (e.g. `alexa`) or a path to switch. Because the community model's scores
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
official models score ~0.99 and use `0.5`).
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
the agent never transcribes itself (no barge-in yet). A short beep plays when
the wake word fires (`gateway.voice.cue`), so you know you're being heard; set
`cue.submit_frequency > 0` for a second beep once the utterance is
transcribed. After a reply, the next
utterance is accepted **without** the wake word for `follow_up_window_s`, so
answering a question is conversational. `max_speak_chars` truncates long
the agent never transcribes itself (no barge-in yet). The wake word is required
before every command and is held while the scheduler is still running the
current request, so a second command cannot start until the first reaches a
result. A short beep plays when
the wake word fires (`gateway.voice.cue`), so you know you're being heard; a
short multi-note "bling" (`cue.submit_notes`, each entry
`[frequency_hz, duration_ms]`, spaced by `cue.note_gap_ms`) plays once the
utterance is transcribed. (Set `cue.submit_notes` to `[]` and
`cue.submit_frequency > 0` for the older single submit beep.) After the wake
word, capture waits `listen_timeout_s` for the command to begin, so a pause before speaking
(e.g. while the cue beep plays) does not truncate it. `max_speak_chars`
truncates long
replies before speaking. `result_only` (default true for voice) speaks only the
skill's result line — queue/urgency bookkeeping is dropped and the
skill's result line — scheduler bookkeeping is dropped and the
`<skill>: ok —` wrapper is stripped — so the spoken output is the answer, not
the scheduler's internals; set it false to speak the full scheduler output.
There is no allowlist: the mic is local, so physical access is the
@@ -680,11 +827,14 @@ python -m semif_agent.cli gateway --platform voice
### Bridge services
`cli bridge` runs standalone bridges: each is a process that stands up a small,
token-guarded localhost HTTP API in front of one third-party system and owns its
own daemon/profile. Generated skill bodies call them like any HTTP service (base
URL from a config var), so they never speak a native protocol directly.
token-guarded localhost HTTP API in front of one third-party system (and, where
the system needs one, owns its own daemon/profile). A bridge is a deliberate
choice for a system that needs state (especially auth state), a native or heavy
protocol, or one sanitized surface — a skill may call a plain HTTP API directly.
When a bridge fronts a service, generated skill bodies call it like any HTTP
service (base URL from a config var) and never speak the native protocol.
The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own
The first bridge is **SimpleX** (`packs/simplex/bridge/simplex.py`), with its own
simplex-chat daemon separate from the gateway's. Its HTTP surface:
```
@@ -703,12 +853,14 @@ so they see messages that arrived while the bridge was down — unlike the live
`/inbox` receive buffer. Both are read-only: v7 has no mark-read command, so
acking is a client-side read receipt, not an API call.
`simplex_bridge_url` (top-level config) is what skills call; the bridge catalog
Skills call the forwarding bridge at the address derived from `bridges.simplex`
(`simplex_bridge_url`); the bridge catalog
is injected into every codegen prompt via `describe_bridges()`, so it is the
single source of bridge specifics. Adding a bridge = a class + a config block +
a `CATALOG` entry.
single source of bridge specifics. Adding a bridge = a pack that ships its
`bridge/<name>.py` + a config block; the core registry discovers it by convention.
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the shared, pack-less one: a
generic
```
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
@@ -719,10 +871,134 @@ text (e.g. extract an event title + description) over HTTP instead of speaking
the OpenAI-compatible protocol itself. It does not own the model connection:
`cli bridge` threads the scheduler's already-configured `llm` client into it, so
the endpoint/model/sampler live only in the top-level `llm` block; `bridges.llm`
carries just the local listener. Skills call it via `llm_bridge_url`
(+ optional `llm_bridge_token`); with no client it returns `502`, never a
fabricated reply. It starts in the same `semif-bridge.service` process as the
other enabled bridges.
carries just the local listener. Skills call it at the address derived from
`bridges.llm` (`llm_bridge_url`, + optional `llm_bridge_token`); with no client
it returns `502`, never a fabricated reply. It starts in the same
`semif-bridge.service` process as the other enabled bridges.
The **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py`) is the third: it
wraps the account's native protocols — WebDAV files, CalDAV calendar events and
tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a
body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is
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`; `NextcloudBridge.from_config`
also accepts the top-level `nextcloud_url` / `nextcloud_username` /
`nextcloud_app_password` / `nextcloud_default_calendar` as a fallback for a
hand-edited config, with a block value winning. Skills call it at the address
derived from `bridges.nextcloud` (`nextcloud_bridge_url`, + optional
`nextcloud_bridge_token`). Its HTTP surface:
```
GET /health
GET /user # account info (OCS)
GET /capabilities # server capabilities (OCS)
GET /files?path=<dir> # list a folder (WebDAV)
GET /files/stat?path=<path>
GET /files/read?path=<path> # text, or base64 for binary
GET /files/search?query=<text>&path=<dir>
POST /files/write {"path","content","encoding"?,"overwrite"?}
POST /files/mkdir | /files/delete | /files/move | /files/copy
GET /calendars # includes "default" (configured default name)
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT; recurrences expand with a window
POST /calendars/events | /calendars/events/update | /calendars/events/delete
GET /tasks?calendar=<name> # CalDAV VTODO
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
GET /addressbooks
GET /contacts?addressbook=<name>&query=<text> # CardDAV
POST /contacts | /contacts/update | /contacts/delete
GET /notes | /notes/get?id=<id> # Notes app (OCS)
POST /notes | /notes/update | /notes/delete
```
A missing connection is `503`; a real Nextcloud failure (transport, HTTP error,
or a bad reply) is `502` — never a fabricated success. Calendar and addressbook
defaults resolve from `bridges.nextcloud` when a request names none and the
account has several.
The **Outlook bridge** (`packs/outlook/bridge/outlook.py`) wraps the user's
Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail,
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
so it starts instantly in the same `semif-bridge` process. Authorization is the
OAuth2 **device code flow**: register an Entra ID public-client app, put its
`client_id` in `bridges.outlook`, and run `packs/outlook/scripts/outlook-auth.py` once — the
tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and
refreshed automatically. The bridge starts without a token; an unauthenticated
route returns `503` telling the operator to run that helper. Skills call it at the
address derived from `bridges.outlook` (`outlook_bridge_url`, + optional
`outlook_bridge_token`). Its HTTP surface:
```
GET /health
GET /user # the signed-in account
GET /mail/folders
GET /mail/messages?folder=<name|id>&count=<n>&search=<text>&unread=<bool>
GET /mail/messages/get?id=<id>
POST /mail/send {"to":[...],"cc"?,"subject"?,"body"?,"content_type"?}
POST /mail/draft {"to"?,"cc"?,"subject"?,"body"?,"content_type"?}
GET /calendars
GET /calendars/events?calendar=<name|id>&start=<iso>&end=<iso> # recurrences expand
POST /calendars/events | /calendars/events/update | /calendars/events/delete
GET /tasklists # Microsoft To Do
GET /tasks?list=<name|id>
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
GET /contacts?query=<text>&count=<n>
GET /files?path=<dir> # OneDrive
GET /files/read?path=<path> # text, or base64 for binary
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 `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.
The **browser bridge** (`packs/browser/bridge/browser.py`) is real browser
automation via **Playwright**: open a URL, read a page's text or links, take a
screenshot, and click/fill/press/select to complete a flow. It is the first
bridge with a heavy optional dependency, so it is **disabled by default** and
installed with `scripts/bootstrap.sh --browser` (Playwright + Chromium land under
`.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch).
If `playwright install` fails — notably on a host with an IPv6 address but no
global IPv6 route, where Playwright's downloader prefers IPv6 and hangs —
bootstrap falls back to `packs/browser/scripts/playwright-browsers.py`, which downloads the
same pinned artifacts over IPv4. To skip the managed download altogether, set
`bridges.browser.channel` (a Playwright channel such as `chrome`/`msedge`) or
`bridges.browser.executable_path` (a browser binary) to use an already-installed
browser.
Unlike the others it owns a browser and keeps a **persistent profile**
(`.runtime/browser/profile`) so a login you do once survives across calls and
restarts — the browser analog of the SimpleX bridge owning its own daemon
(`POST /reset` with `purge=true` wipes it). A dedicated event-loop thread runs
Playwright's async API and serializes whole operations, because the sync API is
bound to its creating thread and the bridge serves each request on a new one.
`check_requirements()` never blocks startup, so a host without Playwright still
runs every other bridge; a missing package/browser is a `503` install hint on the
call, and a real navigation/timeout/selector failure is a `502`. Skills call it
at the address derived from `bridges.browser` (`browser_bridge_url`, + optional
`browser_bridge_token`). Its HTTP surface:
```
GET /health
GET /state # current url + title
GET /content?format=text|html&max_chars=<n> # whole page's rendered text
GET /text?selector=<css> # text of matching elements
GET /links?query=<text>&limit=<n> # anchors (label + href)
GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool>
POST /goto {"url","wait_until"?,"timeout"?}
POST /click {"selector"?|"text"?,"index"?,"timeout"?}
POST /fill {"selector","value","submit"?,"timeout"?}
POST /press {"key","selector"?,"timeout"?}
POST /select {"selector","value"?|"label"?,"timeout"?}
POST /wait {"selector"?|"text"?,"timeout"?}
POST /back | /forward {"timeout"?}
POST /reset {"purge"?} # close; purge deletes the profile
```
Three `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`).
### Dream report
@@ -740,8 +1016,8 @@ rows.
A skill is one specific, single-purpose action reachable by category → skill
navigation. It is three things:
1. a **manifest** (navigable description — `name`, `category`, `description`,
plus optional `allowed_inputs`, `actions`, `cost_budget`, `decision_log_ref`);
1. a **registry entry** (navigable description — `name` + `description`,
authored by the small `llm` provider and recorded in `data/categories.json`);
2. a **code body** (a single `act`);
3. an **`INTEGRATION` declaration** (service / transport / config_vars) and a
flat **`CONTRACT`** (the operational values the runner must provide).
@@ -759,24 +1035,49 @@ 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** 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. Each pack lives in its **own repository**
(`pack.<name>`, listed in the `semif-packs` index repo); `scripts/bootstrap.sh` clones them into
the gitignored `packs/<name>/`, and `merge_packs` loads every enabled pack into
the tree at startup. Recorded config is written to the runtime store, so a pack
repo never holds secrets. `PACKGEN.md` is the authoritative contract for
authoring a new pack (and a new bridge to back one).
- `calendar.create_event` — create an event on Nextcloud CalDAV (the
authoritative worked example); resolves the target calendar with a SemIf
choice over the owned calendars (strong winner, else the configured default);
config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`,
`nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`,
`llm_bridge_token`).
- `calendar.next_event` — next upcoming event from Nextcloud CalDAV (recurring
events expanded server-side); config vars `nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`.
- `nextcloud.create_event` — create an event on the user's Nextcloud calendar
through the Nextcloud bridge (`GET /calendars`, `POST /calendars/events`);
resolves the target calendar with a SemIf choice over the owned calendars
(strong winner, else the configured default); config vars
`nextcloud_bridge_url`, `nextcloud_bridge_token`, plus the LLM bridge
(`llm_bridge_url`, `llm_bridge_token`).
- `nextcloud.next_event` — next upcoming event through the Nextcloud bridge
(`GET /calendars`, `GET /calendars/events`; recurring events expanded
server-side); config vars `nextcloud_bridge_url`, `nextcloud_bridge_token`.
- `nextcloud.create_task` — add a task to a Nextcloud task list through the
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
`llm_bridge_token`.
- `simplex.next_message` — read the next unread message via the forwarding
bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`,
`simplex_default_contact`.
- `simplex.send_message` — send a message to a contact resolved over the
bridge's contact list (a SemIf choice, defaulting to the configured contact);
config vars `simplex_bridge_url`, `simplex_bridge_token`,
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
`llm_bridge_token`) to write the text when the request states none.
- `simplex.connect_link` — show/create the forwarding bot's contact link.
- `calculator.calculate` — evaluate a bounded arithmetic request (two operands,
one operator) and speak the answer in words; the operator is a SemIf choice
over addition, subtraction, multiplication, division, exponents, squares,
cubes, square roots, cube roots, fractions, and percentages, and SemIf picks
the operands when the request writes more numbers than the operation needs
(pure local compute, no config).
- `skills.list_categories` — list the categories of skills the agent has
(pure local compute, no config; reads the read-only `ctx.catalog`, not the
housekeeping-only `ctx.admin`).
- `skills.list_skills` — list the skills inside a category named in the request
("list skills in nextcloud"), asking for one when it is missing and reporting
an unknown category honestly (pure local compute, no config).
---
@@ -804,13 +1105,13 @@ works.
## Roadmap / status
**Done.** Core loop, urgency queue, skill tree, real SemIf assessment, decision
**Done.** Core loop, FIFO queue, skill tree, real SemIf assessment, decision
logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` /
`create_skill` with the async authoring pipeline (elicitation → body → fidelity →
`create_skill` with the async authoring pipeline (spec → body → fidelity →
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).
+29 -14
View File
@@ -3,8 +3,11 @@
This file is the authoritative spec for the **testing** side of a skill. It is
fed verbatim (alongside the finished `skill.py`) to the model that produces the
test artifact. The runnable body contract lives in `CODEGEN.md`; this file is
deliberately separate so the body writer never embeds test data and the test
writer never worries about body semantics.
deliberately separate so the body writer never embeds test data and the test is
generated from the finished body rather than the other way around.
The pack that ships a skill as a committed starter — its manifest, categories,
bridge reference, and config schema — is the separate contract `PACKGEN.md`.
A finished skill leaf is a folder
`data/skills/<category>/<name>/` containing (among others) two artifacts:
@@ -26,6 +29,12 @@ integration, and the agent offers to fix the skill when that real run fails. A
test must never be "fixed" by simulating the action or by weakening an
assertion, and a simulated body is broken even if every test passes.
A skill's result is **bounded** to one speakable budget (it is read in a chat
message or spoken aloud; `chain.result_chars`, ~300 characters). Do not assert a
long/detailed payload: a skill whose real product is long or structured writes it
to the service or a file as a side effect and returns a short summary plus a
pointer. Order by the skill's own contract, not the fixture's size.
## contract.json
A **single JSON object**. Each key is the name of a variable the skill needs;
@@ -33,8 +42,9 @@ each value is a plain-language, semantic description of the expected values for
that variable (what it is, what good values look like).
The body declares this itself as a module-level `CONTRACT` constant (see
`CODEGEN.md`); `contract.json` is a persisted mirror of it, provided to the test
writer as context. The test writer does not author or change the contract.
`CODEGEN.md`); `contract.json` is a persisted mirror of it, and the same
contract object is handed to you as context. You do not author or change the
contract.
This contract exists for exactly two consumers:
@@ -77,12 +87,13 @@ A stdlib-only Python script that:
Assert the server actually received the expected request (method, path,
headers, body) where practical. The loopback address exists only in the test;
the body must read its endpoint from config.
- For a messaging skill (a body that talks to a bridge service), stand up a
loopback server implementing the bridge endpoints the body uses (the bridge
catalog injected into this prompt lists them) and assert the body built the
real requests. If the catalog names an auth header, set the fixture token in
the fixture config and assert the body sent that header. Never connect to a
real service daemon or a live bridge.
- For a body that talks to a bridge service (or any fixed HTTP API), stand up a
loopback server implementing the endpoints the body uses (the bridge catalog
injected into this prompt lists a bridge's; for a direct HTTP API, mirror the
routes the body calls) and assert the body built the real requests. If the
catalog names an auth header, set the fixture token in the fixture config and
assert the body sent that header. Never connect to a real service daemon or a
live bridge.
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
resolution, argument construction, and error paths (missing or misconfigured
values) without performing the real I/O.
@@ -99,10 +110,14 @@ A stdlib-only Python script that:
The test artifact is accepted only if:
1. `skill.test.py` parses as Python, imports only the stdlib and the agent
package, embeds its fixtures inline (no external files), is hermetic, and
runs to exit 0 when executed from the skill folder.
2. The test stays compatible with the body's `CONTRACT` (the same variable
1. `skill.test.py` parses as Python — the only static check — and runs to exit 0
when executed from the skill folder; on failure the captured output drives a
regeneration.
2. It imports only the stdlib and the agent package, embeds its fixtures inline
(no external files), and is hermetic (no external network, no real services).
These are required of every test but are **not** statically verified, so do
not rely on a checker to catch a violation.
3. The test stays compatible with the body's `CONTRACT` (the same variable
names the body reads from `ctx.config`).
Produce one artifact: `skill.test.py` (derived from `skill.py` plus its
+206 -67
View File
@@ -1,28 +1,62 @@
{
"_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json.",
"tau": 0.6,
"max_reentries": 3,
"creation_approval": false,
"query_recall_window": 30,
"new_skill_creation": "deny",
"verbosity": "result",
"chain": {
"result_chars": 300
},
"assess": {
"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 compares the winner's action to the request (phase navigate:intent, P(same) >= intent_tau) and a mismatch authors a new leaf. 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.",
"intent_tau": 0.6,
"category_tau": 0.75,
"action_tau": 0.5
"action_tau": 0.5,
"softmax_bypass_tau": 0.5
},
"queue": {
"max_size": 100
},
"queue": {"max_size": 100, "age_rate": 0.01},
"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.",
"provider": "semif",
"backend": "llamacpp",
"context_tokens": 4096,
"threads": 8
"threads": 8,
"gpu_layers": 0,
"gpu_device": null,
"gpu_split": 0,
"winnow": {
"base_url": "http://127.0.0.1:8091",
"model": "",
"context_tokens": 32768,
"api_key": "!secret engine_winnow_api_key",
"timeout": 120,
"retries": 0,
"user_agent": "semif-agent",
"extra_headers": {}
},
"ollama": {
"base_url": "http://127.0.0.1:11434",
"model": "",
"context_tokens": 16384,
"api_key": "!secret engine_ollama_api_key",
"timeout": 120,
"retries": 0,
"keep_alive": "",
"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) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama",
"base_url": "http://localhost:11434/v1",
"model": "",
"api_key": "",
"api_key_env": "",
"api_key": "!secret llm_api_key",
"user_agent": "",
"timeout": 600,
"stream": false,
@@ -33,15 +67,17 @@
"top_p": 0.9,
"presence_penalty": 0.0,
"frequency_penalty": 0.0,
"disable_thinking": true
"disable_thinking": true,
"semif": {
"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<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama",
"base_url": "http://localhost:11434/v1",
"model": "",
"api_key": "",
"api_key_env": "",
"api_key": "!secret codegen_api_key",
"user_agent": "",
"timeout": 3600,
"stream": true,
@@ -59,31 +95,27 @@
"presence_penalty": 0,
"frequency_penalty": 1,
"max_attempts": 3,
"elicitation": {
"_comment": "Ask the product owner implementation questions before the body is written: which service/account, how to connect, where the credential comes from, what success looks like. Every front end defers questions to the questions panel; the single-slot writer asks them one at a time and waits answer_timeout seconds for each (the clock resets on every answer submit, so the user only ever sees the next question after answering the current one; a timeout stops the sequence). wait_timeout is the separate, longer wait for the optional creation-approval gate. Questions never ask for operational data values (collected at first fire) or config-vs-input cadence (the config step owns that).",
"enabled": true,
"max_questions": 4,
"answer_timeout": 30,
"approval": {
"wait_timeout": 900
},
"fidelity": {
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle, bounded by max_attempts; a still-fake body is accepted but traced/badged, never a hard authoring failure.",
"enabled": true,
"max_attempts": 1
"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,
"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/<category>/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,
@@ -92,47 +124,23 @@
}
},
"skill_bodies": "data/skills",
"skill_seeds": "seeds",
"simplex_bridge_url": "http://127.0.0.1:5227",
"simplex_bridge_token": "",
"llm_bridge_url": "http://127.0.0.1:5229",
"llm_bridge_token": "",
"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 use the top-level `simplex_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
"enabled": 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 use the top-level `llm_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": ""
}
},
"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": {
"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": [],
@@ -141,10 +149,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,
@@ -157,10 +168,33 @@
"storage_path": "",
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8
"text_batch_delay": 0.8,
"result_only": true,
"voice": {
"enabled": false,
"reply_with_voice": true,
"max_speak_chars": 600,
"reply_bitrate": 24000,
"read": {
"enabled": true,
"chunk_chars": 300
},
"stt": {
"model": "base.en",
"device": "cpu",
"compute_type": "int8",
"language": "en"
},
"tts": {
"voice": "en_US-lessac-medium",
"voice_dir": "",
"speaker_id": 0,
"length_scale": 1.0,
"volume": 1.0
}
}
},
"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 (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); 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 each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: 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.",
"enabled": false,
"chat_id": "voice",
"display_name": "voice",
@@ -168,19 +202,33 @@
"reply_prefix": "",
"result_only": true,
"max_speak_chars": 600,
"follow_up_window_s": 5.0,
"read": {
"enabled": true,
"chunk_chars": 300
},
"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; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.",
"enabled": true,
"frequency": 880,
"duration_ms": 120,
"volume": 0.9,
"submit_frequency": 0,
"submit_duration_ms": 100
"submit_duration_ms": 100,
"submit_notes": [
[
1046.5,
70
],
[
1568.0,
90
]
],
"note_gap_ms": 20
},
"wake": {
"model": "hey_mycroft",
"threshold": 0.5,
"model": "hey_computer",
"threshold": 0.2,
"inference_framework": "onnx",
"model_dir": ""
},
@@ -204,16 +252,107 @@
"frame_ms": 80,
"capture_sample_rate": 0,
"output_sample_rate": 0,
"dc_removal": true
"dc_removal": true,
"read_timeout_s": 1.0,
"stall_timeout_s": 5.0
},
"vad": {
"silence_ms": 1000,
"silence_ms": 500,
"min_speech_ms": 120,
"max_utterance_s": 30,
"min_command_ms": 700,
"initial_silence_ms": 1500,
"aggressiveness": 2,
"energy_threshold": 200.0
},
"follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
}
}
},
"dashboard": {"port": 8765, "host": "127.0.0.1"}
}
"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 <key>'.",
"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
}
}
},
"packs": {
"essentials": {
"enabled": true
},
"gutendex": {
"enabled": true
}
}
}
+246
View File
@@ -0,0 +1,246 @@
# Training a custom Piper voice
The voice gateway speaks through **Piper** (`gateway.voice.tts.voice`). You can
replace the stock voice with one trained on your own recordings. This guide is
the end-to-end procedure; the tooling is:
- `scripts/voice-record.py` — record an LJSpeech dataset from a microphone.
- `scripts/voice-verify.py` — transcribe the takes with Whisper and flag the ones
to re-record.
- `scripts/voice-train.sh` — fine-tune + export a Piper voice on a GPU host.
- `pins.json` `voice` block — the pinned piper1-gpl commit and base checkpoint.
None of this runs as part of `scripts/bootstrap.sh`; training is a one-off,
hardware-specific job. The gateway needs **no code change** to use the result.
## The three hosts
| Role | What it needs |
|---|---|
| **Record** | a microphone + the optional voice stack (`scripts/bootstrap.sh --voice`) |
| **Train** | a CUDA/ROCm GPU + PyTorch |
| **Use** | the voice gateway host |
Only the training host needs PyTorch; the recording host only needs the voice
stack for `sounddevice`. Per-deployment host choices live in the gitignored
`local/` notes, not here.
## Important expectations
- **Piper cannot clone a voice from a clip.** It fine-tunes a new voice from a
recorded dataset, starting from an existing checkpoint. Budget real recording
time.
- **Data quality beats quantity.** A quiet room, one consistent mic and
distance, and a steady tone matter more than raw minutes. ~1 h gives a good
voice; ~15–30 min gives a usable but rougher one; below ~50 utterances is
barely worth it.
- **Training is an overnight job**, even for a small dataset (hours on the GPU).
## 1. Record
On the recording host, with the voice stack installed. Three modes:
```sh
# interactive (default): shows each prompt; Enter to record, then accept/redo/skip
.runtime/venv/bin/python scripts/voice-record.py --list-devices
.runtime/venv/bin/python scripts/voice-record.py
# hands-free, spoken: the recorder reads each sentence aloud, you repeat it
.runtime/venv/bin/python scripts/voice-record.py --speak-prompts
# hands-free, read-along: prints each line + beeps (no speech), you read it
.runtime/venv/bin/python scripts/voice-record.py --read-prompts
```
- Prompts default to `scripts/voice-prompts-en.txt` — the 720 public-domain
Harvard (IEEE) sentences, phonetically balanced and ideal for TTS. Override
with `--prompts FILE` (one sentence per line; `#` comments skipped).
- `--device`/`--output-device` default to the voice gateway's configured
`gateway.voice.audio.input_device`/`output_device` from `config.json`; set
them by PortAudio name substring or index.
- The dataset is written as `metadata.csv` + `wavs/NNNN.wav`, and **resumes**:
re-running skips prompts already recorded and prints `N of 720 prompt(s) to
record` up front, so a resume over a nearly-complete dataset is never mistaken
for a fresh run (`--overwrite` re-records everything).
- **Interactive**: a mic check runs first (reports RMS/peak/dBFS, warns on
clipping / too-quiet); `Enter` records, then `Enter` accept / `r` redo /
`p` play / `s` skip / `q` quit.
- **Hands-free** (`--speak-prompts` / `--read-prompts`): no keypresses. Each
prompt waits for you to speak (up to `--max-seconds`), records until you stop,
saves, and moves on. It stops after `--max-misses` consecutive silent prompts
(default 3). `--read-prompts` prints the line and beeps and needs no TTS voice.
- `Ctrl-C` stops and keeps what is saved.
Output is under the gitignored `.runtime/` tree by default. **Recordings are
biometric — never commit them.**
Tuning: `--max-seconds` (hard cap per take), `--silence-ms` (trailing silence
that ends a take), `--vad-threshold` (int16 RMS speech gate), `--read-timeout`
(seconds with no audio frame before a take is abandoned — guards a dropped
device), `--limit N`.
## 1b. Verify (Whisper fidelity check)
The recorder trusts you to accept each take, so a silent false start or a line
read with a word or two wrong slips in silently. Transcribe every take and
compare it to its prompt before training:
```sh
.runtime/venv/bin/python scripts/voice-verify.py --model small.en \
--json .runtime/voice-train/verify.json
```
- `--model` picks the faster-whisper size; `base.en` is the gateway default and
is cached, but `small.en` is noticeably more accurate (a one-time ~700 MB
download into `.runtime/hf`) and is the better choice here — it resolves most
of base's false positives.
- Each take is classified: `empty` (Whisper heard nothing — a silent/false-start
take), `mismatch` (word error rate above `--max-wer`, default 0.5), `review`
(between `--review-wer` 0.35 and `--max-wer` — worth a listen, because
Whisper's own spelling/number variants land here: "two plus seven" -> "2 plus
7", "junk yard" -> "junkyard"), and `ok`. Number words are normalized to
digits before comparison.
- The flagged lines print the prompt and the transcript side by side, so a
spelling/number variant (`review`) is obvious versus a real word swap.
- `--json FILE` writes the full report (every transcript + WER), `--limit N`
does a quick smoke test.
To re-record the flagged takes, mark them first — this moves their wavs into
`<dataset>/rejected/` and drops their metadata rows, so the recorder resumes and
re-records exactly those prompts:
```sh
# --prune-review also marks the 'review' band; drop it to only redo hard fails
.runtime/venv/bin/python scripts/voice-verify.py \
--from-json .runtime/voice-train/verify.json --prune --prune-review
.runtime/venv/bin/python scripts/voice-record.py --read-prompts # only the gaps
```
Nothing is deleted (the rejected wavs stay under `dataset/rejected/`), and
re-running the verifier after re-recording confirms the fixes. Recordings are
biometric — never commit them.
## 2. Train
Copy the dataset to the training host, then run the trainer there. It installs
everything under `.runtime/voice-train/` (gitignored) and fine-tunes from the
checkpoint pinned in `pins.json`.
```sh
rsync -av .runtime/voice-train/dataset <train-host>:'<checkout>/.runtime/voice-train/dataset'
# on the training host, from the checkout:
scripts/voice-train.sh --name en_US-myvoice-medium \
--dataset .runtime/voice-train/dataset \
--max-epochs 2000 --batch-size 16 --free-gpu
```
- `--name` becomes the `.onnx` basename and the `gateway.voice.tts.voice` value.
Use Piper's convention `<locale>-<name>-<quality>`, e.g. `en_US-myvoice-medium`.
- **`--free-gpu`** stops `winnow.service` and unloads ollama models first. On a
host that also serves the decision engine / codegen, the GPU must be free or
training OOMs (without the flag the script only warns).
- **Quality must match the checkpoint**: the pinned base is `medium` (22050 Hz).
A `high`/`low` checkpoint needs `--quality` and a matching `--checkpoint`.
- **torch must be a ROCm/CUDA build.** The script installs torch from
`--torch-index-url` (default `https://download.pytorch.org/whl/nightly/rocm7.1`,
matching this deployment's ROCm). If the device check reports
`cuda_available=False`, change the index for your GPU/ROCm version — this is
the one host-specific piece.
- Stages are skippable (`--skip-setup`, `--skip-train`, `--skip-export`) and
`--resume` continues from the newest run checkpoint.
The run writes checkpoints under `.runtime/voice-train/runs/` and exports:
- `.runtime/voice-train/out/<name>.onnx`
- `.runtime/voice-train/out/<name>.onnx.json`
Fine-tuning from the base checkpoint, ~1000–3000 epochs is the useful range;
watch `loss_disc_all` level off (tensorboard logs under `runs/`).
## 3. Deploy and verify
The gateway resolves `tts.voice` inside `.runtime/voice/tts/` automatically
(`cli._build_gateway_adapter` anchors `voice_dir`), so deploy is just two files:
```sh
rsync -av .runtime/voice-train/out/<name>.onnx .runtime/voice-train/out/<name>.onnx.json \
<gateway-host>:'<checkout>/.runtime/voice/tts/'
```
Then on the gateway host set:
```json
"gateway": { "voice": { "tts": { "voice": "<name>" } } }
```
The LXMF gateway's voice replies resolve a Piper voice the same way from
`.runtime/voice/tts/` (`cli._build_gateway_adapter` anchors
`gateway.lxmf.voice.tts.voice_dir` there too), so the same trained voice can back
both the microphone gateway and Sideband push-to-talk replies:
```json
"gateway": { "lxmf": { "voice": { "tts": { "voice": "<name>" } } } }
```
Restart the gateway and speak a reply. **Only a real spoken reply proves the
integration** — a generated test passing proves mechanics, not that the voice
loads and sounds right.
## Troubleshooting
- **`could not open input device` / silence**: `--list-devices`; on a host where
PortAudio hides a held device, pin by name substring. Another process may hold
the mic (`arecord -l` shows `Subdevices: 0/1`) — e.g. the running gateway
(`gateway --platform all`); stop it for the recording session.
- **No prompt audio** (`--speak-prompts`): the output is muted at the ALSA
level. Unmute with `alsamixer`, or `amixer -c <card> sset Master 100% unmute`
and set `Auto-Mute Mode Disabled` (it silences the speakers when the headphone
jack is sensed). PortAudio has no volume control, so this is the only knob.
- **Recorder hangs mid-session**: usually the audio device dropped (a USB
re-enumeration) and a blocking read stalled. `--read-timeout` (default 3 s)
now ends the take instead of hanging. Prefer a **direct USB port** over a hub,
and check `journalctl -k | grep 'USB disconnect'` for re-enumeration storms.
- **Training `cuda_available=False`**: wrong torch wheel for the GPU — set
`--torch-index-url` to a ROCm/CUDA build matching the host (e.g.
`https://download.pytorch.org/whl/cu124` on a CUDA cloud instance).
- **Training OOMs**: pass `--free-gpu`; lower `--batch-size` (16 → 8).
- **`Weights only load failed` / `Unsupported global: pathlib.PosixPath`**:
PyTorch ≥ 2.6 defaults `torch.load` to `weights_only=True` and Lightning passes
it explicitly, so the pinned base checkpoint's hyperparameters are rejected.
`scripts/voice-train.sh` handles this with a `sitecustomize.py` that
allowlists `PosixPath` on `PYTHONPATH` for the train/export commands; if you
run `piper.train` by hand, do the same.
- **`--ckpt_path` aborts with `does not accept option 'model.sample_bytes'`**:
the pinned older checkpoint's saved model hyperparameters predate the current
`VitsModel` signature, so `LightningCLI._parse_ckpt_path` fails. The script
fine-tunes with `--model.warmstart_ckpt` (non-strict weight copy) instead and
reserves `--ckpt_path` for `--resume`.
- **`ImportError: cannot import name 'espeakbridge'`**: the editable install
builds the CMake extension in its isolated env but does not expose it. Run the
documented dev build in the piper checkout:
`python setup.py build_ext --inplace` (install `scikit-build cmake ninja
cython` first). `scripts/voice-train.sh` does this automatically when the
import fails.
- **Training aborts at epoch 0 with `ModelCheckpoint(monitor='val_mos') could
not find the monitored key`**, or finishes having written **no checkpoints**:
piper's default callbacks monitor `val_mel` (from the validation split) and
`val_mos` (scored over the test split), and Lightning ≥ 2.5 raises rather than
skips when a monitor is missing. Do not zero those splits
(`--data.validation_split` / `--data.num_test_examples`) — leave piper's
defaults. `val_mos` also needs the UTMOS predictor, which downloads on first
use (`torch.hub`, ~392 MB); a host that cannot reach it will not log
`val_mos`.
- **Voice loads but sounds wrong**: too little/clipped data, or too many epochs
(artifacts). Re-record quieter/cleaner; stop training earlier.
- **`piper1-gpl` checkout fails to build**: it needs `espeak-ng`,
`build-essential`, `cmake`, `python3-dev` (the script apt-installs them) and a
compatible Python. Very new interpreters may need a dedicated venv or the
project's Docker image.
## Maintenance
The piper1-gpl commit and base checkpoint are pinned in `pins.json` (`voice`).
Bump them via git and rerun `scripts/voice-train.sh`; the checkpoint sha256 is
verified on download.
+2 -2
View File
@@ -1,4 +1,4 @@
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 687.344px; background-color: white;" viewBox="4 4 687.34375 3827.421875" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-coLine truncated
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 763.308px; background-color: white;" viewBox="4 4 763.308349609375 3864" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-coLine truncated
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
@@ -96,4 +96,4 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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") format("woff2-variations"); unicode-range: U+460-52F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; }
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,d09GMgABAAAAANo0ABQAAAABw5wAANnAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGoNJG+NQHJFiP01WQVKBBAZgP1NUQVSBYicuAIUuL3QRCAqClRSB7QQLhEwAMIPENgE2AiQDiRAEIAWNdgeLCAwHW+GrcUA2xSrj8Xqzqt7vcDOutoLdMgy1E/ncqmGr3EUHco+DocGCzf//OUmHDA24BYDSav30gpTm5oLukVWFEcnonETmsMyRwaxVlcU6uxC9iCZsnT5P+qBoOkFJiqiJxWuPNWT7PHCRw81p1qChF3rCbO9Tu7fKOEyVB/700RQcsJ+gQiqTRi2ocJv6bJMhDPbujiO3awaKVPgtloNHC3ypGDWXlJT8TCcDP38oPBpOaRPPvYUR27Ml25a6QKxwENkIP/a69v/FRGp+aQ7XI8XziaUuA2OXQYk21onIvMPT3P69d7HtlowxR4Zz4BwVR6VBW2SMlChRwmzEbMxGP1b9j1EBH3DbDdCcdsQEon7JRfwSB2JOgISEoFrXAasoq9ikuqrMWEV/62jp5u1E+1v/V5m3nf1UU7+qXlFXNUotNMcB/IgeADjNAt72urO3lVp2YBGuBJyZT+j874Adx5a4m6t4+H87sPv+xERJd6LbnJR0C9XSut7hn/pD3nP3/VCsEWY8IKVyL0BRbPrJwpkALvSfe/ntnpvXkl+oTdlum8K2LiSDUyiDU4xHZ6hWWmURJHAkUCRwVVYWcFc1qyW2TDDkPQCUy/ISPQnRMEiSLBlE0Gqe0tm/u7JkGT8STP/bEDVVzrq7D1ilTqbPpASCR+Q7gyzJwiWc/zr//9vnfT/qQEpcRgoKK0nFOCd9V1qjXj3ukTmFPIN8B77N7El80zWp+LXb3t1TsS//NOl0e2JW0WxECQkSbGAYYRgxQQcLGfht9f844fRGn+hkZjZuva6/iAQxMBsTRBRsREHF6MneytsxPPxzr75PAd4cWpYTG2vx7vJiXWpQLuaqqxWIIP5+vZN6z+wSQHMa4tInAyKJ2jcTVu8K4B8+8KK3zOXjz8vLJ5Xlz+HjSCVSiXwJj1SGHw/P8Litf+xFbrCNNqCNRMWLsjAaD9D+9+370Z3/t6YZVSNaYVRiW7sQhlniSXaD/OHe/f/fZnXfzKy9F1ZLCEQcizlJu1ZRoWs7NG3MNms+VvxW/SKW0O3gkbaIOKT2bATw8P314zePsj0WaBNdtzbq9qHwr2+WdqImlDDQcDFAy/9/nVarp5sfRxlU0LNA0Efe5WqKfrEorS/Z8vfzjzLDtsahQcfDZDugZAm7bRkqYCraPT1gU29Rrf/f1Pqo1OHnhP58tEPYhkiXIenWKz1JVSXLctvdbXdnTwjZT/L8keX+ObE5i0JEIQXClsFlNEQGF+Dl4ftl/SynppqQG7KjySNHOMjGYmT3m94a7j7eD3l2SKlrFSG5ybs/exAGhfBf8vOls7qqcD1ZpG6BE9AJTIf6MrarCN3Xdm+K4ST9KqFSooUwbiFBNwjcQ7JHSOBRANvYmO6mmRCzx5voWR+qSgKXhHCXJHDC3rWxe4Kne4OnZ0O0J3s25HDK8djHPe85Hue8IZ72eNv7nk/Lw7dT+/Ax0KgHQSCwG00HFnA3H+DAeFBP2vyqnhjGH/lozjGSQSYIN7ui9b9+zf6cltYss9yUmTjRGKMGERlFRGRpFhGQel8P/jcLct6XjYdtYYIMEkQk55662z9WGz3qTwstjyIPkSBBguRCkJy4vaGdnc/jzJYpEgh8JVkGJ7hgjOl9vPuzX4vW4mU7Tcdec3SooYmAcoqooH2tqqpRuuaVsQSDcJXd4+5b2vkEIIyYjJ9ALKFbg3j4V0IiBjhMSVkDDWfgzM6DK73tivj3ChMuUpSx4iSbJEWKLPnUyrJSUBWoBlTXQU29sUUrTLsZZpmd84RZ0LBgQ464UEAkhVjGxtwZRQ2Ap5AnU4A7QEiH9gBM03kwEfjwC8EHv/HFkRdVtbN3dij7fhjGo/a77UXHKGdJahYnLUK+oZaTHOSL+Y17Xc210EuD2hrrSXq6ddwlganOXxDxL+jo4YyGCJMEMNDCyQfu5D0WR0XULS2X5wNblsOK3d45+fGE5LBTAv8ksrMHZ3zBWWRnsvNivTPq1wXUkf5NAAVTjlVa9Q3PWVEqG93+ZHLWx6ZaW7Mc2F3Oxzn/meB3ozjohgY841JAsPBNvwkEcAAAhkEMttdvtuBDtwk8bDIILD6N2y8DJACAo3D/ziVNBpv952E5Nk7xf1JA2PpPfD+6HaVoj4fi4PXAXzUfSkAy+5a90g4ELCCwoXK/AAoqeRscEH0v7n9Je5UKAEC37rf078wEduYlCcFtrHe/NTjrZE2qUx07YQpL/oc7+5PrIZ9+F4l325zMp79clc0zAY+voqywiWUh2yzLXsfZbBoxRyNvtX28hmXaefIOPYAbgQfHccZvDhXmOob4ABxIAj+GzKw+Bjb/Tyj5mxJicnayeVr0cWl25PVE/yxriQaJzvSSb8RJ0cy/k1DUGN1uJ2tQF/OjeEKakSq7odyBz/5dlMzOfkkPhcGWkoBKi1YLam06Vnhnx7jggTTZgaUh6FCXqdVf2hh5nVDymiIKVpMiAerLjq0lXaZuAqEvdVoaO3NCV2bAuWgYe85HhIASPPzEnmCVkjCeYV4katjDNhiTzd0Ewhw6zbdKkY+0X7++r9v+fHDRvyzseajWZ0KWtAON8D9kxjHvU5u6lKgpDqN7yTi+AdFGw1chUh6l8yBNOU2OlFGOls4IQ9QFEGMB7HfciZvK79Qu7E7uGya9xMLCLocPPzMZwDHS3wh6MAsetcpIjZWUzUcG9PY4ijiBq5xW+oEH2ERousAe4edeSymw++e+zLm1Xnpm7yU3tl9JUTPXJUNtQArlCrMi5VpOMNQIlhbcOIaZJbhQz5oaG3AcxxCcoWyIOZl2zYLVpjVESR3+V2MMAjLpFDyBXA7//cBRHskTYrfSLwT0zOqslT5YPSGuTe6MJ2dZ26KOl/OYJTLrKi8yoZMknI8UtczGtbBjmXb4sRZlklAWq9Xc6Xs9zIfr3SiZtb+v984CfhjUTgOTGPSonhA2jK7bPbWY49LtVk23Q/TsZSxAhTvwqdUcPkFOSLnPVU840xOYY1cybYP2HN6LZ8wOWO6uFHlVWwMZvfQa7YrsaGzEUh+p7DOm8tUKUyBLM1KNmtTZhXlassZrqcwbgzrKGM5ZDVRzKNunGmVoRt0SUbngf9rwhwQXmua3iQqFBgxkVUqnXGceuslM+t38uVbGYXUK21R8bHZat2kux1l6XDPbzTbfPQ9uxk+8tNh7rPR7Yqs+T22j8++vYO/drljmsTvlGHt+x198OZjA2HvKG359XYdvaGTFkEowSRaQ2GMRDiF6amJ4Eoo0ZccYpIKkBpoGkhaaDoM+8hnASlijkJ0DkxOXC4kbWimkMngeeN6I5IOHULiwKYFwkZAoY5DGPkxUE8lEgTjJoPEEJkxRJpqMLUUmJOvBlg3JwZZLT2800qcYi5rYJMNMjvamqCA2ncwMAlURV60GUhsF6tSDGlAaD+jfX3IquJofzT1jOgt9i3RFlDrpEL4jbLzG2hvTVs46w9Z5F3Bd1D3Nq+D7B9+VaOG6a6Ruknqf1Ae4HjSpzzxleOYlrh3w9VdutSt/GYonD+i9GJJghGpajF6FcCIMRKiigk5BncJNRgQkRiVRUVZYA2hGmQKonnwIgC5K2MRgAAtMIlZKofjCsggqiMCIrEQQS8BEBIIl+D1ZbB6IdfcspBEggCFgTyHMIYQ+TAktq0VaoJ76UTOO7rCBDLIi5fDm4RMOe7YLkIPDsmknKm1MBdhABhk4kIFDlHp+zH7hpXSEaShQ4ECCgopVXvBvtYqiABwAXdcWU60PO4dW1eWhOmciUkInuPRbyZYMnB9OgtCHlXm6evEz1RnnxHPivJAlSU+G86lOta8Wy334Y79lzf6wBYPV3MMoPbo34SfCC5T7IOE4wlB1X4JBFMv4LPwm/H78pmIYO4g/Bj8wdz8Z1w7QuokoeDT5Q8jn4XNGvcVi9pLzE3DSV3A7cAO4Tln3gIuvBiSx7sqBWE4fQ39WG8nh69A7GiVWZplT8PArb4jehpagq1AmeB1Sp+3l+KNYThiyATRFLycFABkJGtAnX84izk7SdL6mKU7RsblqHaAaDWikpui6dkNU5rnjAcf2emgJlmE1OrEGLwze9vTyQom9s3/vYywsGgv22B9x5IhjTJ5YOb12pjm7cc55F5qLj25XXXMz7gzjnuI+8SB5Fs8VL/BSv/8NGDREh5krkFcIFilrNmzZsedAzhvdc3a3TAprp7fObeDqdrvdblT3f3bbufl+E4BoTAS81czMRESkxMTMzMzMfGNzkCr4IPhwwgxc3FsEAJiZKzMYAAAAeBamvWW367vZplUq9gSVmSSp72dTbxER4SofXDI07b0w+uLW3GOci7O4ePgEhCu4/xu3SVBnco+soMDgCCQKjcHiGv7ITwECkUSmUGl0RoYzq9jC5nB5fIFwiKZuiyPx+hEjRWkU1V+dTy4XVw1uHx8w+WF4PbzDpwnfxA8d/giIQAQJFiI0wi6H8FtEiGyiSrQYo40ZxrbY4RB3iUeCREmSY3w7THhMVEySyU3KLVWadBkyI0uyI0dyh7xT/nUUmEJFikPd/LXkUhplR5RLRVMZUyarHtW3msNazbpx1CsaGo1/brpiKU7n4xWgIP4o+U4ePZjydRr25K9KhImUIlWadBkyZatWc19jdz8U3lqP/XJRt6uuuemeB+NCsREhMo+TRkREWmRP5q5Zo0bjOKtKFH8M7IQBlH8Ei8ULine truncated

Before

Width:  |  Height:  |  Size: 322 KiB

After

Width:  |  Height:  |  Size: 364 KiB

+2 -2
View File
@@ -1,4 +1,4 @@
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 1408.24px; background-color: white;" viewBox="4 4 1408.2369384765625 5994.984375" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"Line truncated
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 1725.9px; background-color: white;" viewBox="4 4 1725.9010009765625 6951.078125" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"]Line truncated
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
@@ -96,4 +96,4 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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") format("woff2-variations"); unicode-range: U+460-52F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; }
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 355 KiB

+107 -76
View File
@@ -2,13 +2,15 @@
How one input travels through the agent. Every diamond marked **SemIf** is a
real decision-engine call that is logged as a training row; the LLM only ever
*generates* (skill drafts, bodies, questions). There is no up-front
handle/ignore gate — every input is scored and dispatched.
*generates* (skill drafts, bodies, tests). There is no up-front
handle/ignore gate — every input is dispatched, and an explicit housekeeping
command is routed deterministically before navigation.
The diagram is split in two: the **main pipeline** (intake → navigation → run →
output) and the **authoring pipeline** (what happens when navigation decides a
category or skill does not exist yet). Authoring is asynchronous: the main gate
is freed immediately and the original request is re-queued once the body lands.
The diagram is split in two: the **main pipeline** (intake → dispatch →
navigation → run → output) and the **authoring pipeline** (what happens when
navigation decides a category or skill does not exist yet). Authoring is
asynchronous: the main gate is freed immediately and the original request is
re-queued once the body lands.
Rendered SVG: [flow-main.svg](flow-main.svg) · [flow-authoring.svg](flow-authoring.svg)
@@ -18,92 +20,99 @@ Rendered SVG: [flow-main.svg](flow-main.svg) · [flow-authoring.svg](flow-author
```mermaid
flowchart TD
IN["Input<br/>REPL text · gateway DM · dashboard submit"] --> SUB["Scheduler.submit_request()<br/>create Request, trace 'submit'"]
IN["Input<br/>REPL text · gateway DM (SimpleX · LXMF · voice) · dashboard submit"] --> SUB["Scheduler.submit_request()<br/>create Request, trace 'submit'"]
SUB --> BUSY{"current process?"}
%% ---------- idle path ----------
BUSY -- "idle" --> SCORE["SemIf score<br/>phase 'score'<br/>How urgent is this?"]
SCORE --> DISPATCH
BUSY -- "idle" --> META{"parse_meta_command()<br/>explicit housekeeping command?"}
%% ---------- busy path ----------
BUSY -- "busy" --> INTERRUPT["SemIf choice<br/>phase 'choice'<br/>may this interrupt?"]
INTERRUPT -- "defer" --> SCORE2["SemIf score<br/>phase 'score'"]
SCORE2 --> PUSH["UrgencyQueue.push<br/>max-heap: weight desc, FIFO seq<br/>age pulls low items toward 1.0"]
BUSY -- "busy" --> PUSH["RequestQueue.push<br/>FIFO, bounded"]
PUSH -- "full" --> REJECT["Output: rejected<br/>'queue is full'"]
PUSH -- "ok" --> QUEUED["Output: queued<br/>urgency label + weight"]
QUEUED -. "run_queue when idle" .-> DISPATCH
PUSH -- "ok" --> QUEUED["Output: queued"]
QUEUED -. "run_queue when idle" .-> META
INTERRUPT -- "interrupt" --> PREEMPT["Abandon pending run<br/>requeue previous at its weight<br/>trace 'preempted'"]
PREEMPT --> DISPATCH["Scheduler._dispatch()"]
%% ---------- dispatch ----------
META -- "yes" --> HK["run housekeeping leaf<br/>trace 'meta_command'<br/>deterministic; skips navigation"]
HK --> RUN["_run_skill()<br/>execute the leaf"]
META -- "no" --> NAV["navigate()<br/>descend tree, one SemIf choice per level"]
%% ---------- navigation ----------
DISPATCH --> NAV["navigate()<br/>descend tree, one SemIf choice per level"]
%% ---------- actionability guard (top of navigation) ----------
NAV --> ACTG{"SemIf choice<br/>phase 'navigate:actionability'<br/>P non_action >= action_tau?"}
ACTG -- "non-action" --> CANNEDLEAF["_navigate_canned<br/>phase 'navigate:response'<br/>closed canned reply tree"]
CANNEDLEAF --> RUN
ACTG -- "request" --> CAT["SemIf choice<br/>phase 'navigate:category'<br/>options = real categories +<br/>descriptions + create_category"]
NAV --> CAT["SemIf choice<br/>phase 'navigate:category'<br/>options = categories + descriptions<br/>+ create_category"]
CAT --> CATWIN{"winner =<br/>create_category<br/>or tree empty?"}
%% ---------- category selection ----------
CAT --> CATWIN{"create_category win<br/>or no categories?"}
CATWIN -- "yes" --> CREATECAT["CreateCategory"]
CATWIN -- "no" --> CATFIT["SemIf choice<br/>phase 'navigate:category_scope'<br/>P covers >= category_tau?"]
CATWIN -- "no" --> CATCONF{"winner prob >=<br/>softmax_bypass_tau?"}
CATCONF -- "yes (decisive)" --> HASSKILLS
CATCONF -- "no (unsure)" --> CATFIT["SemIf choice<br/>phase 'navigate:category_scope'<br/>P covers >= category_tau?"]
CATFIT -- "rejected" --> CREATECAT
CATFIT -- "covers" --> CANNED{"category in<br/>CANNED_CATEGORIES?"}
CATFIT -- "covers" --> HASSKILLS
CANNED -- "yes (response)" --> CANNEDLEAF["_navigate_canned<br/>phase 'navigate:response'<br/>closed canned reply tree"]
CANNEDLEAF --> RUN["_run_skill()"]
CANNED -- "no" --> HASSKILLS{"skills in<br/>category?"}
%% ---------- leaf selection ----------
HASSKILLS{"skills in category?"}
HASSKILLS -- "none" --> CREATESKILL["CreateSkill"]
HASSKILLS -- "one" --> SOLE["sole skill<br/>softmax skipped"]
HASSKILLS -- "many" --> LEAF["SemIf choice<br/>phase 'navigate:leaf'<br/>options = existing skills only"]
LEAF --> PICK["picked skill"]
SOLE --> PICK
PICK --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>P same >= intent_tau?<br/>sole reuse-vs-create guard"]
%% ---------- reuse vs create ----------
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
HARD -- "yes" --> RUN
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>same / part / different?<br/>P same+part >= intent_tau"]
INTENT -- "same / part" --> RUN
INTENT -- "different" --> CREATESKILL
INTENT -- "same" --> RUN
CREATECAT --> AUTHORING(["authoring pipeline<br/>see below"])
CREATESKILL --> AUTHORING
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
LOCK -- "locked" --> BLOCKED["Output: error<br/>'new-skill creation is locked'"]
LOCK -- "open" --> BODYQ{"meta<br/>awaiting_skill_body?"}
BODYQ -- "yes" --> PENDINGW["Output: error<br/>'body still being written;<br/>restart category.skill'"]
BODYQ -- "no" --> AUTHORING(["authoring pipeline<br/>see below"])
CREATECAT --> AUTHORING
%% ---------- run ----------
RUN --> WRITING{"leaf still<br/>writing?"}
WRITING -- "yes" --> PENDING["Output: error<br/>'body still being written'"]
WRITING -- "no (noop stub)" --> NOOP["Output: error<br/>'no body yet; restart <cat> <skill>'"]
WRITING -- "runnable" --> RESOLVE["SkillRunner.run()<br/>resolve tiered config<br/>global -> category -> skill"]
RUN --> WRITING{"leaf status?"}
WRITING -- "writing" --> PENDING["Output: error<br/>'body still being written'"]
WRITING -- "stub (no body)" --> NOOP["Output: error<br/>'no body yet;<br/>restart category.skill'"]
WRITING -- "ready" --> RESOLVE["SkillRunner.run()<br/>resolve tiered config<br/>global -> category -> skill"]
RESOLVE --> UNRES{"contract variable<br/>unresolved?"}
UNRES -- "yes" --> PAUSE1["Output: needs_input<br/>pre_act pause<br/>ask one variable"]
PAUSE1 -. "answer() bypasses gate" .-> RECORD["SemIf choice<br/>phase 'config:record'<br/>record as config vs ask each fire"]
PAUSE1 -. "answer() bypasses queue" .-> RECORD["SemIf choice<br/>phase 'config:record'<br/>record as config vs ask each fire"]
RECORD --> RESOLVE
UNRES -- "no" --> ACT["skill.act(ctx, request)<br/>REAL action via stdlib transport<br/>values from ctx.config"]
ACT --> ACTNI{"act asks<br/>for input?"}
ACT --> ACTNI{"act asks for input?"}
ACTNI -- "yes" --> PAUSE2["Output: needs_input<br/>act pause"]
PAUSE2 -. "answer()" .-> ACT
ACTNI -- "no" --> ASSESS
%% ---------- assessment ----------
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>P success >= tau?"] --> OK{"success?"}
OK -- "yes" --> SUMMARY
OK -- "no" --> REQ["SemIf choice<br/>phase 'assess:requeue'<br/>complete vs retry"]
REQ -- "retry" --> REQUEUE["requeue original request<br/>bounded by max_reentries"]
REQUEUE -.-> PUSH
REQ -- "complete" --> REPAIR
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>additional work to do?<br/>a definitive empty result counts as done"] --> OK{"outcome?"}
OK -- "done" --> SUMMARY
OK -- "continue" --> CHAIN["route the logical next step<br/>re-dispatch with the run ledger<br/>bounded by max_reentries + monotonic guard"]
CHAIN -.-> PUSH
OK -- "failed" --> REPAIR
SUMMARY["deterministic summary<br/>category.name: ok/failed - action_log"] --> OUT1["Output: ran<br/>REPL print · gateway reply · dashboard trace"]
SUMMARY["deterministic summary<br/>category.name: ok/failed - action_log"] --> OUT1["Output: ran<br/>SchedulerReply (run_id, skill_ref, result)<br/>REPL · gateway reply · dashboard trace"]
REPAIR["SemIf choice<br/>phase 'repair:choice'<br/>retry / repair_skill / ask_user / no_repair"] --> REPAIROUT["Output: repair offer<br/>surfaced in REPL/dashboard/gateway"]
REPAIROUT -. "user confirms" .-> AUTHORING
%% ---------- canned shortcut ----------
RUN -. "canned category skips assess" .-> SUMMARY
ACT -. "act raises" .-> REPAIR
RUN -. "canned / deterministic category skips assess" .-> SUMMARY
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
classDef output fill:#fce8e6,stroke:#d93025;
classDef author fill:#e6f4ea,stroke:#34a853;
class SCORE,SCORE2,INTERRUPT,CAT,CATFIT,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill;
class REJECT,QUEUED,PENDING,NOOP,PAUSE1,PAUSE2,OUT1,REPAIROUT output;
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REPAIR,RECORD semfill;
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT,CHAIN output;
class CREATECAT,CREATESKILL,AUTHORING author;
```
@@ -111,37 +120,40 @@ flowchart TD
## Authoring pipeline (create / repair)
Entered from `CreateCategory`, `CreateSkill`, or a confirmed repair. Runs in
background single-slot workers so the main gate stays free.
Entered from `CreateCategory`, `CreateSkill`, or a confirmed repair / regen /
restart. Runs in background single-slot workers so the main gate stays free.
Only a *create* asks the small `llm` model for a title + description; a
repair/regen/restart reuses the existing stub and goes straight to the codegen
worker.
```mermaid
flowchart TD
START(["CreateCategory / CreateSkill / repair_skill"]) --> DRAFT["single-slot llm worker<br/>DraftAuthor queue"]
START(["CreateCategory / CreateSkill"]) --> DRAFT["single-slot llm worker<br/>DraftAuthor queue"]
DIRECT(["repair_skill / regen_skill / restart_skill"]) --> WRITE
DRAFT --> GEN{"category<br/>or skill?"}
DRAFT --> GEN{"category or skill?"}
GEN -- "category" --> GC["generate_category()<br/>title + description"]
GEN -- "skill" --> GS["generate_skill()<br/>title + description"]
GEN -- "skill" --> GS["generate_skill_spec()<br/>title + description +<br/>de-identified goal +<br/>generic service/transport"]
GC --> APPROVE
GS --> APPROVE
APPROVE{"creation_approval<br/>on?"}
APPROVE -- "no / already approved" --> REGISTER
APPROVE -- "yes" --> PROMPT["Output: approval prompt<br/>REPL / dashboard / gateway<br/>deny or timeout aborts"]
APPROVE{"new-skill mode<br/>allow / deny / ask<br/>(global default, per-category override)"}
APPROVE -- "allow" --> REGISTER
APPROVE -- "deny" --> ABORT2["Output: creation denied<br/>nothing registered, not re-dispatched"]
APPROVE -- "ask (already approved)" --> REGISTER
APPROVE -- "ask" --> PROMPT["Output: approval prompt<br/>REPL / dashboard / gateway<br/>deny or timeout aborts"]
PROMPT -- "approved" --> REGISTER
PROMPT -- "denied / timeout" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
PROMPT -- "denied / timeout / no front end" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
REGISTER["register stub in registry + tree<br/>trace 'category_created' / 'skill_created'"]
REGISTER["register stub in registry + tree<br/>seed category config (new_skill_creation)<br/>trace 'category_created' / 'skill_created'"]
REGISTER -- "category" --> CHAIN["chain into skill job<br/>approved=true"]
CHAIN --> DRAFT
REGISTER -- "skill" --> WRITE["single-slot codegen worker<br/>SkillWrite queue<br/>leaf.writing = true"]
REGISTER -- "skill" --> WRITE["single-slot codegen worker<br/>SkillWrite queue<br/>leaf.writing = true, trace 'skill_writing'"]
WRITE --> ELICIT["generate_elicitation()<br/>implementation questions +<br/>integration hint"]
ELICIT --> QS["Output: questions<br/>posted one at a time<br/>answer_timeout per question"]
QS -- "answers" --> BODY
QS -- "timeout" --> BODY
WRITE --> BODY
BODY["generate_skill_body()<br/>or regenerate_skill_body() for repair<br/>CODEGEN.md + bridge catalog<br/>declares INTEGRATION + flat CONTRACT"] --> FID["SemIf choice<br/>phase 'authoring:fidelity'<br/>accept / reconsider<br/>+ static integration_findings"]
FID -- "reconsider" --> BODY
BODY["generate_skill_body()<br/>de-identified spec only: goal + service/transport<br/>or regenerate_skill_body() for<br/>repair / fidelity / test / manual regen<br/>CODEGEN.md + bridge catalog<br/>declares INTEGRATION + flat CONTRACT"] --> FID["SemIf choice<br/>phase 'authoring:fidelity'<br/>accept / reconsider<br/>+ static integration_findings"]
FID -- "reconsider (once)" --> BODY
FID -- "accept" --> CONTRACT["parse_contract()<br/>read body's CONTRACT constant"]
CONTRACT --> CFG["SemIf choice per variable<br/>phase 'config:search'<br/>global -> category -> skill"]
@@ -149,20 +161,22 @@ flowchart TD
TEST --> RUNTEST["run_skill_test()<br/>subprocess in skill folder"]
RUNTEST -- "fail" --> REGEN["SemIf choice<br/>phase 'codegen_regen'<br/>regenerate code / test<br/>bounded by test_max_attempts"]
REGEN --> BODY
RUNTEST -- "pass" --> MAT["materialize_skill()<br/>write body + contract to data/skills/<br/>hot-merge into tree"]
RUNTEST -- "pass" --> MAT["materialize_skill()<br/>write body + contract to data/skills/<br/>hot-merge into tree, trace 'skill_ready'"]
MAT --> REQ["requeue original request<br/>meta awaiting_skill_body<br/>trace 'skill_requeued'"] --> BACK(["back to main pipeline<br/>re-runs navigation onto new leaf"])
FAIL["Output: skill_write_failed<br/>leaf stays a restartable stub<br/>restart <cat> <skill>"]
FAIL["Output: skill_write_failed<br/>leaf stays a restartable stub<br/>restart category.skill"]
BODY -. "CodegenError / ValueError" .-> FAIL
RUNTEST -. "budget exhausted" .-> FAIL
CANCEL["cancel_build meta skill<br/>(housekeeping / CLI / dashboard)"] -. "cancel queued or in-flight write" .-> CANCELLED["Output: build cancelled<br/>discard output, delete half-built leaf"]
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
classDef output fill:#fce8e6,stroke:#d93025;
classDef author fill:#e6f4ea,stroke:#34a853;
class FID,CFG,REGEN semfill;
class PROMPT,ABORT,QS,FAIL output;
class START,BACK,MAT,REQ author;
class PROMPT,ABORT,ABORT2,FAIL,CANCELLED output;
class START,DIRECT,BACK,MAT,REQ author;
```
---
@@ -171,16 +185,17 @@ flowchart TD
| Stage | Decision (SemIf) | Phase logged | Output |
| --- | --- | --- | --- |
| Intake, idle | urgency | `score` | weight → dispatch |
| Intake, busy | interrupt? | `choice` | preempt or queue |
| Intake, idle | — (no decision) | — | dispatch immediately |
| Intake, busy | — (no decision) | — | FIFO queue (arrival order) |
| Meta command | — (no decision) | — | route to housekeeping leaf (`meta_command`) |
| Actionability | request or not? | `navigate:actionability` | canned reply / category softmax |
| Category | which category | `navigate:category` | category / create |
| Category scope | does it cover? | `navigate:category_scope` | descend / create |
| Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) |
| Canned | which reply | `navigate:response` | canned line |
| Leaf | which skill | `navigate:leaf` | skill |
| Intent guard | same action? | `navigate:intent` | run / create |
| Intent guard | same / part / different? | `navigate:intent` | run / create (never bypassed) |
| Config record | record or ask? | `config:record` | persisted / per-fire |
| Outcome | did it succeed? | `assess:outcome` | ok / failed |
| Requeue | complete or retry? | `assess:requeue` | done / requeue |
| Outcome | additional work? | `assess:outcome` | done / continue / failed |
| Repair | how to recover? | `repair:choice` | offer |
| Fidelity | real action? | `authoring:fidelity` | accept / rewrite |
| Config search | where is the value? | `config:search` | auto-populate |
@@ -189,3 +204,19 @@ flowchart TD
**The three terminal outputs** are: a run summary (`category.skill: ok/failed — …`),
a question the run is waiting on (`needs_input`), or an offer to fix/learn
(`repair_offer`) / an authoring acknowledgement for a brand-new capability.
**Navigation is two-stage with permissive guards.** The actionability guard runs
first and decides whether the input is an actionable request at all; only
non-action input reaches the closed `response` tree, so a request is never
canned. The category softmax then offers the real categories (never `response`)
plus `create_category`, and the leaf softmax offers only the existing skills —
the reuse-vs-create decision is the intent guard. A **category** softmax winner
at or above `softmax_bypass_tau` (default 0.5) is already decisive, so its scope
confirm is skipped; the **leaf** intent guard is never bypassed (the leaf softmax
has no create option, so a confident winner is only the closest existing skill,
never a match) — it always runs and can reject into create.
New-skill creation is gated deterministically by the tri-state
`new_skill_creation` mode — global default `deny` (opt in with `allow`, or
`ask` for approval-gated authoring) with a
per-category override in `data/skills/<category>/config.json`; the
`housekeeping` and `response` categories are always `deny` in code.
+28 -4
View File
@@ -1,16 +1,40 @@
{
"_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, and the simplex-chat binary. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run. They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.",
"_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, the simplex-chat binary, and the voice-training toolchain/checkpoint. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run (the voice refs by `scripts/voice-train.sh`). They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.",
"engine": {
"semif_repo": "https://github.com/TheoLeeCJ/SemIf.git",
"semif_ref": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37",
"semif_ref": "23cf1f39fc9534fe81437200959b6dfc7106e45a",
"gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
"gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983",
"source": "Qwen/Qwen3.5-4B",
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
},
"simplex_chat": {
"_comment": "Per-arch daemon binaries; bootstrap selects by `uname -m` (x86_64 | aarch64, arm64 normalized to aarch64). The pinned version is the same for every arch.",
"version": "v7.0.3",
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
"assets": {
"x86_64": {
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
},
"aarch64": {
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-aarch64",
"sha256": "2d2e62351f11bc51ae659618584722b38ea5a6796b806c9a388ee6e3124c90ac"
}
}
},
"voice": {
"_comment": "Piper TTS voice-training refs used by scripts/voice-train.sh (optional, off-bootstrap): the piper1-gpl training toolchain commit and the medium base checkpoint it fine-tunes from. See docs/VOICE-TRAIN.md.",
"piper_train_repo": "https://github.com/OHF-Voice/piper1-gpl.git",
"piper_train_ref": "efffbfb226bfb511ebbcf55d0cecd8b35a89743d",
"base_checkpoint_url": "https://huggingface.co/datasets/rhasspy/piper-checkpoints/resolve/main/en/en_US/lessac/medium/epoch=2164-step=1355540.ckpt",
"base_checkpoint_sha256": "ab7e5b8dab40f834b7cc58ae4ad7b7009c954b901e4ddbb784bbe11ce379a1cd"
},
"wake_word": {
"_comment": "openWakeWord-compatible wake-word model refs fetched by scripts/voice-models.py into .runtime/voice/wake (deployment-independent, code-owned like the other pins). openWakeWord ships no 'computer' model, so this community-trained ONNX (Apache-2.0, same mel/embedding feature models) is pinned by sha256. 'phrase' is the spoken wake phrase.",
"hey_computer": {
"url": "https://huggingface.co/Soulcreek2/speechkit-wakeword-models/resolve/main/hey_computer.onnx",
"sha256": "3acbd9ffff04beba2d16ebdfd0d4c734d65fecdd22446f25f4d0afa6e5d7606b",
"phrase": "Hey Computer"
}
}
}
+15
View File
@@ -0,0 +1,15 @@
# Codec2 voice-message decoding (optional).
#
# Sideband's non-HQ push-to-talk messages carry raw Codec2 frames
# (`LXMF.AM_CODEC2_*`); decoding them needs the `pycodec2` bindings, which
# compile against the system `libcodec2` (Debian/Ubuntu: `libcodec2-dev`). Only
# needed for `gateway.lxmf.voice` when the sender uses non-HQ PTT — HQ Opus
# works with `requirements/transcribe.txt` alone. Lazy-imported by
# semif_agent/voice_transport.py, so the core stays stdlib-only; a missing
# decoder is reported per-message, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the plan
# installs it best-effort), or manually:
# apt-get install -y libcodec2-dev
# .runtime/venv/bin/pip install -r requirements/codec2.txt
pycodec2==4.1.1
+9
View File
@@ -0,0 +1,9 @@
# Core agent deps (the agent itself is stdlib-only; this is the test runner).
#
# Every host installs this. The decision engine and messaging transports are
# separate, optional files (engine.txt, transports.txt) so a host installs only
# what its answers require. The voice stack (voice.txt) is hardware-dependent,
# and the browser stack ships WITH its pack (packs/browser/requirements.txt) —
# bootstrap installs each selected pack's own requirements.txt.
# `staging.txt` includes the repo-level files for a full provision.
pytest
+18
View File
@@ -0,0 +1,18 @@
# Local decision-engine deps (SemIf / llama.cpp, CPU path).
#
# Only needed on a host whose `engine.provider` is the local SemIf GGUF. A host
# pointed at a remote Winnow decision server (engine.provider == "winnow")
# installs neither this file nor the SemIf engine clone / GGUF / tokenizer.
#
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
# cp314 wheel (source build fails). So semif-phase1 is installed with
# `--no-deps` and exactly this set is brought in instead. The pins match the
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
# declared version) so the pip resolver stays quiet about it.
numpy==2.3.5
transformers==5.17.0
tokenizers==0.23.2
huggingface-hub==1.31.0
llama-cpp-python==0.3.35
+16 -22
View File
@@ -1,23 +1,17 @@
# Staging-machine engine deps (CPU llama.cpp path).
# Full provision: every repo-level dependency this checkout can need, for a host
# that runs the local decision engine and all messaging transports. This is the
# union of the per-concern files below; a `scripts/bootstrap.sh` run installs
# only the subset its answers require, so prefer those files (engine.txt,
# transports.txt) when provisioning by hand.
#
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
# cp314 wheel (source build fails). So semif-phase1 is installed with
# `--no-deps` and exactly this set is brought in instead. The pins match the
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
# declared version) so the pip resolver stays quiet about it.
numpy==2.3.5
transformers==5.17.0
tokenizers==0.23.2
huggingface-hub==1.31.0
llama-cpp-python==0.3.35
pytest
# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the
# gateway refuses to start without it. Not needed by the decision engine.
websockets==15.0.1
# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway
# refuses to start without it. Runs in-process — there is no daemon binary.
# rns pulls cryptography + pyserial transitively (resolved by pip).
lxmf==1.2.0
rns==1.5.7
# Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
# hardware/optional. Voice is a repo file installed with
# `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are
# installed by bootstrap when that pack is selected. transcribe.txt
# (faster-whisper only, for LXMF Sideband voice messages), tts.txt (piper-tts +
# PyAV, for LXMF voice replies) and codec2.txt (pycodec2, for non-HQ Codec2 PTT)
# are likewise optional and installed by bootstrap when `gateway.lxmf.voice` is
# enabled.
-r core.txt
-r engine.txt
-r transports.txt
+20
View File
@@ -0,0 +1,20 @@
# Voice-message transcription deps (optional).
#
# Only needed on a host whose LXMF gateway transcribes Sideband push-to-talk
# voice messages (`gateway.lxmf.voice.enabled`) but that does NOT run the voice
# gateway — `requirements/voice.txt` is hardware-dependent (PortAudio mic +
# speaker, wake word, TTS) and none of that is required here. faster-whisper
# decodes the Opus/OGG container itself (its bundled PyAV/ffmpeg) and
# transcribes, and is lazy-imported by semif_agent/voice_transport.py, so the
# core stays stdlib-only on every other host.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/transcribe.txt
faster-whisper==1.2.1
# PyAV 19.0.0 (2026-09-29) REMOVED the `metadata_errors` argument to av.open(),
# which faster-whisper 1.2.1 (the latest release) still passes — so any voice
# message fails to decode with `TypeError: open() got an unexpected keyword
# argument 'metadata_errors'`. faster-whisper's git master handles both, but it
# is unreleased; pin PyAV below 19 until a release ships the fix.
av<19
+13
View File
@@ -0,0 +1,13 @@
# Messaging transport deps (SimpleX + LXMF gateways/bridges).
#
# Only needed on a host that enables the SimpleX gateway or bridge (which uses
# `websockets` against its simplex-chat daemon) or the LXMF gateway (in-process
# `lxmf`/`rns`). Both are lazy-imported, so a host without them still runs every
# other front end; the gateway refuses to start with an install hint.
#
# `websockets` is shared by the command gateway and the forwarding bridge (the
# neutral `semif_agent/simplex_ws.py`). `lxmf` pulls `rns` (Reticulum) and
# cryptography transitively; both are pinned so the resolver stays quiet.
websockets==15.0.1
lxmf==1.2.0
rns==1.5.7
+22
View File
@@ -0,0 +1,22 @@
# Voice-reply (text-to-speech) deps for the LXMF gateway (optional).
#
# When the LXMF gateway handles Sideband push-to-talk voice messages
# (`gateway.lxmf.voice.enabled`) and is configured to reply with voice
# (`gateway.lxmf.voice.reply_with_voice`, the default), it synthesizes the reply
# with Piper and encodes it to the Opus/OGG container Sideband's HQ push-to-talk
# uses (`LXMF.AM_OPUS_OGG`). That needs piper-tts (text-to-speech) and PyAV
# (libopus encoding) — NOT the hardware voice stack in `requirements/voice.txt`
# (no microphone, wake word, or speaker) and NOT transcription
# (`requirements/transcribe.txt`, which already pulls PyAV for decoding).
# Lazy-imported by semif_agent/voice_transport.py, so the core stays stdlib-only;
# a missing stack makes the reply fall back to text, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/tts.txt
piper-tts==1.8.0
onnxruntime==1.30.0
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open() (see requirements/transcribe.txt); pin below 19 here
# too so the shared PyAV is the one both paths expect.
av<19
+4
View File
@@ -26,6 +26,10 @@
sounddevice==0.5.6
onnxruntime==1.30.0
faster-whisper==1.2.1
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open(), breaking every transcription; see
# requirements/transcribe.txt for the full note.
av<19
piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Re-apply the audio baseline whenever a sound device is added, changed, or
# removed, so the internal speaker stays at full volume and unmuted (the
# baseline) after a USB mic, HDMI, or headset is plugged or unplugged.
#
# `udevadm monitor` is readable without root, so this runs as a long-lived
# systemd user service (see `audio-baseline.service`); each sound event
# triggers one idempotent apply of `audio-baseline.sh`.
set -u
BASELINE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/audio-baseline.sh"
stdbuf -oL udevadm monitor --udev --subsystem-match=sound 2>/dev/null \
| while IFS= read -r line; do
# Event lines look like `UDEV [1696.123] add /devices/... (sound)`;
# the `[` distinguishes them from the 3-line startup banner.
case "$line" in
UDEV*\[*) "$BASELINE" ;;
esac
done
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Restore the internal analog speaker to full volume, unmuted.
#
# PortAudio/ALSA has no volume control, so the voice gateway's cue beep and
# spoken replies are silent when the card's Master is muted or at 0%. The mixer
# also resets when a sound device is added or removed (e.g. a USB mic or HDMI
# unplug), so this runs both at startup and on every hotplug event (see
# `audio-baseline-watch.sh`).
#
# The card is identified by its 'Speaker' control (HDMI cards only expose
# IEC958), so a shifting card index after a device change does not matter.
# Idempotent and safe to run repeatedly; exits 0 when no card is present yet
# (the watcher retries on the next hotplug event).
set -u
for dir in /proc/asound/card*/; do
[ -e "$dir" ] || continue
idx=${dir#/proc/asound/card}
idx=${idx%/}
amixer -c "$idx" scontrols 2>/dev/null | grep -q "'Speaker'" || continue
amixer -c "$idx" sset Master 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Speaker 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Headphone 100% unmute >/dev/null 2>&1 || true
done
exit 0
+769 -167
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Print the merged config.json as JSON, following its `include` list.
Stdlib-only on purpose: bootstrap.sh reads per-machine values from the config
before the venv exists, so it cannot import `semif_agent.config`. This is the
same include/deep-merge semantics (`semif_agent/config.py`), reduced to the
minimum bootstrap needs (secrets are not resolved — bootstrap only reads
non-secret values like ports and endpoints).
Usage: python3 scripts/config_merge.py [config.json]
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
def _deep_merge(base: dict, extra: dict) -> 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)))
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env python3
"""Print (creating if needed) the SimpleX bot's contact address.
The gateway talks to a local `simplex-chat` daemon running as a bot
(`--create-bot-display-name`, see simplex_chat in config.json). To connect a
phone/client to the bot you need the bot's *user* contact address, not a chat
relay address; this queries the daemon's WebSocket API, creating the address on
first run, and prints the short link (and full link). Requires the daemon to be
running.
Usage:
.runtime/venv/bin/python scripts/simplex-address.py [--config config.json]
[--ws-url ws://...]
[--user-id 1]
"""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
def _ws_url(config_path: str) -> str:
try:
with open(config_path) as fh:
cfg = json.load(fh)
except (OSError, ValueError):
return "ws://127.0.0.1:5226"
return str(cfg.get("gateway", {}).get("simplex", {}).get("ws_url") or "ws://127.0.0.1:5226")
async def _resolve(ws_url: str, user_id: int) -> dict:
try:
import websockets
except ImportError:
raise SystemExit("the `websockets` package is required (pip install websockets)")
async with websockets.connect(ws_url, max_size=None) as ws:
async def cmd(command: str) -> dict:
await ws.send(json.dumps({"corrId": "addr", "cmd": command}))
raw = await asyncio.wait_for(ws.recv(), timeout=20)
return json.loads(raw).get("resp", {}) or {}
resp = await cmd(f"/_show_address {user_id}")
if resp.get("type") == "userContactLink":
return resp.get("contactLink", {}) or {}
# No address yet -> create one (APICreateMyAddress).
resp = await cmd(f"/_address {user_id}")
if resp.get("type") == "userContactLinkCreated":
return {"connLinkContact": resp.get("connLinkContact", {}) or {}}
raise SystemExit(f"could not read or create address: {json.dumps(resp)[:300]}")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--config", default="config.json")
ap.add_argument("--ws-url", default=None)
ap.add_argument("--user-id", type=int, default=1)
args = ap.parse_args()
ws_url = args.ws_url or _ws_url(args.config)
try:
link = asyncio.run(_resolve(ws_url, args.user_id))
except OSError as exc:
print(f"cannot reach simplex-chat at {ws_url}: {exc}", file=sys.stderr)
return 1
except asyncio.TimeoutError:
print(f"simplex-chat at {ws_url} did not answer", file=sys.stderr)
return 1
conn = link.get("connLinkContact", {}) or link
short = conn.get("connShortLink")
full = conn.get("connFullLink")
if short:
print(short)
if full:
print(full)
if not (short or full):
print("no contact address found", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+4 -1
View File
@@ -8,7 +8,10 @@ Type=simple
WorkingDirectory=@REPO@
Environment=HF_HOME=@REPO@/.runtime/hf
Environment=PYTHONUNBUFFERED=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
# voice mic loop) leaves a trace in the journal instead of hanging silently.
Environment=PYTHONFAULTHANDLER=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform @PLATFORMS@
Restart=always
RestartSec=5
StandardOutput=journal
+18 -8
View File
@@ -12,8 +12,11 @@ probability.
description plus `create_category`; `confirm_category_fit` confirms the
winner's scope. `navigation.category_tau` is that guard's P(covers) floor.
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
compares the winner's action to the request. `navigation.intent_tau` is that
guard's P(same) floor.
decides what the winner does for the request (`same` / `part` / `different`).
`navigation.intent_tau` is that guard's P(same or part) floor: `same` or
`part` runs the skill, and only `different` authors a new leaf. The guard
decides contribution only; whether more work remains is `assess:outcome`'s
call.
This replays a hand-labeled eval set through the **real** decision engine and
the **real** skill tree, measuring each guard's probability per request so the
@@ -23,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 (shipped 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
@@ -58,11 +61,13 @@ LEAF_EVAL: list[tuple[str, str]] = [
("check my next message on simplex", "simplex.next_message"),
("read the next simplex message", "simplex.next_message"),
("show me my simplex messages", "simplex.next_message"),
('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"),
("send a simplex message to pepper saying hi", "simplex.send_simplex_message"),
('send a message on simplex to pepper: "hey!"', "simplex.send_message"),
("send a simplex message to pepper saying hi", "simplex.send_message"),
("what is my simplex connection link?", "simplex.connect_link"),
("give me my simplex contact link", "simplex.connect_link"),
("tell me the next event in my nextcloud calendar", "calendar.next_event"),
("tell me the next event in my nextcloud calendar", "nextcloud.next_event"),
("what is 15% of 80?", "calculator.calculate"),
("square root of 144", "calculator.calculate"),
("translate my last simplex message to French", "create"),
("delete my next simplex message", "create"),
("book a flight to japan", "create"),
@@ -73,7 +78,9 @@ CATEGORY_EVAL: list[tuple[str, str]] = [
("what is my next message on simplex?", "simplex"),
("send a simplex message to pepper saying hi", "simplex"),
("what is my simplex connection link?", "simplex"),
("tell me the next event in my nextcloud calendar", "calendar"),
("tell me the next event in my nextcloud calendar", "nextcloud"),
("what is 15% of 80?", "calculator"),
("square root of 144", "calculator"),
("hello there", "response"),
("thanks!", "response"),
("what", "response"),
@@ -118,7 +125,10 @@ def measure(
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
events = trace.read()[before:]
guard = next((e for e in events if e["kind"] == "intent_guard"), None)
return {"picked": f"{nav.category}.{nav.name}", "p": guard["probs"]["same"] if guard else None}
# The guard accepts a skill that is the same action OR one required part of a
# compound request, so the "does it contribute" mass is same + part.
p = (guard["probs"]["same"] + guard["probs"]["part"]) if guard else None
return {"picked": f"{nav.category}.{nav.name}", "p": p}
def verdict(measured: dict, tau: float) -> str:
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""Break down voice-gateway latency from the run trace.
Reads `data/runs.jsonl` (written by the running gateway) and, for each spoken
interaction, reports the time between the **last word spoken** and the **first
reply audio** split by section:
last word ── endpointing ── STT ── adapter ── [scheduler: guards + act + assess]
── reply routing (humanize) ── TTS synth ── playback start
The voice transport emits `voice_speech_end` at the last speech frame and
`voice_playback_start` right before the first reply samples reach the device;
the scheduler emits `submit`/`actionability`/`category_scope`/`intent_guard`/
`assessed`/`ran`; the service emits `humanize`/`gateway_reply_queued` and the
adapter `gateway_reply_dequeued`/`voice_speak_start`/`voice_tts_synth`.
Usage:
python scripts/voice-latency.py [data/runs.jsonl] [--json] [--decisions PATH]
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
from pathlib import Path
def load_rows(path: str) -> list[dict]:
rows = []
if not Path(path).is_file():
return rows
with open(path) as handle:
for line in handle:
line = line.strip()
if line:
rows.append(json.loads(line))
return rows
def _first(events: list[dict], kind: str) -> dict | None:
return next((e for e in events if e.get("kind") == kind), None)
def _ts(event: dict | None) -> float | None:
return None if event is None else event.get("ts")
def build_interactions(rows: list[dict]) -> list[dict]:
"""Split the trace into spoken interactions, each from speech-end to reply-end."""
interactions: list[dict] = []
current: dict | None = None
for event in rows:
kind = event.get("kind")
if kind == "voice_speech_end" or (
kind == "voice_utterance" and current is None
):
# A new utterance begins; close any prior interaction at its reply
# end. `voice_utterance` also starts one on legacy traces that
# predate the `voice_speech_end` probe (last-word boundary unknown).
if current is not None:
interactions.append(current)
current = {"events": [event]}
elif current is not None:
current["events"].append(event)
if kind in ("voice_spoke", "voice_speak_failed", "voice_stt_empty",
"voice_stt_failed", "voice_short_utterance"):
interactions.append(current)
current = None
if current is not None:
interactions.append(current)
return interactions
def _decisions_timing(decisions_path: str) -> dict[str, list[dict]]:
"""Map run_id -> list of {phase, timing} from the decision log."""
by_run: dict[str, list[dict]] = {}
if not Path(decisions_path).is_file():
return by_run
with open(decisions_path) as handle:
for line in handle:
line = line.strip()
if not line:
continue
row = json.loads(line)
extra = row.get("extra") or {}
run_id = extra.get("run_id")
timing = extra.get("timing")
if run_id and timing:
by_run.setdefault(run_id, []).append(
{"phase": extra.get("phase"), **timing}
)
return by_run
def analyze(interaction: dict, decisions: dict[str, list[dict]]) -> dict | None:
events = interaction["events"]
speech_end = _first(events, "voice_speech_end")
utterance = _first(events, "voice_utterance")
transcribed = _first(events, "voice_transcribed")
submit = _first(events, "submit")
if utterance is None or submit is None:
return None # empty/short utterance: nothing was dispatched
# On legacy traces without `voice_speech_end`, measure from the utterance.
origin = speech_end or utterance
actionability = _first(events, "actionability")
category_scope = _first(events, "category_scope")
intent_guard = _first(events, "intent_guard")
assessed = _first(events, "assessed")
ran = _first(events, "ran")
reply_queued = _first(events, "gateway_reply_queued")
reply_dequeued = _first(events, "gateway_reply_dequeued")
speak_start = _first(events, "voice_speak_start")
tts = _first(events, "voice_tts_synth")
playback = _first(events, "voice_playback_start")
spoke = _first(events, "voice_spoke")
humanize = _first(events, "humanize")
t0 = _ts(origin)
run_id = submit.get("run_id")
def delta(a: dict | None, b: dict | None) -> float | None:
ta, tb = _ts(a), _ts(b)
return None if ta is None or tb is None else round(tb - ta, 3)
out = {
"run_id": run_id,
"text": submit.get("text"),
"skill": (ran or {}).get("skill"),
"summary": (ran or {}).get("summary"),
"last_word_ts": t0,
"endpointing_s": delta(speech_end, utterance),
"stt_s": delta(utterance, transcribed),
"adapter_s": delta(transcribed, submit),
"scheduler_s": delta(submit, ran),
"guard_actionability_s": delta(submit, actionability),
"guard_category_s": delta(actionability, category_scope),
"guard_intent_s": delta(category_scope, intent_guard),
"act_assess_s": delta(intent_guard, assessed),
"assess_ran_s": delta(assessed, ran),
"reply_s": delta(ran, playback),
"humanize_s": (humanize or {}).get("elapsed_s"),
"tts_synth_s": (tts or {}).get("synth_s"),
"tts_audio_s": (tts or {}).get("audio_s"),
"queue_s": delta(reply_queued, reply_dequeued),
"speak_to_playback_s": delta(speak_start, playback),
"playback_s": delta(playback, spoke),
"total_to_first_audio_s": delta(origin, playback),
"total_to_reply_end_s": delta(origin, spoke),
"decisions": decisions.get(run_id, []),
}
# Anything after `ran` but before playback that is not humanize/TTS is queue.
if out["reply_s"] is not None:
accounted = (out["humanize_s"] or 0.0) + (out["tts_synth_s"] or 0.0)
out["reply_unaccounted_s"] = round(out["reply_s"] - accounted, 3)
return out
def fmt(value) -> str:
return "—" if value is None else f"{value:.2f}"
def render(results: list[dict]) -> None:
for r in results:
print(f"\nrun {r['run_id']} {r['text']!r} skill={r['skill']}")
print(f" last word → endpointing done : {fmt(r['endpointing_s'])} s")
print(f" STT : {fmt(r['stt_s'])} s")
print(f" adapter → scheduler submit : {fmt(r['adapter_s'])} s")
print(f" SCHEDULER total : {fmt(r['scheduler_s'])} s")
print(f" actionability guard : {fmt(r['guard_actionability_s'])} s")
print(f" category softmax + scope : {fmt(r['guard_category_s'])} s")
print(f" leaf softmax + intent : {fmt(r['guard_intent_s'])} s")
print(f" act + assess:outcome : {fmt(r['act_assess_s'])} s")
print(f" assess → ran : {fmt(r['assess_ran_s'])} s")
print(f" reply (ran → first audio) : {fmt(r['reply_s'])} s")
print(f" humanize : {fmt(r['humanize_s'])} s")
print(f" TTS synth : {fmt(r['tts_synth_s'])} s")
print(f" other (queue/open) : {fmt(r.get('reply_unaccounted_s'))} s")
print(f" playback (audio duration) : {fmt(r['playback_s'])} s")
print(f" ── LAST WORD → FIRST AUDIO : {fmt(r['total_to_first_audio_s'])} s")
if r["decisions"]:
for d in r["decisions"]:
print(
f" [{d.get('phase')}] tokens={d.get('input_tokens')} "
f"forward={d.get('forward_seconds')} total={d.get('total_seconds')}"
)
def agg(key: str) -> str:
vals = [r[key] for r in results if r.get(key) is not None]
if not vals:
return "—"
return f"median {statistics.median(vals):.2f}s mean {statistics.mean(vals):.2f}s (n={len(vals)})"
print("\n===== aggregate =====")
for key, label in (
("endpointing_s", "endpointing"),
("stt_s", "STT"),
("scheduler_s", "SCHEDULER"),
("guard_actionability_s", " actionability"),
("guard_category_s", " category softmax+scope"),
("guard_intent_s", " leaf softmax+intent"),
("act_assess_s", " act+assess"),
("reply_s", "reply (humanize+TTS)"),
("humanize_s", " humanize"),
("tts_synth_s", " TTS synth"),
("total_to_first_audio_s", "TOTAL last word → first audio"),
):
print(f"{label:28s}: {agg(key)}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("trace", nargs="?", default="data/runs.jsonl")
parser.add_argument("--decisions", default="data/decisions.jsonl")
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
rows = load_rows(args.trace)
decisions = _decisions_timing(args.decisions)
results = []
for interaction in build_interactions(rows):
analyzed = analyze(interaction, decisions)
if analyzed is not None:
results.append(analyzed)
if args.json:
print(json.dumps(results, indent=2))
return 0
if not results:
print("no spoken interactions found in", args.trace)
return 1
render(results)
return 0
if __name__ == "__main__":
sys.exit(main())
+58 -9
View File
@@ -6,9 +6,12 @@ Run after installing `requirements/voice.txt` (bootstrap does this with
`gateway.voice` from config.json so the downloaded models match the configured
names, or take explicit flags.
- **Wake word** (openWakeWord): downloaded by `openwakeword.utils.download_models`
into the venv's package resources dir (inside `.runtime/venv/`, so still
contained in the checkout). The detector resolves the model by name there.
- **Wake word** (openWakeWord): official models are downloaded by
`openwakeword.utils.download_models` into the venv's package resources dir
(inside `.runtime/venv/`, so still contained in the checkout); the detector
resolves the model by name there. A **pinned community model** (openWakeWord
ships no "computer" model) is fetched from `pins.json` `wake_word` into the
configured `model_dir` (`.runtime/voice/wake`) and verified by sha256.
- **TTS** (Piper): the voice `.onnx` + `.onnx.json` are fetched from the
`rhasspy/piper-voices` HF repo into `.runtime/voice/tts/`.
- **STT** (faster-whisper): instantiating the model warms it into the HF cache
@@ -18,12 +21,15 @@ names, or take explicit flags.
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import urllib.request
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RUNTIME = REPO_ROOT / ".runtime" / "voice"
PINS = REPO_ROOT / "pins.json"
PIPER_REPO = "rhasspy/piper-voices"
@@ -42,15 +48,56 @@ def piper_hf_path(voice: str) -> str:
return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx"
def download_wake(name: str) -> None:
def pinned_wake_models() -> dict:
"""Return the code-owned wake-word refs from `pins.json` (`name` -> ref)."""
try:
pins = json.loads(PINS.read_text())
except Exception:
return {}
block = pins.get("wake_word", {}) or {}
return {
name: ref
for name, ref in block.items()
if isinstance(ref, dict) and ref.get("url")
}
def _sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def download_wake_file(name: str, ref: dict, target_dir: Path) -> None:
"""Fetch a pinned community wake model into `target_dir`, verifying sha256."""
url = str(ref["url"])
expected = str(ref.get("sha256", "") or "")
target_dir.mkdir(parents=True, exist_ok=True)
dest = target_dir / f"{name}.onnx"
if dest.is_file() and (not expected or _sha256(dest) == expected):
print(f"== wake word: {dest.name} (present)")
return
print(f"== wake word: {url} -> {dest}")
with urllib.request.urlopen(url) as resp: # pinned https URL from pins.json
data = resp.read()
if expected and hashlib.sha256(data).hexdigest() != expected:
raise SystemExit(f"sha256 mismatch for {name}: refusing to write {dest}")
dest.write_bytes(data)
def download_wake(name: str, target_dir: Path) -> None:
import openwakeword.utils as utils
print(f"== wake word model: {name}")
# Default target: the venv's package resources dir (inside .runtime/venv).
# openWakeWord resolves the model (and its shared mel/embedding models) by
# name from there.
# Always fetch the shared feature (mel/embedding) + VAD models, and for an
# official name the phrase model itself, into the venv's package resources
# dir (inside .runtime/venv). An unknown name is skipped here.
utils.download_models(model_names=[name])
# A pinned community model (openWakeWord ships no "computer" model) is
# fetched into the configured model_dir so the detector resolves it by path.
ref = pinned_wake_models().get(name)
if ref:
download_wake_file(name, ref, target_dir)
def download_voice(voice: str, target: Path) -> None:
from huggingface_hub import hf_hub_download
@@ -86,6 +133,8 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default=str(REPO_ROOT / "config.json"))
parser.add_argument("--wake", default=None, help="openWakeWord model name")
parser.add_argument("--wake-dir", default=str(RUNTIME / "wake"),
help="target dir for a pinned community wake model")
parser.add_argument("--stt", default=None, help="faster-whisper model size/path")
parser.add_argument("--tts", default=None, help="Piper voice id")
parser.add_argument("--tts-dir", default=str(RUNTIME / "tts"))
@@ -95,12 +144,12 @@ def main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv)
voice_cfg = _config_voice(Path(args.config))
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_mycroft"
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_computer"
stt = args.stt or (voice_cfg.get("stt", {}) or {}).get("model") or "base.en"
tts = args.tts or (voice_cfg.get("tts", {}) or {}).get("voice") or "en_US-lessac-medium"
if not args.skip_wake:
download_wake(wake)
download_wake(wake, Path(args.wake_dir))
if not args.skip_tts:
download_voice(tts, Path(args.tts_dir))
if not args.skip_stt:
+727
View File
@@ -0,0 +1,727 @@
# English recording prompts for a Piper TTS voice (one utterance per line).
#
# Source: the Harvard (IEEE) sentences, from "IEEE Recommended Practice for
# Speech Quality Measurements" (IEEE Std 297-1969, Appendix C) - 720
# phonetically balanced, public-domain sentences. scripts/voice-record.py reads
# this file to record an LJSpeech-format dataset. Lines starting with "#" and
# blank lines are skipped. A 15-30 minute voice uses roughly 200-450 of them.
The birch canoe slid on the smooth planks.
Glue the sheet to the dark blue background.
It's easy to tell the depth of a well.
These days a chicken leg is a rare dish.
Rice is often served in round bowls.
The juice of lemons makes fine punch.
The box was thrown beside the parked truck.
The hogs were fed chopped corn and garbage.
Four hours of steady work faced us.
A large size in stockings is hard to sell.
The boy was there when the sun rose.
A rod is used to catch pink salmon.
The source of the huge river is the clear spring.
Kick the ball straight and follow through.
Help the woman get back to her feet.
A pot of tea helps to pass the evening.
Smoky fires lack flame and heat.
The soft cushion broke the man's fall.
The salt breeze came across from the sea.
The girl at the booth sold fifty bonds.
The small pup gnawed a hole in the sock.
The fish twisted and turned on the bent hook.
Press the pants and sew a button on the vest.
The swan dive was far short of perfect.
The beauty of the view stunned the young boy.
Two blue fish swam in the tank.
Her purse was full of useless trash.
The colt reared and threw the tall rider.
It snowed, rained, and hailed the same morning.
Read verse out loud for pleasure.
Hoist the load to your left shoulder.
Take the winding path to reach the lake.
Note closely the size of the gas tank.
Wipe the grease off his dirty face.
Mend the coat before you go out.
The wrist was badly strained and hung limp.
The stray cat gave birth to kittens.
The young girl gave no clear response.
The meal was cooked before the bell rang.
What joy there is in living.
A king ruled the state in the early days.
The ship was torn apart on the sharp reef.
Sickness kept him home the third week.
The wide road shimmered in the hot sun.
The lazy cow lay in the cool grass.
Lift the square stone over the fence.
The rope will bind the seven books at once.
Hop over the fence and plunge in.
The friendly gang left the drug store.
Mesh wire keeps chicks inside.
The frosty air passed through the coat.
The crooked maze failed to fool the mouse.
Adding fast leads to wrong sums.
The show was a flop from the very start.
A saw is a tool used for making boards.
The wagon moved on well oiled wheels.
March the soldiers past the next hill.
A cup of sugar makes sweet fudge.
Place a rosebush near the porch steps.
Both lost their lives in the raging storm.
We talked of the side show in the circus.
Use a pencil to write the first draft.
He ran half way to the hardware store.
The clock struck to mark the third period.
A small creek cut across the field.
Cars and busses stalled in snow drifts.
The set of china hit the floor with a crash.
This is a grand season for hikes on the road.
The dune rose from the edge of the water.
Those words were the cue for the actor to leave.
A yacht slid around the point into the bay.
The two met while playing on the sand.
The ink stain dried on the finished page.
The walled town was seized without a fight.
The lease ran out in sixteen weeks.
A tame squirrel makes a nice pet.
The horn of the car woke the sleeping cop.
The heart beat strongly and with firm strokes.
The pearl was worn in a thin silver ring.
The fruit peel was cut in thick slices.
The Navy attacked the big task force.
See the cat glaring at the scared mouse.
There are more than two factors here.
The hat brim was wide and too droopy.
The lawyer tried to lose his case.
The grass curled around the fence post.
Cut the pie into large parts.
Men strive but seldom get rich.
Always close the barn door tight.
He lay prone and hardly moved a limb.
The slush lay deep along the street.
A wisp of cloud hung in the blue air.
A pound of sugar costs more than eggs.
The fin was sharp and cut the clear water.
The play seems dull and quite stupid.
Bail the boat to stop it from sinking.
The term ended in late June that year.
A tusk is used to make costly gifts.
Ten pins were set in order.
The bill was paid every third week.
Oak is strong and also gives shade.
Cats and dogs each hate the other.
The pipe began to rust while new.
Open the crate but don't break the glass.
Add the sum to the product of these three.
Thieves who rob friends deserve jail.
The ripe taste of cheese improves with age.
Act on these orders with great speed.
The hog crawled under the high fence.
Move the vat over the hot fire.
The bark of the pine tree was shiny and dark.
Leaves turn brown and yellow in the fall.
The pennant waved when the wind blew.
Split the log with a quick, sharp blow.
Burn peat after the logs give out.
He ordered peach pie with ice cream.
Weave the carpet on the right hand side.
Hemp is a weed found in parts of the tropics.
A lame back kept his score low.
We find joy in the simplest things.
Type out three lists of orders.
The harder he tried the less he got done.
The boss ran the show with a watchful eye.
The cup cracked and spilled its contents.
Paste can cleanse the most dirty brass.
The slang word for raw whiskey is booze.
It caught its hind paw in a rusty trap.
The wharf could be seen at the farther shore.
Feel the heat of the weak dying flame.
The tiny girl took off her hat.
A cramp is no small danger on a swim.
He said the same phrase thirty times.
Pluck the bright rose without leaves.
Two plus seven is less than ten.
The glow deepened in the eyes of the sweet girl.
Bring your problems to the wise chief.
Write a fond note to the friend you cherish.
Clothes and lodging are free to new men.
We frown when events take a bad turn.
Port is a strong wine with a smoky taste.
The young kid jumped the rusty gate.
Guess the results from the first scores.
A salt pickle tastes fine with ham.
The just claim got the right verdict.
These thistles bend in a high wind.
Pure bred poodles have curls.
The tree top waved in a graceful way.
The spot on the blotter was made by green ink.
Mud was spattered on the front of his white shirt.
The cigar burned a hole in the desk top.
The empty flask stood on the tin tray.
A speedy man can beat this track mark.
He broke a new shoelace that day.
The coffee stand is too high for the couch.
The urge to write short stories is rare.
The pencils have all been used.
The pirates seized the crew of the lost ship.
We tried to replace the coin but failed.
She sewed the torn coat quite neatly.
The sofa cushion is red and of light weight.
The jacket hung on the back of the wide chair.
At that high level the air is pure.
Drop the two when you add the figures.
A filing case is now hard to buy.
An abrupt start does not win the prize.
Wood is best for making toys and blocks.
The office paint was a dull, sad tan.
He knew the skill of the great young actress.
A rag will soak up spilled water.
A shower of dirt fell from the hot pipes.
Steam hissed from the broken valve.
The child almost hurt the small dog.
There was a sound of dry leaves outside.
The sky that morning was clear and bright blue.
Torn scraps littered the stone floor.
Sunday is the best part of the week.
The doctor cured him with these pills.
The new girl was fired today at noon.
They felt gay when the ship arrived in port.
Add the store's account to the last cent.
Acid burns holes in wool cloth.
Fairy tales should be fun to write.
Eight miles of woodland burned to waste.
The third act was dull and tired the players.
A young child should not suffer fright.
Add the column and put the sum here.
We admire and love a good cook.
There the flood mark is ten inches.
He carved a head from the round block of marble.
She has a smart way of wearing clothes.
The fruit of a fig tree is apple-shaped.
Corn cobs can be used to kindle a fire.
Where were they when the noise started.
The paper box is full of thumb tacks.
Sell your gift to a buyer at a good gain.
The tongs lay beside the ice pail.
The petals fall with the next puff of wind.
Bring your best compass to the third class.
They could laugh although they were sad.
Farmers came in to thresh the oat crop.
The brown house was on fire to the attic.
The lure is used to catch trout and flounder.
Float the soap on top of the bath water.
A blue crane is a tall wading bird.
A fresh start will work such wonders.
The club rented the rink for the fifth night.
After the dance, they went straight home.
The hostess taught the new maid to serve.
He wrote his last novel there at the inn.
Even the worst will beat his low score.
The cement had dried when he moved it.
The loss of the second ship was hard to take.
The fly made its way along the wall.
Do that with a wooden stick.
Live wires should be kept covered.
The large house had hot water taps.
It is hard to erase blue or red ink.
Write at once or you may forget it.
The doorknob was made of bright clean brass.
The wreck occurred by the bank on Main Street.
A pencil with black lead writes best.
Coax a young calf to drink from a bucket.
Schools for ladies teach charm and grace.
The lamp shone with a steady green flame.
They took the axe and the saw to the forest.
The ancient coin was quite dull and worn.
The shaky barn fell with a loud crash.
Jazz and swing fans like fast music.
Rake the rubbish up and then burn it.
Slash the gold cloth into fine ribbons.
Try to have the court decide the case.
They are pushed back each time they attack.
He broke his ties with groups of former friends.
They floated on the raft to sun their white backs.
The map had an X that meant nothing.
Whitings are small fish caught in nets.
Some ads serve to cheat buyers.
Jerk the rope and the bell rings weakly.
A waxed floor makes us lose balance.
Madam, this is the best brand of corn.
On the islands the sea breeze is soft and mild.
The play began as soon as we sat down.
This will lead the world to more sound and fury.
Add salt before you fry the egg.
The rush for funds reached its peak Tuesday.
The birch looked stark white and lonesome.
The box is held by a bright red snapper.
To make pure ice, you freeze water.
The first worm gets snapped early.
Jump the fence and hurry up the bank.
Yell and clap as the curtain slides back.
They are men who walk the middle of the road.
Both brothers wear the same size.
In some form or other we need fun.
The prince ordered his head chopped off.
The houses are built of red clay bricks.
Ducks fly north but lack a compass.
Fruit flavors are used in fizz drinks.
These pills do less good than others.
Canned pears lack full flavor.
The dark pot hung in the front closet.
Carry the pail to the wall and spill it there.
The train brought our hero to the big town.
We are sure that one war is enough.
Gray paint stretched for miles around.
The rude laugh filled the empty room.
High seats are best for football fans.
Tea served from the brown jug is tasty.
A dash of pepper spoils beef stew.
A zestful food is the hot-cross bun.
The horse trotted around the field at a brisk pace.
Find the twin who stole the pearl necklace.
Cut the cord that binds the box tightly.
The red tape bound the smuggled food.
Look in the corner to find the tan shirt.
The cold drizzle will halt the bond drive.
Nine men were hired to dig the ruins.
The junk yard had a mouldy smell.
The flint sputtered and lit a pine torch.
Soak the cloth and drown the sharp odor.
The shelves were bare of both jam or crackers.
A joy to every child is the swan boat.
All sat frozen and watched the screen.
A cloud of dust stung his tender eyes.
To reach the end he needs much courage.
Shape the clay gently into block form.
A ridge on a smooth surface is a bump or flaw.
Hedge apples may stain your hands green.
Quench your thirst, then eat the crackers.
Tight curls get limp on rainy days.
The mute muffled the high tones of the horn.
The gold ring fits only a pierced ear.
The old pan was covered with hard fudge.
Watch the log float in the wide river.
The node on the stalk of wheat grew daily.
The heap of fallen leaves was set on fire.
Write fast if you want to finish early.
His shirt was clean but one button was gone.
The barrel of beer was a brew of malt and hops.
Tin cans are absent from store shelves.
Slide the box into that empty space.
The plant grew large and green in the window.
The beam dropped down on the workmen's head.
Pink clouds floated with the breeze.
She danced like a swan, tall and graceful.
The tube was blown and the tire flat and useless.
It is late morning on the old wall clock.
Let's all join as we sing the last chorus.
The last switch cannot be turned off.
The fight will end in just six minutes.
The store walls were lined with colored frocks.
The peace league met to discuss their plans.
The rise to fame of a person takes luck.
Paper is scarce, so write with much care.
The quick fox jumped on the sleeping cat.
The nozzle of the fire hose was bright brass.
Screw the round cap on as tight as needed.
Time brings us many changes.
The purple tie was ten years old.
Men think and plan and sometimes act.
Fill the ink jar with sticky glue.
He smoke a big pipe with strong contents.
We need grain to keep our mules healthy.
Pack the records in a neat thin case.
The crunch of feet in the snow was the only sound.
The copper bowl shone in the sun's rays.
Boards will warp unless kept dry.
The plush chair leaned against the wall.
Glass will clink when struck by metal.
Bathe and relax in the cool green grass.
Nine rows of soldiers stood in line.
The beach is dry and shallow at low tide.
The idea is to sew both edges straight.
The kitten chased the dog down the street.
Pages bound in cloth make a book.
Try to trace the fine lines of the painting.
Women form less than half of the group.
The zones merge in the central part of town.
A gem in the rough needs work to polish.
Code is used when secrets are sent.
Most of the news is easy for us to hear.
He used the lathe to make brass objects.
The vane on top of the pole revolved in the wind.
Mince pie is a dish served to children.
The clan gathered on each dull night.
Let it burn, it gives us warmth and comfort.
A castle built from sand fails to endure.
A child's wit saved the day for us.
Tack the strip of carpet to the worn floor.
Next Tuesday we must vote.
Pour the stew from the pot into the plate.
Each penny shone like new.
The man went to the woods to gather sticks.
The dirt piles were lines along the road.
The logs fell and tumbled into the clear stream.
Just hoist it up and take it away.
A ripe plum is fit for a king's palate.
Our plans right now are hazy.
Brass rings are sold by these natives.
It takes a good trap to capture a bear.
Feed the white mouse some flower seeds.
The thaw came early and freed the stream.
He took the lead and kept it the whole distance.
The key you designed will fit the lock.
Plead to the council to free the poor thief.
Better hash is made of rare beef.
This plank was made for walking on.
The lake sparkled in the red hot sun.
He crawled with care along the ledge.
Tend the sheep while the dog wanders.
It takes a lot of help to finish these.
Mark the spot with a sign painted red.
Take two shares as a fair profit.
The fur of cats goes by many names.
North winds bring colds and fevers.
He asks no person to vouch for him.
Go now and come here later.
A sash of gold silk will trim her dress.
Soap can wash most dirt away.
That move means the game is over.
He wrote down a long list of items.
A siege will crack the strong defense.
Grape juice and water mix well.
Roads are paved with sticky tar.
Fake stones shine but cost little.
The drip of the rain made a pleasant sound.
Smoke poured out of every crack.
Serve the hot rum to the tired heroes.
Much of the story makes good sense.
The sun came up to light the eastern sky.
Heave the line over the port side.
A lathe cuts and trims any wood.
It's a dense crowd in two distinct ways.
His hip struck the knee of the next player.
The stale smell of old beer lingers.
The desk was firm on the shaky floor.
It takes heat to bring out the odor.
Beef is scarcer than some lamb.
Raise the sail and steer the ship northward.
A cone costs five cents on Mondays.
A pod is what peas always grow in.
Jerk the dart from the cork target.
No cement will hold hard wood.
We now have a new base for shipping.
A list of names is carved around the base.
The sheep were led home by a dog.
Three for a dime, the young peddler cried.
The sense of smell is better than that of touch.
No hardship seemed to keep him sad.
Grace makes up for lack of beauty.
Nudge gently but wake her now.
The news struck doubt into restless minds.
Once we stood beside the shore.
A chink in the wall allowed a draft to blow.
Fasten two pins on each side.
A cold dip restores health and zest.
He takes the oath of office each March.
The sand drifts over the sill of the old house.
The point of the steel pen was bent and twisted.
There is a lag between thought and act.
Seed is needed to plant the spring corn.
Draw the chart with heavy black lines.
The boy owed his pal thirty cents.
The chap slipped into the crowd and was lost.
Hats are worn to tea and not to dinner.
The ramp led up to the wide highway.
Beat the dust from the rug onto the lawn.
Say it slowly but make it ring clear.
The straw nest housed five robins.
Screen the porch with woven straw mats.
This horse will nose his way to the finish.
The dry wax protects the deep scratch.
He picked up the dice for a second roll.
These coins will be needed to pay his debt.
The nag pulled the frail cart along.
Twist the valve and release hot steam.
The vamp of the shoe had a gold buckle.
The smell of burned rags itches my nose.
New pants lack cuffs and pockets.
The marsh will freeze when cold enough.
They slice the sausage thin with a knife.
The bloom of the rose lasts a few days.
A gray mare walked before the colt.
Breakfast buns are fine with a hot drink.
Bottles hold four kinds of rum.
The man wore a feather in his felt hat.
He wheeled the bike past the winding road.
Drop the ashes on the worn old rug.
The desk and both chairs were painted tan.
Throw out the used paper cup and plate.
A clean neck means a neat collar.
The couch cover and hall drapes were blue.
The stems of the tall glasses cracked and broke.
The wall phone rang loud and often.
The clothes dried on a thin wooden rack.
Turn on the lantern which gives us light.
The cleat sank deeply into the soft turf.
The bills were mailed promptly on the tenth of the month.
To have is better than to wait and hope.
The price is fair for a good antique clock.
The music played on while they talked.
Dispense with a vest on a day like this.
The bunch of grapes was pressed into wine.
He sent the figs, but kept the ripe cherries.
The hinge on the door creaked with old age.
The screen before the fire kept in the sparks.
Fly by night, and you waste little time.
Thick glasses helped him read the print.
Birth and death mark the limits of life.
The chair looked strong but had no bottom.
The kite flew wildly in the high wind.
A fur muff is stylish once more.
The tin box held priceless stones.
We need an end of all such matter.
The case was puzzling to the old and wise.
The bright lanterns were gay on the dark lawn.
We don't get much money but we have fun.
The youth drove with zest, but little skill.
Five years he lived with a shaggy dog.
A fence cuts through the corner lot.
The way to save money is not to spend much.
Shut the hatch before the waves push it in.
The odor of spring makes young hearts jump.
Crack the walnut with your sharp side teeth.
He offered proof in the form of a large chart.
Send the stuff in a thick paper bag.
A quart of milk is water for the most part.
They told wild tales to frighten him.
The three story house was built of stone.
In the rear of the ground floor was a large passage.
A man in a blue sweater sat at the desk.
Oats are a food eaten by horse and man.
Their eyelids droop for want of sleep.
A sip of tea revives his tired friend.
There are many ways to do these things.
Tuck the sheet under the edge of the mat.
A force equal to that would move the earth.
We like to see clear weather.
The work of the tailor is seen on each side.
Take a chance and win a china doll.
Shake the dust from your shoes, stranger.
She was kind to sick old people.
The square wooden crate was packed to be shipped.
The dusty bench stood by the stone wall.
We dress to suit the weather of most days.
Smile when you say nasty words.
A bowl of rice is free with chicken stew.
The water in this well is a source of good health.
Take shelter in this tent, but keep still.
That guy is the writer of a few banned books.
The little tales they tell are false.
The door was barred, locked, and bolted as well.
Ripe pears are fit for a queen's table.
A big wet stain was on the round carpet.
The kite dipped and swayed, but stayed aloft.
The pleasant hours fly by much too soon.
The room was crowded with a wild mob.
This strong arm shall shield your honor.
She blushed when he gave her a white orchid.
The beetle droned in the hot June sun.
Press the pedal with your left foot.
Neat plans fail without luck.
The black trunk fell from the landing.
The bank pressed for payment of the debt.
The theft of the pearl pin was kept secret.
Shake hands with this friendly child.
The vast space stretched into the far distance.
A rich farm is rare in this sandy waste.
His wide grin earned many friends.
Flax makes a fine brand of paper.
Hurdle the pit with the aid of a long pole.
A strong bid may scare your partner stiff.
Even a just cause needs power to win.
Peep under the tent and see the clowns.
The leaf drifts along with a slow spin.
Cheap clothes are flashy but don't last.
A thing of small note can cause despair.
Flood the mails with requests for this book.
A thick coat of black paint covered all.
The pencil was cut to be sharp at both ends.
Those last words were a strong statement.
He wrote his name boldly at the top of the sheet.
Dill pickles are sour but taste fine.
Down that road is the way to the grain farmer.
Either mud or dust are found at all times.
The best method is to fix it in place with clips.
If you mumble your speech will be lost.
At night the alarm roused him from a deep sleep.
Read just what the meter says.
Fill your pack with bright trinkets for the poor.
The small red neon lamp went out.
Clams are small, round, soft, and tasty.
The fan whirled its round blades softly.
The line where the edges join was clean.
Breathe deep and smell the piny air.
It matters not if he reads these words or those.
A brown leather bag hung from its strap.
A toad and a frog are hard to tell apart.
A white silk jacket goes with any shoes.
A break in the dam almost caused a flood.
Paint the sockets in the wall dull green.
The child crawled into the dense grass.
Bribes fail where honest men work.
Trample the spark, else the flames will spread.
The hilt of the sword was carved with fine designs.
A round hole was drilled through the thin board.
Footprints showed the path he took up the beach.
She was waiting at my front lawn.
A vent near the edge brought in fresh air.
Prod the old mule with a crooked stick.
It is a band of steel three inches wide.
The pipe ran almost the length of the ditch.
It was hidden from sight by a mass of leaves and shrubs.
The weight of the package was seen on the high scale.
Wake and rise, and step into the green outdoors.
The green light in the brown box flickered.
The brass tube circled the high wall.
The lobes of her ears were pierced to hold rings.
Hold the hammer near the end to drive the nail.
Next Sunday is the twelfth of the month.
Every word and phrase he speaks is true.
He put his last cartridge into the gun and fired.
They took their kids from the public school.
Drive the screw straight into the wood.
Keep the hatch tight and the watch constant.
Sever the twine with a quick snip of the knife.
Paper will dry out when wet.
Slide the catch back and open the desk.
Help the weak to preserve their strength.
A sullen smile gets few friends.
Stop whistling and watch the boys march.
Jerk the cord, and out tumbles the gold.
Slide the tray across the glass top.
The cloud moved in a stately way and was gone.
Light maple makes for a swell room.
Set the piece here and say nothing.
Dull stories make her laugh.
A stiff cord will do to fasten your shoe.
Get the trust fund to the bank early.
Choose between the high road and the low.
A plea for funds seems to come again.
He lent his coat to the tall gaunt stranger.
There is a strong chance it will happen once more.
The duke left the park in a silver coach.
Greet the new guests and leave quickly.
When the frost has come it is time for turkey.
Sweet words work better than fierce.
A thin stripe runs down the middle.
A six comes up more often than a ten.
Lush fern grow on the lofty rocks.
The ram scared the school children off.
The team with the best timing looks good.
The farmer swapped his horse for a brown ox.
Sit on the perch and tell the others what to do.
A steep trail is painful for our feet.
The early phase of life moves fast.
Green moss grows on the northern side.
Tea in thin china has a sweet taste.
Pitch the straw through the door of the stable.
The latch on the back gate needed a nail.
The goose was brought straight from the old market.
The sink is the thing in which we pile dishes.
A whiff of it will cure the most stubborn cold.
The facts don't always show who is right.
She flaps her cape as she parades the street.
The loss of the cruiser was a blow to the fleet.
Loop the braid to the left and then over.
Plead with the lawyer to drop the lost cause.
Calves thrive on tender spring grass.
Post no bills on this office wall.
Tear a thin sheet from the yellow pad.
A cruise in warm waters in a sleek yacht is fun.
A streak of color ran down the left edge.
It was done before the boy could see it.
Crouch before you jump or miss the mark.
Pack the kits and don't forget the salt.
The square peg will settle in the round hole.
Fine soap saves tender skin.
Poached eggs and tea must suffice.
Bad nerves are jangled by a door slam.
Ship maps are different from those for planes.
Dimes showered down from all sides.
They sang the same tunes at each party.
The sky in the west is tinged with orange red.
The pods of peas ferment in bare fields.
The horse balked and threw the tall rider.
The hitch between the horse and cart broke.
Pile the coal high in the shed corner.
A gold vase is both rare and costly.
The knife was hung inside its bright sheath.
The rarest spice comes from the far East.
The roof should be tilted at a sharp slant.
A smatter of French is worse than none.
The mule trod the treadmill day and night.
The aim of the contest is to raise a great fund.
To send it now in large amounts is bad.
There is a fine hard tang in salty air.
Cod is the main business of the north shore.
The slab was hewn from heavy blocks of slate.
Dunk the stale biscuits into strong drink.
Hang tinsel from both branches.
Cap the jar with a tight brass cover.
The poor boy missed the boat again.
Be sure to set the lamp firmly in the hole.
Pick a card and slip it under the pack.
A round mat will cover the dull spot.
The first part of the plan needs changing.
A good book informs of what we ought to know.
The mail comes in three batches per day.
You cannot brew tea in a cold pot.
Dots of light betrayed the black cat.
Put the chart on the mantel and tack it down.
The night shift men rate extra pay.
The red paper brightened the dim stage.
See the player scoot to third base.
Slide the bill between the two leaves.
Many hands help get the job done.
We don't like to admit our small faults.
No doubt about the way the wind blows.
Dig deep in the earth for pirate's gold.
The steady drip is worse than a drenching rain.
A flat pack takes less luggage space.
Green ice frosted the punch bowl.
A stuffed chair slipped from the moving van.
The stitch will serve but needs to be shortened.
A thin book fits in the side pocket.
The gloss on top made it unfit to read.
The hail pattered on the burnt brown grass.
Seven seals were stamped on great sheets.
Our troops are set to strike heavy blows.
The store was jammed before the sale could start.
It was a bad error on the part of the new judge.
One step more and the board will collapse.
Take the match and strike it against your shoe.
The pot boiled, but the contents failed to jell.
The baby puts his right foot in his mouth.
The bombs left most of the town in ruins.
Stop and stare at the hard working man.
The streets are narrow and full of sharp turns.
The pup jerked the leash as he saw a feline shape.
Open your book to the first page.
Fish evade the net and swim off.
Dip the pail once and let it settle.
Will you please answer that phone.
The big red apple fell to the ground.
The curtain rose and the show was on.
The young prince became heir to the throne.
He sent the boy on a short errand.
Leave now and you will arrive on time.
The corner store was robbed last night.
A gold ring will please most any girl.
The long journey home took a year.
She saw a cat in the neighbor's house.
A pink shell was found on the sandy beach.
Small children came to see him.
The grass and bushes were wet with dew.
The blind man counted his old coins.
A severe storm tore down the barn.
She called his name many times.
When you hear the bell, come quickly.
+410
View File
@@ -0,0 +1,410 @@
#!/usr/bin/env python3
"""Record a personal Piper TTS dataset (LJSpeech format) from the microphone.
This is the recording front end for the voice-training pipeline: it reads a
prompts file (default `scripts/voice-prompts-en.txt`, the public-domain Harvard
sentences) and walks the prompts one at a time, writing an LJSpeech dataset
(`metadata.csv` + `wavs/NNNN.wav`) that `scripts/voice-train.sh` consumes on the
training host. See `docs/VOICE-TRAIN.md`.
Two modes:
- **Interactive** (default): a mic check, then each prompt is shown; `Enter`
records, then `Enter` accept / `r` redo / `p` play / `s` skip / `q` quit.
- **Hands-free** (`--speak-prompts` or `--read-prompts`): no keypresses. With
`--speak-prompts` the recorder reads each sentence aloud and you repeat it;
with `--read-prompts` it **prints** each line and beeps (no speech) — read it
aloud. Either way it records until you stop speaking and moves on. It stops
after `--max-misses` consecutive silent prompts.
Recordings are **biometric** and stay under the checkout's gitignored
`.runtime/` tree (default output) — never commit them.
Run it from the checkout with the voice stack installed:
.runtime/venv/bin/python scripts/voice-record.py --list-devices
.runtime/venv/bin/python scripts/voice-record.py --speak-prompts
`Ctrl-C` stops and keeps what is already saved; re-running resumes.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
from semif_agent.voice_train import ( # noqa: E402
DEFAULT_MAX_SECONDS,
DEFAULT_MIN_SPEECH_MS,
DEFAULT_SILENCE_MS,
SAMPLE_RATE,
DatasetStore,
duration_s,
level_report,
load_prompts,
record_until_silence,
)
from semif_agent.voice_transport import ( # noqa: E402
PiperSynthesizer,
SoundDeviceAudio,
_tone_pcm,
resolve_model_path,
)
DEFAULT_PROMPT_VOICE = "en_US-lessac-medium"
def _voice_config(config_path: Path) -> dict:
try:
return ((json.loads(config_path.read_text()).get("gateway", {}) or {}).get(
"voice", {}
) or {})
except Exception:
return {}
def _voice_audio_defaults(config_path: Path) -> tuple[str, str]:
"""The voice gateway's configured input/output devices, if present."""
audio = (_voice_config(config_path).get("audio", {}) or {})
return (
str(audio.get("input_device", "") or ""),
str(audio.get("output_device", "") or ""),
)
def _prompt_voice_default(config_path: Path) -> str:
tts = (_voice_config(config_path).get("tts", {}) or {})
return str(tts.get("voice", "") or DEFAULT_PROMPT_VOICE)
def _list_devices() -> int:
try:
import sounddevice as sd
except Exception as exc: # pragma: no cover - depends on the host stack
print(f"sounddevice is not installed: {exc}")
print("install the voice stack: scripts/bootstrap.sh --voice")
return 2
print(sd.query_devices())
return 0
def _play(audio: SoundDeviceAudio, pcm16: bytes, sample_rate: int) -> None:
if not pcm16:
return
try:
audio.write(pcm16, sample_rate)
except Exception as exc:
print(f" (playback failed: {exc})")
def _level_note(report: dict) -> str:
if report["peak_dbfs"] is None:
return ""
if report["peak_dbfs"] > -1.0:
return " WARNING: clipping — lower the mic gain."
if report["peak_dbfs"] < -30.0:
return " WARNING: very quiet — raise the mic gain."
return ""
# --------------------------------------------------------------------------- #
# interactive mode
# --------------------------------------------------------------------------- #
def _mic_check(audio: SoundDeviceAudio, args: argparse.Namespace) -> bool:
"""Record a short sample, report levels, and let the user accept or retry."""
while True:
print(
f"\nMic check: say a sentence (ends on ~{args.silence_ms} ms of silence, "
f"max {args.mic_check_seconds:.0f}s)."
)
input(" press Enter to record… ")
pcm = record_until_silence(
audio,
sample_rate=args.sample_rate,
frame_ms=args.frame_ms,
max_seconds=args.mic_check_seconds,
silence_ms=args.silence_ms,
min_speech_ms=args.min_speech_ms,
threshold=args.vad_threshold,
read_timeout=args.read_timeout,
)
if not pcm:
print(" no speech detected. Check the input device and mic level")
print(" (alsamixer; PortAudio has no volume control), then retry.")
else:
report = level_report(pcm, args.sample_rate)
print(
f" captured {report['seconds']}s rms={report['rms']} "
f"peak={report['peak']} ({report['peak_dbfs']} dBFS)"
+ _level_note(report)
)
choice = input(" [Enter] start recording, p play back, r retry, q quit: ").strip().lower()
if choice == "q":
return False
if choice == "p":
_play(audio, pcm, args.sample_rate)
continue
if choice == "r":
continue
return True
def _record_prompt(audio: SoundDeviceAudio, args: argparse.Namespace) -> bytes:
"""Record one prompt, letting the user accept / redo / play / skip."""
while True:
input(" press Enter to record… ")
pcm = record_until_silence(
audio,
sample_rate=args.sample_rate,
frame_ms=args.frame_ms,
max_seconds=args.max_seconds,
silence_ms=args.silence_ms,
min_speech_ms=args.min_speech_ms,
threshold=args.vad_threshold,
read_timeout=args.read_timeout,
)
if not pcm:
print(" no speech detected; try again.")
continue
report = level_report(pcm, args.sample_rate)
print(f" recorded {report['seconds']}s peak={report['peak_dbfs']} dBFS")
choice = input(" [Enter] accept, r redo, p play, s skip, q quit: ").strip().lower()
if choice == "q":
raise KeyboardInterrupt
if choice == "r":
continue
if choice == "p":
_play(audio, pcm, args.sample_rate)
continue
if choice == "s":
return b""
return pcm
# --------------------------------------------------------------------------- #
# hands-free (read-aloud) mode
# --------------------------------------------------------------------------- #
def _say(tts, audio: SoundDeviceAudio, text: str, args: argparse.Namespace) -> None:
"""Speak `text` through the output device, then beep (mic is flushed)."""
try:
pcm, rate = tts.synthesize(text)
audio.flush()
audio.write(pcm, rate)
except Exception as exc:
print(f" (prompt playback failed: {exc})")
audio.flush()
cue = _tone_pcm(880, 120, args.sample_rate, 0.4)
if cue:
try:
audio.write(cue, args.sample_rate)
except Exception:
pass
audio.flush()
def _beep(audio: SoundDeviceAudio, args: argparse.Namespace) -> None:
"""Short attention beep (the 'read now' cue) — no speech."""
cue = _tone_pcm(880, 120, args.sample_rate, 0.4)
if not cue:
return
audio.flush()
try:
audio.write(cue, args.sample_rate)
except Exception as exc:
print(f" (beep failed: {exc})")
audio.flush()
def _pending_prompts(prompts, store: DatasetStore, args) -> list[tuple[int, str, str]]:
"""The ``(index, uid, text)`` prompts still to record.
A prompt is pending when its id is not in the dataset, or when `--overwrite`
is set. `--limit` caps how many are returned. This is what the session
prints up front so a resume over a mostly-complete dataset is never
mistaken for a fresh run.
"""
pending: list[tuple[int, str, str]] = []
for index, text in enumerate(prompts, start=1):
uid = f"{index:04d}"
if args.overwrite or uid not in store.ids():
pending.append((index, uid, text))
if args.limit:
pending = pending[: args.limit]
return pending
def _hands_free_session(audio, tts, store: DatasetStore, prompts, args) -> int:
"""Walk prompts: speak (or show + beep) each, record the repeat.
In `--read-prompts` mode the line is printed and a beep cues the take
(no text-to-speech). Stops after `--max-misses` consecutive silent prompts.
"""
speak = not args.read_prompts
recorded = 0
misses = 0
pending = _pending_prompts(prompts, store, args)
if not pending:
print("every prompt is already recorded (pass --overwrite to redo them).")
return 0
print(f"{len(pending)} of {len(prompts)} prompt(s) to record.", flush=True)
if speak:
_say(tts, audio, "Let's begin. Repeat each sentence after the beep.", args)
for position, (_index, uid, text) in enumerate(pending, start=1):
print(f"\n[{position}/{len(pending)}] {text}", flush=True)
pcm = b""
for attempt in range(2):
if speak:
_say(tts, audio, text, args)
else:
_beep(audio, args)
pcm = record_until_silence(
audio,
sample_rate=args.sample_rate,
frame_ms=args.frame_ms,
max_seconds=args.max_seconds,
silence_ms=args.silence_ms,
min_speech_ms=args.min_speech_ms,
threshold=args.vad_threshold,
read_timeout=args.read_timeout,
)
if pcm:
break
if attempt == 0:
print(" no speech heard; repeating the cue…", flush=True)
if not pcm:
misses += 1
print(
f" no speech ({misses}/{args.max_misses}) — skipping; re-run to resume.",
flush=True,
)
if misses >= args.max_misses:
print(" too many silent prompts — stopping so it doesn't run away.", flush=True)
break
continue
misses = 0
store.save(uid, text, pcm)
recorded += 1
report = level_report(pcm, args.sample_rate)
print(
f" saved {uid}.wav ({store.count()} total, {report['seconds']}s)"
+ _level_note(report),
flush=True,
)
return recorded
def main(argv: list[str] | None = None) -> int:
default_in, default_out = _voice_audio_defaults(REPO_ROOT / "config.json")
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--out", default=str(REPO_ROOT / ".runtime" / "voice-train" / "dataset"),
help="dataset directory (metadata.csv + wavs/)")
parser.add_argument("--prompts", default=str(REPO_ROOT / "scripts" / "voice-prompts-en.txt"),
help="prompts file (one sentence per line; # comments skipped)")
parser.add_argument("--device", default=default_in,
help="input device (PortAudio name substring or index; default: config)")
parser.add_argument("--output-device", default=default_out,
help="output device for playback (default: config)")
parser.add_argument("--sample-rate", type=int, default=SAMPLE_RATE)
parser.add_argument("--frame-ms", type=int, default=40)
parser.add_argument("--max-seconds", type=float, default=DEFAULT_MAX_SECONDS,
help="hard cap per utterance")
parser.add_argument("--silence-ms", type=int, default=DEFAULT_SILENCE_MS,
help="trailing silence that ends an utterance")
parser.add_argument("--min-speech-ms", type=int, default=DEFAULT_MIN_SPEECH_MS)
parser.add_argument("--vad-threshold", type=float, default=200.0,
help="int16 RMS above which a frame counts as speech")
parser.add_argument("--read-timeout", type=float, default=3.0,
help="seconds with no audio frame before a take is ended (guards a dropped device)")
parser.add_argument("--mic-check-seconds", type=float, default=20.0,
help="hard cap for the mic-check sample")
parser.add_argument("--skip-mic-check", action="store_true")
parser.add_argument("--limit", type=int, default=0, help="record at most N prompts")
parser.add_argument("--overwrite", action="store_true",
help="re-record prompts whose id is already saved")
parser.add_argument("--speak-prompts", action="store_true",
help="hands-free: speak each prompt aloud and record the repeat (no keypresses)")
parser.add_argument("--read-prompts", action="store_true",
help="hands-free: print each line and beep (no speech); read it aloud, recorded")
parser.add_argument("--max-misses", type=int, default=3,
help="stop after this many consecutive silent prompts in --speak-prompts mode")
parser.add_argument("--prompt-voice", default=_prompt_voice_default(REPO_ROOT / "config.json"),
help="Piper voice used to read the prompts in --speak-prompts mode")
parser.add_argument("--list-devices", action="store_true")
args = parser.parse_args(argv)
if args.list_devices:
return _list_devices()
prompts = load_prompts(args.prompts)
if not prompts:
print(f"no prompts found in {args.prompts}")
return 2
store = DatasetStore(args.out, sample_rate=args.sample_rate)
print(f"dataset: {store.out} ({store.count()} already recorded)")
print(f"prompts: {len(prompts)} target rate: {args.sample_rate} Hz")
audio = SoundDeviceAudio(input_device=args.device, output_device=args.output_device)
try:
audio.open_input(args.sample_rate, args.frame_ms, "")
except Exception as exc:
print(f"could not open input device {args.device!r}: {exc}")
print("list devices with --list-devices; install the stack with scripts/bootstrap.sh --voice")
return 2
tts = None
if args.speak_prompts:
voice_path = resolve_model_path(
args.prompt_voice, str(REPO_ROOT / ".runtime" / "voice" / "tts"), (".onnx",)
)
try:
tts = PiperSynthesizer(voice_path)
except Exception as exc:
print(f"could not load the prompt voice {voice_path!r}: {exc}")
print("download it with scripts/voice-models.py, or pass --prompt-voice <path>")
audio.close()
return 2
recorded = 0
try:
if args.speak_prompts or args.read_prompts:
recorded = _hands_free_session(audio, tts, store, prompts, args)
else:
if not args.skip_mic_check and not _mic_check(audio, args):
print("aborted at mic check.")
return 1
pending = _pending_prompts(prompts, store, args)
if not pending:
print("every prompt is already recorded (pass --overwrite to redo them).")
return 0
print(f"{len(pending)} of {len(prompts)} prompt(s) to record.")
for position, (_index, uid, text) in enumerate(pending, start=1):
print(f"\n[{position}/{len(pending)}] Say: {text}")
pcm = _record_prompt(audio, args)
if not pcm:
print(" skipped.")
continue
path = store.save(uid, text, pcm)
recorded += 1
print(f" saved {path.name} ({store.count()} total, {duration_s(pcm, args.sample_rate):.1f}s)")
except KeyboardInterrupt:
print("\nstopping (already-recorded prompts are saved).")
finally:
audio.close()
print(f"\ndone: {recorded} recorded this session, {store.count()} total in {store.out}")
print(f"metadata: {store.metadata}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env bash
# Train a custom Piper TTS voice for the voice gateway from a recorded dataset.
#
# Runs on the TRAINING host (a machine with a real GPU), NOT on the gateway host
# that will use the voice. Everything it installs lives inside this checkout
# under .runtime/voice-train/ (gitignored): the piper1-gpl clone, its venv, the
# base checkpoint, the training cache, runs, and the exported voice. Only the
# finished <name>.onnx + <name>.onnx.json are copied to a gateway host.
#
# It fine-tunes from a pinned "medium" checkpoint (Piper has no zero-shot
# cloning; ~15-60 min of recorded audio gives a usable voice). The dataset is an
# LJSpeech directory (metadata.csv + wavs/) produced by scripts/voice-record.py.
# See docs/VOICE-TRAIN.md.
#
# Pinned external refs (piper1-gpl commit, base checkpoint url+sha256) live in the
# committed pins.json; bump those via git and rerun to upgrade.
#
# Usage:
# scripts/voice-train.sh --name en_US-myvoice-medium [--dataset DIR] [--work DIR]
# [--quality medium] [--espeak-voice en-us]
# [--batch-size 16] [--max-epochs 2000]
# [--checkpoint PATH_OR_URL] [--torch-index-url URL]
# [--torch-spec "torch torchaudio"]
# [--free-gpu] [--resume] [--skip-setup|--skip-train|--skip-export] [-h]
set -euo pipefail
NAME="en_US-custom-medium"
DATASET=""
WORK=""
QUALITY="medium"
ESPEAK_VOICE="en-us"
SAMPLE_RATE="22050"
BATCH_SIZE="16"
MAX_EPOCHS="2000"
CHECKPOINT=""
TORCH_INDEX_URL="https://download.pytorch.org/whl/nightly/rocm7.1"
TORCH_SPEC="torch torchaudio"
FREE_GPU=0
RESUME=0
SKIP_SETUP=0
SKIP_TRAIN=0
SKIP_EXPORT=0
usage() {
sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
echo
echo " --name ID voice id / output basename (default: $NAME)"
echo " --dataset DIR LJSpeech dataset dir (metadata.csv + wavs/)"
echo " --work DIR scratch dir (default: .runtime/voice-train)"
echo " --quality Q medium|high|low (must match the checkpoint; default medium)"
echo " --espeak-voice V espeak-ng voice (default en-us)"
echo " --sample-rate HZ dataset sample rate (default 22050)"
echo " --batch-size N training batch size (default 16; 16 GB VRAM)"
echo " --max-epochs N trainer.max_epochs (default 2000; fine-tune ~1000-3000)"
echo " --checkpoint P|URL base .ckpt to fine-tune from (default: pinned in pins.json)"
echo " --torch-index-url U ROCm wheel index for torch (default: $TORCH_INDEX_URL)"
echo " --torch-spec SPEC torch packages to install (default: \"$TORCH_SPEC\")"
echo " --free-gpu stop winnow + unload ollama models before training"
echo " --resume resume from the newest run checkpoint under --work"
echo " --skip-setup skip apt/clone/venv/torch/deps (reuse an existing env)"
echo " --skip-train skip training (e.g. export an existing run)"
echo " --skip-export stop after training"
echo " -h this help"
exit "${1:-0}"
}
while [[ $# -gt 0 ]]; do
case "$1" in
--name) NAME="$2"; shift 2 ;;
--dataset) DATASET="$2"; shift 2 ;;
--work) WORK="$2"; shift 2 ;;
--quality) QUALITY="$2"; shift 2 ;;
--espeak-voice) ESPEAK_VOICE="$2"; shift 2 ;;
--sample-rate) SAMPLE_RATE="$2"; shift 2 ;;
--batch-size) BATCH_SIZE="$2"; shift 2 ;;
--max-epochs) MAX_EPOCHS="$2"; shift 2 ;;
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
--torch-index-url) TORCH_INDEX_URL="$2"; shift 2 ;;
--torch-spec) TORCH_SPEC="$2"; shift 2 ;;
--free-gpu) FREE_GPU=1; shift ;;
--resume) RESUME=1; shift ;;
--skip-setup) SKIP_SETUP=1; shift ;;
--skip-train) SKIP_TRAIN=1; shift ;;
--skip-export) SKIP_EXPORT=1; shift ;;
-h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;;
esac
done
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# apt/systemctl as root directly when the container has no sudo (common on cloud
# GPU images); fall back to sudo on a normal host.
if [[ "$(id -u)" -eq 0 ]]; then
SUDO=""
elif command -v sudo >/dev/null 2>&1; then
SUDO="sudo"
else
SUDO=""
fi
PINS="$REPO_ROOT/pins.json"
[[ -f "$PINS" ]] || { echo "pins.json not found at $PINS — run from a semif-agent checkout" >&2; exit 1; }
WORK="${WORK:-$REPO_ROOT/.runtime/voice-train}"
DATASET="${DATASET:-$WORK/dataset}"
PIPER_DIR="$WORK/piper1-gpl"
VENV="$WORK/venv"
PY="$VENV/bin/python"
PIP="$VENV/bin/pip"
CACHE="$WORK/cache"
RUNS="$WORK/runs"
OUT="$WORK/out"
CKPTS="$WORK/checkpoints"
COMPAT="$WORK/torch_compat"
# --- read the voice pins from the committed pins.json -----------------------
IFS=$'\x1f' read -r PIPER_REPO PIPER_REF CKPT_URL CKPT_SHA < <(
python3 - "$PINS" <<'PY'
import json, sys
pins = json.load(open(sys.argv[1]))
v = pins.get("voice", {})
print("\x1f".join([
str(v.get("piper_train_repo", "")),
str(v.get("piper_train_ref", "")),
str(v.get("base_checkpoint_url", "")),
str(v.get("base_checkpoint_sha256", "")),
]))
PY
)
[[ -n "$PIPER_REPO" && -n "$PIPER_REF" ]] || {
echo "pins.json is missing the voice.piper_train_repo/ref entries" >&2; exit 1; }
echo "== voice training: $NAME"
echo " work: $WORK"
echo " dataset: $DATASET"
echo " piper: $PIPER_REPO @ ${PIPER_REF:0:12}"
mkdir -p "$WORK" "$CKPTS" "$OUT" "$RUNS" "$COMPAT"
# PyTorch >=2.6 defaults `torch.load` to weights_only=True, and Lightning passes
# it explicitly, so loading the pinned base checkpoint fails on the
# `pathlib.PosixPath` pickled into its hyperparameters. Allowlist it for the
# training/export interpreter only (via a sitecustomize on PYTHONPATH), which is
# the fix PyTorch's own error recommends. See docs/VOICE-TRAIN.md.
cat > "$COMPAT/sitecustomize.py" <<'PY'
import pathlib
try:
from torch.serialization import add_safe_globals
add_safe_globals([pathlib.PosixPath])
except Exception: # pragma: no cover - best effort; old torch has no such API
pass
PY
# --- stage 1: dataset check (only needed to actually train) -----------------
if [[ "$SKIP_TRAIN" != "1" ]]; then
if [[ ! -f "$DATASET/metadata.csv" ]]; then
echo "no dataset at $DATASET/metadata.csv — record one first:" >&2
echo " python scripts/voice-record.py --out '$DATASET'" >&2
exit 1
fi
N_UTT=$(grep -c '|' "$DATASET/metadata.csv" || true)
echo "== dataset: $N_UTT utterances"
if [[ "$N_UTT" -lt 50 ]]; then
echo "WARN: fewer than 50 utterances — the voice will be rough (aim for 200-450+)" >&2
fi
elif [[ -f "$DATASET/metadata.csv" ]]; then
echo "== dataset present ($(grep -c '|' "$DATASET/metadata.csv" || true) utterances); --skip-train set"
else
echo "== no dataset yet; --skip-train set, so this is a setup/GPU smoke test"
fi
# --- stage 2: free the GPU (opt-in) -----------------------------------------
if [[ "$FREE_GPU" == "1" ]]; then
echo "== freeing the GPU"
if systemctl list-unit-files 2>/dev/null | grep -q '^winnow\.service'; then
$SUDO systemctl stop winnow 2>/dev/null || true
fi
if command -v ollama >/dev/null 2>&1; then
ollama ps 2>/dev/null | tail -n +2 | awk '{print $1}' | while read -r m; do
[[ -n "$m" ]] && ollama stop "$m" 2>/dev/null || true
done
fi
else
if systemctl is-active --quiet winnow 2>/dev/null; then
echo "WARN: winnow.service is active and holds the GPU; pass --free-gpu (or stop it) to avoid OOM" >&2
fi
fi
# --- stage 3: system prerequisites + piper checkout + venv ------------------
if [[ "$SKIP_SETUP" != "1" ]]; then
missing=()
for pkg in espeak-ng build-essential cmake python3-dev python3-venv git; do
dpkg -s "$pkg" >/dev/null 2>&1 || missing+=("$pkg")
done
if [[ ${#missing[@]} -gt 0 ]]; then
echo "== installing system prereqs: ${missing[*]}"
$SUDO apt-get update -qq
$SUDO apt-get install -y "${missing[@]}"
fi
if [[ ! -d "$PIPER_DIR/.git" ]]; then
echo "== cloning piper1-gpl"
git clone "$PIPER_REPO" "$PIPER_DIR"
fi
echo "== checking out piper1-gpl @ ${PIPER_REF:0:12}"
git -C "$PIPER_DIR" fetch --all --tags --quiet
git -C "$PIPER_DIR" checkout --quiet "$PIPER_REF"
if [[ ! -x "$PY" ]]; then
echo "== creating venv at $VENV"
python3 -m venv "$VENV"
"$PIP" install --upgrade pip wheel setuptools >/dev/null
fi
if ! "$PY" -c 'import torch' >/dev/null 2>&1; then
echo "== installing torch from $TORCH_INDEX_URL (this may take a while)"
# shellcheck disable=SC2086
"$PIP" install --index-url "$TORCH_INDEX_URL" $TORCH_SPEC
fi
echo "== installing piper1-gpl [train]"
"$PIP" install -e "${PIPER_DIR}[train]"
# The editable install builds the CMake extension `espeakbridge` in its
# isolated build env but does not expose it from the source tree, so
# `from piper import espeakbridge` fails at run time. Run the documented
# in-place dev build to place the compiled extensions under src/.
if ! "$PY" -c 'from piper import espeakbridge' >/dev/null 2>&1; then
echo "== building piper1-gpl C extensions in place (espeakbridge)"
"$PIP" install -q scikit-build cmake ninja "cython>=3,<4"
( cd "$PIPER_DIR" && "$PY" setup.py build_ext --inplace )
fi
if [[ -x "$PIPER_DIR/build_monotonic_align.sh" ]]; then
echo "== building monotonic_align"
( source "$VENV/bin/activate" && cd "$PIPER_DIR" && ./build_monotonic_align.sh )
fi
echo "== torch device check"
"$PY" - <<'PY'
import torch
print(f" torch {torch.__version__} hip={getattr(torch.version, 'hip', None)} "
f"cuda_available={torch.cuda.is_available()}")
if not torch.cuda.is_available():
print(" WARN: no GPU visible to torch — training will be CPU-only and very slow.")
print(" check the ROCm torch wheel matches this GPU (gfx target).")
else:
print(f" device: {torch.cuda.get_device_name(0)}")
PY
fi
# --- stage 4: base checkpoint ------------------------------------------------
if [[ -z "$CHECKPOINT" ]]; then
if [[ -n "$CKPT_URL" ]]; then
CHECKPOINT="$CKPTS/$(basename "$CKPT_URL")"
if [[ ! -f "$CHECKPOINT" ]]; then
echo "== downloading base checkpoint"
curl -fL --retry 3 -o "$CHECKPOINT" "$CKPT_URL"
fi
if [[ -n "$CKPT_SHA" ]]; then
echo "== verifying checkpoint sha256"
echo "$CKPT_SHA $CHECKPOINT" | sha256sum -c -
fi
fi
fi
if [[ -n "$CHECKPOINT" ]]; then
echo "== fine-tuning from: $CHECKPOINT"
else
echo "== WARN: no base checkpoint; training from scratch (much slower, lower quality)" >&2
fi
# --- stage 5: train ----------------------------------------------------------
if [[ "$SKIP_TRAIN" != "1" ]]; then
# `--resume` continues a run (Lightning `--ckpt_path`, which also restores the
# optimizer/loop state). A fresh fine-tune warmstarts the model weights from
# the base checkpoint with `--model.warmstart_ckpt`: unlike `--ckpt_path` it
# does not re-parse the base checkpoint's hyperparameters, which is required
# for the pinned older checkpoints on a newer piper1-gpl (their saved
# `model.*` config no longer matches the current model signature).
WARMSTART_CKPT="$CHECKPOINT"
RESUME_CKPT=""
if [[ "$RESUME" == "1" ]]; then
LATEST="$(find "$RUNS" -name '*.ckpt' -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2- || true)"
[[ -n "$LATEST" ]] && { echo "== resuming from $LATEST"; RESUME_CKPT="$LATEST"; }
fi
echo "== training ($MAX_EPOCHS epochs, batch $BATCH_SIZE) — this runs for hours; Ctrl-C is safe"
FIT_ARGS=(
--data.voice_name "$NAME"
--data.csv_path "$DATASET/metadata.csv"
--data.audio_dir "$DATASET/wavs"
--data.cache_dir "$CACHE"
--data.config_path "$OUT/$NAME.onnx.json"
--data.espeak_voice "$ESPEAK_VOICE"
--data.batch_size "$BATCH_SIZE"
# Keep piper's held-out validation (default 0.1) and test (default 5)
# splits. The default ModelCheckpoint callbacks monitor `val_mel` and
# `val_mos`; `val_mos` is scored over the *test* split, so zeroing either
# split leaves the callback without its metric and Lightning aborts the
# run — and no checkpoint is written for the export step to use.
--model.sample_rate "$SAMPLE_RATE"
--trainer.max_epochs "$MAX_EPOCHS"
--trainer.accelerator gpu
--trainer.devices 1
--trainer.default_root_dir "$RUNS"
)
if [[ -n "$RESUME_CKPT" ]]; then
FIT_ARGS+=( --ckpt_path "$RESUME_CKPT" )
elif [[ -n "$WARMSTART_CKPT" ]]; then
FIT_ARGS+=( --model.warmstart_ckpt "$WARMSTART_CKPT" )
fi
PYTHONPATH="$COMPAT${PYTHONPATH:+:$PYTHONPATH}" "$PY" -m piper.train fit "${FIT_ARGS[@]}"
fi
# --- stage 6: export ---------------------------------------------------------
if [[ "$SKIP_EXPORT" != "1" ]]; then
CKPT="$(find "$RUNS" -name '*.ckpt' -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2- || true)"
if [[ -z "$CKPT" ]]; then
echo "no training checkpoint found under $RUNS — nothing to export" >&2
exit 1
fi
echo "== exporting $CKPT -> $OUT/$NAME.onnx"
PYTHONPATH="$COMPAT${PYTHONPATH:+:$PYTHONPATH}" "$PY" -m piper.train.export_onnx --checkpoint "$CKPT" --output-file "$OUT/$NAME.onnx"
if [[ ! -f "$OUT/$NAME.onnx.json" ]]; then
echo "WARN: $OUT/$NAME.onnx.json missing (config is written during training)" >&2
fi
fi
echo
echo "== done. voice files:"
ls -la "$OUT" 2>/dev/null || true
cat <<EOF
Next: copy the voice to a gateway host and select it.
rsync -av '$OUT/$NAME.onnx' '$OUT/$NAME.onnx.json' \\
<gateway-host>:'<checkout>/.runtime/voice/tts/'
Then set in that host's config.json (gateway.voice.tts.voice_dir is anchored to
.runtime/voice/tts automatically):
"tts": { "voice": "$NAME", ... }
Restart the gateway and speak a reply to verify — a passing skill test is not
proof the integration works; only a real spoken reply is.
EOF
+241
View File
@@ -0,0 +1,241 @@
#!/usr/bin/env python3
"""Check a recorded Piper dataset against its prompts with Whisper.
The recording front end (`scripts/voice-record.py`) resumes by prompt id and
trusts you to accept each take, so a silent false start or a take read from the
wrong line slips in silently. This verifier transcribes every `wavs/<id>.wav`
with faster-whisper and compares it to the prompt recorded for that id in
`metadata.csv`, flagging the ones to re-record.
Statuses:
- ``missing`` — a metadata row whose wav is gone.
- ``empty`` — Whisper heard no speech (a silent / false-start take).
- ``mismatch`` — the transcript differs from the prompt by more than `--max-wer`.
- ``review`` — between `--review-wer` and `--max-wer`: listen, because
Whisper's own spelling/number variants land here (e.g. "two plus seven" ->
"2 plus 7"); not treated as a failure.
- ``ok`` — below `--review-wer`.
Run it from the checkout with the voice stack installed:
.runtime/venv/bin/python scripts/voice-verify.py --model small.en
.runtime/venv/bin/python scripts/voice-verify.py --json .runtime/voice-train/verify.json
# mark the flagged takes for re-recording (bad + review) from that report:
.runtime/venv/bin/python scripts/voice-verify.py \
--from-json .runtime/voice-train/verify.json --prune --prune-review
`--prune` moves each flagged wav into `<dataset>/rejected/` and drops its
metadata row, so re-running the recorder re-records exactly those prompts; it is
off by default (run once and listen, or keep the `--json` report, first).
`--prune-review` also marks the `review` band. `--from-json` reuses a previous
report instead of transcribing again. Recordings are biometric — never commit
them.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
# The voice models live in the checkout's .runtime/hf cache (bootstrap sets this
# for the gateway); default it here so the verifier finds the cached Whisper
# model instead of downloading one into ~/.cache.
os.environ.setdefault("HF_HOME", str(REPO_ROOT / ".runtime" / "hf"))
from semif_agent.voice_train import ( # noqa: E402
BAD_STATUSES,
SAMPLE_RATE,
DatasetStore,
compare_transcript,
duration_s,
read_wav,
resample_pcm16,
)
from semif_agent.voice_transport import WhisperTranscriber # noqa: E402
#: faster-whisper's model input rate (the transcriber contract).
WHISPER_RATE = 16000
def _parse_args(argv: list[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--dataset", default=str(REPO_ROOT / ".runtime" / "voice-train" / "dataset"),
help="LJSpeech dataset dir (metadata.csv + wavs/)",
)
parser.add_argument("--model", default="base.en",
help="faster-whisper model size or path (default: base.en)")
parser.add_argument("--device", default="cpu", help="inference device (default: cpu)")
parser.add_argument("--compute-type", default="int8",
help="CTranslate2 compute type (default: int8)")
parser.add_argument("--language", default="en", help="spoken language (default: en)")
parser.add_argument("--beam-size", type=int, default=5,
help="Whisper beam size; higher is more accurate/slower (default: 5)")
parser.add_argument("--max-wer", type=float, default=0.5,
help="word error rate above which a take fails (default: 0.5)")
parser.add_argument("--review-wer", type=float, default=0.35,
help="word error rate at/above which a take is listed for "
"review but does not fail (default: 0.35)")
parser.add_argument("--limit", type=int, default=0,
help="verify at most N recordings (for a quick smoke test)")
parser.add_argument("--all", action="store_true",
help="print every recording, not just the flagged ones")
parser.add_argument("--json", dest="json_path", default="",
help="write the full report to this JSON file")
parser.add_argument("--prune", action="store_true",
help="move flagged wavs to <dataset>/rejected/ and drop their rows")
parser.add_argument("--prune-review", action="store_true",
help="also prune the 'review' band (Whisper-variant candidates)")
parser.add_argument("--reject-dir", default="",
help="where --prune moves bad takes (default: <dataset>/rejected)")
parser.add_argument("--from-json", default="",
help="reuse a previous --json report instead of transcribing again")
parser.add_argument("--quiet", action="store_true",
help="suppress the per-file progress and print only the summary")
return parser.parse_args(argv)
def _resample_to_whisper(pcm16: bytes, rate: int) -> bytes:
if rate == WHISPER_RATE:
return pcm16
return resample_pcm16(pcm16, rate, WHISPER_RATE)
def _transcribe_dataset(store, ids, args) -> tuple[list[dict], float]:
"""Transcribe each wav and compare it to its prompt."""
transcriber = WhisperTranscriber(
model=args.model,
device=args.device,
compute_type=args.compute_type,
language=args.language,
beam_size=args.beam_size,
)
report: list[dict] = []
total_seconds = 0.0
for index, uid in enumerate(ids, start=1):
reference = store.entries[uid]
wav = store.wav_path(uid)
result = {"id": uid, "reference": reference}
if not wav.is_file():
result.update(compare_transcript(reference, "", args.max_wer, args.review_wer))
result["status"] = "missing"
result["hypothesis"] = ""
result["seconds"] = 0.0
else:
pcm16, rate = read_wav(wav)
seconds = duration_s(pcm16, rate)
total_seconds += seconds
hypothesis = transcriber.transcribe(_resample_to_whisper(pcm16, rate))
result.update(
compare_transcript(reference, hypothesis, args.max_wer, args.review_wer)
)
result["hypothesis"] = hypothesis
result["seconds"] = round(seconds, 2)
report.append(result)
if not args.quiet and sys.stderr.isatty() and index % 25 == 0:
print(f"\r {index}/{len(ids)} …", end="", file=sys.stderr)
if not args.quiet and sys.stderr.isatty():
print("\r" + " " * 24 + "\r", end="", file=sys.stderr)
return report, total_seconds
def _prune(store, ids, reject_dir: Path) -> int:
"""Move each id's wav aside and drop its metadata row; return how many moved."""
reject_dir.mkdir(parents=True, exist_ok=True)
moved = 0
for uid in ids:
src = store.wav_path(uid)
if src.is_file():
src.replace(reject_dir / src.name)
moved += 1
store.remove(uid)
return moved
def main(argv: list[str] | None = None) -> int:
args = _parse_args(argv)
store = DatasetStore(args.dataset, sample_rate=SAMPLE_RATE)
if store.count() == 0:
print(f"no dataset at {store.out} (metadata.csv is empty or missing)", file=sys.stderr)
print("record one first: python scripts/voice-record.py", file=sys.stderr)
return 2
if args.from_json:
payload = json.loads(Path(args.from_json).read_text(encoding="utf-8"))
report = payload.get("results", [])
counts = dict(payload.get("counts", {}))
bad = list(payload.get("bad_ids", []))
review = list(payload.get("review_ids", []))
total_seconds = sum(float(r.get("seconds", 0.0)) for r in report)
args.model = payload.get("model", args.model)
args.beam_size = payload.get("beam_size", args.beam_size)
else:
ids = sorted(store.entries)
if args.limit:
ids = ids[: args.limit]
report, total_seconds = _transcribe_dataset(store, ids, args)
counts = {}
bad, review = [], []
for result in report:
counts[result["status"]] = counts.get(result["status"], 0) + 1
if result["status"] in BAD_STATUSES:
bad.append(result["id"])
elif result["status"] == "review":
review.append(result["id"])
if not args.quiet:
for result in report:
status = result["status"]
if args.all or status in BAD_STATUSES or status == "review":
print(f"{result['id']} {status:<8} wer={result['wer']:.2f} "
f"ref: {result['reference']}")
print(f" hyp: {result['hypothesis']!r}")
prune_ids = list(bad) + (list(review) if args.prune_review else [])
if args.prune and prune_ids:
reject_dir = Path(args.reject_dir) if args.reject_dir else store.out / "rejected"
moved = _prune(store, prune_ids, reject_dir)
print(f"pruned {moved} take(s) to {reject_dir}; re-run the recorder to redo them")
print(
f"\nchecked {len(report)} recording(s), {total_seconds / 60:.1f} min audio "
f"model={args.model} beam={args.beam_size} "
f"max-wer={args.max_wer} review-wer={args.review_wer}"
)
order = ["ok", "review", "mismatch", "empty", "missing"]
print(" " + " ".join(f"{name}: {counts.get(name, 0)}" for name in order))
if bad:
print(f" re-record {len(bad)}: {' '.join(bad)}")
else:
print(" no take failed the fidelity check.")
if review:
print(f" review (listen; likely Whisper variants) {len(review)}: {' '.join(review)}")
if args.json_path:
payload = {
"dataset": str(store.out),
"model": args.model,
"beam_size": args.beam_size,
"max_wer": args.max_wer,
"review_wer": args.review_wer,
"counts": counts,
"bad_ids": bad,
"review_ids": review,
"results": report,
}
Path(args.json_path).write_text(json.dumps(payload, indent=2), encoding="utf-8")
print(f"report: {args.json_path}")
return 1 if bad else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -1,8 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Create a calendar event from a request such as \"add Ashley's dance recital for 5pm Tuesday\"."
}
-626
View File
@@ -1,626 +0,0 @@
"""Create a calendar event on the user's Nextcloud calendar from a request.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` reads `request.text` and derives the event's per-request arguments. The
title and description are extracted by the local LLM bridge (`llm_bridge_url`,
`llm_bridge_token`) with one generic chat call, cached in `request.meta` so a
`needs_input` resume does not re-call it; the start date/time and duration are
parsed deterministically. Missing arguments are asked one at a time and the
answer is stashed in `request.meta`; because `act` is single-phase and re-runs
from the top after a `needs_input` pause, the body never re-asks a question it
already has an answer for. Calendars are discovered over PROPFIND and the target
is resolved by a single SemIf choice over every owned calendar (state = the user
query), asking which one the request refers to; a strong winner (probability >=
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is
used. The event is created with a real CalDAV PUT (iCalendar, UTC timestamps,
`If-None-Match: *`) and the real outcome is reported.
The date/time parse is deliberately bounded; the title/description come from the
model. When the model bridge is unavailable the body reports the real failure
rather than guessing.
"""
from __future__ import annotations
import base64
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from datetime import datetime, time, timedelta, timezone
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
class BridgeError(Exception):
"""A real failure talking to the local LLM bridge."""
def _now():
"""Current local time (aware). A test seam; the body never freezes time."""
return datetime.now().astimezone()
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0", content_type="application/xml; charset=utf-8", extra_headers=None):
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
headers = {"Authorization": f"Basic {token}", "Depth": depth}
if body is not None:
headers["Content-Type"] = content_type
if extra_headers:
headers.update(extra_headers)
request = urllib.request.Request(
url + path, data=body, method=method, headers=headers
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.status, response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
_status, body = _request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")
calendars = []
for response in _multistatus(body).findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
# ---- LLM field extraction ----
def _extract_fields(ctx, request):
"""Ask the LLM bridge for the event title and description.
One generic `POST /chat` call to the local LLM bridge; the reply is the JSON
object the prompt asks for. Raises `BridgeError` when the bridge is
unreachable or the reply carries no usable object.
"""
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BridgeError("llm_bridge_url is not configured")
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
messages = [
{
"role": "system",
"content": (
"Extract the calendar event from the user's request. Reply with "
'ONLY a JSON object: {"title": "<short event title>", '
'"description": "<one short sentence, or empty>"}. The title must '
"not contain the date, the time, or words like add/schedule/create."
),
},
{"role": "user", "content": request.text},
]
payload = json.dumps({"messages": messages}).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(
base + "/chat", data=payload, method="POST", headers=headers
)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"llm bridge /chat: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"llm bridge /chat: {exc}") from exc
return _parse_fields(str(data.get("text") or ""))
def _parse_fields(text):
"""Pull the `{"title","description"}` object out of the model's reply."""
start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start:
raise BridgeError("llm bridge returned no JSON object")
try:
data = json.loads(text[start : end + 1])
except ValueError as exc:
raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc
if not isinstance(data, dict):
raise BridgeError("llm bridge returned JSON that is not an object")
return {
"title": str(data.get("title") or "").strip(),
"description": str(data.get("description") or "").strip(),
}
def _month_number(token):
return _MONTHS.get(token.lower()[:3])
def _resolve_month_day(month, day, year, now):
if not (month and 1 <= day <= 31):
return None
given_year = year is not None
year = year or now.year
try:
candidate = datetime(year, month, day).date()
except ValueError:
return None
if not given_year and candidate < now.date():
try:
candidate = datetime(year + 1, month, day).date()
except ValueError:
return None
return candidate
def _parse_when(text, now):
"""Best-effort extraction of date/time/duration from free text.
Returns a dict with `date` (datetime.date | None), `time` (datetime.time |
None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday`
(bool). The title and description come from the LLM bridge, so no matched
spans are tracked here.
"""
text = text or ""
result = {
"date": None,
"time": None,
"all_day": False,
"duration_minutes": None,
"from_weekday": False,
}
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match:
result["all_day"] = True
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match:
result["duration_minutes"] = int(match.group(1))
else:
for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30),
(r"\bfor\s+an?\s+hour\b", 60),
(r"\bfor\s+a\s+couple\s+of\s+hours\b", 120),
):
match = re.search(phrase, text, re.I)
if match:
result["duration_minutes"] = minutes
break
date = None
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
date = datetime(
int(match.group(1)), int(match.group(2)), int(match.group(3))
).date()
except ValueError:
date = None
if date is None:
match = re.search(
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now)
if date is None:
match = re.search(
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now)
if date is None:
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text)
if match:
first, second = int(match.group(1)), int(match.group(2))
month, day = (first, second) if first <= 12 else (second, first)
year = int(match.group(3)) if match.group(3) else None
if year is not None and year < 100:
year += 2000
date = _resolve_month_day(month, day, year, now)
if date is None:
match = re.search(
r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I
)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
date = now.date()
elif word in ("tomorrow", "tmrw", "tomorow"):
date = now.date() + timedelta(days=1)
else:
date = now.date() + timedelta(days=7)
if date is None:
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
prefix = text[max(0, match.start() - 6):match.start()]
if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7)
result["from_weekday"] = True
parsed_time = None
match = re.search(r"\bnoon\b", text, re.I)
if match:
parsed_time = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed_time = time(int(match.group(1)), 0)
result["date"] = date
result["time"] = parsed_time
return result
# ---- calendar resolution ----
def _resolve_calendar(ctx, request, calendars, decisions):
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
default = None
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
default = calendar
break
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar ----
def _escape_ics(value):
return (
str(value)
.replace("\\", "\\\\")
.replace(";", "\\;")
.replace(",", "\\,")
.replace("\r\n", "\\n")
.replace("\n", "\\n")
.replace("\r", "\\n")
)
def _utc_stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//semif-agent//calendar.create_event//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{stamp}",
]
if all_day:
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
else:
lines.append(f"DTSTART:{_utc_stamp(start)}")
lines.append(f"DTEND:{_utc_stamp(end)}")
lines.append(f"SUMMARY:{_escape_ics(summary)}")
if description:
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
lines += ["END:VEVENT", "END:VCALENDAR", ""]
return "\r\n".join(lines).encode("utf-8")
# ---- skill phases ----
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(
action_log=f"calendar.create_event: waiting for {field}",
new_state=request.text,
needs_input=question,
)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
if answers.get(awaiting) != request.user_input.strip():
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
fields = request.meta.get("create_event_fields")
if fields is None:
try:
fields = _extract_fields(ctx, request)
except BridgeError as exc:
return ActionResult(
action_log=f"calendar.create_event: {exc}",
new_state=request.text,
)
request.meta["create_event_fields"] = fields
title = fields["title"]
description = fields["description"]
now = _now()
parsed = _parse_when(request.text, now)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
parsed["from_weekday"] = extra["from_weekday"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
local_tz = now.tzinfo or timezone.utc
all_day = bool(parsed["all_day"])
if all_day:
start_date = parsed["date"]
end_date = start_date + timedelta(days=1)
start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz)
end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz)
else:
start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz)
if start <= now and parsed.get("from_weekday"):
start += timedelta(days=7)
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
end = start + duration
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.create_event: calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar.create_event: no calendars found on the account",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
uid = f"{uuid.uuid4().hex}@semif-agent"
body = _build_ics(
uid, title, start, end, all_day, _utc_stamp(now), description=description
)
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try:
_request(
ctx,
"PUT",
path,
body=body,
depth="0",
content_type="text/calendar; charset=utf-8",
extra_headers={"If-None-Match": "*"},
)
except CalDavError as exc:
return ActionResult(
action_log=(
f"calendar.create_event: could not create {title!r} on "
f"{calendar!r}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if all_day:
when_text = f"{start_date.isoformat()} (all day)"
else:
when_text = (
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
f"{end.strftime('%H:%M %Z')}"
)
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
return ActionResult(
action_log=f"calendar.create_event: {report}",
new_state=report,
decisions=decisions,
)
-451
View File
@@ -1,451 +0,0 @@
"""Hermetic mechanics test for calendar.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
and description through the LLM bridge (caching the call across a `needs_input`
resume), parses the date/time from the request, asks for a missing field and
resumes, resolves the target calendar with a SemIf choice over the owned
calendars (a strong winner is used, otherwise the configured default), writes a
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
It does NOT prove the live integration — only a real run against the user's
Nextcloud does.
"""
import json
import sys
import threading
import urllib.parse
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda: FIXED_NOW
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
def next_weekday(now, weekday):
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
calendars = []
put_status = 201
requests = []
puts = []
llm_reply = DEFAULT_LLM_REPLY
llm_status = 200
llm_requests = []
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status, content_type):
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._read_body()
self.requests.append(("PROPFIND", self.path))
responses = []
for calendar in self.calendars:
responses.append(
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
f'{calendar["name"]}/</d:href>'
f"<d:propstat><d:prop>"
f'<d:displayname>{calendar["label"]}</d:displayname>'
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
f"</d:response>"
)
body = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
+ "".join(responses)
+ "</d:multistatus>"
)
self._send(body, 207, "application/xml; charset=utf-8")
def do_PUT(self):
body = self._read_body()
self.puts.append(
{"path": self.path, "body": body, "headers": dict(self.headers)}
)
self._send(b"", self.put_status, "text/plain")
def do_POST(self):
body = self._read_body()
if self.path != "/chat":
self._send(json.dumps({"error": "not found"}), 404, "application/json")
return
self.llm_requests.append(body)
if self.llm_status != 200:
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
return
self._send(
json.dumps({"text": json.dumps(self.llm_reply)}),
200,
"application/json",
)
def log_message(self, *args):
pass
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
handler = type(
"Handler",
(CalDavHandler,),
{
"calendars": calendars
if calendars is not None
else [
{"name": "personal", "label": "Personal"},
{"name": "work", "label": "Work"},
],
"put_status": put_status,
"requests": [],
"puts": [],
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
"llm_status": llm_status,
"llm_requests": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, default="personal", llm_url=None):
return {
"nextcloud_url": url,
"nextcloud_username": "alice",
"nextcloud_app_password": "secret",
"nextcloud_default_calendar": default,
"llm_bridge_url": url if llm_url is None else llm_url,
"llm_bridge_token": "",
}
def run(handler, url, text, default="personal", engine=None, llm_url=None):
engine = engine or FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
request = Request(text)
action = skill.act(ctx, request)
return action, request, engine
def test_example_creates_event_on_default_calendar():
server, handler, url = start_server(
llm_reply={
"title": "Ashley's dance recital",
"description": "Dance recital at 5pm.",
}
)
try:
# The query names no calendar, so the SemIf choice is a near-tie and the
# configured default ("personal") wins.
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
action, _request, engine = run(
handler,
url,
"add Ashley's dance recital to the calendar for 5pm Tuesday",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
assert engine.decisions[0].state == (
"add Ashley's dance recital to the calendar for 5pm Tuesday"
), engine.decisions[0]
assert "referred to in the user query" in engine.decisions[0].question
assert len(handler.puts) == 1, handler.puts
put = handler.puts[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
assert put["path"].endswith(".ics"), put
assert put["headers"].get("If-None-Match") == "*"
body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
assert "Ashley's dance recital" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(
handler, url, "add dentist appointment on 2026-11-10"
)
assert action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_day_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked"
assert "day" in action.needs_input.lower(), action.needs_input
request.user_input = "2026-11-10"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks():
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked"
assert "call the event" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
print(action.needs_input)
finally:
server.shutdown()
server.server_close()
def test_named_calendar_is_used():
server, handler, url = start_server(
llm_reply={"title": "team sync", "description": ""}
)
try:
engine = FakeEngine(pick="work")
action, _request, engine = run(
handler,
url,
"add team sync to my work calendar on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:team sync" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# Work edges out personal but stays below the strong-winner threshold, so
# the configured default ("personal") is used instead.
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/personal/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unknown_default_uses_semif_decision():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# The configured default is not among the account's calendars and the
# SemIf winner is weak: the winner is used anyway (never blocks).
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
default="missing",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert action.decisions and len(action.decisions) == 1, action.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try:
action, _request, _engine = run(
handler, url, "add conference all day on 2026-11-10"
)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART;VALUE=DATE:20261110" in body, body
assert "DTEND;VALUE=DATE:20261111" in body, body
assert "SUMMARY:conference" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server()
try:
action, request, _engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
llm_url="http://127.0.0.1:1",
)
assert "llm bridge" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed extraction must not fake a result"
assert handler.puts == [], "no event is created when the LLM bridge is down"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_error_status_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "HTTP 502" in action.action_log, action.action_log
assert action.new_state == request.text
assert handler.puts == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_server_error_is_reported_honestly():
server, handler, url = start_server(
put_status=500, llm_reply={"title": "standup", "description": ""}
)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "500" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_server_fails_honestly():
action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
)
assert action.action_log.startswith("calendar.create_event:"), action.action_log
assert action.new_state == request.text
print(action.action_log)
def main():
test_example_creates_event_on_default_calendar()
test_missing_time_asks_then_creates()
test_missing_day_asks_then_creates()
test_missing_title_asks()
test_named_calendar_is_used()
test_weak_winner_falls_back_to_default()
test_unknown_default_uses_semif_decision()
test_all_day_event()
test_llm_bridge_failure_is_reported_honestly()
test_llm_bridge_error_status_is_reported_honestly()
test_server_error_is_reported_honestly()
test_unreachable_server_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-6
View File
@@ -1,6 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report the next upcoming event on the user's Nextcloud calendar."
}
-414
View File
@@ -1,414 +0,0 @@
"""Report the next upcoming event on the user's Nextcloud calendar.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` discovers the user's calendars over PROPFIND and resolves which one the
request means with a single SemIf choice over every owned calendar (state = the
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
otherwise the configured default calendar is used; with no configured default
the weak winner stands. It then issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has not
ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
lives here; a server that ignores expansion is reported honestly rather than
guessed at.
"""
from __future__ import annotations
import base64
import re
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
DURATION_RE = re.compile(
r"^(?P<sign>[+-])?P"
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
def _now():
"""Current local time (aware). A test seam; the body never freezes time."""
return datetime.now().astimezone()
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0"):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = urllib.request.Request(
url + path,
data=body,
method=method,
headers={
"Authorization": f"Basic {token}",
"Depth": depth,
"Content-Type": "application/xml; charset=utf-8",
},
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery + query ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
calendars = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
def _report_body(start, end):
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
return (
'<?xml version="1.0" encoding="utf-8"?>'
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop>"
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
"</c:calendar-data>"
"</d:prop>"
"<c:filter>"
'<c:comp-filter name="VCALENDAR">'
'<c:comp-filter name="VEVENT">'
f'<c:time-range start="{start_text}" end="{end_text}"/>'
"</c:comp-filter>"
"</c:comp-filter>"
"</c:filter>"
"</c:calendar-query>"
).encode("utf-8")
def _calendar_payloads(body):
root = _multistatus(body)
payloads = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
if data.text:
payloads.append(data.text)
return payloads
# ---- calendar resolution ----
def _default_calendar(ctx, calendars):
"""The configured default calendar, if it is one of the account's."""
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
return calendar
return None
def _resolve_calendar(ctx, request, calendars, decisions):
"""Resolve which calendar the request means, mirroring calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands.
"""
default = _default_calendar(ctx, calendars)
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar parsing ----
def _unfold(text):
lines = []
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
def _parse_property(line):
match = PROPERTY_RE.match(line)
if match is None:
return "", {}, ""
name = match.group("name").upper()
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None
total = timedelta(
weeks=int(match.group("weeks") or 0),
days=int(match.group("days") or 0),
hours=int(match.group("hours") or 0),
minutes=int(match.group("minutes") or 0),
seconds=int(match.group("seconds") or 0),
)
return -total if match.group("sign") == "-" else total
def _parse_events(payloads, default_tz):
events = []
for payload in payloads:
current = None
for line in _unfold(payload):
name, params, value = _parse_property(line)
if name == "BEGIN" and value.strip().upper() == "VEVENT":
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"):
return event["start"] + timedelta(days=1)
return event["start"]
def _pick_next(events, now):
current_or_future = [event for event in events if _event_end(event) >= now]
if not current_or_future:
return None
return min(current_or_future, key=lambda event: event["start"])
def _format_when(event):
start = event["start"]
if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z")
# ---- skill phases ----
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.next_event: calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar.next_event: calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="calendar.next_event aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
now = _now()
local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
body = _request(
ctx,
"REPORT",
_calendar_path(ctx, calendar),
_report_body(window_start, window_end),
depth="1",
)
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
-259
View File
@@ -1,259 +0,0 @@
"""Hermetic mechanics test for calendar.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision (a strong winner is used, otherwise the configured default,
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
when the service errors. It does NOT prove the live integration — only a real
run against the user's Nextcloud does.
"""
import base64
import sys
import threading
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
"""Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc)
past = now - timedelta(days=2)
soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date()
def stamp(value):
return value.strftime("%Y%m%dT%H%M%SZ")
return (
"BEGIN:VCALENDAR\nVERSION:2.0\n"
"BEGIN:VEVENT\nUID:past@example\n"
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
"SUMMARY:Already happened\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:soon@example\n"
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:allday@example\n"
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
"SUMMARY:Offsite\nEND:VEVENT\n"
"END:VCALENDAR"
)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
def _record(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
self.requests.append(
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._record()
responses = "".join(
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
"<d:propstat><d:prop>"
f"<d:displayname>{label}</d:displayname>"
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
for name, label in CALENDARS[: self.calendar_count]
)
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:response>"
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
"<d:propstat><d:prop>"
f"<c:calendar-data>{ICS}</c:calendar-data>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
"</d:response></d:multistatus>"
)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url, default="personal"):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
}
def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
commands = [entry["command"] for entry in handler.requests]
assert commands == ["PROPFIND", "REPORT"], commands
report = handler.requests[1]
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
assert report["depth"] == "1", report["depth"]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
assert report["authorization"] == expected_auth, report["authorization"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner falls back to the configured default calendar.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A single calendar needs no SemIf decision.
server, handler, url = start_server(calendar_count=1)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
try:
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
}
-109
View File
@@ -1,109 +0,0 @@
"""Show the SimpleX contact link others use to connect to this agent.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
the `simplex-chat` daemon is the only thing that can read (or create) the
forwarding bot's *user contact address*; this body asks the bridge for it and
reports the link honestly. It never opens a WebSocket to the daemon and never
invents a link: if the bridge is not running or has no address, it says so.
`act` health-checks the bridge, then `GET /address` shows the existing link and
creates one on first call, returning `{short_link, full_link, created}`.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.connect_link: {exc}", new_state=request.text
)
if not payload.get("ok"):
return ActionResult(
action_log="simplex.connect_link: simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.connect_link failed: {exc}",
new_state=request.text,
)
short = str(payload.get("short_link") or "").strip()
full = str(payload.get("full_link") or "").strip()
if not (short or full):
return ActionResult(
action_log=(
"simplex.connect_link: the bridge returned no SimpleX "
"contact link; the bot has no address yet."
),
new_state=request.text,
)
verb = "created" if payload.get("created") else "current"
lines = [f"SimpleX contact link ({verb}): {short or full}"]
if short and full:
lines.append(f"Full link: {full}")
lines.append(
"Share this link with someone so they can add the agent and message it."
)
report = "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
-174
View File
@@ -1,174 +0,0 @@
"""Hermetic mechanics test for simplex.connect_link.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body health-
checks the bridge, fetches the contact link, reports a freshly created link, and
fails honestly when the bridge has no provider or is unreachable. It does NOT
prove the live integration — only a real run against the bridge and a real
simplex-chat daemon does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class BridgeHandler(BaseHTTPRequestHandler):
address = {}
address_status = 200
requests = []
tokens = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/health":
self._send({"ok": True, "platform": "simplex"})
elif url.path == "/address":
self._send(self.address, self.address_status)
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(address=None, address_status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"address": address or {},
"address_status": address_status,
"requests": [],
"tokens": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, token=""):
return {"simplex_bridge_url": url, "simplex_bridge_token": token}
def test_reports_existing_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
assert handler.requests == ["/health", "/address"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_reports_freshly_created_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#new", "full_link": "", "created": True}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
action = skill.act(ctx, request)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_provider_is_reported_honestly():
server, handler, url = start_server({"error": "address lookup is not available"}, 503)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_link_is_reported_honestly():
server, handler, url = start_server({"short_link": "", "full_link": "", "created": False})
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.connect_link:"), action.action_log
assert action.new_state == request.text
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_existing_link()
test_reports_freshly_created_link()
test_no_provider_is_reported_honestly()
test_empty_link_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-5
View File
@@ -1,5 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Read the next unread SimpleX message."
}
-172
View File
@@ -1,172 +0,0 @@
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf choice over them (state = the user
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
the configured default contact is used; with no configured default (or a default
with no unread message) the weak winner stands. It then pops and reports the
oldest unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
messaging surface it uses.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
}
TIMEOUT_SECONDS = 20
# A SemIf probability at or above this counts as a "strong winner" for the
# conversation; below it the configured default contact is used instead.
CONTACT_WINNER_TAU = 0.6
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- conversation resolution ----
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
seen = set()
for message in messages:
contact = str(message.get("contact_id") or "")
if not contact or contact in seen:
continue
seen.add(contact)
senders.append(
{"id": contact, "display_name": message.get("display_name") or contact}
)
return senders
def _default_sender(ctx, senders):
"""The configured default contact, if it has unread messages."""
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender
return None
def _resolve_contact(ctx, request, senders, decisions):
"""Resolve which conversation to read, mirroring calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default contact, and with no configured default the weak winner stands.
"""
default = _default_sender(ctx, senders)
if len(senders) == 1:
return senders[0]["id"]
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CONTACT_WINNER_TAU:
return winner
if default is not None:
return default["id"]
return winner
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return ActionResult(action_log=f"simplex.next_message: {exc}", new_state=request.text)
senders = _senders(payload.get("messages") or [])
if not senders:
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
decisions = []
contact = _resolve_contact(ctx, request, senders, decisions)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
)
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = message.get("display_name") or contact
body = str(message.get("text") or "")
report = f"SimpleX message from {sender}: {body}"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
-277
View File
@@ -1,277 +0,0 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
strong winner is used, otherwise the configured default, otherwise the weak
winner), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
requests = []
tokens = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/inbox":
self._send({"messages": list(self.messages)})
elif url.path == "/inbox/next":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
found = None
for index, message in enumerate(self.messages):
if contact is None or message["contact_id"] == str(contact):
found = self.messages.pop(index)
break
self._send({"message": found})
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(messages):
handler = type(
"Handler",
(BridgeHandler,),
{"messages": list(messages), "requests": [], "tokens": []},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def message(identifier, contact, name, text):
return {
"id": identifier,
"contact_id": contact,
"display_name": name,
"text": text,
"received_at": 1.0,
}
def config(url, default="", token=""):
return {
"simplex_bridge_url": url,
"simplex_default_contact": default,
"simplex_bridge_token": token,
}
def test_multiple_senders_uses_semif_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_strong_winner_overrides_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message from Bob")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
# Bob edges out Alice but stays below the strong-winner threshold, so the
# configured default ("Alice") is used instead.
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
assert "hello there" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_without_default_stands():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_single_sender_needs_no_decision():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported_honestly():
server, handler, url = start_server([])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
assert handler.requests == ["/inbox"], "an empty inbox needs no pop"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.next_message:"), action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
test_weak_winner_falls_back_to_default_contact()
test_weak_winner_without_default_stands()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report today's date."
}
-21
View File
@@ -1,21 +0,0 @@
"""Report today's date.
Real local compute: reads the host clock and formats the local calendar date.
No external service and no configuration.
"""
from __future__ import annotations
from datetime import datetime
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def act(ctx, request):
today = datetime.now().astimezone().date()
message = f"Today is {today.strftime('%A, %B %d, %Y')} ({today.isoformat()})."
return ActionResult(action_log=f"time.date: {message}", new_state=message)
-29
View File
@@ -1,29 +0,0 @@
"""Hermetic mechanics test for time.date.
Run from this folder: `python skill.test.py`. No external network, no config.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what is today's date?"))
assert action.new_state, "act must report the date"
assert "Today is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report the current local time of day."
}
-33
View File
@@ -1,33 +0,0 @@
"""Report the current local time.
Real local compute: reads the host clock and formats it in the host's local
timezone. No external service and no configuration — the `compute` transport is
the codebase's home for a body that acts on the machine itself.
"""
from __future__ import annotations
from datetime import datetime
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def _offset_text(now: datetime) -> str:
offset = now.strftime("%z")
if not offset:
return ""
return f" UTC{offset[:3]}:{offset[3:]}"
def act(ctx, request):
now = datetime.now().astimezone()
zone = now.tzname() or "local"
message = (
f"It is {now.strftime('%H:%M')} "
f"({now.strftime('%I:%M %p').lstrip('0')} {zone}{_offset_text(now)})."
)
return ActionResult(action_log=f"time.now: {message}", new_state=message)
-31
View File
@@ -1,31 +0,0 @@
"""Hermetic mechanics test for time.now.
Run from this folder: `python skill.test.py`. No external network, no config.
This proves the body reads the host clock and reports a real local time; it
does NOT prove anything about the host's timezone correctness.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what time is it?"))
assert action.new_state, "act must report the time"
assert "It is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Set an alarm for a specific time of day that notifies when it goes off."
}
-84
View File
@@ -1,84 +0,0 @@
"""Set an alarm for a specific time of day that notifies when it goes off.
Real local compute: parses a wall-clock time out of the request and schedules it
on the in-process timer service (`ctx.timers`). A time already past rolls to the
next day. When it fires, the front end that set it notifies the user.
If no time can be parsed the body pauses and asks for one, stashing the answer
in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from datetime import datetime, time, timedelta
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def _parse_time(text, now):
"""The next datetime matching a wall-clock time in `text`, or None."""
text = text or ""
parsed = None
if re.search(r"\bnoon\b", text, re.I):
parsed = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
# A bare hour is only accepted when unambiguous (24-hour).
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed = time(int(match.group(1)), 0)
if parsed is None:
return None
candidate = datetime.combine(now.date(), parsed, tzinfo=now.tzinfo)
if candidate <= now:
candidate += timedelta(days=1)
return candidate
def act(ctx, request):
if request.user_input is not None and request.meta.get("alarm_awaiting"):
if request.user_input.strip():
request.meta["alarm_time_text"] = request.user_input.strip()
request.meta.pop("alarm_awaiting", None)
text = request.meta.get("alarm_time_text") or request.text
now = datetime.now().astimezone()
when = _parse_time(text, now)
if when is None:
request.meta["alarm_awaiting"] = True
return ActionResult(
action_log="time.set_alarm: waiting for a time",
new_state=request.text,
needs_input="What time should the alarm go off? (e.g. '5pm')",
)
if ctx.timers is None:
return ActionResult(
action_log="time.set_alarm: no timer service is available in this front end",
new_state=request.text,
)
label = when.strftime("%H:%M")
ctx.timers.set_alarm(when, label, run_id=request.id, source=request.source)
message = f"Alarm set for {when.strftime('%H:%M')} on {when.strftime('%A')}."
return ActionResult(action_log=f"time.set_alarm: {message}", new_state=message)
-84
View File
@@ -1,84 +0,0 @@
"""Hermetic mechanics test for time.set_alarm.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses wall-clock times (am/pm, 24-hour, noon/midnight), rolls a past time
to the next day, and pauses for input when no time is present.
"""
import sys
from datetime import datetime, timedelta
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimers:
def __init__(self):
self.alarms = []
def set_alarm(self, at, label, run_id="", source=""):
self.alarms.append((at, label))
return SimpleNamespace(id="a1", due_at=at.timestamp())
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
now = datetime.now().astimezone()
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert action.needs_input is None, action.needs_input
assert len(timers.alarms) == 1, timers.alarms
at, label = timers.alarms[0]
assert (at.hour, at.minute) == (17, 0), at
assert label == "17:00"
assert at > now, "an alarm must be in the future"
assert at <= now + timedelta(days=1)
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set an alarm for 17:30"))
assert timers.alarms[0][0].strftime("%H:%M") == "17:30", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("wake me at noon"))
assert timers.alarms[0][0].strftime("%H:%M") == "12:00", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("alarm at midnight"))
assert timers.alarms[0][0].strftime("%H:%M") == "00:00", timers.alarms
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set an alarm")
action = skill.act(ctx, request)
assert action.needs_input, "an alarm with no time must ask for one"
assert timers.alarms == []
request.user_input = "6:15am"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.alarms[0][0].strftime("%H:%M") == "06:15", timers.alarms
print(action.action_log)
# No timer service fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Set a countdown timer that notifies when it finishes."
}
-127
View File
@@ -1,127 +0,0 @@
"""Set a countdown timer that notifies the user when it finishes.
Real local compute: parses a duration out of the request (digits or words) and
schedules it on the in-process timer service (`ctx.timers`). When it fires, the
front end that set it notifies the user — the REPL prints it, the gateway sends
it back to the originating chat, the dashboard shows it. A timer lives in the
process that set it and does not survive a restart.
If no duration can be parsed the body pauses and asks for one, stashing the
answer in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from semif_agent.skills import ActionResult
from semif_agent.timers import format_duration
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
_DURATION_WORDS = {
"a": 1,
"an": 1,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"fifteen": 15,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fortyfive": 45,
"sixty": 60,
"ninety": 90,
}
_UNIT_SECONDS = {
"second": 1,
"seconds": 1,
"sec": 1,
"secs": 1,
"s": 1,
"minute": 60,
"minutes": 60,
"min": 60,
"mins": 60,
"m": 60,
"hour": 3600,
"hours": 3600,
"hr": 3600,
"hrs": 3600,
"h": 3600,
}
_DIGIT_DURATION = re.compile(
r"\b(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b",
re.I,
)
_WORD_DURATION = re.compile(
r"\b(" + "|".join(sorted(_DURATION_WORDS, key=len, reverse=True)) + r")\s+"
r"(seconds?|secs?|minutes?|mins?|hours?|hrs?)\b",
re.I,
)
def _parse_duration(text):
"""Seconds for a duration phrase, or None when none is present."""
text = text or ""
if re.search(r"\bhalf\s+an?\s+hour\b", text, re.I):
return 1800
if re.search(r"\bquarter\s+(?:of\s+)?an?\s+hour\b", text, re.I):
return 900
if re.search(r"\ba\s+couple\s+of\s+(?:minutes?|mins?)\b", text, re.I):
return 120
if re.search(r"\ba\s+few\s+(?:minutes?|mins?)\b", text, re.I):
return 180
match = _DIGIT_DURATION.search(text)
if match:
unit = _UNIT_SECONDS.get(match.group(2).lower())
if unit:
return int(round(float(match.group(1)) * unit))
match = _WORD_DURATION.search(text)
if match:
value = _DURATION_WORDS.get(match.group(1).lower())
unit = _UNIT_SECONDS.get(match.group(2).lower())
if value and unit:
return value * unit
return None
def act(ctx, request):
if request.user_input is not None and request.meta.get("timer_awaiting"):
if request.user_input.strip():
request.meta["timer_duration_text"] = request.user_input.strip()
request.meta.pop("timer_awaiting", None)
text = request.meta.get("timer_duration_text") or request.text
seconds = _parse_duration(text)
if seconds is None:
request.meta["timer_awaiting"] = True
return ActionResult(
action_log="time.set_timer: waiting for a duration",
new_state=request.text,
needs_input="How long should the timer run? (e.g. '5 minutes')",
)
if ctx.timers is None:
return ActionResult(
action_log="time.set_timer: no timer service is available in this front end",
new_state=request.text,
)
label = format_duration(seconds)
timer = ctx.timers.set_timer(seconds, label, run_id=request.id, source=request.source)
due = timer.due_datetime().strftime("%H:%M")
message = f"Timer set for {label}; it will fire at {due}."
return ActionResult(action_log=f"time.set_timer: {message}", new_state=message)
-90
View File
@@ -1,90 +0,0 @@
"""Hermetic mechanics test for time.set_timer.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses durations (digits and words) and schedules the right number of
seconds, and that an unparseable request pauses for input; it does NOT prove
the in-process timer actually fires (tests/test_timers.py covers the service).
"""
import sys
import time
from datetime import datetime
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimer:
def __init__(self, seconds):
self.due_at = time.time() + seconds
def due_datetime(self):
return datetime.fromtimestamp(self.due_at).astimezone()
class FakeTimers:
def __init__(self):
self.timers = []
def set_timer(self, seconds, label, run_id="", source=""):
self.timers.append((seconds, label))
return FakeTimer(seconds)
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("please set a timer for five minutes"))
assert action.needs_input is None, action.needs_input
assert timers.timers == [(300, "5 minutes")], timers.timers
assert "300" not in action.action_log and "5 minutes" in action.action_log
print(action.action_log)
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set a timer for 90 seconds"))
assert timers.timers == [(90, "1 minute 30 seconds")], timers.timers
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("timer for 1.5 hours"))
assert timers.timers == [(5400, "1 hour 30 minutes")], timers.timers
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set a timer for half an hour"))
assert timers.timers == [(1800, "30 minutes")], timers.timers
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set a timer")
action = skill.act(ctx, request)
assert action.needs_input, "a timer with no duration must ask for one"
assert timers.timers == []
request.user_input = "ten minutes"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.timers == [(600, "10 minutes")], timers.timers
print(action.action_log)
# No timer service (e.g. a front end without one) fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set a timer for 5 minutes"))
assert action.needs_input is None
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+30 -8
View File
@@ -1,12 +1,21 @@
"""Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system
(SimpleX, the local language model) to codegen-authored skill bodies over a
local, token-guarded HTTP API. It exists so a generated body never speaks a
system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
surface instead, and the bridge owns the messy integration details and
credentials.
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook, a real
web browser via Playwright) to codegen-authored skill bodies over a local,
token-guarded HTTP API. A skill body can call a plain HTTP API directly; a
bridge is a deliberate choice for a system that needs state (especially auth
state), a native or heavy protocol, or one sanitized surface. When a bridge
fronts a service, a generated body never speaks that system's native protocol
(WebSocket, SMTP, CalDAV, an OpenAI-compatible chat API, a CLI's private flags)
directly: it calls a small, documented, uniform HTTP surface instead, and the
bridge owns the messy integration details and credentials.
Bridges **ship with their pack**: the core owns only the shared contract
(``bridges/base.py``) and the discovery registry (``bridges/registry.py``); a
bridge implementation lives in ``packs/<name>/bridge/`` and is imported by
convention from the pack that declares it. The one exception is the shared,
pack-less LLM bridge (``bridges/llm.py``), which many packs call.
Two boundaries matter:
@@ -15,20 +24,26 @@ Two boundaries matter:
own processes (`python -m semif_agent.cli bridge`) against their own service
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
every code-generation prompt (body, retry, regen, elicitation, testgen) and is
every code-generation prompt (body, retry, regen, testgen) and is
the single source of bridge specifics: the model learns which real services it
may build against, each one's base-URL config var, auth header/token var,
config-var docs, and its endpoints with request/response/error shapes. CODEGEN.md
and TESTGEN.md carry only the generic pattern.
"""
from .base import BridgeInfo, BridgeService
from .base import BridgeInfo, BridgeService, checkout_root
from .inbox import MessagingInbox
from .registry import (
build_bridge,
derived_config_vars,
describe_bridges,
discover_bridge_classes,
known_infos,
load_pack_bridge_class,
load_pack_bridge_module,
load_pack_bridge_package,
run_bridges,
set_bridge_packs,
)
__all__ = [
@@ -36,7 +51,14 @@ __all__ = [
"BridgeService",
"MessagingInbox",
"build_bridge",
"checkout_root",
"derived_config_vars",
"describe_bridges",
"discover_bridge_classes",
"known_infos",
"load_pack_bridge_class",
"load_pack_bridge_module",
"load_pack_bridge_package",
"run_bridges",
"set_bridge_packs",
]
+30
View File
@@ -14,9 +14,20 @@ import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
def checkout_root() -> Path:
"""The agent checkout root (anchors gitignored ``.runtime/`` artifacts).
``semif_agent/bridges/base.py`` -> repo root. A bridge implementation ships
inside its pack (``packs/<name>/bridge/...``), so it must not derive the root
from its own ``__file__``; it uses this helper instead.
"""
return Path(__file__).resolve().parents[2]
@dataclass(frozen=True)
class BridgeInfo:
"""Static, prompt-safe metadata about a bridge.
@@ -60,6 +71,25 @@ class BridgeService(ABC):
self._server: ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
@classmethod
def from_config(
cls,
block: dict | None,
config: dict | None = None,
trace=None,
llm=None,
) -> "BridgeService":
"""Build a bridge from its ``bridges.<name>`` block.
The registry constructs every bridge through this hook so a bridge that
needs more than its own block — the shared LLM client, or a top-level
fallback (e.g. Nextcloud's ``nextcloud_*`` values) — can declare that
itself instead of the core special-casing it by name. The default passes
the block and trace straight through; override in a pack bridge that
needs ``llm`` or the full ``config``.
"""
return cls(block, trace=trace)
# ---- lifecycle ----
@abstractmethod
+25 -16
View File
@@ -2,7 +2,7 @@
The bridge owns the read cursor so a read skill stays stateless. Generic over
transports: entries are normalized message dicts (`contact_id`, `display_name`,
`text`), which is exactly what `semif_agent.simplex_ws` yields.
`text`, `item_id`), which is exactly what `semif_agent.simplex_ws` yields.
"""
from __future__ import annotations
@@ -18,7 +18,7 @@ class MessagingInbox:
self._lock = threading.Lock()
self._items: deque[dict] = deque()
self._max = max(1, int(max_size))
self._contacts: dict[str, str] = {}
self._contacts: dict[str, dict] = {}
def record(self, message: dict) -> dict:
contact_id = str(message.get("contact_id") or "")
@@ -28,18 +28,32 @@ class MessagingInbox:
"contact_id": contact_id,
"display_name": display_name,
"text": message.get("text") or "",
# The transport's per-item id (SimpleX `itemId`), when known: lets a
# consumer mark exactly this message read on the daemon.
"item_id": str(message.get("item_id") or ""),
"received_at": time.time(),
}
with self._lock:
if display_name:
self._contacts[contact_id] = display_name
else:
self._contacts.setdefault(contact_id, "")
self._remember(contact_id, message)
self._items.append(entry)
while len(self._items) > self._max:
self._items.popleft()
return entry
def _remember(self, contact_id: str, contact: dict) -> None:
"""Upsert the cached contact for an id (caller holds the lock)."""
current = self._contacts.setdefault(
contact_id, {"id": contact_id, "display_name": ""}
)
name = contact.get("display_name") or ""
if name:
current["display_name"] = name
# Keep the unique local name and connection health when the source knows
# them; never invent them (an inbound item has no connection state).
for key in ("local_name", "connected", "auth_errors"):
if key in contact and contact[key] not in (None, ""):
current[key] = contact[key]
def peek(self) -> list[dict]:
with self._lock:
return list(self._items)
@@ -59,22 +73,17 @@ class MessagingInbox:
"""Upsert contacts learned from the daemon (not from a message).
A non-empty incoming name overwrites a cached one; an empty name never
clobbers a name already learned from an inbound message.
clobbers a name already learned from an inbound message. The unique
local name and connection health ride along when the daemon reports
them.
"""
with self._lock:
for contact in contacts:
contact_id = str(contact.get("id") or "")
if not contact_id:
continue
name = contact.get("display_name") or ""
if name:
self._contacts[contact_id] = name
else:
self._contacts.setdefault(contact_id, "")
self._remember(contact_id, contact)
def contacts(self) -> list[dict]:
with self._lock:
return [
{"id": contact_id, "display_name": name}
for contact_id, name in self._contacts.items()
]
return [dict(contact) for contact in self._contacts.values()]
+6
View File
@@ -60,6 +60,12 @@ class LLMBridge(BridgeService):
#: the bridge is built without one; calls then report 502, never a guess.
self.client = client
@classmethod
def from_config(cls, block, config=None, trace=None, llm=None) -> "LLMBridge":
# The LLM bridge reuses the scheduler's already-configured `llm` client
# (endpoint/model/sampler configured once in the top-level `llm` block).
return cls(block, trace=trace, client=llm)
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
+241 -27
View File
@@ -1,40 +1,251 @@
"""The bridge catalog: discovery, prompt description, and standalone runner.
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
static metadata, `describe_bridges()` renders the catalog block injected into
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
adding its class here and a `config.example.json` block; the gateway is never
touched.
A bridge implementation ships **with its pack** (``packs/<name>/bridge/``); the
core owns only the shared contract (``bridges/base.py``) and this registry. A
pack's ``pack.json`` names its bridge(s) in ``bridges`` and ships one module per
name under ``bridge/`` (``bridge/<name>.py``, plus optional sibling modules such
as ``bridge/<name>_client.py``). The registry imports each enabled pack's bridge
by convention, so nothing in the core names a concrete bridge — a new bridge is a
new pack, not a core edit.
The shared, pack-less **LLM bridge** stays a core built-in (``CORE_BRIDGES``):
many packs call it, so it belongs to no single concern. ``known_infos()`` exposes
every bridge's static metadata, ``describe_bridges()`` renders the catalog block
injected into the code-generation prompts, and ``run_bridges()`` starts the
enabled ones as a standalone process (``python -m semif_agent.cli bridge``).
"""
from __future__ import annotations
import importlib
import importlib.util
import sys
import threading
import types
from pathlib import Path
from .base import BridgeInfo, BridgeService
from .llm import LLMBridge
from .simplex import SimplexBridge
#: Known bridge services. Order is presentation order.
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge)
#: The agent checkout root; a relative pack root resolves against it, and the
#: default pack root is ``<checkout>/packs``.
REPO_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_PACK_ROOT = REPO_ROOT / "packs"
#: Bridges that belong to no pack — shared services any pack may call. They
#: still live under ``bridges.<name>`` so ``derived_config_vars`` and
#: ``run_bridges`` find them. Order is presentation order.
CORE_BRIDGES: tuple[type[BridgeService], ...] = (LLMBridge,)
#: Pack-discovered bridge classes, keyed by ``pack:bridge:path`` (loaded once
#: per process).
_CLASS_CACHE: dict[str, type[BridgeService]] = {}
#: Packs the running scheduler discovered; ``describe_bridges()`` (called from
#: codegen with no config) prefers these over a fresh default-root scan.
_ACTIVE_PACKS: list | None = None
def _class_for(name: str) -> type[BridgeService] | None:
for bridge_class in CATALOG:
def set_bridge_packs(packs) -> None:
"""Record the packs the running agent loaded, for prompt-time discovery.
``describe_bridges()`` is called from codegen, which has no config in hand;
``build_scheduler`` calls this after loading packs so the catalog reflects
the host's real ``skill_packs`` roots. ``None`` restores default discovery.
"""
global _ACTIVE_PACKS
_ACTIVE_PACKS = list(packs) if packs is not None else None
def _resolve_roots(roots) -> list[Path]:
if isinstance(roots, (str, Path)):
roots = [roots]
if not roots:
roots = [DEFAULT_PACK_ROOT]
resolved = []
for root in roots:
path = Path(str(root))
resolved.append(path if path.is_absolute() else REPO_ROOT / path)
return resolved
def _packs_from_roots(roots=None) -> list:
from ..packs import PackRegistry
return PackRegistry(_resolve_roots(roots)).discover()
def _packs_from_config(config: dict) -> list:
return _packs_from_roots((config or {}).get("skill_packs"))
def _packs(packs=None) -> list:
if packs is not None:
return list(packs)
if _ACTIVE_PACKS is not None:
return list(_ACTIVE_PACKS)
return _packs_from_roots(None)
def _load_package(module_name: str, directory: Path) -> types.ModuleType:
"""Import ``directory`` as a package under ``module_name`` (idempotent).
The pack's ``bridge/`` folder is loaded from its real path (never relying on
it being importable by name), so sibling modules and relative imports work
regardless of where the pack was cloned. An absent ``__init__.py`` is fine —
a synthetic package namespace is registered instead.
"""
existing = sys.modules.get(module_name)
if existing is not None:
return existing
init = directory / "__init__.py"
if not init.is_file():
package = types.ModuleType(module_name)
package.__path__ = [str(directory)] # type: ignore[attr-defined]
package.__package__ = module_name
sys.modules[module_name] = package
return package
spec = importlib.util.spec_from_file_location(
module_name, init, submodule_search_locations=[str(directory)]
)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load bridge package at {directory}")
package = importlib.util.module_from_spec(spec)
sys.modules[module_name] = package
spec.loader.exec_module(package)
return package
def _find_bridge_class(module: types.ModuleType, name: str) -> type[BridgeService] | None:
"""The ``BridgeService`` subclass a pack bridge module defines.
An explicit ``BRIDGE`` attribute wins; otherwise scan for subclasses defined
in the module, preferring one whose ``INFO.name`` matches the pack's declared
bridge name.
"""
explicit = getattr(module, "BRIDGE", None)
if isinstance(explicit, type) and issubclass(explicit, BridgeService):
return explicit
candidates = [
value
for value in vars(module).values()
if isinstance(value, type)
and issubclass(value, BridgeService)
and value is not BridgeService
and getattr(value, "__module__", None) == module.__name__
]
for candidate in candidates:
info = getattr(candidate, "INFO", None)
if info is not None and getattr(info, "name", None) == name:
return candidate
return candidates[0] if candidates else None
def load_pack_bridge_class(pack, bridge_name: str) -> type[BridgeService] | None:
"""Import one pack's bridge module and return its bridge class (or None)."""
bridge_dir = Path(pack.path) / "bridge"
module_file = bridge_dir / f"{bridge_name}.py"
if not module_file.is_file():
return None
package_name = f"semif_pack_bridge_{pack.name}"
_load_package(package_name, bridge_dir)
module = importlib.import_module(f"{package_name}.{bridge_name}")
return _find_bridge_class(module, bridge_name)
def load_pack_bridge_package(pack_name: str, packs=None) -> types.ModuleType:
"""Import and return a pack's ``bridge/`` package.
The package is registered under the stable name
``semif_pack_bridge_<pack>``, so a caller (a pack's own test, or a tool) can
import a sibling module with ``importlib.import_module(f"{pkg.__name__}.<mod>")``.
"""
pack = next((p for p in _packs(packs) if p.name == pack_name), None)
if pack is None:
raise KeyError(f"unknown pack: {pack_name!r}")
bridge_dir = Path(pack.path) / "bridge"
if not bridge_dir.is_dir():
raise KeyError(f"pack {pack_name!r} ships no bridge/ directory")
return _load_package(f"semif_pack_bridge_{pack.name}", bridge_dir)
def load_pack_bridge_module(
pack_name: str, bridge_name: str, packs=None
) -> types.ModuleType:
"""Import and return one pack's bridge module (``bridge/<bridge_name>.py``)."""
package = load_pack_bridge_package(pack_name, packs)
return importlib.import_module(f"{package.__name__}.{bridge_name}")
def discover_bridge_classes(packs=None) -> list[type[BridgeService]]:
"""Every bridge class: the packs' bridges (in pack order) then core built-ins.
With no ``packs``, uses the running scheduler's packs, else a scan of the
default pack root. A pack that declares a bridge but ships no ``bridge/``
module is skipped (a half-authored pack never breaks the catalog).
"""
classes: list[type[BridgeService]] = []
for pack in _packs(packs):
for bridge_name in getattr(pack, "bridges", ()) or ():
key = f"{pack.name}:{bridge_name}:{getattr(pack, 'path', '')}"
if key not in _CLASS_CACHE:
found = load_pack_bridge_class(pack, bridge_name)
if found is None:
continue
_CLASS_CACHE[key] = found
bridge_class = _CLASS_CACHE[key]
if bridge_class not in classes:
classes.append(bridge_class)
for bridge_class in CORE_BRIDGES:
if bridge_class not in classes:
classes.append(bridge_class)
return classes
def _class_for(name: str, packs=None) -> type[BridgeService] | None:
for bridge_class in discover_bridge_classes(packs):
if bridge_class.INFO.name == name:
return bridge_class
return None
def known_infos() -> list[BridgeInfo]:
return [bridge_class.INFO for bridge_class in CATALOG]
def known_infos(packs=None) -> list[BridgeInfo]:
return [bridge_class.INFO for bridge_class in discover_bridge_classes(packs)]
def describe_bridges() -> str:
def derived_config_vars(config: dict) -> dict[str, str]:
"""Skill-facing config vars for every bridge, derived from its own block.
The `bridges.<name>` block is the single source of truth: its `host`/`port`
are the listener a skill body calls and its `token` is the shared secret.
There is deliberately no duplicate top-level `*_bridge_url`/`*_bridge_token`
to keep in sync — the values are derived here and injected into the config a
skill reads (`ctx.config`). A bridge with no block (or no port) contributes
nothing, so an unconfigured bridge still surfaces as an unresolved contract
variable the operator is asked for.
"""
blocks = config.get("bridges", {}) or {}
derived: dict[str, str] = {}
for info in known_infos(_packs_from_config(config)):
block = blocks.get(info.name)
if not isinstance(block, dict):
continue
host = str(block.get("host") or "127.0.0.1").strip()
# A bind-all address is not a callable one; skills always call loopback.
if host in ("", "0.0.0.0", "::", "[::]"):
host = "127.0.0.1"
port = block.get("port")
if info.url_config_var and port:
derived[info.url_config_var] = f"http://{host}:{int(port)}"
if info.auth_config_var:
derived[info.auth_config_var] = str(block.get("token") or "")
return derived
def describe_bridges(packs=None) -> str:
"""A prompt block describing every available bridge service.
Injected into the skill-body, retry, regen, elicitation, and testgen
Injected into the skill-body, retry, regen, and testgen
prompts so codegen knows which real services it may build a skill against,
how to reach and authenticate to each one, and which `ctx.config` variables
carry its URL, token, and other values. This is the single source of bridge
@@ -42,11 +253,14 @@ def describe_bridges() -> str:
bridge needs to be running or enabled.
"""
lines = [
"Available bridge services (call these over HTTP with urllib.request; "
"never speak a service's native protocol directly; read every value "
"from ctx.config):",
"Available bridge services — call a service's own HTTP API directly "
"when it is a plain HTTP API; use one of these bridges when the service "
"needs state/auth, a native or heavy protocol, or a sanitized surface. "
"For a service a bridge fronts, call the bridge over HTTP with "
"urllib.request rather than reaching around it; read every value from "
"ctx.config:",
]
for info in known_infos():
for info in known_infos(packs):
lines.append(f"- {info.name} (service: {info.service}): {info.description}")
lines.append(f" base URL config var: {info.url_config_var}")
if info.auth_header and info.auth_config_var:
@@ -73,17 +287,17 @@ def build_bridge(
) -> BridgeService:
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
`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. Other bridges ignore it.
The class is discovered from the host's packs (plus the core built-ins); it
is constructed through ``BridgeService.from_config``, so a bridge that needs
the scheduler's ``llm`` client (the shared LLM bridge) or top-level fallback
values (Nextcloud's ``nextcloud_*``) declares that itself rather than the
core special-casing it by name.
"""
bridge_class = _class_for(name)
bridge_class = _class_for(name, _packs_from_config(config))
if bridge_class is None:
raise KeyError(f"unknown bridge: {name!r}")
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
if bridge_class is LLMBridge:
return LLMBridge(block, trace=trace, client=llm)
return bridge_class(block, trace=trace)
return bridge_class.from_config(block, config=config, trace=trace, llm=llm)
def run_bridges(
@@ -100,7 +314,7 @@ def run_bridges(
"""
blocks = config.get("bridges", {}) or {}
selected: list[BridgeService] = []
for bridge_class in CATALOG:
for bridge_class in discover_bridge_classes(_packs_from_config(config)):
name = bridge_class.INFO.name
if names and name not in names:
continue
-281
View File
@@ -1,281 +0,0 @@
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
The first third-party API bridge. It stands up a small HTTP API that a skill
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
SimpleX daemon/profile — separate from the command gateway's. That separation is
the point: the gateway takes commands; this bridge forwards the user's messaging
UX (show/create the contact link, read the next message, compose a send).
It buffers every inbound direct message (no allowlist — the user wants to see
who reached the bot through its invite link), and it never runs inside the
gateway process.
"""
from __future__ import annotations
import threading
from semif_agent.simplex_ws import SimplexDaemon
from .base import BridgeInfo, BridgeService
from .inbox import MessagingInbox
class SimplexBridge(BridgeService):
name = "simplex"
INFO = BridgeInfo(
name="simplex",
service="simplex",
description=(
"Read and send SimpleX messages on the user's behalf, and show or "
"create the contact link others use to reach this agent."
),
url_config_var="simplex_bridge_url",
endpoints=(
"GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the "
"bridge is up",
"GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — "
"contacts known to the daemon (learned from inbound messages and "
"refreshed from the daemon's contact list)",
"GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", "
"\"display_name\", \"text\", \"received_at\"}]} — peek buffered "
"inbound messages; does not consume",
"GET /inbox/next?contact=<id> -> 200 {\"message\": {...}|null} — pop "
"the oldest unread message (optionally from one contact); null means "
"none buffered. The bridge owns the read cursor",
"GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", "
"\"unread_count\", \"min_unread_item_id\", \"unread\", \"messages\": "
"[{item_id, text, status, unread, direction, sent_at}]}]} — the "
"daemon's persistent unread chats (survives bridge restarts), not "
"just what arrived while connected. Read-only; 503 when the daemon "
"is not connected, 502 when the lookup fails",
"GET /history?contact=<id>&count=<n> -> 200 {\"contact_id\", "
"\"messages\": [{item_id, text, status, unread, direction, "
"sent_at}]} — recent message history for one contact (count default "
"20); status is rcvNew (unread) or rcvRead. Read-only; 503/502 as "
"/unread, 400 without a contact",
"GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — "
"the agent's contact link; creates it on first call. 503 when the "
"daemon is not connected, 502 when the lookup fails",
"POST /send {\"recipient\": \"<id|display_name>\", \"text\": \"...\"} "
"-> 200 {\"ok\": true, \"contact_id\": \"<id>\"}; 400 {\"error\": "
"\"...\"} on a missing/invalid field or an unknown recipient",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
),
config_vars=(
"simplex_bridge_url",
"simplex_default_contact",
"simplex_bridge_token",
),
config_var_docs=(
(
"simplex_bridge_url",
"Base URL of the local SimpleX forwarding bridge "
"(e.g. http://127.0.0.1:5227); never hardcode it in the body.",
),
(
"simplex_default_contact",
"Optional default SimpleX contact (contact id or display name) "
"used when the request does not already make the conversation "
"clear; leave blank to always choose among senders.",
),
(
"simplex_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no "
"auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="simplex_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, daemon=None):
super().__init__(config, trace)
cfg = config or {}
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
self.daemon = daemon or SimplexDaemon(
cfg.get("ws_url", "ws://127.0.0.1:5228"),
user_id=int(cfg.get("user_id", 1)),
auto_accept=bool(cfg.get("auto_accept", True)),
reconnect=cfg.get("reconnect", {}) or {},
on_connected=self._refresh_on_connect,
trace=trace,
name=self.name,
)
self._daemon_thread: threading.Thread | None = None
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
return self.daemon.check_requirements()
def start(self) -> int:
port = super().start()
self._daemon_thread = threading.Thread(
target=self.daemon.run,
args=(self._on_message,),
name="bridge-simplex-daemon",
daemon=True,
)
self._daemon_thread.start()
return port
def _stop_transport(self) -> None:
self.daemon.close()
def _on_message(self, message: dict) -> None:
self.inbox.record(message)
async def _refresh_on_connect(self) -> None:
"""Prime the contact list from the daemon on (re)connect.
Runs on the daemon's event loop, so it awaits `contacts()` directly
rather than the thread-safe wrapper. A failure is traced, not fatal.
"""
contacts = await self.daemon.contacts()
self.inbox.merge_contacts(contacts)
self._event("contacts_refreshed", count=len(contacts))
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
if path == "/contacts":
return 200, {"contacts": self.refresh_contacts()}
if path == "/inbox":
return 200, {"messages": self.inbox.peek()}
if path == "/inbox/next":
contact = (query.get("contact") or [None])[0]
return 200, {"message": self.inbox.pop(contact)}
if path == "/unread":
return self._unread(query)
if path == "/history":
contact = (query.get("contact") or [None])[0]
count = (query.get("count") or [None])[0]
return self._history(contact, count)
if path == "/address":
return self._address()
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path != "/send":
return 404, {"error": "not found"}
recipient = payload.get("recipient")
text = payload.get("text")
if not isinstance(recipient, str) or not recipient.strip():
return 400, {"error": "recipient is required"}
if not isinstance(text, str) or not text.strip():
return 400, {"error": "text is required"}
try:
contact_id = self.send(recipient, text)
except ValueError as exc:
return 400, {"error": str(exc)}
return 200, {"ok": True, "contact_id": contact_id}
# ---- actions ----
def refresh_contacts(self) -> list[dict]:
"""Best-effort refresh of the daemon's contact list into the inbox.
Never raises: when the daemon is not connected (or is slow) it returns
whatever contacts are already cached, so `/contacts` and `/send` stay
available. The read cursor and inbound-learned names are preserved.
"""
try:
contacts = self.daemon.request_contacts()
except Exception as exc: # RuntimeError, TimeoutError, daemon error
self._event("contacts_refresh_failed", message=str(exc)[:200])
return self.inbox.contacts()
self.inbox.merge_contacts(contacts)
self._event("contacts_refreshed", count=len(contacts))
return self.inbox.contacts()
def _unread(self, query: dict) -> tuple[int, dict]:
"""The daemon's persistent unread chats (not the live receive buffer).
Read-only: there is no mark-read command in v7, so this never consumes.
Best-effort like `/address` — 503 when the daemon is not connected, 502
when the lookup fails, never a fabricated chat.
"""
count = self._count((query.get("count") or [None])[0])
try:
chats = self.daemon.request_chats(unread_only=True, count=count)
except RuntimeError as exc:
return 503, {"error": f"unread lookup is not available: {exc}"[:300]}
except Exception as exc: # TimeoutError, daemon error
return 502, {"error": f"unread lookup failed: {exc}"[:300]}
return 200, {"chats": chats}
def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]:
"""Recent message history for one contact, straight from the daemon.
Read-only. A missing contact is a client error; a disconnected or
failing daemon degrades like `/unread`.
"""
contact = str(contact or "").strip()
if not contact:
return 400, {"error": "contact is required"}
try:
messages = self.daemon.request_chat_history(
contact, count=self._count(count)
)
except RuntimeError as exc:
return 503, {"error": f"history lookup is not available: {exc}"[:300]}
except Exception as exc: # TimeoutError, daemon error
return 502, {"error": f"history lookup failed: {exc}"[:300]}
return 200, {"contact_id": contact, "messages": messages}
@staticmethod
def _count(raw: str | None, default: int = 20, maximum: int = 100) -> int:
try:
value = int(raw) if raw is not None else default
except (TypeError, ValueError):
value = default
return max(1, min(value, maximum))
def _address(self) -> tuple[int, dict]:
try:
link = self.daemon.request_address()
except RuntimeError as exc:
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
except Exception as exc: # TimeoutError, daemon error
return 502, {"error": f"address lookup failed: {exc}"[:300]}
if not isinstance(link, dict):
return 502, {"error": "address lookup returned no link"}
return 200, link
def send(self, recipient: str, text: str) -> str:
"""Resolve a recipient and enqueue the message. Returns the contact id."""
contact_id = self.resolve(recipient)
if contact_id is None:
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
self.daemon.enqueue(contact_id, text)
return contact_id
def resolve(self, recipient: str) -> str | None:
"""A numeric id (with or without `@`) or a known display name.
On a display-name miss, refresh the daemon's contact list once and
retry: a contact the bridge has never received from is still addressable
as long as the daemon knows them.
"""
recipient = str(recipient or "").strip()
if not recipient:
return None
bare = recipient.lstrip("@")
if bare.isdigit():
return bare
match = self._match_contact(recipient)
if match is None:
self.refresh_contacts()
match = self._match_contact(recipient)
return match
def _match_contact(self, recipient: str) -> str | None:
for contact in self.inbox.contacts():
if contact["display_name"] == recipient or contact["id"] == recipient:
return contact["id"]
return None
+452 -69
View File
@@ -13,6 +13,7 @@ Run on a host with SemIf + a GGUF + a local OpenAI-compatible server:
from __future__ import annotations
import argparse
import faulthandler
import json
import os
import sys
@@ -22,24 +23,42 @@ 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,
ConsoleLLMClient,
)
from .decisions import DecisionRequest, Option
from .engine import EngineConfig, EngineUnavailable, SemIfEngine
from .llm import LLMClient
from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine
from .ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
from .winnow import WinnowConfig, WinnowEngine
from .llm import LLMClient, SemIfLLMClient
from .log import DecisionLog
from .packs import load_packs
from .scheduler import Scheduler
from .setup import run_setup as run_bootstrap_setup
from .skills import tree_summary
from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WINNOW_URL = "http://127.0.0.1:8091"
DEFAULT_OLLAMA_SYSTEMONE_URL = "http://127.0.0.1:11434"
_PATH_KEYS = (
"skill_seeds",
"skill_packs",
"skill_bodies",
"category_registry",
"deleted_skills",
@@ -47,7 +66,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",
@@ -62,18 +81,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:
@@ -108,8 +123,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 (
@@ -124,26 +140,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 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
@@ -177,6 +202,7 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
gguf = _anchor_path(override) if override else str(
REPO_ROOT / ".runtime" / "models" / os.path.basename(pin_eng.get("gguf_url", ""))
)
gpu_device = eng.get("gpu_device")
return EngineConfig(
backend=eng.get("backend", "llamacpp"),
source=pin_eng.get("source", ""),
@@ -184,18 +210,86 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
gguf=gguf,
context_tokens=int(eng.get("context_tokens", 4096)),
threads=eng.get("threads"),
gpu_layers=int(eng.get("gpu_layers", 0)),
gpu_device=None if gpu_device is None else int(gpu_device),
gpu_split=int(eng.get("gpu_split", 0)),
)
def build_codegen_client(config: dict) -> CodegenClient:
def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
"""Build the decision engine from the `engine` config block.
`provider` selects the implementation, mirroring `llm`/`codegen`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
from the per-machine `engine` knobs + the pinned refs in pins.json.
* ``"winnow"`` — a remote Winnow `/v1/systemone` typed-decision API
(`WinnowEngine`), configured by the nested `engine.winnow` block
(`base_url`/`model`/`api_key`/`timeout`/`retries`).
* ``"ollama"`` — ollama's native System One `/v1/systemone` route
(`OllamaSystemOneEngine`), configured by the nested `engine.ollama` block
(`base_url`/`model`/`keep_alive`/`api_key`/`timeout`/`retries`), probed
through ollama's own `/api/version` + `/api/show` endpoints.
The engine is always real: a provider that cannot be reached raises
`EngineUnavailable` at call time, which the scheduler treats as fatal. The
`winnow` and `ollama` models are required (no default) exactly as
`llm.model`/`codegen.model` are, so a misconfigured endpoint fails as an
actionable config error.
"""
eng = config.get("engine", {}) or {}
provider = str(eng.get("provider", "semif") or "semif").lower()
if provider == "winnow":
win = eng.get("winnow", {}) or {}
endpoint = _provider_endpoint(win, DEFAULT_WINNOW_URL)
return WinnowEngine(
WinnowConfig(
base_url=endpoint["base_url"],
model=_required_model(win, "engine.winnow"),
context_tokens=int(win.get("context_tokens", 32768)),
timeout=float(win.get("timeout", 120.0)),
retries=int(win.get("retries", 0)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=str(win.get("user_agent") or "semif-agent"),
)
)
if provider == "ollama":
block = eng.get("ollama", {}) or {}
endpoint = _provider_endpoint(block, DEFAULT_OLLAMA_SYSTEMONE_URL)
return OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url=endpoint["base_url"],
model=_required_model(block, "engine.ollama"),
context_tokens=int(block.get("context_tokens", 16384)),
timeout=float(block.get("timeout", 120.0)),
retries=int(block.get("retries", 0)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=str(block.get("user_agent") or "semif-agent"),
keep_alive=str(block.get("keep_alive") or ""),
)
)
return SemIfEngine(build_engine_config(config, pins))
def build_codegen_client(config: dict) -> CodegenClient | None:
"""Build the codegen client from the `codegen` config block.
`provider` selects the class (`opencode` -> the Console client, which adds
bearer auth and a User-Agent) and the endpoint/auth come from
`_provider_endpoint`. Shared by `build_scheduler` and the integration tests
so both exercise the configured provider rather than assuming ollama.
Returns ``None`` when no `codegen.model` is configured: skill authoring is
an opt-in capability, so a host that only runs the shipped packs (the
minimum path) needs no codegen endpoint and the app must not fail without
one. The scheduler guards every authoring path against a missing client.
"""
codegen_cfg = config.get("codegen", {}) or {}
model = str(codegen_cfg.get("model") or "").strip()
if not model:
return None
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
client_cls = ConsoleCodegenClient if provider == "opencode" else CodegenClient
@@ -205,7 +299,7 @@ def build_codegen_client(config: dict) -> CodegenClient:
)
return client_cls(
base_url=endpoint["base_url"],
model=_required_model(codegen_cfg, "codegen"),
model=model,
timeout=float(codegen_cfg.get("timeout", 1200.0)),
stream=bool(codegen_cfg.get("stream", False)),
idle_warn=float(codegen_cfg.get("idle_warn", 60.0)),
@@ -231,15 +325,35 @@ def build_codegen_client(config: dict) -> CodegenClient:
)
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
engine = SemIfEngine(build_engine_config(config))
def build_llm_client(config: dict, engine) -> LLMClient | None:
"""Build the `llm` title/description client from the `llm` config block.
`provider` selects the backend: `"semif"` drives the already-loaded SemIf
engine model in-process (the GGUF is the model — no endpoint or `model` is
needed), `"opencode"` the hosted Console client, and anything else the
default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests
so both exercise the configured provider rather than assuming ollama.
Returns ``None`` when a non-`semif` provider has no `model`: the `llm` client
is only needed for skill authoring and gateway result cleanup, both optional.
"""
llm_cfg = config.get("llm", {}) or {}
llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient
llm_endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
llm = llm_cls(
base_url=llm_endpoint["base_url"],
model=_required_model(llm_cfg, "llm"),
provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
if provider == "semif":
semif_cfg = llm_cfg.get("semif", {}) or {}
return SemIfLLMClient(
engine,
temperature=float(semif_cfg.get("temperature", 0.0)),
max_tokens=int(semif_cfg.get("max_tokens", 256)),
)
model = str(llm_cfg.get("model") or "").strip()
if not model:
return None
llm_cls = ConsoleLLMClient if provider == "opencode" else LLMClient
endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
return llm_cls(
base_url=endpoint["base_url"],
model=model,
timeout=float(llm_cfg.get("timeout", 600.0)),
stream=bool(llm_cfg.get("stream", False)),
idle_warn=float(llm_cfg.get("idle_warn", 30.0)),
@@ -250,15 +364,42 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
presence_penalty=_opt_float(llm_cfg.get("presence_penalty")),
frequency_penalty=_opt_float(llm_cfg.get("frequency_penalty")),
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
api_key=llm_endpoint["api_key"],
extra_headers=llm_endpoint["extra_headers"],
user_agent=llm_endpoint["user_agent"],
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=endpoint["user_agent"],
)
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
# Bridge listener addresses/tokens are derived from each bridge's own
# `bridges.<name>` block (host/port/token) — the single source of truth.
# There is no duplicate top-level *_bridge_url to drift; skills read these
# from ctx.config and the contract config search finds them here.
from .bridges.registry import derived_config_vars
config = {**config, **derived_config_vars(config)}
engine = build_engine(config)
llm = build_llm_client(config, engine)
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
codegen_cfg = config.get("codegen", {})
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
codegen = build_codegen_client(config)
if str(config.get("new_skill_creation", "deny") or "deny").lower() != "deny":
if codegen is None:
print(
"WARN: new_skill_creation is enabled but codegen.model is not "
"set — skill authoring will not run. Set codegen.model (and "
"base_url) to enable it.",
file=sys.stderr,
)
if llm is None:
print(
"WARN: new_skill_creation is enabled but llm.model is not set — "
"skill authoring will not run. Set llm.model (and base_url), or "
"llm.provider 'semif' to use the decision model.",
file=sys.stderr,
)
def make_degeneration_check(run_id: str):
"""2-option SemIf decision (continue/stop) that aborts a degenerating
@@ -346,12 +487,18 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
degeneration_check_factory=make_degeneration_check,
regen_decision_factory=make_regen_decision,
)
# Bridges ship with their packs; tell the registry which packs this host
# loaded so `describe_bridges()` (called from codegen with no config) lists
# the real set rather than a default-root scan.
from .bridges.registry import set_bridge_packs
set_bridge_packs(scheduler.packs)
return scheduler, config
def try_warm(scheduler: Scheduler) -> str:
try:
scheduler.engine._ensure_loaded()
scheduler.engine.warm()
return "decision engine loaded."
except EngineUnavailable as exc:
return f"decision engine unavailable: {exc}"
@@ -383,8 +530,8 @@ def _print_repairs(scheduler: Scheduler) -> None:
def _answer_approvals(scheduler: Scheduler) -> None:
"""Ask any pending creation approvals at the REPL.
Only prompts when `creation_approval` is on (the scheduler posts nothing
otherwise). An empty answer denies.
Only prompts when a category (or the global default) uses the `ask` mode
(the scheduler posts nothing otherwise). An empty answer denies.
"""
while True:
pending = scheduler.pending_approvals()
@@ -416,6 +563,32 @@ def _print_approvals(scheduler: Scheduler) -> None:
print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}")
def _print_reply(reply, show_run_id: bool = False, verbosity: str = "result") -> None:
"""Print a scheduler reply, honoring the configured verbosity.
"result" shows only the final answer of a request (an intermediate chain
step is hidden); "query" also shows intermediate steps; "decision"
additionally prints each SemIf decision phase for the run.
"""
if getattr(reply, "intermediate", False) and verbosity == "result":
return
label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else ""
print(f"[{reply.status}] {label}{reply.text}")
for line in getattr(reply, "decision_lines", ()) or ():
print(f" {line}")
def _drain_queue(scheduler: Scheduler) -> None:
"""Run queued work, printing each outcome with its run id.
Routes any replies a background drain buffered (a post-authoring re-run, a
repair retry) before the queued work, so an off-gate completion still prints.
"""
verbosity = getattr(scheduler, "verbosity", "result")
for reply in [*scheduler.drain_outbox(), *scheduler.run_queue()]:
_print_reply(reply, show_run_id=True, verbosity=verbosity)
def _fatal_exit(scheduler: Scheduler) -> int | None:
"""If the scheduler hit a fatal engine failure, print it and return non-zero.
@@ -458,7 +631,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
"housekeeping (slash-prefixed so plain requests still route by SemIf): "
"/delete <category> <skill> | /clear-config <category> <skill> | "
"/regen <category> <skill> | /cancel-build <category> <skill> | "
"/lock <category> on|off"
"/mode <category> allow|deny|ask"
)
while True:
_answer_questions(scheduler)
@@ -499,8 +672,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
print(f"[{status}] {detail}")
_answer_questions(scheduler)
_answer_approvals(scheduler)
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
continue
if lower.startswith("relabel "):
parts = line.split()
@@ -550,14 +722,12 @@ def repl(scheduler: Scheduler, config: dict) -> int:
status, detail = scheduler.cancel_skill_build(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/lock "):
if lower.startswith("/mode "):
parts = line.lstrip("/").split()
if len(parts) != 3 or parts[2].lower() not in ("on", "off"):
print("usage: /lock <category> on|off")
if len(parts) != 3 or parts[2].lower() not in ("allow", "deny", "ask"):
print("usage: /mode <category> allow|deny|ask")
continue
status, detail = scheduler.set_category_lock(
parts[1], parts[2].lower() == "on"
)
status, detail = scheduler.set_category_mode(parts[1], parts[2].lower())
print(f"[{status}] {detail}")
continue
if lower == "idle":
@@ -568,19 +738,16 @@ def repl(scheduler: Scheduler, config: dict) -> int:
scheduler.busy(line[5:].strip())
print("current process set (busy).")
continue
status, detail = scheduler.submit(line)
print(f"[{status}] {detail}")
_print_reply(scheduler.submit(line), verbosity=scheduler.verbosity)
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None:
hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ")
status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}")
_print_reply(scheduler.answer(answer), verbosity=scheduler.verbosity)
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
if _fatal_exit(scheduler) is not None:
return 1
_answer_questions(scheduler)
@@ -593,12 +760,13 @@ def scripted(scheduler: Scheduler, path: str) -> int:
print(try_warm(scheduler))
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows:
status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
print(f"[{status}] {detail}")
_print_reply(
scheduler.submit(str(row["text"]), source=row.get("source", "scripted")),
verbosity=scheduler.verbosity,
)
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
return _fatal_exit(scheduler) or 0
@@ -606,7 +774,7 @@ def _gateway_address_callback(adapter):
"""Return an `on_connected` coroutine that prints the bot's contact link once.
A human cannot reach the gateway without the bot's SimpleX contact address,
and the only thing that surfaced it before was `scripts/simplex-address.py`
and the only thing that surfaced it before was `packs/simplex/scripts/simplex-address.py`
run once at provision time. Print it on connect, from the operator front end
(the CLI), through the daemon the gateway already owns — show-or-create, no
second connection, no new transport surface. The lookup is best-effort: a
@@ -693,6 +861,14 @@ def _build_gateway_adapter(platform: str, cfg: dict, trace):
# Contain Reticulum's config + identity under the checkout's .runtime/.
cfg.setdefault("config_dir", str(REPO_ROOT / ".runtime" / "lxmf" / "reticulum"))
cfg.setdefault("storage_path", str(REPO_ROOT / ".runtime" / "lxmf" / "router"))
# A voice reply's Piper voice lives with the voice gateway's, under the
# checkout's .runtime/ (bootstrap downloads it there).
voice_cfg = dict(cfg.get("voice") or {})
tts_cfg = dict(voice_cfg.get("tts") or {})
if not tts_cfg.get("voice_dir"):
tts_cfg["voice_dir"] = str(REPO_ROOT / ".runtime" / "voice" / "tts")
voice_cfg["tts"] = tts_cfg
cfg["voice"] = voice_cfg
return LxmfAdapter(cfg, trace=trace)
if platform == "voice":
from .gateway.voice import VoiceAdapter
@@ -718,7 +894,8 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]:
`all`/`*` means every **enabled** gateway block in config; a
comma-separated list is taken as-is (unknown names are kept so the caller
can report them).
can report them). Non-platform keys (`_comment`, the global `humanize`
defaults block) are skipped.
"""
requested = (requested or "simplex").strip()
if requested in ("all", "*"):
@@ -727,6 +904,7 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]:
for name, block in (gateway_cfg or {}).items()
if isinstance(block, dict)
and not name.startswith("_")
and name != "humanize"
and block.get("enabled", False)
]
return [name.strip() for name in requested.split(",") if name.strip()]
@@ -744,6 +922,12 @@ def run_gateway(
run two scheduler processes over one skill store), so each gets its own
transport thread but they route through one `GatewayService`.
"""
# Dump every thread's Python stack on a fatal signal (SIGSEGV/SIGABRT/...):
# a wedged front end (e.g. a voice loop stuck on the mic) leaves a trace in
# the journal instead of dying silently. Also enabled by the unit's
# PYTHONFAULTHANDLER=1; harmless when set twice.
faulthandler.enable()
gateway_cfg = config.get("gateway", {}) or {}
platforms = _resolve_platforms(platform, gateway_cfg)
@@ -857,9 +1041,120 @@ 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 _setup_command(args) -> int:
"""Run the first-run interview (or emit the install plan) — see `setup.py`."""
config_path = Path(args.path)
if not config_path.is_absolute():
config_path = REPO_ROOT / config_path
packs = load_packs({"skill_packs": _anchor_pack_roots({})})
return run_bootstrap_setup(
root=config_path.parent,
path=config_path,
packs=packs,
interview=args.interview,
yes=args.yes,
answers_file=args.answers,
plan_only=args.plan_only,
plan_out=args.plan_out,
force=args.force,
answers_out=args.answers_out,
pack_index=args.pack_index,
)
def _load_config_tolerant(path: str) -> dict:
"""Load the config, or ``{}`` when it is missing/invalid.
Used for parser defaults (dashboard bind) before the subcommand is known.
Runtime commands still require a real config: `main` re-loads it fatally
after the config-independent subcommands return.
"""
try:
return load_config(path)
except SystemExit:
return {}
def main(argv: list[str] | None = None) -> int:
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)
defaults = _load_config_tolerant(config_path)
parser = argparse.ArgumentParser(prog="semif-agent")
parser.add_argument("--config", default="config.json")
sub = parser.add_subparsers(dest="command")
@@ -871,15 +1166,93 @@ 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")
setup_p = sub.add_parser(
"setup",
help="first-run interview: generate config/ from your answers",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"answers JSON fields (all optional; --answers FILE):\n"
" engine_provider (semif|winnow|ollama), winnow_base_url, winnow_model,\n"
" winnow_api_key, ollama_base_url, ollama_model, ollama_api_key\n"
" new_skill_creation (deny|ask|allow)\n"
" llm_provider (semif|ollama|opencode|openai), llm_base_url,\n"
" llm_model, llm_api_key\n"
" codegen_provider, codegen_base_url, codegen_model, codegen_api_key\n"
" packs (list of pack names; the offered set comes from --pack-index)\n"
" gateways (list of: simplex, lxmf, voice), timezone\n"
" nextcloud_url, nextcloud_username, nextcloud_app_password,\n"
" outlook_client_id"
),
)
setup_p.add_argument("--path", default="config.json", help="config index path to seed")
setup_p.add_argument(
"--interview", action="store_true", help="ask the setup questions interactively"
)
setup_p.add_argument(
"--yes",
action="store_true",
help="non-interactive: take the minimum working defaults",
)
setup_p.add_argument(
"--answers", default=None, metavar="FILE", help="JSON answers file (non-interactive)"
)
setup_p.add_argument(
"--answers-out",
default=None,
metavar="FILE",
help="collect the answers and write them as JSON to FILE, then exit "
"(no config; bootstrap's pre-clone pass)",
)
setup_p.add_argument(
"--pack-index",
default=None,
metavar="FILE",
help="pack-index JSON whose entries the interview offers "
"(semif-packs; see scripts/bootstrap.sh)",
)
setup_p.add_argument(
"--plan-out",
default=None,
metavar="PATH",
help="write the install plan JSON to PATH (for scripts/bootstrap.sh)",
)
setup_p.add_argument(
"--plan-only",
action="store_true",
help="read the existing config and emit the plan; write nothing",
)
setup_p.add_argument(
"--force", action="store_true", help="overwrite an existing config"
)
relabel_p = sub.add_parser("relabel", help="human override of a decision label")
relabel_p.add_argument("id")
relabel_p.add_argument("outcome")
dash_p = sub.add_parser("dashboard", help="run the local browser dashboard")
dash_p.add_argument("--port", type=int, default=int(config.get("dashboard", {}).get("port", 8765)))
dash_p.add_argument(
"--port",
type=int,
default=int(defaults.get("dashboard", {}).get("port", 8765)),
)
dash_p.add_argument(
"--host",
default=str(config.get("dashboard", {}).get("host", "127.0.0.1")),
default=str(defaults.get("dashboard", {}).get("host", "127.0.0.1")),
help="bind address (0.0.0.0 to expose on the LAN)",
)
dash_p.add_argument(
@@ -910,6 +1283,16 @@ 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)
if args.command == "setup":
return _setup_command(args)
# Runtime commands need a real config; this is fatal when it is missing.
config = defaults or load_config(config_path)
scheduler, config = build_scheduler(config)
if args.command == "run":
+177 -268
View File
@@ -21,7 +21,6 @@ from pathlib import Path
from typing import Callable, NamedTuple
from .bridges.registry import describe_bridges
from .decisions import Request
from .provider import OpenAICompatClient, ProviderError
from .skills import SkillDraft, tree_summary
@@ -41,6 +40,18 @@ class DegenerationError(CodegenError):
"""
class ArtifactTooLong(ValueError):
"""A generated artifact exceeded the size budget for a decision.
A hard ceiling, not a warning: the artifact is ingested *whole* by a
decision (the fidelity gate reads the entire skill body), so it must fit
the decision engine's context with headroom for everything else in the
state. The budget is derived from the active engine's context; the codegen
retry ladder asks the model for a shorter artifact, and a body that still
cannot fit stubs out rather than shipping something the gate cannot read.
"""
def read_skill_contract(path: str | None = None) -> str:
contract = Path(path) if path else DEFAULT_CONTRACT
if not contract.is_file():
@@ -104,10 +115,9 @@ class CodegenClient(OpenAICompatClient):
BODY_DIRECTIVES = (
"This body is a reusable module executed across many requests. It owns no "
"working data: every required operational value is provided by the runner "
"through `ctx.config` under a clear snake_case name — request data from the "
"runner, never embed or fabricate working values, and never ask the human "
"for operational data. Ask the human only to refine the product goal and "
"requirements.\n"
"through `ctx.config` under a clear snake_case name — never embed or "
"fabricate working values, and never assume a specific user, account, "
"address, or value.\n"
"Write a single `act(ctx, request)` function. Declare the required "
"operational values as a module-level `CONTRACT` dict exactly as CODEGEN.md "
"specifies: a flat map of variable name -> semantic description. Every key "
@@ -115,74 +125,67 @@ BODY_DIRECTIVES = (
"values with safe defaults — read those with `ctx.config.get(...)` instead.\n"
"Read `request.text` and derive the action's per-request arguments from it "
"(recipient, subject/body, date, target, search terms); never declare a "
"query argument in CONTRACT and never ask the human for one. Return the real "
"result in `new_state` and a truthful `action_log` — the fetched data or the "
"service's real response, never an empty or placeholder output.\n"
"query argument in CONTRACT. Return the real result in `new_state` and a "
"truthful `action_log` — the fetched data or the service's real response, "
"never an empty or placeholder output.\n"
"Perform the real action: if this skill interacts with an external system, "
"`act` must call the user's configured service with a stdlib transport "
"(urllib.request/http.client for HTTP, imaplib/smtplib/poplib for mail, "
"subprocess for a configured local CLI) using endpoint, account, "
"credential, and CLI-path values read from `ctx.config`. Never simulate "
"success, never return canned output, and never default to writing a draft "
"unless the requirements explicitly ask for draft-only. The auto-run test "
"unless the reusable goal explicitly asks for draft-only. The auto-run test "
"is a hermetic mechanics check and will not exercise the live service, so "
"no localhost defaults, test ports, or fixture values may appear in the "
"body.\n"
"Declare the integration as a module-level `INTEGRATION` dict exactly as "
"CODEGEN.md specifies: service, transport, config_vars.\n"
"If this skill interacts with one of the available bridge services listed "
"below, call that bridge over HTTP with the URL from its config variable — "
"never speak the service's native protocol directly (no WebSocket to "
"simplex-chat, no direct daemon access). Whenever you have a set of "
"To reach a service, call its HTTP API directly with a stdlib transport "
"when it is a plain HTTP API; use one of the bridge services listed below "
"when the service needs state/auth, a native or heavy protocol, or a "
"sanitized surface — and when a bridge fronts a service, call the bridge "
"over HTTP with the URL from its config variable rather than reaching "
"around it (no WebSocket to simplex-chat, no direct daemon access, no "
"DAV/OCS hand-rolling). Whenever you have a set of "
"candidates to choose from (contacts, conversations, calendars, targets), "
"employ a `ctx.engine` SemIf sub-decision over them and return the "
"`(DecisionRequest, DecisionResult)` pairs on `ActionResult.decisions`; "
"send only when the request or requirements ask for it.\n"
"send only when the reusable goal calls for it.\n"
"Keep the body small: it is ingested whole by the decision engine's "
"fidelity check, so delegate complex protocol details to a bridge instead "
"of hand-rolling them (a simple HTTP call needs no bridge), and keep `act` "
"to one purpose.\n"
)
def _requirements_block(requirements: dict[str, str] | None) -> str:
if not requirements:
return ""
lines = "\n".join(
f"- {question} -> {answer}" for question, answer in requirements.items()
)
return f"Requirements gathered from the product owner:\n{lines}\n"
def _integration_hint_block(draft: SkillDraft) -> str:
"""Advisory integration hint from elicitation: service + transport.
Never overrides the request, requirements, or CODEGEN.md contract — it only
biases the body writer toward the integration the questions were aiming at.
"""
"""Advisory integration hint from the de-identified skill spec: service +
transport. Never overrides the reusable goal or the CODEGEN.md contract — it
only biases the body writer toward the integration the spec named."""
integration = getattr(draft, "integration", None) or {}
service = integration.get("service")
transport = integration.get("transport")
if not service and not transport:
return ""
return (
"Elicitation pointed at this integration (advisory only: follow the "
"request, requirements, and contract if they disagree): "
"The skill spec points at this integration (advisory only: follow the "
"reusable goal and the contract if they disagree): "
f"service={service or 'unknown'}, transport={transport or 'unknown'}.\n"
)
def build_skill_body_prompt(
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
contract: str,
requirements: dict[str, str] | None = None,
) -> list[dict]:
"""Messages for the code-generation model.
The small model already chose the title + description; the big model only
writes the runnable body against the CODEGEN.md contract, informed by the
request, the category, and the existing skills so it avoids duplication.
`requirements` carries the answers to elicitation questions asked of the
human during authoring.
Built ONLY from the de-identified spec (goal + generic service/transport),
the category, the existing tree, and the CODEGEN.md contract. It never
carries the user's request, question answers, or any run output: codegen
must be able to write a reusable body from the generalized goal alone.
"""
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
system = (
@@ -190,15 +193,14 @@ def build_skill_body_prompt(
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
req_block = _requirements_block(requirements)
user = (
f"Request: {request.text}\n"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Reusable goal (de-identified; never embed or ask for user-specific "
f"values): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\n"
f"{req_block}"
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
@@ -273,13 +275,17 @@ def _unresolved_names(code: str) -> list[str]:
return sorted(unresolved)
def parse_skill_body(raw: str) -> str:
def parse_skill_body(raw: str, max_chars: int | None = None) -> str:
"""Extract and validate a Python skill body from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The body
must parse, define a module-level `act` function, declare a valid flat
`CONTRACT` whose keys are all read from `ctx.config`, and import every name
it uses. Returns the cleaned source. Raises ValueError otherwise.
`max_chars` is the hard size ceiling (the scheduler derives it from the
active decision engine's context). A body over it raises `ArtifactTooLong`
so the retry ladder asks for a shorter one.
"""
text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text:
@@ -302,6 +308,12 @@ def parse_skill_body(raw: str) -> str:
text = text.strip()
if not text:
raise ValueError("skill body is empty")
if max_chars is not None and len(text) > max_chars:
raise ArtifactTooLong(
f"skill body is {len(text)} chars, over the {max_chars}-char limit "
"for a decision-ingestible body; keep it small and delegate "
"protocol details to a bridge"
)
try:
module = ast.parse(text, filename="<generated>")
except SyntaxError as exc:
@@ -555,19 +567,93 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
return findings
_HTTP_VERBS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
_SUBPROCESS_FUNCS = frozenset({"run", "Popen", "call", "check_call", "check_output"})
_FILE_WRITE_FUNCS = frozenset({"write_text", "write_bytes", "write"})
def _call_name(node) -> str:
"""Best-effort dotted name of a call target (e.g. `urllib.request.urlopen`)."""
parts: list[str] = []
while isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
parts.append(node.id)
return ".".join(reversed(parts))
def operation_inventory(code: str) -> list[str]:
"""A compact, static inventory of the side-effecting operations in a body.
The fidelity gate reads the whole body; this inventory is its deterministic
companion. It names the concrete operations (HTTP verb + path, CLI run,
mail send, file write, timer) so the gate and its regen evidence see *what
the body does* at a glance, and a body that performs no operation at all is
legible immediately. Best-effort and purely static: a dynamic target
renders as `?`, an unparseable body yields nothing. Never raises.
"""
try:
module = ast.parse(code, filename="<inventory>")
except SyntaxError:
return []
operations: list[str] = []
for node in ast.walk(module):
if not isinstance(node, ast.Call):
continue
name = _call_name(node.func)
leaf = name.rsplit(".", 1)[-1]
args = list(node.args) + [kw.value for kw in node.keywords]
strings = [s for a in args if (s := _const_str(a)) is not None]
verbs = [s for s in strings if s.upper() in _HTTP_VERBS]
if verbs:
paths = [s for s in strings if s.startswith("/")]
target = paths[0] if paths else "?"
operations.append(f"HTTP {verbs[0].upper()} {target} (via {name or '?'})")
continue
if name in {
"urllib.request.urlopen",
"urlopen",
"http.client.HTTPConnection",
"http.client.HTTPSConnection",
}:
operations.append(f"HTTP request (via {name})")
elif "subprocess" in name and leaf in _SUBPROCESS_FUNCS:
operations.append(f"run CLI (via {name})")
elif "smtplib" in name and leaf in {"sendmail", "send_message"}:
operations.append(f"send mail (via {name})")
elif "imaplib" in name and leaf in {"append", "store", "copy", "expunge"}:
operations.append(f"mail mutation (via {name})")
elif "poplib" in name and leaf in {"dele", "quit"}:
operations.append(f"mail mutation (via {name})")
elif leaf in _FILE_WRITE_FUNCS or (
name == "open"
and any(s in {"w", "a", "x", "wb", "ab", "xb", "w+", "a+", "wt", "at"} for s in strings)
):
operations.append(f"write file (via {name})")
elif name.startswith("ctx.timers"):
operations.append(f"schedule timer (via {name})")
if not operations:
operations.append("no side-effecting operation found")
return operations
def render_operation_inventory(operations: list[str]) -> str:
"""Render `operation_inventory` as a bulleted block for a decision state."""
return "\n".join(f"- {operation}" for operation in operations)
def _retry_prompt(
request: Request,
category: str,
draft: SkillDraft,
contract: str,
error: Exception,
requirements: dict[str, str] | None = None,
) -> list[dict]:
"""Fresh short prompt for a corrective retry.
Not a growing conversation: the context resets to SMART (new request, tiny
prompt) and the model is told in one line to stop looping and emit the
final Python. The elicitation answers are repeated so a retry cannot fall
final Python. The de-identified goal is repeated so a retry cannot fall
back to a toy body.
"""
system = (
@@ -575,14 +661,21 @@ def _retry_prompt(
"is authoritative: follow it exactly.\n\n"
f"{contract}"
)
if isinstance(error, ArtifactTooLong):
guidance = (
"The previous attempt was too long to fit the decision engine's "
"context. Emit a SHORTER body: keep `act` minimal and delegate "
"complex protocol details to a bridge.\n"
)
else:
guidance = "You are looping; emit the final Python now.\n"
user = (
f"The previous attempt to write the skill body for {category}.{draft.name} "
f"was rejected: {error}. You are looping; emit the final Python now.\n"
f"Request: {request.text}\n"
f"was rejected: {error}. {guidance}"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"{_requirements_block(requirements)}"
f"{_integration_hint_block(draft)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
@@ -597,24 +690,24 @@ def _retry_prompt(
def generate_skill_body(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
contract: str | None = None,
max_tokens: int | None = None,
degeneration_check: Callable[[str], str | None] | None = None,
requirements: dict[str, str] | None = None,
max_chars: int | None = None,
) -> str:
"""Author a skill body with the big model; retry up to `max_attempts`.
Built only from the de-identified spec (goal + generic integration), the
category, the tree, and the CODEGEN.md contract — never the user's request.
Every attempt uses the client's configured sampler parameters (or omits
them when unset). A rejected parse (ValueError) retries with a fresh short
prompt that resets the context to SMART and tells the model to emit the
final Python now. Only an invalid parse retries; a DegenerationError or
other CodegenError propagates immediately so the scheduler can stub out
gracefully. `requirements` (elicitation answers) are fed to the
first-attempt prompt only.
gracefully.
"""
contract_text = contract if contract is not None else read_skill_contract()
if client.stream:
@@ -624,16 +717,14 @@ def generate_skill_body(
for attempt in range(1, attempts + 1):
if attempt == 1:
messages = build_skill_body_prompt(
request,
category,
draft,
tree,
contract_text,
requirements=requirements,
)
else:
messages = _retry_prompt(
request, category, draft, contract_text, last_error, requirements
category, draft, contract_text, last_error
)
try:
raw = client.chat(
@@ -641,203 +732,12 @@ def generate_skill_body(
max_tokens=max_tokens,
degeneration_check=degeneration_check,
)
return parse_skill_body(raw)
return parse_skill_body(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
# ---- requirements elicitation ----
ELICITATION_EXAMPLES = [
"Should this skill really send/query/execute against the live service, or produce a reviewable draft first?",
"Which service or account should it use, and how should it connect (HTTP API base URL, IMAP/SMTP host, CalDAV URL, local CLI command)?",
"How does it authenticate with the service, and should that credential come from the app's config?",
"What does a successful run look like — what should it report back to you?",
"If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?",
"Should this skill read or send through one of the available bridge services (see the catalog below), and if so which conversation or target?",
]
def build_elicitation_prompt(
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> list[dict]:
"""Messages asking the big model to propose implementation questions.
The agent does real tasks against the user's actual services, so success
depends on pinning down how the new skill will connect. The questions
refine the product goal and the integration — never operational data values
(the runner collects those after the body is written) and never
config-vs-input cadence questions (the config step decides that at first
fire). The examples are deliberately concrete so a weaker model can mirror
them.
"""
examples = "\n".join(f"- \"{q}\"" for q in ELICITATION_EXAMPLES)
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
system = (
"You are eliciting requirements for a new skill in a local agent. The "
"agent performs real tasks for an everyday person against their actual "
"services, so success depends on understanding HOW the skill will "
"connect. You ask the human (the product owner) up to "
f"{max_questions} questions that refine the product goal and the "
"integration. Ask about product behavior and integration, not code.\n\n"
"Good example questions:\n"
f"{examples}\n\n"
"Never ask:\n"
"- for operational data values (passwords, API keys, addresses, "
"tracking numbers, hostnames) — the runner collects those after the "
"body is written;\n"
"- config-vs-input cadence questions like \"should the sender address "
"change?\" — the config step owns that decision at first fire;\n"
"- trivia you can decide yourself (variable names, formatting, "
"internal wording).\n\n"
"If the request and description already make the integration clear, "
"return an empty list rather than inventing questions.\n\n"
"Also give your best guess of the integration the questions are aiming "
"at, so the body writer implements exactly that. Reply with JSON only: "
'{"questions": ["...", "..."], "integration": {"service": '
'"<lowercase_snake_case or unknown>", "transport": '
'"<http|caldav|imap|smtp|pop|subprocess|file|compute>"}}'
)
user = (
f"Request: {request.text}\n"
f"Category: {category}\n"
f"Skill name: {draft.name}\n"
f"Skill description: {draft.description}\n"
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\n"
f"{describe_bridges()}\n"
)
return [
{"role": "system", "content": system},
{"role": "user", "content": user},
]
class ElicitationResult(NamedTuple):
"""Questions for the human plus the integration they are aiming at."""
questions: list[str]
integration: dict
def _parse_elicitation_object(raw: str) -> dict:
text = raw.strip()
start, end = text.find("{"), text.rfind("}")
if start == -1 or end == -1:
raise ValueError(f"elicitation reply is not a JSON object: {raw!r}")
try:
return json.loads(text[start : end + 1])
except ValueError as exc:
raise ValueError(f"elicitation reply is not valid JSON: {exc}") from exc
def parse_elicitation(raw: str) -> list[str]:
"""Extract a JSON {"questions": [...]} list of non-empty strings."""
parsed = _parse_elicitation_object(raw)
questions = parsed.get("questions")
if not isinstance(questions, list):
raise ValueError("elicitation reply must have a `questions` list")
cleaned = []
for question in questions:
if isinstance(question, str) and question.strip():
cleaned.append(question.strip())
return cleaned
def parse_elicitation_result(raw: str) -> ElicitationResult:
"""Questions plus the model's integration hint (service + transport).
A bad or absent hint is dropped, never fatal: the questions are the point
and the body writer can still declare the integration itself.
"""
parsed = _parse_elicitation_object(raw)
integration: dict = {}
hint = parsed.get("integration")
if isinstance(hint, dict):
service = hint.get("service")
transport = hint.get("transport")
if (
isinstance(service, str)
and _SERVICE_RE.fullmatch(service)
and transport in INTEGRATION_TRANSPORTS
):
integration = {"service": service, "transport": transport}
return ElicitationResult(parse_elicitation(raw), integration)
def _retry_elicitation_prompt(
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
error: Exception,
max_questions: int = 4,
) -> list[dict]:
messages = build_elicitation_prompt(
request, category, draft, tree, max_questions=max_questions
)
messages[1]["content"] += (
f"\nYour previous reply was rejected: {error}. Reply with JSON only: "
'{"questions": ["...", "..."], "integration": {"service": "...", '
'"transport": "..."}}'
)
return messages
def generate_elicitation(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> ElicitationResult:
"""Propose implementation questions + an integration hint with the big model.
Returns an empty result when the model produced none or the reply failed to
parse after the retry ladder — elicitation must never block authoring.
"""
attempts = max(client.max_attempts, 1)
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
if attempt == 1:
messages = build_elicitation_prompt(
request, category, draft, tree, max_questions=max_questions
)
else:
messages = _retry_elicitation_prompt(
request, category, draft, tree, last_error, max_questions=max_questions
)
try:
raw = client.chat(messages)
result = parse_elicitation_result(raw)
return ElicitationResult(
result.questions[: max(0, max_questions)], result.integration
)
except ValueError as exc:
last_error = exc
return ElicitationResult([], {})
def generate_requirements(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
tree: dict,
max_questions: int = 4,
) -> list[str]:
"""Question-only view of generate_elicitation (kept for callers/tests)."""
return generate_elicitation(
client, request, category, draft, tree, max_questions=max_questions
).questions
# ---- data contract + test ----
TESTGEN_CONTRACT = Path(__file__).resolve().parent.parent / "TESTGEN.md"
@@ -852,14 +752,15 @@ def read_testgen_contract(path: str | None = None) -> str:
def build_testgen_base_prompt(
request: Request, category: str, name: str, skill_code: str, contract_md: str
category: str, draft: SkillDraft, skill_code: str, contract_md: str
) -> list[dict]:
"""The shared context for the contract + test generation calls.
Seeded with the TESTGEN.md contract and the finished skill body; the
contract call appends its ask, and the testgen call appends the contract
output (as the assistant turn) plus its own ask — the two calls share this
context but produce distinct artifacts.
Seeded with the TESTGEN.md contract, the de-identified spec, and the
finished skill body; the contract call appends its ask, and the testgen call
appends the contract output (as the assistant turn) plus its own ask — the
two calls share this context but produce distinct artifacts. Never carries
the user's request.
"""
system = (
"You produce the data contract and test for a skill body of a "
@@ -867,8 +768,8 @@ def build_testgen_base_prompt(
f"{contract_md}"
)
user = (
f"Skill: {category}.{name}\n"
f"Request: {request.text}\n"
f"Skill: {category}.{draft.name}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Finished skill body:\n```python\n{skill_code}\n```\n"
f"{describe_bridges()}"
)
@@ -969,12 +870,12 @@ def build_testgen_request_prompt(
]
def parse_skill_test(raw: str) -> str:
def parse_skill_test(raw: str, max_chars: int | None = None) -> str:
"""Extract and validate skill.test.py from the model's reply.
Accepts bare code, ```fenced``` code, or JSON {"code": "..."}. The test
must parse as Python. Returns the cleaned source. Raises ValueError
otherwise.
must parse as Python and (when `max_chars` is set) fit the artifact size
budget. Returns the cleaned source. Raises ValueError otherwise.
"""
text = raw.strip()
if "code" in text[:400] and "{" in text and "}" in text:
@@ -997,6 +898,11 @@ def parse_skill_test(raw: str) -> str:
text = text.strip()
if not text:
raise ValueError("skill test is empty")
if max_chars is not None and len(text) > max_chars:
raise ArtifactTooLong(
f"skill test is {len(text)} chars, over the {max_chars}-char limit "
"for a codegen artifact; keep fixtures compact"
)
try:
ast.parse(text, filename="<generated test>")
except SyntaxError as exc:
@@ -1006,7 +912,6 @@ def parse_skill_test(raw: str) -> str:
def generate_skill_tests(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
skill_code: str,
@@ -1014,12 +919,14 @@ def generate_skill_tests(
contract_md: str | None = None,
reason: str | None = None,
target: str | None = None,
max_chars: int | None = None,
) -> str:
"""Generate skill.test.py against the finished body.
Shares the base context with the contract call (TESTGEN.md + skill.py) and
continues it with the accepted contract, so the test stays compatible with
the body and the contract. Fixture data is embedded inline in the test.
the body and the contract. Built only from the de-identified spec — never
the user's request. Fixture data is embedded inline in the test.
Escalates on parse failure; `reason` + `target` drive a corrective
regeneration.
"""
@@ -1033,7 +940,7 @@ def generate_skill_tests(
note = str(last_error)
messages = build_testgen_request_prompt(
build_testgen_base_prompt(
request, category, draft.name, skill_code, contract_text
category, draft, skill_code, contract_text
),
contract,
note=note,
@@ -1041,7 +948,7 @@ def generate_skill_tests(
)
try:
raw = client.chat(messages)
return parse_skill_test(raw)
return parse_skill_test(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"testgen reply rejected {attempts} times: {last_error}")
@@ -1072,7 +979,6 @@ def render_evidence(evidence: dict) -> str:
def _regen_body_prompt(
request: Request,
category: str,
draft: SkillDraft,
contract: str,
@@ -1081,7 +987,9 @@ def _regen_body_prompt(
reason_kind: str = "test",
) -> list[dict]:
"""Fresh corrective prompt carrying the raw evidence bundle, not a prose
diagnosis. `reason_kind` labels the corrective context in one word."""
diagnosis. `reason_kind` labels the corrective context in one word. Built
only from the de-identified spec and the evidence — never the user's
request."""
system = (
"You write runnable skill bodies for a local agent. The contract below "
"is authoritative: follow it exactly.\n\n"
@@ -1089,7 +997,7 @@ def _regen_body_prompt(
)
user = (
f"Correct a skill body for {category}.{draft.name} ({reason_kind}).\n"
f"Request: {request.text}\n"
f"Reusable goal (de-identified): {draft.goal}\n"
f"Skill description: {draft.description}\n"
f"Evidence:\n{render_evidence(evidence)}\n"
f"Previous body:\n```python\n{previous_code}\n```\n"
@@ -1107,21 +1015,22 @@ def _regen_body_prompt(
def regenerate_skill_body(
client: CodegenClient,
request: Request,
category: str,
draft: SkillDraft,
previous_code: str,
evidence: dict,
contract: str | None = None,
reason_kind: str = "test",
max_chars: int | None = None,
) -> str:
"""Rewrite a skill body whose test, review, or real run failed.
Fresh prompt (context resets) carrying the raw evidence bundle and the
previous body; retry ladder identical to generate_skill_body.
`reason_kind` labels the corrective context (`test`, `fidelity`, or
`run_failure`). The bundle is handed through as-is — the caller includes
requirements and the raw failure fields, never a paraphrase. A
`run_failure`). The evidence bundle must be de-identified by the caller: it
carries only the generalized failure kind, integration, goal, and previous
body — never the user's request or any run output. A
DegenerationError or other CodegenError propagates immediately.
"""
contract_text = contract if contract is not None else read_skill_contract()
@@ -1132,12 +1041,12 @@ def regenerate_skill_body(
if attempt > 1:
attempt_evidence["previous_parse_error"] = str(last_error)
messages = _regen_body_prompt(
request, category, draft, contract_text, previous_code,
category, draft, contract_text, previous_code,
attempt_evidence, reason_kind=reason_kind,
)
try:
raw = client.chat(messages)
return parse_skill_body(raw)
return parse_skill_body(raw, max_chars=max_chars)
except ValueError as exc:
last_error = exc
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
+584
View File
@@ -0,0 +1,584 @@
"""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': 'deny',
'type': 'str',
'doc': 'Global tri-state new-skill mode: deny (default) | allow | ask (a '
'category config overrides it). Deny by default: the agent leans on '
'the shipped packs, and a host opts in to live skill authoring by '
'setting allow.'},
'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'}},
'ollama': {'base_url': {'default': 'http://127.0.0.1:11434', 'type': 'str'},
'model': {'default': '', 'type': 'str'},
'context_tokens': {'default': 16384, 'type': 'int'},
'api_key': {'default': '', 'type': 'str', 'secret': True},
'timeout': {'default': 120, 'type': 'int'},
'retries': {'default': 0, 'type': 'int'},
'keep_alive': {'default': '', 'type': 'str'},
'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'},
# Reply with the skill's result line only (drop queue/
# urgency chatter and the `<skill>: ok —` wrapper).
'result_only': {'default': True, 'type': 'bool'},
# Transcribe Sideband push-to-talk voice messages
# (FIELD_AUDIO) into commands and (when reply_with_voice)
# answer a voice chat with a Piper voice reply. Needs only
# faster-whisper (requirements/transcribe.txt) plus
# piper-tts + PyAV (requirements/tts.txt) for replies,
# not the microphone stack.
'voice': {'enabled': {'default': False, 'type': 'bool'},
'reply_with_voice': {'default': True, 'type': 'bool'},
'max_speak_chars': {'default': 600, 'type': 'int'},
'reply_bitrate': {'default': 24000, 'type': 'int'},
# Read a long text (a book) aloud to a voice
# chat as a sequence of voice messages until the
# user sends "stop". Position is kept in a
# bookmarks.json beside the saved text.
'read': {'enabled': {'default': True, 'type': 'bool'},
'chunk_chars': {'default': 300, 'type': 'int'}},
'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'}}}},
'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'},
# Read a long text (a book) aloud: a skill registers a
# read-aloud request and this front end streams it through
# Piper one chunk at a time until the user stops it. The
# position is kept in a bookmarks.json beside the text.
# `chunk_chars` bounds one spoken chunk.
'read': {'enabled': {'default': True, 'type': 'bool'},
'chunk_chars': {'default': 300, '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'},
# Interrupt a spoken reply with the wake word: stop the
# playback, listen for a command, and either abort (a
# bare "stop"/"cancel") or run the new command. Disable
# for strict half-duplex (the agent never listens while
# speaking). `wait_s` bounds how long to wait for the
# interrupted playback to release the audio device.
'barge_in': {'enabled': {'default': True, 'type': 'bool'},
'wait_s': {'default': 2.0, 'type': 'float'},
'threshold': {'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.
"""
+38 -13
View File
@@ -111,8 +111,8 @@ def build_status(scheduler: Scheduler) -> dict:
else None
)
queue = [
{"id": request.id, "weight": weight, "text": request.text[:80]}
for weight, request in scheduler.queue.items()
{"id": request.id, "text": request.text[:80]}
for request in scheduler.queue.items()
]
tau = scheduler.tau
queue_max = scheduler.queue.max_size
@@ -151,7 +151,7 @@ def build_tree_payload(scheduler: Scheduler) -> dict:
]
for category, skills in sorted(snapshot.items())
},
"locks": scheduler.category_locks(),
"new_skill_modes": scheduler.category_modes(),
}
@@ -235,8 +235,8 @@ class DashboardHandler(BaseHTTPRequestHandler):
if path == "/api/approvals":
self._send(200, {"approvals": self.scheduler.pending_approvals()})
return
if path == "/api/locks":
self._send(200, {"locks": self.scheduler.category_locks()})
if path == "/api/new-skill-modes":
self._send(200, {"modes": self.scheduler.category_modes()})
return
if path == "/api/timers":
self._send(
@@ -255,13 +255,16 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail, request_id = self.scheduler.submit_request(
str(body.get("text", "")), source=str(body.get("source", "dashboard"))
reply = self._complete(
self.scheduler.submit_request(
str(body.get("text", "")),
source=str(body.get("source", "dashboard")),
)
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail, "request_id": request_id})
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
return
if path == "/api/relabel":
with self.lock:
@@ -277,11 +280,11 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.answer(str(body.get("text", "")))
reply = self._complete(self.scheduler.answer(str(body.get("text", ""))))
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
return
if path == "/api/restart":
with self.lock:
@@ -345,12 +348,12 @@ class DashboardHandler(BaseHTTPRequestHandler):
if path == "/api/cancel-build":
self._housekeeping("cancel_skill_build")
return
if path == "/api/lock":
if path == "/api/new-skill-mode":
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.set_category_lock(
str(body.get("category", "")), bool(body.get("locked"))
status, detail = self.scheduler.set_category_mode(
str(body.get("category", "")), str(body.get("mode", ""))
)
except Exception as exc:
self._send_error(500, str(exc))
@@ -372,6 +375,28 @@ class DashboardHandler(BaseHTTPRequestHandler):
return
self._send(200, {"status": status, "detail": detail})
def _complete(self, first):
"""Finish a request's chain and return the reply that answers it.
A `continue` assessment re-dispatches the next step onto the queue
rather than running it inline, so a multi-step request only completes
when a front end drains `Scheduler.run_queue()` — as the CLI and
gateway do. Without this the dashboard would run just the first step
and strand the rest. The last reply is the final answer (intermediate
steps are hidden at `result` verbosity).
"""
return [first, *self._drain_chain()][-1]
def _drain_chain(self) -> list:
"""Run queued chain steps, bounded like `GatewayService.drain`."""
replies = list(self.scheduler.drain_outbox())
for _ in range(100):
batch = self.scheduler.run_queue()
if not batch:
break
replies.extend(batch)
return replies
def log_message(self, format, *args):
pass
+26
View File
@@ -66,21 +66,47 @@ class Request:
text: str
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
source: str = "typed"
#: The originating source/chat, threaded through a continued chain (whose
#: own `source` becomes "continue"). Recall memory is keyed by this so a
#: follow-up in one chat never recalls another chat's run.
origin_source: str = ""
meta: dict[str, Any] = field(default_factory=dict)
received_at: float = field(default_factory=time.time)
priority: float = 0.5
reentries: int = 0
resume: dict[str, Any] = field(default_factory=dict)
user_input: str | None = None
#: Compact, deterministic record of the chain of skills already run toward
#: this request: one ``{query, skill (category.name), outcome}`` entry per
#: step. It threads through a continuation so the next step's routing and
#: the outcome assessment see what was already done; empty on a first-step
#: request. Bounded by construction (each outcome is bounded to the
#: speakable budget, and the chain is capped).
run_ledger: list[dict[str, Any]] = field(default_factory=list)
#: The previous *completed* run's ledger, recalled when this request arrived
#: within `query_recall_window` seconds of it (per origin source). Rendered
#: as a "previous request" context block and exposed to bodies via
#: `last_result`, so a follow-up can refer to the prior result ("send it to
#: Sam"). Deliberately separate from `run_ledger`: recall is not an in-flight
#: continuation, so it must not skip the actionability guard nor feed the
#: monotonic-progress guard. Empty when there is nothing to recall.
prior_ledger: list[dict[str, Any]] = field(default_factory=list)
#: Completion time of the recalled run (for the "Ns ago" label); 0.0 when
#: there is no recall.
prior_at: float = 0.0
def copy_for_requeue(self) -> "Request":
return Request(
text=self.text,
id=self.id,
source=self.source,
origin_source=self.origin_source,
meta=dict(self.meta),
received_at=self.received_at,
priority=self.priority,
reentries=self.reentries + 1,
resume=dict(self.resume),
run_ledger=[dict(entry) for entry in self.run_ledger],
prior_ledger=[dict(entry) for entry in self.prior_ledger],
prior_at=self.prior_at,
)
+232 -9
View File
@@ -1,16 +1,23 @@
"""Real SemIf decision engine (no mocking).
"""The decision-engine contract and the local SemIf implementation.
Wraps the SemIf package (`semif_phase1`). The import and model load happen
`DecisionEngine` is the pluggable contract every provider satisfies; the
provider is selected per machine by `engine.provider` in config.json, exactly
like `llm.provider` / `codegen.provider`. `SemIfEngine` is the default: it wraps
the SemIf package (`semif_phase1`). The import and model load happen
lazily so the rest of the agent is pure stdlib and testable without SemIf
installed. On hardware that is neither CUDA nor Apple, use the shipped
llama.cpp backend: a local GGUF scored on CPU (or Vulkan if your llama.cpp
build enables it). This engine is only usable on a machine with SemIf and the
pinned GGUF available; elsewhere calls raise EngineUnavailable.
installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
machine with SemIf and the pinned GGUF available; elsewhere calls raise
EngineUnavailable. The remote alternatives live in `semif_agent.winnow` (the
Winnow reference server) and `semif_agent.ollama_systemone` (ollama's native
System One route).
"""
from __future__ import annotations
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
@@ -18,7 +25,72 @@ from .decisions import DecisionRequest, DecisionResult
class EngineUnavailable(RuntimeError):
"""SemIf is not installed or the configured model is missing."""
"""The decision engine is not installed, not reachable, or failed.
This is the one error a decision engine raises. It is fatal by contract:
the scheduler records it (`_mark_fatal`) and the front ends exit, because
the agent cannot make decisions without a real engine.
"""
class DecisionEngine(ABC):
"""The pluggable decision-engine contract.
A decision engine answers a `DecisionRequest` (state + question + typed
options) with a `DecisionResult` (probabilities over exactly those options).
It is selected per machine by `engine.provider` in config.json, mirroring
`llm.provider` / `codegen.provider`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
* ``"winnow"`` — a remote Winnow ``/v1/systemone`` typed-decision API
(`semif_agent.winnow.WinnowEngine`).
* ``"ollama"`` — ollama's native System One ``/v1/systemone`` route
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`), probed through
ollama's own ``/api/version`` + ``/api/show`` endpoints.
The engine is always real: any failure to produce a decision raises
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the
optional text-generation face of the same model (used by
`llm.provider == "semif"`); an engine that cannot generate text raises
`EngineUnavailable` there rather than inventing a reply.
"""
label: str = "engine"
@property
def context_tokens(self) -> int:
"""The decision context window, in tokens.
Every decision state must fit inside it, so the scheduler sizes the
generated skill bodies it feeds the fidelity gate from this value. A
provider that does not expose its window keeps the conservative local
default (the local 4B engine's `engine.context_tokens`).
"""
return 4096
@property
@abstractmethod
def loaded(self) -> bool:
"""Whether the underlying model is loaded/warm."""
@abstractmethod
def warm(self) -> None:
"""Load/warm the model, raising `EngineUnavailable` on failure."""
@abstractmethod
def call(self, request: DecisionRequest) -> DecisionResult:
"""Score one decision, raising `EngineUnavailable` on failure."""
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Autoregressively generate text from the same model, if supported."""
raise EngineUnavailable(
f"{self.label} engine does not support text generation"
)
@dataclass
@@ -29,10 +101,77 @@ class EngineConfig:
gguf: str = ""
context_tokens: int = 4096
threads: int | None = None
# GPU offload (llama.cpp). 0 keeps the CPU-only default; a positive count
# offloads that many layers, -1 offloads all of them. Requires a
# llama-cpp-python built with a GPU backend (Vulkan/ROCm/CUDA).
gpu_layers: int = 0
gpu_device: int | None = None
gpu_split: int = 0
class SemIfEngine:
"""One pinned SemIf model, loaded once and used for every decision."""
def _require_gpu_offload() -> None:
"""Fail loudly when GPU layers are requested but the build cannot offload."""
import llama_cpp
if not llama_cpp.llama_supports_gpu_offload():
raise EngineUnavailable(
"engine.gpu_layers is set but this llama-cpp-python build has no GPU "
"backend. Rebuild it with one, e.g. "
"CMAKE_ARGS='-DGGML_VULKAN=on' (Vulkan), '-DGGML_HIP=on' (ROCm) or "
"'-DGGML_CUDA=on' (CUDA)."
)
def _install_gpu_state_reset(model) -> None:
"""Force a full cache reset between scored prompts when running on the GPU.
SemIf's `_Engine.clear` calls `llama_memory_clear(memory, False)`: it resets
the cache metadata but leaves the stored data. The CPU backend tolerates that
(the slots are overwritten before use), but the Vulkan backend keeps stale
hybrid-attention/recurrent state, so repeated `score` calls drift and return
wrong probabilities. Clearing the data as well restores determinism and
matches the CPU path. Applied only when offloading, so CPU behaviour is
untouched.
"""
engine = model.engine
library = engine.lib
def clear():
library.llama_memory_clear(engine.memory, True)
engine.clear = clear
def _offloading_params(original, config: EngineConfig):
"""Wrap SemIf's CPU-only model-params factory to offload layers to the GPU.
`semif_phase1.llamacpp_backend` is CPU-only by construction: its
`_cpu_model_params` hardcodes `n_gpu_layers = 0`. The backend looks that name
up on its own module while loading, so wrapping it for the duration of the
load lets the same path offload without patching (and losing) the re-cloned
engine source. The caller restores the original afterwards, so a CPU engine
loaded later in the same process is unaffected.
"""
def offloading(library):
params = original(library)
params.n_gpu_layers = config.gpu_layers
params.split_mode = config.gpu_split
if config.gpu_device is not None:
params.main_gpu = config.gpu_device
return params
return offloading
class SemIfEngine(DecisionEngine):
"""One pinned SemIf model, loaded once and used for every decision.
The default `engine.provider`: the local llama.cpp GGUF. Text generation
from the same model backs `llm.provider == "semif"`.
"""
label = "semif"
def __init__(self, config: EngineConfig):
self.config = config
@@ -59,6 +198,11 @@ class SemIfEngine:
"SemIf is not installed here. Install it on the target box with "
"`pip install -e '.[test,llamacpp]'`."
) from exc
if self.config.gpu_layers:
_require_gpu_offload()
original_params = backend._cpu_model_params
if self.config.gpu_layers:
backend._cpu_model_params = _offloading_params(original_params, self.config)
try:
model, tokenizer, metadata = backend.load_model(
self.config.source,
@@ -69,13 +213,31 @@ class SemIfEngine:
)
except Exception as exc:
raise EngineUnavailable(f"Failed to load the SemIf model: {exc}") from exc
finally:
backend._cpu_model_params = original_params
if self.config.gpu_layers:
_install_gpu_state_reset(model)
# The backend hardcodes n_gpu_layers=0 in its metadata; record what we
# actually asked llama.cpp to offload instead.
metadata = dict(metadata)
metadata["n_gpu_layers"] = self.config.gpu_layers
if self.config.gpu_device is not None:
metadata["main_gpu"] = self.config.gpu_device
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
return model, tokenizer, metadata
@property
def context_tokens(self) -> int:
return int(self.config.context_tokens or 4096)
@property
def loaded(self) -> bool:
return self._model is not None
def warm(self) -> None:
"""Load the model (idempotent), raising `EngineUnavailable` on failure."""
self._ensure_loaded()
def call(self, request: DecisionRequest) -> DecisionResult:
with self._lock:
model, tokenizer, metadata = self._ensure_loaded()
@@ -95,3 +257,64 @@ class SemIfEngine:
},
)
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Drive the pinned decision model in the normal way: text generation.
SemIf scoring reads option logits directly; this instead autoregressively
samples from the same llama.cpp context, e.g. for skill-tree authoring.
Generation decodes the chat template through the backend's low-level
context (there is no high-level chat-completion object on the CPU
backend), stopping at the tokenizer's eos token. The KV cache is cleared
at the start, so interleaving scoring and generation on one model is safe.
It shares `self._lock` with `call`, so a generation serializes against
decisions on the one loaded model — short JSON replies are seconds of
contention, and there is only ever one copy of the GGUF.
"""
with self._lock:
model, tokenizer, metadata = self._ensure_loaded()
try:
import numpy
engine = model.engine
prompt_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
prompt_ids = tokenizer.encode(prompt_text, add_special_tokens=False)
engine.clear()
logits = engine._decode(prompt_ids, 0, 0, True)
generated: list[int] = []
rng = numpy.random.default_rng()
for position in range(max_tokens):
token = _sample_token(logits, temperature, rng)
if token == tokenizer.eos_token_id:
break
generated.append(token)
logits = engine._decode([token], len(prompt_ids) + position, 0, True)
return tokenizer.decode(generated).strip()
except EngineUnavailable:
raise
except Exception as exc:
raise EngineUnavailable(f"generation failed: {exc}") from exc
def _sample_token(logits, temperature: float, rng) -> int:
"""Pick the next token from next-position logits: greedy or temperature."""
import numpy
if temperature <= 0.0:
return int(numpy.argmax(logits))
scaled = numpy.asarray(logits, dtype=numpy.float64) / max(temperature, 1e-6)
scaled = scaled - scaled.max()
probabilities = numpy.exp(scaled)
probabilities /= probabilities.sum()
return int(rng.choice(probabilities.size, p=probabilities))
+63 -5
View File
@@ -35,26 +35,84 @@ class InboundMessage:
@dataclass
class OutboundMessage:
"""One reply destined for an external chat."""
"""One reply destined for an external chat.
`text` is the reply. `stream` optionally carries a long-form read-aloud
request (a `semif_agent.speech.ReadAloud`) instead of a plain line: the
voice front end streams it chunk-by-chunk with text-to-speech until the user
stops it. A platform that does not stream leaves it None and speaks `text`.
"""
chat_id: str
text: str
stream: Any = None
#: Callback the adapter invokes for each authorized inbound message.
InboundHandler = Callable[[InboundMessage], None]
#: Words/phrases that abort a long-form read-aloud (and a spoken reply) when
#: heard/typed. The match is on the whole normalized utterance (so "stop the
#: timer" stays a real command) with a first-word fallback only for a short
#: utterance with trailing filler ("stop please", "cancel that"). Shared by the
#: voice and LXMF adapters, which both stream read-aloud text.
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_STOP_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def is_stop_command(text: str) -> bool:
"""Whether an utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts a spoken reply / long-form read. Anything
longer is a real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_STOP_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_STOP_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_STOP_PUNCT) in _STOP_FILLER for word in words[1:])
class GatewayAdapter(ABC):
"""Transport contract for a messenger platform."""
#: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway"
#: Spoken front ends (the voice gateway) set this so the service speaks only
#: the skill's result line, not the scheduler's bookkeeping (queue/urgency
#: status) and not the `<skill>: ok —` wrapper. A per-platform config
#: `result_only` overrides it. Plain chat adapters leave it False.
#: Front ends that should send only the skill's result line set this, so the
#: service drops the scheduler's bookkeeping (queue/urgency status) and the
#: `<skill>: ok —` wrapper. The voice gateway and the LXMF gateway set it; a
#: per-platform config `result_only` overrides it either way.
result_only: bool = False
@abstractmethod
+93
View File
@@ -0,0 +1,93 @@
"""Optional LLM cleanup of a skill's result line for the messenger gateway.
The scheduler's run summary is deterministic and technical — ``<skill>:
<ok|failed> — <action_log>``, where the action log is whatever the skill body
wrote (often mechanical: ``PUT 201 …``, ``sent via /_send to contact 12``).
This layer rewrites only that result detail into one grounded, friendly
sentence for a chat front end.
It is generation, never a decision: the success/failure verdict and the routing
are already settled by SemIf and the runner, and the rewrite is never fed back
into assessment, tracing, or the decision log. The prompt forbids adding,
inferring, or dropping facts, and `humanize` falls back to the original text on
any error, timeout, empty reply, or runaway length — a cleanup failure
must never swallow or corrupt a real result.
It reuses the scheduler's configured ``llm`` client (its endpoint/model/sampler)
and passes a short per-call ``timeout`` so a slow cleanup cannot hold the
gateway's poll loop for the client's full authoring budget. It is deliberately
gateway-only: the runner and the REPL keep the raw, deterministic summary.
"""
from __future__ import annotations
#: The strict rephrasing instruction. Grounding is enforced by the prompt and
#: by the caller's fallback, not by a second model call.
SYSTEM_PROMPT = (
"You rewrite an assistant's raw action result into one short, friendly "
"sentence for a chat reply.\n"
"Rules:\n"
"- Use ONLY the facts in the result. Do not add, guess, or infer anything.\n"
"- Preserve whether the action succeeded or failed exactly as stated.\n"
"- Do not mention servers, HTTP status codes, command names, file paths, "
"or internal bookkeeping unless that is the only content.\n"
"- One sentence. No preamble, no explanation, no quotes, no markdown.\n"
"- If the result is already a plain sentence, return it unchanged."
)
def _clean_reply(raw: str) -> str:
"""Normalize a model reply into one bare sentence, or "" if unusable."""
text = (raw or "").strip()
if not text:
return ""
# Drop a wrapping pair of quotes the model may add.
if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'“”‘’":
text = text[1:-1].strip()
# Collapse newlines / runs of whitespace to a single line.
return " ".join(text.split())
class Humanizer:
"""Rewrite a result line with an LLM, falling back to the source verbatim."""
def __init__(
self,
client,
*,
enabled: bool = True,
timeout: float = 20.0,
max_tokens: int = 200,
max_chars: int = 600,
):
self.client = client
self.enabled = bool(enabled) and client is not None
self.timeout = float(timeout)
self.max_tokens = int(max_tokens)
self.max_chars = int(max_chars)
def humanize(self, text: str) -> str:
"""Return a grounded rewrite of `text`, or `text` unchanged.
Never raises: any failure (unreachable client, timeout, empty or
unusable reply, runaway length) returns the original text.
"""
source = (text or "").strip()
if not self.enabled or not source:
return text
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": source},
]
try:
raw = self.client.chat(
messages, max_tokens=self.max_tokens, timeout=self.timeout
)
except Exception:
return text
cleaned = _clean_reply(raw)
if not cleaned:
return text
if len(cleaned) > self.max_chars:
return text
return cleaned
+494 -25
View File
@@ -11,6 +11,32 @@ This adapter is the policy layer over the neutral `LxmfDaemon` transport in
and hands authorized text to the scheduler. Unlike the SimpleX adapter there is
no external daemon and no event loop — Reticulum runs in-process on its own
threads, so batching uses a per-chat `threading.Timer`.
**Voice commands.** A Sideband push-to-talk message arrives as LXMF content with
an empty body and the audio in `FIELD_AUDIO` (`[audio_mode, bytes]`); the
transport surfaces it as a normalized `audio` dict. When `voice.enabled` is set,
this adapter transcribes that payload to text and dispatches the transcript as an
ordinary command — so the same allowlist, batching-free delivery, and reply path
apply. Both PTT shapes are handled: HQ Opus/OGG goes through
`WhisperTranscriber.transcribe_bytes` (faster-whisper's bundled PyAV decodes the
container), and non-HQ Codec2 is decoded to 8 kHz PCM by `voice_transport.
decode_codec2` (the optional `pycodec2` bindings), wrapped in a WAV, and
transcribed the same way. Transcription needs only `faster-whisper`
(`requirements/transcribe.txt`), never the microphone voice stack; Codec2
additionally needs `pycodec2` (`requirements/codec2.txt`). A missing transcriber,
missing Codec2 decoder, or undecodable mode is traced and reported, never
silently dropped; the audio itself is transient and never stored, exactly like
the voice gateway.
**Voice replies.** When `voice.reply_with_voice` is on (the default), a reply to
a chat that last messaged by voice is synthesized with Piper and sent back as a
Sideband HQ push-to-talk voice message (the reply text is encoded to Opus/OGG
and rides `FIELD_AUDIO`), so a voice user hears the answer. The reply *mode*
follows the chat's most recent inbound message: a text message reverts it to
text replies. It needs `piper-tts` + PyAV (`requirements/tts.txt`), never the
microphone stack; a missing synthesizer, a synthesis failure, or an encode
failure is traced and the reply falls back to text — never dropped. The reply
text is also sent as the message content, so a text-only client still sees it.
"""
from __future__ import annotations
@@ -18,16 +44,54 @@ from __future__ import annotations
import os
import queue
import threading
import time
from semif_agent.lxmf_transport import LxmfDaemon
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import (
OPUS_OGG_BITRATE,
build_synthesizer,
build_transcriber,
check_codec2_requirements,
check_synthesis_requirements,
check_transcription_requirements,
decode_codec2,
pcm_to_opus_ogg,
pcm_to_wav,
)
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: Sent (once) when a voice message can't be transcribed at all. A spoken or
#: typed command still works, so the user is not left guessing.
VOICE_FAILED_MESSAGE = (
"Sorry, I couldn't make out that voice message — please resend it or type "
"your command."
)
#: Sent when the codec is one we can't decode (the raw Opus `AM_OPUS_*` modes
#: and the binding-less 450 Codec2 modes; HQ Opus is the default and works).
VOICE_UNSUPPORTED_MESSAGE = (
"I can't read that voice format yet — send an HQ (Opus) voice message, or "
"type your command."
)
#: Sent for a Codec2 voice message when the optional Codec2 decoder is absent.
VOICE_CODEC2_MESSAGE = (
"I can't read that Codec2 voice message — the codec2 decoder isn't "
"installed. Send an HQ (Opus) voice message, or type your command."
)
class LxmfAdapter(GatewayAdapter):
name = "lxmf"
#: Send the skill's result line only — drop the scheduler's queue/urgency
#: bookkeeping and the `<skill>: ok —` wrapper, so a reply (text or voice) is
#: the answer, not the internals. Override with `gateway.lxmf.result_only:
#: false` for the full scheduler output.
result_only = True
def __init__(self, cfg: dict | None = None, trace=None):
def __init__(
self, cfg: dict | None = None, trace=None, transcriber=None, synthesizer=None
):
cfg = cfg or {}
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
self.allow_all_users = bool(cfg.get("allow_all_users", False))
@@ -51,15 +115,73 @@ class LxmfAdapter(GatewayAdapter):
)
self.config_dir = config_dir
self.storage_path = storage_path
#: Voice-message transcription (`gateway.lxmf.voice`). The transcriber is
#: built lazily from `voice.stt` (faster-whisper only) on the first
#: voice message; a test can inject one instead.
self.voice_cfg = cfg.get("voice", {}) or {}
self.voice_enabled = bool(self.voice_cfg.get("enabled", False))
#: Reply to a voice chat with a synthesized voice message (Piper). The
#: reply mode follows the chat's most recent inbound message.
self.reply_with_voice = bool(self.voice_cfg.get("reply_with_voice", True))
self.voice_max_chars = int(self.voice_cfg.get("max_speak_chars", 600) or 0)
self.voice_bitrate = int(
self.voice_cfg.get("reply_bitrate", OPUS_OGG_BITRATE) or OPUS_OGG_BITRATE
)
self._transcriber = transcriber
self._transcriber_unavailable = False
self._synthesizer = synthesizer
self._synthesizer_unavailable = False
#: Chats whose most recent inbound message was voice: their replies go
#: back as voice (until a text message reverts them).
self._voice_chats: set[str] = set()
self._voice_queue: "queue.Queue[tuple[dict, dict] | None]" = queue.Queue()
self._voice_thread: threading.Thread | None = None
self._voice_lock = threading.Lock()
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
self._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {}
self._buffered: dict[str, dict] = {}
self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock()
self._on_inbound = None
#: Read-aloud: a book is streamed to a voice chat as a sequence of
#: voice messages, one Piper-synthesized chunk each, until the user
#: sends "stop" or a new command. Only a voice chat can receive it, so
#: a text chat keeps the skill's saved-file summary.
read_cfg = self.voice_cfg.get("read", {}) or {}
self._read_enabled = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
#: How many messages may be queued on the daemon ahead of the stream
#: (backpressure so a stop is prompt).
self._read_max_lead = max(1, int(read_cfg.get("max_lead", 4) or 4))
self._read_lock = threading.Lock()
self._read_stop = threading.Event()
self._read_key: str | None = None
self._read_chat: str | None = None
@property
def supports_speech_stream(self) -> bool:
"""Whether this adapter can deliver a read-aloud at all.
Only when voice replies are on: a read-aloud is sent as voice messages.
Whether a *particular* chat can receive one is `speech_stream_ready`.
"""
return bool(self.voice_enabled and self.reply_with_voice and self._read_enabled)
def speech_stream_ready(self, chat: str) -> bool:
"""Whether `chat` should get a read-aloud (it last messaged by voice)."""
if not self.supports_speech_stream:
return False
with self._lock:
return str(chat) in self._voice_chats
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
# Only the transport is mandatory: text commands work without the
# optional transcription stack, and a voice message then traces
# `lxmf_voice_unavailable` rather than taking the whole gateway down.
return self.daemon.check_requirements()
# ---- authorization ----
@@ -82,17 +204,29 @@ class LxmfAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Translate the service's OutboundMessage queue onto the daemon's
# (chat_id, text) queue without letting scheduler work touch the
# Reticulum callback threads.
# (chat_id, text, audio) queue without letting scheduler work touch
# the Reticulum callback threads. Synthesis runs here (off the router
# thread), so a slow Piper render never stalls the transport.
while True:
message = outbound.get()
if message is None:
self.daemon.enqueue(None)
return
self.daemon.enqueue(message.chat_id, message.text)
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump.
self.daemon._event(
"lxmf_read_failed", message=str(exc)[:300]
)
continue
audio = self._voice_reply(message)
self.daemon.enqueue(message.chat_id, message.text, audio=audio)
threading.Thread(
target=_pump, name="lxmf-outbound-pump", daemon=True
@@ -105,6 +239,7 @@ class LxmfAdapter(GatewayAdapter):
self._timers.clear()
for timer in timers:
timer.cancel()
self._voice_queue.put(None)
self.daemon.close()
# ---- inbound ----
@@ -121,23 +256,23 @@ class LxmfAdapter(GatewayAdapter):
display_name=display_name,
)
return
inbound = InboundMessage(
text=message.get("content") or "",
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
self._schedule_flush(inbound)
audio = message.get("audio")
if audio:
# A voice message puts the chat in voice-reply mode (when the reply
# path is on); a later text message reverts it.
if self.voice_enabled and self.reply_with_voice:
self._mark_voice_chat(source_hash)
self._handle_audio(message, audio)
return
self._unmark_voice_chat(source_hash)
self._schedule_flush(message)
def _schedule_flush(self, message: InboundMessage) -> None:
chat = message.chat_id
def _schedule_flush(self, message: dict) -> None:
chat = str(message.get("source_hash") or "")
text = message.get("content") or ""
with self._lock:
existing = self._buffers.get(chat)
self._buffers[chat] = (
f"{existing}\n{message.text}" if existing else message.text
)
self._buffers[chat] = f"{existing}\n{text}" if existing else text
self._buffered[chat] = message
timer = self._timers.get(chat)
if timer is not None:
@@ -154,12 +289,346 @@ class LxmfAdapter(GatewayAdapter):
self._timers.pop(chat, None)
if message is None or not text:
return
message.text = text
self._deliver(message, text)
def _deliver(self, message: dict, text: str) -> None:
"""Hand one command to the service (never called on the router thread)."""
source_hash = str(message.get("source_hash") or "")
display_name = message.get("display_name")
# Any command interrupts a read-aloud playing to this chat; a bare
# "stop"/"cancel" is not submitted as a request.
if self._stop_read_for_command(source_hash):
self.daemon._event(
"lxmf_read_stopped", contact_id=source_hash, chars=len(text)
)
if is_stop_command(text):
return
self.daemon._event(
"gateway_message",
contact_id=message.contact_id,
display_name=message.display_name,
contact_id=source_hash,
display_name=display_name,
chars=len(text),
)
if self._on_inbound is not None:
self._on_inbound(message)
if self._on_inbound is None:
return
self._on_inbound(
InboundMessage(
text=text,
chat_id=source_hash,
chat_type="dm",
contact_id=source_hash,
display_name=display_name,
raw=message.get("raw") or {},
)
)
# ---- voice messages (Sideband push-to-talk) ----
def _handle_audio(self, message: dict, audio: dict) -> None:
"""Route a received voice message to transcription, or report why not.
Runs on the Reticulum callback thread, so it only enqueues: the actual
(slow) transcription happens on the worker thread, keeping the router
responsive. An ignored/undecodable payload keeps any caption text.
"""
source_hash = str(message.get("source_hash") or "")
codec = audio.get("codec_name")
content = message.get("content") or ""
if not self.voice_enabled:
self.daemon._event(
"lxmf_voice_ignored", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
return
kind = audio.get("kind")
if kind == "codec2":
# Codec2 needs the optional pycodec2 bindings; report a missing one
# up front rather than queueing a transcription that can't happen.
ok, _hint = check_codec2_requirements()
if not ok:
self.daemon._event(
"lxmf_voice_codec2_unavailable", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_CODEC2_MESSAGE)
return
elif kind != "opus_ogg":
self.daemon._event(
"lxmf_voice_unsupported_codec", contact_id=source_hash, codec=codec
)
if content:
self._schedule_flush(message)
else:
self._notify(message, VOICE_UNSUPPORTED_MESSAGE)
return
self._ensure_voice_worker()
self._voice_queue.put((message, audio))
def _ensure_voice_worker(self) -> None:
with self._voice_lock:
if self._voice_thread is not None and self._voice_thread.is_alive():
return
self._voice_thread = threading.Thread(
target=self._voice_worker, name="lxmf-voice-worker", daemon=True
)
self._voice_thread.start()
def _voice_worker(self) -> None:
"""Transcribe queued voice messages off the Reticulum callback thread."""
while True:
item = self._voice_queue.get()
if item is None:
return
message, audio = item
text = self._transcribe(audio)
content = (message.get("content") or "").strip()
if not text:
if content:
self._deliver(message, content)
else:
self._notify(message, VOICE_FAILED_MESSAGE)
continue
self._deliver(message, f"{content}\n{text}" if content else text)
def _transcribe(self, audio: dict) -> str:
"""Transcribe one audio payload to text; "" (traced) on any failure."""
transcriber = self._ensure_transcriber()
if transcriber is None:
return ""
data = audio.get("data") or b""
if not data:
self.daemon._event("lxmf_voice_empty", codec=audio.get("codec_name"))
return ""
if audio.get("kind") == "codec2":
# Codec2 decodes to raw 8 kHz PCM; wrap it in a WAV so faster-whisper's
# PyAV decodes and resamples it like any other container.
pcm = decode_codec2(data, audio.get("codec2_rate") or 0)
if not pcm:
self.daemon._event(
"lxmf_voice_codec2_failed", codec=audio.get("codec_name")
)
return ""
payload = pcm_to_wav(pcm, 8000)
else:
payload = data
try:
text = transcriber.transcribe_bytes(payload)
except NotImplementedError:
self.daemon._event(
"lxmf_voice_transcribe_unsupported", codec=audio.get("codec_name")
)
return ""
except Exception as exc:
self.daemon._event(
"lxmf_voice_transcribe_failed", message=str(exc)[:300]
)
return ""
text = (text or "").strip()
if not text:
self.daemon._event(
"lxmf_voice_empty_transcript", codec=audio.get("codec_name")
)
return ""
self.daemon._event(
"lxmf_voice_transcribed", codec=audio.get("codec_name"), chars=len(text)
)
return text
def _ensure_transcriber(self):
"""Build (once) and return the transcriber, or None (traced) if absent."""
with self._voice_lock:
if self._transcriber is not None:
return self._transcriber
if self._transcriber_unavailable:
return None
ok, hint = check_transcription_requirements()
if not ok:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=hint)
return None
try:
self._transcriber = build_transcriber(self.voice_cfg)
except Exception as exc:
self._transcriber_unavailable = True
self.daemon._event("lxmf_voice_unavailable", message=str(exc)[:300])
return None
return self._transcriber
def _notify(self, message: dict, text: str) -> None:
"""Send a transport-level notice back to the sender (best-effort).
A transcription failure is reported to the user rather than silently
dropped; the audio itself is never stored or forwarded.
"""
chat = str(message.get("source_hash") or "")
outbound = self._outbound
if outbound is None or not chat:
return
outbound.put(OutboundMessage(chat_id=chat, text=text))
# ---- voice replies (Piper -> Opus/OGG) ----
def _mark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.add(chat)
def _unmark_voice_chat(self, chat: str) -> None:
with self._lock:
self._voice_chats.discard(chat)
def _voice_reply(self, message) -> bytes | None:
"""Synthesize a voice reply for a voice chat, or None to send text.
Runs on the outbound pump thread. Returns an OGG/Opus container (a
Sideband HQ push-to-talk payload) or None — for a text chat, an empty
reply, or any synthesis/encode failure (traced), in which case the
caller sends the text reply unchanged.
"""
if not self.reply_with_voice:
return None
chat = str(message.chat_id)
with self._lock:
is_voice = chat in self._voice_chats
if not is_voice:
return None
text = (message.text or "").strip()
if not text:
return None
if self.voice_max_chars and len(text) > self.voice_max_chars:
clipped = text[: self.voice_max_chars].rsplit(" ", 1)[0]
text = clipped or text[: self.voice_max_chars]
synthesizer = self._ensure_synthesizer()
if synthesizer is None:
return None
try:
pcm, sample_rate = synthesizer.synthesize(text)
except Exception as exc:
self.daemon._event("lxmf_voice_synth_failed", message=str(exc)[:300])
return None
if not pcm:
self.daemon._event("lxmf_voice_synth_empty")
return None
audio = pcm_to_opus_ogg(pcm, sample_rate, self.voice_bitrate)
if not audio:
self.daemon._event("lxmf_voice_encode_failed", chars=len(text))
return None
self.daemon._event(
"lxmf_voice_reply", chars=len(text), audio_bytes=len(audio)
)
return audio
def _ensure_synthesizer(self):
"""Build (once) and return the Piper synthesizer, or None (traced)."""
with self._voice_lock:
if self._synthesizer is not None:
return self._synthesizer
if self._synthesizer_unavailable:
return None
ok, hint = check_synthesis_requirements()
if not ok:
self._synthesizer_unavailable = True
self.daemon._event("lxmf_voice_tts_unavailable", message=hint)
return None
try:
self._synthesizer = build_synthesizer(self.voice_cfg)
except Exception as exc:
self._synthesizer_unavailable = True
self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300])
return None
return self._synthesizer
# ---- read-aloud (a book streamed as voice messages) ----
def _stop_read_for_command(self, chat: str) -> bool:
"""Stop a read-aloud playing to `chat`; report whether one was active."""
with self._read_lock:
if self._read_key is None or self._read_chat != str(chat):
return False
self._read_stop.set()
return True
def _synthesize_chunk(self, text: str) -> bytes | None:
"""Piper-synthesize one chunk to Opus/OGG, or None (send it as text)."""
synthesizer = self._ensure_synthesizer()
if synthesizer is None:
return None
try:
pcm, sample_rate = synthesizer.synthesize(text)
except Exception as exc:
self.daemon._event("lxmf_voice_synth_failed", message=str(exc)[:300])
return None
if not pcm:
return None
audio = pcm_to_opus_ogg(pcm, sample_rate, self.voice_bitrate)
if not audio:
self.daemon._event("lxmf_voice_encode_failed", chars=len(text))
return None
return audio
def _stream(self, read) -> None:
"""Stream a read-aloud request as a sequence of voice messages.
Runs on the outbound pump thread: each chunk is synthesized and queued
to the daemon, and the bookmark is written before it is sent so a stop
leaves the position at the interrupted chunk. The read ends when the
text is finished or the user interrupts (a stop flag set by `_deliver`).
"""
chat = str(read.source or "").split(":", 1)[-1]
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
self._read_chat = chat
try:
if not chat or not self.speech_stream_ready(chat):
return
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"lxmf_read_failed", contact_id=chat, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
if self.voice_max_chars > 0:
chunk_chars = min(chunk_chars, self.voice_max_chars)
self.daemon._event(
"lxmf_read_start",
contact_id=chat,
key=read.key,
start=read.start,
chars=len(text),
)
sent = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
# Keep only a few messages queued ahead so a stop takes effect
# promptly instead of after a large backlog drains.
while not stop.is_set() and self.daemon.pending_sends() >= self._read_max_lead:
time.sleep(0.05)
if stop.is_set():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.enqueue(chat, chunk, audio=self._synthesize_chunk(chunk))
sent += 1
if stop.is_set():
self.daemon._event(
"lxmf_read_interrupted", contact_id=chat, key=read.key, chunks=sent
)
else:
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event(
"lxmf_read_done", contact_id=chat, key=read.key, chunks=sent
)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
self._read_chat = None
+303 -39
View File
@@ -22,51 +22,86 @@ reaches the right chat.
from __future__ import annotations
import queue
import re
import threading
import time
from .base import InboundMessage, OutboundMessage
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
from .humanize import Humanizer
#: The scheduler's run summary wraps the real result as
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
#: gateway) speaks just `<detail>`.
#: gateway) speaks just `<detail>`. Kept as a fallback for callers that hand
#: `_reply` a raw summary; the scheduler itself passes the unwrapped `result`.
_RESULT_SEP = " — "
_REPAIR_ACTIONS = {
"retry": "retry",
"repair": "repair_skill",
"fix": "repair_skill",
"repair_skill": "repair_skill",
"ask": "ask_user",
"ask_user": "ask_user",
"no": "no_repair",
"skip": "no_repair",
"cancel": "no_repair",
"no_repair": "no_repair",
}
_APPROVAL_ACTIONS = {
"yes": True,
"y": True,
"yeah": True,
"yep": True,
"yup": True,
"approve": True,
"approved": True,
"ok": True,
"okay": True,
"sure": True,
"confirm": True,
"affirmative": True,
"go ahead": True,
"do it": True,
"no": False,
"n": False,
"nope": False,
"deny": False,
"denied": False,
"cancel": False,
"skip": False,
"never mind": False,
"nevermind": False,
"dont": False,
"don't": False,
"stop": False,
}
#: An owner target is `(platform, chat_id)`.
Target = tuple[str, str]
def _strip_run_id(text: str) -> str:
return _LEADING_RUN_ID.sub("", text or "")
#: Characters stripped from the edges of a spoken reply before matching an
#: action. STT emits sentence punctuation the fixed vocabulary does not carry
#: ("Approve.", "Yes."), so a bare `in _APPROVAL_ACTIONS` lookup silently misses.
_ACTION_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def _leading_run_id(text: str) -> str:
match = _LEADING_RUN_ID.match(text or "")
return match.group(0)[1:-2] if match else ""
def _normalize_action(text: str) -> str:
"""Normalize a spoken reply into a command-vocabulary key.
Speech-to-text appends sentence punctuation ("Approve.", "Yes.") that the
fixed `_REPAIR_ACTIONS` / `_APPROVAL_ACTIONS` maps do not carry, so an exact
lookup drops a perfectly clear answer into `submit_request` and the pending
approval times out. Lowercase, strip edge whitespace/punctuation, then fall
back to the first word so "yes please" / "approve it" match. Returns "" for
empty input. This stays a deterministic command vocabulary — no model.
"""
cleaned = (text or "").strip().lower().strip(_ACTION_PUNCT)
if not cleaned:
return ""
if cleaned in _REPAIR_ACTIONS or cleaned in _APPROVAL_ACTIONS:
return cleaned
first = cleaned.split(None, 1)[0]
return first.strip(_ACTION_PUNCT)
def _result_detail(text: str) -> str:
@@ -82,7 +117,7 @@ def _result_detail(text: str) -> str:
def _reply_kind(status: str) -> str:
"""Classify a scheduler outcome for a result-only front end."""
if status in ("running", "preempted", "ran"):
if status in ("running", "ran"):
return "result"
if status == "needs_input":
return "question"
@@ -112,6 +147,7 @@ class GatewayService:
adapters,
config: dict | None = None,
poll_interval: float = 1.0,
humanizer: Humanizer | None = None,
):
self.scheduler = scheduler
self.adapters = _normalize_adapters(adapters)
@@ -125,6 +161,31 @@ class GatewayService:
self._platform_cfg: dict[str, dict] = {
platform: self._config_for(platform) for platform in self.platforms
}
#: Optional LLM result cleanup (gateway-only presentation). Built from
#: the scheduler's `llm` client unless one is injected; a no-op unless
#: `gateway.humanize.enabled` (or a per-platform override) turns it on.
if humanizer is not None:
self.humanizer = humanizer
self._humanize_default = bool(humanizer.enabled)
else:
humanize_cfg = self.config.get("humanize")
humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {}
self._humanize_default = bool(humanize_cfg.get("enabled", False))
self.humanizer = self._build_humanizer(humanize_cfg)
#: Let an adapter that needs it gate input on the scheduler being free
#: (the voice gateway holds the wake word until the current request
#: reaches a result). Generic hook; only some adapters implement it.
for adapter in self.adapters.values():
setter = getattr(adapter, "set_input_ready", None)
if callable(setter):
setter(self.input_ready)
#: Tell the scheduler's speech channel which sources this service can
#: stream a read-aloud to, so a skill asks before it posts one.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
setter = getattr(speech, "set_stream_check", None)
if callable(setter):
setter(self.stream_ready)
self._owners: dict[str, Target] = {}
self._parents: dict[str, str] = {}
self._pending_owner: Target | None = None
@@ -165,6 +226,71 @@ class GatewayService:
return bool(cfg["result_only"])
return bool(getattr(self.adapters.get(platform), "result_only", False))
# ---- optional LLM result cleanup ----
def _build_humanizer(self, cfg: dict) -> Humanizer | None:
"""Build the result humanizer from config + the scheduler's `llm`.
Global defaults live in `gateway.humanize`; a per-platform
`gateway.<platform>.humanize` (bool or `{enabled, timeout, max_tokens,
max_chars}`) overrides the enable flag. Returns None when no `llm`
client is available, so a client-less scheduler degrades to no cleanup.
The instance is always built `enabled`; the global default is kept
separately so a per-platform override can turn it on or off.
"""
client = getattr(self.scheduler, "llm", None)
if client is None:
return None
return Humanizer(
client,
enabled=True,
timeout=float(cfg.get("timeout", 20.0)),
max_tokens=int(cfg.get("max_tokens", 200)),
max_chars=int(cfg.get("max_chars", 600)),
)
def _humanize_enabled(self, platform: str, skill_ref: str | None = None) -> bool:
"""Whether this result is cleaned up.
Precedence: the **skill's own config** (`data/skills/<category>/<name>/
config.json` -> `{"humanize": bool}`) wins; otherwise the per-platform
override (`gateway.<platform>.humanize`), otherwise the global default
(`gateway.humanize.enabled`). A missing `llm` client disables it.
"""
if self.humanizer is None:
return False
skill_override = self._skill_humanize_override(skill_ref)
if skill_override is not None:
return skill_override
override = self._platform_cfg.get(platform, {}).get("humanize")
if isinstance(override, bool):
return override
if isinstance(override, dict) and "enabled" in override:
return bool(override["enabled"])
return self._humanize_default
def _skill_humanize_override(self, skill_ref: str | None) -> bool | None:
"""The skill's own `humanize` config value, or None when unset.
A skill opts in/out of result cleanup regardless of the platform default
via its recorded config: `data/skills/<category>/<name>/config.json` ->
`{"humanize": false}`. Read from the scheduler's skill store; a missing
store/config/key (or an unparseable ref) means no override.
"""
if not skill_ref or "." not in skill_ref:
return None
store = getattr(self.scheduler, "body_store", None)
if store is None:
return None
category, name = skill_ref.split(".", 1)
try:
config = store.read_config(category, name) or {}
except Exception:
return None
if "humanize" in config:
return bool(config["humanize"])
return None
def _fallback_target(self) -> Target | None:
for platform in self.platforms:
home = self._home_channel(platform)
@@ -207,22 +333,69 @@ class GatewayService:
return (platform, source[len(prefix):])
return None
def input_ready(self) -> bool:
"""Whether a new command may start now.
False while the single scheduler slot is executing a run; True when the
scheduler is idle or paused for the user's answer to a question (the run
is not running, so the answer must be accepted). The voice gateway uses
this to hold the wake word until the current request has reached a
result. Reads the scheduler's flags without its lock on purpose — the
lock is held for the whole run, so acquiring it here would block the
audio loop for the duration of the run.
"""
scheduler = self.scheduler
if getattr(scheduler, "pending", None) is not None:
return True
return getattr(scheduler, "current", None) is None
def stream_ready(self, source: str) -> bool:
"""Whether this service can stream a read-aloud to `source`.
The owning platform's adapter decides: the voice gateway always can
(when `read.enabled`); the LXMF adapter only for a chat that last
messaged by voice (a text chat keeps the saved-file summary). A source
with no known owner is not streamed.
"""
target = self._owner_from_source(source)
if target is None:
return False
platform, chat = target
adapter = self.adapters.get(platform)
if adapter is None:
return False
check = getattr(adapter, "speech_stream_ready", None)
if callable(check):
try:
return bool(check(chat))
except Exception:
return False
return bool(getattr(adapter, "supports_speech_stream", False))
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
"""Handle one authorized inbound command. Called by the adapter."""
if platform is None:
platform = self.platforms[0] if self.platforms else ""
with self._route_lock:
reply_to: Target = (platform, msg.chat_id)
#: A single command-vocabulary key for this reply (punctuation- and
#: case-insensitive), so a spoken "Approve." / "Yes." matches the
#: approval and repair maps exactly like a typed "yes".
action = _normalize_action(msg.text)
pending = self.scheduler.pending
if pending is not None and self._pending_owner is None:
self._pending_owner = self._owner_from_source(pending.request.source)
if pending is not None and pending.request.source == self.source_for(
platform, msg.chat_id
):
status, detail = self.scheduler.answer(msg.text)
reply = self.scheduler.answer(msg.text)
if self.scheduler.pending is None:
self._pending_owner = None
self._reply(*reply_to, detail, kind=_reply_kind(status))
if not self._hidden(reply):
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
elif pending is not None and self._pending_owner not in (None, reply_to):
self._reply(
*reply_to,
@@ -234,45 +407,75 @@ class GatewayService:
status, detail = self.scheduler.answer_question(question_id, msg.text)
self._surfaced.add(question_id)
self._reply(*reply_to, detail, kind="notice")
elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
elif reply_to in self._repair_for_chat and action in _REPAIR_ACTIONS:
offer_id = self._repair_for_chat.pop(reply_to)
action = _REPAIR_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.resolve_repair(offer_id, action)
status, detail = self.scheduler.resolve_repair(
offer_id, _REPAIR_ACTIONS[action]
)
self._surfaced.add(offer_id)
self._reply(*reply_to, detail, kind="notice")
elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
elif reply_to in self._approval_for_chat and action in _APPROVAL_ACTIONS:
approval_id = self._approval_for_chat.pop(reply_to)
approved = _APPROVAL_ACTIONS[msg.text.strip().lower()]
approved = _APPROVAL_ACTIONS[action]
status, detail = self.scheduler.answer_approval(approval_id, approved)
self._surfaced.add(approval_id)
self._reply(*reply_to, detail, kind="notice")
else:
status, detail, run_id = self.scheduler.submit_request(
reply = self.scheduler.submit_request(
msg.text, source=self.source_for(platform, msg.chat_id)
)
if run_id:
self._owners[run_id] = reply_to
if status == "needs_input":
if reply.run_id:
self._owners[reply.run_id] = reply_to
if reply.status == "needs_input":
self._pending_owner = reply_to
self._reply(*reply_to, detail, kind=_reply_kind(status))
if not self._hidden(reply):
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
self.drain()
self.surface(origin=reply_to)
def drain(self) -> None:
"""Run queued work and route each outcome back to its owner."""
"""Run queued work and route each outcome back to its owner.
A background drain (the codegen worker's post-authoring re-run, a repair
retry) buffers its replies in the scheduler outbox; route those first so
an off-gate completion still reaches the chat, then drain the queue.
"""
drain_outbox = getattr(self.scheduler, "drain_outbox", None)
if callable(drain_outbox):
self._route(drain_outbox())
for _ in range(100):
results = self.scheduler.run_queue()
if not results:
break
for status, detail in results:
run_id = _leading_run_id(detail)
owner = self._owner_of(run_id)
text = _strip_run_id(detail)
if status == "needs_input" and owner:
self._pending_owner = owner
target = owner or self._fallback_target()
if target:
self._reply(*target, text, kind=_reply_kind(status))
self._route(results)
def _route(self, results) -> None:
for reply in results:
if self._hidden(reply):
continue
owner = self._owner_of(reply.run_id)
if reply.status == "needs_input" and owner:
self._pending_owner = owner
target = owner or self._fallback_target()
if target:
self._reply(
*target, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
def _hidden(self, reply) -> bool:
"""Hide an intermediate chain step at `result` verbosity.
The default end-user view is just the final answer; a chained request's
intermediate "continue" steps are only surfaced at `query`/`decision`
verbosity.
"""
if not getattr(reply, "intermediate", False):
return False
return getattr(self.scheduler, "verbosity", "result") == "result"
def surface(self, origin: Target | None = None) -> None:
"""Send any newly posted authoring questions / repair offers."""
@@ -346,6 +549,16 @@ class GatewayService:
if target:
self._reply(*target, fired.message, kind="notice")
# Long-form read-aloud requests a skill posted for a voice front end:
# route each to the platform that owns the run. Only a streaming adapter
# (the voice gateway) can deliver one; others are traced and skipped.
speech = getattr(self.scheduler, "speech", None)
if speech is not None:
for read in speech.drain():
target = self._resolve_target(read.run_id, origin)
if target:
self._enqueue_stream(target, read)
# ---- scheduler requeue hook (called under the scheduler lock) ----
def on_request_requeued(self, parent_id: str, child_id: str) -> None:
@@ -375,17 +588,41 @@ class GatewayService:
# ---- outbound ----
def _trace(self, kind: str, **fields) -> None:
"""Best-effort trace (a test double's scheduler may have no trace log)."""
trace = getattr(self.scheduler, "trace", None)
if trace is not None:
trace.append(kind, "?", **fields)
def _reply(
self, platform: str, chat_id: str, text: str, kind: str = "reply"
self,
platform: str,
chat_id: str,
text: str,
kind: str = "reply",
skill_ref: str | None = None,
result: str | None = None,
) -> None:
text = _strip_run_id(text)
if self._result_only(platform):
result_only = self._result_only(platform)
humanize = kind == "result" and self._humanize_enabled(platform, skill_ref)
if result_only:
# A spoken front end says the skill's result, not the scheduler's
# bookkeeping: drop queue/urgency chatter and unwrap the result line.
# bookkeeping: drop queue/urgency chatter.
if kind == "status":
return
if kind == "result":
text = _result_detail(text)
if kind == "result" and (result_only or humanize):
# The scheduler hands us the skill's own unwrapped detail; fall back
# to unwrapping `<skill>: <ok|failed> — <detail>` for raw-string
# callers.
text = result if result is not None else _result_detail(text)
if humanize:
started = time.time()
text = self.humanizer.humanize(text)
self._trace(
"humanize",
elapsed_s=round(time.time() - started, 3),
chars=len(text),
)
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
if prefix:
text = f"{prefix}{text}"
@@ -394,4 +631,31 @@ class GatewayService:
target_queue = self.outbound.get(platform)
if target_queue is None:
return
self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text))
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
def _enqueue_stream(self, target: Target, read) -> None:
"""Queue a read-aloud stream for the platform that can stream it.
Only an adapter that declares `supports_speech_stream` (the voice
gateway) can speak a long-form stream; a platform that cannot is traced
and skipped rather than handed a message it would drop silently.
"""
platform, chat_id = target
adapter = self.adapters.get(platform)
if adapter is None or not getattr(adapter, "supports_speech_stream", False):
self._trace(
"gateway_stream_unsupported",
platform=platform,
key=getattr(read, "key", ""),
)
return
self._trace(
"gateway_stream_queued",
platform=platform,
key=getattr(read, "key", ""),
start=getattr(read, "start", 0),
)
self.outbound[platform].put(
OutboundMessage(chat_id=str(chat_id), text="", stream=read)
)
+243 -12
View File
@@ -23,9 +23,14 @@ from __future__ import annotations
import queue
import threading
from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark
from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command
#: The stop vocabulary lives in `gateway.base` (shared with the LXMF adapter,
#: which also streams read-aloud text). Kept under the old name for callers.
_is_stop_command = is_stop_command
class VoiceAdapter(GatewayAdapter):
@@ -41,13 +46,51 @@ class VoiceAdapter(GatewayAdapter):
self.display_name = str(cfg.get("display_name") or self.chat_id)
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
#: Set by the daemon while a barge-in command is being captured, so the
#: transcribed utterance is classified as an interrupt.
self._barged_in = False
self.daemon.on_barge_in = self._on_barge_in
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
#: The outbound reply queue (set in `run`), so a "stop" can drop replies
#: that were already queued behind the interrupted one.
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
#: Long-form read-aloud: the adapter streams a saved text through the
#: daemon's Piper voice one chunk at a time, and any inbound command
#: interrupts it. `read.enabled` (default on) gates the whole path;
#: `read.chunk_chars` bounds one spoken chunk (clamped to the speakable
#: budget so a chunk is never truncated).
read_cfg = cfg.get("read", {}) or {}
self.supports_speech_stream = bool(read_cfg.get("enabled", True))
self._read_chunk_chars = max(
1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS)
)
self._read_lock = threading.Lock()
#: Set to ask the active read to stop; swapped per read so a stale read
#: never observes a new read's stop signal.
self._read_stop = threading.Event()
#: The bookmark key of the active read (None when nothing is being read).
self._read_key: str | None = None
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
return self.daemon.check_requirements()
def set_input_ready(self, ready) -> None:
"""Gate the wake word on the scheduler being able to accept a command.
`ready` is a callable returning whether a new command may start now
(`GatewayService.input_ready`). While it returns False the wake word is
ignored, so a second command cannot be started before the current
request has reached a result.
"""
self.daemon.input_ready = ready
# ---- transport ----
def run(
@@ -56,42 +99,230 @@ class VoiceAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Drain the service's replies onto the daemon's speaker. Speaking
# blocks (it plays audio), so this runs off the listening thread.
# blocks (it plays audio), so this runs off the listening thread. A
# read-aloud stream blocks here for as long as the user listens.
while True:
message = outbound.get()
if message is None:
self.daemon.stop()
return
if message.stream is not None:
try:
self._stream(message.stream)
except Exception as exc:
# A read failure must never kill the outbound pump (and
# with it the front end).
self.daemon._event(
"gateway_read_failed", message=str(exc)[:300]
)
continue
self.daemon._event("gateway_reply_dequeued", chars=len(message.text))
self.daemon.speak(message.text)
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
self.daemon.run(self._on_utterance)
threading.Thread(
target=self._inbound_worker, name="voice-inbound-worker", daemon=True
).start()
try:
self.daemon.run(self._on_utterance)
finally:
self._inbound.put(None)
def close(self) -> None:
self.daemon.close()
# ---- inbound ----
def _inbound_worker(self) -> None:
"""Run the scheduler off the audio thread, one utterance at a time.
The scheduler is synchronous and can block on the decision engine; a
slow task must not stop the mic being read, and a task error is traced
and spoken rather than propagated — one bad command must not take the
voice front end down with it.
"""
while True:
message = self._inbound.get()
if message is None:
return
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
# Any inbound command interrupts an in-progress read-aloud: the user
# either said "stop" or wants to do something else. The bookmark already
# points at the chunk that was interrupted, so a later request resumes
# there.
was_reading = self._stop_read_for_command(message)
if message.raw.get("barge_in"):
if _is_stop_command(message.text):
# A "stop"/"cancel" after a barge-in aborts the spoken reply and
# is not a request: the daemon already cut the playback, and any
# reply still queued behind it is stale output the user stopped.
self.daemon._event("gateway_barge_in_stop", chars=len(message.text))
self._drop_pending_speech()
self.daemon.set_muted(False)
return
# A new command after a barge-in: the playback was already aborted,
# so just run it (and unmute once it has been handled).
self.daemon._event("gateway_barge_in_command", chars=len(message.text))
try:
if self._on_inbound is not None:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
finally:
self.daemon.set_muted(False)
return
if was_reading and _is_stop_command(message.text):
# A bare "stop" heard between chunks (not a barge-in) stops the
# reading and is not submitted as a request.
self.daemon._event("gateway_read_stopped", chars=len(message.text))
self._drop_pending_speech()
return
if self._on_inbound is None:
return
try:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
# ---- read-aloud (long-form streaming) ----
def _read_active(self) -> bool:
with self._read_lock:
return self._read_key is not None
def _stop_read_for_command(self, message: InboundMessage) -> bool:
"""Stop an active read when a command arrives; report whether one was."""
if not self._read_active():
return False
reason = "barge_in" if message.raw.get("barge_in") else "new_command"
self._stop_reading(reason)
return True
def _stop_reading(self, reason: str) -> None:
"""Ask the active read to stop at the next chunk boundary.
The bookmark was already written for the chunk being spoken, so the
position is correct without any extra bookkeeping here.
"""
with self._read_lock:
if self._read_key is None:
return
key = self._read_key
self._read_stop.set()
self.daemon._event("gateway_read_stop", key=key, reason=reason)
def _stream(self, read) -> None:
"""Stream a read-aloud request through the daemon's Piper voice.
Chunks are spoken one at a time; the bookmark is written before each
chunk so a stop (or a crash) leaves the position at the interrupted
chunk. The read ends when the text is finished or the user interrupts
(a stop flag set by `_handle`, or a barge-in muting playback).
"""
with self._read_lock:
self._read_stop.set() # supersede any prior read
stop = threading.Event()
self._read_stop = stop
self._read_key = read.key
try:
try:
with open(read.path, "r", encoding="utf-8", errors="replace") as handle:
text = handle.read()
except OSError as exc:
self.daemon._event(
"gateway_read_failed", key=read.key, message=str(exc)[:200]
)
return
chunk_chars = min(
self._read_chunk_chars,
max(1, int(read.chunk_chars or self._read_chunk_chars)),
)
# Never exceed the daemon's speakable budget, or a chunk would be
# truncated and text would be lost.
speak_limit = int(getattr(self.daemon, "max_speak_chars", 0) or 0)
if speak_limit > 0:
chunk_chars = min(chunk_chars, speak_limit)
self.daemon._event(
"gateway_read_start", key=read.key, start=read.start, chars=len(text)
)
spoken = 0
for offset, chunk in chunk_text(text, read.start, chunk_chars):
if stop.is_set() or self.daemon.stopping():
break
save_bookmark(read.bookmarks_path, read.key, offset, read.title)
self.daemon.speak(chunk)
spoken += 1
# A barge-in mutes playback synchronously on the audio thread;
# break promptly so we do not skip through suppressed chunks
# before the transcribed "stop" reaches `_handle`.
if stop.is_set() or self.daemon.muted():
break
if stop.is_set() or self.daemon.stopping():
self.daemon._event("gateway_read_interrupted", key=read.key, chunks=spoken)
else:
# Finished: park the bookmark at the end so a later request
# starts over rather than replaying the final chunk.
save_bookmark(read.bookmarks_path, read.key, len(text), read.title)
self.daemon._event("gateway_read_done", key=read.key, chunks=spoken)
finally:
with self._read_lock:
if self._read_stop is stop:
self._read_key = None
def _drop_pending_speech(self) -> None:
"""Discard replies already queued behind an interrupted one.
The daemon aborted the in-flight playback; anything waiting on the
outbound queue is output the user asked to stop, so it is dropped rather
than spoken next.
"""
outbound = self._outbound
if outbound is None:
return
dropped = 0
while True:
try:
message = outbound.get_nowait()
except queue.Empty:
break
if message is None:
outbound.put(None) # preserve the pump's shutdown sentinel
break
dropped += 1
if dropped:
self.daemon._event("gateway_speech_dropped", count=dropped)
def _on_barge_in(self, active: bool) -> None:
"""Daemon callback: mark a barge-in session (True) and its end (False)."""
self._barged_in = bool(active)
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
return
barge_in = self._barged_in
self._barged_in = False
self.daemon._event(
"gateway_message",
contact_id=self.chat_id,
display_name=self.display_name,
chars=len(text),
)
message = InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
self._inbound.put(
InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={"barge_in": True} if barge_in else {},
)
)
if self._on_inbound is not None:
self._on_inbound(message)
+15 -1
View File
@@ -13,7 +13,7 @@ from __future__ import annotations
import json
from .provider import OpenAICompatClient, ProviderError
from .provider import OpenAICompatClient, ProviderError, SemIfEngineClient
class LLMError(ProviderError):
@@ -102,3 +102,17 @@ class LLMClient(OpenAICompatClient):
if start != -1 and end != -1:
text = text[start : end + 1]
return json.loads(text)
class SemIfLLMClient(SemIfEngineClient):
"""`llm` authoring backed by the loaded SemIf engine model.
The `llm.provider = "semif"` option: the same in-process GGUF the decision
engine already loaded generates the title/description (and any other `llm`
text) instead of calling an HTTP endpoint. Same `chat(...)` surface, same
graceful error contract — raises `LLMError` so the scheduler traces a
`draft_failed` and the LLM bridge reports 502 rather than crashing.
"""
error_class = LLMError
label = "semif:llm"
+8
View File
@@ -42,6 +42,14 @@ class DecisionLog:
}
if extra:
row["extra"] = extra
result_extra = getattr(result, "extra", None) or {}
timing = {
key: result_extra[key]
for key in ("input_tokens", "forward_seconds", "total_seconds")
if key in result_extra
}
if timing:
row.setdefault("extra", {})["timing"] = timing
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a") as handle:
handle.write(json.dumps(row) + "\n")
+225 -15
View File
@@ -31,6 +31,96 @@ MessageHandler = Callable[[InboundDict], None]
#: Zero-argument callback invoked once the router is ready to receive.
ConnectedHandler = Callable[[], None]
#: The LXMF `FIELD_AUDIO` (0x07) field a Sideband push-to-talk voice message
#: rides in. `LXMF` is optional and lazy-imported, so its stable, committed wire
#: constants are mirrored here (the same way `simplex_ws` mirrors the v7 shapes).
FIELD_AUDIO = 0x07
#: Audio modes — the first element of a `FIELD_AUDIO` value (mirrors
#: `LXMF.AM_*`). `AM_OPUS_OGG` is a complete OGG/Opus container a decoder (PyAV,
#: which `faster-whisper` bundles) reads directly; the Codec2 modes are raw
#: frames decoded by `pycodec2`.
AM_OPUS_OGG = 0x10
AUDIO_MODE_NAMES = {
0x01: "codec2_450pwb", 0x02: "codec2_450", 0x03: "codec2_700c",
0x04: "codec2_1200", 0x05: "codec2_1300", 0x06: "codec2_1400",
0x07: "codec2_1600", 0x08: "codec2_2400", 0x09: "codec2_3200",
0x10: "opus_ogg", 0x11: "opus_lbw", 0x12: "opus_mbw", 0x13: "opus_ptt",
0x14: "opus_rt_hdx", 0x15: "opus_rt_fdx", 0x16: "opus_standard",
0x17: "opus_hq", 0x18: "opus_broadcast", 0x19: "opus_lossless",
}
#: Codec2 audio modes -> the codec2 bitrate (bits/s) they decode at. `pycodec2`
#: has bindings for these; 450PWB/450 (0x01/0x02) have none, so they stay
#: undecodable. (Mirrors Sideband's `audioproc.codec2_modes`.)
CODEC2_MODE_RATES = {
0x03: 700, 0x04: 1200, 0x05: 1300, 0x06: 1400,
0x07: 1600, 0x08: 2400, 0x09: 3200,
}
#: How often the announce loop wakes to re-check the clock and interfaces.
ANNOUNCE_TICK = 1.0
#: How often to scan Reticulum interfaces for online/offline transitions.
PEER_SCAN_INTERVAL = 10.0
def audio_mode_name(codec: int) -> str:
"""A human-readable name for an audio mode id (e.g. `AM_OPUS_OGG` ->
`opus_ogg`); an unknown id is rendered as hex."""
return AUDIO_MODE_NAMES.get(codec, f"0x{codec:02x}")
def audio_decode_kind(codec: int) -> str:
"""The decode path for an audio mode.
`"opus_ogg"` (a self-contained OGG/Opus container), `"codec2"` (raw Codec2
frames), or `"unknown"` (no decode path — e.g. the raw Opus `AM_OPUS_*`
modes and the binding-less 450 Codec2 modes).
"""
if codec == AM_OPUS_OGG:
return "opus_ogg"
if codec in CODEC2_MODE_RATES:
return "codec2"
return "unknown"
def parse_audio_field(value: Any) -> dict[str, Any] | None:
"""Normalize an LXMF `FIELD_AUDIO` value into a plain dict.
The wire value is `[audio_mode, data]` (see `LXMF.FIELD_AUDIO`): an integer
codec id and the raw audio bytes. Returns
`{"codec", "codec_name", "data", "kind", "codec2_rate"}` or None when
malformed. `kind` is the decode path (`opus_ogg`/`codec2`/`unknown`);
`codec2_rate` is the bitrate for a Codec2 mode, else None.
"""
if not isinstance(value, (list, tuple)) or len(value) < 2:
return None
data = value[1]
if not isinstance(data, (bytes, bytearray)):
return None
try:
codec = int(value[0])
except (TypeError, ValueError):
return None
return {
"codec": codec,
"codec_name": audio_mode_name(codec),
"data": bytes(data),
"kind": audio_decode_kind(codec),
"codec2_rate": CODEC2_MODE_RATES.get(codec),
}
def audio_fields(audio: bytes | None) -> dict[int, Any] | None:
"""The LXMF fields for an outbound voice reply, or None for a text message.
A voice reply rides `FIELD_AUDIO` as `[AM_OPUS_OGG, ogg_bytes]` — the
Sideband HQ push-to-talk shape. Pure so the wire construction is testable
without a Reticulum router.
"""
if not audio:
return None
return {FIELD_AUDIO: [AM_OPUS_OGG, bytes(audio)]}
def _as_text(value: Any) -> str:
"""Best-effort UTF-8 text for a `str`/`bytes`/`None` LXMF field."""
@@ -87,12 +177,24 @@ def normalize_message(message: Any) -> InboundDict:
if source is not None:
display_name = _as_text(getattr(source, "display_name", None))
fields = getattr(message, "fields", None)
if not isinstance(fields, dict):
fields = {}
# A Sideband push-to-talk voice message carries its Opus/Codec2 payload in
# `FIELD_AUDIO` and an empty content; surface it as a normalized `audio` dict
# so a front end can transcribe it without knowing the wire shape.
audio = None
if FIELD_AUDIO in fields:
audio = parse_audio_field(fields.get(FIELD_AUDIO))
return {
"source_hash": source_hash,
"display_name": display_name or None,
"title": title,
"content": content,
"timestamp": getattr(message, "timestamp", None),
"fields": fields,
"audio": audio,
"raw": message,
}
@@ -101,7 +203,10 @@ class LxmfDaemon:
"""One in-process Reticulum instance + LXMF router.
`run(on_message)` blocks, announcing the delivery destination periodically
and delivering each received message to `on_message`. `enqueue(chat_id,
— and whenever a Reticulum interface or AutoInterface peer comes online, so
a peer that was not yet reachable at startup (or that joined mid-interval)
learns the destination promptly instead of waiting out `announce_interval`.
Each received message is delivered to `on_message`. `enqueue(chat_id,
text)` queues an outbound send (a `None` chat_id is the stop sentinel),
drained by an internal pump thread. `address` is the bot's LXMF address.
@@ -138,9 +243,20 @@ class LxmfDaemon:
self._reticulum = None
self._destination = None
self._address = ""
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
#: Outbound items are `(chat_id, text, audio)`; `audio` is an OGG/Opus
#: container for a Sideband HQ push-to-talk voice reply, else None.
self._outbound: "queue.Queue[tuple[str, str, bytes | None] | None]" = (
queue.Queue()
)
self._stop = threading.Event()
self._on_message: MessageHandler | None = None
#: Last announce time, and whether an interface transition asked for
#: an immediate re-announce (set by the announce loop's interface scan).
self._last_announce = 0.0
self._announce_due = False
#: `str(interface) -> online`, so the scan can spot interfaces and
#: AutoInterface peers that just came up.
self._interface_states: dict[str, bool] = {}
# ---- requirements ----
@@ -216,6 +332,15 @@ class LxmfDaemon:
)
except Exception as exc:
self._event("lxmf_propagation_error", message=str(exc)[:300])
# Snapshot the interfaces Reticulum brought up so the announce loop can
# tell which ones (and which AutoInterface peers) come online later.
try:
self._interface_states = {
str(interface): bool(getattr(interface, "online", False))
for interface in RNS.Transport.interfaces
}
except Exception as exc:
self._event("lxmf_error", phase="interface_snapshot", message=str(exc)[:300])
self._event("lxmf_ready", address=self._address)
return self._router
@@ -225,7 +350,7 @@ class LxmfDaemon:
threading.Thread(
target=self._pump, name="lxmf-outbound-pump", daemon=True
).start()
self._announce()
self._announce("startup")
if self.on_connected is not None:
try:
self.on_connected()
@@ -234,15 +359,75 @@ class LxmfDaemon:
"lxmf_error", phase="on_connected", message=str(exc)[:300]
)
while not self._stop.wait(self._announce_wait()):
self._announce()
self._announce_loop()
def enqueue(self, chat_id: str | None, text: str = "") -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
def _announce_loop(self) -> None:
"""Announce on the interval, and whenever an interface/peer comes up.
The startup announce fires before AutoInterface has finished its
peering handshake, so it reaches no peer; a peer discovered later (or a
link that recovers) would otherwise have to wait out the whole
`announce_interval`. Re-announcing on every online transition makes a
newly-reachable peer learn the destination promptly.
"""
last_scan = 0.0
while not self._stop.is_set():
try:
now = time.time()
if self._announce_due:
self._announce_due = False
self._announce("peer discovered")
elif now - self._last_announce >= self._announce_wait():
self._announce("interval")
if now - last_scan >= PEER_SCAN_INTERVAL:
last_scan = now
if self._scan_interfaces():
self._announce_due = True
except Exception as exc:
self._event(
"lxmf_error", phase="announce_loop", message=str(exc)[:300]
)
self._stop.wait(ANNOUNCE_TICK)
def _scan_interfaces(self) -> bool:
"""Note interface transitions; True when one newly came online.
AutoInterface reports `online` only after its peering wait, and every
discovered peer is a fresh `AutoInterfacePeer` interface, so an online
transition is exactly "we may now be reachable by someone new".
"""
changed = False
try:
import RNS
for interface in RNS.Transport.interfaces:
key = str(interface)
online = bool(getattr(interface, "online", False))
prev = self._interface_states.get(key)
self._interface_states[key] = online
if online and prev is not True:
self._event("lxmf_interface_online", interface=key)
changed = True
except Exception as exc:
self._event(
"lxmf_error", phase="interface_scan", message=str(exc)[:300]
)
return changed
def enqueue(
self, chat_id: str | None, text: str = "", audio: bytes | None = None
) -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel.
`audio` is an OGG/Opus container: it rides the LXMF `FIELD_AUDIO` field
(a Sideband HQ push-to-talk voice reply) with `text` as the message
content, so a text-only client still sees the reply.
"""
if chat_id is None:
self._outbound.put(None)
else:
self._outbound.put((str(chat_id), text))
self._outbound.put((str(chat_id), text, audio))
def close(self) -> None:
self._stop.set()
@@ -254,6 +439,15 @@ class LxmfDaemon:
except Exception:
pass
def pending_sends(self) -> int:
"""How many outbound items are queued (a stream's backpressure signal).
A long-form read-aloud uses this to keep only a few messages queued
ahead, so stopping it takes effect promptly instead of after a large
backlog drains.
"""
return self._outbound.qsize()
# ---- identity ----
def _load_identity(self, RNS):
@@ -277,12 +471,13 @@ class LxmfDaemon:
return 3600.0
return self.announce_interval
def _announce(self) -> None:
def _announce(self, reason: str = "") -> None:
if self._router is None or self._destination is None:
return
try:
self._router.announce(self._destination.hash)
self._event("lxmf_announced", address=self._address)
self._last_announce = time.time()
self._event("lxmf_announced", address=self._address, reason=reason or None)
except Exception as exc:
self._event("lxmf_error", phase="announce", message=str(exc)[:300])
@@ -309,17 +504,27 @@ class LxmfDaemon:
item = self._outbound.get()
if item is None:
return
chat_id, text = item
chat_id, text, audio = item
try:
self.send(chat_id, text)
self.send(chat_id, text, audio=audio)
except Exception as exc:
self._event(
"lxmf_send_failed", contact=chat_id, message=str(exc)[:300]
)
def send(self, destination_hex: str, text: str, timeout: float = 15.0) -> None:
def send(
self,
destination_hex: str,
text: str,
audio: bytes | None = None,
timeout: float = 15.0,
) -> None:
"""Send `text` to an LXMF address (destination hash hex).
When `audio` (an OGG/Opus container) is given it is attached in the
LXMF `FIELD_AUDIO` field as a Sideband HQ push-to-talk voice message
(`[AM_OPUS_OGG, audio]`), with `text` as the message content.
Recalls the peer identity from the network; when the path is not yet
known it requests it and waits briefly. Raises (never silently drops)
when the destination cannot be resolved — a reply must be real.
@@ -351,9 +556,14 @@ class LxmfDaemon:
if self.desired_method == "opportunistic"
else LXMF.LXMessage.DIRECT
)
message = LXMF.LXMessage(dest, self._destination, text, desired_method=method)
fields = audio_fields(audio)
message = LXMF.LXMessage(
dest, self._destination, text, desired_method=method, fields=fields
)
self._router.handle_outbound(message)
self._event("lxmf_sent", contact=destination_hex, chars=len(text))
self._event(
"lxmf_sent", contact=destination_hex, chars=len(text), audio=bool(audio)
)
# ---- tracing ----
+348
View File
@@ -0,0 +1,348 @@
"""Ollama System One decision engine: ollama's native ``/v1/systemone`` API.
An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`) and
to the Winnow server (`semif_agent.winnow.WinnowEngine`), selected per machine
with ``engine.provider == "ollama"`` in config.json — the same provider pattern
as ``llm`` / ``codegen``.
The agent's flat decision contract (state + question + typed options) maps onto
Ollama's System One ``choice`` question: the options become the question's
``criteria`` (id -> description, or ``null`` for a bare label) and the question
becomes its ``instructions``; the server returns a probability over exactly
those keys. This provider implements the **Ollama** shape of that API (the one
documented at docs.ollama.com/api/systemone), which differs from the Winnow
reference server in ways that matter at the edges:
* no ``/health`` route — reachability/warmth is probed through Ollama's native
``GET /api/version`` and ``POST /api/show`` (which also verifies the model
exists and advertises the ``decision`` capability);
* the decision context window is read from the model's ``num_ctx`` parameter
(``/api/show``) when ``engine.ollama.context_tokens`` is 0, so generated
skill bodies are sized to what the server really loaded;
* ``keep_alive`` is an Ollama request knob, not part of the System One contract;
* choice criteria descriptions are the Ollama subset ``string | null`` (never
an object) and at least two options are required;
* decision models do not generate text, so ``generate`` is unavailable here
(use ``llm.provider == "ollama"`` for the chat path).
The engine is real: any network, HTTP, or distribution failure raises
`EngineUnavailable`, which the scheduler treats as fatal — there is no fallback
model and no fabricated reply.
"""
from __future__ import annotations
import json
import math
import re
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .engine import DecisionEngine, EngineUnavailable
@dataclass
class OllamaSystemOneConfig:
"""Per-machine settings for the Ollama System One engine (`engine.ollama`)."""
#: The Ollama server root — **no** ``/v1`` suffix (System One lives at
#: ``/v1/systemone`` on the root server, unlike the OpenAI-compatible API).
base_url: str = "http://127.0.0.1:11434"
model: str = ""
#: The model's decision context window, in tokens. 0 asks the server (the
#: model's `num_ctx` parameter, then its architecture context length), so
#: the fidelity-state budget mirrors the window the server really loaded.
context_tokens: int = 16384
timeout: float = 120.0
#: Transient-failure retries before declaring the engine unavailable. 0
#: means a single attempt: an unreachable remote engine is fatal by
#: contract.
retries: int = 0
#: Bearer key for Ollama's cloud models (``https://ollama.com``); empty for
#: a local server.
api_key: str = ""
extra_headers: dict | None = None
user_agent: str = "semif-agent"
#: Ollama's model-unload policy for the request (a duration such as "5m",
#: or seconds). Empty keeps the server's own keep-alive setting.
keep_alive: str = ""
def _context_from_show(show: dict) -> int | None:
"""The model's context window from an Ollama ``/api/show`` payload.
Ollama reports ``parameters`` either as modelfile text
(``"num_ctx 16384\\n..."``) or as a mapping, depending on version; the
architecture context length in ``model_info`` is the fallback. Returns
``None`` when neither shape carries a usable number.
"""
params = show.get("parameters")
if isinstance(params, str):
match = re.search(r"(?m)^\s*num_ctx\s+(\d+)\s*$", params)
if match:
return int(match.group(1))
elif isinstance(params, dict):
value = params.get("num_ctx")
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
info = show.get("model_info")
if isinstance(info, dict):
# Prefer the text model's context length over a vision tower's.
candidates = [
value
for key, value in info.items()
if str(key).endswith(".context_length") and "vision" not in str(key)
]
for value in candidates:
try:
return int(value)
except (TypeError, ValueError):
continue
return None
class OllamaSystemOneEngine(DecisionEngine):
"""One Ollama System One endpoint, used for every decision.
Scoring maps a `DecisionRequest` -> a single ``choice`` question and reads
the returned distribution back over the requested option ids. The endpoint
is a single-slot server, so calls serialize on an internal lock exactly as
`SemIfEngine` serializes on its llama.cpp context.
"""
label = "ollama"
def __init__(self, config: OllamaSystemOneConfig):
self.config = config
self._lock = threading.Lock()
self._loaded = False
self._discovered_context: int | None = None
@property
def context_tokens(self) -> int:
configured = int(self.config.context_tokens or 0)
if configured > 0:
return configured
return int(self._discovered_context or 16384)
@property
def loaded(self) -> bool:
return self._loaded
# ---- transport ----
def _headers(self) -> dict:
headers = {
"content-type": "application/json",
"accept": "application/json",
}
if self.config.user_agent:
headers["user-agent"] = self.config.user_agent
if self.config.api_key:
headers["authorization"] = f"Bearer {self.config.api_key}"
for key, value in (self.config.extra_headers or {}).items():
headers[str(key)] = str(value)
return headers
def _request(self, path: str, payload: dict | None = None) -> dict:
"""GET (no payload) or POST JSON, or raise `EngineUnavailable`."""
url = self.config.base_url.rstrip("/") + path
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
attempts = max(0, int(self.config.retries)) + 1
last: Exception | None = None
for attempt in range(attempts):
request = urllib.request.Request(
url,
data=data,
method="POST" if data is not None else "GET",
headers=self._headers(),
)
try:
with urllib.request.urlopen(
request, timeout=self.config.timeout
) as response:
body = response.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if not isinstance(parsed, dict):
raise EngineUnavailable(
f"Ollama response from {url} is not a JSON object"
)
return parsed
except urllib.error.HTTPError as exc:
detail = ""
try:
# Ollama reports failures as {"error": "..."}.
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
pass
last = EngineUnavailable(
f"HTTP {exc.code} from {url}: {detail}".strip()
)
# A 4xx (except 429) will not succeed on retry.
if 400 <= exc.code < 500 and exc.code != 429:
break
except EngineUnavailable:
raise
except Exception as exc: # URLError, timeout, socket, JSONDecodeError
last = exc
if attempt + 1 < attempts:
time.sleep(min(2.0**attempt, 5.0))
if isinstance(last, EngineUnavailable):
raise last
raise EngineUnavailable(
f"Ollama request to {url} failed: {type(last).__name__}: {last}"
)
def _post(self, path: str, payload: dict) -> dict:
return self._request(path, payload)
# ---- DecisionEngine ----
def warm(self) -> None:
"""Verify the server and the configured model, then mark loaded.
Ollama has no ``/health`` route: ``GET /api/version`` proves the server
answers and ``POST /api/show`` proves the model is pulled (404 when it
is not) and lets a 0 ``context_tokens`` follow the model's real
``num_ctx``. A model that advertises capabilities without ``decision``
is rejected with an actionable error instead of failing on first use.
"""
self._request("/api/version")
show = self._post("/api/show", {"model": self.config.model})
if int(self.config.context_tokens or 0) <= 0:
discovered = _context_from_show(show)
if discovered:
self._discovered_context = discovered
capabilities = show.get("capabilities")
if isinstance(capabilities, list) and capabilities:
if "decision" not in capabilities:
raise EngineUnavailable(
f"Ollama model {self.config.model!r} does not advertise the "
"'decision' capability (capabilities: "
f"{', '.join(str(c) for c in capabilities)}); point "
"engine.ollama.model at a System One model"
)
self._loaded = True
def call(self, request: DecisionRequest) -> DecisionResult:
option_ids = [option.id for option in request.options]
if len(option_ids) < 2:
raise EngineUnavailable(
"Ollama System One choice questions need at least two options"
)
state = request.state if isinstance(request.state, str) else json.dumps(
request.state
)
if not state.strip():
raise EngineUnavailable("Ollama System One requires a non-empty state")
# Ollama's choice criteria descriptions are `string | null`; a bare
# label is the explicit `null` form.
criteria = {
option.id: (option.description.strip() or None)
for option in request.options
}
payload = {
"model": self.config.model,
"state": state,
"questions": {
"decision": {
"type": "choice",
"instructions": request.question,
"criteria": criteria,
}
},
}
keep_alive = str(self.config.keep_alive or "").strip()
if keep_alive:
payload["keep_alive"] = keep_alive
with self._lock:
started = time.perf_counter()
body = self._post("/v1/systemone", payload)
elapsed = time.perf_counter() - started
answers = body.get("answers")
answer = answers.get("decision") if isinstance(answers, dict) else None
if not isinstance(answer, dict):
raise EngineUnavailable(
"Ollama response is missing answers.decision"
)
if answer.get("type") not in (None, "choice"):
raise EngineUnavailable(
f"Ollama answer type {answer.get('type')!r} is not 'choice'"
)
raw = answer.get("probabilities")
if not isinstance(raw, dict):
raise EngineUnavailable("Ollama answer is missing probabilities")
if set(raw) != set(option_ids):
raise EngineUnavailable(
"Ollama probabilities do not match the requested options: "
f"{sorted(raw)} != {sorted(option_ids)}"
)
choice = answer.get("choice")
if choice is not None and choice not in option_ids:
raise EngineUnavailable(
f"Ollama choice {choice!r} is not one of the requested options"
)
try:
values = [float(raw[option_id]) for option_id in option_ids]
except (TypeError, ValueError) as exc:
raise EngineUnavailable(
f"Ollama probabilities are not numeric: {exc}"
) from exc
if any(
(not math.isfinite(value)) or value < 0.0 or value > 1.0
for value in values
):
raise EngineUnavailable(
"Ollama returned a non-finite or out-of-range probability"
)
total = sum(values)
if total <= 0.0:
raise EngineUnavailable("Ollama returned an all-zero distribution")
probabilities = [value / total for value in values]
usage = body.get("usage") if isinstance(body.get("usage"), dict) else {}
self._loaded = True
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=probabilities,
extra={
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
"forward_seconds": elapsed,
"total_seconds": elapsed,
"raw_probability_sum": total,
"served_model": body.get("model"),
"choice": choice,
"confidence": answer.get("confidence"),
},
)
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Unavailable: System One decision models do not generate text.
Use ``llm.provider == "ollama"`` (an OpenAI-compatible chat endpoint) for
text; pointing ``llm.provider`` at this decision engine would ask a
classifier to write prose, so it is refused rather than faked.
"""
raise EngineUnavailable(
"the ollama System One decision engine does not generate text; "
"configure llm.provider = \"ollama\" for the chat path"
)
+199
View File
@@ -0,0 +1,199 @@
"""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 ships and talks to, its
runtime requirements, and its config schema/defaults — so "the Nextcloud
product, its bridge, its skills, and its settings" are one thing. A bridge
*ships with its pack* (``packs/<name>/bridge/``); the core keeps only the shared
contract (``semif_agent/bridges/base.py``) and the discovery registry
(``semif_agent/bridges/registry.py``). Gateway isolation is non-negotiable.
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()}
)
@property
def requirements_file(self) -> Path | None:
"""The pack's optional pip requirements file, if it ships one.
A pack owns its python deps: ``packs/<name>/requirements.txt`` (standard
pip format) is installed by ``scripts/bootstrap.sh`` when the pack is
selected (see ``setup.build_plan``). Returns ``None`` when absent.
"""
path = self.path / "requirements.txt"
return path if path.is_file() else None
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
+92 -11
View File
@@ -8,6 +8,11 @@ provider logic once; subclasses set `base_url`/`model`, their sampler
parameters, and the error classes they raise so existing callers keep catching
their own types.
It also holds `SemIfEngineClient`, the non-HTTP sibling that generates text
from the in-process SemIf engine model (`engine.SemIfEngine.generate`) behind
the same ``chat(...)`` surface, so the `llm` task can be served by the loaded
decision model instead of an HTTP endpoint.
Stdlib-only and imports nothing from the agent's own modules, so `codegen.py`
(which imports `skills.py`, which imports `llm.py`) can depend on it without a
cycle.
@@ -192,8 +197,13 @@ class OpenAICompatClient:
top_p: float | None = None,
presence_penalty: float | None = None,
frequency_penalty: float | None = None,
timeout: float | None = None,
degeneration_check: Callable[[str], str | None] | None = None,
) -> str:
# A per-call `timeout` overrides the constructor value for this request
# only (used by short auxiliary calls such as the gateway's result
# cleanup, which must not inherit the authoring client's long budget).
deadline = self.timeout if timeout is None else timeout
budget = self._compute_budget(messages)
if self.stream:
self._print_budget(budget)
@@ -227,15 +237,17 @@ class OpenAICompatClient:
url, data=body, headers=self._headers()
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
return self._read_stream(response, budget, degeneration_check)
with urllib.request.urlopen(request, timeout=deadline) as response:
return self._read_stream(
response, budget, degeneration_check, timeout=deadline
)
except urllib.error.URLError as exc:
raise self.error_class(
f"{self.label} endpoint unreachable at {url}: {exc}. Is your local server running?"
) from exc
except TimeoutError as exc:
raise self.error_class(
f"{self.label} request timed out after {self.timeout}s at {url}"
f"{self.label} request timed out after {deadline:.0f}s at {url}"
) from exc
def _native_base_url(self) -> str:
@@ -399,6 +411,7 @@ class OpenAICompatClient:
response,
budget: TokenBudget,
degeneration_check: Callable[[str], str | None] | None = None,
timeout: float | None = None,
) -> str:
"""Read an OpenAI-compatible SSE stream; echo tokens if `stream`.
@@ -426,7 +439,10 @@ class OpenAICompatClient:
parts: list[str] = []
sock = self._stream_socket(response)
if sock is None:
return self._read_stream_blocking(response, budget, degeneration_check)
return self._read_stream_blocking(
response, budget, degeneration_check, timeout=timeout
)
deadline = self.timeout if timeout is None else timeout
start = time.monotonic()
last_activity = start
warned = False
@@ -437,9 +453,9 @@ class OpenAICompatClient:
recent_len = 0
last_check: int | None = None
while True:
if time.monotonic() - start >= self.timeout:
if time.monotonic() - start >= deadline:
raise self.error_class(
f"{self.label} request exceeded {self.timeout:.0f}s total budget"
f"{self.label} request exceeded {deadline:.0f}s total budget"
)
ready, _, _ = select.select([sock], [], [], 1.0)
now = time.monotonic()
@@ -499,16 +515,18 @@ class OpenAICompatClient:
response,
budget: TokenBudget,
degeneration_check: Callable[[str], str | None] | None = None,
timeout: float | None = None,
) -> str:
"""Fallback reader when the response socket can't be located.
A plain blocking read relies on the per-read socket timeout for
silence, but that bounds individual reads, not the whole stream — so
enforce the same total wall-clock budget `self.timeout` and the token
budget in the loop, or a continuously-streaming runaway would never be
cut short.
enforce the same total wall-clock budget (the per-call `timeout`, else
`self.timeout`) and the token budget in the loop, or a
continuously-streaming runaway would never be cut short.
"""
parts: list[str] = []
deadline = self.timeout if timeout is None else timeout
start = time.monotonic()
warned_fill = False
out_chars = 0
@@ -517,9 +535,9 @@ class OpenAICompatClient:
recent_len = 0
last_check: int | None = None
for raw in response:
if time.monotonic() - start >= self.timeout:
if time.monotonic() - start >= deadline:
raise self.error_class(
f"{self.label} request exceeded {self.timeout:.0f}s total budget"
f"{self.label} request exceeded {deadline:.0f}s total budget"
)
continues, text, reasoning, frame_usage = self._consume_frame(
raw.decode("utf-8").strip()
@@ -620,3 +638,66 @@ class OpenAICompatClient:
if sock is None:
sock = getattr(response, "sock", None)
return sock
class SemIfEngineClient:
"""Text generation backed by the in-process SemIf engine model.
A drop-in sibling of `OpenAICompatClient` for the small `llm` task: instead
of speaking HTTP to an ollama/Console endpoint it drives the already-loaded
decision GGUF through `engine.generate(...)`. It exposes the same
``chat(messages, max_tokens=..., temperature=..., ...)`` surface every `llm`
caller uses, so the provider choice is invisible to callers — title/
description authoring, gateway result cleanup, and the LLM bridge all reuse
it unchanged.
The engine is duck-typed (any object with ``generate(messages, temperature,
max_tokens)``); this module stays free of imports from the agent's own
modules, so subclasses in `llm.py` set the `LLMError` contract without a
cycle. Sampler/`timeout`/`degeneration_check` arguments are accepted for
signature compatibility and ignored: the engine generation is bounded by
`max_tokens` and serializes on the engine's own lock.
Any engine failure (`EngineUnavailable`, a missing GGUF, a sampling error)
is re-raised as `error_class` so the scheduler's graceful `draft_failed`
path and the LLM bridge's 502 path keep their existing contracts.
"""
error_class = ProviderError
label = "semif"
def __init__(
self,
engine,
temperature: float = 0.0,
max_tokens: int = 256,
disable_thinking: bool = True,
):
self.engine = engine
self.temperature = temperature
self.max_tokens = max_tokens
# The engine's `generate` always decodes with thinking disabled; the knob
# is accepted so the class mirrors the other providers' constructors.
self.disable_thinking = disable_thinking
def chat(
self,
messages: list[dict],
max_tokens: int | None = None,
temperature: float | None = None,
top_p: float | None = None,
presence_penalty: float | None = None,
frequency_penalty: float | None = None,
timeout: float | None = None,
degeneration_check: Callable[[str], str | None] | None = None,
) -> str:
resolved_max = self.max_tokens if max_tokens is None else max_tokens
resolved_temp = self.temperature if temperature is None else temperature
try:
return self.engine.generate(
messages, temperature=resolved_temp, max_tokens=resolved_max
)
except Exception as exc: # EngineUnavailable and anything the engine raises
raise self.error_class(
f"{self.label} generation failed: {exc}"
) from exc
+16 -55
View File
@@ -1,83 +1,44 @@
"""Urgency priority queue.
"""FIFO request queue with a maximum depth.
Items are sorted by descending urgency weight, then FIFO arrival, then most
recent first. Queued items age upward so they cannot starve, and the queue has
a maximum depth.
Requests are dispatched strictly in arrival order: there is no urgency scoring
and no preemption, so the running process always finishes before the next queued
request is picked up.
"""
from __future__ import annotations
import heapq
import itertools
import time
from dataclasses import dataclass
from collections import deque
from typing import Iterator
from .decisions import Request
MIN_RECENCY = 0.0
class RequestQueue:
"""A bounded first-in-first-out queue of pending requests."""
@dataclass
class QueueItem:
weight: float
seq: int
recency: float
request: Request
def key(self) -> tuple:
return (-self.weight, self.seq)
class UrgencyQueue:
"""A max-by-urgency priority queue with FIFO/recency tie-breaking."""
def __init__(self, max_size: int = 100, age_rate: float = 0.0):
def __init__(self, max_size: int = 100):
self.max_size = max_size
self.age_rate = age_rate
self._entries: list[tuple] = []
self._counter = itertools.count()
self._entries: deque[Request] = deque()
def push(self, request: Request, weight: float, recency: float | None = None) -> bool:
"""Insert an item. Returns False if the queue is full."""
def push(self, request: Request) -> bool:
"""Append an item. Returns False if the queue is full."""
if len(self._entries) >= self.max_size:
return False
item = QueueItem(
weight=weight,
seq=next(self._counter),
recency=recency if recency is not None else time.time(),
request=request,
)
entry = (*item.key(), next(self._counter), item)
heapq.heappush(self._entries, entry)
self._entries.append(request)
return True
def pop(self) -> Request | None:
if not self._entries:
return None
return heapq.heappop(self._entries)[-1].request
return self._entries.popleft()
def peek(self) -> Request | None:
if not self._entries:
return None
return self._entries[0][-1].request
def age(self, dt: float = 1.0) -> None:
"""Pull queued priorities toward critical so old items catch up."""
if self.age_rate <= 0:
return
rebuilt = []
for entry in self._entries:
item = entry[-1]
item.weight += self.age_rate * dt * (1.0 - item.weight)
rebuilt.append((*item.key(), next(self._counter), item))
self._entries = rebuilt
heapq.heapify(self._entries)
return self._entries[0]
def __len__(self) -> int:
return len(self._entries)
def items(self) -> Iterator[tuple[float, Request]]:
for entry in sorted(self._entries, key=lambda e: e[:-1]):
item = entry[-1]
yield item.weight, item.request
def items(self) -> Iterator[Request]:
yield from self._entries
+140
View File
@@ -0,0 +1,140 @@
"""Long-form spoken reading: bookmark positions and speakable chunking.
A skill that resolves a long text (a book) asks the voice front end to read it
aloud; the front end streams it with text-to-speech one speakable chunk at a
time. The position reached is recorded in a ``bookmarks.json`` file beside the
saved text so a later request resumes where the listener stopped.
This module is neutral and stdlib-only: it knows nothing about the scheduler,
the gateway, or audio. The chunker is deterministic — the same text and start
offset always yield the same chunks — so a saved offset is always a valid
resume point.
"""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Iterator
#: The file (beside the saved books) that maps a book key -> last read offset.
BOOKMARKS_FILE = "bookmarks.json"
#: Default characters per spoken chunk. Kept below the voice front end's
#: `max_speak_chars` so a chunk is spoken whole, never truncated.
DEFAULT_CHUNK_CHARS = 300
_WHITESPACE = " \t\r\n"
_SENTENCE_END = ".!?"
def bookmarks_file(directory) -> Path:
"""The bookmarks path inside a books directory."""
return Path(directory) / BOOKMARKS_FILE
def load_bookmarks(path) -> dict:
"""Read the bookmarks map (``{key: {"offset", "title", "updated_at"}}``).
A missing or unparseable file is an empty map — bookmarks are an
optimization, never a reason a read fails.
"""
target = Path(path)
if not target.is_file():
return {}
try:
data = json.loads(target.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return data if isinstance(data, dict) else {}
def read_offset(path, key) -> int:
"""The last read offset recorded for `key` (0 when unset/unknown)."""
entry = load_bookmarks(path).get(str(key))
if isinstance(entry, dict):
try:
return max(0, int(entry.get("offset", 0)))
except (TypeError, ValueError):
return 0
if isinstance(entry, int): # tolerate a bare-offset legacy shape
return max(0, entry)
return 0
def save_bookmark(path, key, offset, title: str = "") -> None:
"""Record the read offset for `key`, atomically.
Written to a temp file and renamed so a reader never sees a half-written
map. Any filesystem failure is swallowed: a failed bookmark must not break
the reading itself.
"""
target = Path(path)
data = load_bookmarks(target)
data[str(key)] = {
"offset": max(0, int(offset)),
"title": str(title or ""),
"updated_at": time.time(),
}
try:
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_name(target.name + ".tmp")
tmp.write_text(
json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
os.replace(tmp, target)
except OSError:
pass
def _skip_whitespace(text: str, index: int) -> int:
while index < len(text) and text[index] in _WHITESPACE:
index += 1
return index
def _break_point(window: str) -> int:
"""How many characters of `window` to keep for one chunk.
Prefer a paragraph break, then a sentence end, then a whitespace break —
but only past the window's midpoint, so a break never yields a tiny chunk.
Falls back to the whole window when it holds no good boundary.
"""
half = len(window) // 2
paragraph = window.rfind("\n\n")
if paragraph >= half:
return paragraph + 2
for index in range(len(window) - 1, -1, -1):
if window[index] in _SENTENCE_END and (
index + 1 == len(window) or window[index + 1] in _WHITESPACE + "\"')]"
):
return index + 1
space = window.rfind(" ")
if space >= half:
return space + 1
return len(window)
def chunk_text(text: str, start: int = 0, max_chars: int = DEFAULT_CHUNK_CHARS) -> Iterator[tuple[int, str]]:
"""Yield ``(offset, chunk)`` speakable chunks of `text` from `start`.
`offset` is the absolute index of the chunk's first character in `text`, so
a front end can persist it as the resume point. Deterministic for a given
`text`, `start`, and `max_chars`.
"""
text = text or ""
total = len(text)
limit_chars = max(1, int(max_chars))
index = _skip_whitespace(text, max(0, int(start)))
while index < total:
window_end = min(index + limit_chars, total)
if window_end >= total:
end = total
else:
end = index + _break_point(text[index:window_end])
chunk = text[index:end].strip()
if chunk:
yield index, chunk
index = _skip_whitespace(text, end)
+826 -451
View File
File diff suppressed because it is too large. Load diff
+898
View File
@@ -0,0 +1,898 @@
"""First-run setup: the bootstrap interview, config generation, and the plan.
``scripts/bootstrap.sh`` calls this module (via ``python -m semif_agent.cli
setup``) to ask the few questions that make a fresh machine work — which decision
engine, whether the agent may author new skills, which capability packs, and
which gateways — and to write the split ``config/`` plus ``secrets.json`` from
the answers. It also emits a machine-readable *plan* so bootstrap installs **only
what the answers require** (no simplex-chat binary for a REPL-only host, no
Playwright for a host that did not pick the browser pack, no voice stack without
the voice gateway).
Which packs exist is owned by a dedicated *pack index* repo (``semif-packs``),
not this checkout; bootstrap fetches it and passes ``--pack-index FILE`` so the
interview offers exactly the packs the index lists. Config generation still reads
each pack's ``pack.json`` from the cloned ``packs/`` tree, so bootstrap runs setup
in two passes: ``--answers-out FILE`` collects the answers (no packs needed),
bootstrap clones only the selected packs, then a second pass writes the config.
The two ends of the spectrum are both reachable here:
* **Minimum** — the local SemIf 4B decision engine + the ``essentials`` pack
(canned replies, time/timers, calculator). No account, no network, no gateway.
* **Maximum** — every pack (SimpleX, browser, Nextcloud, Outlook), a remote
Winnow decision engine, remote ``llm``/``codegen`` endpoints, and all
gateways (SimpleX, LXMF, voice).
The module is pure stdlib and takes injectable ``input_fn``/``output`` so the
interview is unit-testable without a TTY.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Iterable, Sequence
from .config import (
DEFAULT_SECRETS_FILE,
default_config,
load_secrets,
write_split_config,
)
from .packs import SkillPack, pack_enabled
#: ``llm``/``codegen`` providers the wizard can emit.
PROVIDERS = ("semif", "ollama", "opencode", "openai")
#: ``engine`` providers.
ENGINE_PROVIDERS = ("semif", "winnow", "ollama")
#: New-skill creation modes.
AUTHORING_MODES = ("deny", "ask", "allow")
# The capability packs the wizard offers come from the pack index repo
# (`semif-packs`), passed as `--pack-index FILE` (see `load_pack_index`); the
# index is the single source of truth for which packs exist. With no index the
# interview offers essentials only (see `run_interview`).
#: Gateway platforms the wizard offers.
GATEWAY_CHOICES: tuple[tuple[str, str], ...] = (
("simplex", "SimpleX command gateway (DM the bot to run tasks)"),
("lxmf", "LXMF / Reticulum command gateway (in-process, no daemon)"),
("voice", "Voice gateway (wake word + speech, needs a microphone)"),
)
#: The always-on pack: the built-in local utilities.
BASE_PACK = "essentials"
@dataclass
class Answers:
"""The wizard's answers, and the source of truth for the generated config."""
# Decision engine.
engine_provider: str = "semif" # semif | winnow | ollama
winnow_base_url: str = ""
winnow_model: str = ""
winnow_api_key: str = ""
#: Ollama's native System One route (`engine.ollama`).
ollama_base_url: str = ""
ollama_model: str = ""
ollama_api_key: str = ""
# New-skill authoring: deny | ask | allow.
new_skill_creation: str = "deny"
# The small `llm` (title/description) provider. `semif` reuses the loaded
# decision model in-process, so the minimum path needs no endpoint at all.
llm_provider: str = "semif"
llm_base_url: str = ""
llm_model: str = ""
llm_api_key: str = ""
# The `codegen` (skill-body) provider. Empty model == not configured; the
# agent then has no authoring path (which is the minimum path's intent).
codegen_provider: str = "ollama"
codegen_base_url: str = ""
codegen_model: str = ""
codegen_api_key: str = ""
# Capability packs to enable (essentials is always included).
packs: list[str] = field(default_factory=lambda: [BASE_PACK])
# Gateway platforms to enable.
gateways: list[str] = field(default_factory=list)
# LXMF gateway: transcribe Sideband push-to-talk voice messages into
# commands (install `requirements/transcribe.txt`; faster-whisper only) and
# reply to a voice chat with a Piper voice message (install
# `requirements/tts.txt`; piper-tts + PyAV).
lxmf_voice: bool = False
lxmf_voice_reply: bool = True
# IANA timezone; empty uses the host zone.
timezone: str = ""
# Nextcloud connection (optional; collected only when the pack is picked).
nextcloud_url: str = ""
nextcloud_username: str = ""
nextcloud_app_password: str = ""
# Outlook public-client id (not a secret).
outlook_client_id: str = ""
def __post_init__(self) -> None:
self.engine_provider = _norm(self.engine_provider, ENGINE_PROVIDERS, "semif")
self.new_skill_creation = _norm(
self.new_skill_creation, AUTHORING_MODES, "deny"
)
self.llm_provider = _norm(self.llm_provider, PROVIDERS, "semif")
self.codegen_provider = _norm(self.codegen_provider, PROVIDERS, "ollama")
self.packs = _clean_list(self.packs)
self.gateways = _clean_list(self.gateways)
self.normalize()
def normalize(self) -> "Answers":
"""Ensure the always-on base pack is present (idempotent)."""
if BASE_PACK not in self.packs:
self.packs.insert(0, BASE_PACK)
return self
@classmethod
def minimal(cls) -> "Answers":
"""The minimum working path: local engine, no authoring, essentials only."""
return cls()
@classmethod
def from_dict(cls, data: dict) -> "Answers":
"""Build answers from a JSON object (an ``--answers FILE`` payload)."""
fields = {f for f in cls.__dataclass_fields__} # type: ignore[attr-defined]
return cls(**{k: v for k, v in (data or {}).items() if k in fields})
def to_dict(self) -> dict:
return {
f: getattr(self, f) for f in self.__dataclass_fields__ # type: ignore[attr-defined]
}
def _norm(value: str, allowed: Sequence[str], default: str) -> str:
value = str(value or "").strip().lower()
return value if value in allowed else default
def _clean_list(values: Iterable[str] | None) -> list[str]:
out: list[str] = []
for value in values or []:
token = str(value).strip().lower()
if token and token not in out:
out.append(token)
return out
# --------------------------------------------------------------------------- #
# Interview
# --------------------------------------------------------------------------- #
def _ask_text(
input_fn: Callable[[str], str],
output: Callable[[str], None],
prompt: str,
default: str = "",
*,
secret: bool = False,
) -> str:
suffix = f" [{default}]" if default else ""
try:
raw = input_fn(f"{prompt}{suffix}: ").strip()
except EOFError:
raw = ""
return raw or default
def _ask_choice(
input_fn: Callable[[str], str],
output: Callable[[str], None],
prompt: str,
options: Sequence[tuple[str, str]],
default_index: int = 1,
) -> str:
for index, (_, label) in enumerate(options, 1):
marker = " (default)" if index == default_index else ""
output(f" {index}) {label}{marker}")
while True:
raw = _ask_text(input_fn, output, prompt, str(default_index))
if raw.isdigit() and 1 <= int(raw) <= len(options):
return options[int(raw) - 1][0]
output(f" please enter a number between 1 and {len(options)}")
def _ask_multi(
input_fn: Callable[[str], str],
output: Callable[[str], None],
prompt: str,
options: Sequence[tuple[str, str]],
default: Iterable[str] = (),
) -> list[str]:
letters = {chr(ord("a") + i): key for i, (key, _) in enumerate(options)}
for index, (_, label) in enumerate(options):
output(f" {chr(ord('a') + index)}) {label}")
default = list(default)
default_str = ",".join(
chr(ord("a") + i) for i, (key, _) in enumerate(options) if key in default
)
raw = _ask_text(input_fn, output, prompt, default_str)
if not raw:
return []
picked: list[str] = []
for token in raw.replace(" ", "").split(","):
key = letters.get(token.lower())
if key and key not in picked:
picked.append(key)
return picked
def _ask_provider(
input_fn: Callable[[str], str],
output: Callable[[str], None],
label: str,
default: str,
*,
allow_semif: bool = True,
) -> str:
options: list[tuple[str, str]] = []
if allow_semif:
options.append(("semif", "the loaded decision engine (in-process, no endpoint)"))
options += [
("ollama", "a local ollama endpoint"),
("opencode", "the hosted OpenCode Console"),
("openai", "another OpenAI-compatible endpoint"),
]
default_index = next(
(i for i, (key, _) in enumerate(options, 1) if key == default), 1
)
output(f" Which endpoint should {label} use?")
return _ask_choice(input_fn, output, f"{label} provider", options, default_index)
def _collect_llm(
input_fn: Callable[[str], str],
output: Callable[[str], None],
answers: Answers,
*,
label: str,
allow_semif: bool,
) -> None:
"""Ask for an OpenAI-compatible endpoint and record it on `answers`."""
provider = _ask_provider(
input_fn, output, label, answers.llm_provider, allow_semif=allow_semif
)
setattr(answers, f"{label}_provider", provider)
if provider == "semif":
setattr(answers, f"{label}_model", "")
setattr(answers, f"{label}_base_url", "")
setattr(answers, f"{label}_api_key", "")
return
if provider == "opencode":
base_default = "https://opencode.ai/inference/openai/v1"
elif provider == "ollama":
base_default = "http://localhost:11434/v1"
else:
base_default = ""
setattr(
answers,
f"{label}_base_url",
_ask_text(input_fn, output, f"{label} base URL", base_default),
)
model = ""
while not model:
model = _ask_text(input_fn, output, f"{label} model (required)")
if not model:
output(f" {label}.model is required; the agent fails fast without it.")
setattr(answers, f"{label}_model", model)
key = _ask_text(
input_fn, output, f"{label} API key (blank for none)", "", secret=True
)
setattr(answers, f"{label}_api_key", key)
def load_pack_index(path: str | Path | None) -> list[tuple[str, str]]:
"""The interview's pack choices ``(key, label)`` from a pack-index JSON file.
The index repo (``semif-packs``) owns which packs exist; bootstrap clones it
and passes ``--pack-index FILE``. Each entry is ``{name, url, title?,
description?}``; the label is ``"<title> — <description>"`` (or the name).
Returns ``[]`` for a missing/unreadable index — the interview then offers
essentials only.
"""
if not path:
return []
try:
data = json.loads(Path(path).read_text())
except (OSError, ValueError):
return []
choices: list[tuple[str, str]] = []
for entry in data.get("packs", []) or []:
if not isinstance(entry, dict):
continue
name = str(entry.get("name", "")).strip()
if not name:
continue
title = str(entry.get("title") or name).strip()
desc = str(entry.get("description") or "").strip()
choices.append((name, f"{title} — {desc}" if desc else title))
return choices
def run_interview(
*,
input_fn: Callable[[str], str] = input,
output: Callable[[str], None] = print,
interactive: bool = True,
prefill: Answers | None = None,
pack_choices: Sequence[tuple[str, str]] | None = None,
) -> Answers:
"""Run the setup interview and return the answers.
``interactive=False`` returns the prefill (or the minimum path) without
prompting — the ``--yes`` behaviour. ``pack_choices`` is the offered pack
list (from the pack index); empty means essentials only.
"""
answers = prefill or Answers.minimal()
if not interactive:
return answers
output("")
output("== SemIf agent setup ==")
output(
"This writes this machine's config. Press Enter to accept the default\n"
"shown in [brackets]. Nothing is installed that your answers don't need."
)
# 1. Decision engine.
output("")
output("Decision engine")
output(
" The decision engine routes every request. It runs locally on the\n"
" pinned SemIf 4B GGUF by default (no network), or against a remote\n"
" Winnow /v1/systemone server or an Ollama System One decision model."
)
answers.engine_provider = _ask_choice(
input_fn,
output,
"engine",
[
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
("winnow", "remote Winnow decision server"),
("ollama", "remote Ollama System One model (/v1/systemone)"),
],
1,
)
if answers.engine_provider == "winnow":
answers.winnow_base_url = _ask_text(
input_fn, output, " winnow base URL", "http://127.0.0.1:8091"
)
model = ""
while not model:
model = _ask_text(input_fn, output, " winnow model (required)")
if not model:
output(" engine.winnow.model is required.")
answers.winnow_model = model
answers.winnow_api_key = _ask_text(
input_fn, output, " winnow API key (blank for none)", "", secret=True
)
elif answers.engine_provider == "ollama":
answers.ollama_base_url = _ask_text(
input_fn, output, " ollama base URL", "http://127.0.0.1:11434"
)
model = ""
while not model:
model = _ask_text(
input_fn, output, " ollama System One model (required)"
)
if not model:
output(" engine.ollama.model is required.")
answers.ollama_model = model
answers.ollama_api_key = _ask_text(
input_fn,
output,
" ollama API key (blank for a local server)",
"",
secret=True,
)
# 2. Skill authoring.
output("")
output("Skill authoring")
output(
" May the agent write brand-new skills when no shipped skill fits?\n"
" This needs two endpoints: a small `llm` to name the skill and a\n"
" code-capable `codegen` to write its body."
)
mode = _ask_choice(
input_fn,
output,
"authoring",
[
("deny", "no — use the shipped skills only (recommended)"),
("ask", "ask me before each new skill"),
("allow", "yes — write new skills automatically"),
],
1,
)
answers.new_skill_creation = mode
if mode != "deny":
output("")
# The Ollama System One decision model does not generate text, so it
# cannot back the small `llm` task; only a real endpoint can.
_collect_llm(
input_fn,
output,
answers,
label="llm",
allow_semif=answers.engine_provider != "ollama",
)
output("")
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False)
# 3. Capability packs (the offered list comes from the pack index; the
# always-on base pack is never offered — it is included automatically).
output("")
output("Capabilities (skill packs)")
choices = [c for c in (pack_choices or []) if c[0] != BASE_PACK]
if choices:
output(
" Essentials (time, timers, calculator) is always included. Enable more\n"
" packs by their letter; separate several with commas (e.g. a,c)."
)
answers.packs = _ask_multi(
input_fn,
output,
"packs (blank for essentials only)",
choices,
default=[p for p in answers.packs if p != BASE_PACK],
)
else:
output(
" No pack index was provided, so only essentials (time, timers,\n"
" calculator) will be enabled. Pass --pack-index FILE to choose packs."
)
# 4. Pack-specific connection details.
if "nextcloud" in answers.packs:
output("")
output("Nextcloud connection (blank to fill in later)")
answers.nextcloud_url = _ask_text(
input_fn, output, " Nextcloud URL", answers.nextcloud_url
)
answers.nextcloud_username = _ask_text(
input_fn, output, " Nextcloud username", answers.nextcloud_username
)
answers.nextcloud_app_password = _ask_text(
input_fn,
output,
" Nextcloud app password",
answers.nextcloud_app_password,
secret=True,
)
if "outlook" in answers.packs:
output("")
output("Outlook / Microsoft 365")
output(
" Register an Entra ID public-client app and paste its application\n"
" (client) id; run packs/outlook/scripts/outlook-auth.py once after."
)
answers.outlook_client_id = _ask_text(
input_fn, output, " Outlook client id", answers.outlook_client_id
)
# 5. Gateways.
output("")
output("Gateways (how you talk to the agent)")
output(
" You can always use the terminal REPL and dashboard. Optionally reach\n"
" the agent over a messenger or the local microphone too."
)
answers.gateways = _ask_multi(
input_fn,
output,
"gateways (blank for none)",
GATEWAY_CHOICES,
default=answers.gateways,
)
# 5b. LXMF voice messages (Sideband push-to-talk).
if "lxmf" in answers.gateways:
output("")
output("LXMF voice messages")
output(
" Sideband can send push-to-talk voice messages. The agent can\n"
" transcribe them into commands, and reply to a voice chat with a\n"
" synthesized voice message (Piper)."
)
mode = _ask_choice(
input_fn,
output,
"lxmf voice",
[
("off", "ignore voice messages"),
("transcribe", "transcribe to commands, reply with text"),
("reply", "transcribe, and reply with a synthesized voice"),
],
3,
)
answers.lxmf_voice = mode in ("transcribe", "reply")
answers.lxmf_voice_reply = mode == "reply"
# 6. Timezone.
output("")
answers.timezone = _ask_text(
input_fn,
output,
"Timezone (IANA name, e.g. America/Chicago; blank for the host zone)",
answers.timezone,
)
return answers.normalize()
# --------------------------------------------------------------------------- #
# Config generation
# --------------------------------------------------------------------------- #
def _set_secret_or_literal(block: dict, key: str, value: str, secret_key: str) -> None:
"""Write ``!secret <secret_key>`` when a value is present, else an empty literal."""
block[key] = f"!secret {secret_key}" if value else ""
def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
"""The merged config dict for these answers (defaults + overrides)."""
answers.normalize()
config = default_config(packs)
# Decision engine.
engine = config.setdefault("engine", {})
engine["provider"] = answers.engine_provider
if answers.engine_provider == "winnow":
winnow = engine.setdefault("winnow", {})
if answers.winnow_base_url:
winnow["base_url"] = answers.winnow_base_url
winnow["model"] = answers.winnow_model
_set_secret_or_literal(
winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key"
)
elif answers.engine_provider == "ollama":
ollama = engine.setdefault("ollama", {})
if answers.ollama_base_url:
ollama["base_url"] = answers.ollama_base_url
ollama["model"] = answers.ollama_model
_set_secret_or_literal(
ollama, "api_key", answers.ollama_api_key, "engine_ollama_api_key"
)
# Authoring mode.
config["new_skill_creation"] = answers.new_skill_creation
# `llm`: semif reuses the loaded engine; anything else needs an endpoint.
llm = config.setdefault("llm", {})
llm["provider"] = answers.llm_provider
if answers.llm_provider == "semif":
llm["model"] = ""
llm["api_key"] = ""
else:
if answers.llm_base_url:
llm["base_url"] = answers.llm_base_url
llm["model"] = answers.llm_model
_set_secret_or_literal(llm, "api_key", answers.llm_api_key, "llm_api_key")
# `codegen`: an empty model means "not configured" (no authoring path).
codegen = config.setdefault("codegen", {})
if answers.codegen_model:
codegen["provider"] = answers.codegen_provider
if answers.codegen_base_url:
codegen["base_url"] = answers.codegen_base_url
codegen["model"] = answers.codegen_model
_set_secret_or_literal(
codegen, "api_key", answers.codegen_api_key, "codegen_api_key"
)
else:
codegen["model"] = ""
codegen["api_key"] = ""
if answers.timezone:
config["timezone"] = answers.timezone
# Packs: enable exactly the chosen ones (essentials always on).
for pack in packs:
enabled = pack.name in answers.packs
if pack.bridges:
config.setdefault("bridges", {}).setdefault(pack.bridges[0], {})[
"enabled"
] = enabled
else:
config.setdefault("packs", {}).setdefault(pack.name, {})["enabled"] = enabled
# The shared LLM bridge is only useful when a bridge-owning pack is on.
bridge_packs = [p for p in packs if p.bridges and p.name in answers.packs]
config.setdefault("bridges", {}).setdefault("llm", {})["enabled"] = bool(
bridge_packs
)
# Nextcloud / Outlook connection details.
if "nextcloud" in answers.packs:
nc = config["bridges"].setdefault("nextcloud", {})
if answers.nextcloud_url:
nc["url"] = answers.nextcloud_url
if answers.nextcloud_username:
nc["username"] = answers.nextcloud_username
_set_secret_or_literal(
nc, "app_password", answers.nextcloud_app_password, "nextcloud_app_password"
)
if "outlook" in answers.packs:
config["bridges"].setdefault("outlook", {})["client_id"] = (
answers.outlook_client_id
)
# Gateways.
gateway = config.setdefault("gateway", {})
for platform in ("simplex", "lxmf", "voice"):
gateway.setdefault(platform, {})["enabled"] = platform in answers.gateways
gateway.setdefault("humanize", {})["enabled"] = bool(answers.gateways)
# Sideband voice messages are transcribed only when the LXMF gateway is on
# and the answer opted in; needs faster-whisper (requirements/transcribe.txt).
# A voice reply adds Piper + PyAV (requirements/tts.txt).
voice_block = gateway.setdefault("lxmf", {}).setdefault("voice", {})
voice_block["enabled"] = bool("lxmf" in answers.gateways and answers.lxmf_voice)
voice_block["reply_with_voice"] = bool(answers.lxmf_voice_reply)
return config
def build_secrets(answers: Answers) -> dict:
"""The secrets to store for these answers (only keys that were provided)."""
secrets: dict[str, str] = {}
if answers.engine_provider == "winnow" and answers.winnow_api_key:
secrets["engine_winnow_api_key"] = answers.winnow_api_key
if answers.engine_provider == "ollama" and answers.ollama_api_key:
secrets["engine_ollama_api_key"] = answers.ollama_api_key
if answers.llm_provider != "semif" and answers.llm_api_key:
secrets["llm_api_key"] = answers.llm_api_key
if answers.codegen_api_key:
secrets["codegen_api_key"] = answers.codegen_api_key
if "nextcloud" in answers.packs and answers.nextcloud_app_password:
secrets["nextcloud_app_password"] = answers.nextcloud_app_password
return secrets
def write_secrets(root: str | Path, secrets: dict, *, merge: bool = True) -> Path:
"""Write ``secrets.json`` under `root`, merging with any existing entries."""
path = Path(root) / DEFAULT_SECRETS_FILE
current = load_secrets(path) if merge else {}
current.update({k: v for k, v in secrets.items() if v})
path.write_text(json.dumps(current, indent=2) + "\n")
return path
# --------------------------------------------------------------------------- #
# Install plan
# --------------------------------------------------------------------------- #
def build_plan(answers: Answers, packs: Sequence[SkillPack]) -> dict:
"""What bootstrap should install for these answers.
Drives the conditional stages so a REPL-only host never downloads the
simplex-chat binary, Playwright, or the voice stack.
"""
answers.normalize()
bridge_packs = [
p.name for p in packs if p.bridges and p.name in answers.packs
]
daemon_gateways = [g for g in answers.gateways if g != "voice"]
return {
"engine_provider": answers.engine_provider,
"authoring": answers.new_skill_creation,
"packs": list(answers.packs),
"bridge_packs": bridge_packs,
# Packs that ship their own python deps (packs/<name>/requirements.txt);
# bootstrap pip-installs each. See PACKGEN.md, "Pack python deps".
"pack_requirements": [
p.name for p in packs if p.name in answers.packs and p.requirements_file
],
"gateways": list(answers.gateways),
# Platforms the systemd gateway unit runs (voice is foreground-only).
"gateway_platforms": daemon_gateways,
"install_engine": answers.engine_provider == "semif",
"install_bridge_service": bool(bridge_packs),
"install_gateway_service": bool(daemon_gateways),
"install_simplex_binary": ("simplex" in answers.packs)
or ("simplex" in answers.gateways),
"install_simplex_forward": "simplex" in answers.packs,
"install_browser": "browser" in answers.packs,
"install_voice": "voice" in answers.gateways,
# faster-whisper only (no microphone stack): transcribe Sideband voice
# messages when the LXMF gateway is on and the answer opted in.
"install_transcribe": "lxmf" in answers.gateways and bool(answers.lxmf_voice),
# Piper + PyAV (no microphone stack): reply to a voice chat with a
# synthesized voice message when the LXMF gateway handles voice and the
# answer wants voice replies.
"install_lxmf_tts": (
"lxmf" in answers.gateways
and bool(answers.lxmf_voice)
and bool(answers.lxmf_voice_reply)
),
}
def plan_from_config(config: dict, packs: Sequence[SkillPack]) -> dict:
"""Derive the same plan from an already-merged config (a rerun)."""
gateways = [
platform
for platform in ("simplex", "lxmf", "voice")
if ((config.get("gateway", {}) or {}).get(platform, {}) or {}).get("enabled")
]
enabled = [p.name for p in packs if pack_enabled(config, p)]
bridge_packs = [p.name for p in packs if p.bridges and p.name in enabled]
daemon_gateways = [g for g in gateways if g != "voice"]
engine_provider = str(
(config.get("engine", {}) or {}).get("provider", "semif") or "semif"
).lower()
return {
"engine_provider": engine_provider,
"authoring": str(config.get("new_skill_creation", "deny") or "deny"),
"packs": enabled,
"bridge_packs": bridge_packs,
"pack_requirements": [
p.name for p in packs if p.name in enabled and p.requirements_file
],
"gateways": gateways,
"gateway_platforms": daemon_gateways,
"install_engine": engine_provider == "semif",
"install_bridge_service": bool(bridge_packs),
"install_gateway_service": bool(daemon_gateways),
"install_simplex_binary": ("simplex" in enabled) or ("simplex" in gateways),
"install_simplex_forward": "simplex" in enabled,
"install_browser": "browser" in enabled,
"install_voice": "voice" in gateways,
"install_transcribe": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
),
"install_lxmf_tts": bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("enabled")
)
and bool(
(((config.get("gateway", {}) or {}).get("lxmf", {}) or {})
.get("voice", {}) or {})
.get("reply_with_voice", True)
),
}
# --------------------------------------------------------------------------- #
# Top-level entry used by the CLI
# --------------------------------------------------------------------------- #
def run_setup(
*,
root: str | Path,
path: str | Path,
packs: Sequence[SkillPack],
interview: bool = False,
yes: bool = False,
answers_file: str | None = None,
plan_only: bool = False,
plan_out: str | None = None,
force: bool = False,
answers_out: str | None = None,
pack_index: str | None = None,
input_fn: Callable[[str], str] = input,
output: Callable[[str], None] = print,
) -> int:
"""Seed (or re-seed) the split config from an interview, or emit a plan.
Returns a process exit code. In ``plan_only`` mode it reads the existing
config and writes the derived plan without touching anything. In
``answers_out`` mode it collects the answers and writes them as JSON to that
path (no config, no packs needed) — the bootstrap phase that precedes cloning
the selected packs. ``pack_index`` is the pack-index file whose entries the
interview offers (see `load_pack_index`).
"""
config_path = Path(path)
if plan_only:
from .config import load_config_file
try:
raw = load_config_file(config_path)
except Exception as exc: # noqa: BLE001 - surfaced as a clean error
output(f"could not read {config_path}: {exc}")
return 1
plan = plan_from_config(raw, packs)
_emit_plan(plan, plan_out, output)
return 0
prefill = None
if answers_file:
try:
prefill = Answers.from_dict(json.loads(Path(answers_file).read_text()))
except (OSError, ValueError) as exc:
output(f"could not read answers file {answers_file}: {exc}")
return 1
choices = load_pack_index(pack_index)
# Answers-only pass: collect and persist the answers, then stop. Bootstrap
# uses this to learn which packs to clone before config generation needs them.
if answers_out is not None:
if interview and not yes:
answers = run_interview(
input_fn=input_fn, output=output, interactive=True,
prefill=prefill, pack_choices=choices,
)
else:
answers = prefill or Answers.minimal()
out_path = Path(answers_out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(answers.to_dict(), indent=2) + "\n")
output("")
output("== answers captured")
_print_summary(answers, output)
return 0
if config_path.exists() and not force:
output(f"{config_path} already exists; leaving it alone (use --force)")
return 1
if interview and not yes:
answers = run_interview(
input_fn=input_fn, output=output, interactive=True,
prefill=prefill, pack_choices=choices,
)
else:
answers = prefill or Answers.minimal()
config = build_config(answers, packs)
written = write_split_config(Path(root), config, packs)
secrets_path = write_secrets(Path(root), build_secrets(answers), merge=True)
plan = build_plan(answers, packs)
output("")
output("== config written")
output(f" {len(written)} files under {Path(root) / 'config'}")
output(f" {secrets_path.name} (credentials)")
_print_summary(answers, output)
_emit_plan(plan, plan_out, output)
return 0
def _print_summary(answers: Answers, output: Callable[[str], None]) -> None:
output(
" engine: "
+ (
"local SemIf 4B"
if answers.engine_provider == "semif"
else (
f"remote Winnow ({answers.winnow_model or '?'})"
if answers.engine_provider == "winnow"
else f"remote Ollama System One ({answers.ollama_model or '?'})"
)
)
)
output(f" authoring: {answers.new_skill_creation}")
output(f" packs: {', '.join(answers.packs)}")
output(f" gateways: {', '.join(answers.gateways) or 'none (REPL + dashboard)'}")
if answers.timezone:
output(f" timezone: {answers.timezone}")
def _emit_plan(plan: dict, plan_out: str | None, output: Callable[[str], None]) -> None:
if plan_out:
Path(plan_out).parent.mkdir(parents=True, exist_ok=True)
Path(plan_out).write_text(json.dumps(plan, indent=2) + "\n")
else:
output("PLAN " + json.dumps(plan))
+168 -11
View File
@@ -34,25 +34,45 @@ ConnectedHandler = Callable[[], Awaitable[None]]
def contact_entry(contact: dict) -> dict | None:
"""Normalize one daemon `Contact` into `{"id", "display_name"}`, or None.
"""Normalize one daemon `Contact` into a contact dict, or None.
The single source of truth for contact identity across the wire: the same
shape appears in `newChatItems` items and in the `/_contacts` list. v7's
`Contact.displayName` is null and the real peer name lives in
`profile.displayName`; `localDisplayName` is auto-suffixed on collisions
(e.g. a second contact becomes `pepper_1`).
`profile.displayName`; `localDisplayName` is the daemon's **unique** local
name, auto-suffixed on collisions (e.g. a second contact becomes
`pepper_1`). We keep both: `display_name` is the peer's profile name (what
a human recognizes, but it can collide) and `local_name` is the daemon's
unique name, so two peers with the same profile name stay distinguishable.
When the daemon reports connection state (the `/_contacts` list does),
`connected` and `auth_errors` are included so callers can prefer a live
peer over a dead one.
"""
contact_id = str(contact.get("contactId") or contact.get("chatId") or "")
if not contact_id:
return None
profile = contact.get("profile") or {}
local_name = (
contact.get("localDisplayName")
or contact.get("displayName")
or profile.get("displayName")
or ""
)
display_name = (
profile.get("displayName")
or contact.get("displayName")
or contact.get("localDisplayName")
or local_name
or ""
)
return {"id": contact_id, "display_name": display_name}
entry = {"id": contact_id, "display_name": display_name, "local_name": local_name}
active = contact.get("activeConn") or {}
conn = active.get("connStatus") or {}
status = contact.get("contactStatus")
if status is not None or conn:
entry["connected"] = status == "active" and conn.get("type") == "ready"
if isinstance(active.get("authErrCounter"), int):
entry["auth_errors"] = active["authErrCounter"]
return entry
def contact_link(resp: dict) -> dict:
@@ -111,8 +131,9 @@ def parse_chat_item(item: dict) -> dict | None:
text = _text_from_content(item.get("content") or {})
if not text:
return None
status = (meta.get("itemStatus") or {}).get("type") or ""
return {
status_obj = meta.get("itemStatus") or {}
status = status_obj.get("type") or ""
entry = {
"item_id": str(item_id),
"text": text,
"status": status,
@@ -120,6 +141,12 @@ def parse_chat_item(item: dict) -> dict | None:
"direction": (item.get("chatDir") or {}).get("type") or "",
"sent_at": meta.get("itemTs") or "",
}
# A failed send carries the agent-level reason (`{"type":"auth"}` etc.);
# surface it so a caller can report *why* a message did not go out.
agent_error = status_obj.get("agentError") or {}
if agent_error:
entry["error"] = agent_error.get("type") or str(agent_error)
return entry
def parse_chat(achat: dict) -> dict | None:
@@ -159,10 +186,10 @@ def parse_chat(achat: dict) -> dict | None:
def parse_direct_text_item(item: dict) -> InboundDict | None:
"""Normalize one `newChatItems` entry into a message dict, or None.
Returns `{text, contact_id, display_name, raw}` for a received direct text
message. Drops group chats, own echoes, non-text content, and items with no
resolvable contact id. Authorization is the caller's job — this layer is
deliberately policy-free.
Returns `{text, contact_id, display_name, item_id, raw}` for a received
direct text message. Drops group chats, own echoes, non-text content, and
items with no resolvable contact id. Authorization is the caller's job —
this layer is deliberately policy-free.
"""
chat_info = item.get("chatInfo") or {}
if chat_info.get("type") != "direct":
@@ -194,10 +221,15 @@ def parse_direct_text_item(item: dict) -> InboundDict | None:
entry = contact_entry(contact)
if entry is None:
return None
item_id = (chat_item.get("meta") or {}).get("itemId")
return {
"text": text,
"contact_id": entry["id"],
"display_name": entry["display_name"],
"local_name": entry.get("local_name", ""),
# Carried so a consumer can mark exactly this item read (the bridge's
# live inbox keeps it; the command gateway ignores it).
"item_id": str(item_id) if item_id is not None else "",
"raw": item,
}
@@ -228,6 +260,64 @@ def accept_command(resp: dict) -> str | None:
return f"/_accept {req_id}"
def parse_send_response(resp: dict) -> dict:
"""Normalize a `/_send` response into `{item_id, status, error}`.
A successful send comes back as `newChatItems` carrying the freshly created
`chatItem` (its `meta.itemId` and initial `meta.itemStatus`, usually
`sndNew`). A rejected send comes back as `chatCmdError`. `item_id` is None
on any rejection so the caller can tell "no message was created" from
"created but later failed at the agent layer".
"""
if not isinstance(resp, dict):
return {"item_id": None, "status": "", "error": "empty daemon response"}
if resp.get("type") == "chatCmdError" or resp.get("error"):
detail = resp.get("chatError") or resp.get("error") or "chat command failed"
return {"item_id": None, "status": "", "error": str(detail)[:300]}
for item in resp.get("chatItems") or []:
meta = (item.get("chatItem") or {}).get("meta") or {}
item_id = meta.get("itemId")
if item_id is None:
continue
status = (meta.get("itemStatus") or {}).get("type") or ""
error = ((meta.get("itemStatus") or {}).get("agentError") or {}).get("type") or ""
return {"item_id": str(item_id), "status": status, "error": error}
return {"item_id": None, "status": "", "error": "daemon returned no message id"}
def read_command(chat_id: str, item_ids=None) -> str:
"""Structured command that marks a chat, or specific items, read.
v7 exposes `/_read chat @<id>` (the whole chat) and `/_read chat items @<id>
<comma-separated item ids>` (a precise subset). The item form is used so
consuming the next unread message clears exactly that message and leaves the
rest of the chat untouched. With no usable item ids it falls back to the
whole-chat form.
"""
chat_ref = f"@{str(chat_id).strip().lstrip('@')}"
if item_ids:
ids = ",".join(str(i).strip() for i in item_ids if str(i).strip())
if ids:
return f"/_read chat items {chat_ref} {ids}"
return f"/_read chat {chat_ref}"
def parse_read_response(resp: dict) -> dict:
"""Normalize a `/_read chat` response into `{ok, type, error}`.
A successful item read comes back as `itemsReadForChat` and a whole-chat
read as the chat's `ok`; a rejected command comes back as `chatCmdError`.
`ok` is True only when the daemon did not report an error, so a caller never
treats a rejected (or empty) response as a consumed message.
"""
if not isinstance(resp, dict) or not resp:
return {"ok": False, "type": "", "error": "empty daemon response"}
if resp.get("type") == "chatCmdError" or resp.get("error"):
detail = resp.get("chatError") or resp.get("error") or "read command failed"
return {"ok": False, "type": "chatCmdError", "error": str(detail)[:300]}
return {"ok": True, "type": resp.get("type") or "", "error": ""}
class SimplexDaemon:
"""One WebSocket connection to a `simplex-chat` daemon.
@@ -434,6 +524,73 @@ class SimplexDaemon:
future.cancel()
raise TimeoutError("simplex address request timed out") from exc
# ---- send ----
async def send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict:
"""Send a direct text message and return the daemon's correlated reply.
Unlike `enqueue` (fire-and-forget, used by the command gateway), this
awaits the `/_send` response so the caller sees whether the message was
created and its initial status. The daemon reports agent-level failures
(auth, quota) asynchronously, so a caller that needs delivery truth must
still poll `chat_history` for the item's terminal status.
"""
return await self._roundtrip(send_text_command(chat_id, text), timeout)
def request_send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict:
"""Thread-safe correlated send for callers off the event loop.
Raises `RuntimeError` when no live connection exists and `TimeoutError`
when the daemon does not answer in time — never a fabricated success.
"""
loop = self._loop
if loop is None or not loop.is_running():
raise RuntimeError("simplex gateway is not connected")
future = asyncio.run_coroutine_threadsafe(
self.send(chat_id, text, timeout=timeout), loop
)
try:
return future.result(timeout=timeout + 5.0)
except concurrent.futures.TimeoutError as exc:
future.cancel()
raise TimeoutError("simplex send request timed out") from exc
# ---- read ----
async def mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Mark a direct chat, or specific items, read on the daemon.
`/_read chat items @<id> <ids>` clears exactly the reported items'
`rcv_new` status (leaving other unread messages intact);
`/_read chat @<id>` clears the whole chat. Returns `{ok, type, error}`.
A transport failure raises (via `_roundtrip`) — never a fabricated
success.
"""
resp = await self._roundtrip(read_command(chat_id, item_ids), timeout)
return parse_read_response(resp)
def request_mark_read(
self, chat_id: str, item_ids=None, timeout: float = 20.0
) -> dict:
"""Thread-safe read-mark for callers off the event loop.
Raises `RuntimeError` when no live connection exists and `TimeoutError`
when the daemon does not answer in time — never a fabricated success.
"""
loop = self._loop
if loop is None or not loop.is_running():
raise RuntimeError("simplex gateway is not connected")
future = asyncio.run_coroutine_threadsafe(
self.mark_read(chat_id, item_ids, timeout=timeout), loop
)
try:
return future.result(timeout=timeout + 5.0)
except concurrent.futures.TimeoutError as exc:
future.cancel()
raise TimeoutError("simplex read request timed out") from exc
# ---- contacts ----
async def active_user(self, timeout: float = 20.0) -> int:
+112 -61
View File
@@ -7,11 +7,13 @@ the human for anything unresolved), performs the real action, and returns an
`ActionResult.decisions` and are logged by the runner with the run outcome.
Assessment is a SemIf decision, not generation: `assess:outcome` decides
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides
complete/retry. The run summary is deterministic — same inputs, same string —
built from the category, skill, outcome flag, and action log. Every SemIf
decision made during a run is logged as a training row; the assessment outcome
is kept on the row so the dream pass can weigh failed runs.
whether there is any additional work to do — `done` (request satisfied),
`continue` (the step worked but more work is needed; the scheduler routes the
next step), or `failed` (the step errored → the repair path). The run summary is
deterministic — same inputs, same string — built from the category, skill,
outcome flag, and action log. Every SemIf decision made during a run is logged as
a training row; the assessment outcome is kept on the row so the dream pass can
weigh failed runs.
A skill with a data contract may need variables collected from the human before
it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
@@ -32,9 +34,13 @@ from .log import DecisionLog
from .skills import (
CANNED_CATEGORIES,
DETERMINISTIC_CATEGORIES,
HOUSEKEEPING_CATEGORY,
ActionContext,
Skill,
SkillStore,
bound_output,
render_ledger,
render_recall,
resolve_skill_config,
unresolved_variables,
)
@@ -87,7 +93,12 @@ class RunResult:
summary: str
action_log: str
new_state: str
updated_request: str | None = None
#: The three-way outcome for a chained run: "done" (request satisfied),
#: "continue" (the step worked but more work is needed → the scheduler routes
#: the next step), or "failed" (the step errored → the repair path). None
#: only for a pause for input (needs_input/error), which never reaches the
#: outcome branch.
outcome: str | None = None
decisions_logged: int = 0
assessment_summary: str = ""
error: str | None = None
@@ -102,11 +113,25 @@ class SkillRunner:
log: DecisionLog,
store: SkillStore | None = None,
tau: float = 0.6,
done_tau: float = 0.5,
fail_tau: float = 0.5,
result_chars: int = 300,
):
self.ctx = ctx
self.log = log
self.store = store
self.tau = tau
#: Thresholds for the three-way `assess:outcome` decision. Precedence is
#: failed > done > continue: a step is only declared "continue" when the
#: model is genuinely unsure, so a confident success/failure is honored
#: and the chain is not entered needlessly.
self.done_tau = done_tau
self.fail_tau = fail_tau
#: The shared speakable budget: every skill's action_log/new_state is
#: truncated to this many characters (the same bound the voice front end
#: and the humanizer use), so a result fits one message / ~20s of speech
#: and the run ledger stays bounded.
self.result_chars = result_chars
# ---- contract resolution ----
@@ -123,7 +148,14 @@ class SkillRunner:
engine=self.ctx.engine,
config=merged,
timers=self.ctx.timers,
admin=self.ctx.admin,
# The scheduler's speech channel (a skill can post a long-form
# read-aloud for a voice front end) rides on every run.
speech=self.ctx.speech,
# `admin` (mutation of the agent) is reserved for the built-in
# housekeeping meta skills; an ordinary body only ever gets the
# read-only `catalog`.
admin=self.ctx.admin if skill.category == HOUSEKEEPING_CATEGORY else None,
catalog=self.ctx.catalog,
)
def _unresolved(self, skill: Skill, request: Request) -> list[str]:
@@ -288,82 +320,101 @@ class SkillRunner:
def _assess(
self, skill: Skill, request: Request, ctx: ActionContext, action
) -> tuple[bool, str | None]:
"""SemIf assessment: did the run succeed, and should it run again?
) -> str:
"""SemIf assessment: is there any *additional work* to be done?
`assess:outcome` decides success (`P(success) >= tau`); a failure is
then offered to `assess:requeue`, which picks complete/retry. On retry
the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The state carries
the resolved inputs so a wrong resolution is visible to the decision.
The engine is always real: EngineUnavailable propagates to the
scheduler, which marks the app fatal.
A single three-way `assess:outcome` decision over the step's own action
plus the run ledger so far:
- ``done`` — the request is satisfied (a definitive "nothing found"
counts as done);
- ``continue`` — the step worked, but the request is not yet satisfied;
the scheduler routes the next step (bounded by ``max_reentries`` and
the monotonic-progress guard);
- ``failed`` — the step errored / did not work → the repair path.
The verdict uses thresholds, not argmax, with precedence
``failed > done > continue`` (``fail_tau`` then ``done_tau``), so a
confident success/failure is honored and ``continue`` — the over-trigger
— only wins when the model is genuinely unsure. Real logged decision row
(phase `assess:outcome`). The state carries the skill's declared action,
the goal, the resolved inputs, the (bounded) action log, and the steps
already taken. The engine is always real: EngineUnavailable propagates to
the scheduler, which marks the app fatal.
"""
label = f"{skill.category}.{skill.name}"
resolved = _resolved_inputs(skill, ctx.config)
outcome = DecisionRequest(
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}"
),
question="Did the skill achieve the user's goal?",
observed = bound_output(action.action_log, self.result_chars)
if not observed:
observed = bound_output(action.new_state, self.result_chars)
state = (
f"skill: {label}\n"
f"skill action: {skill.description}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{observed}"
)
recall = render_recall(request)
if recall:
state += f"\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"
decision = DecisionRequest(
state=state,
question="Is there any additional work to be done to satisfy the request?",
options=[
Option("success", "Yes — the goal was met."),
Option("failure", "No — the goal was not met."),
Option(
"done",
"No — the request is satisfied. A definitive 'nothing found' "
"or 'nothing to do' result (empty inbox, no unread messages, "
"no matching event) counts as done.",
),
Option(
"continue",
"Yes — this step worked, but the request is not yet satisfied; "
"another skill should run next toward the same request.",
),
Option(
"failed",
"The step did not work: the result is an error, a refusal, or "
"an unresolved action.",
),
],
)
result = self.ctx.engine.call(outcome)
result = self.ctx.engine.call(decision)
self.log.append(
outcome,
decision,
result,
extra={"phase": "assess:outcome", "run_id": request.id, "skill": label},
)
success = result.prob("success") >= self.tau
if success:
return True, None
requeue = DecisionRequest(
state=(
f"skill: {label}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}\n"
"outcome: failed"
),
question="Is the request complete, or should it run again?",
options=[
Option("complete", "It is complete; do nothing further."),
Option("retry", "Run the original request again."),
],
)
requeue_result = self.ctx.engine.call(requeue)
self.log.append(
requeue,
requeue_result,
extra={"phase": "assess:requeue", "run_id": request.id, "skill": label},
)
updated = request.text if requeue_result.prob("retry") >= self.tau else None
return False, updated
probs = result.probs
if probs.get("failed", 0.0) >= self.fail_tau:
return "failed"
if probs.get("done", 0.0) >= self.done_tau:
return "done"
return "continue"
def _finish(
self, skill: Skill, request: Request, ctx: ActionContext, action
) -> RunResult:
observed = action.new_state
action_log = bound_output(action.action_log, self.result_chars)
observed = bound_output(action.new_state, self.result_chars)
if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES:
summary = deterministic_summary(
skill.category, skill.name, True, action.action_log, observed
skill.category, skill.name, True, action_log, observed
)
return RunResult(
skill=skill.name,
success=True,
summary=summary,
action_log=action.action_log,
action_log=action_log,
new_state=observed,
assessment_summary=summary,
outcome="done",
)
success, updated_request = self._assess(skill, request, ctx, action)
verdict = self._assess(skill, request, ctx, action)
success = verdict != "failed"
decisions = getattr(action, "decisions", [])
for decision, result in decisions:
@@ -379,15 +430,15 @@ class SkillRunner:
)
summary = deterministic_summary(
skill.category, skill.name, success, action.action_log, observed
skill.category, skill.name, success, action_log, observed
)
return RunResult(
skill=skill.name,
success=success,
summary=summary,
action_log=action.action_log,
action_log=action_log,
new_state=observed,
updated_request=updated_request,
outcome=verdict,
decisions_logged=len(decisions),
assessment_summary=summary,
)
+327 -121
View File
@@ -17,14 +17,16 @@ import json
import os
import re
import shutil
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
from .decisions import DecisionRequest, Option, Request
from .engine import SemIfEngine
from .engine import DecisionEngine
from .llm import LLMClient
from .log import DecisionLog
from .speech import SpeechService
from .timers import TimerService
from .trace import TraceLog
@@ -41,13 +43,45 @@ class ActionResult:
@dataclass
class ActionContext:
engine: SemIfEngine
engine: DecisionEngine
config: dict
timers: TimerService | None = None
#: The scheduler's speech channel. A body that resolves a long text to be
#: read aloud (a book) registers it here and returns immediately; the voice
#: front end streams it and the user stops it. None for a body running
#: without a scheduler (a test) — callers must tolerate None.
speech: SpeechService | None = None
# The scheduler, exposed to built-in meta skills (housekeeping) so they can
# act on the agent's own tree/registry/store. None for ordinary bodies, which
# must never reach into the agent.
# must never reach into the agent (the read-only `catalog` is their view).
admin: object | None = None
# A read-only view of the agent's own skill catalog (categories -> skills),
# for an introspection skill that reports what the agent can do. Unlike
# `admin` it exposes no mutation, so an ordinary body may read it.
catalog: "SkillCatalog | None" = None
@dataclass
class SkillCatalog:
"""Read-only introspection of the agent's own skill tree.
An ordinary skill body must never reach into the agent (`ctx.admin` is for
the built-in housekeeping meta skills), but a skill that reports the agent's
own capabilities legitimately needs to see the tree. This is that surface:
reads only — the category list and the skills inside one category — with no
way to mutate. `provider` returns the live tree (the scheduler supplies a
locked snapshot), so a skill authored after startup is still listed.
"""
provider: Callable[[], dict[str, list[Skill]]]
def categories(self) -> dict[str, str]:
"""Category id -> scope description, for every category in the tree."""
return category_descriptions(self.provider())
def skills(self, category: str) -> list[str]:
"""The leaf names inside one category (empty when it is unknown)."""
return sorted(skill.name for skill in self.provider().get(category, []))
def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
@@ -67,9 +101,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 shipped 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"
@@ -120,17 +154,19 @@ class CategoryDraft:
class SkillDraft:
"""An authored skill leaf stub: one specific action within a category.
`requirements` maps elicitation questions (asked of the human during
authoring) to their answers; they are fed to the body-writer so the body
reflects the refined product goal. `integration` carries the service and
transport the answers point at; it is fed to the body writer as an advisory
hint only — the CODEGEN.md contract, request, and requirements still win.
`goal` is the **de-identified** statement of the reusable action, authored
by the trusted local `llm` from the request and stripped of every
user-specific value (names, addresses, dates, accounts, credentials, quoted
content). It is the only task data the codegen endpoint is ever shown —
codegen never receives the request text or any user detail. `integration`
carries the generic service and transport (e.g. `nextcloud`/`caldav`), never
an account.
"""
name: str
description: str
goal: str = ""
code: str = ""
requirements: dict[str, str] = field(default_factory=dict)
integration: dict = field(default_factory=dict)
@@ -161,14 +197,13 @@ class CategoryRegistry:
category: str,
name: str,
description: str,
request_text: str = "",
requirements: dict[str, str] | None = None,
goal: str = "",
) -> None:
"""Add a skill leaf to a category, creating the category entry if needed.
`request_text` is the originating request, kept so a later restart of the
stub can re-drive codegen with the same context. `requirements` are the
elicitation answers, kept so a restart does not have to ask again.
`goal` is the de-identified, reusable action statement authored by the
local `llm`. Neither the originating request nor any user detail is
persisted here (see the codegen privacy invariant).
"""
categories = self.read()
entry = categories.setdefault(category, {"description": "", "skills": []})
@@ -177,9 +212,7 @@ class CategoryRegistry:
if entry_row is None:
entry_row = {"name": name, "description": description}
skills.append(entry_row)
entry_row["request_text"] = request_text
if requirements:
entry_row["requirements"] = requirements
entry_row["goal"] = goal
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(categories, indent=2) + "\n")
@@ -310,10 +343,11 @@ 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.
Pack skills (cloned from their own repos into `packs/`) reload 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 +530,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 +540,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 +572,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):
@@ -575,18 +614,91 @@ def unresolved_variables(
return [name for name in (skill.contract or {}) if name not in merged]
def bound_output(text: str, limit: int) -> str:
"""Truncate a skill's output to the speakable budget.
A skill result is read in a text message or heard as speech, so a long
result is a bad result: the budget is the one shared bound (the same one the
voice front end and the humanizer use). Truncation is at a word boundary and
marked with an ellipsis; a non-positive limit disables it. A long *product*
of a skill belongs in a file I/O side effect, not in the result string (see
CODEGEN.md / TESTGEN.md).
"""
if limit <= 0 or len(text) <= limit:
return text
clipped = text[:limit].rsplit(" ", 1)[0] or text[:limit]
return clipped + "…"
def render_ledger(entries: list[dict]) -> str:
"""Render the run ledger as a compact, deterministic block.
One line per step: ``N. <category.skill> -> <outcome>``. Same entries, same
string. Threaded into the routing/assessment state so a continuation sees
what was already done toward the request.
"""
lines = []
for index, entry in enumerate(entries, 1):
skill = entry.get("skill") or "?"
outcome = (entry.get("outcome") or "").strip()
lines.append(f" {index}. {skill} -> {outcome}" if outcome else f" {index}. {skill}")
return "\n".join(lines)
def last_result(request: Request) -> str:
"""The most recent result this run can build on.
A body that runs as a later step of a chain reads this to use what the
previous step produced (e.g. a computed value to send) instead of
recomputing or fabricating it. The value is the prior step's bounded outcome
(its ``action_log`` or ``new_state``) — the same text the run ledger carries
and renders into the routing/assessment state.
When the current chain has no steps yet, it falls back to the recalled
previous request's last outcome (a follow-up within ``query_recall_window``),
so "send it to Sam" can reuse the answer the agent just gave.
"""
ledger = getattr(request, "run_ledger", None) or []
if not ledger:
ledger = getattr(request, "prior_ledger", None) or []
return str(ledger[-1].get("outcome") or "") if ledger else ""
return str(ledger[-1].get("outcome") or "")
def render_recall(request: Request) -> str:
"""Render the recalled previous request's ledger as a compact context block.
Distinct from `render_ledger`/`run_ledger`: recall is background context for
resolving a reference in the current request, not a step of the current
chain. Returns "" when there is nothing to recall.
"""
entries = getattr(request, "prior_ledger", None) or []
if not entries:
return ""
prior_at = getattr(request, "prior_at", 0.0) or 0.0
age = f" ({int(max(0.0, time.time() - prior_at))}s ago)" if prior_at else ""
return f"previous request{age}:\n{render_ledger(entries)}"
def compose_state(request: Request, additional_context: str | None = None) -> str:
parts = [request.text]
if additional_context:
parts.append(f"({additional_context})")
return " ".join(parts)
state = " ".join(parts)
recall = render_recall(request)
if recall:
state = f"{state}\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state = f"{state}\nsteps already taken:\n{ledger}"
return state
def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config."""
def act(ctx: ActionContext, request: Request) -> ActionResult:
return ActionResult(action_log=f"{name}: {message}", new_state=message)
return ActionResult(action_log=message, new_state=message)
return act
@@ -645,29 +757,25 @@ _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.
#: The deterministic reply when new-skill creation is denied and no existing
#: skill can serve the request. Unlike the `response` tree this is never
#: navigable: it is reached only from the scheduler's deny gate. The user is
#: deliberately never told that authoring (or config) exists — the request
#: simply cannot be served.
UNABLE_MESSAGE = "I'm sorry, I'm not able to help with that."
# 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."
),
"calendar": (
"Calendar and scheduling: reading or changing the user's calendar "
"events and reminders."
),
"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."
),
"housekeeping": (
"Agent self-maintenance: deleting, reconfiguring, regenerating, and "
"cancelling the agent's own skills."
@@ -679,10 +787,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
@@ -720,7 +828,7 @@ _TARGET_QUESTION = (
# Explicit housekeeping command forms. They are routed deterministically to the
# housekeeping skill (see parse_meta_command) because the generic SemIf guards
# read a task-like skill name in the request as the task itself (e.g.
# "regen skill calendar.create_event" scores as a calendar task). The skill name
# "regen skill nextcloud.create_event" scores as a nextcloud task). The skill name
# is just a variable the skill resolves — or asks for.
_META_PATTERNS: list[tuple[str, "re.Pattern[str]"]] = [
(
@@ -781,10 +889,10 @@ def parse_meta_command(text: str) -> str | None:
def _resolve_target(admin, request: Request):
"""Resolve the skill a housekeeping request targets.
The target may be named in the request ("delete skill calendar.foo") or
The target may be named in the request ("delete skill nextcloud.foo") or
supplied as an input variable when the request is name-free ("delete
skill") — in which case the skill asks for it. Keeping the name out of the
routed request is deliberate: a skill name like `calendar.create_event`
routed request is deliberate: a skill name like `nextcloud.create_event`
reads as a task and pulls navigation to the wrong category. Returns a
`(category, name)` tuple, or an `ActionResult` (needs_input / not-found /
ambiguous) to return as-is.
@@ -799,7 +907,7 @@ def _resolve_target(admin, request: Request):
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -807,7 +915,7 @@ def _resolve_target(admin, request: Request):
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping: awaiting skill name",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input=_TARGET_QUESTION,
)
@@ -819,11 +927,11 @@ def _resolve_target(admin, request: Request):
if isinstance(ref, list):
names = ", ".join(f"{c}.{n}" for c, n in ref)
return ActionResult(
action_log=f"housekeeping: several skills match ({names}); be specific",
action_log=f"several skills match ({names}); be specific",
new_state="ambiguous",
)
return ActionResult(
action_log=f"housekeeping: no skill matches {answer!r}",
action_log=f"no skill matches {answer!r}",
new_state="not found",
)
@@ -831,7 +939,7 @@ def _resolve_target(admin, request: Request):
def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.delete_skill: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -840,35 +948,35 @@ def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.delete_skill: awaiting confirmation for {ref}",
action_log=f"awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=f"Delete {ref} and all its files? Reply yes to confirm.",
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.delete_skill: cancelled by user for {ref}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.delete_skill(category, name)
return ActionResult(f"housekeeping.delete_skill: {detail}", detail)
return ActionResult(detail, detail)
def _clear_config_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.clear_config: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
category, name = target
_status, detail = admin.clear_skill_config(category, name)
return ActionResult(f"housekeeping.clear_config: {detail}", detail)
return ActionResult(detail, detail)
def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.regen_skill: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -877,19 +985,19 @@ def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_regen") != ref:
request.meta["housekeeping_regen"] = ref
return ActionResult(
action_log=f"housekeeping.regen_skill: awaiting guidance for {ref}",
action_log=f"awaiting guidance for {ref}",
new_state="awaiting guidance",
needs_input="What needs to be fixed?",
)
guidance = (request.user_input or "").strip()
_status, detail = admin.regen_skill(category, name, guidance)
return ActionResult(f"housekeeping.regen_skill: {detail}", detail)
return ActionResult(detail, detail)
def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.cancel_build: no admin available", "error")
return ActionResult("no admin available", "error")
writing = [
(category, skill.name)
for category, skills in admin.tree.items()
@@ -905,7 +1013,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping.cancel_build: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -915,7 +1023,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = resolved
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build is in progress for "
f"no build is in progress for "
f"{category}.{name}"
),
new_state="no build",
@@ -925,14 +1033,14 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = writing[0]
elif not writing:
return ActionResult(
action_log="housekeeping.cancel_build: no skill build is in progress",
action_log="no skill build is in progress",
new_state="no build",
)
else:
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping.cancel_build: awaiting skill name",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input="Which skill build should I cancel? Reply with its name.",
)
@@ -943,7 +1051,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
else:
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build in progress matching "
f"no build in progress matching "
f"{answer!r}"
),
new_state="no build",
@@ -953,7 +1061,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.cancel_build: awaiting confirmation for {ref}",
action_log=f"awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=(
f"Cancel the build for {ref} and delete its half-built leaf? "
@@ -962,11 +1070,11 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.cancel_build: cancelled by user for {ref}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.cancel_skill_build(category, name)
return ActionResult(f"housekeeping.cancel_build: {detail}", detail)
return ActionResult(detail, detail)
def build_housekeeping_skills() -> list[Skill]:
@@ -1117,7 +1225,7 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) ->
def _navigate_canned(
engine: SemIfEngine,
engine: DecisionEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
@@ -1160,16 +1268,35 @@ def _navigate_canned(
def navigate(
engine: SemIfEngine,
engine: DecisionEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
tree: dict[str, list[Skill]],
category_tau: float = 0.75,
action_tau: float = 0.5,
bypass_tau: float = 0.5,
skip_actionability: bool = False,
) -> Skill | CreateCategory | CreateSkill:
"""Descend the tree one SemIf choice per level. Every choice is logged.
**A confident category winner skips the scope confirm; the leaf intent
guard always runs.** When the category softmax winner's probability is >=
`bypass_tau` (default 0.5) the scope confirm (`confirm_category_fit`) is
skipped — the winner is taken as-is (traced `category_scope_bypassed`). That
is sound because `create_category` is one of the category softmax options, so
a confident winner genuinely beat "author a new category"; below the threshold
the guard runs and can reject the winner into create. The leaf softmax has
**no** create option (`create_skill` is deliberately absent), so its
probabilities are renormalized over only the existing skills and a confident
winner means "best of the wrong lot", not a match. The leaf intent guard
(`confirm_skill_fit`) is therefore **never** bypassed: it is the sole
leaf-level create door, and skipping it would make codegen unreachable for an
unmatched request. (Regression: with Winnow as the engine, "send a message to
pepper on SimpleX" picked `connect_link` at 0.86 / `next_message` at 0.995,
skipped the guard, and ran a read skill instead of authoring
`simplex.send_message`.)
The **actionability guard** (`confirm_non_action`, phase
`navigate:actionability`, keyed by `navigation.action_tau`) runs at the **top**
of navigation, before any category is considered: the closed `response` tree
@@ -1202,7 +1329,7 @@ def navigate(
"create_category",
request.id,
state=compose_state(request),
question="Which top-level category handles this request?",
question="Which category is the logical next step toward satisfying this request?",
options=[],
selected="create_category",
probs={},
@@ -1212,8 +1339,10 @@ def navigate(
# Actionability first: is this input a request at all? A non-request goes to
# the closed `response` tree (a canned reply) and never reaches the category
# softmax; a request always proceeds to category selection, so it can never
# be canned.
if confirm_non_action(engine, log, trace, request, action_tau):
# be canned. A **continuation** (a request already carrying a run ledger) is
# actionable by construction — it is the next step of an in-flight request —
# so it skips this guard; only a fresh first-step input is checked.
if not skip_actionability and confirm_non_action(engine, log, trace, request, action_tau):
response_skills = tree.get("response")
if response_skills:
return _navigate_canned(
@@ -1223,7 +1352,7 @@ def navigate(
"create_category",
request.id,
state=compose_state(request),
question="Which top-level category handles this request?",
question="Which category is the logical next step toward satisfying this request?",
options=[],
selected="create_category",
probs={},
@@ -1239,7 +1368,7 @@ def navigate(
)
top = DecisionRequest(
state=compose_state(request),
question="Which top-level category handles this request?",
question="Which category is the logical next step toward satisfying this request?",
options=[Option(c, descriptions.get(c, c)) for c in categories]
+ [create_category],
)
@@ -1258,7 +1387,16 @@ def navigate(
log.append(top, top_result, extra={"phase": "navigate:category", "run_id": request.id})
category = top_result.selected
if category != "create_category":
if not confirm_category_fit(
winner_prob = float(top_result.probs.get(category, 0.0))
if winner_prob >= bypass_tau:
# Confident winner: skip the scope confirm (one fewer SemIf call).
trace.append(
"category_scope_bypassed",
request.id,
category=category,
prob=winner_prob,
)
elif not confirm_category_fit(
engine, log, trace, request, category, descriptions.get(category, ""),
category_tau,
):
@@ -1305,7 +1443,7 @@ def navigate(
request,
additional_context=f"all choices are within the {category} category",
),
question=f"Which {category} skill performs the action this request asks for?",
question=f"Which {category} skill should run next to help satisfy this request?",
options=[Option(s.name, s.description) for s in skills],
)
leaf_result = engine.call(leaf)
@@ -1315,7 +1453,7 @@ def navigate(
def confirm_category_fit(
engine: SemIfEngine,
engine: DecisionEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
@@ -1380,7 +1518,7 @@ def confirm_category_fit(
def confirm_non_action(
engine: SemIfEngine,
engine: DecisionEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
@@ -1443,42 +1581,76 @@ def confirm_non_action(
def confirm_skill_fit(
engine: SemIfEngine,
engine: DecisionEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
skill: Skill,
tau: float = 0.6,
) -> bool:
"""Does this skill's action actually match what the request asks for?
) -> str:
"""What does this skill do for the request? "same" | "part" | "different".
Navigation picks the closest existing leaf; this guard is now the **sole**
Navigation picks the closest existing leaf; this guard is the **sole**
leaf-level reuse-vs-create decision (create_skill is no longer an option in
the leaf softmax). If the skill's action is not the same action the request
asks for, dispatch authors a new leaf instead. The threshold is
`navigation.intent_tau` (deliberately separate from the run-assessment
`tau`, so tuning reuse-vs-create does not move assessment/fidelity).
the leaf softmax). It answers three ways:
Wording tuned against the real model: comparing the two *actions*
("different action") is unambiguous where "can this serve the request" was
not — e.g. "message Sam" (an implicit send in instant-messaging syntax)
reads as a different action from "read the next message". Do not add an
instant-messaging context hint: it over-fires and pulls read phrasings to
the send side. The comparison is over-permissive on near-synonyms (read vs
send score "same" ~0.74-0.78), so it is paired with the softmax that
disambiguates them — the guard only ever sees the softmax winner.
- ``same`` — the skill performs the next action the request needs (running it
can satisfy the request, or is its final step);
- ``part`` — the request needs more than one action and this skill performs
one required part of it;
- ``different`` — the skill does not do any action the request asks for;
dispatch authors a new leaf instead.
``same``/``part`` run the skill; ``different`` is the create door. The guard
only decides whether the skill *contributes* — whether more work remains is
``assess:outcome``'s call (the guard must never force a continuation: in a
real run it labeled the final send step ``part`` 0.85 while the assessment
correctly said ``done`` 0.99, and a forced continue drove the chain into a
spurious new category). The **run ledger is part of the state** so a later
step judges against the *remaining* work, not the whole request. Without the
ledger a compound request has no single skill that is ``same``, so the guard
would author a monolithic skill for every one of them — the bug this fixes (a
real run picked ``calculator.calculate`` at 0.99 and was rejected into
create_skill).
The threshold is ``navigation.intent_tau`` (deliberately separate from the
run-assessment ``tau``, so tuning reuse-vs-create does not move
assessment/fidelity). Wording tuned against the real model: comparing the
two *actions* is unambiguous where "can this serve the request" was not.
Do not add an instant-messaging context hint: it over-fires and pulls read
phrasings to the send side.
"""
state = (
f"Requested action: {request.text}\n"
f"Action of the existing skill: {skill.description}"
)
recall = render_recall(request)
if recall:
state += f"\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"
decision = DecisionRequest(
state=(
f"Requested action: {request.text}\n"
f"Action of the existing skill: {skill.description}"
state=state,
question=(
"Given the steps already taken, what does this skill do for the "
"request?"
),
question="Compare the requested action and the skill's action. Are they the same action?",
options=[
Option("same", "Same action."),
Option(
"same",
"It performs the next action the request needs and can satisfy "
"the request (or is its final step).",
),
Option(
"part",
"The request needs more than one action; this skill performs one "
"required part of it, and more steps remain after it.",
),
Option(
"different",
"Different action: the skill does not do what the user asks.",
"It does not do any action the request asks for; a new skill is "
"needed.",
),
],
)
@@ -1492,7 +1664,15 @@ def confirm_skill_fit(
"skill": f"{skill.category}.{skill.name}",
},
)
fits = result.prob("same") >= tau
same = result.prob("same")
part = result.prob("part")
fits = (same + part) >= tau
if not fits:
verdict = "different"
elif same >= part:
verdict = "same"
else:
verdict = "part"
trace.append(
"intent_guard",
request.id,
@@ -1500,9 +1680,10 @@ def confirm_skill_fit(
skill=skill.name,
selected=result.selected,
probs=result.probs,
verdict=verdict,
fits=fits,
)
return fits
return verdict
def tree_summary(tree: dict[str, list[Skill]]) -> str:
@@ -1564,19 +1745,31 @@ def generate_category(
def build_skill_prompt(
request: Request, category: str, tree: dict[str, list[Skill]]
) -> list[dict]:
"""Chat messages for the decision model used as the skill author.
"""Chat messages for the spec-authoring step (trusted local `llm`).
The skill must be one specific, single-purpose action that fits inside the
given category — not a broad bucket. Existing skills in the category are
included so the model avoids duplicating them.
given category. Alongside the title + description the model must author a
**de-identified** reusable goal: the codegen endpoint never sees the original
request, so every user-specific value (names, addresses, dates, accounts,
credentials, quoted content) must be stripped and left for the script to
derive from the request at runtime.
"""
system = (
"You are the skill-tree authoring step of a local agent. A request inside "
f"the '{category}' category did not fit any existing skill. Propose ONE "
"new skill for this category: a specific, single-purpose action the agent "
"can take. Reply with JSON only: "
"can take. Also write a DE-IDENTIFIED reusable goal for that action: the "
"code writer will never see the original request, so you MUST remove every "
"user-specific value — names, addresses, emails, phone numbers, dates, "
"times, numbers, account names, hostnames, credentials, and quoted content "
"— and describe only the generic action plus which values it must derive "
"from the request at runtime. Reply with JSON only: "
'{"title": "<short lowercase snake_case id, no spaces, generic and reusable>", '
'"description": "<one to two sentence description of how it benefits user>"}'
'"description": "<one to two sentence description of how it benefits the '
'user, no user-specific values>", '
'"goal": "<de-identified reusable action, no user-specific values>", '
'"service": "<generic service family in lowercase snake_case, or unknown>", '
'"transport": "<http|caldav|imap|smtp|pop|subprocess|file|compute>"}'
)
existing = ", ".join(s.name for s in tree.get(category, [])) or "(none)"
user = (
@@ -1592,7 +1785,8 @@ def build_skill_prompt(
def parse_skill_draft(raw: str) -> SkillDraft:
"""Parse the model's JSON reply into a SkillDraft."""
"""Parse the model's JSON reply into a SkillDraft (title, description, goal,
integration)."""
parsed = LLMClient._parse_json(raw)
title = str(parsed.get("title", "")).strip()
description = str(parsed.get("description", "")).strip()
@@ -1601,12 +1795,24 @@ def parse_skill_draft(raw: str) -> SkillDraft:
name = re.sub(r"\s+", "_", title.lower())
if not re.fullmatch(r"[a-z0-9_]+(?:\.[a-z0-9_]+)*", name):
raise ValueError(f"skill title must be snake_case alnum (dots allowed): {title!r}")
return SkillDraft(name=name, description=description)
goal = str(parsed.get("goal", "")).strip() or description
integration: dict = {}
service = str(parsed.get("service", "")).strip().lower()
transport = str(parsed.get("transport", "")).strip().lower()
# Validate the advisory hint against the generic transport set; a bad or
# absent hint is dropped, never fatal.
from .codegen import INTEGRATION_TRANSPORTS
if re.fullmatch(r"[a-z0-9_]+", service) and transport in INTEGRATION_TRANSPORTS:
integration = {"service": service, "transport": transport}
return SkillDraft(
name=name, description=description, goal=goal, integration=integration
)
def generate_skill(
def generate_skill_spec(
client: LLMClient, request: Request, category: str, tree: dict[str, list[Skill]]
) -> SkillDraft:
"""Author a new skill leaf stub with the `llm` provider."""
raw = client.chat(build_skill_prompt(request, category, tree), max_tokens=128)
"""Author a de-identified skill spec (stub) with the local `llm` provider."""
raw = client.chat(build_skill_prompt(request, category, tree), max_tokens=256)
return parse_skill_draft(raw)
+164
View File
@@ -0,0 +1,164 @@
"""The scheduler's speech channel: a long-form read-aloud request for a front end.
A skill body cannot speak: it runs inside the scheduler, which is transport-
agnostic and must never reach into a front end. So a body that resolves a long
text to be *read aloud* registers a `ReadAloud` here (through `ctx.speech`) and
returns immediately. The gateway that owns the originating chat drains the
request (`drain()`) and hands it to the platform adapter, which streams it with
text-to-speech until the user stops it. Position is tracked in a
``bookmarks.json`` beside the text (see `semif_agent.reading`).
This mirrors `semif_agent.timers`: the scheduler exposes a small thread-safe
service; a front end drains what it can deliver. It is neutral — stdlib only,
and it knows nothing about audio or any specific gateway.
"""
from __future__ import annotations
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
from .reading import DEFAULT_CHUNK_CHARS
@dataclass
class ReadAloud:
"""One queued request to read a saved text aloud from a position.
`path` is the text file; `bookmarks_path` the ``bookmarks.json`` beside it;
`key` the book's bookmark key; `start` the character offset to resume from.
`source` is the originating front-end source (`"voice:<chat_id>"`) and
`run_id` the run that asked, so the gateway can route it to the right chat.
"""
path: str
key: str
bookmarks_path: str
run_id: str = ""
source: str = ""
title: str = ""
start: int = 0
chunk_chars: int = DEFAULT_CHUNK_CHARS
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
created_at: float = field(default_factory=time.time)
class SpeechService:
"""Holds read-aloud requests until a front end drains them.
Bounded like the request queue: a front end that never drains (the REPL)
cannot grow it without limit.
"""
def __init__(self, trace=None, max_pending: int = 64):
self.trace = trace
self._lock = threading.Lock()
self._pending: deque[ReadAloud] = deque(maxlen=max(1, int(max_pending)))
#: Optional predicate set by a front end: whether a given source can be
#: streamed to (the voice gateway; an LXMF voice chat). None means no
#: front end is attached (the REPL, a test), so nothing supports it.
self._stream_check = None
def set_stream_check(self, check) -> None:
"""Register the front end's per-source streaming capability predicate.
Called by the gateway service with a callable `(source) -> bool` so a
skill can ask `supports(source)` before it posts a read-aloud. A front
end that cannot stream (or has none attached) leaves it None.
"""
self._stream_check = check if callable(check) else None
def supports(self, source: str) -> bool:
"""Whether the front end can stream a read-aloud to `source`.
False when no front end is attached, when the source's platform cannot
stream, or when the check raises — the caller then keeps its normal
(non-read-aloud) behaviour.
"""
check = self._stream_check
if check is None:
return False
try:
return bool(check(str(source or "")))
except Exception:
return False
def read_aloud(
self,
*,
path: str,
key: str,
bookmarks_path: str,
run_id: str = "",
source: str = "",
title: str = "",
start: int = 0,
chunk_chars: int = DEFAULT_CHUNK_CHARS,
) -> ReadAloud:
"""Queue a text to be read aloud. Returns the queued request."""
read = ReadAloud(
path=str(path),
key=str(key),
bookmarks_path=str(bookmarks_path),
run_id=str(run_id or ""),
source=str(source or ""),
title=str(title or ""),
start=max(0, int(start or 0)),
chunk_chars=max(1, int(chunk_chars or DEFAULT_CHUNK_CHARS)),
)
with self._lock:
self._pending.append(read)
self._event(
"read_aloud_queued",
read.run_id,
read_id=read.id,
key=read.key,
source=read.source,
start=read.start,
)
return read
def drain(self) -> list[ReadAloud]:
"""Pop and return the queued requests, oldest first (for a front end)."""
with self._lock:
reads = list(self._pending)
self._pending.clear()
return reads
def pending_for(self, run_id: str) -> bool:
"""Whether a read-aloud is queued for a run (not yet drained).
Lets the scheduler treat a run that handed off to a long-form read as
complete: the read is the answer, so `assess:outcome` has no further
work to find and must not re-dispatch the request.
"""
with self._lock:
return any(r.run_id == str(run_id) for r in self._pending)
def pending(self) -> list[dict]:
"""A snapshot of the queue (for the dashboard)."""
with self._lock:
return [
{
"id": r.id,
"run_id": r.run_id,
"source": r.source,
"key": r.key,
"title": r.title,
"start": r.start,
"path": r.path,
"created_at": r.created_at,
}
for r in self._pending
]
def _event(self, kind: str, run_id: str, **fields) -> None:
if self.trace is None:
return
try:
self.trace.append(kind, run_id, **fields)
except Exception:
pass
+33 -35
View File
@@ -65,7 +65,7 @@ function shortPhase(phase) {
return phase.replace("navigate:", "nav:");
}
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "act"];
const ALL_PHASES = ["navigate:category", "navigate:leaf", "act"];
function optionProbs(row) {
return (row.options || []).map((o) => ({
@@ -130,9 +130,7 @@ function eventRow(evt) {
div.textContent = `assessed → ${evt.success ? "ok" : "fail"}`;
div.title = evt.summary || "";
} else if (evt.kind === "queued") {
div.textContent = `queued (${evt.label})`;
} else if (evt.kind === "preempted") {
div.textContent = `preempted ${evt.preempted}`;
div.textContent = "queued";
} else if (evt.kind === "skill_writing") {
div.textContent = `writing skill ${evt.skill} — ${evt.description} (${evt.model || "codegen"})`;
if (evt.contract_ref) {
@@ -148,8 +146,6 @@ function eventRow(evt) {
div.textContent = `ready: ${evt.skill}`;
} else if (evt.kind === "codegen_regen") {
div.textContent = `regen → ${evt.selected}`;
} else if (evt.kind === "requirements") {
div.textContent = "refinement questions asked";
} else if (evt.kind === "skill_write_failed") {
div.textContent = `body write failed: ${evt.skill}`;
div.title = evt.message || "";
@@ -165,8 +161,10 @@ function eventRow(evt) {
div.textContent = `cleared config: ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_create_blocked") {
div.textContent = `new-skill creation blocked: ${evt.category}`;
} else if (evt.kind === "category_lock_set") {
div.textContent = `${evt.category} new-skill lock ${evt.new_skill ? "on" : "off"}`;
} else if (evt.kind === "category_create_blocked") {
div.textContent = "new-category creation blocked";
} else if (evt.kind === "category_mode_set") {
div.textContent = `${evt.category} new-skill creation: ${evt.mode}`;
} else if (evt.kind === "needs_input") {
div.textContent = "needs input";
div.title = evt.question || "";
@@ -413,16 +411,16 @@ function eventNode(evt) {
body.className = "node-question";
if (evt.kind === "assessed") {
body.textContent = evt.summary || "";
if (evt.updated_request) {
const req = document.createElement("div");
req.className = "muted";
req.textContent = `→ requeued: ${evt.updated_request}`;
node.appendChild(req);
}
} else if (evt.kind === "continued") {
body.textContent = `→ next step: ${evt.skill || ""}`;
const outcome = document.createElement("div");
outcome.className = "muted";
outcome.textContent = `outcome: ${evt.outcome || ""}`;
node.appendChild(outcome);
} else if (evt.kind === "chain_halted") {
body.textContent = `chain halted (${evt.reason || ""})`;
} else if (evt.kind === "queued") {
body.textContent = `urgency ${evt.label} (weight ${Number(evt.weight || 0).toFixed(2)})`;
} else if (evt.kind === "preempted") {
body.textContent = `interrupted ${evt.preempted}, requeued with state`;
body.textContent = "queued";
} else if (evt.kind === "dropped") {
body.textContent = evt.reason || "";
} else if (evt.kind === "skill_writing") {
@@ -490,8 +488,6 @@ function eventNode(evt) {
out.textContent = evt.reason.slice(0, 160);
body.appendChild(out);
}
} else if (evt.kind === "requirements") {
body.textContent = `refinement: ${(evt.questions || []).join(" | ")}`;
} else if (evt.kind === "skill_write_failed") {
node.classList.add("stub");
const title = document.createElement("div");
@@ -521,8 +517,10 @@ function eventNode(evt) {
body.textContent = `cleared config for ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_create_blocked") {
body.textContent = `new-skill creation blocked in ${evt.category}`;
} else if (evt.kind === "category_lock_set") {
body.textContent = `${evt.category} new-skill lock ${evt.new_skill ? "on" : "off"}`;
} else if (evt.kind === "category_create_blocked") {
body.textContent = "new-category creation blocked";
} else if (evt.kind === "category_mode_set") {
body.textContent = `${evt.category} new-skill creation: ${evt.mode}`;
} else if (evt.kind === "needs_input") {
node.classList.add("needs-input");
body.textContent = `awaiting input: ${evt.question || ""}`;
@@ -610,16 +608,16 @@ async function housekeepingAction(path, category, name) {
await refreshAll();
}
async function toggleLock(category, locked) {
async function setSkillMode(category, mode) {
try {
const res = await getJSON("/api/lock", {
const res = await getJSON("/api/new-skill-mode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, locked }),
body: JSON.stringify({ category, mode }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`lock failed: ${err.message}`);
flash(`mode change failed: ${err.message}`);
}
await refreshAll();
}
@@ -703,15 +701,15 @@ function renderTree() {
const name = document.createElement("div");
name.className = "cat-name";
name.textContent = cat;
const locked = (state.tree.locks || {})[cat];
if (locked !== undefined) {
const lock = actionBtn(
locked ? "locked" : "open",
locked
? "new-skill creation is locked; click to allow"
: "new-skill creation is allowed; click to lock",
() => toggleLock(cat, !locked)
);
const mode = (state.tree.new_skill_modes || {})[cat];
if (mode !== undefined) {
const next = { allow: "ask", ask: "deny", deny: "allow" }[mode] || "allow";
const hint = {
allow: "new skills are created without asking; click to ask first",
ask: "new skills ask for approval; click to deny creation",
deny: "new-skill creation is denied; click to allow",
}[mode];
const lock = actionBtn(mode, hint, () => setSkillMode(cat, next));
lock.classList.add("lock-btn");
name.appendChild(lock);
}
@@ -825,7 +823,7 @@ function renderStatus() {
q.className = "muted";
q.style.marginTop = "8px";
q.textContent = state.status.queue
.map((item) => `${item.id} w=${item.weight.toFixed(2)} ${item.text}`)
.map((item) => `${item.id} ${item.text}`)
.join("\n") || "queue empty";
el.appendChild(q);
-2
View File
@@ -183,8 +183,6 @@ select {
}
.pill.gate { background: #2b3a52; color: #9ec1ff; }
.pill.choice { background: #4a3a2b; color: #ffd59e; }
.pill.score { background: #3a2b4a; color: #d59eff; }
.pill.navigate { background: #2b4a3a; color: #9effd5; }
.pill.act { background: #2b464a; color: #9eeaff; }
.pill.assess { background: #4a2b2b; color: #ff9e9e; }
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more