Compare commits
51
Commits
228886f7cd
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
addbe53392 | ||
|
|
894a85ec2d | ||
|
|
faebe8a53a | ||
|
|
a8ca65a6e4 | ||
|
|
a6b8617562 | ||
|
|
ec3e6b1b97 | ||
|
|
ed894bd329 | ||
|
|
b1a7bfd272 | ||
|
|
bf071ee529 | ||
|
|
c57983f1f5 | ||
|
|
2296801b22 | ||
|
|
d67ea26f3d | ||
|
|
41c18e6c47 | ||
|
|
16e8583921 | ||
|
|
1329de42c4 | ||
|
|
883c51de97 | ||
|
|
0b02a3feac | ||
|
|
f379c0a746 | ||
|
|
711dba2f03 | ||
|
|
78b4621ba0 | ||
|
|
b953475bf7 | ||
|
|
b15a9e1b45 | ||
|
|
3a5b90b1cb | ||
|
|
e4961ef492 | ||
|
|
6240392632 | ||
|
|
c010cdb44e | ||
|
|
9757ae893e | ||
|
|
1833932f1c | ||
|
|
def51f81dc | ||
|
|
ab0defca1e | ||
|
|
9ba14fdab0 | ||
|
|
c5ee87875f | ||
|
|
88700898be | ||
|
|
ff94ea938c | ||
|
|
a388c292bc | ||
|
|
e2cbf74797 | ||
|
|
fc0beb5798 | ||
|
|
4e3e3f767c | ||
|
|
f05e06e6f6 | ||
|
|
f6ef66b532 | ||
|
|
e86ed805ee | ||
|
|
dcfe5e5fec | ||
|
|
ec39a990e4 | ||
|
|
ae37abbc3f | ||
|
|
f1ea9f0c2c | ||
|
|
b8f86849ea | ||
|
|
e434b9fbe5 | ||
|
|
b7d405454a | ||
|
|
aa25693091 | ||
|
|
912417792f | ||
|
|
0005d8f7ee |
No files matched your search
@@ -12,6 +12,8 @@ data/skills/
|
||||
data/drafts/
|
||||
.pytest_cache/
|
||||
config.json
|
||||
config/
|
||||
secrets.json
|
||||
*.log
|
||||
# Machine-specific material: deployment notes (hostnames, addresses, SSH,
|
||||
# model choices), GPU offload probe, benchmark harness. Deliberately not part
|
||||
@@ -19,3 +21,6 @@ config.json
|
||||
local/
|
||||
*.egg-info/
|
||||
*.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/
|
||||
@@ -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.
|
||||
+122
-36
@@ -6,10 +6,19 @@ 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 native python modules, 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 decision 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:
|
||||
|
||||
@@ -21,7 +30,8 @@ A skill is three things:
|
||||
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.
|
||||
@@ -137,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
|
||||
|
||||
@@ -162,12 +173,12 @@ 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 — 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 `calendar.create_event` asks only for a title and description), and
|
||||
(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
|
||||
@@ -175,6 +186,14 @@ Rules:
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
## The registry entry
|
||||
|
||||
The body writer does **not** author a manifest. The `llm` provider authors the
|
||||
@@ -193,8 +212,7 @@ The registry is a map of category -> bucket:
|
||||
{
|
||||
"name": "<leaf_name>",
|
||||
"description": "<what this leaf does, for navigation>",
|
||||
"request_text": "<the originating request, optional>",
|
||||
"requirements": {"<question>": "<answer>"}
|
||||
"goal": "<the de-identified, reusable action statement>"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -204,8 +222,10 @@ The registry is a map of category -> bucket:
|
||||
- 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.
|
||||
- `request_text` and `requirements` are recorded by the scheduler so a stub can
|
||||
be re-driven later; the body never sets them.
|
||||
- `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
|
||||
|
||||
@@ -283,8 +303,12 @@ def act(ctx, request) -> ActionResult:
|
||||
`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.admin` exists for the built-in housekeeping meta skills only; an ordinary
|
||||
body must never touch it.
|
||||
`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
|
||||
@@ -386,7 +410,7 @@ INTEGRATION = {
|
||||
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. In
|
||||
the committed seeds this is exactly the body's `CONTRACT` key set; an empty
|
||||
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.
|
||||
|
||||
@@ -422,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)
|
||||
|
||||
@@ -451,14 +475,44 @@ Rules:
|
||||
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, and a
|
||||
**successful** run: the `assess:outcome` step treats a definitive "nothing
|
||||
found / nothing to do" result as success. 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.
|
||||
**`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
|
||||
@@ -515,29 +569,50 @@ Rules:
|
||||
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 `calendar.create_event` caches the extracted title/description and the
|
||||
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.
|
||||
- **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>",
|
||||
@@ -548,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.
|
||||
@@ -557,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
|
||||
@@ -575,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
|
||||
@@ -616,9 +697,14 @@ 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
|
||||
|
||||
+468
@@ -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/`.
|
||||
@@ -127,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.
|
||||
@@ -151,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
|
||||
@@ -168,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.
|
||||
@@ -203,9 +217,9 @@ 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
|
||||
|
||||
@@ -218,11 +232,13 @@ 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
|
||||
|
||||
@@ -232,11 +248,10 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog**
|
||||
| `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` |
|
||||
@@ -248,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
|
||||
|
||||
@@ -329,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.
|
||||
@@ -338,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.
|
||||
@@ -365,7 +386,7 @@ semif_agent/
|
||||
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);
|
||||
SemIfEngineClient generates text from the in-process engine
|
||||
@@ -384,15 +405,31 @@ semif_agent/
|
||||
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, LLM, Nextcloud)
|
||||
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)
|
||||
```
|
||||
@@ -402,30 +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):
|
||||
|
||||
- **`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. Its `provider` can be `"ollama"` (default),
|
||||
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 (see the `llm.semif` block in `config.json`).
|
||||
|
||||
The **decision engine is separate** and runs via llama.cpp, not ollama. It 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).
|
||||
`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.
|
||||
|
||||
### Option A: one-command provisioning (`bootstrap.sh`)
|
||||
|
||||
@@ -435,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)
|
||||
|
||||
@@ -480,53 +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` |
|
||||
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
|
||||
| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
|
||||
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
|
||||
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD, 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 |
|
||||
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
|
||||
| `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 |
|
||||
|
||||
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / `nextcloud_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.
|
||||
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** (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.
|
||||
`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.
|
||||
@@ -542,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
|
||||
@@ -624,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**;
|
||||
@@ -638,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.
|
||||
@@ -664,18 +788,32 @@ 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 — scheduler bookkeeping is dropped and the
|
||||
`<skill>: ok —` wrapper is stripped — so the spoken output is the answer, not
|
||||
@@ -690,11 +828,13 @@ python -m semif_agent.cli gateway --platform voice
|
||||
|
||||
`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, where
|
||||
the system needs one, 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.
|
||||
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:
|
||||
|
||||
```
|
||||
@@ -716,10 +856,11 @@ acking is a client-side read receipt, not an API call.
|
||||
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": "..."}
|
||||
@@ -735,17 +876,18 @@ carries just the local listener. Skills call it at the address derived from
|
||||
it returns `502`, never a fabricated reply. It starts in the same
|
||||
`semif-bridge.service` process as the other enabled bridges.
|
||||
|
||||
The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it
|
||||
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` and falls back to the top-level
|
||||
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` /
|
||||
`nextcloud_default_calendar` the calendar seeds use, so the account is
|
||||
configured once. Skills call it at the address derived from `bridges.nextcloud`
|
||||
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface:
|
||||
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
|
||||
@@ -757,8 +899,8 @@ 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
|
||||
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT
|
||||
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
|
||||
@@ -774,6 +916,90 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo
|
||||
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
|
||||
|
||||
```sh
|
||||
@@ -809,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).
|
||||
|
||||
---
|
||||
|
||||
@@ -856,11 +1107,11 @@ works.
|
||||
|
||||
**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).
|
||||
|
||||
|
||||
+16
-6
@@ -6,6 +6,9 @@ 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 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;
|
||||
@@ -78,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.
|
||||
|
||||
+178
-80
@@ -1,21 +1,27 @@
|
||||
{
|
||||
"_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.",
|
||||
"tau": 0.6,
|
||||
"max_reentries": 3,
|
||||
"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. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.",
|
||||
"intent_tau": 0.6,
|
||||
"category_tau": 0.75,
|
||||
"action_tau": 0.5,
|
||||
"softmax_bypass_tau": 0.5
|
||||
},
|
||||
"queue": {"max_size": 100},
|
||||
"queue": {
|
||||
"max_size": 100
|
||||
},
|
||||
"engine": {
|
||||
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
|
||||
"_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).",
|
||||
"_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.",
|
||||
"provider": "semif",
|
||||
"backend": "llamacpp",
|
||||
"context_tokens": 4096,
|
||||
@@ -24,24 +30,33 @@
|
||||
"gpu_device": null,
|
||||
"gpu_split": 0,
|
||||
"winnow": {
|
||||
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
|
||||
"base_url": "http://127.0.0.1:8091",
|
||||
"model": "",
|
||||
"api_key": "",
|
||||
"api_key_env": "",
|
||||
"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), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
|
||||
"provider": "ollama",
|
||||
"base_url": "http://localhost:11434/v1",
|
||||
"model": "",
|
||||
"api_key": "",
|
||||
"api_key_env": "",
|
||||
"api_key": "!secret llm_api_key",
|
||||
"user_agent": "",
|
||||
"timeout": 600,
|
||||
"stream": false,
|
||||
@@ -54,18 +69,15 @@
|
||||
"frequency_penalty": 0.0,
|
||||
"disable_thinking": true,
|
||||
"semif": {
|
||||
"_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.",
|
||||
"temperature": 0.0,
|
||||
"max_tokens": 256
|
||||
}
|
||||
},
|
||||
"codegen": {
|
||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<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,
|
||||
@@ -83,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,
|
||||
@@ -116,64 +124,23 @@
|
||||
}
|
||||
},
|
||||
"skill_bodies": "data/skills",
|
||||
"skill_seeds": "seeds",
|
||||
"log": "data/decisions.jsonl",
|
||||
"trace": "data/runs.jsonl",
|
||||
"category_registry": "data/categories.json",
|
||||
"simplex_chat": {
|
||||
"_comment": "Per-machine simplex-chat daemon settings. The pinned binary (version/bin_url/sha256) lives in the committed pins.json, not here. The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh renders both units from these values. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
|
||||
"port": 5226,
|
||||
"display_name": "semif",
|
||||
"forward_port": 5228,
|
||||
"forward_display_name": "semif-forward"
|
||||
},
|
||||
"bridges": {
|
||||
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
|
||||
"simplex": {
|
||||
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5227,
|
||||
"token": "",
|
||||
"max_inbox": 100,
|
||||
"ws_url": "ws://127.0.0.1:5228",
|
||||
"user_id": 1,
|
||||
"auto_accept": true,
|
||||
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
|
||||
},
|
||||
"llm": {
|
||||
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5229,
|
||||
"token": ""
|
||||
},
|
||||
"nextcloud": {
|
||||
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_addressbook` are used when a request names none and the account has several. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5230,
|
||||
"token": "",
|
||||
"url": "",
|
||||
"username": "",
|
||||
"app_password": "",
|
||||
"default_calendar": "",
|
||||
"default_addressbook": "",
|
||||
"verify_tls": true,
|
||||
"timeout": 30
|
||||
}
|
||||
},
|
||||
"gateway": {
|
||||
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.",
|
||||
"humanize": {
|
||||
"_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `<skill>: <ok|failed> — <detail>` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.",
|
||||
"enabled": true,
|
||||
"timeout": 20.0,
|
||||
"max_tokens": 200,
|
||||
"max_chars": 600
|
||||
},
|
||||
"simplex": {
|
||||
"_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. Groups/attachments are not supported.",
|
||||
"enabled": true,
|
||||
"ws_url": "ws://127.0.0.1:5226",
|
||||
"allowed_users": [],
|
||||
@@ -182,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,
|
||||
@@ -198,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",
|
||||
@@ -209,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": ""
|
||||
},
|
||||
@@ -245,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": 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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: 746.35px; background-color: white;" viewBox="4 4 746.3495483398438 4081.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"][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: 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,d09GMgABAAAAAAfcABMAAAAAENQAAAdzAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cKD9NVkFSgQQGYD9TVEFUgWInLgBUL3QRCAqDIIMLCw4AMIV2ATYCJAMUBCAFjXYHTgwHG2MPSI7UVnlAcpP/PG76574XKIQgNQ9aMWYOzJzOnNE6+ESr23eT2sQ1RNFtdi+PQgg0oMcgECuU/O/3a6IXUT+YhE5qlMRjzRMmUcT/YlIScRND3N9WFIkkvBEqHjKN0AqmS7W7pslGyKGniKzRX/+9JQiAiBw5aNSYSTOggQAAigIAiiIHB/beSc/SWAAGANDyAhpoMeP2RQKKNKUDo1nRZauCIaHysUgQAKNoAY8HlgeJKDoirKqpjmHl8iNBgurKDAAZMvKGFua5re5aEBjg+Fyna7lAoPNUChXAbmNzAEzcG6ZFKEsOpL8J4Egh/wvuyzsb30Avf8A/UtSA8DEZl4DuBwBmYF8AkEkgMGigApBCB2AoNnnqlKmkB0aelZPIAFpZXRMjI1i0IRAjE/hIb+UsSoSA+7AJawQs4jXGYOUs0hAYQE/ww0A+7XHelvYYl9MeZV+kPcLmJDxM54kbZvQQ3QNokx6kUqL2BwAmBN0nF/y6ngQfzpwmgFq038AQjGjtpvSk8anfZwfIhO0+c2bZx44f+m8b8LALJOxE4gMpOCj9GwJcAAkaMAjQQ/aMnCB/oCiA5W3KZWWPsmzX9V3TQBBrBMCEgZBCA7FL20qBd3NHDYKM5LVlUCXNK38PQPNp2cLzAPmoDhj4jnqKdMi1KUprAC4DtJZaAN4GUCvdBn0Auh0EUhQYAQBqAIAEQAPgfgBvOdipExAm/csIgCDppeRkqxlGraFRkG576CFS6W9/8MGa77u7u0eKkqB7+PHHq7/p6Ohw6fQq8ZFn5iu0aBI5SkibeQ8UW/JB/Ln7e2r+qku8raNQJNep+eH0l3/v1t3e+ee7QNM3S0jX0YGmLzsP7d0jdJ/oaXog5ZWnS+JtXV1Ezd9fnVM+R1r108fcY+MpI0Jvqy912Ng1Y9ca/qGiZ6Q+t/aP5OjQMatJsqbQxOAJknYfSt9zqpkqQSM64VxZltvj3uJXtuLZ7Gd7vLaHrJbsCWnDB07LuiypRW0CV9srF/tcom3o9KSUSrOmcLllV+ZDi5KnjKqwTpmUPnTIQss2SW2QJJXAEmd68iebiiYtszkV76m1pIGpQYA8Fog6AUu/kEMaNAHrwlPD5r1FMKSYtwC4ILjIPi/tUHHOiMUyEglPE3tRwXDmrMHoQrv61IMPLqmui7vQlNCW4Q0988iDtxNRi4vK2bDXXx+Nf/APtuE65d/cw34rnDVSSTULU25eRasuI+OwUMYdudAs+orPfvHcG6HQytUb3GhSVmof/Es9dNake+65pcWlrG9tUzFyq81DDpxBO6W/7FJC1NQ0liR2JY2sVHhzh5KkbKDj88fgfrRQxM0z4w7e3N2KpgZGM1cUc2nRJnI4Q7aGHO4a8Wdy6JmNikfl5u746/3nuer7/+w9fIVd5bt27cxpFO2pefZCKuO4fr3v9JVVl7nL7EbS1k8QTNn6i6eOncg81zrCnu0wntlWuPWM0S7nmMXjXcaPi7KzrMymO9r9w2uP07TXPv/8046r/5nsaqZBxYs4TzDl2u1Fzt+PHj2iNfebvoRMjHU4ChNPd/d0//ffvgvX6Xyc2/3////+0dq4UeXlp3pevZWrPvvbvuMKLvNdu3EDGikxw1JYQvP6HDmSN92DW82izOCEgaUpXMf1E6Ayac8fPXAk82BreUW2M/VMV2Hn6ZQKe45Dd+gPS4dE++Ak98DUA7++datHibOpvDueffbNH3dTSmZOdrKo4ktojFkWe/HAb4988Y+h95QVHtzOplIbRo/um6M+e2jP1u79567yg5zc9s9ff3zbChAASv0+8GHvzYuNQy9oOD8MADv3Pa9NX3cgoKjZHN4XgBoMAEDAt6ufzQEepxD2MsEpXEvlUCaVQaEadYT1/G5GIAAF2QoOErQAHhNa8iD03yaBwSAMB8esOQwBY+Y5qJA1txSr4Zpx1UiPpOkPAyReTMaQPJgg8hQkwsDV8MLS/ahEaT/BPKT1OcyHsxEsg61T4ENhHahDYW6iHr3zByKQ8waiKE4LrQmZg7XoGxtaYAlDK0p10W0hr+F2FGvCfdBgFR6AhAY8CBHLZA91r5DxMCTMwiMwGYNHocFwPIYkpXgcIix4AikMf+VJGADMFBJRq1qNmNFWiYlYyqPBUj71p7WKkaAGyx8zK/k1qrXRZFo+EtdoUgUs1xPgxwkRlfwBUV5+PnGR50itFfzOhZMERJSZE4S6/rFTRu0ph80VLNRv8qk/4Pqdwy1gsZrjgxNWXzDhUHGDrtVyh9PkTSJXTwmOOKaKUC1vAGyM5QoST71NBbZatdtImLzhfDZmNr/uaktFxS3VYLKggKCo0DRpuF9c7arT+g3tnMXvz+AfJeulnNNA/eigcqN2katYjfxJh3Dz8pptSODrWvQf7MUjBYWsFgmfrzenXgaRzbCSf0P8xGkiguqczHOhW1xMjaByoqxQtVqrhbhlyvkENaoQBPN+/5ViVgvxqxCpor8IgzSq9EGZy6kBcGLESSBVQjxQ63S6nWn2E8on0tNX4uR5oz4hpf0d4U4AAAA=") 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,d09GMgABAAAAAC98ABQAAAAAckwAAC8MAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGnUbh2wcKD9NVkFSgQQGYD9TVEFUgWInLgCDAC90EQgKxVy+FwuCHAAw6w4BNgIkA4QkBCAFjXYHilcMBxsPbCXs2Eu4HUBQUm2iiIrVrkZUkiIm//8lQY64LdyqxwUoEfFu9YzNaLwD6TZ2ztHaAWFzikR5Xi6076tcblFCgSgoqF/G54g+NvH2HKUdx3BKkns+Jt0QAZc+7CS+BWwZfEVglBik+hP91k9GW3FD9t4jNPZJ7g+0uX+XcHccHHAcNTJHLora3AarNlZGz8gZf8rMqT9S/RmlPyL8qT0IyjFyL8kDl1kBCsMOyBGwAgLX8cRCtcJVdTzJDOhWBs7hzXz7nyticzuapbqZjG9W6neOBA5N8KghySGB4IEiuu3FmkCQJa9BABJw5s3S2nYlkDL5TQ2Vq7Whm0ikdKLRZ0gkjW+OaG78vH+v533AkadUDDxM7Zat4Nb1/cC4jyGxV8PmvKVJiB0q1KnfzJAjnZZmZ0GA5iPi9j5F8wgtgeVHhO4A0YkVkCKwFoXJbIAd/X9v0yrt37+fbZlWGi0MkLzbs9ag7aV0RvIsRccUXQSRWr/lVnerNTKW1LYHNSSNB+QFyXA7UkuyeYE9Bwwta8BYJS96vYcQXl0ESOmFFF3lEG24SXjhhZdfxEGQHwF0Kmec5S0IebDEbHRsq1X7IB24gQpawAJgoex/6q1ALlUkPIMMcpn/1MdQnVZ7PzWPKGZoyNnxzVcVD/JINjoUm2VwNkIzPFZC5aWM/dX2VQECo3AeLwiFW2c9zEbjZ9MWW00Ttp2OACj95EgwECgEFLa+Yl+/KgBQAH0TSNpB3Q7STtB0h8AgGFsMCBQ4vye1A9LIh57mlIbOnC2aIN266jSDFA4ACgUoAAS6Zd1hBmHbkmkAKXDUzFkxuSYdIIZ2CFHR2IwQgY6JV7E1NM71YmgPg4Dd5ZggcxfPDAk5TCLEYXG5xyzxsoBd73yACev1ItluUgqRG2QB8mo+eIchQGl97M3d24XjEWChG/MErsS42EQYV+JJc62KcZEkNeRLbiTwZQMwqxOcxO8rfR7AGaDzpxpKgiAHoKTDKmKkYuanEVTCoUyVoBpZUU16JPWZK2e+5fqssNqwbbaZByXDw2JMYAZjiNpbSaLqKBOoCO/cidSlB4KNUSwK0NaYjHpALJZiESbXpzCOaYxhlNcBwgILSCw2LJHFOswggRCzIQ7JQnSRoN56IzEMoD9waADikwAAO8lh/ulzhYLMT7yJaAUZgo5NGwGg5KY4H2Whjrm/K5GIh/C+fBJvRoSKIAY2j3s4ZdMsTuTvjsBh9fN0ii5GEIQRiPUjEOkkWi0qrMqsoP6U3jUpXCwEUQjdNDHewQkKCoQxj8F57ihG6dpYHGYkrqWPi/ZctwVu6+ewAACKjtuxfdtLSERwqgP4wY3NCVcxT1leYhb5MndqhlS5jSnbxUVzUwhPPeEv3QU9l/oA5B5fNbJcIIqcg9eCVkxe3e3UQt2BZwF22Evs4ToMgL8K2RDkOgBAO9EnqcgSn7L48OnIYwBUQefMkxXEAmSmGSKSAnJgQ3tCMkD3bJ1PiIPNWGjYSA53kZ3GLTdHhxkqBFkJEChAHuSfwetp9/Pkafey+bS76cnT7qQ+0+34D2GvGo3L4gJQ1nwz/AhRbwBlAPiajNdrvQoGELm4SpZRnz0L6FCju6kVjSqf/s0hq/17y/rAI06ohCz9hXOeRYSJfCMjjyY8lla2M8Ph2NlcGxgiD08siuvi3oxgOEZhtuwZcsp5pCMC4kuOgSJcuGNhXBv3ZMBCFiu49lWuq994LVV77u1TnHtRzwXgqy6LAgj1RRmZWdk5uX0VmZGZJ3OVNYp0CZrPvLEutgAp8Y89SSyFkkbLYNSSqMOaQaqeTANOI7kspSa8ZiotBK3U2mi00+qg08mgm1EPi35WA2xmspvFYTanOVwGuQ3xGOY1wmeU31whC4UtErFY1BIxS8UtU2K5MiuUW6nCKpVWQwBwUAieGC0/1Q9uRFT7AOlCOqAFyKIYsL4CkCUxIv6x8JpYDEZJYEusmqD31ntiHGDDTEdiOzprOhN70W/pvKAW1T4Z3o8GTN8FqJ6APgvIXwBrlxU/Q1wdreerwF+uCeb2EmDyNQUdBwuvgGqfrwNkkXy9QaMwkX+Cyyb0xYyDeGUskoJZX0zhotcteo4xKA7x8kqFQo3oZavRZFcwO6PSJ62r8tbwgrPIpZd6rD4V73LK9QqOKzYVRTeOJ2Zh1weMgmAHGSU19WUlyV7tMoRgp9RLF+556GVoCc5cbh9esCGaLMmwBH1FMFOewozLvP64rQshum1W97kWo/e552tV1ILdl5qqEgEhYlgZVQ41S9zDK8nKB7CGrG5UZKBZzyYTo1KXb8U8lyXbvULGHmqsh3IP4qZPe7bpan0df3IBEJOZdxYfOoS9bNao6UwacdfTid8vsxmGCQCSMBphP8S5+50Ty0UAYXgTJ3BDhVTpv5volTGONjzj7LwGo4LaDhGkpm5p4UV8ehYfCRnec85LMM1AgKRpxLJIfhtH+ybo/tuoOybc3FcguttbYw5E0sD/sGyqPjxnLD3VkryMBN2PNK7glYodrv2X6+oPN3LjkTVZw7cHacvFh2NvNYSY9ygiI25iiCG+nmsvCKz4r+TRhge/iTiwEpJaXiuLezbqbg8HnVVy92RkTCRd598rc7olzUy4sKxdBgoU7aKfqNeRrYvVrc7a7GU/vH0+ejeNBljx7TVVasrkEvOmTqFLq6Pbr7akw77e69n8A2SnSW5r5x+9IDRz5I2JZzuhDAjkI6PIG+w/84aTufqD0GrbgFcckOU25RJakqt0UN7Y6OzA7TcHIkDAvUslgZZzxEdB5ZULppzsI7Wpj96gJPpNzQcf2v2w0+7seqrXWF+k563dXk5Y5NeJx0+8c5QeFbzJbfb+3AFLbgIzvHWvX5Z45neFrly8+r2pCMJ0atvcZPMw9E5ZSaZUVZMGVExRST2ks3IkRT73HUzUwd34GvMwcHScej+CbkxFgxMiVUYDK54AwXq3Jc3TO68ImnxKJNL6CXCHx6tbj+clLLR2s95pUJmaHMOVxbOHLknzrjv2vvGx3Pheos6r09hj5Y7K5X3og7lBPE8PsT5jgn/2+O2j4MQtbOsVvvq8D04fu21O54kl4e8kpvjOGRkTyI58HX1p/ClzOqNA/P31Qtvm6Lb6Q4UQ2XFHXpC9GB7aA2i4lQqPeVM4iAcjd8/h8br/LgpK96Mwvq8Co2yTs0smAus1q/6H5uH+B8FQtwh6QjjcUKgDE/uAiHKOLFf2iPXVWoNrl6bfDnlTuojBCjzuNFgf7GM/kzd96fI604KJM/maFOY71z+BAG80HitU6G6H2/eMm827tFHuslp3c1bp5Nl0i5443Fh6qwbfonu6L9gn2fDyI1jajjU6eMQ2qqquH6/fNGSuotMZ1rDoTeXqqhkb5R6fnbAiK6G+g5xVdjEn6p+d7a84RvlftJLBMgSGWEcso5/8agxECHN4mke1rdFrolfjaD+iLVe1MAKDp13Ov72ToYuLL/Zsmz4TOC31bgzti14SuQiK5lFyuZwiuok6e6/b84y3/zNhHlhGSiSk+OFz60Z0vtS9SQlz0Tq2p/adDs7MdbzTmT7lIlIKFN997vUrJ/PUZqoanSuWielcxbWFAK1b6kppj91bkaPzW1J9pLj4CGifeAOP2DGao9/A0o/+/njCf1PYcFLCiLLiJjRsVaK1u3fv2l1bmlW61ZV7Lrgg3Ul0E5SCgnORPHOkNyzAfIbJlPd+jx8AhTLu5b2q+v37D9SXDXBWeeOFF114waxGLGzFUBEjIRuDGIOUMJ0PNhLdBEGJKeKmsAf/bQp1SP1YWWrd7Pdn1a1aFU+nV8TrVs96b3Zi3Yqyrd+VWFoOdiWLYhX94dhg7aeuc88s65qh89f3lbgHE+l7pqAXb2ryhr/r+77T8/7f72sWS+QiaoGYNAjKsutff6O4WMSyHFV7+8b1LXLODSGSZUVoSK5A0Z4777qzpyCRvM6h8ZKLL85qIzZ/IKN9V13rSxy4olkb1tJKWv3E9N57V1emPpso7rV3zXS37/HcmIq3GkAb/r1FdXsrTwcXHewQPeQ8+psPN+9mkcvZdJHiGxgNQ7bH0PfLh0oH40PXrXY7T48PjvVXDOcYobuL9fy8SEe0K9YVaZ/LchMpWHuiM9Yd64l0gXZT+65FzIl1bvatadesxvIRfZXW57RbOHw+3nVLfCC6KhcXlRkS502cl+S9UWvLqKe4r/515+P7E8l/jvsd6epyA6n/ZSgFZazJNAerh/S15bZZafh+oSmZSpqUPfO7eQlKoBJKTpFdBIFjvOfm7/XOHidnMXPRXS+XGnsCt0toBY0pobbcyPojDYpPVKnZfHAs5qkVUuWxfmOgPMP7wnXmOYEiayZ/kcOazDjFS3ipN5PxF+374on7BAiqY3M8VcM9Kcwewc2cmVPOGSFZMiLUz4tut7X0987t11/t+GJ9VhOzLxIukkhUYhSTF2KGdlcM6I+a2kvnpO19PzQL4FOHW4y7DLnAxmT58HBJJWBMlQ+9TzLF5U1BVy64ynGgO7beUt4ccjb5Vrm2dkfXwcWL8YgND862ORaXdAY0f07X3NugvWrLSae1Tq0wBvoH/OYaE63sL9mlbu9UncZlEGf1s8CG99x5Z7eIZUHFEpe7itoqbyi7KrK/8WhLzE5pBA4jOkUOidKhtD513zrLYHB79OLYpUIKpyjqIfGoMxFaE9ngW2TK5vQLine truncated
|
||||
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,d09GMgABAAAAAMcoABQAAAACIVgAAMazAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGoFpG6NkHIJ6P01WQVKBBAZgP1NUQVSBYicuAIhQL3QRCAqC7HSCwVgLhiAAMITeAAE2AiQDjDwEIAWNdgedLwwHW0AHckHF6x6C2wbAvHMdZvVXhTJuj3CeYJV5mv/DZkbzOAi4NJL9/39SciJjbCrwqe83ywIzgolkyo3VCjtasCkUIVMwDzfKONHViNbg12b3EYqYi2Z2gbgyLnivrnQwI5gRjORbUCxIgbEUGuMtOH4+0kIxJ7MeGRm5znGzgd0Ehd1goLq/PT4lfx06eOqGGV+EerXkB9un0+PUHbj/0wfMuZi5FhCvOSbuyzWr4djgX8HBHp3zvlAbHhhZpQ+Zd4ZnjStdBcYumxGr6sQL/8/3V/7a5zwU0e3qqOrLfklGH5KmgEbBHaK1NbN5kdxxHAecR6QHHrR4sAiCpCIHiBiJmIBwkiUi0fYbGA02COor2tiNDVbgcTvwndlPtIkHcjDJRNjNquDBvXuQe/OIX4JHtT1VW6zDP/8/9rR93htHpZJMumid8Yy45Aohm1ZCZP07PG7aP6Dqt564Udquu31zBYIFL+IFDwnBJEECXvdJJ3qqHaDp7JoTjZnWEm/TJrUkFaWGlXZQvMCK6RB9ZqjPhIkxmMNg/+yVmf7Ef3jP+j+zV1wPO+ywHVaI2KhR2zRpPeB2vLx5+hO+7F/qT9IOvFvWw2g7NTt1+3zvW303297uiWh9W59tRxjEQyBCSIiIYUEH5tPZ58xIMkg2//8PicsLYNPdy1pLCXd5KVMCdwdIS2CQbeFoABkMccoiH6jCjcvnE2lUPNnP4/EFTjQuTy6VS2VSrlzK4XAO5lpIgVYgU/cTsxe1k6Oc9n13dbOkFliSCRKexKEBzuwnpNNeEzn0AfnGNzo/ANoBCnlslrYty2UF9/PKktJkAS7nHHyTAisxgvNsXKhAX6Bpt/nezZq585lyGqTmENZEEoIH1ni7vP0yDb+Z30CwmkFVkLpQQkCNtRdVxOwaluhMZ0iEZhZqYXmAv9w/xcOxdbW2LdI0S7M0jlLpDc21luiQxCf24jf128v0JgqNkIoXQMD8m6rVzoDzIVIEZZASJdCZkgNAUGuCouzWeVOorKs25OouD2YwHAQOBIIEBYCkltFLkLIFghRNgrJMcAYDkgChuKSc5Y3yPukcHr0n5wEGlACQkkFAkQqOF0LWpiz7Qk7dPdiV9yr6KpVbXlFenaorr7rrqqvKa8p7/f3/qr6ueITwK///lkspo1N2l9K3rBkm4N73+EA8PJKfFFWLjyy5Sm6FwKNAAqBISS6tKU5rKim1DWv29GXKNjCe6EwZvYwZtjFjCL72U/1mwwronDwrA3wu4bJMZabya1NZWb93mdIbj8eltiV0/xkQMXjW7Flu41ZSOioVoChVCgrKWx4GQ2AgCfGvp/bDw2J1yZIdDsCXjKqVAU1gNoJo03yyk3QHLk7ACcXF2Vq/qq7eOJx8+Pp/nVX11K0AI/vq2CIbUBo25c/1H5mr/3s0QR23XLf0qez+qY4kMSICAkIoIuP78P3G0HfXlLEFSUhIiHwksra3rymFZK9AhvAIg0hoRKSRRppGxDnu/dyvvbLNWcy7AyJ66v+xpoDsj8z5Sc1Tv/1e+8e8O8ckjJIJCWSyvD0EigFufRwEoVGZCYnPhNzMhHwTQ7krR8XAgqAKLiQzvIhMTZrMiU3MTEubmV5GZlbZ6nwrnVmsEnW5lVavcBrQBtgD4pZxgNo1LXKLLeS/DEwStjB6+aRb8y+/RdJvKpklDBKC4P9SNq/L75SUqFFZWvlU4fJ4wiHOl61y2OqP+eLuw9SDWd/7fURr/ImOrICdWMj6TwlF4O33TG8HeGAACDSuFVPQYd8XDnbATsEaULyxiQOIASKySKtlcEH452clIGu/CGTg9eqCq8SVDgQQGCDlXlggeYJ31VKFpcbaMKBXAVu52r7QFwRuoldca9zOs3loY6fC3AqP1yDpAOmkZSK2qnxbYkkPFm4wQFzUUnylZarL+Wju1VR2wKOsXR6PH8y9bKX89DbIjEDRzh/w0jaZu3qShRIPIYrmunirUZeqhPnGEz49ripHljSuRCHhLP4R5t3bYfdMVHVTb5NUNcxBbt9OwbTBBNnqkSxCVnaJMyZ8LVe7dcJz9UKkRPBkhDqN6cTjuWjMlWOblrwBJ3yZei9agkB1kMptD6FMpdhxWypNWimQH/yauVlTynSxTuktay1vj6vHDWJQ6FO21R3bQCpaZuLYTTFDmMYSV6WVLtLKFDwoxsLbNzj21sXmnjUKN8meRCAXB8C5Evzer7O8onUym5nVWigUQxa39AR+qJJS2OzW2bMIOeba0Wkbil6LVQr6qVDVnVW23lwx3gov5B2thp64VCaKW11Gp0w7yBPHH/OkTzJc8cjMaeIZPhrTLqJAhaROpHEeuaE78IJXPIWo+8zVmNCnHsrjzeNSFT1O/6BDFRWej3Uge8wXejyvxlWwtMECe+rmXDUEeMvHQUnd0lkezz7LdODCO8VvCDn8BlsNMlTG3dzCrYRDm4XKibJRUI2utjlmKNgRK2C4wmFNrIQIgSE5HgrWpGzZD4rDuTDnxk3jUW0OvPgEB04Zw1kQDU8xJgs01Vzh5lkkVpLMnJktb+IFyi1QYYVU1Wqlq7dGlnWKXOI/rUpttVOl3fauFNt0aHDMydanXLbZFRT3uuaWfe58dz3onscOeeqjYwZ8d8FPetcCMAYPIqGQZ4kk4UNSyfmUQpb8TJcNf7Nkx78cuaIrlLcIqJZ/HDgxZYoUnynW3IkZamGLk6hCy2WsFaqSiWpSixkIEYrds4NTFUAREsF1g0OZMmAQzJ267Xxc5OphQuFEZHhMiEM6pcuhZvaiV6vuuUEjJs10ZVbNpu5qaxbawmEQCCL41R5czrgMKoyLhYEBwSBgjCQhDKOqNZhsZAuic3AfDkANr//CkFKOsOSkETCkSgnjnBOIXBIsuZ5hvIbZepBA5Dmb/h4pb5hSywe2fHnCLEr+dzegMXPTOgy/oJqpBNfsBFXCAWpji2xKgmvxAdvMDtwO3DZcwdiMYVjM4PjMWRCwhMNyGRM4BUPiYH3XwqinmOMu0ETBLb2baKGHsbLg9hLDmUJDOOWnlT32wk2G4ORkkTskMidwQ/rgACiufgXD4kEh0Go8BoEMbCByssg9kjQMps4h4kbKy0cMXMBXf0xLGRVjA5mcmHbTFv3pTCDhMABTbvqNvSd07gP/t1ldd7neAJchBOYMJAKwRrCVnS3KVraIxeiGuqljNhluRQ6hfihvntjsN4RpGoWWc7WV40FKHfrlkwhF/Mho4q8tngBSv+pKXxzI5Q+1EgsCgGAAzZRQUHfhgOJEjgEKsE8QPEVs/hrYqZDY7VOrlO14t5ssm4y4ej/AzKW8u0wzZqsJdrcj3c+3XmPIEPjd1l9uxvBus5cV6bp6H8HMJYx7E8tmM8q7QjDQcJr9FUq0iwDgRxUEkaVxCm6/kKpeacJ3a6tbL74UUVCaCu1q6uPYbPMFJDboAyQ8u72uFD26DkoLW9qPmUe0szGCqMikHHPNeghLar008HgZc+sN4cTGIb2m1/dYsx7pCSmDwGPf9K1QK8DlioecdYqOxN2GuUCaNNY7Nlb1HaTSK/D3eZihJa20V3Ah3r0IktbHZGvnlz4ocGSXxm5H12MwSjzGK60MMDg2TpuGAHtLwm5voiA58PKNVrV8mj4QDuN9JtoZ8M6SmdnHO3tEqzDUq7pAtzgtjAGLc5LYdrnEFjOSD3xg4UET/zBIM3Drzn1uew+Ur+82tsDmNq149+hgp6ekegV1oR8L4XFMkl1qaEXs5JZQt2kEMfKpXq/Uqq1ZIE+HAjxpZfA85NWR5aeb53cAw2wOqEpU3KyLKsC79hAUyBQRGicAL3moCqnXQ7PL/9OH4DRSUuyJqkjrrywijYn+JJkI+yo5mES/3DjYuZ+sK3Fjv0PnnOwaBx3zsINdABi5MeqHv9mM0wJwSHTUy50eFSB6t2xJ17+0KtKJviVMJkevf7g3FVlsyqw72TkWB7DZubz25Jgp+9NuAk584fs9r3NONeF/3Klm4khYA0RPij8DvPRuzCpItwTBqSUY2x9jCxvA6pAtThekPi4A6z2qCX08AI98qdvr4wPk0Nd3en0C0PXOaUafEIwG5bIlmSZKEG9OLEhAEICu83eAsNe1XrrXNa7Y62rr3usqi2u/Uj+IH4yoRXWlObtdLiWBmcvUtKRfIqL8/vWgG59lcBvezHyJCgOO/Mwaiaxe7TFJSrxTDeaD/o9sKh6PPFdqTTEcFkDLOrhmYpH635szFCIg4KKwMZUmlF+tGrRem9SuXr3VR3031hzN1Txt0kpdx6zbTtp5u2xPHKIYykQt3X4iK6/KuwIvyIIuuEJFaAk9YTWgCUwOzA8kB3ICZXKFXC3Xy63y95+HKnrSZxSIAlcEFFFFQpFW5BR5894ZDRLOBHBZRaPDztp0Rm/0QV+1aY6pAHfCJ+AL8wDqKOPxychL8pbACZKgCY5QFppCV5gPhAfiA9MCiwKZgUK5XK66m/YGjOaPKOIKQpFtq9nzIvyE/a0PZPhgoQDQwsib87fnob5YX6Tfps/S1+oDP3f5GL3qz9cAiPjNmy/0AHz5/+7bnnc+TzyPM07kefh58Hnguf/5GIBA7iTPk/PTqfYrqZQKVaxSVeiSrnPXRc+oW6d14clkenVV13VTt3VXffqmC5ZDBCYxhVmsN8x6OPwtQ6IEG5BsxGErLtvw2I7PjpeX/xlcmy2G2kiLine 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
|
||||
@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: 367 KiB After Width: | Height: | Size: 364 KiB |
+27
-27
@@ -2,7 +2,7 @@
|
||||
|
||||
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
|
||||
*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.
|
||||
|
||||
@@ -64,8 +64,8 @@ flowchart TD
|
||||
%% ---------- reuse vs create ----------
|
||||
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
|
||||
HARD -- "yes" --> RUN
|
||||
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>P same >= intent_tau?"]
|
||||
INTENT -- "same" --> 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
|
||||
|
||||
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
|
||||
@@ -94,12 +94,11 @@ flowchart TD
|
||||
ACTNI -- "no" --> ASSESS
|
||||
|
||||
%% ---------- assessment ----------
|
||||
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>P success >= tau?<br/>a definitive empty result counts as success"] --> 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/>SchedulerReply (run_id, skill_ref, result)<br/>REPL · gateway reply · dashboard trace"]
|
||||
|
||||
@@ -112,8 +111,8 @@ flowchart TD
|
||||
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
|
||||
classDef output fill:#fce8e6,stroke:#d93025;
|
||||
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill;
|
||||
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,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;
|
||||
```
|
||||
|
||||
@@ -134,26 +133,26 @@ flowchart TD
|
||||
|
||||
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? (default off)"}
|
||||
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 / no front end" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
|
||||
|
||||
REGISTER["register stub in registry + tree<br/>seed category config (locks.new_skill)<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, trace 'skill_writing'"]
|
||||
|
||||
WRITE --> ELICIT["generate_elicitation()<br/>implementation questions + integration hint"]
|
||||
ELICIT --> QS["Output: questions<br/>posted one at a time<br/>answer_timeout per question"]
|
||||
QS -- "answers / timeout" --> BODY
|
||||
WRITE --> BODY
|
||||
|
||||
BODY["generate_skill_body()<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"]
|
||||
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"]
|
||||
|
||||
@@ -176,7 +175,7 @@ flowchart TD
|
||||
classDef output fill:#fce8e6,stroke:#d93025;
|
||||
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||
class FID,CFG,REGEN semfill;
|
||||
class PROMPT,ABORT,QS,FAIL,CANCELLED output;
|
||||
class PROMPT,ABORT,ABORT2,FAIL,CANCELLED output;
|
||||
class START,DIRECT,BACK,MAT,REQ author;
|
||||
```
|
||||
|
||||
@@ -194,10 +193,9 @@ flowchart TD
|
||||
| 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 (never bypassed) |
|
||||
| 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 |
|
||||
@@ -217,6 +215,8 @@ 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 also gated deterministically by the per-category
|
||||
`locks.new_skill` (the `housekeeping` and `response` categories are hard-locked
|
||||
in code).
|
||||
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.
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_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": "23cf1f39fc9534fe81437200959b6dfc7106e45a",
|
||||
@@ -9,8 +9,32 @@
|
||||
"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",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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).
|
||||
|
||||
Executable
+20
@@ -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
|
||||
Executable
+26
@@ -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
|
||||
+692
-184
File diff suppressed because it is too large.
Load diff
@@ -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)))
|
||||
@@ -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())
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
+58
-9
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
Executable
+410
@@ -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())
|
||||
Executable
+345
@@ -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
|
||||
Executable
+241
@@ -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\"."
|
||||
}
|
||||
@@ -1,628 +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
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
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(ctx):
|
||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
||||
config value when set, else host local. A test seam; never freezes time."""
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
# ---- 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"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=str(exc),
|
||||
new_state=request.text,
|
||||
)
|
||||
request.meta["create_event_fields"] = fields
|
||||
title = fields["title"]
|
||||
description = fields["description"]
|
||||
|
||||
now = _now(ctx)
|
||||
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 discovery failed: {exc}",
|
||||
new_state=request.text,
|
||||
)
|
||||
if not calendars:
|
||||
return ActionResult(
|
||||
action_log="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"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=report,
|
||||
new_state=report,
|
||||
decisions=decisions,
|
||||
)
|
||||
@@ -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 ctx: 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 and "calendar.create_event" not in action.action_log, 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)
|
||||
@@ -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)."
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Report the next upcoming event on the user's Nextcloud calendar."
|
||||
}
|
||||
@@ -1,416 +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
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
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(ctx):
|
||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
||||
config value when set, else host local. A test seam; never freezes time."""
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
# ---- 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 discovery failed: {exc}",
|
||||
new_state=request.text,
|
||||
)
|
||||
if not calendars:
|
||||
return ActionResult(
|
||||
action_log="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="aborted: no calendar resolved.",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
now = _now(ctx)
|
||||
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"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)
|
||||
@@ -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)
|
||||
@@ -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."
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
|
||||
}
|
||||
@@ -1,107 +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=str(exc), new_state=request.text)
|
||||
if not payload.get("ok"):
|
||||
return ActionResult(
|
||||
action_log="simplex forwarding bridge is not healthy",
|
||||
new_state=request.text,
|
||||
)
|
||||
try:
|
||||
payload = _get(ctx, "/address")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"reading the contact 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=(
|
||||
"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)
|
||||
@@ -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 and "simplex.connect_link" not in action.action_log, 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)
|
||||
@@ -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."
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Read the next unread SimpleX message."
|
||||
}
|
||||
@@ -1,258 +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.
|
||||
|
||||
When the live buffer is empty it falls back to the daemon's persistent unread
|
||||
(`/unread` + `/history`), so a message that arrived before the bridge started is
|
||||
still reported. (v7 has no mark-read command, so a persistent-unread message can
|
||||
be reported again until the user reads it in their own client.)
|
||||
|
||||
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 _is_healthy(sender):
|
||||
"""A conversation is healthy when its connection is not known-bad.
|
||||
|
||||
`connected` is absent when the source did not report it (treat as unknown);
|
||||
`auth_errors` counts failed sends on the connection and marks a stale peer.
|
||||
"""
|
||||
if sender.get("connected") is False:
|
||||
return False
|
||||
try:
|
||||
return int(sender.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
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=str(exc), new_state=request.text)
|
||||
senders = _senders(payload.get("messages") or [])
|
||||
if senders:
|
||||
return _read_live(ctx, request, senders)
|
||||
# The live buffer only holds messages that arrived while the bridge was
|
||||
# connected; fall back to the daemon's persistent unread so a message that
|
||||
# landed before the bridge started is not silently missed.
|
||||
return _read_persistent(ctx, request)
|
||||
|
||||
|
||||
def _read_live(ctx, request, senders):
|
||||
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"failed reading {contact!r}: {exc}",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
message = payload.get("message")
|
||||
if not message:
|
||||
return ActionResult(
|
||||
action_log=f"no unread message from {contact!r}.",
|
||||
new_state="no unread SimpleX messages",
|
||||
decisions=decisions,
|
||||
)
|
||||
return _report(message.get("display_name") or contact, message.get("text"), decisions)
|
||||
|
||||
|
||||
def _read_persistent(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/unread")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"no unread SimpleX messages ({exc}).",
|
||||
new_state="no unread SimpleX messages",
|
||||
)
|
||||
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
|
||||
if not chats:
|
||||
return ActionResult(
|
||||
action_log="no unread SimpleX messages.",
|
||||
new_state="no unread SimpleX messages",
|
||||
)
|
||||
senders = [
|
||||
{
|
||||
"id": str(chat.get("contact_id") or ""),
|
||||
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
|
||||
"connected": chat.get("connected"),
|
||||
"auth_errors": chat.get("auth_errors"),
|
||||
}
|
||||
for chat in chats
|
||||
if chat.get("contact_id")
|
||||
]
|
||||
decisions = []
|
||||
healthy = [s for s in senders if _is_healthy(s)]
|
||||
if len(healthy) == 1:
|
||||
# Exactly one conversation is on a healthy connection (the rest are
|
||||
# stale duplicates): read it without a coin-flip decision.
|
||||
contact = healthy[0]["id"]
|
||||
else:
|
||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
||||
try:
|
||||
history = _get(
|
||||
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
|
||||
)
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"failed reading {contact!r}: {exc}",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
|
||||
if not messages:
|
||||
# Fall back to the previewed unread messages from /unread.
|
||||
chat = next(
|
||||
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
|
||||
)
|
||||
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
|
||||
if not messages:
|
||||
return ActionResult(
|
||||
action_log=f"no unread message from {contact!r}.",
|
||||
new_state="no unread SimpleX messages",
|
||||
decisions=decisions,
|
||||
)
|
||||
sender = next(
|
||||
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
|
||||
)
|
||||
return _report(sender, messages[0].get("text"), decisions)
|
||||
|
||||
|
||||
def _report(sender, body, decisions):
|
||||
report = f"SimpleX message from {sender}: {str(body or '')}"
|
||||
return ActionResult(action_log=report, new_state=report, decisions=decisions)
|
||||
@@ -1,375 +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 = []
|
||||
unread_chats = []
|
||||
history = {}
|
||||
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})
|
||||
elif url.path == "/unread":
|
||||
self._send({"chats": list(self.unread_chats)})
|
||||
elif url.path == "/history":
|
||||
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
|
||||
self._send(
|
||||
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
|
||||
)
|
||||
else:
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(messages, unread_chats=None, history=None):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"messages": list(messages),
|
||||
"unread_chats": list(unread_chats or []),
|
||||
"history": dict(history or {}),
|
||||
"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
|
||||
# An empty live buffer falls back to the daemon's persistent unread.
|
||||
assert handler.requests == ["/inbox", "/unread"], handler.requests
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_live_inbox_falls_back_to_persistent_unread():
|
||||
server, handler, url = start_server(
|
||||
[],
|
||||
unread_chats=[
|
||||
{
|
||||
"contact_id": "3",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 2,
|
||||
"min_unread_item_id": "8",
|
||||
"unread": True,
|
||||
"messages": [],
|
||||
}
|
||||
],
|
||||
history={
|
||||
"3": [
|
||||
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
|
||||
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
|
||||
]
|
||||
},
|
||||
)
|
||||
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 == [], "a single unread chat needs no decision"
|
||||
assert "hello" in action.action_log, action.action_log
|
||||
assert "pepper" in action.action_log, action.action_log
|
||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
|
||||
handler.requests
|
||||
)
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_persistent_unread_prefers_a_healthy_conversation():
|
||||
server, handler, url = start_server(
|
||||
[],
|
||||
unread_chats=[
|
||||
{
|
||||
"contact_id": "3",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 1,
|
||||
"unread": True,
|
||||
"connected": True,
|
||||
"auth_errors": 2,
|
||||
"messages": [],
|
||||
},
|
||||
{
|
||||
"contact_id": "4",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 1,
|
||||
"unread": True,
|
||||
"connected": True,
|
||||
"auth_errors": 0,
|
||||
"messages": [],
|
||||
},
|
||||
],
|
||||
history={
|
||||
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
|
||||
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
|
||||
},
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
action = skill.act(ctx, Request("read my next simplex message"))
|
||||
assert engine.decisions == [], "one healthy chat must win without a decision"
|
||||
assert "fresh hello" in action.action_log, action.action_log
|
||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
|
||||
handler.requests
|
||||
)
|
||||
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 and "simplex.next_message" not in action.action_log, 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_empty_live_inbox_falls_back_to_persistent_unread()
|
||||
test_persistent_unread_prefers_a_healthy_conversation()
|
||||
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 +0,0 @@
|
||||
{}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Report today's date."
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Report today's date.
|
||||
|
||||
Real local compute: reads the host clock and formats the calendar date in the
|
||||
user's timezone — the top-level `timezone` config value (an IANA name) when set,
|
||||
otherwise the host's local timezone. No external service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
|
||||
|
||||
CONTRACT = {}
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
today = local_now(ctx.config).date()
|
||||
message = f"Today is {today.strftime('%A, %B %d, %Y')} ({today.isoformat()})."
|
||||
return ActionResult(action_log=message, new_state=message)
|
||||
@@ -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 +0,0 @@
|
||||
{}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Report the current local time of day."
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
"""Report the current local time.
|
||||
|
||||
Real local compute: reads the host clock and formats it in the user's
|
||||
timezone — the top-level `timezone` config value (an IANA name such as
|
||||
`America/Chicago`) when set, otherwise the host's local timezone. No external
|
||||
service; 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
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
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 = local_now(ctx.config)
|
||||
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=message, new_state=message)
|
||||
@@ -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 +0,0 @@
|
||||
{}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Set an alarm for a specific time of day that notifies when it goes off."
|
||||
}
|
||||
@@ -1,87 +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`). The wall-clock time is read in
|
||||
the user's timezone — the top-level `timezone` config value when set, otherwise
|
||||
the host's local timezone. 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
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
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 = local_now(ctx.config)
|
||||
when = _parse_time(text, now)
|
||||
if when is None:
|
||||
request.meta["alarm_awaiting"] = True
|
||||
return ActionResult(
|
||||
action_log="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="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=message, new_state=message)
|
||||
@@ -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 +0,0 @@
|
||||
{}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"description": "Set a countdown timer that notifies when it finishes."
|
||||
}
|
||||
@@ -1,128 +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. The due time is shown
|
||||
in the user's timezone (the top-level `timezone` config value, else host local).
|
||||
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="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="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=message, new_state=message)
|
||||
@@ -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)
|
||||
@@ -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, Nextcloud) 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,21 +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__ = [
|
||||
@@ -37,8 +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",
|
||||
]
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -28,6 +28,9 @@ 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:
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -1,501 +0,0 @@
|
||||
"""Nextcloud bridge: files, calendars, tasks, contacts, and notes over HTTP.
|
||||
|
||||
Nextcloud speaks several native protocols (WebDAV for files, CalDAV for events
|
||||
and tasks, CardDAV for contacts, and OCS for the Notes app and server info). A
|
||||
codegen-authored skill body must never speak those directly. This bridge owns the
|
||||
connection — base URL, username, and app password — and exposes one uniform,
|
||||
token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` and
|
||||
`nextcloud_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only
|
||||
(`urllib` + `xml.etree`) and starts instantly. The connection comes from
|
||||
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook),
|
||||
falling back to the top-level `nextcloud_url`/`nextcloud_username`/
|
||||
`nextcloud_app_password`/`nextcloud_default_calendar` values the calendar seeds
|
||||
already use, so the same account is configured in one place.
|
||||
|
||||
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate
|
||||
input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError
|
||||
|
||||
|
||||
class NextcloudBridge(BridgeService):
|
||||
name = "nextcloud"
|
||||
INFO = BridgeInfo(
|
||||
name="nextcloud",
|
||||
service="nextcloud",
|
||||
description=(
|
||||
"Read and write the user's Nextcloud: files (WebDAV), calendar events "
|
||||
"and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app)."
|
||||
),
|
||||
url_config_var="nextcloud_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"nextcloud\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, email, language, "
|
||||
"locale}} — the account (OCS)",
|
||||
"GET /capabilities -> 200 {Nextcloud server capabilities} (OCS)",
|
||||
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{name, path, "
|
||||
"type (file|dir), size, modified, etag, content_type}]} — list a "
|
||||
"folder (default /)",
|
||||
"GET /files/stat?path=<path> -> 200 {one entry, same fields as an "
|
||||
"entries item}",
|
||||
"GET /files/read?path=<path> -> 200 {\"path\", \"content\", "
|
||||
"\"encoding\" (utf-8|base64), \"size\"} — file contents; binary is "
|
||||
"base64",
|
||||
"GET /files/search?query=<text>&path=<dir> -> 200 {\"results\": "
|
||||
"[entry]} — filename search under a folder",
|
||||
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
|
||||
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/mkdir {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/delete {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/move {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"GET /calendars -> 200 {\"calendars\": [{name, label, description, "
|
||||
"color, ctag}]}",
|
||||
"GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 "
|
||||
"{\"calendar\", \"events\": [{uid, summary, start, end, all_day, "
|
||||
"location, description, rrule, status, href, etag}]} — start/end "
|
||||
"optional (ISO 8601); without them every event is returned",
|
||||
"POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", "
|
||||
"\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"}",
|
||||
"POST /calendars/events/update {\"calendar\"?, \"uid\", \"summary\"?, "
|
||||
"\"start\"?, \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?} -> 200 {\"ok\": true, \"uid\", \"calendar\", \"etag\"} — "
|
||||
"only the named fields change",
|
||||
"POST /calendars/events/delete {\"calendar\"?, \"uid\"} -> 200 "
|
||||
"{\"ok\": true, \"uid\", \"calendar\"}",
|
||||
"GET /tasks?calendar=<name> -> 200 {\"calendar\", \"tasks\": [{uid, "
|
||||
"summary, due, status, percent_complete, priority, description, href, "
|
||||
"etag}]} — CalDAV VTODO",
|
||||
"POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, "
|
||||
"\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"}",
|
||||
"POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, "
|
||||
"\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} "
|
||||
"-> 200 {ok, uid}",
|
||||
"POST /tasks/complete {\"calendar\"?, \"uid\"} -> 200 {ok, uid} — "
|
||||
"marks the task COMPLETED",
|
||||
"POST /tasks/delete {\"calendar\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /addressbooks -> 200 {\"addressbooks\": [{name, label, "
|
||||
"description}]}",
|
||||
"GET /contacts?addressbook=<name>&query=<text> -> 200 "
|
||||
"{\"addressbook\", \"contacts\": [{uid, fn, n, emails, phones, org, "
|
||||
"title, note, url, href, etag}]} — query filters by name/org/email/"
|
||||
"phone",
|
||||
"POST /contacts {\"addressbook\"?, \"uid\"?, \"fn\", \"emails\"?, "
|
||||
"\"phones\"?, \"org\"?, \"title\"?, \"note\"?, \"url\"?, \"n\"?} -> "
|
||||
"200 {ok, uid}",
|
||||
"POST /contacts/update {\"addressbook\"?, \"uid\", ...fields} -> 200 "
|
||||
"{ok, uid}",
|
||||
"POST /contacts/delete {\"addressbook\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /notes -> 200 {\"notes\": [{id, title, category, modified, ...}]} "
|
||||
"— Nextcloud Notes app (metadata only)",
|
||||
"GET /notes/get?id=<id> -> 200 {\"note\": {id, title, content, "
|
||||
"category, ...}}",
|
||||
"POST /notes {\"title\", \"content\"?, \"category\"?} -> 200 "
|
||||
"{\"note\": {...}}",
|
||||
"POST /notes/update {\"id\", \"title\"?, \"content\"?, "
|
||||
"\"category\"?} -> 200 {\"note\": {...}}",
|
||||
"POST /notes/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when the bridge has no Nextcloud connection "
|
||||
"configured; 502 {\"error\": \"...\"} on a real Nextcloud failure "
|
||||
"(transport, HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("nextcloud_bridge_url", "nextcloud_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"nextcloud_bridge_url",
|
||||
"Base URL of the local Nextcloud bridge (e.g. "
|
||||
"http://127.0.0.1:5230); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"nextcloud_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="nextcloud_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, fallback: dict | None = None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
fb = fallback or {}
|
||||
|
||||
def pick(key: str, default=""):
|
||||
value = cfg.get(key)
|
||||
if value in (None, ""):
|
||||
value = fb.get(key)
|
||||
return default if value in (None, "") else value
|
||||
|
||||
self.url = str(pick("url")).strip()
|
||||
self.username = str(pick("username")).strip()
|
||||
self.app_password = str(pick("app_password"))
|
||||
self.default_calendar = str(pick("default_calendar")).strip()
|
||||
self.default_addressbook = str(pick("default_addressbook")).strip()
|
||||
self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True)))
|
||||
self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT))
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or NextcloudClient(
|
||||
self.url,
|
||||
self.username,
|
||||
self.app_password,
|
||||
timeout=self.timeout,
|
||||
verify_tls=self.verify_tls,
|
||||
default_calendar=self.default_calendar,
|
||||
default_addressbook=self.default_addressbook,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing connection surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Nextcloud bridge has no connection configured (set "
|
||||
"bridges.nextcloud.url/username/app_password, or the top-level "
|
||||
"nextcloud_url/nextcloud_username/nextcloud_app_password)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.user_info()}
|
||||
if path == "/capabilities":
|
||||
return 200, self.client.capabilities()
|
||||
if path == "/files":
|
||||
return 200, self.client.list_files(self._q(query, "path", "/") or "/")
|
||||
if path == "/files/stat":
|
||||
return 200, self.client.stat(self._required_query(query, "path"))
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
if path == "/files/search":
|
||||
query_text = self._required_query(query, "query")
|
||||
return 200, {
|
||||
"results": self.client.search(
|
||||
query_text, self._q(query, "path", "/") or "/"
|
||||
)
|
||||
}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/calendars/events":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"))
|
||||
return 200, {
|
||||
"calendar": calendar,
|
||||
"events": self.client.list_events(
|
||||
calendar,
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasks":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"))
|
||||
return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)}
|
||||
if path == "/addressbooks":
|
||||
return 200, {"addressbooks": self.client.list_addressbooks()}
|
||||
if path == "/contacts":
|
||||
addressbook = self._resolve_addressbook(self._q(query, "addressbook"))
|
||||
return 200, {
|
||||
"addressbook": addressbook,
|
||||
"contacts": self.client.list_contacts(
|
||||
addressbook, self._q(query, "query", "") or ""
|
||||
),
|
||||
}
|
||||
if path == "/notes":
|
||||
return 200, {"notes": self.client.list_notes()}
|
||||
if path == "/notes/get":
|
||||
return 200, {"note": self.client.get_note(self._required_query(query, "id"))}
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8"),
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
if path == "/files/mkdir":
|
||||
return 200, self.client.mkdir(self._required(payload, "path"))
|
||||
if path == "/files/delete":
|
||||
return 200, self.client.delete(self._required(payload, "path"))
|
||||
if path == "/files/move":
|
||||
return 200, self.client.move(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/files/copy":
|
||||
return 200, self.client.copy(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self._create_event(payload)
|
||||
if path == "/calendars/events/update":
|
||||
return 200, self._update_event(payload)
|
||||
if path == "/calendars/events/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks":
|
||||
return 200, self._create_task(payload)
|
||||
if path == "/tasks/update":
|
||||
return 200, self._update_task(payload)
|
||||
if path == "/tasks/complete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
return 200, self.client.complete_task(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/contacts":
|
||||
return 200, self._create_contact(payload)
|
||||
if path == "/contacts/update":
|
||||
return 200, self._update_contact(payload)
|
||||
if path == "/contacts/delete":
|
||||
addressbook = self._resolve_addressbook(
|
||||
self._optional_str(payload, "addressbook")
|
||||
)
|
||||
return 200, self.client.delete_contact(
|
||||
addressbook, self._required(payload, "uid")
|
||||
)
|
||||
if path == "/notes":
|
||||
return 200, {
|
||||
"note": self.client.create_note(
|
||||
self._required(payload, "title"),
|
||||
self._optional_str(payload, "content"),
|
||||
self._optional_str(payload, "category"),
|
||||
)
|
||||
}
|
||||
if path == "/notes/update":
|
||||
return 200, {"note": self._update_note(payload)}
|
||||
if path == "/notes/delete":
|
||||
return 200, self.client.delete_note(self._required_id(payload))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- calendar/task helpers ----
|
||||
|
||||
def _create_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_event(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
rrule=self._optional_str(payload, "rrule"),
|
||||
overwrite=self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
|
||||
def _update_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "start", "end", "location", "description", "rrule")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return self.client.update_event(calendar, uid, **changes)
|
||||
|
||||
def _create_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_task(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
priority=self._optional_int(payload, "priority"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
|
||||
def _update_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "due", "priority", "description", "status", "percent_complete")
|
||||
if key in payload
|
||||
}
|
||||
return self.client.update_task(calendar, uid, **changes)
|
||||
|
||||
# ---- contact helpers ----
|
||||
|
||||
def _create_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_contact(
|
||||
addressbook,
|
||||
uid,
|
||||
fn=self._required(payload, "fn"),
|
||||
n=self._optional_str(payload, "n"),
|
||||
emails=self._string_list(payload, "emails"),
|
||||
phones=self._string_list(payload, "phones"),
|
||||
org=self._optional_str(payload, "org"),
|
||||
title=self._optional_str(payload, "title"),
|
||||
note=self._optional_str(payload, "note"),
|
||||
url=self._optional_str(payload, "url"),
|
||||
)
|
||||
|
||||
def _update_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {}
|
||||
for key in ("fn", "n", "org", "title", "note", "url"):
|
||||
if key in payload:
|
||||
changes[key] = payload[key]
|
||||
for key in ("emails", "phones"):
|
||||
if key in payload:
|
||||
changes[key] = self._string_list(payload, key)
|
||||
return self.client.update_contact(addressbook, uid, **changes)
|
||||
|
||||
# ---- notes helpers ----
|
||||
|
||||
def _update_note(self, payload: dict) -> dict:
|
||||
note_id = self._required_id(payload)
|
||||
changes = {
|
||||
key: payload[key] for key in ("title", "content", "category") if key in payload
|
||||
}
|
||||
return self.client.update_note(note_id, **changes)
|
||||
|
||||
# ---- default resolution ----
|
||||
|
||||
def _resolve_calendar(self, name) -> str:
|
||||
name = str(name or self.default_calendar or "").strip()
|
||||
if name:
|
||||
return name
|
||||
calendars = self.client.list_calendars()
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
raise ValueError(
|
||||
"calendar is required (name one in the request, or set "
|
||||
"bridges.nextcloud.default_calendar)"
|
||||
)
|
||||
|
||||
def _resolve_addressbook(self, name) -> str:
|
||||
name = str(name or self.default_addressbook or "").strip()
|
||||
if name:
|
||||
return name
|
||||
addressbooks = self.client.list_addressbooks()
|
||||
if len(addressbooks) == 1:
|
||||
return addressbooks[0]["name"]
|
||||
raise ValueError(
|
||||
"addressbook is required (name one in the request, or set "
|
||||
"bridges.nextcloud.default_addressbook)"
|
||||
)
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = NextcloudBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _required_id(payload: dict):
|
||||
value = payload.get("id")
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
raise ValueError("id is required")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_int(payload: dict, key: str):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
+213
-43
@@ -1,35 +1,216 @@
|
||||
"""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 .nextcloud import NextcloudBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge, NextcloudBridge)
|
||||
#: 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 derived_config_vars(config: dict) -> dict[str, str]:
|
||||
@@ -45,7 +226,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
derived: dict[str, str] = {}
|
||||
for info in known_infos():
|
||||
for info in known_infos(_packs_from_config(config)):
|
||||
block = blocks.get(info.name)
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
@@ -61,10 +242,10 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
return derived
|
||||
|
||||
|
||||
def describe_bridges() -> str:
|
||||
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
|
||||
@@ -72,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:
|
||||
@@ -103,31 +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. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
||||
fallback, so the same account the calendar seeds use is configured once. Other
|
||||
bridges ignore both.
|
||||
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)
|
||||
if bridge_class is NextcloudBridge:
|
||||
return NextcloudBridge(
|
||||
block,
|
||||
trace=trace,
|
||||
fallback={
|
||||
"url": config.get("nextcloud_url"),
|
||||
"username": config.get("nextcloud_username"),
|
||||
"app_password": config.get("nextcloud_app_password"),
|
||||
"default_calendar": config.get("nextcloud_default_calendar"),
|
||||
"default_addressbook": config.get("nextcloud_default_addressbook"),
|
||||
},
|
||||
)
|
||||
return bridge_class(block, trace=trace)
|
||||
return bridge_class.from_config(block, config=config, trace=trace, llm=llm)
|
||||
|
||||
|
||||
def run_bridges(
|
||||
@@ -144,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
|
||||
|
||||
@@ -1,427 +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
|
||||
import time
|
||||
|
||||
from semif_agent.simplex_ws import SimplexDaemon, parse_send_response
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
|
||||
#: Send statuses that mean the message really left the agent.
|
||||
SEND_OK_STATUSES = frozenset({"sndSent", "sndRcvd"})
|
||||
#: Send statuses that are final (no further polling needed).
|
||||
SEND_TERMINAL_STATUSES = frozenset({"sndSent", "sndRcvd", "sndError"})
|
||||
#: How long to poll the daemon for a terminal send status before giving up.
|
||||
SEND_CONFIRM_TIMEOUT = 6.0
|
||||
SEND_POLL_INTERVAL = 0.5
|
||||
|
||||
|
||||
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\", "
|
||||
"\"local_name\"?, \"connected\"?}]} — contacts known to the daemon "
|
||||
"(learned from inbound messages and refreshed from the daemon's "
|
||||
"contact list). `display_name` is the peer's profile name and can "
|
||||
"collide; `local_name` is the daemon's unique local name; "
|
||||
"`connected` (when the daemon reports it) is false for a peer whose "
|
||||
"connection is not ready — prefer a connected peer",
|
||||
"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\", "
|
||||
"\"connected\"?, \"auth_errors\"?, \"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, error?}]} — recent message history for one contact (count "
|
||||
"default 20); status is rcvNew (unread), rcvRead, sndSent, sndRcvd, "
|
||||
"or sndError, and `error` carries the agent reason (e.g. auth) on a "
|
||||
"failed send. 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|local_name|display_name>\", "
|
||||
"\"text\": \"...\"} -> 200 {\"ok\": bool, \"contact_id\": \"<id>\", "
|
||||
"\"item_id\": \"<id>\", \"status\": \"sndSent|sndRcvd|sndError\", "
|
||||
"\"error\": \"...\"?}. The bridge resolves the recipient, sends, and "
|
||||
"waits for the daemon's real send status: `ok` is true only for "
|
||||
"sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead "
|
||||
"connection) returns ok:false with the reason — never a false "
|
||||
"success. 400 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:
|
||||
result = self.send(recipient, text)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, result
|
||||
|
||||
# ---- 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]}
|
||||
self._attach_health(chats)
|
||||
return 200, {"chats": chats}
|
||||
|
||||
def _attach_health(self, chats: list[dict]) -> None:
|
||||
"""Merge cached connection health into each chat summary, in place.
|
||||
|
||||
Lets a caller prefer a live conversation over a stale duplicate when
|
||||
several chats share a display name. Best-effort: a chat with no cached
|
||||
contact is left untouched.
|
||||
"""
|
||||
health = {c["id"]: c for c in self.inbox.contacts()}
|
||||
for chat in chats:
|
||||
info = health.get(str(chat.get("contact_id") or ""))
|
||||
if not info:
|
||||
continue
|
||||
for key in ("connected", "auth_errors"):
|
||||
if key in info:
|
||||
chat[key] = info[key]
|
||||
|
||||
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) -> dict:
|
||||
"""Resolve a recipient, send the text, and report the real outcome.
|
||||
|
||||
Returns `{ok, contact_id, item_id?, status?, error?}`. `ok` is True only
|
||||
when the daemon created the message and it reached a terminal status of
|
||||
`sndSent` (relayed to the server) or `sndRcvd` (delivered to the peer).
|
||||
A dead connection surfaces as `ok: false` carrying the daemon's agent
|
||||
error (e.g. `auth`) — never a false success.
|
||||
"""
|
||||
contact_id = self.resolve(recipient)
|
||||
if contact_id is None:
|
||||
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
||||
try:
|
||||
response = self.daemon.request_send(contact_id, text)
|
||||
except RuntimeError as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "unavailable",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "error",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
parsed = parse_send_response(response)
|
||||
if parsed["item_id"] is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "rejected",
|
||||
"error": parsed["error"] or "the daemon rejected the send",
|
||||
}
|
||||
item_id = parsed["item_id"]
|
||||
status, error = parsed["status"], parsed["error"]
|
||||
if status not in SEND_TERMINAL_STATUSES:
|
||||
status, error = self._await_send_status(contact_id, item_id, status)
|
||||
result = {
|
||||
"ok": status in SEND_OK_STATUSES,
|
||||
"contact_id": contact_id,
|
||||
"item_id": item_id,
|
||||
"status": status,
|
||||
}
|
||||
if not result["ok"]:
|
||||
result["error"] = error or f"send status {status}"
|
||||
return result
|
||||
|
||||
def _await_send_status(
|
||||
self, contact_id: str, item_id: str, current: str,
|
||||
timeout: float = SEND_CONFIRM_TIMEOUT,
|
||||
) -> tuple[str, str]:
|
||||
"""Poll the daemon for the item's terminal send status + agent error.
|
||||
|
||||
A send is `sndNew` the moment it is created; the agent then resolves it
|
||||
to `sndSent`/`sndRcvd` (success) or `sndError` (failure, with the reason
|
||||
in `agentError`). Returns `(status, error)`; a still-`sndNew` item after
|
||||
the window stays unconfirmed rather than being reported as sent.
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
status, error = current, ""
|
||||
while True:
|
||||
try:
|
||||
messages = self.daemon.request_chat_history(contact_id, count=20)
|
||||
except Exception:
|
||||
return status or "unknown", error
|
||||
for message in messages:
|
||||
if str(message.get("item_id")) == str(item_id):
|
||||
status = str(message.get("status") or "")
|
||||
error = str(message.get("error") or "")
|
||||
if status in SEND_TERMINAL_STATUSES:
|
||||
return status, error
|
||||
if time.monotonic() >= deadline:
|
||||
return status or "unknown", error
|
||||
time.sleep(SEND_POLL_INTERVAL)
|
||||
|
||||
def resolve(self, recipient: str) -> str | None:
|
||||
"""A numeric id (with or without `@`), a unique local name, or a display name.
|
||||
|
||||
An explicit id always wins. Two peers can share a profile display name
|
||||
(the daemon suffixes its own local names, e.g. `pepper` / `pepper_1`),
|
||||
so a local-name or display-name match that hits several peers prefers
|
||||
the healthiest (connected, no recorded auth errors). On a 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:
|
||||
contacts = self.inbox.contacts()
|
||||
for contact in contacts:
|
||||
if contact["id"] == recipient:
|
||||
return contact["id"]
|
||||
exact = [
|
||||
c
|
||||
for c in contacts
|
||||
if c.get("local_name") == recipient or c["display_name"] == recipient
|
||||
]
|
||||
if exact:
|
||||
return self._prefer_connected(exact)
|
||||
lowered = recipient.lower()
|
||||
partial = [
|
||||
c
|
||||
for c in contacts
|
||||
if lowered in c["display_name"].lower()
|
||||
or lowered in str(c.get("local_name", "")).lower()
|
||||
]
|
||||
if len(partial) == 1:
|
||||
return partial[0]["id"]
|
||||
if partial:
|
||||
return self._prefer_connected(partial)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _prefer_connected(matches: list[dict]) -> str:
|
||||
"""Pick the healthiest peer among equally-named matches.
|
||||
|
||||
Prefer a ready connection, then a connection with no recorded auth
|
||||
errors (a stale duplicate that fails to send), and finally the first.
|
||||
"""
|
||||
|
||||
def rank(contact: dict) -> tuple[bool, bool]:
|
||||
try:
|
||||
clean = int(contact.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
clean = True
|
||||
return (bool(contact.get("connected")), clean)
|
||||
|
||||
return max(matches, key=rank)["id"]
|
||||
+360
-55
@@ -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,6 +23,17 @@ from pathlib import Path
|
||||
|
||||
from .dream import dream as run_dream
|
||||
from .codegen import CodegenClient
|
||||
from .config import (
|
||||
ConfigError,
|
||||
DEFAULT_SECRETS_FILE,
|
||||
generate_example_config,
|
||||
load_config_file,
|
||||
load_secrets,
|
||||
missing_secret_refs,
|
||||
resolve_secrets,
|
||||
validate_config,
|
||||
write_split_config,
|
||||
)
|
||||
from .console import (
|
||||
OPENCODE_BASE_URL,
|
||||
ConsoleCodegenClient,
|
||||
@@ -29,10 +41,13 @@ from .console import (
|
||||
)
|
||||
from .decisions import DecisionRequest, Option
|
||||
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
|
||||
|
||||
@@ -40,9 +55,10 @@ 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",
|
||||
@@ -50,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",
|
||||
@@ -65,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:
|
||||
@@ -111,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 (
|
||||
@@ -127,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
|
||||
|
||||
|
||||
@@ -201,14 +223,19 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
|
||||
|
||||
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
|
||||
from the per-machine `engine` knobs + the pinned refs in pins.json.
|
||||
* ``"winnow"`` — a remote `/v1/systemone` typed-decision API
|
||||
* ``"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` model is required (no default) exactly as `llm.model`/`codegen.model`
|
||||
are, so a misconfigured endpoint fails as an actionable config error.
|
||||
`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()
|
||||
@@ -219,6 +246,7 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
|
||||
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"],
|
||||
@@ -226,18 +254,42 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
|
||||
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:
|
||||
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
|
||||
@@ -247,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)),
|
||||
@@ -273,7 +325,7 @@ def build_codegen_client(config: dict) -> CodegenClient:
|
||||
)
|
||||
|
||||
|
||||
def build_llm_client(config: dict, engine):
|
||||
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
|
||||
@@ -281,6 +333,9 @@ def build_llm_client(config: dict, engine):
|
||||
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 {}
|
||||
provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
||||
@@ -291,11 +346,14 @@ def build_llm_client(config: dict, 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=_required_model(llm_cfg, "llm"),
|
||||
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)),
|
||||
@@ -327,6 +385,21 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
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
|
||||
@@ -414,6 +487,12 @@ 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
|
||||
|
||||
|
||||
@@ -451,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()
|
||||
@@ -484,16 +563,30 @@ 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) -> None:
|
||||
"""Print a scheduler reply, optionally keeping its run id visible."""
|
||||
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."""
|
||||
for reply in scheduler.run_queue():
|
||||
_print_reply(reply, show_run_id=True)
|
||||
"""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:
|
||||
@@ -538,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)
|
||||
@@ -629,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":
|
||||
@@ -647,13 +738,13 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
scheduler.busy(line[5:].strip())
|
||||
print("current process set (busy).")
|
||||
continue
|
||||
_print_reply(scheduler.submit(line))
|
||||
_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} ")
|
||||
_print_reply(scheduler.answer(answer))
|
||||
_print_reply(scheduler.answer(answer), verbosity=scheduler.verbosity)
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
_drain_queue(scheduler)
|
||||
@@ -670,7 +761,8 @@ def scripted(scheduler: Scheduler, path: str) -> int:
|
||||
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
|
||||
for row in rows:
|
||||
_print_reply(
|
||||
scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
|
||||
scheduler.submit(str(row["text"]), source=row.get("source", "scripted")),
|
||||
verbosity=scheduler.verbosity,
|
||||
)
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
@@ -682,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
|
||||
@@ -769,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
|
||||
@@ -822,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)
|
||||
|
||||
@@ -935,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")
|
||||
@@ -949,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(
|
||||
@@ -988,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
@@ -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}")
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
"""
|
||||
|
||||
+35
-10
@@ -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,8 +255,11 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
||||
with self.lock:
|
||||
try:
|
||||
body = self._read_json()
|
||||
reply = 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))
|
||||
@@ -277,11 +280,11 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
||||
with self.lock:
|
||||
try:
|
||||
body = self._read_json()
|
||||
reply = 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": reply.status, "detail": reply.text})
|
||||
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
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
+22
-2
@@ -9,7 +9,9 @@ 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 alternative lives in `semif_agent.winnow`.
|
||||
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
|
||||
@@ -40,8 +42,11 @@ class DecisionEngine(ABC):
|
||||
`llm.provider` / `codegen.provider`:
|
||||
|
||||
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
|
||||
* ``"winnow"`` — a remote ``/v1/systemone`` typed-decision API
|
||||
* ``"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
|
||||
@@ -52,6 +57,17 @@ class DecisionEngine(ABC):
|
||||
|
||||
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:
|
||||
@@ -210,6 +226,10 @@ class SemIfEngine(DecisionEngine):
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,7 +10,7 @@ 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, refusal, or runaway length — a cleanup failure
|
||||
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)
|
||||
@@ -35,18 +35,6 @@ SYSTEM_PROMPT = (
|
||||
"- If the result is already a plain sentence, return it unchanged."
|
||||
)
|
||||
|
||||
#: Leading phrases that mark a meta/refusal reply rather than a rewrite.
|
||||
_REFUSAL_PREFIXES = (
|
||||
"i cannot",
|
||||
"i can't",
|
||||
"i'm sorry",
|
||||
"i am sorry",
|
||||
"i'm unable",
|
||||
"i am unable",
|
||||
"as an ai",
|
||||
"sorry,",
|
||||
)
|
||||
|
||||
|
||||
def _clean_reply(raw: str) -> str:
|
||||
"""Normalize a model reply into one bare sentence, or "" if unusable."""
|
||||
@@ -82,7 +70,7 @@ class Humanizer:
|
||||
"""Return a grounded rewrite of `text`, or `text` unchanged.
|
||||
|
||||
Never raises: any failure (unreachable client, timeout, empty or
|
||||
unusable reply, refusal, runaway length) returns the original text.
|
||||
unusable reply, runaway length) returns the original text.
|
||||
"""
|
||||
source = (text or "").strip()
|
||||
if not self.enabled or not source:
|
||||
@@ -100,8 +88,6 @@ class Humanizer:
|
||||
cleaned = _clean_reply(raw)
|
||||
if not cleaned:
|
||||
return text
|
||||
if cleaned.lower().startswith(_REFUSAL_PREFIXES):
|
||||
return text
|
||||
if len(cleaned) > self.max_chars:
|
||||
return text
|
||||
return cleaned
|
||||
+494
-25
@@ -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
|
||||
@@ -37,28 +37,72 @@ _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]
|
||||
|
||||
#: 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 _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:
|
||||
"""Unwrap the scheduler's `"<skill>: <ok|failed> — <detail>"` summary.
|
||||
@@ -128,6 +172,20 @@ class GatewayService:
|
||||
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
|
||||
@@ -275,12 +333,55 @@ 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)
|
||||
@@ -290,6 +391,7 @@ class GatewayService:
|
||||
reply = self.scheduler.answer(msg.text)
|
||||
if self.scheduler.pending is None:
|
||||
self._pending_owner = None
|
||||
if not self._hidden(reply):
|
||||
self._reply(
|
||||
*reply_to, reply.text, kind=_reply_kind(reply.status),
|
||||
skill_ref=reply.skill_ref, result=reply.result,
|
||||
@@ -305,15 +407,16 @@ 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")
|
||||
@@ -325,6 +428,7 @@ class GatewayService:
|
||||
self._owners[reply.run_id] = reply_to
|
||||
if reply.status == "needs_input":
|
||||
self._pending_owner = reply_to
|
||||
if not self._hidden(reply):
|
||||
self._reply(
|
||||
*reply_to, reply.text, kind=_reply_kind(reply.status),
|
||||
skill_ref=reply.skill_ref, result=reply.result,
|
||||
@@ -333,12 +437,25 @@ class GatewayService:
|
||||
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
|
||||
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
|
||||
@@ -349,6 +466,17 @@ class GatewayService:
|
||||
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."""
|
||||
questions = self.scheduler.pending_questions()
|
||||
@@ -421,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:
|
||||
@@ -495,3 +633,29 @@ class GatewayService:
|
||||
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)
|
||||
)
|
||||
@@ -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,43 +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()
|
||||
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(
|
||||
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={},
|
||||
raw={"barge_in": True} if barge_in else {},
|
||||
)
|
||||
)
|
||||
if self._on_inbound is not None:
|
||||
self._on_inbound(message)
|
||||
+225
-15
@@ -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 ----
|
||||
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
+695
-304
File diff suppressed because it is too large.
Load diff
@@ -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))
|
||||
@@ -186,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":
|
||||
@@ -221,11 +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,
|
||||
}
|
||||
|
||||
@@ -281,6 +285,39 @@ def parse_send_response(resp: dict) -> dict:
|
||||
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.
|
||||
|
||||
@@ -518,6 +555,42 @@ class SimplexDaemon:
|
||||
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:
|
||||
|
||||
+105
-64
@@ -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,92 +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=(
|
||||
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{action.action_log}"
|
||||
),
|
||||
question="Did the skill achieve the user's goal?",
|
||||
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 skill carried out the request and produced a "
|
||||
"truthful result. A definitive 'nothing found' or 'nothing "
|
||||
"to do' result (empty inbox, no unread messages, no "
|
||||
"matching event) counts as success.",
|
||||
"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(
|
||||
"failure",
|
||||
"No — the request was not carried out, or the result is an "
|
||||
"error, a refusal, or an unresolved action.",
|
||||
"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:
|
||||
@@ -389,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,
|
||||
)
|
||||
+268
-89
@@ -17,6 +17,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
@@ -25,6 +26,7 @@ from .decisions import DecisionRequest, Option, Request
|
||||
from .engine import DecisionEngine
|
||||
from .llm import LLMClient
|
||||
from .log import DecisionLog
|
||||
from .speech import SpeechService
|
||||
from .timers import TimerService
|
||||
from .trace import TraceLog
|
||||
|
||||
@@ -44,10 +46,42 @@ class ActionContext:
|
||||
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,11 +614,84 @@ 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):
|
||||
@@ -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.
|
||||
@@ -1168,6 +1276,7 @@ def navigate(
|
||||
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.
|
||||
|
||||
@@ -1220,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={},
|
||||
@@ -1230,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(
|
||||
@@ -1241,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={},
|
||||
@@ -1257,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],
|
||||
)
|
||||
@@ -1332,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)
|
||||
@@ -1476,36 +1587,70 @@ def confirm_skill_fit(
|
||||
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.
|
||||
"""
|
||||
decision = DecisionRequest(
|
||||
state=(
|
||||
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=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.",
|
||||
),
|
||||
],
|
||||
)
|
||||
@@ -1519,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,
|
||||
@@ -1527,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:
|
||||
@@ -1591,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 = (
|
||||
@@ -1619,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()
|
||||
@@ -1628,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)
|
||||
@@ -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
|
||||
+29
-27
@@ -146,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 || "";
|
||||
@@ -163,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 || "";
|
||||
@@ -411,12 +411,14 @@ 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 = "queued";
|
||||
} else if (evt.kind === "dropped") {
|
||||
@@ -486,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");
|
||||
@@ -517,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 || ""}`;
|
||||
@@ -606,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();
|
||||
}
|
||||
@@ -699,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);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
scheduler.
|
||||
|
||||
Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events
|
||||
(submit, dropped, queued, dequeued, assessed, requeued, ...) live here in
|
||||
(submit, dropped, queued, dequeued, assessed, continued, ...) live here in
|
||||
`runs.jsonl`, keyed by `run_id` (the request id) so the dashboard can rebuild
|
||||
each run's flow without touching the decision-log contract. Both files are
|
||||
append-only; replays read them in order.
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
"""Recording helpers for a personal Piper TTS voice (training data only).
|
||||
|
||||
This is the neutral, stdlib-only half of the voice-training pipeline: it turns a
|
||||
list of prompts plus recorded audio into an **LJSpeech-format dataset**
|
||||
(``metadata.csv`` + ``wavs/NNNN.wav``) that ``piper.train fit`` consumes, and it
|
||||
provides the mic-check level math and the silence-endpointing loop. It knows
|
||||
nothing about the voice gateway's runtime (`semif_agent.voice_transport`) or
|
||||
about the training host.
|
||||
|
||||
Heavy deps stay lazy: numpy is imported only inside `resample_pcm16`, so
|
||||
importing this module is safe on a machine without the optional voice stack.
|
||||
`scripts/voice-record.py` is the thin CLI front end; the real capture path
|
||||
reuses `voice_transport.SoundDeviceAudio` (which resamples the device's native
|
||||
rate down to the target 22050 Hz for us).
|
||||
|
||||
Audio is mono signed 16-bit little-endian PCM throughout.
|
||||
|
||||
Dataset format note: piper's loader reads column 1 as the audio filename (looked
|
||||
up under its ``--data.audio_dir``) and the **last** column as the text, so a row
|
||||
is ``0001.wav|<sentence>`` and the wavs live in ``wavs/``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
#: The sample rate the recorder targets (Piper "medium" quality).
|
||||
SAMPLE_RATE = 22050
|
||||
BYTES_PER_SAMPLE = 2
|
||||
|
||||
#: Endpointing defaults (see `record_until_silence`).
|
||||
DEFAULT_SILENCE_MS = 800
|
||||
DEFAULT_MIN_SPEECH_MS = 150
|
||||
DEFAULT_MAX_SECONDS = 15.0
|
||||
#: int16 RMS above which a frame counts as speech (the energy VAD threshold).
|
||||
SPEECH_RMS_THRESHOLD = 200.0
|
||||
|
||||
#: An `is_speech(pcm16, sample_rate) -> bool` predicate (injected in tests).
|
||||
SpeechPredicate = Callable[[bytes, int], bool]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# prompts
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def load_prompts(path: str | Path) -> list[str]:
|
||||
"""Read one prompt per line; skip blanks and ``#`` comments."""
|
||||
lines: list[str] = []
|
||||
for raw in Path(path).read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if line and not line.startswith("#"):
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# wav io (stdlib `wave`)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def write_wav(path: str | Path, pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> None:
|
||||
"""Write mono 16-bit PCM as a WAV file (creating parent dirs)."""
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with wave.open(str(target), "wb") as handle:
|
||||
handle.setnchannels(1)
|
||||
handle.setsampwidth(BYTES_PER_SAMPLE)
|
||||
handle.setframerate(int(sample_rate))
|
||||
handle.writeframes(pcm16)
|
||||
|
||||
|
||||
def read_wav(path: str | Path) -> tuple[bytes, int]:
|
||||
"""Read a WAV file back as ``(pcm16, sample_rate)``."""
|
||||
with wave.open(str(path), "rb") as handle:
|
||||
return handle.readframes(handle.getnframes()), handle.getframerate()
|
||||
|
||||
|
||||
def resample_pcm16(pcm16: bytes, source_rate: int, target_rate: int) -> bytes:
|
||||
"""Linear-interpolate int16 PCM from `source_rate` to `target_rate`.
|
||||
|
||||
numpy is a voice-stack dependency and this is only reached by the real
|
||||
capture path, so the module stays stdlib-only on import.
|
||||
"""
|
||||
if source_rate == target_rate or not pcm16:
|
||||
return pcm16
|
||||
import numpy as np
|
||||
|
||||
source = np.frombuffer(pcm16, dtype=np.int16).astype(np.float32)
|
||||
count = int(round(len(source) * target_rate / source_rate))
|
||||
if count <= 0:
|
||||
return b""
|
||||
positions = np.linspace(0.0, len(source) - 1, count)
|
||||
resampled = np.interp(positions, np.arange(len(source)), source)
|
||||
return np.clip(resampled, -32768, 32767).astype(np.int16).tobytes()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# levels (mic check)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _samples(pcm16: bytes):
|
||||
"""Yield int16 sample values from little-endian PCM."""
|
||||
for offset in range(0, len(pcm16) - BYTES_PER_SAMPLE + 1, BYTES_PER_SAMPLE):
|
||||
yield int.from_bytes(
|
||||
pcm16[offset : offset + BYTES_PER_SAMPLE], "little", signed=True
|
||||
)
|
||||
|
||||
|
||||
def rms_int16(pcm16: bytes) -> float:
|
||||
"""Root-mean-square level of int16 PCM (0.0 for empty input)."""
|
||||
count = len(pcm16) // BYTES_PER_SAMPLE
|
||||
if count == 0:
|
||||
return 0.0
|
||||
total = sum(sample * sample for sample in _samples(pcm16))
|
||||
return math.sqrt(total / count)
|
||||
|
||||
|
||||
def peak_int16(pcm16: bytes) -> int:
|
||||
"""Peak absolute sample value of int16 PCM."""
|
||||
return max((abs(sample) for sample in _samples(pcm16)), default=0)
|
||||
|
||||
|
||||
def duration_s(pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> float:
|
||||
"""Playback duration of int16 PCM in seconds."""
|
||||
if sample_rate <= 0:
|
||||
return 0.0
|
||||
return (len(pcm16) // BYTES_PER_SAMPLE) / float(sample_rate)
|
||||
|
||||
|
||||
def level_report(pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> dict:
|
||||
"""Mic-check summary: RMS, peak, dBFS, and duration."""
|
||||
peak = peak_int16(pcm16)
|
||||
rms = rms_int16(pcm16)
|
||||
peak_dbfs = 20.0 * math.log10(peak / 32768.0) if peak > 0 else float("-inf")
|
||||
return {
|
||||
"rms": round(rms, 1),
|
||||
"peak": peak,
|
||||
"peak_dbfs": None if peak <= 0 else round(peak_dbfs, 1),
|
||||
"seconds": round(duration_s(pcm16, sample_rate), 2),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# capture loops
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _read_frame(audio, timeout: float | None):
|
||||
"""Read one frame, passing a `timeout` only if the source supports it.
|
||||
|
||||
The real `SoundDeviceAudio.read(timeout=...)` returns `None` on a stall so a
|
||||
dropped device cannot hang the loop; test doubles take no argument.
|
||||
"""
|
||||
if timeout is None:
|
||||
return audio.read()
|
||||
try:
|
||||
return audio.read(timeout)
|
||||
except TypeError:
|
||||
return audio.read()
|
||||
|
||||
|
||||
def _default_is_speech(threshold: float) -> SpeechPredicate:
|
||||
def is_speech(pcm16: bytes, sample_rate: int) -> bool:
|
||||
return rms_int16(pcm16) >= threshold
|
||||
|
||||
return is_speech
|
||||
|
||||
|
||||
def record_for(
|
||||
audio,
|
||||
*,
|
||||
sample_rate: int = SAMPLE_RATE,
|
||||
frame_ms: int = 40,
|
||||
seconds: float = 5.0,
|
||||
read_timeout: float | None = None,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
on_frame: Callable[[int, float], None] | None = None,
|
||||
) -> bytes:
|
||||
"""Read frames for `seconds` regardless of content (the mic check).
|
||||
|
||||
`audio` is any object with a blocking ``read() -> bytes | None`` (the
|
||||
`voice_transport.AudioIO` contract); a ``None`` frame ends capture early.
|
||||
`read_timeout` bounds each read so a stalled device ends capture instead of
|
||||
blocking forever.
|
||||
"""
|
||||
frames: list[bytes] = []
|
||||
started = clock()
|
||||
while True:
|
||||
pcm = _read_frame(audio, read_timeout)
|
||||
if pcm is None:
|
||||
break
|
||||
frames.append(pcm)
|
||||
if on_frame is not None:
|
||||
on_frame(len(frames), clock() - started)
|
||||
if seconds > 0 and (clock() - started) >= seconds:
|
||||
break
|
||||
return b"".join(frames)
|
||||
|
||||
|
||||
def record_until_silence(
|
||||
audio,
|
||||
*,
|
||||
sample_rate: int = SAMPLE_RATE,
|
||||
frame_ms: int = 40,
|
||||
max_seconds: float = DEFAULT_MAX_SECONDS,
|
||||
silence_ms: int = DEFAULT_SILENCE_MS,
|
||||
min_speech_ms: int = DEFAULT_MIN_SPEECH_MS,
|
||||
threshold: float = SPEECH_RMS_THRESHOLD,
|
||||
is_speech: SpeechPredicate | None = None,
|
||||
read_timeout: float | None = None,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
on_frame: Callable[[int, int], None] | None = None,
|
||||
) -> bytes:
|
||||
"""Accumulate frames until trailing silence or `max_seconds`.
|
||||
|
||||
Returns the captured PCM, or ``b""`` when less than `min_speech_ms` of
|
||||
speech was heard (a false start / silence). `is_speech` defaults to an int16
|
||||
RMS threshold; tests inject a scripted predicate. `read_timeout` bounds each
|
||||
read so a stalled/dropped device ends the take instead of hanging.
|
||||
"""
|
||||
predicate = is_speech or _default_is_speech(threshold)
|
||||
frames: list[bytes] = []
|
||||
speech_ms = 0
|
||||
trailing_silence_ms = 0
|
||||
started = clock()
|
||||
while True:
|
||||
pcm = _read_frame(audio, read_timeout)
|
||||
if pcm is None:
|
||||
break
|
||||
frames.append(pcm)
|
||||
if predicate(pcm, sample_rate):
|
||||
speech_ms += frame_ms
|
||||
trailing_silence_ms = 0
|
||||
else:
|
||||
trailing_silence_ms += frame_ms
|
||||
if on_frame is not None:
|
||||
on_frame(speech_ms, trailing_silence_ms)
|
||||
if speech_ms >= min_speech_ms and trailing_silence_ms >= silence_ms:
|
||||
break
|
||||
if max_seconds > 0 and (clock() - started) >= max_seconds:
|
||||
break
|
||||
if speech_ms < min_speech_ms:
|
||||
return b""
|
||||
return b"".join(frames)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# dataset on disk
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class DatasetStore:
|
||||
"""An LJSpeech-format dataset directory: ``metadata.csv`` + ``wavs/``.
|
||||
|
||||
Survives across runs (the recorder resumes where it left off): the existing
|
||||
``metadata.csv`` is parsed on construction and rewritten (sorted by id)
|
||||
after every save.
|
||||
"""
|
||||
|
||||
def __init__(self, out_dir: str | Path, sample_rate: int = SAMPLE_RATE):
|
||||
self.out = Path(out_dir)
|
||||
self.sample_rate = int(sample_rate)
|
||||
self.wavs = self.out / "wavs"
|
||||
self.metadata = self.out / "metadata.csv"
|
||||
self._entries: dict[str, str] = {}
|
||||
self._load()
|
||||
|
||||
# ---- loading ----
|
||||
|
||||
def _load(self) -> None:
|
||||
if not self.metadata.is_file():
|
||||
return
|
||||
for raw in self.metadata.read_text(encoding="utf-8").splitlines():
|
||||
if "|" not in raw:
|
||||
continue
|
||||
uid, text = raw.split("|", 1)
|
||||
uid = uid.strip()
|
||||
if uid.endswith(".wav"):
|
||||
uid = uid[:-4] # metadata stores the filename; ids stay bare
|
||||
if uid:
|
||||
self._entries[uid] = text.strip()
|
||||
|
||||
# ---- queries ----
|
||||
|
||||
@property
|
||||
def entries(self) -> dict[str, str]:
|
||||
return dict(self._entries)
|
||||
|
||||
def ids(self) -> set[str]:
|
||||
return set(self._entries)
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._entries)
|
||||
|
||||
def next_id(self) -> str:
|
||||
"""The lowest zero-padded 4-digit id not yet recorded."""
|
||||
index = 1
|
||||
while f"{index:04d}" in self._entries:
|
||||
index += 1
|
||||
return f"{index:04d}"
|
||||
|
||||
def wav_path(self, uid: str) -> Path:
|
||||
return self.wavs / f"{uid}.wav"
|
||||
|
||||
# ---- mutation ----
|
||||
|
||||
def save(self, uid: str, text: str, pcm16: bytes) -> Path:
|
||||
"""Write ``wavs/<uid>.wav`` and record ``<uid>.wav|<text>``."""
|
||||
uid = str(uid)
|
||||
path = self.wav_path(uid)
|
||||
write_wav(path, pcm16, self.sample_rate)
|
||||
self._entries[uid] = text.strip()
|
||||
self.rewrite()
|
||||
return path
|
||||
|
||||
def remove(self, uid: str) -> bool:
|
||||
"""Drop a recording: delete ``wavs/<uid>.wav`` and its metadata row.
|
||||
|
||||
Returns whether the id was present. Used by the verifier's ``--prune`` to
|
||||
take a bad take out of the dataset so the recorder re-records it (the
|
||||
recorder resumes by id). The caller may move the wav aside first; the
|
||||
unlink here tolerates it already being gone.
|
||||
"""
|
||||
uid = str(uid)
|
||||
if uid not in self._entries:
|
||||
return False
|
||||
try:
|
||||
self.wav_path(uid).unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
del self._entries[uid]
|
||||
self.rewrite()
|
||||
return True
|
||||
|
||||
def rewrite(self) -> None:
|
||||
self.out.mkdir(parents=True, exist_ok=True)
|
||||
lines = [f"{uid}.wav|{self._entries[uid]}" for uid in sorted(self._entries)]
|
||||
self.metadata.write_text(
|
||||
"\n".join(lines) + ("\n" if lines else ""), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# fidelity check (transcript vs. prompt)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: Statuses the verifier flags as needing a re-record.
|
||||
BAD_STATUSES = frozenset({"missing", "empty", "mismatch"})
|
||||
|
||||
_WORD_RE = re.compile(r"[a-z0-9]+(?:'[a-z]+)?")
|
||||
|
||||
#: Number words -> digits, so Whisper's "2 plus 7 is less than 10" matches a
|
||||
#: prompt that spells them out. Comparison-only; never used for output.
|
||||
_NUMBER_WORDS = {
|
||||
"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4",
|
||||
"five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9",
|
||||
"ten": "10", "eleven": "11", "twelve": "12", "thirteen": "13",
|
||||
"fourteen": "14", "fifteen": "15", "sixteen": "16", "seventeen": "17",
|
||||
"eighteen": "18", "nineteen": "19", "twenty": "20", "thirty": "30",
|
||||
"forty": "40", "fifty": "50", "sixty": "60", "seventy": "70",
|
||||
"eighty": "80", "ninety": "90",
|
||||
}
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
"""Lowercase, strip punctuation, collapse whitespace, digitize number words.
|
||||
|
||||
Whisper's output differs from the prompt in capitalization, punctuation,
|
||||
spacing, and (for numbers) digits-vs-words; this reduces both to a comparable
|
||||
word sequence. Apostrophes are kept so ``it's`` does not silently become
|
||||
``its``.
|
||||
"""
|
||||
words = _WORD_RE.findall(text.lower())
|
||||
return " ".join(_NUMBER_WORDS.get(word, word) for word in words)
|
||||
|
||||
|
||||
def word_tokens(text: str) -> list[str]:
|
||||
"""The normalized word sequence of `text`."""
|
||||
return normalize_text(text).split()
|
||||
|
||||
|
||||
def word_error_rate(reference: str, hypothesis: str) -> float:
|
||||
"""Word-level Levenshtein distance divided by the reference word count.
|
||||
|
||||
0.0 is an exact match; 1.0 means every reference word was wrong (or the
|
||||
hypothesis was empty). An empty reference scores 0.0 for an empty
|
||||
hypothesis, else 1.0.
|
||||
"""
|
||||
ref = word_tokens(reference)
|
||||
hyp = word_tokens(hypothesis)
|
||||
if not ref:
|
||||
return 0.0 if not hyp else 1.0
|
||||
previous = list(range(len(hyp) + 1))
|
||||
for i, ref_word in enumerate(ref, start=1):
|
||||
current = [i]
|
||||
for j, hyp_word in enumerate(hyp, start=1):
|
||||
substitution = previous[j - 1] + (0 if ref_word == hyp_word else 1)
|
||||
current.append(min(previous[j] + 1, current[j - 1] + 1, substitution))
|
||||
previous = current
|
||||
return previous[-1] / len(ref)
|
||||
|
||||
|
||||
def compare_transcript(
|
||||
reference: str,
|
||||
hypothesis: str,
|
||||
max_wer: float = 0.3,
|
||||
review_wer: float | None = None,
|
||||
) -> dict:
|
||||
"""Classify a Whisper transcript against the prompt it was read from.
|
||||
|
||||
Returns ``{"status", "wer", "similarity", "ref_words", "hyp_words"}`` where
|
||||
status is one of:
|
||||
|
||||
- ``empty`` — Whisper heard nothing (a silent / false-start take);
|
||||
- ``mismatch`` — word error rate above `max_wer` (a wrong or truncated take);
|
||||
- ``review`` — between `review_wer` and `max_wer`: worth a listen, because
|
||||
Whisper's own spelling/number variants live in this band (e.g. "two plus
|
||||
seven" -> "2 plus 7");
|
||||
- ``ok`` — below `review_wer` (or below `max_wer` when no review band).
|
||||
|
||||
`similarity` is ``1 - min(wer, 1)``, a friendlier 0..1 score.
|
||||
"""
|
||||
ref = word_tokens(reference)
|
||||
hyp = word_tokens(hypothesis)
|
||||
if not hyp:
|
||||
return {
|
||||
"status": "empty",
|
||||
"wer": 1.0,
|
||||
"similarity": 0.0,
|
||||
"ref_words": len(ref),
|
||||
"hyp_words": 0,
|
||||
}
|
||||
wer = word_error_rate(reference, hypothesis)
|
||||
if wer > max_wer:
|
||||
status = "mismatch"
|
||||
elif review_wer is not None and wer >= review_wer:
|
||||
status = "review"
|
||||
else:
|
||||
status = "ok"
|
||||
return {
|
||||
"status": status,
|
||||
"wer": round(wer, 3),
|
||||
"similarity": round(max(0.0, 1.0 - min(wer, 1.0)), 3),
|
||||
"ref_words": len(ref),
|
||||
"hyp_words": len(hyp),
|
||||
}
|
||||
+698
-58
@@ -15,11 +15,14 @@ Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
|
||||
resampling is done in the loop.
|
||||
|
||||
Design notes:
|
||||
- **Half-duplex.** Capture frames are discarded while a reply is being spoken,
|
||||
so the agent never transcribes its own voice (no barge-in yet).
|
||||
- **Follow-up window.** After a reply, the next utterance is accepted without
|
||||
the wake word for `follow_up_window_s`, so answering a question is
|
||||
conversational.
|
||||
- **Half-duplex by default, barge-in optional.** Capture frames are normally
|
||||
discarded while a reply is being spoken, so the agent never transcribes its
|
||||
own voice. With barge-in enabled (`barge_in.enabled`), the wake word is still
|
||||
scored during playback: the user can interrupt a spoken reply, the playback
|
||||
is aborted, and the following command is captured and handed to the front end
|
||||
(which decides whether it is a stop or a new request). Speech is muted while
|
||||
the interrupt command is captured and handled, so the interrupted reply does
|
||||
not resume over the user.
|
||||
- The engine interfaces are plain classes so tests can inject fakes and drive
|
||||
the loop without hardware or the optional packages.
|
||||
"""
|
||||
@@ -51,6 +54,28 @@ _REQUIRED_MODULES: tuple[tuple[str, str], ...] = (
|
||||
("onnxruntime", "onnxruntime"),
|
||||
)
|
||||
|
||||
#: The one package a transcribe-only front end needs (see
|
||||
#: `check_transcription_requirements`). `faster-whisper` bundles PyAV, whose
|
||||
#: ffmpeg decodes an incoming Opus/OGG voice message to PCM.
|
||||
_TRANSCRIBE_MODULES: tuple[tuple[str, str], ...] = (
|
||||
("faster_whisper", "faster-whisper"),
|
||||
)
|
||||
|
||||
#: The packages a voice-reply front end needs (see
|
||||
#: `check_synthesis_requirements`): Piper for text-to-speech and PyAV for the
|
||||
#: Opus/OGG container a Sideband HQ push-to-talk reply rides in. No microphone,
|
||||
#: wake word, or transcription is implied — a headless host can synthesize a
|
||||
#: reply without the hardware voice stack.
|
||||
_SYNTHESIS_MODULES: tuple[tuple[str, str], ...] = (
|
||||
("piper", "piper-tts"),
|
||||
("av", "av (PyAV, Opus/OGG encoding)"),
|
||||
)
|
||||
|
||||
#: Sideband's HQ push-to-talk container (`LXMF.AM_OPUS_OGG`) is 48 kHz mono
|
||||
#: OGG/Opus; a reply's PCM is resampled to that rate before encoding.
|
||||
OPUS_OGG_SAMPLE_RATE = 48000
|
||||
OPUS_OGG_BITRATE = 24000
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Engine interfaces (fakes are injected in tests)
|
||||
@@ -86,6 +111,15 @@ class Transcriber:
|
||||
def transcribe(self, pcm16: bytes) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
def transcribe_bytes(self, data: bytes) -> str:
|
||||
"""Transcribe an encoded audio container (e.g. OGG/Opus) to text.
|
||||
|
||||
Default: not supported. `WhisperTranscriber` overrides it so a received
|
||||
voice message (a Sideband PTT Opus/OGG payload) is transcribed without a
|
||||
separate decode step.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
@@ -103,15 +137,17 @@ class Synthesizer:
|
||||
class AudioIO:
|
||||
"""Mic capture and speaker playback.
|
||||
|
||||
`read()` blocks for one frame and returns its bytes, or `None` once the
|
||||
input is closed (the loop exits on `None`). `open_output`/`write` may be
|
||||
called at any sample rate the synthesizer produced.
|
||||
`read(timeout)` returns one frame's bytes; with a `timeout` it returns
|
||||
`b""` when no frame arrived in time, and `None` once the input is closed
|
||||
(the loop exits on `None`). The timeout is how the loop detects a stalled
|
||||
capture stream and recovers from it. `open_output`/`write` may be called at
|
||||
any sample rate the synthesizer produced.
|
||||
"""
|
||||
|
||||
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def read(self) -> bytes | None:
|
||||
def read(self, timeout: float | None = None) -> bytes | None:
|
||||
raise NotImplementedError
|
||||
|
||||
def open_output(self, sample_rate: int, device: str = "") -> None:
|
||||
@@ -120,6 +156,17 @@ class AudioIO:
|
||||
def write(self, pcm16: bytes, sample_rate: int) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
|
||||
"""Play PCM, returning `False` if aborted early via `stop_event`.
|
||||
|
||||
The default plays the whole buffer in one `write`. The real device
|
||||
overrides this to stream in small chunks so a barge-in stops the reply
|
||||
promptly instead of after the whole buffer; a fake that only implements
|
||||
`write` still plays through here.
|
||||
"""
|
||||
self.write(pcm16, sample_rate)
|
||||
return True
|
||||
|
||||
def flush(self) -> None:
|
||||
"""Drop any buffered capture frames (called after speaking to clear echo)."""
|
||||
|
||||
@@ -226,13 +273,21 @@ class WhisperTranscriber(Transcriber):
|
||||
device: str = "cpu",
|
||||
compute_type: str = "int8",
|
||||
language: str = "en",
|
||||
beam_size: int = 1,
|
||||
vad_filter: bool = True,
|
||||
):
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
self.language = str(language or "en") or None
|
||||
self.beam_size = int(beam_size)
|
||||
self.vad_filter = bool(vad_filter)
|
||||
self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"),
|
||||
compute_type=str(compute_type or "int8"))
|
||||
|
||||
@staticmethod
|
||||
def _join(segments) -> str:
|
||||
return " ".join(segment.text.strip() for segment in segments).strip()
|
||||
|
||||
def transcribe(self, pcm16: bytes) -> str:
|
||||
import numpy as np
|
||||
|
||||
@@ -240,10 +295,28 @@ class WhisperTranscriber(Transcriber):
|
||||
segments, _info = self._model.transcribe(
|
||||
audio,
|
||||
language=self.language,
|
||||
beam_size=1,
|
||||
vad_filter=True,
|
||||
beam_size=self.beam_size,
|
||||
vad_filter=self.vad_filter,
|
||||
)
|
||||
return " ".join(segment.text.strip() for segment in segments).strip()
|
||||
return self._join(segments)
|
||||
|
||||
def transcribe_bytes(self, data: bytes) -> str:
|
||||
"""Transcribe an encoded audio container (e.g. OGG/Opus).
|
||||
|
||||
faster-whisper decodes the container to 16 kHz mono internally via PyAV
|
||||
(its own bundled ffmpeg), so a PTT voice message's Opus/OGG payload is
|
||||
transcribed directly — no separate decode step and no system ffmpeg.
|
||||
`data` is the raw container bytes.
|
||||
"""
|
||||
import io
|
||||
|
||||
segments, _info = self._model.transcribe(
|
||||
io.BytesIO(bytes(data)),
|
||||
language=self.language,
|
||||
beam_size=self.beam_size,
|
||||
vad_filter=self.vad_filter,
|
||||
)
|
||||
return self._join(segments)
|
||||
|
||||
|
||||
class PiperSynthesizer(Synthesizer):
|
||||
@@ -328,6 +401,43 @@ def _tone_pcm(frequency: float, duration_ms: int, sample_rate: int, volume: floa
|
||||
return bytes(frames)
|
||||
|
||||
|
||||
def _tone_sequence(notes, sample_rate: int, volume: float, gap_ms: int = 0) -> bytes:
|
||||
"""Concatenate `_tone_pcm` notes (each `[frequency_hz, duration_ms]`).
|
||||
|
||||
A short inter-note silence (`gap_ms`) makes a multi-note chime read as
|
||||
distinct notes rather than one warble. Each note already fades in and out,
|
||||
so there is no click at a boundary whether or not a gap is used.
|
||||
"""
|
||||
gap = b"\x00\x00" * int(sample_rate * max(0, gap_ms) / 1000)
|
||||
parts: list[bytes] = []
|
||||
for frequency, duration in notes:
|
||||
tone = _tone_pcm(frequency, duration, sample_rate, volume)
|
||||
if not tone:
|
||||
continue
|
||||
if parts and gap:
|
||||
parts.append(gap)
|
||||
parts.append(tone)
|
||||
return b"".join(parts)
|
||||
|
||||
|
||||
def _parse_notes(value) -> list[tuple[float, int]]:
|
||||
"""Parse a cue note list (`[[frequency_hz, duration_ms], ...]`).
|
||||
|
||||
Bad entries are dropped rather than raising: this is cosmetic audio config,
|
||||
not a contract. An empty/absent list yields `[]` (the single-beep fallback).
|
||||
"""
|
||||
notes: list[tuple[float, int]] = []
|
||||
for item in value or []:
|
||||
try:
|
||||
frequency, duration = item
|
||||
frequency, duration = float(frequency), int(duration)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if frequency > 0 and duration > 0:
|
||||
notes.append((frequency, duration))
|
||||
return notes
|
||||
|
||||
|
||||
def _device_arg(value):
|
||||
"""Coerce a config device value to a PortAudio argument.
|
||||
|
||||
@@ -435,8 +545,20 @@ class SoundDeviceAudio(AudioIO):
|
||||
except queue.Full:
|
||||
pass # a slow consumer (STT) drops stale frames; the mic is real-time
|
||||
|
||||
def read(self) -> bytes | None:
|
||||
def read(self, timeout: float | None = None) -> bytes | None:
|
||||
"""Block for the next frame (or up to `timeout` seconds).
|
||||
|
||||
Returns `None` once the input is closed (the sentinel `close()` puts on
|
||||
the queue), or `b""` when a `timeout` elapses with no frame — so a
|
||||
caller that passes a timeout can detect a stalled capture stream
|
||||
instead of blocking forever.
|
||||
"""
|
||||
if timeout is None:
|
||||
return self._frames.get()
|
||||
try:
|
||||
return self._frames.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return b""
|
||||
|
||||
def open_output(self, sample_rate: int, device: str = "") -> None:
|
||||
pass # a raw stream is opened per utterance in `write`
|
||||
@@ -457,6 +579,40 @@ class SoundDeviceAudio(AudioIO):
|
||||
) as stream:
|
||||
stream.write(pcm16)
|
||||
|
||||
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
|
||||
"""Stream PCM in small chunks so a barge-in can abort playback.
|
||||
|
||||
A single `write` of the whole buffer blocks until the device drains it,
|
||||
so an interrupt could only take effect after the reply had finished. The
|
||||
buffer is played in ~50 ms chunks instead, checking `stop_event` between
|
||||
them; on a stop the stream is aborted (discarding what is still buffered)
|
||||
and `False` is returned. One output stream is opened for the whole
|
||||
buffer, so the chunks play gaplessly.
|
||||
"""
|
||||
import sounddevice as sd
|
||||
|
||||
rate = self.output_sample_rate or self._device_rate(
|
||||
self.output_device, "output"
|
||||
)
|
||||
if rate != int(sample_rate):
|
||||
pcm16 = _resample_pcm16(pcm16, int(sample_rate), rate)
|
||||
chunk = max(BYTES_PER_SAMPLE, int(rate * 0.05) * BYTES_PER_SAMPLE) # 50 ms
|
||||
with sd.RawOutputStream(
|
||||
samplerate=rate,
|
||||
channels=1,
|
||||
dtype="int16",
|
||||
device=self.output_device,
|
||||
) as stream:
|
||||
for offset in range(0, len(pcm16), chunk):
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
try:
|
||||
stream.abort()
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
stream.write(pcm16[offset : offset + chunk])
|
||||
return True
|
||||
|
||||
def flush(self) -> None:
|
||||
try:
|
||||
while not self._frames.empty():
|
||||
@@ -520,42 +676,245 @@ def _build_vad(cfg: dict) -> VadGate:
|
||||
return EnergyVadGate(threshold=float(vad_cfg.get("energy_threshold", 200.0)))
|
||||
|
||||
|
||||
def build_engines(cfg: dict, trace=None) -> VoiceEngines:
|
||||
"""Construct the real engine bundle from a `gateway.voice` config block."""
|
||||
wake_cfg = cfg.get("wake", {}) or {}
|
||||
stt_cfg = cfg.get("stt", {}) or {}
|
||||
tts_cfg = cfg.get("tts", {}) or {}
|
||||
audio_cfg = cfg.get("audio", {}) or {}
|
||||
def build_transcriber(cfg: dict) -> Transcriber:
|
||||
"""Build just the speech-to-text engine from an `stt` config block.
|
||||
|
||||
wake_model = resolve_model_path(
|
||||
str(wake_cfg.get("model", "hey_mycroft") or ""),
|
||||
str(wake_cfg.get("model_dir", "") or ""),
|
||||
(".onnx", ".tflite"),
|
||||
`build_engines` also needs a microphone, a wake word, and TTS; a headless
|
||||
front end that only transcribes received audio — the LXMF gateway handling a
|
||||
Sideband PTT voice message — uses this instead, so it needs only
|
||||
`faster-whisper` and none of the hardware voice stack.
|
||||
"""
|
||||
stt_cfg = (cfg or {}).get("stt", {}) or {}
|
||||
return WhisperTranscriber(
|
||||
model=str(stt_cfg.get("model", "base.en") or "base.en"),
|
||||
device=str(stt_cfg.get("device", "cpu") or "cpu"),
|
||||
compute_type=str(stt_cfg.get("compute_type", "int8") or "int8"),
|
||||
language=str(stt_cfg.get("language", "en") or "en"),
|
||||
)
|
||||
|
||||
|
||||
def check_transcription_requirements() -> tuple[bool, str | None]:
|
||||
"""Return `(ok, install_hint)` for the transcribe-only path.
|
||||
|
||||
Unlike `VoiceDaemon.check_requirements` this needs no microphone, wake word,
|
||||
or TTS — only `faster-whisper` — so a headless host can transcribe incoming
|
||||
voice messages without the hardware voice stack. Never raises.
|
||||
"""
|
||||
missing = []
|
||||
for module, hint in _TRANSCRIBE_MODULES:
|
||||
try:
|
||||
importlib.import_module(module)
|
||||
except Exception:
|
||||
missing.append(hint)
|
||||
if missing:
|
||||
return False, (
|
||||
"install the transcription stack (requirements/transcribe.txt): "
|
||||
+ "; ".join(missing)
|
||||
)
|
||||
return True, None
|
||||
|
||||
|
||||
def check_synthesis_requirements() -> tuple[bool, str | None]:
|
||||
"""Return `(ok, install_hint)` for the voice-reply (Piper) path.
|
||||
|
||||
A voice reply needs Piper (text-to-speech) and PyAV (to encode the
|
||||
synthesized PCM into the Opus/OGG container a Sideband HQ push-to-talk
|
||||
message rides in). Neither a microphone, a wake word, nor transcription is
|
||||
implied — the headless counterpart of `VoiceDaemon.check_requirements`.
|
||||
Never raises.
|
||||
"""
|
||||
missing = []
|
||||
for module, hint in _SYNTHESIS_MODULES:
|
||||
try:
|
||||
importlib.import_module(module)
|
||||
except Exception:
|
||||
missing.append(hint)
|
||||
if missing:
|
||||
return False, (
|
||||
"install the voice-reply stack (requirements/tts.txt): "
|
||||
+ "; ".join(missing)
|
||||
)
|
||||
return True, None
|
||||
|
||||
|
||||
def pcm_to_opus_ogg(
|
||||
pcm16: bytes, sample_rate: int, bitrate: int = OPUS_OGG_BITRATE
|
||||
) -> bytes:
|
||||
"""Encode 16-bit mono PCM into an OGG/Opus container (Sideband HQ PTT).
|
||||
|
||||
A received voice message is Opus/OGG (`LXMF.AM_OPUS_OGG`), so a voice reply
|
||||
is encoded to the same container: the PCM is resampled to 48 kHz (Opus's
|
||||
fullband rate) with PyAV's `AudioResampler` and muxed into OGG by its
|
||||
bundled libopus. Returns `b""` on any failure (the caller falls back to a
|
||||
text reply) — never raises, so a missing PyAV degrades gracefully.
|
||||
"""
|
||||
if not pcm16 or len(pcm16) < BYTES_PER_SAMPLE:
|
||||
return b""
|
||||
try:
|
||||
import av
|
||||
except Exception:
|
||||
return b""
|
||||
try:
|
||||
rate = int(sample_rate or OPUS_OGG_SAMPLE_RATE)
|
||||
source = av.AudioFrame(
|
||||
format="s16", layout="mono", samples=len(pcm16) // BYTES_PER_SAMPLE
|
||||
)
|
||||
source.sample_rate = rate
|
||||
source.planes[0].update(pcm16)
|
||||
if rate == OPUS_OGG_SAMPLE_RATE:
|
||||
frames = [source]
|
||||
else:
|
||||
resampler = av.AudioResampler(
|
||||
format="s16", layout="mono", rate=OPUS_OGG_SAMPLE_RATE
|
||||
)
|
||||
# PyAV's `resample` returns a list of frames (older versions a single
|
||||
# frame or None); normalize both shapes.
|
||||
frames = resampler.resample(source)
|
||||
if not isinstance(frames, list):
|
||||
frames = [frames]
|
||||
tail = resampler.resample(None)
|
||||
frames += tail if isinstance(tail, list) else [tail]
|
||||
frames = [frame for frame in frames if frame is not None]
|
||||
if not frames:
|
||||
return b""
|
||||
buffer = io.BytesIO()
|
||||
container = av.open(buffer, mode="w", format="ogg")
|
||||
stream = container.add_stream("libopus", rate=OPUS_OGG_SAMPLE_RATE)
|
||||
stream.layout = "mono"
|
||||
stream.bit_rate = int(bitrate or OPUS_OGG_BITRATE)
|
||||
try: # voice-optimised mode (Sideband's HQ PTT uses the voice profile)
|
||||
stream.codec_context.options = {"application": "voip"}
|
||||
except Exception:
|
||||
pass
|
||||
for frame in frames:
|
||||
for packet in stream.encode(frame):
|
||||
container.mux(packet)
|
||||
for packet in stream.encode(None):
|
||||
container.mux(packet)
|
||||
container.close()
|
||||
return buffer.getvalue()
|
||||
except Exception:
|
||||
return b""
|
||||
|
||||
|
||||
def check_codec2_requirements() -> tuple[bool, str | None]:
|
||||
"""Return `(ok, install_hint)` for Codec2 voice-message decoding.
|
||||
|
||||
Codec2 (Sideband's non-HQ push-to-talk) needs the optional `pycodec2`
|
||||
bindings, which compile against the system `libcodec2`. Never raises.
|
||||
"""
|
||||
try:
|
||||
importlib.import_module("pycodec2")
|
||||
except Exception:
|
||||
return False, (
|
||||
"pip install pycodec2 (needs the system libcodec2: "
|
||||
"apt install libcodec2-dev)"
|
||||
)
|
||||
return True, None
|
||||
|
||||
|
||||
def decode_codec2(data: bytes, rate: int) -> bytes | None:
|
||||
"""Decode a raw Codec2 bitstream to 8 kHz mono int16 PCM.
|
||||
|
||||
`rate` is the codec2 bitrate in bits/s (700..3200). Returns None when the
|
||||
optional `pycodec2` bindings (or the mode) are unavailable, so the caller
|
||||
reports the message unsupported rather than guessing. Frames shorter than a
|
||||
full codec frame are dropped; decoding mirrors Sideband's per-frame loop.
|
||||
"""
|
||||
if not data or not rate:
|
||||
return None
|
||||
try:
|
||||
import pycodec2
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
codec = pycodec2.Codec2(int(rate))
|
||||
bytes_per_frame = int(codec.bytes_per_frame())
|
||||
except Exception:
|
||||
return None
|
||||
if bytes_per_frame <= 0:
|
||||
return None
|
||||
try:
|
||||
import numpy as np
|
||||
except Exception:
|
||||
return None
|
||||
frames = [
|
||||
np.asarray(codec.decode(data[offset : offset + bytes_per_frame]), dtype=np.int16)
|
||||
for offset in range(0, len(data) - bytes_per_frame + 1, bytes_per_frame)
|
||||
]
|
||||
if not frames:
|
||||
return None
|
||||
return np.concatenate(frames).astype(np.int16).tobytes()
|
||||
|
||||
|
||||
def pcm_to_wav(pcm16: bytes, sample_rate: int, channels: int = 1) -> bytes:
|
||||
"""Wrap raw int16 PCM in a minimal in-memory WAV container (stdlib).
|
||||
|
||||
Lets a non-container payload (Codec2 frames decoded to 8 kHz PCM) ride the
|
||||
same transcription path as an Opus/OGG message: faster-whisper's PyAV decodes
|
||||
the WAV and resamples it to 16 kHz, so the boundary needs no manual resample.
|
||||
"""
|
||||
import io
|
||||
import wave
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with wave.open(buffer, "wb") as wav:
|
||||
wav.setnchannels(int(channels))
|
||||
wav.setsampwidth(2)
|
||||
wav.setframerate(int(sample_rate))
|
||||
wav.writeframes(pcm16)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _build_piper(tts_cfg: dict) -> PiperSynthesizer:
|
||||
"""Build the Piper synthesizer from a `tts` config block (shared by the
|
||||
microphone front end and the headless LXMF voice-reply path)."""
|
||||
tts_voice = resolve_model_path(
|
||||
str(tts_cfg.get("voice", "") or ""),
|
||||
str(tts_cfg.get("voice_dir", "") or ""),
|
||||
(".onnx",),
|
||||
)
|
||||
return VoiceEngines(
|
||||
wake=OpenWakeWordDetector(
|
||||
wake_model,
|
||||
threshold=float(wake_cfg.get("threshold", 0.5)),
|
||||
inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
|
||||
),
|
||||
vad=_build_vad(cfg),
|
||||
stt=WhisperTranscriber(
|
||||
model=str(stt_cfg.get("model", "base.en") or "base.en"),
|
||||
device=str(stt_cfg.get("device", "cpu") or "cpu"),
|
||||
compute_type=str(stt_cfg.get("compute_type", "int8") or "int8"),
|
||||
language=str(stt_cfg.get("language", "en") or "en"),
|
||||
),
|
||||
tts=PiperSynthesizer(
|
||||
return PiperSynthesizer(
|
||||
tts_voice,
|
||||
speaker_id=int(tts_cfg.get("speaker_id", 0) or 0),
|
||||
length_scale=float(tts_cfg.get("length_scale", 1.0) or 1.0),
|
||||
volume=float(tts_cfg.get("volume", 1.0) or 1.0),
|
||||
)
|
||||
|
||||
|
||||
def build_synthesizer(cfg: dict) -> Synthesizer:
|
||||
"""Build just the text-to-speech engine from a `tts` config block.
|
||||
|
||||
`build_engines` also needs a microphone, a wake word, and speech-to-text; a
|
||||
headless front end that only synthesizes a reply — the LXMF gateway
|
||||
answering a Sideband push-to-talk voice message with a Piper voice message —
|
||||
uses this instead, so it needs only `piper-tts` (and PyAV to encode the
|
||||
reply), none of the hardware voice stack.
|
||||
"""
|
||||
tts_cfg = (cfg or {}).get("tts", {}) or {}
|
||||
return _build_piper(tts_cfg)
|
||||
|
||||
|
||||
def build_engines(cfg: dict, trace=None) -> VoiceEngines:
|
||||
"""Construct the real engine bundle from a `gateway.voice` config block."""
|
||||
wake_cfg = cfg.get("wake", {}) or {}
|
||||
tts_cfg = cfg.get("tts", {}) or {}
|
||||
audio_cfg = cfg.get("audio", {}) or {}
|
||||
|
||||
wake_model = resolve_model_path(
|
||||
str(wake_cfg.get("model", "hey_computer") or ""),
|
||||
str(wake_cfg.get("model_dir", "") or ""),
|
||||
(".onnx", ".tflite"),
|
||||
)
|
||||
return VoiceEngines(
|
||||
wake=OpenWakeWordDetector(
|
||||
wake_model,
|
||||
threshold=float(wake_cfg.get("threshold", 0.2)),
|
||||
inference_framework=str(wake_cfg.get("inference_framework", "onnx")),
|
||||
),
|
||||
vad=_build_vad(cfg),
|
||||
stt=build_transcriber(cfg),
|
||||
tts=_build_piper(tts_cfg),
|
||||
audio=SoundDeviceAudio(
|
||||
input_device=str(audio_cfg.get("input_device", "") or ""),
|
||||
output_device=str(audio_cfg.get("output_device", "") or ""),
|
||||
@@ -581,21 +940,52 @@ class VoiceDaemon:
|
||||
"""
|
||||
|
||||
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
|
||||
name: str = "voice"):
|
||||
name: str = "voice", input_ready=None, on_barge_in=None):
|
||||
cfg = cfg or {}
|
||||
self.config = cfg
|
||||
self.trace = trace
|
||||
self.name = name
|
||||
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.5))
|
||||
#: Optional predicate: whether a new command may start now. While it
|
||||
#: returns False the wake word is ignored (the scheduler's single slot
|
||||
#: is still running the current request), so a second command cannot be
|
||||
#: started before the first reaches a result. None = always ready.
|
||||
self.input_ready = input_ready
|
||||
#: Optional callback the loop invokes around a barge-in: `True` when the
|
||||
#: wake word is heard over a spoken reply (playback aborted, listening
|
||||
#: begins), `False` once that listening session ends. The front end uses
|
||||
#: it to classify the following utterance as an interrupt.
|
||||
self.on_barge_in = on_barge_in
|
||||
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
|
||||
#: After the wake word, how long to wait for the command's speech to
|
||||
#: begin before giving up (a natural pause after "hey <word>" — e.g.
|
||||
#: waiting for the cue beep — must not truncate the command).
|
||||
self.listen_timeout_ms = int(float(cfg.get("listen_timeout_s", 3.0) or 0) * 1000)
|
||||
audio_cfg = cfg.get("audio", {}) or {}
|
||||
self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE)
|
||||
self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80)
|
||||
self.input_device = str(audio_cfg.get("input_device", "") or "")
|
||||
#: Capture-stream watchdog. `read_timeout_s` is how long a frame read
|
||||
#: waits before it counts as a stall; when the stream stalls
|
||||
#: continuously for `stall_timeout_s` the input is closed and reopened
|
||||
#: (a wedged PortAudio/ALSA callback otherwise blocks `read()` forever).
|
||||
#: 0 for either restores the old blocking read with no recovery.
|
||||
self.read_timeout_s = float(audio_cfg.get("read_timeout_s", 1.0) or 0.0)
|
||||
self.stall_timeout_s = float(audio_cfg.get("stall_timeout_s", 5.0) or 0.0)
|
||||
self._stall_since = 0.0
|
||||
vad_cfg = cfg.get("vad", {}) or {}
|
||||
self.vad_silence_ms = int(vad_cfg.get("silence_ms", 1000) or 1000)
|
||||
self.min_speech_ms = int(vad_cfg.get("min_speech_ms", 120) or 120)
|
||||
self.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
|
||||
self.follow_up_window = float(cfg.get("follow_up_window_s", 5.0) or 0.0)
|
||||
#: A longer silence tolerance while the utterance is still short. The
|
||||
#: wake detector can fire inside the wake phrase (the cue beep follows),
|
||||
#: so the first speech after it is the phrase's tail, not the command;
|
||||
#: a natural pause before the command must not end the capture. Once
|
||||
#: `min_command_ms` of speech is in hand, the normal `vad_silence_ms`
|
||||
#: endpoint applies (so a real command still ends promptly).
|
||||
self.min_command_ms = int(vad_cfg.get("min_command_ms", 700) or 0)
|
||||
self.initial_silence_ms = max(
|
||||
int(vad_cfg.get("initial_silence_ms", 1500) or 0), self.vad_silence_ms
|
||||
)
|
||||
self.max_speak_chars = int(cfg.get("max_speak_chars", 600) or 0)
|
||||
cue = cfg.get("cue", {}) or {}
|
||||
self.cue_enabled = bool(cue.get("enabled", True))
|
||||
@@ -604,6 +994,24 @@ class VoiceDaemon:
|
||||
self.cue_volume = float(cue.get("volume", 0.25) or 0)
|
||||
self.cue_submit_frequency = float(cue.get("submit_frequency", 0) or 0)
|
||||
self.cue_submit_duration_ms = int(cue.get("submit_duration_ms", 100) or 0)
|
||||
#: A short multi-note "bling" played once a transcription lands (each
|
||||
#: entry `[frequency_hz, duration_ms]`). When empty, the single
|
||||
#: `submit_frequency` beep is used instead (silent when that is 0).
|
||||
self.cue_submit_notes = _parse_notes(cue.get("submit_notes"))
|
||||
self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0)
|
||||
|
||||
#: Barge-in: keep scoring the wake word while a reply is playing, abort
|
||||
#: the playback on a wake, and mute speech while the interrupt command
|
||||
#: is captured/handled. `wait_s` bounds how long to wait for the
|
||||
#: interrupted playback to release the audio device. `threshold`
|
||||
#: overrides the wake threshold for barge-in only (a higher bar keeps
|
||||
#: the agent's own TTS from self-triggering; 0 = use `wake.threshold`).
|
||||
barge_cfg = cfg.get("barge_in", {}) or {}
|
||||
self.barge_in_enabled = bool(barge_cfg.get("enabled", True))
|
||||
self.barge_in_wait_s = float(barge_cfg.get("wait_s", 2.0) or 0.0)
|
||||
self.barge_in_threshold = (
|
||||
float(barge_cfg.get("threshold", 0.0) or 0.0) or self.wake_threshold
|
||||
)
|
||||
|
||||
self._engines = engines
|
||||
self._engines_lock = threading.Lock()
|
||||
@@ -611,7 +1019,10 @@ class VoiceDaemon:
|
||||
self._on_utterance: UtteranceHandler | None = None
|
||||
self._stop = threading.Event()
|
||||
self._speaking = threading.Event()
|
||||
self._follow_until = 0.0
|
||||
#: Set while a reply is being played; `_interrupt` aborts that playback.
|
||||
self._interrupt = threading.Event()
|
||||
#: While set, `speak` drops text (a barge-in is being captured/handled).
|
||||
self._mute = threading.Event()
|
||||
|
||||
# ---- requirements ----
|
||||
|
||||
@@ -679,24 +1090,54 @@ class VoiceDaemon:
|
||||
|
||||
def _loop(self, engines: VoiceEngines) -> None:
|
||||
while not self._stop.is_set():
|
||||
pcm = engines.audio.read()
|
||||
pcm = self._read_frame(engines)
|
||||
if pcm is None:
|
||||
return
|
||||
if self._speaking.is_set():
|
||||
if not pcm:
|
||||
continue
|
||||
armed = time.time() < self._follow_until
|
||||
if not armed:
|
||||
barge_in = False
|
||||
if self._speaking.is_set():
|
||||
# Half-duplex by default: the agent's own voice is discarded.
|
||||
# With barge-in enabled the wake word is still scored, so the
|
||||
# user can interrupt a spoken reply ("hey <word>, stop").
|
||||
if not self.barge_in_enabled:
|
||||
continue
|
||||
score = engines.wake.score(pcm)
|
||||
if score < self.barge_in_threshold:
|
||||
continue
|
||||
barge_in = True
|
||||
self._begin_barge_in(engines, score)
|
||||
else:
|
||||
score = engines.wake.score(pcm)
|
||||
if score < self.wake_threshold:
|
||||
continue
|
||||
delivered = False
|
||||
try:
|
||||
if self.input_ready is not None and not self.input_ready():
|
||||
# The single scheduler slot is still running the current
|
||||
# request: hold the wake word until it reaches a result (or
|
||||
# pauses for the user's answer), so a new command cannot
|
||||
# start while one is in flight. Reset the detector so the
|
||||
# same wake phrase does not immediately re-fire once the
|
||||
# slot frees.
|
||||
try:
|
||||
engines.wake.reset()
|
||||
except Exception:
|
||||
pass
|
||||
self._event("voice_wake_blocked", score=round(float(score), 3))
|
||||
continue
|
||||
if not barge_in:
|
||||
self._event("voice_wake", score=round(float(score), 3))
|
||||
try:
|
||||
engines.wake.reset()
|
||||
except Exception:
|
||||
pass
|
||||
self._cue(self.cue_frequency, self.cue_duration_ms)
|
||||
self._follow_until = 0.0
|
||||
utterance = self._collect(engines, pcm)
|
||||
# Wait for the command to start rather than assuming it is glued
|
||||
# to the wake word (the wake frame + a natural pause are
|
||||
# discarded so the command is not truncated).
|
||||
wait_for_speech_ms = self.listen_timeout_ms
|
||||
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
|
||||
if not utterance:
|
||||
continue
|
||||
try:
|
||||
@@ -709,35 +1150,117 @@ class VoiceDaemon:
|
||||
self._event("voice_stt_empty", samples=len(utterance) // BYTES_PER_SAMPLE)
|
||||
continue
|
||||
self._event("voice_transcribed", chars=len(text))
|
||||
self._cue(self.cue_submit_frequency, self.cue_submit_duration_ms)
|
||||
self._bling()
|
||||
delivered = True
|
||||
if self._on_utterance is not None:
|
||||
self._on_utterance(text)
|
||||
finally:
|
||||
if barge_in:
|
||||
self._end_barge_in(delivered)
|
||||
|
||||
def _collect(self, engines: VoiceEngines, first_frame: bytes) -> bytes:
|
||||
"""Accumulate frames from the wake word until trailing silence."""
|
||||
frames = [first_frame]
|
||||
speech_ms = self.frame_ms
|
||||
def _begin_barge_in(self, engines: VoiceEngines, score: float) -> None:
|
||||
"""Abort the current reply and start listening for an interrupt.
|
||||
|
||||
The playback is stopped (the daemon's `play` watches `_interrupt`) and
|
||||
speech is muted so the interrupted reply cannot resume over the user
|
||||
while the interrupt command is captured and handled. The front end is
|
||||
told via `on_barge_in(True)` so it can classify the next utterance.
|
||||
"""
|
||||
self._event("voice_barge_in", score=round(float(score), 3))
|
||||
self._mute.set()
|
||||
self._interrupt.set()
|
||||
if self.on_barge_in is not None:
|
||||
try:
|
||||
self.on_barge_in(True)
|
||||
except Exception:
|
||||
pass
|
||||
# Wait for the interrupted playback to release the audio device so the
|
||||
# wake cue and the captured command are not played over it.
|
||||
deadline = time.time() + self.barge_in_wait_s
|
||||
while self._speaking.is_set() and time.time() < deadline:
|
||||
time.sleep(0.005)
|
||||
try:
|
||||
engines.audio.flush() # drop the reply's echo captured while speaking
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _end_barge_in(self, delivered: bool) -> None:
|
||||
"""Close a barge-in session.
|
||||
|
||||
`delivered` is True when a command was transcribed and handed to the
|
||||
front end; the front end then owns un-muting (it un-mutes only after the
|
||||
interrupt has been handled, so the interrupted reply never resumes). A
|
||||
barge-in that captured nothing un-mutes here.
|
||||
"""
|
||||
self._interrupt.clear()
|
||||
if self.on_barge_in is not None:
|
||||
try:
|
||||
self.on_barge_in(False)
|
||||
except Exception:
|
||||
pass
|
||||
if not delivered or self.on_barge_in is None:
|
||||
self._mute.clear()
|
||||
|
||||
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
|
||||
"""Accumulate frames from the wake word until trailing silence.
|
||||
|
||||
With `wait_for_speech_ms > 0`, `first_frame` (the wake-word frame) and
|
||||
any leading silence are discarded and capture starts only once the
|
||||
command's speech begins — so a natural pause after the wake word does
|
||||
not truncate the command. Gives up after that many milliseconds with no
|
||||
speech (traced `voice_no_command`).
|
||||
"""
|
||||
frames: list[bytes] = []
|
||||
speech_ms = 0
|
||||
silence_ms = 0
|
||||
started = time.time()
|
||||
#: Wall-clock of the most recent frame the VAD called speech — the
|
||||
#: "last word spoken" boundary the latency breakdown measures from.
|
||||
last_speech_ts = started
|
||||
waiting = wait_for_speech_ms > 0
|
||||
wait_started = started
|
||||
if not waiting:
|
||||
frames.append(first_frame)
|
||||
speech_ms = self.frame_ms
|
||||
while not self._stop.is_set():
|
||||
if self._speaking.is_set():
|
||||
break # a reply started; stop capturing so we don't transcribe it
|
||||
if self.max_utterance_s > 0 and (time.time() - started) >= self.max_utterance_s:
|
||||
break
|
||||
pcm = engines.audio.read()
|
||||
pcm = self._read_frame(engines)
|
||||
if pcm is None:
|
||||
break
|
||||
if not pcm:
|
||||
# No frame within the read timeout: keep waiting, but still
|
||||
# honor the "command never started" deadline below.
|
||||
if waiting and (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
|
||||
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
|
||||
return b""
|
||||
continue
|
||||
is_speech = engines.vad.is_speech(pcm, self.sample_rate)
|
||||
if waiting:
|
||||
if not is_speech:
|
||||
if (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
|
||||
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
|
||||
return b""
|
||||
continue
|
||||
waiting = False
|
||||
frames.append(pcm)
|
||||
if engines.vad.is_speech(pcm, self.sample_rate):
|
||||
if is_speech:
|
||||
speech_ms += self.frame_ms
|
||||
silence_ms = 0
|
||||
last_speech_ts = time.time()
|
||||
else:
|
||||
silence_ms += self.frame_ms
|
||||
if silence_ms >= self.vad_silence_ms:
|
||||
# Tolerate a longer pause until the command's speech is underway
|
||||
# (see `initial_silence_ms`): the wake phrase's tail is captured
|
||||
# first, and a pause before the actual command must not end it.
|
||||
limit = (
|
||||
self.initial_silence_ms
|
||||
if speech_ms < self.min_command_ms
|
||||
else self.vad_silence_ms
|
||||
)
|
||||
if silence_ms >= limit:
|
||||
break
|
||||
if speech_ms < self.min_speech_ms:
|
||||
self._event(
|
||||
@@ -751,6 +1274,60 @@ class VoiceDaemon:
|
||||
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
|
||||
return b"".join(frames)
|
||||
|
||||
# ---- capture health ----
|
||||
|
||||
def _read_frame(self, engines: VoiceEngines) -> bytes | None:
|
||||
"""Read one capture frame, recovering from a stalled stream.
|
||||
|
||||
Returns the frame bytes, `b""` when no frame arrived within
|
||||
`read_timeout_s`, or `None` once the input is closed. When the stream
|
||||
stalls continuously for `stall_timeout_s` — the PortAudio callback has
|
||||
stopped delivering, so a blocking `read()` would hang the front end
|
||||
forever — the input is closed and reopened so the loop recovers.
|
||||
"""
|
||||
timeout = self.read_timeout_s if self.read_timeout_s > 0 else None
|
||||
pcm = engines.audio.read(timeout=timeout)
|
||||
if pcm is None:
|
||||
return None
|
||||
if pcm:
|
||||
self._stall_since = 0.0
|
||||
return pcm
|
||||
if timeout is None or self.stall_timeout_s <= 0:
|
||||
return b""
|
||||
now = time.time()
|
||||
if not self._stall_since:
|
||||
self._stall_since = now
|
||||
return b""
|
||||
if now - self._stall_since >= self.stall_timeout_s:
|
||||
self._stall_since = 0.0
|
||||
self._reopen_input(engines)
|
||||
return b""
|
||||
|
||||
def _reopen_input(self, engines: VoiceEngines) -> None:
|
||||
"""Close and reopen the capture stream after a stall (best-effort).
|
||||
|
||||
A stalled PortAudio/ALSA stream never delivers another frame, so the
|
||||
blocking read would hang the whole front end. Reopening gives the
|
||||
device a fresh stream; a hard failure is traced and backed off rather
|
||||
than raised, so the loop keeps retrying instead of dying.
|
||||
"""
|
||||
self._event("voice_stream_stalled", stall_s=round(self.stall_timeout_s, 3))
|
||||
try:
|
||||
engines.audio.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
engines.audio.open_input(self.sample_rate, self.frame_ms, self.input_device)
|
||||
except Exception as exc:
|
||||
self._event("voice_stream_reopen_failed", message=str(exc)[:200])
|
||||
time.sleep(min(2.0, self.stall_timeout_s or 1.0))
|
||||
return
|
||||
try:
|
||||
engines.wake.reset()
|
||||
except Exception:
|
||||
pass
|
||||
self._event("voice_stream_reopened")
|
||||
|
||||
# ---- speaking ----
|
||||
|
||||
def _cue(self, frequency: float, duration_ms: int) -> None:
|
||||
@@ -771,15 +1348,72 @@ class VoiceDaemon:
|
||||
except Exception as exc:
|
||||
self._event("voice_cue_failed", message=str(exc)[:200])
|
||||
|
||||
def _bling(self) -> None:
|
||||
"""Play the post-transcription chime.
|
||||
|
||||
A configured `submit_notes` sequence (a short multi-note "bling") wins;
|
||||
otherwise it falls back to the single `submit_frequency` beep (silent at
|
||||
the shipped default of 0).
|
||||
"""
|
||||
if self.cue_submit_notes:
|
||||
self._play_tones(self.cue_submit_notes)
|
||||
else:
|
||||
self._cue(self.cue_submit_frequency, self.cue_submit_duration_ms)
|
||||
|
||||
def _play_tones(self, notes) -> None:
|
||||
"""Play a note sequence (the multi-note submit cue); silent on failure."""
|
||||
if not self.cue_enabled:
|
||||
return
|
||||
engines = self._engines
|
||||
if engines is None:
|
||||
return
|
||||
pcm = _tone_sequence(notes, self.sample_rate, self.cue_volume, self.cue_note_gap_ms)
|
||||
if not pcm:
|
||||
return
|
||||
with self._audio_lock:
|
||||
try:
|
||||
engines.audio.open_output(self.sample_rate)
|
||||
engines.audio.write(pcm, self.sample_rate)
|
||||
self._event("voice_cue", notes=[[float(f), int(d)] for f, d in notes])
|
||||
except Exception as exc:
|
||||
self._event("voice_cue_failed", message=str(exc)[:200])
|
||||
|
||||
def set_muted(self, muted: bool) -> None:
|
||||
"""Mute/unmute spoken replies (used around a barge-in)."""
|
||||
if muted:
|
||||
self._mute.set()
|
||||
else:
|
||||
self._mute.clear()
|
||||
|
||||
def muted(self) -> bool:
|
||||
"""Whether spoken replies are currently muted (a barge-in is in flight)."""
|
||||
return self._mute.is_set()
|
||||
|
||||
def stopping(self) -> bool:
|
||||
"""Whether the daemon is shutting down (a long stream should stop)."""
|
||||
return self._stop.is_set()
|
||||
|
||||
def speak(self, text: str) -> None:
|
||||
"""Synthesize and play `text`; called from the outbound pump thread."""
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return
|
||||
if self._mute.is_set():
|
||||
# A barge-in is in progress: the user interrupted and is giving a
|
||||
# new command, so a pending reply is dropped rather than played over
|
||||
# them. Replies after the interrupt is handled are spoken normally.
|
||||
self._event("voice_speak_suppressed", chars=len(text))
|
||||
return
|
||||
if self.max_speak_chars and len(text) > self.max_speak_chars:
|
||||
clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0]
|
||||
text = (clipped or text[: self.max_speak_chars]) + "…"
|
||||
engines = self._ensure_engines()
|
||||
# Start from a clean wake-detector state so the reply's own audio does
|
||||
# not inherit a stale partial match.
|
||||
try:
|
||||
engines.wake.reset()
|
||||
except Exception:
|
||||
pass
|
||||
self._speaking.set()
|
||||
self._event("voice_speak_start", chars=len(text))
|
||||
try:
|
||||
@@ -794,11 +1428,19 @@ class VoiceDaemon:
|
||||
else 0.0,
|
||||
)
|
||||
if pcm:
|
||||
if self._interrupt.is_set():
|
||||
# A barge-in landed during synthesis; skip playback.
|
||||
self._event("voice_speak_aborted", chars=len(text))
|
||||
else:
|
||||
with self._audio_lock:
|
||||
engines.audio.open_output(sample_rate)
|
||||
# The instant the first reply audio is handed to the device.
|
||||
self._event("voice_playback_start", ts=time.time(), chars=len(text))
|
||||
engines.audio.write(pcm, sample_rate)
|
||||
completed = engines.audio.play(
|
||||
pcm, sample_rate, stop_event=self._interrupt
|
||||
)
|
||||
if not completed:
|
||||
self._event("voice_speak_interrupted", chars=len(text))
|
||||
self._event("voice_spoke", chars=len(text))
|
||||
except Exception as exc:
|
||||
self._event("voice_speak_failed", message=str(exc)[:300])
|
||||
@@ -808,8 +1450,6 @@ class VoiceDaemon:
|
||||
engines.audio.flush() # clear any TTS echo captured while speaking
|
||||
except Exception:
|
||||
pass
|
||||
if self.follow_up_window > 0:
|
||||
self._follow_until = time.time() + self.follow_up_window
|
||||
try:
|
||||
engines.wake.reset()
|
||||
except Exception:
|
||||
|
||||
+15
-5
@@ -8,10 +8,12 @@ question type: the options become the question's ``criteria`` (id -> description
|
||||
and the question becomes its ``instructions``; the server returns a probability
|
||||
over exactly those keys.
|
||||
|
||||
Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md``
|
||||
for this deployment. 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.
|
||||
It works against any server implementing that route: the reference
|
||||
``winnow-server``, or an OpenAI-compatible host (ollama 0.40+) serving a
|
||||
``decision`` model such as ``clef-flash``. See ``local/ENVIRONMENT.md`` for this
|
||||
deployment. 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
|
||||
@@ -24,7 +26,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .decisions import DecisionRequest, DecisionResult
|
||||
from .decisions import DecisionRequest, DecisionResult, Option
|
||||
from .engine import DecisionEngine, EngineUnavailable
|
||||
|
||||
|
||||
@@ -34,6 +36,10 @@ class WinnowConfig:
|
||||
|
||||
base_url: str = "http://127.0.0.1:8091"
|
||||
model: str = "Winnow-12B"
|
||||
#: The server's decision context window (`--ctx-size`). Must mirror the
|
||||
#: running server; used to size generated skill bodies so a fidelity state
|
||||
#: always fits. The reference deployment runs `--ctx-size 32768`.
|
||||
context_tokens: int = 32768
|
||||
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.
|
||||
@@ -59,6 +65,10 @@ class WinnowEngine(DecisionEngine):
|
||||
self._lock = threading.Lock()
|
||||
self._loaded = False
|
||||
|
||||
@property
|
||||
def context_tokens(self) -> int:
|
||||
return int(self.config.context_tokens or 32768)
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
return self._loaded
|
||||
|
||||
@@ -42,7 +42,7 @@ from semif_agent.skills import (
|
||||
build_skills,
|
||||
build_tree,
|
||||
generate_category,
|
||||
generate_skill,
|
||||
generate_skill_spec,
|
||||
materialize_skill,
|
||||
navigate,
|
||||
)
|
||||
@@ -215,7 +215,7 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path):
|
||||
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
|
||||
)
|
||||
print(f"[lookup] {text!r} -> {result!r}")
|
||||
assert getattr(result, "category", None) == "calendar", f"lookup misrouted: {text!r}"
|
||||
assert getattr(result, "category", None) == "nextcloud", f"lookup misrouted: {text!r}"
|
||||
for text in noise:
|
||||
result = navigate(
|
||||
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
|
||||
@@ -380,19 +380,20 @@ def test_generate_category(tmp_path):
|
||||
|
||||
|
||||
def test_generate_skill(tmp_path):
|
||||
"""Authoring a skill leaf stub through the real `llm` provider."""
|
||||
"""Authoring a de-identified skill spec through the real `llm` provider."""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
scheduler, config = build_scheduler(config)
|
||||
draft = generate_skill(
|
||||
draft = generate_skill_spec(
|
||||
scheduler.llm,
|
||||
Request("tell me if my package was delivered"),
|
||||
"tracking",
|
||||
scheduler.tree,
|
||||
)
|
||||
print(f"draft: {draft.name!r} — {draft.description!r}")
|
||||
print(f"draft: {draft.name!r} — {draft.description!r} / goal: {draft.goal!r}")
|
||||
assert isinstance(draft, SkillDraft)
|
||||
assert draft.name and draft.description
|
||||
assert draft.goal
|
||||
|
||||
|
||||
def test_generate_skill_body_codegen(tmp_path):
|
||||
@@ -415,23 +416,18 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(
|
||||
name="check_service",
|
||||
description="Check whether an HTTP service is reachable.",
|
||||
)
|
||||
requirements = {
|
||||
"How should it connect?": (
|
||||
"HTTP GET the service_url from config (no auth) and report the "
|
||||
"status code; treat a non-2xx or unreachable host as a failure."
|
||||
description="Check whether a generic HTTP service is reachable.",
|
||||
goal=(
|
||||
"HTTP GET the service URL from config and report the status code; "
|
||||
"treat a non-2xx or unreachable host as a failure"
|
||||
),
|
||||
"Should it use a test fixture address?": "No; the endpoint comes from config.",
|
||||
}
|
||||
request = Request("check whether my home server is reachable")
|
||||
integration={"service": "http_service", "transport": "http"},
|
||||
)
|
||||
code = generate_skill_body(
|
||||
client,
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
tree,
|
||||
requirements=requirements,
|
||||
)
|
||||
print(f"generated {len(code)} bytes of skill body")
|
||||
integration = parse_integration(code)
|
||||
@@ -447,7 +443,6 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
print(f"data contract: {contract}")
|
||||
test = generate_skill_tests(
|
||||
client,
|
||||
request,
|
||||
"tracking",
|
||||
draft,
|
||||
code,
|
||||
@@ -534,6 +529,78 @@ def act(ctx, request):
|
||||
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
|
||||
print(f"declared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
|
||||
assert rows[-1]["extra"]["findings"] == [], "a consistent declaration has no findings"
|
||||
assert rows[-1]["extra"]["reconsider"] is False, (
|
||||
"a declared body with a real transport call must be accepted"
|
||||
)
|
||||
|
||||
|
||||
def test_fidelity_gate_reads_the_whole_body(tmp_path):
|
||||
"""Regression: the gate ingests the WHOLE body, never a prefix.
|
||||
|
||||
A body whose real action sits *after* the old 4000-char cutoff (helpers and
|
||||
padding first) must be accepted by the real engine. Before the fix the gate
|
||||
saw only a prefix that contained no action and wrongly returned
|
||||
`reconsider`; the raw request must also stay out of the state.
|
||||
"""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
_isolate_runtime(config, tmp_path)
|
||||
scheduler, config = build_scheduler(config)
|
||||
scheduler.codegen = CodegenClient(
|
||||
base_url="http://127.0.0.1:1/v1", model="test", timeout=2
|
||||
)
|
||||
|
||||
padding = "# filler to push the real action past the old 4000-char cutoff\n"
|
||||
body = (
|
||||
'"""Check a delivery through the carrier HTTP API."""\n\n'
|
||||
'INTEGRATION = {"service": "carrier", "transport": "http", '
|
||||
'"config_vars": ["tracking_url"]}\n'
|
||||
'CONTRACT = {"tracking_url": "Carrier status endpoint."}\n\n'
|
||||
"import json\n"
|
||||
"import urllib.request\n\n"
|
||||
"from semif_agent.skills import ActionResult\n\n\n"
|
||||
+ padding * 60
|
||||
+ "def _post(ctx, path, payload):\n"
|
||||
" req = urllib.request.Request(\n"
|
||||
' ctx.config["tracking_url"] + path,\n'
|
||||
" data=json.dumps(payload).encode(),\n"
|
||||
' method="POST",\n'
|
||||
" )\n"
|
||||
" with urllib.request.urlopen(req, timeout=15) as response:\n"
|
||||
' return json.loads(response.read().decode("utf-8"))\n\n\n'
|
||||
"def act(ctx, request):\n"
|
||||
' reply = _post(ctx, "/deliveries/check", {"id": "1"})\n'
|
||||
" return ActionResult(\n"
|
||||
' action_log=f"carrier said {reply[\'status\']}",\n'
|
||||
' new_state=reply["status"],\n'
|
||||
" )\n"
|
||||
)
|
||||
assert body.index('method="POST"') > 4000, "fixture must place the action past the old cutoff"
|
||||
|
||||
job = SkillWrite(
|
||||
request=Request("check my delivery status for package 12345"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(
|
||||
name="check_delivery",
|
||||
description="Check a package's delivery status.",
|
||||
goal="POST the carrier's check endpoint and report the observed status.",
|
||||
),
|
||||
)
|
||||
scheduler._fidelity_gate(job, body)
|
||||
row = [
|
||||
r
|
||||
for r in scheduler.log.read()
|
||||
if r.get("extra", {}).get("phase") == "authoring:fidelity"
|
||||
][-1]
|
||||
print(f"whole-body reconsider: {row['extra']['reconsider']} {row['predicted_probs']}")
|
||||
assert row["extra"]["findings"] == [], "a consistent declaration has no findings"
|
||||
assert row["extra"]["reconsider"] is False, (
|
||||
"the gate must see the action and accept the body (whole-body ingestion)"
|
||||
)
|
||||
assert 'method="POST"' in row["state"], "the whole body must reach the gate"
|
||||
assert "check my delivery status for package 12345" not in row["state"], (
|
||||
"the raw request must not reach the gate"
|
||||
)
|
||||
|
||||
|
||||
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
||||
@@ -583,7 +650,7 @@ def test_create_simplex_send_skill(tmp_path):
|
||||
scheduler, config = build_scheduler(config)
|
||||
|
||||
seeded = {s.name for s in scheduler.tree.get("simplex", [])}
|
||||
assert {"next_message", "connect_link"} <= seeded, (
|
||||
assert {"next_message", "send_message", "connect_link"} <= seeded, (
|
||||
f"the simplex seeds must be loaded, got {seeded}"
|
||||
)
|
||||
|
||||
@@ -720,11 +787,43 @@ def test_empty_result_is_assessed_as_success(tmp_path):
|
||||
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
||||
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
|
||||
outcome = runner.run(skill, Request("What's my next simplex message?"))
|
||||
print(f"[{outcome.success}] {outcome.summary}")
|
||||
print(f"[{outcome.outcome}] {outcome.summary}")
|
||||
|
||||
assert outcome.success is True, outcome.summary
|
||||
assert outcome.outcome == "done", outcome.summary
|
||||
phases = [row["extra"]["phase"] for row in log.read()]
|
||||
assert "assess:outcome" in phases
|
||||
assert "assess:requeue" not in phases, (
|
||||
"an empty discovery must not be retried or repaired"
|
||||
|
||||
|
||||
def test_read_result_is_assessed_as_done(tmp_path):
|
||||
"""A correctly-read result is a satisfied request, not a failure.
|
||||
|
||||
The assessment must see the skill's declared action; with only the skill
|
||||
label the real model marked a truthful read failed for ambiguous phrasings
|
||||
(e.g. "What's my next simplex message?"), which then looped into repair of a
|
||||
working skill. This exercises the real engine, since only it produces the
|
||||
probabilities.
|
||||
"""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
engine = SemIfEngine(build_engine_config(config))
|
||||
|
||||
def act(ctx, request):
|
||||
return ActionResult(
|
||||
action_log="SimpleX message from pepper: hello",
|
||||
new_state="SimpleX message from pepper: hello",
|
||||
)
|
||||
|
||||
skill = Skill(
|
||||
name="next_message",
|
||||
category="simplex",
|
||||
description="Read the next unread SimpleX message.",
|
||||
act=act,
|
||||
)
|
||||
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
||||
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
|
||||
outcome = runner.run(skill, Request("What's my next simplex message?"))
|
||||
print(f"[{outcome.outcome}] {outcome.summary}")
|
||||
|
||||
assert outcome.outcome == "done", outcome.summary
|
||||
phases = [row["extra"]["phase"] for row in log.read()]
|
||||
assert "assess:outcome" in phases
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user