Compare commits
158
Commits
fcb0f0f988
...
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 | ||
|
|
228886f7cd | ||
|
|
d9cc7e4fed | ||
|
|
e64354e78d | ||
|
|
dff4849947 | ||
|
|
0efbf218c5 | ||
|
|
f1e0de33ca | ||
|
|
ee7700275c | ||
|
|
17f16a6bfc | ||
|
|
4e70a5889e | ||
|
|
e9a7fc73ee | ||
|
|
d0c1dccffd | ||
|
|
5bb0e9d21d | ||
|
|
e426998cf7 | ||
|
|
1dc0550659 | ||
|
|
a354958599 | ||
|
|
85cdb94dc9 | ||
|
|
ddbe5f167d | ||
|
|
7ee200d921 | ||
|
|
e8d1685177 | ||
|
|
172e61e6be | ||
|
|
d2f9a74bd9 | ||
|
|
eeed8407f9 | ||
|
|
d25b3259e4 | ||
|
|
4496b8eceb | ||
|
|
49f67575cf | ||
|
|
1d9730bfcb | ||
|
|
80518dcdda | ||
|
|
9a135f53ab | ||
|
|
07b0e2ff7e | ||
|
|
780c9592ed | ||
|
|
8426b85ce0 | ||
|
|
e81e6c3a6b | ||
|
|
63c5fc9903 | ||
|
|
f21baa7ebd | ||
|
|
18f3d6fee5 | ||
|
|
341eb9f8a0 | ||
|
|
43ece0cfd6 | ||
|
|
38cba33bbf | ||
|
|
5747ad2fa6 | ||
|
|
8afb488dc4 | ||
|
|
159112b8fb | ||
|
|
215c22afb8 | ||
|
|
25ade160df | ||
|
|
8751e7c08e | ||
|
|
da53e1eefc | ||
|
|
857ad1ac39 | ||
|
|
de78a0e96a | ||
|
|
567c280ee2 | ||
|
|
4a62e794a5 | ||
|
|
375d37d1f1 | ||
|
|
65c5899393 | ||
|
|
50c83c61fd | ||
|
|
e93db6ec09 | ||
|
|
4a4fe850e0 | ||
|
|
fb5303928b | ||
|
|
ea3d79be99 | ||
|
|
22f91e0360 | ||
|
|
5a6f220e79 | ||
|
|
a29371f510 | ||
|
|
6e197596c8 | ||
|
|
8eb4541f19 | ||
|
|
98ec4ee5e2 | ||
|
|
d0df6f16c4 | ||
|
|
13a512cc31 | ||
|
|
5589358de2 | ||
|
|
42b2472328 | ||
|
|
3d0cff325c | ||
|
|
ddc5cb66c8 | ||
|
|
d46fbdca19 | ||
|
|
a9b096f2e8 | ||
|
|
9057213217 | ||
|
|
08d6bb23e2 | ||
|
|
b348f19486 | ||
|
|
5f05c5c749 | ||
|
|
221edb827e | ||
|
|
c92aff5038 | ||
|
|
6059bec1e4 | ||
|
|
5ee3905aec | ||
|
|
756d4b47b7 | ||
|
|
5df560a922 | ||
|
|
a6f46b735d | ||
|
|
483c51f559 | ||
|
|
6ab4d94423 | ||
|
|
a627f59a67 | ||
|
|
de2c1a73f2 | ||
|
|
b66d1e325a | ||
|
|
dde034f1b4 | ||
|
|
06ccfb77c6 | ||
|
|
ddd2495f81 | ||
|
|
927f66b696 | ||
|
|
87438c881a | ||
|
|
db35cb66dc | ||
|
|
2297bbd6aa | ||
|
|
72af30f449 | ||
|
|
67027ecc20 | ||
|
|
d866d94d04 | ||
|
|
f91f86742e | ||
|
|
90fda9f2a4 | ||
|
|
db7d431976 | ||
|
|
340520d630 | ||
|
|
d18f0ccdb6 | ||
|
|
7c5cd2b685 | ||
|
|
bd99735283 | ||
|
|
9c2d41d984 | ||
|
|
3661443184 | ||
|
|
71abc0f762 | ||
|
|
0076b3d0f9 |
No files matched your search
+15
@@ -1,11 +1,26 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
.venv/
|
.venv/
|
||||||
|
# Repo-contained install artifacts (venv, SemIf engine, GGUF, HF cache,
|
||||||
|
# simplex-chat binary/profile, rendered systemd units). See bootstrap.sh.
|
||||||
|
.runtime/
|
||||||
data/decisions.jsonl
|
data/decisions.jsonl
|
||||||
data/runs.jsonl
|
data/runs.jsonl
|
||||||
data/categories.json
|
data/categories.json
|
||||||
|
data/deleted_skills.json
|
||||||
data/skills/
|
data/skills/
|
||||||
data/drafts/
|
data/drafts/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
config.json
|
config.json
|
||||||
|
config/
|
||||||
|
secrets.json
|
||||||
*.log
|
*.log
|
||||||
|
# Machine-specific material: deployment notes (hostnames, addresses, SSH,
|
||||||
|
# model choices), GPU offload probe, benchmark harness. Deliberately not part
|
||||||
|
# of the shipped agent.
|
||||||
|
local/
|
||||||
|
*.egg-info/
|
||||||
|
*.bak.*
|
||||||
|
# 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.
|
||||||
+715
@@ -0,0 +1,715 @@
|
|||||||
|
# CODEGEN.md — the contract for new skills
|
||||||
|
|
||||||
|
This file is the authoritative spec for what a new skill is and how its code
|
||||||
|
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 native python modules — including direct HTTP
|
||||||
|
requests to a service's own API — user-provided data, and, where warranted, a
|
||||||
|
catalog of basic services known as bridges. A skill is the thing that performs
|
||||||
|
one of those tasks: it is the leaf in the skill tree that the agent navigates to
|
||||||
|
when it has resolved a request to a single, concrete action. Navigation is
|
||||||
|
performed by an llm-based decision engine known as SemIf.
|
||||||
|
|
||||||
|
A skill is three things:
|
||||||
|
|
||||||
|
1. **A registry entry** — its navigable `name` + `description`, recorded in
|
||||||
|
`data/categories.json` and mirrored in the running tree.
|
||||||
|
2. **A code body** — a runnable Python module implementing a single `act`
|
||||||
|
phase against a real service.
|
||||||
|
3. **A declaration** — the `INTEGRATION` constant (which real system the body
|
||||||
|
talks to and how) and the `CONTRACT` constant (the values the runner must
|
||||||
|
provide).
|
||||||
|
|
||||||
|
The `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.
|
||||||
|
|
||||||
|
## The decision engine: SemIf
|
||||||
|
|
||||||
|
A skill body turns a request into an action, and along the way it must decide
|
||||||
|
things: which calendar the query means, whether the evidence is enough, what to
|
||||||
|
call the event. Those decisions are made by **SemIf** — the agent's decision
|
||||||
|
engine — not by text generation. This section explains what SemIf is, what it
|
||||||
|
can do, and when a body should reach for it instead of plain code or an LLM.
|
||||||
|
|
||||||
|
### What SemIf is
|
||||||
|
|
||||||
|
SemIf ("semantic ifs", formerly OpenJev) is a small, pinned, local language
|
||||||
|
model whose single job is to answer a **typed, runtime-defined decision**
|
||||||
|
without generating any text. You give it three things:
|
||||||
|
|
||||||
|
- a **state** — the unstructured evidence, usually `request.text` (sometimes the
|
||||||
|
query plus a list of candidates);
|
||||||
|
- a **question** — the criterion in plain language ("Which calendar is referred
|
||||||
|
to in the user query?");
|
||||||
|
- **options** — 2–16 named, described alternatives (`work`, `personal`, ...).
|
||||||
|
|
||||||
|
It performs one forward pass and reads the probabilities of the declared answer
|
||||||
|
tokens directly. It returns a probability for each option — no sentence, no
|
||||||
|
JSON, no decoding loop, nothing to parse. In effect it is a semantic `if`:
|
||||||
|
software asks a yes/no/which question in natural language and gets back a typed,
|
||||||
|
thresholdable number. In this agent the `state` is always a string
|
||||||
|
(`request.text`, or the query plus a list of candidates); the broader SemIf
|
||||||
|
project also accepts a nonempty JSON object or array as state, but a body here
|
||||||
|
must pass a string.
|
||||||
|
|
||||||
|
The whole point is that the **question and options arrive with the request**.
|
||||||
|
Routing, selection, and assessment are not baked into the model or the prompt;
|
||||||
|
they are supplied at call time. You never fine-tune SemIf to add a new decision —
|
||||||
|
you just describe a new question.
|
||||||
|
|
||||||
|
That is the difference from a chat model: a chat model answers by generating text
|
||||||
|
that your code immediately parses back into an `if`. SemIf skips the text. On the
|
||||||
|
reference hardware, reading 21 binary decisions directly took about 1.0 s and
|
||||||
|
zero output tokens; the same decisions as a generated JSON array took about
|
||||||
|
5.3 s and 111 tokens. It is decision-native and cheap enough to embed in ordinary
|
||||||
|
code.
|
||||||
|
|
||||||
|
### SemIf's feature set
|
||||||
|
|
||||||
|
SemIf (<https://github.com/TheoLeeCJ/SemIf>) is a broader project than
|
||||||
|
the one call this agent makes. Its full feature set:
|
||||||
|
|
||||||
|
- **Runtime-defined decisions** — state, criterion, and option descriptions are
|
||||||
|
supplied per call; no retraining, no per-decision prompt engineering.
|
||||||
|
- **Decision-native readout** — one forward pass over the declared option
|
||||||
|
logits, softmaxed over the allowed answer tokens. No token is sampled, so
|
||||||
|
there is no generation, no JSON repair, and no decoding loop to get stuck.
|
||||||
|
- **Typed probabilities** — a probability per option, conditional on exactly the
|
||||||
|
options you supplied. 2–16 described options per decision.
|
||||||
|
- **Structured state** — the state can be a string or a nonempty JSON object or
|
||||||
|
array; direct modes preserve it as structured JSON rather than flattening it.
|
||||||
|
- **Shared-state awareness** — one long state can be prefetched once and branched
|
||||||
|
across many criteria: serial prefix reuse (~10.8 decisions/s) and parallel
|
||||||
|
suffix branches (~20 decisions/s) instead of re-scoring the state per decision.
|
||||||
|
Best when every decision shares the same state.
|
||||||
|
- **Multiple backends** — CUDA/PyTorch, Apple Silicon (MLX and PyTorch/MPS), and
|
||||||
|
a CPU llama.cpp path over a local GGUF. This agent pins the llama.cpp CPU
|
||||||
|
backend.
|
||||||
|
- **Reranker mode** — a second readout that scores each candidate as a yes/no
|
||||||
|
relevance proposition and softmaxes the log-odds across options; strongest for
|
||||||
|
ranking/retrieval rather than categorical decisions.
|
||||||
|
- **Auditability** — every row carries the option scores, timing, the exact model
|
||||||
|
revision, and a `prompt_sha256`, so a decision can be reproduced and compared.
|
||||||
|
- **Calibration** — optional per-workload temperature scaling fitted on labeled
|
||||||
|
decisions, which tightens expected calibration error (e.g. WANLI 0.208 → 0.069
|
||||||
|
out of fold). Calibration does not change the selected option.
|
||||||
|
- **Batch scoring CLI** (`semif-score`) — reads a JSONL of decisions and writes a
|
||||||
|
JSONL of typed scores, for offline evaluation.
|
||||||
|
- **Open, auditable evidence** — owned fixtures, committed runners, raw results,
|
||||||
|
and known failure modes.
|
||||||
|
|
||||||
|
Two caveats shape how the agent uses it: the probabilities are **conditional on
|
||||||
|
the options you supplied** — not calibrated operational confidence — so treat
|
||||||
|
them as conditional scores and threshold them rather than believing them; and a
|
||||||
|
forced typed output can still be semantically wrong. Quality depends on the
|
||||||
|
model: the pinned 4B reaches ~0.81 balanced accuracy on the project's authored
|
||||||
|
decision set (a 27B EXL3 bridge reaches ~0.96).
|
||||||
|
|
||||||
|
### What a skill body can use
|
||||||
|
|
||||||
|
A body does not speak SemIf's wire protocol. It reaches the engine through
|
||||||
|
**one** interface: the typed decision call.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from semif_agent.decisions import DecisionRequest, Option
|
||||||
|
|
||||||
|
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)
|
||||||
|
result.selected # option id with the highest probability
|
||||||
|
result.prob("work") # that option's probability
|
||||||
|
result.probs # {option_id: probability}
|
||||||
|
```
|
||||||
|
|
||||||
|
The engine is always real (`ctx.engine`); there is no mock path. The runner
|
||||||
|
serializes calls onto one model, so keep decisions few. Return every
|
||||||
|
`(DecisionRequest, DecisionResult)` pair on `ActionResult.decisions` so the choice
|
||||||
|
is logged as a training row with the run outcome.
|
||||||
|
|
||||||
|
The shared-state, reranker, batch, and calibration features above are
|
||||||
|
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 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
|
||||||
|
|
||||||
|
Every value a body produces comes from one of three sources. Pick deliberately;
|
||||||
|
mixing them up is the most common way a body goes wrong.
|
||||||
|
|
||||||
|
| Source | Use it for | Examples |
|
||||||
|
| ------ | ---------- | -------- |
|
||||||
|
| **Deterministic code** | Exact, mechanical mappings that are right every time | parsing a date/time or number, formatting output, computing a duration, building a URL, comparing ids, iterating a fetched list, reading a status code, escaping text |
|
||||||
|
| **SemIf** (`ctx.engine.call`) | A judgment among a known, enumerated set of options, when the right one is semantic rather than an exact match | which calendar/contact/conversation/folder the query means; whether the evidence supports / contradicts / is insufficient; which target to use when several fit |
|
||||||
|
| **LLM text** (the LLM bridge) | Novel natural-language content that is not chosen from a set | an event title, a subject line, a message body, a summary, a description, a reformulation |
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Deterministic code is the default.** If a rule can decide it, write the rule.
|
||||||
|
Never spend a model call on something a regex, a dict lookup, or arithmetic
|
||||||
|
settles.
|
||||||
|
- **Use SemIf for choices, not for generation.** SemIf returns a probability over
|
||||||
|
the options you gave it; it cannot write a title or a sentence. Give it the
|
||||||
|
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 `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 `nextcloud.create_event` asks only for a title and description), and
|
||||||
|
report a real failure when the bridge is down rather than guessing the text.
|
||||||
|
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
|
||||||
|
selects, or assesses; deterministic code never invents a value it cannot
|
||||||
|
observe. A request input is resolved by SemIf, not by substring matching by
|
||||||
|
hand; a title is generated by the LLM, not assembled by string concatenation
|
||||||
|
when it should be written; a date is parsed by code, not asked of a model.
|
||||||
|
|
||||||
|
**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
|
||||||
|
leaf's `name` and `description`, and the scheduler records them in
|
||||||
|
`data/categories.json` (mirrored in the running tree). You are told the chosen
|
||||||
|
`name` and `description` in the prompt; use them, and never invent or rename the
|
||||||
|
skill.
|
||||||
|
|
||||||
|
The registry is a map of category -> bucket:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"<category>": {
|
||||||
|
"description": "<one to two sentences: the bucket's purpose>",
|
||||||
|
"skills": [
|
||||||
|
{
|
||||||
|
"name": "<leaf_name>",
|
||||||
|
"description": "<what this leaf does, for navigation>",
|
||||||
|
"goal": "<the de-identified, reusable action statement>"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- A leaf `name` is a single snake_case token (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`),
|
||||||
|
not dotted with the category; the category is the key it lives under, and the
|
||||||
|
runner joins them as `category.name` only when it builds the run summary.
|
||||||
|
- `goal` is the de-identified, reusable action statement authored by the local
|
||||||
|
`llm`; the scheduler records it so a stub can be re-driven later. The
|
||||||
|
originating request and any user detail are never persisted here, and never
|
||||||
|
reach the codegen endpoint.
|
||||||
|
|
||||||
|
## Code body contract
|
||||||
|
|
||||||
|
The generated module is persisted to `data/skills/<category>/<name>/skill.py`
|
||||||
|
and imported at runtime. It must satisfy **all** of the following.
|
||||||
|
|
||||||
|
**Import everything you use.** The module is not handed `ActionResult`, the
|
||||||
|
engine types, or any stdlib module for free — the runner imports your file
|
||||||
|
as-is. A body that calls `urllib.request.urlopen`, `json.loads`, `re.match`, or
|
||||||
|
returns `ActionResult` **without importing them raises `NameError` the moment it
|
||||||
|
runs**. Start every body with its imports (see the complete example below).
|
||||||
|
|
||||||
|
### Complete minimal example
|
||||||
|
|
||||||
|
This is the whole shape of a body — imports first, then `INTEGRATION`,
|
||||||
|
`CONTRACT`, and `act`. Copy this structure.
|
||||||
|
|
||||||
|
```python
|
||||||
|
"""Check whether a configured HTTP service is reachable.
|
||||||
|
|
||||||
|
Real integration: the service over HTTP. Operational values come from
|
||||||
|
`ctx.config` (declared in CONTRACT).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
INTEGRATION = {
|
||||||
|
"service": "example_service",
|
||||||
|
"transport": "http",
|
||||||
|
"config_vars": ["example_base_url"],
|
||||||
|
}
|
||||||
|
|
||||||
|
CONTRACT = {
|
||||||
|
"example_base_url": "Base URL of the service, e.g. https://service.example.org.",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request) -> ActionResult:
|
||||||
|
"""Perform the real action and return the result + new state."""
|
||||||
|
base_url = ctx.config["example_base_url"]
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"{base_url}/status", timeout=15) as response:
|
||||||
|
payload = json.loads(response.read().decode("utf-8"))
|
||||||
|
except (urllib.error.URLError, ValueError) as exc:
|
||||||
|
return ActionResult(
|
||||||
|
action_log=f"could not reach {base_url}: {exc}",
|
||||||
|
new_state=request.text,
|
||||||
|
)
|
||||||
|
return ActionResult(
|
||||||
|
action_log=f"{base_url} returned {payload}",
|
||||||
|
new_state=json.dumps(payload),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
That example checks a fixed configured endpoint, so it takes no per-request
|
||||||
|
argument; a skill that acts on the query reads `request.text` and derives its
|
||||||
|
arguments from it — see "Turning the request into arguments".
|
||||||
|
|
||||||
|
### Required function
|
||||||
|
|
||||||
|
```python
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
def act(ctx, request) -> ActionResult:
|
||||||
|
"""Perform the real action and return the result + new state."""
|
||||||
|
```
|
||||||
|
|
||||||
|
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine),
|
||||||
|
`ctx.config` (the resolved values for this skill, including its own config),
|
||||||
|
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
|
||||||
|
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
|
||||||
|
`ctx.catalog` is a **read-only** view of the agent's own skill tree for an
|
||||||
|
introspection skill that reports what the agent can do: `ctx.catalog.categories()`
|
||||||
|
returns a `{category_id: description}` map and `ctx.catalog.skills(category)`
|
||||||
|
the leaf names inside one category (the `skills.list_categories` /
|
||||||
|
`skills.list_skills` seeds). `ctx.admin` exists for the built-in housekeeping
|
||||||
|
meta skills only; an ordinary body must never touch it.
|
||||||
|
- `request` is the `Request` being handled.
|
||||||
|
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
|
||||||
|
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
|
||||||
|
type. `decisions` carries any `(DecisionRequest, DecisionResult)` pairs made
|
||||||
|
during `act` so they are logged as training rows. `needs_input` carries a
|
||||||
|
question for the human; see the rules below.
|
||||||
|
|
||||||
|
### Data contract
|
||||||
|
|
||||||
|
Every **required** operational value the body needs is declared in a
|
||||||
|
module-level `CONTRACT` dict: a flat map of snake_case variable name to a
|
||||||
|
plain-language, semantic description of the expected value.
|
||||||
|
|
||||||
|
```python
|
||||||
|
CONTRACT = {
|
||||||
|
"nextcloud_url": "Base URL of the user's Nextcloud, e.g. https://cloud.example.org.",
|
||||||
|
"nextcloud_username": "Nextcloud login name whose calendar is read.",
|
||||||
|
"nextcloud_app_password": "Nextcloud app password for that login.",
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- The runner resolves each contract variable from the agent's tiered config
|
||||||
|
(global -> category -> skill) and asks the human for any it cannot resolve.
|
||||||
|
The resolved values arrive in `ctx.config` under the same names.
|
||||||
|
- Every key in `CONTRACT` must be read from `ctx.config` in the body. Do not
|
||||||
|
declare a variable you do not read.
|
||||||
|
- **Optional** values with a safe default are NOT contract keys: read them with
|
||||||
|
`ctx.config.get("<name>", <default>)`. Declaring an optional value would make
|
||||||
|
the runner ask the human for it.
|
||||||
|
- Do not put type declarations, validation logic, or nested structures in
|
||||||
|
`CONTRACT`; the body implements whatever type safety it needs. It is for the
|
||||||
|
human and SemIf only.
|
||||||
|
|
||||||
|
### Turning the request into arguments
|
||||||
|
|
||||||
|
`request.text` is the user's query — the thing the human actually asked for. A
|
||||||
|
skill that turns queries into outputs must **read `request.text`** and derive
|
||||||
|
from it the action's **per-request arguments**: the recipient, the subject or
|
||||||
|
message body, the date or time range, the search terms, the target, the filter,
|
||||||
|
the filename. Do not ignore the query and do a fixed thing.
|
||||||
|
|
||||||
|
There are exactly two lanes of values, and they must not blur:
|
||||||
|
|
||||||
|
- **Per-request arguments** come from `request.text`. They change on every
|
||||||
|
request. Never declare them in `CONTRACT`, never ask the human for them, and
|
||||||
|
never embed them as constants.
|
||||||
|
- **Operational values** — endpoints, accounts, credentials, CLI paths, and
|
||||||
|
stable defaults — come from `CONTRACT` -> `ctx.config`. See "Data contract".
|
||||||
|
|
||||||
|
When the query names a target that maps onto a set the service exposes
|
||||||
|
(contacts, calendars, folders, files), resolve it with a SemIf sub-decision over
|
||||||
|
the real candidate set, not by hand — see "Candidate selection". When a required
|
||||||
|
argument is missing or genuinely ambiguous and no candidate set can resolve it,
|
||||||
|
return `needs_input` (below); do not invent a value.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# DecisionRequest/Option come from semif_agent.decisions (not .skills).
|
||||||
|
# The recipient is a per-request argument: read it from the query, then resolve
|
||||||
|
# it against the real contact list with a SemIf sub-decision.
|
||||||
|
matches = [c for c in contacts if c["display_name"].lower() in request.text.lower()]
|
||||||
|
if len(matches) == 1:
|
||||||
|
recipient = matches[0]["id"]
|
||||||
|
elif matches:
|
||||||
|
decision = DecisionRequest(
|
||||||
|
state=request.text,
|
||||||
|
question="Which contact should the message go to?",
|
||||||
|
options=[Option(c["id"], c["display_name"]) for c in matches],
|
||||||
|
)
|
||||||
|
result = ctx.engine.call(decision)
|
||||||
|
decisions.append((decision, result))
|
||||||
|
recipient = result.selected
|
||||||
|
else:
|
||||||
|
return ActionResult(
|
||||||
|
action_log="no contact matched the request",
|
||||||
|
new_state=request.text,
|
||||||
|
needs_input="Which contact should I message?",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration declaration
|
||||||
|
|
||||||
|
Every body defines a module-level `INTEGRATION` dict: the real system this
|
||||||
|
skill acts on. Flat, string-valued, and honest — it must match what the body
|
||||||
|
actually does.
|
||||||
|
|
||||||
|
```python
|
||||||
|
INTEGRATION = {
|
||||||
|
"service": "nextcloud_calendar",
|
||||||
|
"transport": "caldav",
|
||||||
|
"config_vars": ["nextcloud_url", "nextcloud_username", "nextcloud_app_password"],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `service` — short snake_case id of the real system (e.g. `gmail`,
|
||||||
|
`nextcloud_calendar`, `simplex`, `local_files`).
|
||||||
|
- `transport` — exactly one of `http`, `caldav`, `imap`, `smtp`, `pop`,
|
||||||
|
`subprocess`, `file`, `compute`
|
||||||
|
(`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for
|
||||||
|
skills that perform no external action at all (pure analysis/formatting); an
|
||||||
|
action skill must not use it.
|
||||||
|
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
|
||||||
|
the shipped seeds this is exactly the body's `CONTRACT` key set; an empty
|
||||||
|
list is allowed for `compute`. Declaring a variable the body never reads is a
|
||||||
|
mismatch the fidelity check flags.
|
||||||
|
|
||||||
|
The auto-run test is a hermetic mechanics check and never exercises the live
|
||||||
|
service, so this declaration is how the agent knows what the skill was built to
|
||||||
|
talk to. Declaring a transport the body does not use is a broken skill.
|
||||||
|
|
||||||
|
### Candidate selection
|
||||||
|
|
||||||
|
When the body has a **set of candidates to choose from** — contacts,
|
||||||
|
conversations, calendars, folders, targets — it must employ a relevant SemIf
|
||||||
|
query over them. The decision types come from the agent package, not
|
||||||
|
`semif_agent.skills`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from semif_agent.decisions import DecisionRequest, Option
|
||||||
|
|
||||||
|
decision = DecisionRequest(
|
||||||
|
state=request.text,
|
||||||
|
question="Which calendar is the intended one?",
|
||||||
|
options=[Option(c["name"], c["label"]) for c in calendars],
|
||||||
|
)
|
||||||
|
result = ctx.engine.call(decision)
|
||||||
|
...
|
||||||
|
return ActionResult(..., decisions=[(decision, result)])
|
||||||
|
```
|
||||||
|
|
||||||
|
- Use the real engine (`ctx.engine.call`); never mock, never guess, never pick
|
||||||
|
by hand when more than one candidate fits.
|
||||||
|
- Return every `(DecisionRequest, DecisionResult)` pair on
|
||||||
|
`ActionResult.decisions` so the choice is logged with the run outcome.
|
||||||
|
- Include any configured default (a value read from `ctx.config`) as one of the
|
||||||
|
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 `nextcloud.create_event` resolves its calendar.
|
||||||
|
|
||||||
|
### Producing the result (output)
|
||||||
|
|
||||||
|
A skill exists to turn the query into an **output the human wants**. Both
|
||||||
|
strings on `ActionResult` carry that output and must reflect what really
|
||||||
|
happened:
|
||||||
|
|
||||||
|
- `action_log` is the human-readable record of the run. The `assess:outcome`
|
||||||
|
SemIf decision judges the run from it (together with the goal and the resolved
|
||||||
|
inputs), and the deterministic run summary is built from it. Write what the
|
||||||
|
service actually returned: the message that was read, the id/reference of the
|
||||||
|
thing that was created, the status code and error text of a failure.
|
||||||
|
- `new_state` is the run's resulting observation — the state the agent carries
|
||||||
|
forward. For a read/query skill it is the retrieved data itself (the message
|
||||||
|
body, the event, the value); for an action skill it is a short report of what
|
||||||
|
was done (recipient, id, timestamp).
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Do not prefix the skill name to `action_log` or `new_state`.** The runner
|
||||||
|
wraps the result in the deterministic summary (`category.name: ok — <detail>`)
|
||||||
|
and carries the skill ref structurally, so a body writes only the result text
|
||||||
|
— never `"<category>.<name>: ..."`.
|
||||||
|
- **Return the real result.** A read/query skill returns the data it fetched; an
|
||||||
|
action skill reports the service's real response. A generic "done" that omits
|
||||||
|
the result is a broken output.
|
||||||
|
- **Never an empty or placeholder output.** If there is genuinely nothing (empty
|
||||||
|
inbox, no matching event), say so explicitly — that is a real result, and a
|
||||||
|
**`done`** run: the `assess:outcome` step treats a definitive "nothing found /
|
||||||
|
nothing to do" result as done. Phrase it as the answer the user asked for
|
||||||
|
("checked the inbox: no unread messages"), not as an absence or an error, so
|
||||||
|
the assessment does not read a healthy empty result as a failure.
|
||||||
|
- **Keep the result speakable — it is bounded.** A skill's output is read in a
|
||||||
|
chat message or heard as speech, so the runner truncates `action_log` /
|
||||||
|
`new_state` to one shared budget (`chain.result_chars`, ~300 characters /
|
||||||
|
~20 seconds of speech) and feeds the bounded text to the assessment and the
|
||||||
|
run ledger. A result longer than that is a bad result. When a skill's real
|
||||||
|
product is long or structured (a file listing, a document body, a full
|
||||||
|
thread), write it to the service or a file as a **side effect** and return a
|
||||||
|
short summary plus a pointer (path / id) — never dump the payload into the
|
||||||
|
result string.
|
||||||
|
- **Never claim success you did not observe.** If the action failed, put the
|
||||||
|
real failure in `action_log` and set `new_state` back to `request.text` (see
|
||||||
|
the hard requirements).
|
||||||
|
|
||||||
|
### Multi-step chains
|
||||||
|
|
||||||
|
A request can take more than one action ("calculate 2*10 and send the result to
|
||||||
|
Pepper"). The runner does not ask one body to satisfy the whole request: it runs
|
||||||
|
the **next** skill, judges the outcome, and if more work remains re-dispatches
|
||||||
|
the request with a **run ledger** of the steps already taken. A body may
|
||||||
|
therefore run as a later step of a chain.
|
||||||
|
|
||||||
|
- `request.run_ledger` is a list of `{"query", "skill", "outcome"}` entries, one
|
||||||
|
per step already taken (empty on a first step). The most recent entry's
|
||||||
|
`outcome` is the previous step's result — the same bounded text the runner
|
||||||
|
shows the user.
|
||||||
|
- **If the request depends on the previous step's result, read it — never
|
||||||
|
recompute or fabricate it.** `from semif_agent.skills import last_result`
|
||||||
|
returns `run_ledger[-1]["outcome"]` (or `""`). Do not ask the LLM bridge to
|
||||||
|
redo a calculation or re-fetch a value an earlier step produced; that would
|
||||||
|
silently invent a working value. Prefer a literal value the user stated, then
|
||||||
|
the prior step's result, and only then generate novel text.
|
||||||
|
- A body still returns only its own step's `action_log` / `new_state`; the
|
||||||
|
runner owns the ledger and decides whether the chain continues.
|
||||||
|
|
||||||
|
### Rules (hard requirements)
|
||||||
|
|
||||||
|
- **Perform the real action.** If the skill's purpose involves an external
|
||||||
|
system, `act` must perform the real operation against the user's configured
|
||||||
|
service — using the endpoint, account, credential, and CLI-path values the
|
||||||
|
runner provides through `ctx.config`. Never simulate success, never return a
|
||||||
|
canned result as if the action happened, and never silently downgrade to "a
|
||||||
|
draft you can review": draft-only is allowed only when the requirements say
|
||||||
|
so. If the service is unreachable, auth fails, or a tool is missing, report
|
||||||
|
the real failure in `action_log` / `new_state` (status code, exception, or
|
||||||
|
message) — the agent will offer to fix or learn from it.
|
||||||
|
- **Stdlib only, transports included.** No third-party imports, no files
|
||||||
|
outside the project. Use stdlib transports for real integrations:
|
||||||
|
`urllib.request` / `http.client` for HTTP, `imaplib` / `smtplib` / `poplib`
|
||||||
|
for mail, `subprocess` to invoke a local CLI at the absolute path given in
|
||||||
|
`ctx.config` (check it exists first), file I/O under configured data dirs
|
||||||
|
for file integrations. Do not assume a tool, library, or config value
|
||||||
|
exists; fail honestly when it does not.
|
||||||
|
- **No mocking.** Sub-decisions use the real engine: build a
|
||||||
|
`DecisionRequest(state, question, options=[Option(id, description), ...])`
|
||||||
|
(both imported from `semif_agent.decisions`) and call
|
||||||
|
`ctx.engine.call(decision)`; return it inside
|
||||||
|
`ActionResult.decisions`.
|
||||||
|
- **Never swallow the request.** If the skill cannot act, return an
|
||||||
|
`ActionResult` with a short `action_log` explaining why and set `new_state`
|
||||||
|
back to `request.text`.
|
||||||
|
- **Data comes from the runner, never from you.** A skill body is executed
|
||||||
|
across many requests and owns no working data. Every required operational
|
||||||
|
value is declared in `CONTRACT` and provided by the runner through
|
||||||
|
`ctx.config` under a clear snake_case name — endpoints, accounts,
|
||||||
|
credentials, CLI paths, identifiers; never embed or fabricate working values,
|
||||||
|
never invent mock data, and never ask the human for operational data.
|
||||||
|
Optional values with a safe default are read with `ctx.config.get(...)`.
|
||||||
|
- **No test fixtures at runtime.** A body must never contain a hardcoded
|
||||||
|
localhost/loopback address, a test port, or fixture data. Which environment
|
||||||
|
it talks to is `ctx.config`'s decision, never the code's.
|
||||||
|
- **Request input for clarification when requirements are unclear from the
|
||||||
|
prompt.** If the human's intent is ambiguous, do not guess: return an
|
||||||
|
`ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`.
|
||||||
|
The run pauses and the human answers on `request.user_input`; `act` is then
|
||||||
|
called again — check `request.user_input` on the resume pass to finish the
|
||||||
|
run. This refines the product goal and requirements only — never operational
|
||||||
|
data (the runner supplies that).
|
||||||
|
- **Write files under configured data dirs only** (e.g. the directory named by
|
||||||
|
a config variable such as `ctx.config["output_dir"]`), never anywhere else on
|
||||||
|
disk.
|
||||||
|
- **No work at import time.** The module is imported when the skill loads and
|
||||||
|
again by its test; keep module scope to constants and function definitions. Do
|
||||||
|
not call the network, read files, or touch `ctx` at import.
|
||||||
|
- **`act` is single-phase and re-runs from the top.** After a `needs_input`
|
||||||
|
pause the human's answer arrives on `request.user_input` and `act` is invoked
|
||||||
|
again from the beginning — re-derive the query and config, consume
|
||||||
|
`request.user_input`, and do not re-ask a question you already have an answer
|
||||||
|
for. `request.meta` is a scratch dict carried on the same request across the
|
||||||
|
pause, so a body can cache a computed value or an already-collected answer
|
||||||
|
there and reuse it on the resume pass instead of recomputing or re-asking —
|
||||||
|
see how `nextcloud.create_event` caches the extracted title/description and the
|
||||||
|
answers it collected.
|
||||||
|
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
||||||
|
- **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
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
```python
|
||||||
|
INTEGRATION = {
|
||||||
|
"service": "<the bridge's service id, from the catalog>",
|
||||||
|
"transport": "http",
|
||||||
|
"config_vars": ["<base URL config var>", "<any other config var it reads>"],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
- **Send the auth header when the catalog lists one.** If the catalog names an
|
||||||
|
auth config var and header, read the var and send it in that header when it is
|
||||||
|
set; omit the header when the value is blank.
|
||||||
|
- **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 `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
|
||||||
|
requirements) asks for it. Never broadcast, never message a contact the user
|
||||||
|
did not name or confirm, and never fabricate a message body as a working
|
||||||
|
value.
|
||||||
|
- **Report real failures.** A bridge error, an unknown recipient, or an empty
|
||||||
|
inbox is reported honestly in `action_log` / `new_state` — use the error
|
||||||
|
statuses the catalog documents. Never claim a message was sent or read when it
|
||||||
|
was not.
|
||||||
|
- **The bridge owns its own state.** Read cursors and similar state live in the
|
||||||
|
bridge, not in the body; the body keeps no working state of its own.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- 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 `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
|
||||||
|
service actually returned.
|
||||||
|
- Act like a developer eliciting requirements from a product owner: when the
|
||||||
|
prompt leaves a behavioral or integration choice open, prefer a clarifying
|
||||||
|
`needs_input` over guessing — a clarifying question is cheaper than a wrong
|
||||||
|
body.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
A generated skill is accepted only if:
|
||||||
|
|
||||||
|
1. It parses as Python (`ast.parse` succeeds), defines a module-level `act`
|
||||||
|
function, and imports every name it uses (`ActionResult` from
|
||||||
|
`semif_agent.skills`; `DecisionRequest`/`Option` from `semif_agent.decisions`
|
||||||
|
only when it actually builds a sub-decision; each stdlib module it calls — no
|
||||||
|
`NameError` at run time).
|
||||||
|
2. Its `name` matches the leaf-name regex and its `category` is given.
|
||||||
|
3. Its body imports nothing outside the stdlib and the agent package.
|
||||||
|
4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
|
||||||
|
5. It is single-purpose and does not duplicate an existing category leaf.
|
||||||
|
6. It derives its per-request arguments from `request.text` — resolving a target
|
||||||
|
against a real candidate set with a SemIf sub-decision when one exists —
|
||||||
|
rather than ignoring the query or hardcoding values.
|
||||||
|
7. `CONTRACT` is present, flat, and every key is read from `ctx.config`;
|
||||||
|
optional values are read with `.get`. No per-request argument is a contract
|
||||||
|
key.
|
||||||
|
8. Every required operational value it needs is declared in `CONTRACT` — nothing
|
||||||
|
is embedded, fabricated, or asked of the human.
|
||||||
|
9. It returns 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.
|
||||||
|
10. If its purpose is an external action, `act` performs the real operation via
|
||||||
|
the configured service/transport (no simulated success, no draft-by-default)
|
||||||
|
and reports real failures honestly.
|
||||||
|
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 the service it targets is fronted by a bridge, it calls that bridge over
|
||||||
|
HTTP (never the service's native protocol); otherwise it may call the
|
||||||
|
service's HTTP API directly. A messaging skill resolves recipients with a
|
||||||
|
SemIf sub-decision and sends only on explicit user intent.
|
||||||
|
14. It is small enough to be ingested whole by the fidelity decision (a body
|
||||||
|
over the engine's artifact budget is rejected as too long) — delegate
|
||||||
|
complex protocol details to a bridge rather than hand-rolling them (a simple
|
||||||
|
HTTP call needs no bridge).
|
||||||
|
|
||||||
|
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
|
||||||
|
body outright. The rest are not statically rejected: a missing or inconsistent
|
||||||
|
`INTEGRATION` (#11) is inferred and the body is accepted badged `unverified`, a
|
||||||
|
third-party import (#3) only fails when the module is actually imported, and
|
||||||
|
import-time work (#12) only shows up when it runs. The fidelity gate rewrites a
|
||||||
|
body once for these, then accepts it — so treat every item as required, not
|
||||||
|
optional.
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
# Semif Agent
|
|
||||||
|
|
||||||
A local desktop CLI agent whose control flow is a single decision model (SemIf). Inputs are gated, scored, queued, and dispatched through a skill tree; every decision is logged as a labeled training row, and the decision model is fine-tuned at regular intervals on the accumulated prediction-vs-observation cost.
|
|
||||||
|
|
||||||
## Engine: SemIf (local decision layer)
|
|
||||||
|
|
||||||
- **SemIf** (formerly OpenJev, TheoLeeCJ, MIT) is a local rebuild of Jev's interface pattern. One forward pass reads typed option logits directly from a model; no answer sentence, no decoding loop.
|
|
||||||
- Contract: input `{state, question, options[]}`, output per-option probabilities conditional on the supplied options. Probabilities are conditional on the option set, not absolute confidence — calibrate per workload (SemIf ships per-workload temperature scaling).
|
|
||||||
- **Why local**: desktop target, data stays in-network (SemIf's data boundary), runs on a home GPU (or CPU via llama.cpp). Jev (hosted) is not in scope.
|
|
||||||
- Decision model is pinned to an exact revision; every swap is auditable via prompt hashes in SemIf's output.
|
|
||||||
|
|
||||||
## Core loop
|
|
||||||
|
|
||||||
```
|
|
||||||
intake (typed / events / timers / other skills)
|
|
||||||
└─ contains_request? (gate: is this even actionable?)
|
|
||||||
└─ choice (SemIf: "should this interrupt the current process?")
|
|
||||||
├─ yes → preempt current, requeue it with state preserved
|
|
||||||
└─ no → score (SemIf: "how urgent?")
|
|
||||||
└─ priority queue, sorted by urgency desc
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Scheduler**: run head of queue when idle. A new interrupt displaces the current process, which itself requeues preserving its state.
|
|
||||||
- **Concurrency** (TODO resolved): single execution slot for v1. SemIf's shared-state mode (one prefetched state branched across many criteria in parallel) is the lever for parallelizing decisions later, not concurrent process execution.
|
|
||||||
- **Tie-breaking**: FIFO within equal urgency, recency as secondary key.
|
|
||||||
- **Priority ageing**: queued items decay upward over time so they can't starve.
|
|
||||||
- **Bounds**: max queue depth; overflow rejects with a notification.
|
|
||||||
|
|
||||||
## Decision templates
|
|
||||||
|
|
||||||
All decisions are SemIf calls: `{state, question, options[]}`. State is the current process + input. Options are typed with descriptions.
|
|
||||||
|
|
||||||
- **`choice`** — binary: `interrupt` / `defer`. Interrupt iff `P(interrupt) >= τ`.
|
|
||||||
- **`score`** — ordinal urgency: `critical` / `high` / `medium` / `low`, mapped to numeric weights for sorting.
|
|
||||||
- **skill navigation** — at each tree level: choose category / descend; the category level offers a `create_category` suggestion and the leaf level a `create_skill` suggestion.
|
|
||||||
- **`read_next()`** — argument selection within a skill (e.g., which contact is "girlfriend").
|
|
||||||
|
|
||||||
**LLM/SemIf boundary**: SemIf for fast, repeated, low-latency decisions (gating, scoring, routing, argument selection). LLM for generation and assessment (email body, self-assessment summary). Never the reverse.
|
|
||||||
|
|
||||||
## Skill tree
|
|
||||||
|
|
||||||
- Structure: categories → skills → actions. Top level listed at each level.
|
|
||||||
- Navigation is a chain of SemIf choices, one per level, descending until a leaf skill matches.
|
|
||||||
- Navigation offers a `create_category` suggestion at the category level and a `create_skill` suggestion at the leaf level. Both are live: the decision model, driven in normal generation mode, authors a title + description (broad bucket for a category, single specific action for a skill), and the stub is persisted to the category registry and merged into the running tree. For a new skill the stub is then promoted to a runnable body: a separate, larger OpenAI-compatible model writes the `predict`/`act` code against the `SKILL.md` contract, persisted under `data/skills/` and hot-loaded. The newly created leaf is then executed directly (no re-dispatch through navigation) so the request that prompted creation is answered: `create_category` → `create_skill` → run, or `create_skill` → run.
|
|
||||||
|
|
||||||
### Skill manifest
|
|
||||||
- name, category, description, allowed inputs, action list, cost budget, decision log reference.
|
|
||||||
|
|
||||||
## Skill anatomy
|
|
||||||
|
|
||||||
Every skill run follows the same loop:
|
|
||||||
|
|
||||||
1. **observe baseline** — capture state relevant to the skill.
|
|
||||||
2. **make prediction** — predict outcome; log it.
|
|
||||||
3. **act** — execute actions (possibly calling `read_next()`-style SemIf decisions for arguments).
|
|
||||||
4. **observe outcome** — capture post-action state.
|
|
||||||
5. **self-assess** (LLM) — "have I succeeded?" → success/failure + summary + **updated request** back to the priority queue.
|
|
||||||
|
|
||||||
- The self-assessment result **labels** every SemIf decision made during that run (`choice`, `score`, navigation, argument selection): the predicted distribution vs. the observed outcome is one labeled training row.
|
|
||||||
- Per-skill cost budget: a run that exceeds it fails fast and requeues with a degraded goal.
|
|
||||||
|
|
||||||
## Learning / fine-tuning pipeline
|
|
||||||
|
|
||||||
- **Log**: every decision row → `{state, question, options, predicted_probs, observed_outcome}` — SemIf `decisions.jsonl`-compatible, so logs replay directly into the scorer.
|
|
||||||
- **Cost function**: loss between the predicted distribution and the observed outcome — cross-entropy / NLL under a proper scoring rule, plus optional calibration loss. This is the training signal.
|
|
||||||
- **Labels**: self-assessment output by default; human confirmations/corrections override and become high-weight labels.
|
|
||||||
- **"Dreaming"** — a cronjob at a regular interval: accumulate logged rows → compute cost over the period → fine-tune the decision model on them → CI/CD validates (accuracy / ECE on a held-out slice, prompt-hash regression) → swap in the new pinned model revision.
|
|
||||||
- **GPU offload**: training runs on a beefier GPU; the running agent keeps a frozen inference revision until a swap validates.
|
|
||||||
- Cold start: no labels yet — seed from self-assessed runs only; human overrides accelerate early calibration.
|
|
||||||
|
|
||||||
## Worked examples
|
|
||||||
|
|
||||||
### Example 1
|
|
||||||
- current_process: none
|
|
||||||
- input: "send my girlfriend an email that says that I'm going to be late to the party"
|
|
||||||
- contains_request: yes
|
|
||||||
- interrupt_current: yes
|
|
||||||
- skill_selection: email => compose => transcribe(input): [code block that uses SemIf `read_next()` to determine "girlfriend" from contacts, plus a normally functioning LLM for the email body]
|
|
||||||
|
|
||||||
### Example 2
|
|
||||||
- current_process: driving car
|
|
||||||
- input: "send my girlfriend an email that says that I'm going to be late to the party"
|
|
||||||
- interrupt_current: no
|
|
||||||
- priority: .21
|
|
||||||
- skill_selection: response => rejection(input)
|
|
||||||
|
|
||||||
### Example 3
|
|
||||||
- current_process: driving car
|
|
||||||
- input: "holy shit stop!"
|
|
||||||
- contains_request: yes
|
|
||||||
- interrupt_current: yes
|
|
||||||
- skill_selection: driving => decelerate(input)
|
|
||||||
|
|
||||||
### Example 4 (skill creation)
|
|
||||||
- current_process: none
|
|
||||||
- input: "tell me if my package was delivered"
|
|
||||||
- contains_request: yes
|
|
||||||
- interrupt_current: yes
|
|
||||||
- skill_selection: tracking => (no leaf) => create_skill
|
|
||||||
- the codegen model authors `tracking.check_delivery` (title+description from the decision model; `predict`/`act` body from a larger OpenAI-compatible model per `SKILL.md`) → body persisted + registered → requeue → skill_selection: tracking => check_delivery(input)
|
|
||||||
|
|
||||||
### Example 5 (self-assessment + dream)
|
|
||||||
- current_process: email compose
|
|
||||||
- input: "send my girlfriend an email…" → email compose succeeds but sends to the wrong contact (`read_next` picked wrong)
|
|
||||||
- self-assess: fail → labels the `read_next` decision row (predicted_probs vs wrong outcome)
|
|
||||||
- cost computed, logged
|
|
||||||
- next dream cycle: row included in fine-tune → model revision swapped → `read_next` recalibrated
|
|
||||||
|
|
||||||
## Open questions
|
|
||||||
|
|
||||||
- **Safety / authority**: which inputs may interrupt high-stakes processes (driving-grade)? Is interrupt a per-skill permission, not a global default?
|
|
||||||
- **Queue persistence**: is the priority queue in-memory or durable across restarts?
|
|
||||||
- **Input taxonomy**: enumerate intake sources and their `contains_request` gating semantics.
|
|
||||||
- **Privacy boundary**: all data stays local — confirm no telemetry even for dreaming.
|
|
||||||
- **Override UX**: how do human confirmations/corrections get surfaced and captured cheaply?
|
|
||||||
+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/`.
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
# SKILL.md — the contract for new skills
|
|
||||||
|
|
||||||
This file is the authoritative spec for what a new skill is and how its code
|
|
||||||
body must be written. It is fed verbatim to the code-generation model so every
|
|
||||||
generated skill is consistent, and it is read by humans who want to know what a
|
|
||||||
good skill looks like.
|
|
||||||
|
|
||||||
## What a skill is
|
|
||||||
|
|
||||||
A skill is a **leaf** in the agent's skill tree, reached by a chain of SemIf
|
|
||||||
decisions (category -> skill). It is one specific, single-purpose action the
|
|
||||||
agent can take — never a broad bucket (that is a category's job). It runs the
|
|
||||||
standard skill loop: observe -> predict -> act -> observe -> assess.
|
|
||||||
|
|
||||||
A skill is two things:
|
|
||||||
|
|
||||||
1. **A manifest** — the registry entry that makes it navigable and describes
|
|
||||||
what it does.
|
|
||||||
2. **A code body** — a runnable Python module implementing the `predict` and
|
|
||||||
`act` phases.
|
|
||||||
|
|
||||||
## Manifest schema
|
|
||||||
|
|
||||||
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
|
|
||||||
|
|
||||||
| Field | Meaning |
|
|
||||||
| -------------------- | -------------------------------------------------------------------- |
|
|
||||||
| `name` | `category.skill` dotted snake_case id. Lowercase letters, digits, `_` and `.` only (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`). Single purpose. |
|
|
||||||
| `category` | The top-level category bucket the skill lives under. |
|
|
||||||
| `description` | One to two sentences: what the skill does, for navigation. |
|
|
||||||
| `allowed_inputs` | What the skill accepts / needs as input context. |
|
|
||||||
| `actions` | The concrete actions the skill takes. |
|
|
||||||
| `cost_budget` | Relative budget for one run; a run that exceeds it fails fast. |
|
|
||||||
| `decision_log_ref` | Reference to the decision rows this skill logged during a run. |
|
|
||||||
|
|
||||||
Only `name` and `description` are required for a stub; the rest fill in as the
|
|
||||||
skill is exercised.
|
|
||||||
|
|
||||||
## Code body contract
|
|
||||||
|
|
||||||
The generated module is persisted to `data/skills/<category>/<name>.py` and
|
|
||||||
imported at runtime. It must satisfy **all** of the following:
|
|
||||||
|
|
||||||
### Required functions
|
|
||||||
|
|
||||||
```python
|
|
||||||
def predict(ctx, request) -> Prediction:
|
|
||||||
"""Forecast + make any SemIf sub-decisions. Return the prediction."""
|
|
||||||
|
|
||||||
def act(ctx, request, prediction) -> ActionResult:
|
|
||||||
"""Execute the action. Return the result + new state."""
|
|
||||||
```
|
|
||||||
|
|
||||||
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and
|
|
||||||
`ctx.config` (the agent config dict).
|
|
||||||
- `request` is the `Request` being handled.
|
|
||||||
- `Prediction(text: str, decisions: list)` and
|
|
||||||
`ActionResult(action_log: str, new_state: str, needs_input: str | None = None)`
|
|
||||||
are imported from
|
|
||||||
`semif_agent.skills`; return those exact types. `decisions` carries any
|
|
||||||
`(DecisionRequest, DecisionResult)` pairs made during predict so they are
|
|
||||||
logged as training rows. `needs_input` carries a question for the human; see
|
|
||||||
the rules below.
|
|
||||||
|
|
||||||
### Rules (hard requirements)
|
|
||||||
|
|
||||||
- **Stdlib only.** No third-party imports, no files outside the project. The
|
|
||||||
core agent is pure-stdlib and runs on the thin dev box.
|
|
||||||
- **No mocking.** Sub-decisions use the real engine: build a
|
|
||||||
`DecisionRequest(state, question, options=[Option(id, description), ...])`
|
|
||||||
and call `ctx.engine.call(decision)`; return it inside `Prediction.decisions`.
|
|
||||||
- **Never swallow the request.** If the skill cannot act, return an
|
|
||||||
`ActionResult` with a short `action_log` explaining why and set `new_state`
|
|
||||||
back to `request.text`.
|
|
||||||
- **Request input when data is missing.** If a required piece of data is not
|
|
||||||
in the request or in local files, do not fail silently: return an
|
|
||||||
`ActionResult(action_log="...", new_state=request.text, needs_input="<question>")`.
|
|
||||||
The run pauses and the human is asked. The answer arrives on
|
|
||||||
`request.user_input` and `act` is called again with the *same* prediction —
|
|
||||||
check `request.user_input` on the resume pass to finish the run (or ask again
|
|
||||||
if it is still insufficient).
|
|
||||||
- **Write files under configured data dirs only** (e.g. `ctx.config["drafts"]`),
|
|
||||||
never anywhere else on disk.
|
|
||||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
|
||||||
- **Names match the manifest.** The module is imported as its manifest name;
|
|
||||||
the functions are `predict` and `act` exactly.
|
|
||||||
|
|
||||||
## Conventions
|
|
||||||
|
|
||||||
- Single purpose, single file, single module.
|
|
||||||
- Avoid duplicating an existing skill in the same category.
|
|
||||||
- `predict` resolves ambiguity (arguments, recipients, targets) with SemIf
|
|
||||||
sub-decisions, mirroring how `email.compose` resolves its recipient.
|
|
||||||
- `act` performs the concrete action and writes a human-readable `action_log`
|
|
||||||
that the self-assessment LLM can judge.
|
|
||||||
|
|
||||||
## Acceptance criteria
|
|
||||||
|
|
||||||
A generated skill is accepted only if:
|
|
||||||
|
|
||||||
1. It compiles (`compile(..., "exec")` succeeds) and defines both `predict`
|
|
||||||
and `act`.
|
|
||||||
2. Its `name` matches the manifest regex and its `category` is given.
|
|
||||||
3. Its body imports nothing outside the stdlib and the agent package.
|
|
||||||
4. It uses `ctx.engine` (never mocks) and returns proper `Prediction` /
|
|
||||||
`ActionResult` types.
|
|
||||||
5. It is single-purpose and does not duplicate an existing category leaf.
|
|
||||||
|
|
||||||
## Worked example
|
|
||||||
|
|
||||||
`email.compose` resolves its recipient with a SemIf sub-decision, then writes a
|
|
||||||
draft file:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def predict(ctx, request):
|
|
||||||
contacts = read_contacts(ctx.config) # config-driven, local data
|
|
||||||
decision = DecisionRequest(
|
|
||||||
state=f"{request.text} [current process: none]",
|
|
||||||
question="Which contact is the intended recipient?",
|
|
||||||
options=[Option(c["name"], c.get("description", "")) for c in contacts]
|
|
||||||
+ [Option("none", "None of the listed contacts.")],
|
|
||||||
)
|
|
||||||
result = ctx.engine.call(decision)
|
|
||||||
return Prediction(text=f"recipient is {result.selected}",
|
|
||||||
decisions=[(decision, result)])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
recipient = prediction.text.removeprefix("recipient is ")
|
|
||||||
drafts = Path(ctx.config.get("drafts", "data/drafts"))
|
|
||||||
drafts.mkdir(parents=True, exist_ok=True)
|
|
||||||
target = drafts / f"{request.id}.txt"
|
|
||||||
target.write_text(f"To: {recipient}\nBody: {request.text}\n")
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"email.compose: wrote draft {target} for {recipient!r}.",
|
|
||||||
new_state=f"Draft written to {target.name} for {recipient}.",
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
Write skill bodies in this shape: resolve ambiguity in `predict` via
|
|
||||||
`ctx.engine`, do the work in `act`, keep both stdlib-only, and return the
|
|
||||||
proper types.
|
|
||||||
+186
@@ -0,0 +1,186 @@
|
|||||||
|
# TESTGEN.md — the contract for skill test artifacts
|
||||||
|
|
||||||
|
This file is the authoritative spec for the **testing** side of a skill. It is
|
||||||
|
fed verbatim (alongside the finished `skill.py`) to the model that produces the
|
||||||
|
test artifact. The runnable body contract lives in `CODEGEN.md`; this file is
|
||||||
|
deliberately separate so the body writer never embeds test data and the test 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:
|
||||||
|
|
||||||
|
| File | Meaning |
|
||||||
|
| ----------------- | ------------------------------------------------------------------ |
|
||||||
|
| `contract.json` | A mirror of the body's `CONTRACT` constant: what the runner must provide. Derived from `skill.py`, not authored here. |
|
||||||
|
| `skill.test.py` | A hermetic mechanics test, runnable as `python skill.test.py`. |
|
||||||
|
|
||||||
|
## What the test is for (and is not)
|
||||||
|
|
||||||
|
The test is a **hermetic mechanics check**: it proves the body's code runs, its
|
||||||
|
config resolution works, its request construction is sane, and its error paths
|
||||||
|
return proper results. It is deliberately cut off from the outside world.
|
||||||
|
|
||||||
|
It is **not** proof that the real integration works. Skill bodies act on the
|
||||||
|
user's actual services; only a real run against that service can verify the
|
||||||
|
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;
|
||||||
|
each value is a plain-language, semantic description of the expected values for
|
||||||
|
that variable (what it is, what good values look like).
|
||||||
|
|
||||||
|
The body declares this itself as a module-level `CONTRACT` constant (see
|
||||||
|
`CODEGEN.md`); `contract.json` is a persisted mirror of it, and the same
|
||||||
|
contract object is handed to you as context. You do not author or change the
|
||||||
|
contract.
|
||||||
|
|
||||||
|
This contract exists for exactly two consumers:
|
||||||
|
|
||||||
|
1. **User input** — the config step asks the human for these variables when
|
||||||
|
they are not already configured.
|
||||||
|
2. **SemIf** — the config search and the record-vs-ask decision route on the
|
||||||
|
variable names.
|
||||||
|
|
||||||
|
Therefore the contract must be flat and semantic. Do NOT put type declarations,
|
||||||
|
validation logic, or nested data structures in it — the skill body and the test
|
||||||
|
implement whatever type safety and validation they need on their own. The test
|
||||||
|
writer consumes `skill.py` in context and keeps the artifact compatible, so the
|
||||||
|
contract never has to carry that burden. Convoluted structure here is
|
||||||
|
pointless: it only confuses the human and the decision model.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- Top level is exactly one JSON object; no arrays, no nesting.
|
||||||
|
- Each key is the snake_case name of a variable the body reads from
|
||||||
|
`ctx.config`.
|
||||||
|
- Each value is a non-empty string describing the expected values in plain
|
||||||
|
language (e.g. `"The email address the message is sent from."`).
|
||||||
|
- The keys are exactly the body's `CONTRACT` constant; every declared key is
|
||||||
|
read from `ctx.config`. Do not invent keys the body does not use.
|
||||||
|
- Optional values with safe defaults are read with `ctx.config.get(...)` and
|
||||||
|
are not contract keys.
|
||||||
|
|
||||||
|
## skill.test.py
|
||||||
|
|
||||||
|
A stdlib-only Python script that:
|
||||||
|
|
||||||
|
- Runs as `python skill.test.py` from the skill folder (its cwd is the folder,
|
||||||
|
so the `skill` module is importable at `import skill`).
|
||||||
|
- Is hermetic: it never contacts an external network, never touches the user's
|
||||||
|
real services, and never writes outside the folder.
|
||||||
|
- Embeds its fixture data **inline** as Python literals — no external files.
|
||||||
|
- For a body that performs HTTP in `act`, starts a real loopback server
|
||||||
|
(`http.server` on `127.0.0.1`, ephemeral port) and passes its URL to the body
|
||||||
|
through the fixture config — the same `ctx.config` key the body reads.
|
||||||
|
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 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.
|
||||||
|
- Exercises the skill's `act` against those fixtures — call it directly with a
|
||||||
|
real-ish `ActionContext` (a fake `engine` is acceptable **in the test only**;
|
||||||
|
the test is the exception to the no-mocking rule for the decision engine).
|
||||||
|
- Exits 0 on success and non-zero on failure (use `assert`/`sys.exit(1)` with a
|
||||||
|
message). No third-party imports.
|
||||||
|
- Covers at least the happy path (through the loopback server where the body
|
||||||
|
does HTTP) and one edge case (missing input, unclear request, unreachable
|
||||||
|
target).
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
The test artifact is accepted only if:
|
||||||
|
|
||||||
|
1. `skill.test.py` parses as Python — the only static check — and runs to exit 0
|
||||||
|
when executed from the skill folder; on failure the captured output drives a
|
||||||
|
regeneration.
|
||||||
|
2. It imports only the stdlib and the agent package, embeds its fixtures inline
|
||||||
|
(no external files), and is hermetic (no external network, no real services).
|
||||||
|
These are required of every test but are **not** statically verified, so do
|
||||||
|
not rely on a checker to catch a violation.
|
||||||
|
3. The test stays compatible with the body's `CONTRACT` (the same variable
|
||||||
|
names the body reads from `ctx.config`).
|
||||||
|
|
||||||
|
Produce one artifact: `skill.test.py` (derived from `skill.py` plus its
|
||||||
|
`CONTRACT`, with fixture data embedded inline).
|
||||||
|
|
||||||
|
## Worked example
|
||||||
|
|
||||||
|
A body that checks a service over HTTP with `service_url` read from
|
||||||
|
`ctx.config`. The test stands up a loopback `http.server` and points the fixture
|
||||||
|
config at it, so the body's real HTTP call is exercised without leaving the
|
||||||
|
machine:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
from semif_agent.decisions import DecisionResult, Request
|
||||||
|
from semif_agent.skills import ActionContext
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
Handler.seen.append(self.path)
|
||||||
|
body = b'{"status": "ok"}'
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FakeEngine:
|
||||||
|
def call(self, decision):
|
||||||
|
return DecisionResult(
|
||||||
|
request=decision,
|
||||||
|
option_ids=[o.id for o in decision.options],
|
||||||
|
probabilities=[1.0] + [0.0] * (len(decision.options) - 1),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||||
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||||
|
url = f"http://127.0.0.1:{server.server_address[1]}/health"
|
||||||
|
try:
|
||||||
|
ctx = ActionContext(engine=FakeEngine(), config={"service_url": url})
|
||||||
|
req = Request("check the service")
|
||||||
|
skill = __import__("skill")
|
||||||
|
result = skill.act(ctx, req)
|
||||||
|
assert result.action_log, "act must log what it did"
|
||||||
|
assert Handler.seen == ["/health"], f"body must really call the service: {Handler.seen}"
|
||||||
|
print(result.action_log)
|
||||||
|
print("ok")
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
```
|
||||||
+345
-22
@@ -1,35 +1,358 @@
|
|||||||
{
|
{
|
||||||
"_comment": "Per-machine config. config.json is gitignored; copy this file to config.json and adjust paths. The box (guppy) keeps its own config.json with local paths.",
|
|
||||||
"tau": 0.6,
|
"tau": 0.6,
|
||||||
"max_reentries": 3,
|
"max_reentries": 3,
|
||||||
"queue": {"max_size": 100, "age_rate": 0.01},
|
"query_recall_window": 30,
|
||||||
"engine": {
|
"new_skill_creation": "deny",
|
||||||
"backend": "llamacpp",
|
"verbosity": "result",
|
||||||
"source": "Qwen/Qwen3.5-4B",
|
"chain": {
|
||||||
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a",
|
"result_chars": 300
|
||||||
"gguf": "/home/abby/models/Qwen3.5-4B-Q4_K_M.gguf",
|
|
||||||
"context_tokens": 4096,
|
|
||||||
"threads": 8
|
|
||||||
},
|
},
|
||||||
"llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"},
|
"assess": {
|
||||||
"codegen": {
|
"done_tau": 0.5,
|
||||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Larger/slower than the decision or self-assessment model. No max_tokens cap: qwen38-iq3s reasons extensively (~7 min) before emitting the body; reasoning is filtered automatically. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream in minutes instead of blocking on the total timeout.",
|
"fail_tau": 0.5
|
||||||
|
},
|
||||||
|
"timezone": "",
|
||||||
|
"navigation": {
|
||||||
|
"intent_tau": 0.6,
|
||||||
|
"category_tau": 0.75,
|
||||||
|
"action_tau": 0.5,
|
||||||
|
"softmax_bypass_tau": 0.5
|
||||||
|
},
|
||||||
|
"queue": {
|
||||||
|
"max_size": 100
|
||||||
|
},
|
||||||
|
"engine": {
|
||||||
|
"provider": "semif",
|
||||||
|
"backend": "llamacpp",
|
||||||
|
"context_tokens": 4096,
|
||||||
|
"threads": 8,
|
||||||
|
"gpu_layers": 0,
|
||||||
|
"gpu_device": null,
|
||||||
|
"gpu_split": 0,
|
||||||
|
"winnow": {
|
||||||
|
"base_url": "http://127.0.0.1:8091",
|
||||||
|
"model": "",
|
||||||
|
"context_tokens": 32768,
|
||||||
|
"api_key": "!secret engine_winnow_api_key",
|
||||||
|
"timeout": 120,
|
||||||
|
"retries": 0,
|
||||||
|
"user_agent": "semif-agent",
|
||||||
|
"extra_headers": {}
|
||||||
|
},
|
||||||
|
"ollama": {
|
||||||
|
"base_url": "http://127.0.0.1:11434",
|
||||||
|
"model": "",
|
||||||
|
"context_tokens": 16384,
|
||||||
|
"api_key": "!secret engine_ollama_api_key",
|
||||||
|
"timeout": 120,
|
||||||
|
"retries": 0,
|
||||||
|
"keep_alive": "",
|
||||||
|
"user_agent": "semif-agent",
|
||||||
|
"extra_headers": {}
|
||||||
|
},
|
||||||
|
"gguf": ""
|
||||||
|
},
|
||||||
|
"llm": {
|
||||||
|
"provider": "ollama",
|
||||||
"base_url": "http://localhost:11434/v1",
|
"base_url": "http://localhost:11434/v1",
|
||||||
"model": "qwen38-iq3s",
|
"model": "",
|
||||||
"timeout": 1200,
|
"api_key": "!secret llm_api_key",
|
||||||
|
"user_agent": "",
|
||||||
|
"timeout": 600,
|
||||||
"stream": false,
|
"stream": false,
|
||||||
|
"idle_warn": 30,
|
||||||
|
"idle_timeout": 120,
|
||||||
|
"context_window": 0,
|
||||||
|
"temperature": 0.2,
|
||||||
|
"top_p": 0.9,
|
||||||
|
"presence_penalty": 0.0,
|
||||||
|
"frequency_penalty": 0.0,
|
||||||
|
"disable_thinking": true,
|
||||||
|
"semif": {
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": 256
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"codegen": {
|
||||||
|
"provider": "ollama",
|
||||||
|
"base_url": "http://localhost:11434/v1",
|
||||||
|
"model": "",
|
||||||
|
"api_key": "!secret codegen_api_key",
|
||||||
|
"user_agent": "",
|
||||||
|
"timeout": 3600,
|
||||||
|
"stream": true,
|
||||||
"idle_warn": 60,
|
"idle_warn": 60,
|
||||||
"idle_timeout": 180
|
"idle_timeout": 180,
|
||||||
|
"context_window": 0,
|
||||||
|
"smart_limit": 250000,
|
||||||
|
"warn_limit": 500000,
|
||||||
|
"max_fill_ratio": 0.9,
|
||||||
|
"warn_fill_ratio": 0.7,
|
||||||
|
"max_output": 0.85,
|
||||||
|
"chars_per_token": 4.0,
|
||||||
|
"temperature": 1,
|
||||||
|
"top_p": 0.95,
|
||||||
|
"presence_penalty": 0,
|
||||||
|
"frequency_penalty": 1,
|
||||||
|
"max_attempts": 3,
|
||||||
|
"approval": {
|
||||||
|
"wait_timeout": 900
|
||||||
|
},
|
||||||
|
"fidelity": {
|
||||||
|
"enabled": true,
|
||||||
|
"max_attempts": 1,
|
||||||
|
"tau": 0.6
|
||||||
|
},
|
||||||
|
"repair": {
|
||||||
|
"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": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"degeneration": {
|
||||||
|
"enabled": true,
|
||||||
|
"threshold": 0.9,
|
||||||
|
"interval": 8000,
|
||||||
|
"window": 2000,
|
||||||
|
"min_chars": 4000
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"skill_bodies": "data/skills",
|
"skill_bodies": "data/skills",
|
||||||
"skills": {
|
|
||||||
"email": {"cost_budget": 1.0},
|
|
||||||
"contacts": "data/contacts.json",
|
|
||||||
"drafts": "data/drafts",
|
|
||||||
"packages": "data/packages.json"
|
|
||||||
},
|
|
||||||
"log": "data/decisions.jsonl",
|
"log": "data/decisions.jsonl",
|
||||||
"trace": "data/runs.jsonl",
|
"trace": "data/runs.jsonl",
|
||||||
"category_registry": "data/categories.json",
|
"category_registry": "data/categories.json",
|
||||||
"dashboard": {"port": 8765, "host": "0.0.0.0"}
|
"simplex_chat": {
|
||||||
|
"port": 5226,
|
||||||
|
"display_name": "semif",
|
||||||
|
"forward_port": 5228,
|
||||||
|
"forward_display_name": "semif-forward"
|
||||||
|
},
|
||||||
|
"gateway": {
|
||||||
|
"humanize": {
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 20.0,
|
||||||
|
"max_tokens": 200,
|
||||||
|
"max_chars": 600
|
||||||
|
},
|
||||||
|
"simplex": {
|
||||||
|
"enabled": true,
|
||||||
|
"ws_url": "ws://127.0.0.1:5226",
|
||||||
|
"allowed_users": [],
|
||||||
|
"allow_all_users": false,
|
||||||
|
"auto_accept": true,
|
||||||
|
"home_channel": "",
|
||||||
|
"reply_prefix": "",
|
||||||
|
"text_batch_delay": 0.8,
|
||||||
|
"reconnect": {
|
||||||
|
"initial": 1.0,
|
||||||
|
"max": 60.0,
|
||||||
|
"jitter": 0.2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"lxmf": {
|
||||||
|
"enabled": false,
|
||||||
|
"allowed_users": [],
|
||||||
|
"allow_all_users": false,
|
||||||
|
"display_name": "semif",
|
||||||
|
"announce_interval": 3600,
|
||||||
|
"stamp_cost": 8,
|
||||||
|
"desired_method": "direct",
|
||||||
|
"propagation_node": "",
|
||||||
|
"config_dir": "",
|
||||||
|
"storage_path": "",
|
||||||
|
"home_channel": "",
|
||||||
|
"reply_prefix": "",
|
||||||
|
"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": {
|
||||||
|
"enabled": false,
|
||||||
|
"chat_id": "voice",
|
||||||
|
"display_name": "voice",
|
||||||
|
"home_channel": "voice",
|
||||||
|
"reply_prefix": "",
|
||||||
|
"result_only": true,
|
||||||
|
"max_speak_chars": 600,
|
||||||
|
"read": {
|
||||||
|
"enabled": true,
|
||||||
|
"chunk_chars": 300
|
||||||
|
},
|
||||||
|
"listen_timeout_s": 3.0,
|
||||||
|
"cue": {
|
||||||
|
"enabled": true,
|
||||||
|
"frequency": 880,
|
||||||
|
"duration_ms": 120,
|
||||||
|
"volume": 0.9,
|
||||||
|
"submit_frequency": 0,
|
||||||
|
"submit_duration_ms": 100,
|
||||||
|
"submit_notes": [
|
||||||
|
[
|
||||||
|
1046.5,
|
||||||
|
70
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1568.0,
|
||||||
|
90
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"note_gap_ms": 20
|
||||||
|
},
|
||||||
|
"wake": {
|
||||||
|
"model": "hey_computer",
|
||||||
|
"threshold": 0.2,
|
||||||
|
"inference_framework": "onnx",
|
||||||
|
"model_dir": ""
|
||||||
|
},
|
||||||
|
"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
|
||||||
|
},
|
||||||
|
"audio": {
|
||||||
|
"input_device": "",
|
||||||
|
"output_device": "",
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"frame_ms": 80,
|
||||||
|
"capture_sample_rate": 0,
|
||||||
|
"output_sample_rate": 0,
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
[
|
|
||||||
{"name": "alice", "description": "Partner; usually home by six."},
|
|
||||||
{"name": "bob", "description": "Work colleague on the ops team."},
|
|
||||||
{"name": "carol", "description": "Landlord; prefers email."}
|
|
||||||
]
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
[
|
|
||||||
{"id": "1Z999AA10123456784", "status": "out for delivery"},
|
|
||||||
{"id": "1Z999BB10234567891", "status": "delivered"},
|
|
||||||
{"id": "1Z999CC10345678908", "status": "at sorting facility"}
|
|
||||||
]
|
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<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:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
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
|
||||||
|
After Width: | Height: | Size: 364 KiB |
@@ -0,0 +1,99 @@
|
|||||||
|
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 1725.9px; background-color: white;" viewBox="4 4 1725.9010009765625 6951.078125" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"]Line truncated
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
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
|
||||||
|
After Width: | Height: | Size: 355 KiB |
+222
@@ -0,0 +1,222 @@
|
|||||||
|
# Input → Output flow
|
||||||
|
|
||||||
|
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, tests). There is no up-front
|
||||||
|
handle/ignore gate — every input is dispatched, and an explicit housekeeping
|
||||||
|
command is routed deterministically before navigation.
|
||||||
|
|
||||||
|
The diagram is split in two: the **main pipeline** (intake → dispatch →
|
||||||
|
navigation → run → output) and the **authoring pipeline** (what happens when
|
||||||
|
navigation decides a category or skill does not exist yet). Authoring is
|
||||||
|
asynchronous: the main gate is freed immediately and the original request is
|
||||||
|
re-queued once the body lands.
|
||||||
|
|
||||||
|
Rendered SVG: [flow-main.svg](flow-main.svg) · [flow-authoring.svg](flow-authoring.svg)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Main pipeline
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
IN["Input<br/>REPL text · gateway DM (SimpleX · LXMF · voice) · dashboard submit"] --> SUB["Scheduler.submit_request()<br/>create Request, trace 'submit'"]
|
||||||
|
|
||||||
|
SUB --> BUSY{"current process?"}
|
||||||
|
|
||||||
|
%% ---------- idle path ----------
|
||||||
|
BUSY -- "idle" --> META{"parse_meta_command()<br/>explicit housekeeping command?"}
|
||||||
|
|
||||||
|
%% ---------- busy path ----------
|
||||||
|
BUSY -- "busy" --> PUSH["RequestQueue.push<br/>FIFO, bounded"]
|
||||||
|
PUSH -- "full" --> REJECT["Output: rejected<br/>'queue is full'"]
|
||||||
|
PUSH -- "ok" --> QUEUED["Output: queued"]
|
||||||
|
QUEUED -. "run_queue when idle" .-> META
|
||||||
|
|
||||||
|
%% ---------- dispatch ----------
|
||||||
|
META -- "yes" --> HK["run housekeeping leaf<br/>trace 'meta_command'<br/>deterministic; skips navigation"]
|
||||||
|
HK --> RUN["_run_skill()<br/>execute the leaf"]
|
||||||
|
META -- "no" --> NAV["navigate()<br/>descend tree, one SemIf choice per level"]
|
||||||
|
|
||||||
|
%% ---------- actionability guard (top of navigation) ----------
|
||||||
|
NAV --> ACTG{"SemIf choice<br/>phase 'navigate:actionability'<br/>P non_action >= action_tau?"}
|
||||||
|
ACTG -- "non-action" --> CANNEDLEAF["_navigate_canned<br/>phase 'navigate:response'<br/>closed canned reply tree"]
|
||||||
|
CANNEDLEAF --> RUN
|
||||||
|
ACTG -- "request" --> CAT["SemIf choice<br/>phase 'navigate:category'<br/>options = real categories +<br/>descriptions + create_category"]
|
||||||
|
|
||||||
|
%% ---------- category selection ----------
|
||||||
|
CAT --> CATWIN{"create_category win<br/>or no categories?"}
|
||||||
|
CATWIN -- "yes" --> CREATECAT["CreateCategory"]
|
||||||
|
CATWIN -- "no" --> CATCONF{"winner prob >=<br/>softmax_bypass_tau?"}
|
||||||
|
CATCONF -- "yes (decisive)" --> HASSKILLS
|
||||||
|
CATCONF -- "no (unsure)" --> CATFIT["SemIf choice<br/>phase 'navigate:category_scope'<br/>P covers >= category_tau?"]
|
||||||
|
CATFIT -- "rejected" --> CREATECAT
|
||||||
|
CATFIT -- "covers" --> HASSKILLS
|
||||||
|
|
||||||
|
%% ---------- leaf selection ----------
|
||||||
|
HASSKILLS{"skills in category?"}
|
||||||
|
HASSKILLS -- "none" --> CREATESKILL["CreateSkill"]
|
||||||
|
HASSKILLS -- "one" --> SOLE["sole skill<br/>softmax skipped"]
|
||||||
|
HASSKILLS -- "many" --> LEAF["SemIf choice<br/>phase 'navigate:leaf'<br/>options = existing skills only"]
|
||||||
|
LEAF --> PICK["picked skill"]
|
||||||
|
SOLE --> PICK
|
||||||
|
|
||||||
|
%% ---------- reuse vs create ----------
|
||||||
|
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
|
||||||
|
HARD -- "yes" --> RUN
|
||||||
|
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>same / part / different?<br/>P same+part >= intent_tau"]
|
||||||
|
INTENT -- "same / part" --> RUN
|
||||||
|
INTENT -- "different" --> CREATESKILL
|
||||||
|
|
||||||
|
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
|
||||||
|
LOCK -- "locked" --> BLOCKED["Output: error<br/>'new-skill creation is locked'"]
|
||||||
|
LOCK -- "open" --> BODYQ{"meta<br/>awaiting_skill_body?"}
|
||||||
|
BODYQ -- "yes" --> PENDINGW["Output: error<br/>'body still being written;<br/>restart category.skill'"]
|
||||||
|
BODYQ -- "no" --> AUTHORING(["authoring pipeline<br/>see below"])
|
||||||
|
|
||||||
|
CREATECAT --> AUTHORING
|
||||||
|
|
||||||
|
%% ---------- run ----------
|
||||||
|
RUN --> WRITING{"leaf status?"}
|
||||||
|
WRITING -- "writing" --> PENDING["Output: error<br/>'body still being written'"]
|
||||||
|
WRITING -- "stub (no body)" --> NOOP["Output: error<br/>'no body yet;<br/>restart category.skill'"]
|
||||||
|
WRITING -- "ready" --> RESOLVE["SkillRunner.run()<br/>resolve tiered config<br/>global -> category -> skill"]
|
||||||
|
|
||||||
|
RESOLVE --> UNRES{"contract variable<br/>unresolved?"}
|
||||||
|
UNRES -- "yes" --> PAUSE1["Output: needs_input<br/>pre_act pause<br/>ask one variable"]
|
||||||
|
PAUSE1 -. "answer() bypasses queue" .-> RECORD["SemIf choice<br/>phase 'config:record'<br/>record as config vs ask each fire"]
|
||||||
|
RECORD --> RESOLVE
|
||||||
|
|
||||||
|
UNRES -- "no" --> ACT["skill.act(ctx, request)<br/>REAL action via stdlib transport<br/>values from ctx.config"]
|
||||||
|
ACT --> ACTNI{"act asks for input?"}
|
||||||
|
ACTNI -- "yes" --> PAUSE2["Output: needs_input<br/>act pause"]
|
||||||
|
PAUSE2 -. "answer()" .-> ACT
|
||||||
|
ACTNI -- "no" --> ASSESS
|
||||||
|
|
||||||
|
%% ---------- assessment ----------
|
||||||
|
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>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"]
|
||||||
|
|
||||||
|
REPAIR["SemIf choice<br/>phase 'repair:choice'<br/>retry / repair_skill / ask_user / no_repair"] --> REPAIROUT["Output: repair offer<br/>surfaced in REPL/dashboard/gateway"]
|
||||||
|
REPAIROUT -. "user confirms" .-> AUTHORING
|
||||||
|
|
||||||
|
ACT -. "act raises" .-> REPAIR
|
||||||
|
RUN -. "canned / deterministic category skips assess" .-> SUMMARY
|
||||||
|
|
||||||
|
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
|
||||||
|
classDef output fill:#fce8e6,stroke:#d93025;
|
||||||
|
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||||
|
class 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;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Authoring pipeline (create / repair)
|
||||||
|
|
||||||
|
Entered from `CreateCategory`, `CreateSkill`, or a confirmed repair / regen /
|
||||||
|
restart. Runs in background single-slot workers so the main gate stays free.
|
||||||
|
Only a *create* asks the small `llm` model for a title + description; a
|
||||||
|
repair/regen/restart reuses the existing stub and goes straight to the codegen
|
||||||
|
worker.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
START(["CreateCategory / CreateSkill"]) --> DRAFT["single-slot llm worker<br/>DraftAuthor queue"]
|
||||||
|
DIRECT(["repair_skill / regen_skill / restart_skill"]) --> WRITE
|
||||||
|
|
||||||
|
DRAFT --> GEN{"category or skill?"}
|
||||||
|
GEN -- "category" --> GC["generate_category()<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{"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 (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 --> BODY
|
||||||
|
|
||||||
|
BODY["generate_skill_body()<br/>de-identified spec only: goal + service/transport<br/>or regenerate_skill_body() for<br/>repair / fidelity / test / manual regen<br/>CODEGEN.md + bridge catalog<br/>declares INTEGRATION + flat CONTRACT"] --> FID["SemIf choice<br/>phase 'authoring:fidelity'<br/>accept / reconsider<br/>+ static integration_findings"]
|
||||||
|
FID -- "reconsider (once)" --> BODY
|
||||||
|
FID -- "accept" --> CONTRACT["parse_contract()<br/>read body's CONTRACT constant"]
|
||||||
|
|
||||||
|
CONTRACT --> CFG["SemIf choice per variable<br/>phase 'config:search'<br/>global -> category -> skill"]
|
||||||
|
CFG --> TEST["generate_skill_tests()<br/>hermetic mechanics test"]
|
||||||
|
TEST --> RUNTEST["run_skill_test()<br/>subprocess in skill folder"]
|
||||||
|
RUNTEST -- "fail" --> REGEN["SemIf choice<br/>phase 'codegen_regen'<br/>regenerate code / test<br/>bounded by test_max_attempts"]
|
||||||
|
REGEN --> BODY
|
||||||
|
RUNTEST -- "pass" --> MAT["materialize_skill()<br/>write body + contract to data/skills/<br/>hot-merge into tree, trace 'skill_ready'"]
|
||||||
|
|
||||||
|
MAT --> REQ["requeue original request<br/>meta awaiting_skill_body<br/>trace 'skill_requeued'"] --> BACK(["back to main pipeline<br/>re-runs navigation onto new leaf"])
|
||||||
|
|
||||||
|
FAIL["Output: skill_write_failed<br/>leaf stays a restartable stub<br/>restart category.skill"]
|
||||||
|
BODY -. "CodegenError / ValueError" .-> FAIL
|
||||||
|
RUNTEST -. "budget exhausted" .-> FAIL
|
||||||
|
|
||||||
|
CANCEL["cancel_build meta skill<br/>(housekeeping / CLI / dashboard)"] -. "cancel queued or in-flight write" .-> CANCELLED["Output: build cancelled<br/>discard output, delete half-built leaf"]
|
||||||
|
|
||||||
|
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
|
||||||
|
classDef output fill:#fce8e6,stroke:#d93025;
|
||||||
|
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||||
|
class FID,CFG,REGEN semfill;
|
||||||
|
class PROMPT,ABORT,ABORT2,FAIL,CANCELLED output;
|
||||||
|
class START,DIRECT,BACK,MAT,REQ author;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reading the path
|
||||||
|
|
||||||
|
| Stage | Decision (SemIf) | Phase logged | Output |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Intake, idle | — (no decision) | — | dispatch immediately |
|
||||||
|
| Intake, busy | — (no decision) | — | FIFO queue (arrival order) |
|
||||||
|
| Meta command | — (no decision) | — | route to housekeeping leaf (`meta_command`) |
|
||||||
|
| Actionability | request or not? | `navigate:actionability` | canned reply / category softmax |
|
||||||
|
| Category | which category | `navigate:category` | category / create |
|
||||||
|
| Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) |
|
||||||
|
| Canned | which reply | `navigate:response` | canned line |
|
||||||
|
| Leaf | which skill | `navigate:leaf` | skill |
|
||||||
|
| Intent guard | same / part / different? | `navigate:intent` | run / create (never bypassed) |
|
||||||
|
| Config record | record or ask? | `config:record` | persisted / per-fire |
|
||||||
|
| 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 |
|
||||||
|
| Test regen | code or test? | `codegen_regen` | regenerate |
|
||||||
|
|
||||||
|
**The three terminal outputs** are: a run summary (`category.skill: ok/failed — …`),
|
||||||
|
a question the run is waiting on (`needs_input`), or an offer to fix/learn
|
||||||
|
(`repair_offer`) / an authoring acknowledgement for a brand-new capability.
|
||||||
|
|
||||||
|
**Navigation is two-stage with permissive guards.** The actionability guard runs
|
||||||
|
first and decides whether the input is an actionable request at all; only
|
||||||
|
non-action input reaches the closed `response` tree, so a request is never
|
||||||
|
canned. The category softmax then offers the real categories (never `response`)
|
||||||
|
plus `create_category`, and the leaf softmax offers only the existing skills —
|
||||||
|
the reuse-vs-create decision is the intent guard. A **category** softmax winner
|
||||||
|
at or above `softmax_bypass_tau` (default 0.5) is already decisive, so its scope
|
||||||
|
confirm is skipped; the **leaf** intent guard is never bypassed (the leaf softmax
|
||||||
|
has no create option, so a confident winner is only the closest existing skill,
|
||||||
|
never a match) — it always runs and can reject into create.
|
||||||
|
New-skill creation is gated deterministically by the tri-state
|
||||||
|
`new_skill_creation` mode — global default `deny` (opt in with `allow`, or
|
||||||
|
`ask` for approval-gated authoring) with a
|
||||||
|
per-category override in `data/skills/<category>/config.json`; the
|
||||||
|
`housekeeping` and `response` categories are always `deny` in code.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"_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",
|
||||||
|
"gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
|
||||||
|
"gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983",
|
||||||
|
"source": "Qwen/Qwen3.5-4B",
|
||||||
|
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
|
||||||
|
},
|
||||||
|
"simplex_chat": {
|
||||||
|
"_comment": "Per-arch daemon binaries; bootstrap selects by `uname -m` (x86_64 | aarch64, arm64 normalized to aarch64). The pinned version is the same for every arch.",
|
||||||
|
"version": "v7.0.3",
|
||||||
|
"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
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
#
|
||||||
|
# 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
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Voice gateway deps (optional, hardware-dependent).
|
||||||
|
#
|
||||||
|
# Only needed on a host that runs the voice front end
|
||||||
|
# (`python -m semif_agent.cli gateway --platform voice`). Lazy-imported by
|
||||||
|
# semif_agent/voice_transport.py, so the core stays stdlib-only on every other
|
||||||
|
# host. Install with scripts/bootstrap.sh --voice, or:
|
||||||
|
# .runtime/venv/bin/pip install -r requirements/voice.txt
|
||||||
|
# .runtime/venv/bin/pip install --no-deps openwakeword==0.6.0
|
||||||
|
#
|
||||||
|
# System prerequisites (not pip): PortAudio + ALSA mixer tools, e.g.
|
||||||
|
# `apt-get install -y libportaudio2 alsa-utils`. PortAudio is the I/O backend;
|
||||||
|
# alsa-utils provides amixer/alsamixer/alsactl to unmute and set mic/speaker
|
||||||
|
# levels (PortAudio itself has no volume control).
|
||||||
|
#
|
||||||
|
# The audio pipeline is 16 kHz mono int16:
|
||||||
|
# sounddevice mic capture + speaker playback (raw PortAudio streams)
|
||||||
|
# faster-whisper CTranslate2 Whisper speech-to-text (model from HF cache)
|
||||||
|
# piper-tts local neural text-to-speech (voice .onnx under .runtime/voice/tts)
|
||||||
|
# onnxruntime inference backend for openwakeword + piper
|
||||||
|
# webrtcvad-wheels VAD endpointing (imports as `webrtcvad`; prebuilt wheels)
|
||||||
|
#
|
||||||
|
# openWakeWord is installed SEPARATELY with --no-deps: its Linux metadata
|
||||||
|
# hard-requires tflite-runtime, which has no py3.12+ wheel. The onnxruntime
|
||||||
|
# backend (used here) does not need it. Its own runtime deps are pinned below
|
||||||
|
# so this file alone is enough for the rest of the stack.
|
||||||
|
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).
|
||||||
|
scipy==1.18.1
|
||||||
|
scikit-learn==1.9.1
|
||||||
|
requests==2.34.2
|
||||||
|
tqdm==4.70.1
|
||||||
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
|
||||||
Executable
+1165
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)))
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent third-party API bridges (SimpleX forwarding)
|
||||||
|
After=network-online.target semif-simplex-forward.service
|
||||||
|
Wants=network-online.target semif-simplex-forward.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=@REPO@
|
||||||
|
Environment=HF_HOME=@REPO@/.runtime/hf
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli bridge
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-bridge
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent messenger gateway (SimpleX, LXMF)
|
||||||
|
After=network-online.target semif-simplex.service
|
||||||
|
Wants=network-online.target semif-simplex.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=@REPO@
|
||||||
|
Environment=HF_HOME=@REPO@/.runtime/hf
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
# 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
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-gateway
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent SimpleX forwarding bridge daemon
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# The forwarding bridge owns its OWN simplex-chat profile (separate from the
|
||||||
|
# command gateway's bot), so messaging UX never shares the command identity.
|
||||||
|
# Bot mode + a PTY are required for the same reason as semif-simplex.service:
|
||||||
|
# --headless means "chat relay" in v7, and the CLI only pumps WebSocket events
|
||||||
|
# with a controlling terminal.
|
||||||
|
ExecStart=/usr/bin/script -q -e -c "@REPO@/.runtime/bin/simplex-chat -p @FORWARD_PORT@ -d @REPO@/.runtime/simplex-forward/simplex_v1 -k '' --create-bot-display-name '@FORWARD_DISPLAY@'" /dev/null
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-simplex-forward
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent SimpleX Chat bot daemon
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# Bot mode: a local WebSocket chat server with a bot user. Do NOT add
|
||||||
|
# --headless here — in SimpleX Chat v7 --headless means "chat relay" and
|
||||||
|
# requires --relay, which yields a relay address, not a user contact address.
|
||||||
|
# The CLI only pumps WebSocket events (receivedContactRequest, newChatItems)
|
||||||
|
# when it has a controlling terminal, so `script` allocates a PTY; without it
|
||||||
|
# systemd's TTY-less process receives no events and contact requests hang.
|
||||||
|
ExecStart=/usr/bin/script -q -e -c "@REPO@/.runtime/bin/simplex-chat -p @PORT@ -d @REPO@/.runtime/simplex/simplex_v1 -k '' --create-bot-display-name '@DISPLAY_NAME@'" /dev/null
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-simplex
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Tune the two-stage navigation guards.
|
||||||
|
|
||||||
|
Navigation is two-stage at both levels, and the guards are the create doors.
|
||||||
|
Before either stage, the **actionability guard** (`confirm_non_action`) decides
|
||||||
|
whether the input is a request at all: a non-request goes straight to the closed
|
||||||
|
`response` tree and never reaches the category softmax, so a category-level
|
||||||
|
measurement of a non-request is reported as `response` with no guard
|
||||||
|
probability.
|
||||||
|
|
||||||
|
- **Category**: the softmax offers every existing (real) category WITH its
|
||||||
|
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`
|
||||||
|
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
|
||||||
|
floors can be placed between the true matches and the true mismatches. Run it on
|
||||||
|
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 (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
|
||||||
|
logs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(REPO))
|
||||||
|
|
||||||
|
from semif_agent.cli import build_scheduler, load_config
|
||||||
|
from semif_agent.decisions import Request
|
||||||
|
from semif_agent.log import DecisionLog
|
||||||
|
from semif_agent.skills import (
|
||||||
|
CreateCategory,
|
||||||
|
category_descriptions,
|
||||||
|
confirm_category_fit,
|
||||||
|
confirm_skill_fit,
|
||||||
|
navigate,
|
||||||
|
)
|
||||||
|
from semif_agent.trace import TraceLog
|
||||||
|
|
||||||
|
# (request, expected) at the LEAF level: "category.skill" or "create".
|
||||||
|
LEAF_EVAL: list[tuple[str, str]] = [
|
||||||
|
("what is my next message on simplex?", "simplex.next_message"),
|
||||||
|
("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_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", "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"),
|
||||||
|
]
|
||||||
|
|
||||||
|
# (request, expected) at the CATEGORY level: a category name or "create".
|
||||||
|
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", "nextcloud"),
|
||||||
|
("what is 15% of 80?", "calculator"),
|
||||||
|
("square root of 144", "calculator"),
|
||||||
|
("hello there", "response"),
|
||||||
|
("thanks!", "response"),
|
||||||
|
("what", "response"),
|
||||||
|
("book a flight to japan", "create"),
|
||||||
|
("what is the weather in paris", "create"),
|
||||||
|
("order me a pizza", "create"),
|
||||||
|
("tell me if my package was delivered", "create"),
|
||||||
|
]
|
||||||
|
|
||||||
|
SWEEP = [0.30, 0.40, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
|
||||||
|
|
||||||
|
|
||||||
|
def _present(tree: dict, qualified: str) -> bool:
|
||||||
|
if qualified == "create":
|
||||||
|
return True
|
||||||
|
if "." not in qualified:
|
||||||
|
return qualified in tree
|
||||||
|
category, _, name = qualified.partition(".")
|
||||||
|
return any(s.name == name for s in tree.get(category, []))
|
||||||
|
|
||||||
|
|
||||||
|
def measure(
|
||||||
|
scheduler, log, trace, request: Request, level: str, tau: float
|
||||||
|
) -> dict:
|
||||||
|
"""Run one navigation pass and return the guard probability for `level`."""
|
||||||
|
before = len(trace.read())
|
||||||
|
nav = navigate(
|
||||||
|
scheduler.engine, log, trace, request, scheduler.tree, category_tau=tau
|
||||||
|
)
|
||||||
|
events = trace.read()[before:]
|
||||||
|
|
||||||
|
if level == "category":
|
||||||
|
if isinstance(nav, CreateCategory):
|
||||||
|
return {"picked": "create", "p": None}
|
||||||
|
# navigate already ran the guard internally; read its event.
|
||||||
|
guard = next((e for e in events if e["kind"] == "category_scope"), None)
|
||||||
|
return {"picked": nav.category, "p": guard["probs"]["covers"] if guard else None}
|
||||||
|
|
||||||
|
# leaf: navigate returns a Skill, CreateSkill, or CreateCategory.
|
||||||
|
if not hasattr(nav, "name"):
|
||||||
|
return {"picked": "create", "p": None}
|
||||||
|
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)
|
||||||
|
# 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:
|
||||||
|
if measured["p"] is None:
|
||||||
|
return measured["picked"]
|
||||||
|
if measured["p"] >= tau:
|
||||||
|
return measured["picked"]
|
||||||
|
return "create"
|
||||||
|
|
||||||
|
|
||||||
|
def run_level(scheduler, log, trace, level: str, tau: float, eval_set, sweep) -> None:
|
||||||
|
print(f"### {level.upper()} level (real engine; ~1s/decision)\n")
|
||||||
|
results = []
|
||||||
|
for text, expected in eval_set:
|
||||||
|
present = _present(scheduler.tree, expected)
|
||||||
|
measured = measure(scheduler, log, trace, Request(text), level, tau)
|
||||||
|
results.append((text, expected, present, measured))
|
||||||
|
|
||||||
|
print(f"{'request':52s} {'picked':28s} {'p':>8s} {'expected':24s}")
|
||||||
|
print("-" * 116)
|
||||||
|
for text, expected, present, m in results:
|
||||||
|
picked = m["picked"] or "(create)"
|
||||||
|
p = f"{m['p']:.3f}" if m["p"] is not None else " -"
|
||||||
|
exp = expected + ("" if present else " [N/A]")
|
||||||
|
print(f"{text[:52]:52s} {picked:28s} {p:>8s} {exp:24s}")
|
||||||
|
|
||||||
|
print(f"\n{'tau':>6s} {'correct':>8s} {'false_create':>13s} {'false_reuse':>12s} {'na':>4s}")
|
||||||
|
print("-" * 46)
|
||||||
|
for t in sweep:
|
||||||
|
correct = fc = fr = na = 0
|
||||||
|
for _text, expected, present, m in results:
|
||||||
|
if not present:
|
||||||
|
na += 1
|
||||||
|
continue
|
||||||
|
got = verdict(m, t)
|
||||||
|
if got == expected:
|
||||||
|
correct += 1
|
||||||
|
elif expected == "create":
|
||||||
|
fr += 1
|
||||||
|
else:
|
||||||
|
fc += 1
|
||||||
|
print(f"{t:6.2f} {correct:8d} {fc:13d} {fr:12d} {na:4d}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--config", default=str(REPO / "config.json"))
|
||||||
|
parser.add_argument("--tau", type=float, default=None, help="report a single tau only")
|
||||||
|
parser.add_argument(
|
||||||
|
"--level", choices=["leaf", "category", "both"], default="both"
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
config = load_config(args.config)
|
||||||
|
scheduler, _ = build_scheduler(config)
|
||||||
|
scratch = Path(tempfile.mkdtemp(prefix="tune_navigation."))
|
||||||
|
log = DecisionLog(str(scratch / "decisions.jsonl"))
|
||||||
|
trace = TraceLog(str(scratch / "runs.jsonl"))
|
||||||
|
sweep = [args.tau] if args.tau is not None else SWEEP
|
||||||
|
|
||||||
|
if args.level in ("category", "both"):
|
||||||
|
run_level(
|
||||||
|
scheduler, log, trace, "category", args.tau or 0.5, CATEGORY_EVAL, sweep
|
||||||
|
)
|
||||||
|
if args.level in ("leaf", "both"):
|
||||||
|
run_level(scheduler, log, trace, "leaf", args.tau or 0.6, LEAF_EVAL, sweep)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"false_create = should have reused something existing but authored a new one\n"
|
||||||
|
"false_reuse = should have authored something new but used an existing one"
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Break down voice-gateway latency from the run trace.
|
||||||
|
|
||||||
|
Reads `data/runs.jsonl` (written by the running gateway) and, for each spoken
|
||||||
|
interaction, reports the time between the **last word spoken** and the **first
|
||||||
|
reply audio** split by section:
|
||||||
|
|
||||||
|
last word ── endpointing ── STT ── adapter ── [scheduler: guards + act + assess]
|
||||||
|
── reply routing (humanize) ── TTS synth ── playback start
|
||||||
|
|
||||||
|
The voice transport emits `voice_speech_end` at the last speech frame and
|
||||||
|
`voice_playback_start` right before the first reply samples reach the device;
|
||||||
|
the scheduler emits `submit`/`actionability`/`category_scope`/`intent_guard`/
|
||||||
|
`assessed`/`ran`; the service emits `humanize`/`gateway_reply_queued` and the
|
||||||
|
adapter `gateway_reply_dequeued`/`voice_speak_start`/`voice_tts_synth`.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python scripts/voice-latency.py [data/runs.jsonl] [--json] [--decisions PATH]
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import statistics
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def load_rows(path: str) -> list[dict]:
|
||||||
|
rows = []
|
||||||
|
if not Path(path).is_file():
|
||||||
|
return rows
|
||||||
|
with open(path) as handle:
|
||||||
|
for line in handle:
|
||||||
|
line = line.strip()
|
||||||
|
if line:
|
||||||
|
rows.append(json.loads(line))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _first(events: list[dict], kind: str) -> dict | None:
|
||||||
|
return next((e for e in events if e.get("kind") == kind), None)
|
||||||
|
|
||||||
|
|
||||||
|
def _ts(event: dict | None) -> float | None:
|
||||||
|
return None if event is None else event.get("ts")
|
||||||
|
|
||||||
|
|
||||||
|
def build_interactions(rows: list[dict]) -> list[dict]:
|
||||||
|
"""Split the trace into spoken interactions, each from speech-end to reply-end."""
|
||||||
|
interactions: list[dict] = []
|
||||||
|
current: dict | None = None
|
||||||
|
for event in rows:
|
||||||
|
kind = event.get("kind")
|
||||||
|
if kind == "voice_speech_end" or (
|
||||||
|
kind == "voice_utterance" and current is None
|
||||||
|
):
|
||||||
|
# A new utterance begins; close any prior interaction at its reply
|
||||||
|
# end. `voice_utterance` also starts one on legacy traces that
|
||||||
|
# predate the `voice_speech_end` probe (last-word boundary unknown).
|
||||||
|
if current is not None:
|
||||||
|
interactions.append(current)
|
||||||
|
current = {"events": [event]}
|
||||||
|
elif current is not None:
|
||||||
|
current["events"].append(event)
|
||||||
|
if kind in ("voice_spoke", "voice_speak_failed", "voice_stt_empty",
|
||||||
|
"voice_stt_failed", "voice_short_utterance"):
|
||||||
|
interactions.append(current)
|
||||||
|
current = None
|
||||||
|
if current is not None:
|
||||||
|
interactions.append(current)
|
||||||
|
return interactions
|
||||||
|
|
||||||
|
|
||||||
|
def _decisions_timing(decisions_path: str) -> dict[str, list[dict]]:
|
||||||
|
"""Map run_id -> list of {phase, timing} from the decision log."""
|
||||||
|
by_run: dict[str, list[dict]] = {}
|
||||||
|
if not Path(decisions_path).is_file():
|
||||||
|
return by_run
|
||||||
|
with open(decisions_path) as handle:
|
||||||
|
for line in handle:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
row = json.loads(line)
|
||||||
|
extra = row.get("extra") or {}
|
||||||
|
run_id = extra.get("run_id")
|
||||||
|
timing = extra.get("timing")
|
||||||
|
if run_id and timing:
|
||||||
|
by_run.setdefault(run_id, []).append(
|
||||||
|
{"phase": extra.get("phase"), **timing}
|
||||||
|
)
|
||||||
|
return by_run
|
||||||
|
|
||||||
|
|
||||||
|
def analyze(interaction: dict, decisions: dict[str, list[dict]]) -> dict | None:
|
||||||
|
events = interaction["events"]
|
||||||
|
speech_end = _first(events, "voice_speech_end")
|
||||||
|
utterance = _first(events, "voice_utterance")
|
||||||
|
transcribed = _first(events, "voice_transcribed")
|
||||||
|
submit = _first(events, "submit")
|
||||||
|
if utterance is None or submit is None:
|
||||||
|
return None # empty/short utterance: nothing was dispatched
|
||||||
|
# On legacy traces without `voice_speech_end`, measure from the utterance.
|
||||||
|
origin = speech_end or utterance
|
||||||
|
|
||||||
|
actionability = _first(events, "actionability")
|
||||||
|
category_scope = _first(events, "category_scope")
|
||||||
|
intent_guard = _first(events, "intent_guard")
|
||||||
|
assessed = _first(events, "assessed")
|
||||||
|
ran = _first(events, "ran")
|
||||||
|
reply_queued = _first(events, "gateway_reply_queued")
|
||||||
|
reply_dequeued = _first(events, "gateway_reply_dequeued")
|
||||||
|
speak_start = _first(events, "voice_speak_start")
|
||||||
|
tts = _first(events, "voice_tts_synth")
|
||||||
|
playback = _first(events, "voice_playback_start")
|
||||||
|
spoke = _first(events, "voice_spoke")
|
||||||
|
humanize = _first(events, "humanize")
|
||||||
|
|
||||||
|
t0 = _ts(origin)
|
||||||
|
run_id = submit.get("run_id")
|
||||||
|
|
||||||
|
def delta(a: dict | None, b: dict | None) -> float | None:
|
||||||
|
ta, tb = _ts(a), _ts(b)
|
||||||
|
return None if ta is None or tb is None else round(tb - ta, 3)
|
||||||
|
|
||||||
|
out = {
|
||||||
|
"run_id": run_id,
|
||||||
|
"text": submit.get("text"),
|
||||||
|
"skill": (ran or {}).get("skill"),
|
||||||
|
"summary": (ran or {}).get("summary"),
|
||||||
|
"last_word_ts": t0,
|
||||||
|
"endpointing_s": delta(speech_end, utterance),
|
||||||
|
"stt_s": delta(utterance, transcribed),
|
||||||
|
"adapter_s": delta(transcribed, submit),
|
||||||
|
"scheduler_s": delta(submit, ran),
|
||||||
|
"guard_actionability_s": delta(submit, actionability),
|
||||||
|
"guard_category_s": delta(actionability, category_scope),
|
||||||
|
"guard_intent_s": delta(category_scope, intent_guard),
|
||||||
|
"act_assess_s": delta(intent_guard, assessed),
|
||||||
|
"assess_ran_s": delta(assessed, ran),
|
||||||
|
"reply_s": delta(ran, playback),
|
||||||
|
"humanize_s": (humanize or {}).get("elapsed_s"),
|
||||||
|
"tts_synth_s": (tts or {}).get("synth_s"),
|
||||||
|
"tts_audio_s": (tts or {}).get("audio_s"),
|
||||||
|
"queue_s": delta(reply_queued, reply_dequeued),
|
||||||
|
"speak_to_playback_s": delta(speak_start, playback),
|
||||||
|
"playback_s": delta(playback, spoke),
|
||||||
|
"total_to_first_audio_s": delta(origin, playback),
|
||||||
|
"total_to_reply_end_s": delta(origin, spoke),
|
||||||
|
"decisions": decisions.get(run_id, []),
|
||||||
|
}
|
||||||
|
# Anything after `ran` but before playback that is not humanize/TTS is queue.
|
||||||
|
if out["reply_s"] is not None:
|
||||||
|
accounted = (out["humanize_s"] or 0.0) + (out["tts_synth_s"] or 0.0)
|
||||||
|
out["reply_unaccounted_s"] = round(out["reply_s"] - accounted, 3)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def fmt(value) -> str:
|
||||||
|
return "—" if value is None else f"{value:.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def render(results: list[dict]) -> None:
|
||||||
|
for r in results:
|
||||||
|
print(f"\nrun {r['run_id']} {r['text']!r} skill={r['skill']}")
|
||||||
|
print(f" last word → endpointing done : {fmt(r['endpointing_s'])} s")
|
||||||
|
print(f" STT : {fmt(r['stt_s'])} s")
|
||||||
|
print(f" adapter → scheduler submit : {fmt(r['adapter_s'])} s")
|
||||||
|
print(f" SCHEDULER total : {fmt(r['scheduler_s'])} s")
|
||||||
|
print(f" actionability guard : {fmt(r['guard_actionability_s'])} s")
|
||||||
|
print(f" category softmax + scope : {fmt(r['guard_category_s'])} s")
|
||||||
|
print(f" leaf softmax + intent : {fmt(r['guard_intent_s'])} s")
|
||||||
|
print(f" act + assess:outcome : {fmt(r['act_assess_s'])} s")
|
||||||
|
print(f" assess → ran : {fmt(r['assess_ran_s'])} s")
|
||||||
|
print(f" reply (ran → first audio) : {fmt(r['reply_s'])} s")
|
||||||
|
print(f" humanize : {fmt(r['humanize_s'])} s")
|
||||||
|
print(f" TTS synth : {fmt(r['tts_synth_s'])} s")
|
||||||
|
print(f" other (queue/open) : {fmt(r.get('reply_unaccounted_s'))} s")
|
||||||
|
print(f" playback (audio duration) : {fmt(r['playback_s'])} s")
|
||||||
|
print(f" ── LAST WORD → FIRST AUDIO : {fmt(r['total_to_first_audio_s'])} s")
|
||||||
|
if r["decisions"]:
|
||||||
|
for d in r["decisions"]:
|
||||||
|
print(
|
||||||
|
f" [{d.get('phase')}] tokens={d.get('input_tokens')} "
|
||||||
|
f"forward={d.get('forward_seconds')} total={d.get('total_seconds')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def agg(key: str) -> str:
|
||||||
|
vals = [r[key] for r in results if r.get(key) is not None]
|
||||||
|
if not vals:
|
||||||
|
return "—"
|
||||||
|
return f"median {statistics.median(vals):.2f}s mean {statistics.mean(vals):.2f}s (n={len(vals)})"
|
||||||
|
|
||||||
|
print("\n===== aggregate =====")
|
||||||
|
for key, label in (
|
||||||
|
("endpointing_s", "endpointing"),
|
||||||
|
("stt_s", "STT"),
|
||||||
|
("scheduler_s", "SCHEDULER"),
|
||||||
|
("guard_actionability_s", " actionability"),
|
||||||
|
("guard_category_s", " category softmax+scope"),
|
||||||
|
("guard_intent_s", " leaf softmax+intent"),
|
||||||
|
("act_assess_s", " act+assess"),
|
||||||
|
("reply_s", "reply (humanize+TTS)"),
|
||||||
|
("humanize_s", " humanize"),
|
||||||
|
("tts_synth_s", " TTS synth"),
|
||||||
|
("total_to_first_audio_s", "TOTAL last word → first audio"),
|
||||||
|
):
|
||||||
|
print(f"{label:28s}: {agg(key)}")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("trace", nargs="?", default="data/runs.jsonl")
|
||||||
|
parser.add_argument("--decisions", default="data/decisions.jsonl")
|
||||||
|
parser.add_argument("--json", action="store_true")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
rows = load_rows(args.trace)
|
||||||
|
decisions = _decisions_timing(args.decisions)
|
||||||
|
results = []
|
||||||
|
for interaction in build_interactions(rows):
|
||||||
|
analyzed = analyze(interaction, decisions)
|
||||||
|
if analyzed is not None:
|
||||||
|
results.append(analyzed)
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(results, indent=2))
|
||||||
|
return 0
|
||||||
|
if not results:
|
||||||
|
print("no spoken interactions found in", args.trace)
|
||||||
|
return 1
|
||||||
|
render(results)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Download the voice-gateway models into the checkout's `.runtime/voice` tree.
|
||||||
|
|
||||||
|
Run after installing `requirements/voice.txt` (bootstrap does this with
|
||||||
|
`--voice`). Idempotent: a model already on disk is skipped. Reads
|
||||||
|
`gateway.voice` from config.json so the downloaded models match the configured
|
||||||
|
names, or take explicit flags.
|
||||||
|
|
||||||
|
- **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
|
||||||
|
(`.runtime/hf`); the runner reuses that cache at runtime.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
|
||||||
|
def piper_hf_path(voice: str) -> str:
|
||||||
|
"""Map a Piper voice id to its file path in the `rhasspy/piper-voices` repo.
|
||||||
|
|
||||||
|
`en_US-lessac-medium` -> `en/en_US/lessac/medium/en_US-lessac-medium.onnx`
|
||||||
|
(the voice name may itself contain dashes).
|
||||||
|
"""
|
||||||
|
parts = voice.split("-")
|
||||||
|
if len(parts) < 3:
|
||||||
|
raise ValueError(f"unrecognized piper voice id {voice!r}")
|
||||||
|
locale, quality = parts[0], parts[-1]
|
||||||
|
name = "-".join(parts[1:-1])
|
||||||
|
lang = locale.split("_")[0]
|
||||||
|
return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx"
|
||||||
|
|
||||||
|
|
||||||
|
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}")
|
||||||
|
# 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
|
||||||
|
|
||||||
|
target.mkdir(parents=True, exist_ok=True)
|
||||||
|
rel = piper_hf_path(voice)
|
||||||
|
for suffix in ("", ".json"):
|
||||||
|
dest = target / f"{voice}.onnx{suffix}"
|
||||||
|
if dest.is_file():
|
||||||
|
print(f"== tts voice: {dest.name} (present)")
|
||||||
|
continue
|
||||||
|
print(f"== tts voice: {voice}{suffix or '.onnx'} -> {dest}")
|
||||||
|
cached = hf_hub_download(repo_id=PIPER_REPO, filename=rel + suffix)
|
||||||
|
shutil.copyfile(cached, dest)
|
||||||
|
|
||||||
|
|
||||||
|
def download_stt(model: str) -> None:
|
||||||
|
from faster_whisper import WhisperModel
|
||||||
|
|
||||||
|
print(f"== stt model: {model} (warming HF cache)")
|
||||||
|
WhisperModel(model, device="cpu", compute_type="int8")
|
||||||
|
|
||||||
|
|
||||||
|
def _config_voice(config_path: Path) -> dict:
|
||||||
|
try:
|
||||||
|
config = json.loads(config_path.read_text())
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
return (config.get("gateway", {}) or {}).get("voice", {}) or {}
|
||||||
|
|
||||||
|
|
||||||
|
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"))
|
||||||
|
parser.add_argument("--skip-wake", action="store_true")
|
||||||
|
parser.add_argument("--skip-stt", action="store_true")
|
||||||
|
parser.add_argument("--skip-tts", action="store_true")
|
||||||
|
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_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, Path(args.wake_dir))
|
||||||
|
if not args.skip_tts:
|
||||||
|
download_voice(tts, Path(args.tts_dir))
|
||||||
|
if not args.skip_stt:
|
||||||
|
download_stt(stt)
|
||||||
|
print("== voice models ready")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""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, 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:
|
||||||
|
|
||||||
|
- **Bridges are not the gateway.** The command gateway only takes commands and
|
||||||
|
replies; it must never grow read/send/invite endpoints. Bridges run as their
|
||||||
|
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, 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, 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__ = [
|
||||||
|
"BridgeInfo",
|
||||||
|
"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",
|
||||||
|
]
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
"""Bridge service contract + the shared secure HTTP layer.
|
||||||
|
|
||||||
|
Every bridge stands up the same thin HTTP surface: JSON in, JSON out, bound to
|
||||||
|
localhost, optionally guarded by a shared-secret header. A subclass only
|
||||||
|
implements its routes (`handle_get` / `handle_post`) and, if it needs a service
|
||||||
|
daemon, starts it in `start()`. The HTTP/JSON/auth plumbing lives here once so
|
||||||
|
each new bridge is small and hard to get wrong.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
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.
|
||||||
|
|
||||||
|
Fed to the code-generation model so it knows what it can build against,
|
||||||
|
and used to describe the service in docs. Holds no secrets and needs no
|
||||||
|
running process.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
service: str
|
||||||
|
description: str
|
||||||
|
url_config_var: str
|
||||||
|
#: Human-readable `METHOD /path` -> purpose lines.
|
||||||
|
endpoints: tuple[str, ...] = ()
|
||||||
|
#: Other `ctx.config` keys a body built on this bridge may read.
|
||||||
|
config_vars: tuple[str, ...] = field(default=())
|
||||||
|
#: One-line semantic description per config var: `(name, description)`.
|
||||||
|
#: Every entry in `config_vars` must be documented here.
|
||||||
|
config_var_docs: tuple[tuple[str, str], ...] = ()
|
||||||
|
#: Optional shared-secret header the bridge enforces when its token is set
|
||||||
|
#: (e.g. `X-Semif-Token`), and the top-level `ctx.config` var holding it.
|
||||||
|
auth_header: str = ""
|
||||||
|
auth_config_var: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class BridgeService(ABC):
|
||||||
|
"""Base class for a standalone third-party API bridge."""
|
||||||
|
|
||||||
|
#: short snake_case id (`simplex`)
|
||||||
|
name: str = "bridge"
|
||||||
|
#: static catalog entry
|
||||||
|
info: BridgeInfo
|
||||||
|
|
||||||
|
def __init__(self, config: dict | None = None, trace=None):
|
||||||
|
cfg = config or {}
|
||||||
|
self.host = str(cfg.get("host", "127.0.0.1"))
|
||||||
|
self.port = int(cfg.get("port", 0))
|
||||||
|
self.token = str(cfg.get("token", "") or "")
|
||||||
|
self.trace = trace
|
||||||
|
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
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
|
||||||
|
|
||||||
|
def start(self) -> int:
|
||||||
|
"""Start serving HTTP; returns the bound port (`port=0` is ephemeral)."""
|
||||||
|
server = ThreadingHTTPServer((self.host, self.port), _BridgeHTTPHandler)
|
||||||
|
server.bridge = self # type: ignore[attr-defined]
|
||||||
|
self._server = server
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=server.serve_forever,
|
||||||
|
name=f"bridge-{self.name}",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
return int(server.server_address[1])
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop_transport()
|
||||||
|
server, self._server = self._server, None
|
||||||
|
if server is not None:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
thread, self._thread = self._thread, None
|
||||||
|
if thread is not None:
|
||||||
|
thread.join(timeout=2.0)
|
||||||
|
|
||||||
|
def _stop_transport(self) -> None:
|
||||||
|
"""Hook for subclasses that own a background transport (daemon)."""
|
||||||
|
|
||||||
|
# ---- routes ----
|
||||||
|
|
||||||
|
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
# ---- helpers ----
|
||||||
|
|
||||||
|
def _event(self, kind: str, **fields) -> None:
|
||||||
|
if self.trace is not None:
|
||||||
|
self.trace.append(kind, "?", **fields)
|
||||||
|
|
||||||
|
|
||||||
|
class _BridgeHTTPHandler(BaseHTTPRequestHandler):
|
||||||
|
"""JSON request handler; the owning bridge is on `self.server.bridge`."""
|
||||||
|
|
||||||
|
def log_message(self, *args) -> None: # silence the default stderr spam
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _bridge(self) -> BridgeService:
|
||||||
|
return self.server.bridge # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
def _authorized(self) -> bool:
|
||||||
|
token = self._bridge().token
|
||||||
|
if not token:
|
||||||
|
return True
|
||||||
|
return self.headers.get("X-Semif-Token") == token
|
||||||
|
|
||||||
|
def _json(self, status: int, payload: dict) -> None:
|
||||||
|
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 _require_auth(self) -> bool:
|
||||||
|
if self._authorized():
|
||||||
|
return True
|
||||||
|
self._json(401, {"error": "unauthorized"})
|
||||||
|
return False
|
||||||
|
|
||||||
|
def do_GET(self) -> None:
|
||||||
|
if not self._require_auth():
|
||||||
|
return
|
||||||
|
url = urlparse(self.path)
|
||||||
|
status, payload = self._bridge().handle_get(url.path, parse_qs(url.query))
|
||||||
|
self._json(status, payload)
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
if not self._require_auth():
|
||||||
|
return
|
||||||
|
url = urlparse(self.path)
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length) if length else b""
|
||||||
|
try:
|
||||||
|
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||||
|
except ValueError:
|
||||||
|
self._json(400, {"error": "invalid JSON body"})
|
||||||
|
return
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
self._json(400, {"error": "body must be a JSON object"})
|
||||||
|
return
|
||||||
|
status, response = self._bridge().handle_post(url.path, payload)
|
||||||
|
self._json(status, response)
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""A bounded, thread-safe FIFO of buffered inbound messages + known contacts.
|
||||||
|
|
||||||
|
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`, `item_id`), which is exactly what `semif_agent.simplex_ws` yields.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
|
||||||
|
class MessagingInbox:
|
||||||
|
def __init__(self, max_size: int = 100):
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._items: deque[dict] = deque()
|
||||||
|
self._max = max(1, int(max_size))
|
||||||
|
self._contacts: dict[str, dict] = {}
|
||||||
|
|
||||||
|
def record(self, message: dict) -> dict:
|
||||||
|
contact_id = str(message.get("contact_id") or "")
|
||||||
|
display_name = message.get("display_name") or ""
|
||||||
|
entry = {
|
||||||
|
"id": uuid.uuid4().hex[:12],
|
||||||
|
"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:
|
||||||
|
self._remember(contact_id, message)
|
||||||
|
self._items.append(entry)
|
||||||
|
while len(self._items) > self._max:
|
||||||
|
self._items.popleft()
|
||||||
|
return entry
|
||||||
|
|
||||||
|
def _remember(self, contact_id: str, contact: dict) -> None:
|
||||||
|
"""Upsert the cached contact for an id (caller holds the lock)."""
|
||||||
|
current = self._contacts.setdefault(
|
||||||
|
contact_id, {"id": contact_id, "display_name": ""}
|
||||||
|
)
|
||||||
|
name = contact.get("display_name") or ""
|
||||||
|
if name:
|
||||||
|
current["display_name"] = name
|
||||||
|
# Keep the unique local name and connection health when the source knows
|
||||||
|
# them; never invent them (an inbound item has no connection state).
|
||||||
|
for key in ("local_name", "connected", "auth_errors"):
|
||||||
|
if key in contact and contact[key] not in (None, ""):
|
||||||
|
current[key] = contact[key]
|
||||||
|
|
||||||
|
def peek(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
return list(self._items)
|
||||||
|
|
||||||
|
def pop(self, contact_id: str | None = None) -> dict | None:
|
||||||
|
with self._lock:
|
||||||
|
if contact_id is None:
|
||||||
|
return self._items.popleft() if self._items else None
|
||||||
|
target = str(contact_id)
|
||||||
|
for index, entry in enumerate(self._items):
|
||||||
|
if entry["contact_id"] == target:
|
||||||
|
del self._items[index]
|
||||||
|
return entry
|
||||||
|
return None
|
||||||
|
|
||||||
|
def merge_contacts(self, contacts: list[dict]) -> None:
|
||||||
|
"""Upsert contacts learned from the daemon (not from a message).
|
||||||
|
|
||||||
|
A non-empty incoming name overwrites a cached one; an empty name never
|
||||||
|
clobbers a name already learned from an inbound message. The unique
|
||||||
|
local name and connection health ride along when the daemon reports
|
||||||
|
them.
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
for contact in contacts:
|
||||||
|
contact_id = str(contact.get("id") or "")
|
||||||
|
if not contact_id:
|
||||||
|
continue
|
||||||
|
self._remember(contact_id, contact)
|
||||||
|
|
||||||
|
def contacts(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
return [dict(contact) for contact in self._contacts.values()]
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
"""LLM bridge: the agent's language model behind the standard bridge surface.
|
||||||
|
|
||||||
|
Skill bodies are stdlib-only and must not speak a model's native
|
||||||
|
OpenAI-compatible protocol directly. This bridge exposes one generic chat call
|
||||||
|
over the same local, token-guarded JSON surface every other bridge uses, so a
|
||||||
|
body can ask for short generated text (e.g. extract an event title and
|
||||||
|
description from a request) without importing a client or knowing the endpoint.
|
||||||
|
|
||||||
|
It does **not** own the model connection: it reuses the scheduler's already
|
||||||
|
configured `llm` client, passed in at construction, so the endpoint/model/
|
||||||
|
sampler live in one place (the top-level `llm` block). Constructed without a
|
||||||
|
client (tests, standalone) it has no model and every call reports 502 rather
|
||||||
|
than fabricating an answer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .base import BridgeInfo, BridgeService
|
||||||
|
|
||||||
|
|
||||||
|
class LLMBridge(BridgeService):
|
||||||
|
name = "llm"
|
||||||
|
INFO = BridgeInfo(
|
||||||
|
name="llm",
|
||||||
|
service="llm",
|
||||||
|
description=(
|
||||||
|
"Generate short text with the agent's configured language model, "
|
||||||
|
"e.g. extract a title and a description from a user's request."
|
||||||
|
),
|
||||||
|
url_config_var="llm_bridge_url",
|
||||||
|
endpoints=(
|
||||||
|
'GET /health -> 200 {"ok": true, "platform": "llm"} — the bridge is up',
|
||||||
|
'POST /chat {"messages": [{"role", "content"}, ...], "max_tokens"?: int} '
|
||||||
|
'-> 200 {"text": "<model reply>"}; 400 {"error": "..."} on a '
|
||||||
|
'missing/invalid messages list; 502 {"error": "..."} when the model '
|
||||||
|
"call fails or no model is configured",
|
||||||
|
'any request -> 401 {"error": "unauthorized"} when the token is '
|
||||||
|
"configured and the auth header is missing or wrong",
|
||||||
|
),
|
||||||
|
config_vars=("llm_bridge_url", "llm_bridge_token"),
|
||||||
|
config_var_docs=(
|
||||||
|
(
|
||||||
|
"llm_bridge_url",
|
||||||
|
"Base URL of the local LLM bridge (e.g. http://127.0.0.1:5229); "
|
||||||
|
"never hardcode it in the body.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"llm_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="llm_bridge_token",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||||
|
super().__init__(config, trace)
|
||||||
|
#: The scheduler's configured `llm` client (or a test double). None when
|
||||||
|
#: 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]:
|
||||||
|
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||||
|
# missing model surfaces as a 502 on the call, not as 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}
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||||
|
if path != "/chat":
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
messages = payload.get("messages")
|
||||||
|
if not isinstance(messages, list) or not messages:
|
||||||
|
return 400, {"error": "messages is required"}
|
||||||
|
if not all(
|
||||||
|
isinstance(message, dict)
|
||||||
|
and isinstance(message.get("role"), str)
|
||||||
|
and isinstance(message.get("content"), str)
|
||||||
|
for message in messages
|
||||||
|
):
|
||||||
|
return 400, {"error": "each message needs a string role and content"}
|
||||||
|
max_tokens = payload.get("max_tokens")
|
||||||
|
if max_tokens is not None and not isinstance(max_tokens, int):
|
||||||
|
return 400, {"error": "max_tokens must be an integer"}
|
||||||
|
if self.client is None:
|
||||||
|
return 502, {"error": "no language model is configured"}
|
||||||
|
try:
|
||||||
|
text = self.client.chat(messages, max_tokens=max_tokens)
|
||||||
|
except Exception as exc: # the model client's error type + anything it raises
|
||||||
|
return 502, {"error": f"llm call failed: {exc}"[:300]}
|
||||||
|
return 200, {"text": text}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
"""The bridge catalog: discovery, prompt description, and standalone runner.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
#: 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 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(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]:
|
||||||
|
"""Skill-facing config vars for every bridge, derived from its own block.
|
||||||
|
|
||||||
|
The `bridges.<name>` block is the single source of truth: its `host`/`port`
|
||||||
|
are the listener a skill body calls and its `token` is the shared secret.
|
||||||
|
There is deliberately no duplicate top-level `*_bridge_url`/`*_bridge_token`
|
||||||
|
to keep in sync — the values are derived here and injected into the config a
|
||||||
|
skill reads (`ctx.config`). A bridge with no block (or no port) contributes
|
||||||
|
nothing, so an unconfigured bridge still surfaces as an unresolved contract
|
||||||
|
variable the operator is asked for.
|
||||||
|
"""
|
||||||
|
blocks = config.get("bridges", {}) or {}
|
||||||
|
derived: dict[str, str] = {}
|
||||||
|
for info in known_infos(_packs_from_config(config)):
|
||||||
|
block = blocks.get(info.name)
|
||||||
|
if not isinstance(block, dict):
|
||||||
|
continue
|
||||||
|
host = str(block.get("host") or "127.0.0.1").strip()
|
||||||
|
# A bind-all address is not a callable one; skills always call loopback.
|
||||||
|
if host in ("", "0.0.0.0", "::", "[::]"):
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = block.get("port")
|
||||||
|
if info.url_config_var and port:
|
||||||
|
derived[info.url_config_var] = f"http://{host}:{int(port)}"
|
||||||
|
if info.auth_config_var:
|
||||||
|
derived[info.auth_config_var] = str(block.get("token") or "")
|
||||||
|
return derived
|
||||||
|
|
||||||
|
|
||||||
|
def describe_bridges(packs=None) -> str:
|
||||||
|
"""A prompt block describing every available bridge service.
|
||||||
|
|
||||||
|
Injected into the skill-body, retry, regen, 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
|
||||||
|
specifics — CODEGEN.md/TESTGEN.md carry only the generic pattern. Static: no
|
||||||
|
bridge needs to be running or enabled.
|
||||||
|
"""
|
||||||
|
lines = [
|
||||||
|
"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(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:
|
||||||
|
lines.append(
|
||||||
|
f" auth: send the value of {info.auth_config_var} in the "
|
||||||
|
f"{info.auth_header} header when it is set"
|
||||||
|
)
|
||||||
|
docs = dict(info.config_var_docs)
|
||||||
|
if info.config_vars:
|
||||||
|
lines.append(" config vars:")
|
||||||
|
for name in info.config_vars:
|
||||||
|
description = docs.get(name)
|
||||||
|
suffix = f" — {description}" if description else ""
|
||||||
|
lines.append(f" - {name}{suffix}")
|
||||||
|
if info.endpoints:
|
||||||
|
lines.append(" endpoints:")
|
||||||
|
for endpoint in info.endpoints:
|
||||||
|
lines.append(f" - {endpoint}")
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def build_bridge(
|
||||||
|
config: dict, name: str, trace=None, llm=None
|
||||||
|
) -> BridgeService:
|
||||||
|
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
|
||||||
|
|
||||||
|
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, _packs_from_config(config))
|
||||||
|
if bridge_class is None:
|
||||||
|
raise KeyError(f"unknown bridge: {name!r}")
|
||||||
|
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
|
||||||
|
return bridge_class.from_config(block, config=config, trace=trace, llm=llm)
|
||||||
|
|
||||||
|
|
||||||
|
def run_bridges(
|
||||||
|
config: dict,
|
||||||
|
names: list[str] | None = None,
|
||||||
|
trace=None,
|
||||||
|
llm=None,
|
||||||
|
) -> int:
|
||||||
|
"""Run the selected (+ enabled) bridges until interrupted.
|
||||||
|
|
||||||
|
With explicit `names`, a bridge runs even if disabled is not set; with no
|
||||||
|
names, only `enabled` bridges run. Returns a process exit code. `llm` is the
|
||||||
|
scheduler's configured language-model client (see `build_bridge`).
|
||||||
|
"""
|
||||||
|
blocks = config.get("bridges", {}) or {}
|
||||||
|
selected: list[BridgeService] = []
|
||||||
|
for bridge_class in discover_bridge_classes(_packs_from_config(config)):
|
||||||
|
name = bridge_class.INFO.name
|
||||||
|
if names and name not in names:
|
||||||
|
continue
|
||||||
|
block = blocks.get(name, {}) or {}
|
||||||
|
if not names and not block.get("enabled", False):
|
||||||
|
continue
|
||||||
|
bridge = build_bridge(config, name, trace=trace, llm=llm)
|
||||||
|
ok, hint = bridge.check_requirements()
|
||||||
|
if not ok:
|
||||||
|
print(f"bridge {name} unavailable: {hint}")
|
||||||
|
for running in selected:
|
||||||
|
running.stop()
|
||||||
|
return 1
|
||||||
|
port = bridge.start()
|
||||||
|
selected.append(bridge)
|
||||||
|
print(
|
||||||
|
f"bridge {name} listening on http://{bridge.host}:{port} "
|
||||||
|
f"(skills use the {bridge_class.INFO.url_config_var} config var)"
|
||||||
|
)
|
||||||
|
if not selected:
|
||||||
|
print("no bridge services enabled (set bridges.<name>.enabled)")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
stop = threading.Event()
|
||||||
|
try:
|
||||||
|
while not stop.wait(0.5):
|
||||||
|
pass
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for bridge in selected:
|
||||||
|
bridge.stop()
|
||||||
|
return 0
|
||||||
+1178
-43
File diff suppressed because it is too large.
Load diff
+964
-214
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""OpenCode Console provider (hosted, authenticated OpenAI-compatible API).
|
||||||
|
|
||||||
|
The `OpenCode Console <https://opencode.ai/console>`_ serves an
|
||||||
|
OpenAI-compatible Chat Completions API at
|
||||||
|
``https://opencode.ai/inference/openai/v1``. It is wire-identical to
|
||||||
|
``provider.OpenAICompatClient`` (SSE ``delta.content`` +
|
||||||
|
``delta.reasoning_content``, an ``include_usage`` chunk, then ``[DONE]``), so
|
||||||
|
this module only adds what the Console needs on top of the shared transport:
|
||||||
|
|
||||||
|
* a bearer service-account key (``Authorization: Bearer <key>``), and
|
||||||
|
* ``query_context = False`` — the Console has no ollama ``/api/show``, so the
|
||||||
|
context window comes from config or the default instead of a stray probe.
|
||||||
|
|
||||||
|
Only the **Chat Completions** model family is supported (GLM, DeepSeek, Kimi,
|
||||||
|
Qwen3.8 Max, MiniMax, and the free models). Claude / OpenAI-Responses / Gemini
|
||||||
|
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`` (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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from .codegen import CodegenClient, CodegenError, DegenerationError
|
||||||
|
from .llm import LLMClient, LLMError
|
||||||
|
from .provider import OpenAICompatClient, ProviderError
|
||||||
|
|
||||||
|
OPENCODE_BASE_URL = "https://opencode.ai/inference/openai/v1"
|
||||||
|
OPENCODE_MODELS_URL = "https://opencode.ai/inference/v1/models"
|
||||||
|
OPENCODE_USER_AGENT = "semif-agent/0.1"
|
||||||
|
|
||||||
|
|
||||||
|
class OpenCodeError(ProviderError):
|
||||||
|
"""The OpenCode Console endpoint could not be reached."""
|
||||||
|
|
||||||
|
|
||||||
|
class OpenCodeConsoleClient(OpenAICompatClient):
|
||||||
|
"""Authenticated OpenAI-compatible client for the OpenCode Console.
|
||||||
|
|
||||||
|
Pins the Console defaults: bearer auth, the Console base URL, a Console
|
||||||
|
label, and ``query_context = False`` (no ollama ``/api/show`` probe). The
|
||||||
|
endpoint subclasses below reuse it via cooperative multiple inheritance so
|
||||||
|
they also keep ``LLMClient``/``CodegenClient`` sampler parameters (opt-in:
|
||||||
|
none are sent unless configured).
|
||||||
|
|
||||||
|
A default ``User-Agent`` is always sent: the Console gateway rejects
|
||||||
|
urllib's default ``Python-urllib/<ver>`` with HTTP 403. Pass ``user_agent``
|
||||||
|
to override it (the Go docs ask clients to identify themselves).
|
||||||
|
"""
|
||||||
|
|
||||||
|
label = "opencode"
|
||||||
|
error_class = OpenCodeError
|
||||||
|
degeneration_error_class = OpenCodeError
|
||||||
|
query_context = False
|
||||||
|
|
||||||
|
def __init__(self, base_url: str = OPENCODE_BASE_URL, **kwargs):
|
||||||
|
if not kwargs.get("user_agent"):
|
||||||
|
kwargs["user_agent"] = OPENCODE_USER_AGENT
|
||||||
|
super().__init__(base_url=base_url, **kwargs)
|
||||||
|
|
||||||
|
def list_models(self, url: str | None = None) -> list[str]:
|
||||||
|
"""Fetch the Console model catalog (``GET /inference/v1/models``).
|
||||||
|
|
||||||
|
Returns the model ids; a fresh service-account key is not required for
|
||||||
|
the free models. Raises the client's own error type when unreachable.
|
||||||
|
"""
|
||||||
|
target = url or OPENCODE_MODELS_URL
|
||||||
|
request = urllib.request.Request(target, headers=self._headers())
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
request, timeout=min(self.timeout, 30.0)
|
||||||
|
) as response:
|
||||||
|
data = json.loads(response.read().decode("utf-8"))
|
||||||
|
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} model list unreachable at {target}: {exc}"
|
||||||
|
) from exc
|
||||||
|
return [
|
||||||
|
item["id"]
|
||||||
|
for item in (data.get("data") or [])
|
||||||
|
if isinstance(item, dict) and item.get("id")
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ConsoleLLMClient(OpenCodeConsoleClient, LLMClient):
|
||||||
|
"""Console-backed `llm` author (skill/category title + description).
|
||||||
|
|
||||||
|
Same opt-in sampler behavior as ``LLMClient`` (none sent unless configured);
|
||||||
|
the Console transport adds the bearer key and skips the ollama probe. Raises
|
||||||
|
``LLMError`` (unchanged contract).
|
||||||
|
|
||||||
|
``disable_thinking`` is forced **off**: `LLMClient` sends
|
||||||
|
``reasoning_effort: "none"`` (an ollama-compat knob) and the Console
|
||||||
|
gateway rejects that parameter with HTTP 400. Console models are not the
|
||||||
|
local reasoning model the knob exists for, so the parameter is simply not
|
||||||
|
sent. Passing ``disable_thinking=True`` to the constructor still ends up
|
||||||
|
off here.
|
||||||
|
"""
|
||||||
|
|
||||||
|
label = "opencode:llm"
|
||||||
|
error_class = LLMError
|
||||||
|
degeneration_error_class = LLMError
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
kwargs["disable_thinking"] = False
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class ConsoleCodegenClient(OpenCodeConsoleClient, CodegenClient):
|
||||||
|
"""Console-backed `codegen` writer (runnable skill bodies).
|
||||||
|
|
||||||
|
Console defaults on the codegen transport. Raises ``CodegenError`` /
|
||||||
|
``DegenerationError`` (unchanged contract).
|
||||||
|
"""
|
||||||
|
|
||||||
|
label = "opencode:codegen"
|
||||||
|
error_class = CodegenError
|
||||||
|
degeneration_error_class = DegenerationError
|
||||||
+179
-17
@@ -3,12 +3,14 @@
|
|||||||
A pure-stdlib HTTP server on localhost serving a Redux-DevTools-style
|
A pure-stdlib HTTP server on localhost serving a Redux-DevTools-style
|
||||||
inspector over the agent's decision flow. Reads the decision log
|
inspector over the agent's decision flow. Reads the decision log
|
||||||
(`decisions.jsonl`) plus the run lifecycle trace (`runs.jsonl`), exposes the
|
(`decisions.jsonl`) plus the run lifecycle trace (`runs.jsonl`), exposes the
|
||||||
static skill tree, the dream cost report, and three write endpoints: submit a
|
static skill tree, the dream cost report, and the write endpoints: submit a
|
||||||
request, answer a run paused for input, and relabel a decision (human override).
|
request, answer a run paused for input, answer a deferred authoring question,
|
||||||
|
resolve a repair offer, restart a skill write, and relabel a decision (human
|
||||||
|
override).
|
||||||
|
|
||||||
The scheduler's engine and LLM are built lazily, so the dashboard runs on the
|
The scheduler's engine and LLM are built lazily, so the dashboard runs in
|
||||||
thin dev box in replay mode (reads logs; submit degrades to a JSON error) and
|
replay mode on a machine without the engine (reads logs; submit degrades to a
|
||||||
in live mode on the box with SemIf + a local LLM.
|
JSON error) and in live mode on a host with SemIf + a local LLM.
|
||||||
|
|
||||||
python -m semif_agent.cli dashboard [--port 8765]
|
python -m semif_agent.cli dashboard [--port 8765]
|
||||||
"""
|
"""
|
||||||
@@ -93,36 +95,63 @@ def build_dream_report(scheduler: Scheduler) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def build_status(scheduler: Scheduler) -> dict:
|
def build_status(scheduler: Scheduler) -> dict:
|
||||||
|
with scheduler._lock:
|
||||||
current = (
|
current = (
|
||||||
{"skill": scheduler.current.skill, "request_id": scheduler.current.request.id}
|
{"skill": scheduler.current.skill, "request_id": scheduler.current.request.id}
|
||||||
if scheduler.current
|
if scheduler.current
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
pending = (
|
pending = (
|
||||||
{"skill": scheduler.pending.skill.name, "question": scheduler.pending.question}
|
{
|
||||||
|
"skill": scheduler.pending.skill.name,
|
||||||
|
"question": scheduler.pending.question,
|
||||||
|
"run_id": scheduler.pending.request.id,
|
||||||
|
}
|
||||||
if scheduler.pending
|
if scheduler.pending
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
queue = [
|
queue = [
|
||||||
{"id": request.id, "weight": weight, "text": request.text[:80]}
|
{"id": request.id, "text": request.text[:80]}
|
||||||
for weight, request in scheduler.queue.items()
|
for request in scheduler.queue.items()
|
||||||
]
|
]
|
||||||
|
tau = scheduler.tau
|
||||||
|
queue_max = scheduler.queue.max_size
|
||||||
|
questions = scheduler.pending_questions()
|
||||||
|
repairs = scheduler.pending_repairs()
|
||||||
|
approvals = scheduler.pending_approvals()
|
||||||
return {
|
return {
|
||||||
"current": current,
|
"current": current,
|
||||||
"pending": pending,
|
"pending": pending,
|
||||||
"queue": queue,
|
"queue": queue,
|
||||||
"tau": scheduler.tau,
|
"tau": tau,
|
||||||
"queue_max": scheduler.queue.max_size,
|
"queue_max": queue_max,
|
||||||
|
"questions": questions,
|
||||||
|
"repairs": repairs,
|
||||||
|
"approvals": approvals,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_tree_payload(scheduler: Scheduler) -> dict:
|
def build_tree_payload(scheduler: Scheduler) -> dict:
|
||||||
tree = scheduler.tree
|
with scheduler._lock:
|
||||||
|
snapshot = {
|
||||||
|
category: list(skills) for category, skills in scheduler.tree.items()
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
"categories": {
|
"categories": {
|
||||||
category: [{"name": skill.name, "description": skill.description} for skill in skills]
|
category: [
|
||||||
for category, skills in sorted(tree.items())
|
{
|
||||||
|
"name": skill.name,
|
||||||
|
"description": skill.description,
|
||||||
|
"status": skill.status,
|
||||||
|
"origin": skill.origin,
|
||||||
|
"integration": skill.integration or None,
|
||||||
|
"integration_source": skill.integration_source,
|
||||||
}
|
}
|
||||||
|
for skill in skills
|
||||||
|
]
|
||||||
|
for category, skills in sorted(snapshot.items())
|
||||||
|
},
|
||||||
|
"new_skill_modes": scheduler.category_modes(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -197,6 +226,27 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
|||||||
if path == "/api/status":
|
if path == "/api/status":
|
||||||
self._send(200, build_status(self.scheduler))
|
self._send(200, build_status(self.scheduler))
|
||||||
return
|
return
|
||||||
|
if path == "/api/questions":
|
||||||
|
self._send(200, {"questions": self.scheduler.pending_questions()})
|
||||||
|
return
|
||||||
|
if path == "/api/repairs":
|
||||||
|
self._send(200, {"repairs": self.scheduler.pending_repairs()})
|
||||||
|
return
|
||||||
|
if path == "/api/approvals":
|
||||||
|
self._send(200, {"approvals": self.scheduler.pending_approvals()})
|
||||||
|
return
|
||||||
|
if path == "/api/new-skill-modes":
|
||||||
|
self._send(200, {"modes": self.scheduler.category_modes()})
|
||||||
|
return
|
||||||
|
if path == "/api/timers":
|
||||||
|
self._send(
|
||||||
|
200,
|
||||||
|
{
|
||||||
|
"pending": self.scheduler.timers.pending(),
|
||||||
|
"fired": self.scheduler.timers.fired(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return
|
||||||
self._send_error(404, "no such endpoint")
|
self._send_error(404, "no such endpoint")
|
||||||
|
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
@@ -205,13 +255,16 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
try:
|
try:
|
||||||
body = self._read_json()
|
body = self._read_json()
|
||||||
status, detail = self.scheduler.submit(
|
reply = self._complete(
|
||||||
str(body.get("text", "")), source=str(body.get("source", "dashboard"))
|
self.scheduler.submit_request(
|
||||||
|
str(body.get("text", "")),
|
||||||
|
source=str(body.get("source", "dashboard")),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._send_error(500, str(exc))
|
self._send_error(500, str(exc))
|
||||||
return
|
return
|
||||||
self._send(200, {"status": status, "detail": detail})
|
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
|
||||||
return
|
return
|
||||||
if path == "/api/relabel":
|
if path == "/api/relabel":
|
||||||
with self.lock:
|
with self.lock:
|
||||||
@@ -227,7 +280,81 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
try:
|
try:
|
||||||
body = self._read_json()
|
body = self._read_json()
|
||||||
status, detail = self.scheduler.answer(str(body.get("text", "")))
|
reply = self._complete(self.scheduler.answer(str(body.get("text", ""))))
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
return
|
||||||
|
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
|
||||||
|
return
|
||||||
|
if path == "/api/restart":
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
status, detail = self.scheduler.restart_skill(
|
||||||
|
str(body.get("category", "")), str(body.get("skill", ""))
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
return
|
||||||
|
self._send(200, {"status": status, "detail": detail})
|
||||||
|
return
|
||||||
|
if path == "/api/questions":
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
status, detail = self.scheduler.answer_question(
|
||||||
|
str(body.get("id", "")), str(body.get("text", ""))
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
return
|
||||||
|
self._send(200, {"status": status, "detail": detail})
|
||||||
|
return
|
||||||
|
if path == "/api/repair":
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
action = body.get("action")
|
||||||
|
status, detail = self.scheduler.resolve_repair(
|
||||||
|
str(body.get("id", "")),
|
||||||
|
None if action is None else str(action),
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
return
|
||||||
|
self._send(200, {"status": status, "detail": detail})
|
||||||
|
return
|
||||||
|
if path == "/api/approvals":
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
status, detail = self.scheduler.answer_approval(
|
||||||
|
str(body.get("id", "")), bool(body.get("approve"))
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
return
|
||||||
|
self._send(200, {"status": status, "detail": detail})
|
||||||
|
return
|
||||||
|
if path == "/api/delete":
|
||||||
|
self._housekeeping("delete_skill")
|
||||||
|
return
|
||||||
|
if path == "/api/clear-config":
|
||||||
|
self._housekeeping("clear_skill_config")
|
||||||
|
return
|
||||||
|
if path == "/api/regen":
|
||||||
|
self._housekeeping("regen_skill")
|
||||||
|
return
|
||||||
|
if path == "/api/cancel-build":
|
||||||
|
self._housekeeping("cancel_skill_build")
|
||||||
|
return
|
||||||
|
if path == "/api/new-skill-mode":
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
status, detail = self.scheduler.set_category_mode(
|
||||||
|
str(body.get("category", "")), str(body.get("mode", ""))
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._send_error(500, str(exc))
|
self._send_error(500, str(exc))
|
||||||
return
|
return
|
||||||
@@ -235,6 +362,41 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
|||||||
return
|
return
|
||||||
self._send_error(404, "no such endpoint")
|
self._send_error(404, "no such endpoint")
|
||||||
|
|
||||||
|
def _housekeeping(self, method: str):
|
||||||
|
"""Run a housekeeping operation by category + skill (dashboard action)."""
|
||||||
|
with self.lock:
|
||||||
|
try:
|
||||||
|
body = self._read_json()
|
||||||
|
status, detail = getattr(self.scheduler, method)(
|
||||||
|
str(body.get("category", "")), str(body.get("skill", ""))
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_error(500, str(exc))
|
||||||
|
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):
|
def log_message(self, format, *args):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
@@ -66,21 +66,47 @@ class Request:
|
|||||||
text: str
|
text: str
|
||||||
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
|
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
|
||||||
source: str = "typed"
|
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)
|
meta: dict[str, Any] = field(default_factory=dict)
|
||||||
received_at: float = field(default_factory=time.time)
|
received_at: float = field(default_factory=time.time)
|
||||||
priority: float = 0.5
|
priority: float = 0.5
|
||||||
reentries: int = 0
|
reentries: int = 0
|
||||||
resume: dict[str, Any] = field(default_factory=dict)
|
resume: dict[str, Any] = field(default_factory=dict)
|
||||||
user_input: str | None = None
|
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":
|
def copy_for_requeue(self) -> "Request":
|
||||||
return Request(
|
return Request(
|
||||||
text=self.text,
|
text=self.text,
|
||||||
id=self.id,
|
id=self.id,
|
||||||
source=self.source,
|
source=self.source,
|
||||||
|
origin_source=self.origin_source,
|
||||||
meta=dict(self.meta),
|
meta=dict(self.meta),
|
||||||
received_at=self.received_at,
|
received_at=self.received_at,
|
||||||
priority=self.priority,
|
priority=self.priority,
|
||||||
reentries=self.reentries + 1,
|
reentries=self.reentries + 1,
|
||||||
resume=dict(self.resume),
|
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,
|
||||||
)
|
)
|
||||||
+180
-9
@@ -1,15 +1,23 @@
|
|||||||
"""Real SemIf decision engine (no mocking).
|
"""The decision-engine contract and the local SemIf implementation.
|
||||||
|
|
||||||
Wraps the SemIf package (`semif_phase1`). The import and model load happen
|
`DecisionEngine` is the pluggable contract every provider satisfies; the
|
||||||
|
provider is selected per machine by `engine.provider` in config.json, exactly
|
||||||
|
like `llm.provider` / `codegen.provider`. `SemIfEngine` is the default: it wraps
|
||||||
|
the SemIf package (`semif_phase1`). The import and model load happen
|
||||||
lazily so the rest of the agent is pure stdlib and testable without SemIf
|
lazily so the rest of the agent is pure stdlib and testable without SemIf
|
||||||
installed. On hardware that is neither CUDA nor Apple, use the shipped
|
installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
|
||||||
llama.cpp backend: a local GGUF scored on CPU (or Vulkan if your llama.cpp
|
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
|
||||||
build enables it). This engine is only usable on a machine with SemIf and the
|
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
|
||||||
pinned GGUF available; elsewhere calls raise EngineUnavailable.
|
machine with SemIf and the pinned GGUF available; elsewhere calls raise
|
||||||
|
EngineUnavailable. The remote alternatives live in `semif_agent.winnow` (the
|
||||||
|
Winnow reference server) and `semif_agent.ollama_systemone` (ollama's native
|
||||||
|
System One route).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -17,7 +25,72 @@ from .decisions import DecisionRequest, DecisionResult
|
|||||||
|
|
||||||
|
|
||||||
class EngineUnavailable(RuntimeError):
|
class EngineUnavailable(RuntimeError):
|
||||||
"""SemIf is not installed or the configured model is missing."""
|
"""The decision engine is not installed, not reachable, or failed.
|
||||||
|
|
||||||
|
This is the one error a decision engine raises. It is fatal by contract:
|
||||||
|
the scheduler records it (`_mark_fatal`) and the front ends exit, because
|
||||||
|
the agent cannot make decisions without a real engine.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class DecisionEngine(ABC):
|
||||||
|
"""The pluggable decision-engine contract.
|
||||||
|
|
||||||
|
A decision engine answers a `DecisionRequest` (state + question + typed
|
||||||
|
options) with a `DecisionResult` (probabilities over exactly those options).
|
||||||
|
It is selected per machine by `engine.provider` in config.json, mirroring
|
||||||
|
`llm.provider` / `codegen.provider`:
|
||||||
|
|
||||||
|
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
|
||||||
|
* ``"winnow"`` — a remote Winnow ``/v1/systemone`` typed-decision API
|
||||||
|
(`semif_agent.winnow.WinnowEngine`).
|
||||||
|
* ``"ollama"`` — ollama's native System One ``/v1/systemone`` route
|
||||||
|
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`), probed through
|
||||||
|
ollama's own ``/api/version`` + ``/api/show`` endpoints.
|
||||||
|
|
||||||
|
The engine is always real: any failure to produce a decision raises
|
||||||
|
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the
|
||||||
|
optional text-generation face of the same model (used by
|
||||||
|
`llm.provider == "semif"`); an engine that cannot generate text raises
|
||||||
|
`EngineUnavailable` there rather than inventing a reply.
|
||||||
|
"""
|
||||||
|
|
||||||
|
label: str = "engine"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def context_tokens(self) -> int:
|
||||||
|
"""The decision context window, in tokens.
|
||||||
|
|
||||||
|
Every decision state must fit inside it, so the scheduler sizes the
|
||||||
|
generated skill bodies it feeds the fidelity gate from this value. A
|
||||||
|
provider that does not expose its window keeps the conservative local
|
||||||
|
default (the local 4B engine's `engine.context_tokens`).
|
||||||
|
"""
|
||||||
|
return 4096
|
||||||
|
|
||||||
|
@property
|
||||||
|
@abstractmethod
|
||||||
|
def loaded(self) -> bool:
|
||||||
|
"""Whether the underlying model is loaded/warm."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def warm(self) -> None:
|
||||||
|
"""Load/warm the model, raising `EngineUnavailable` on failure."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def call(self, request: DecisionRequest) -> DecisionResult:
|
||||||
|
"""Score one decision, raising `EngineUnavailable` on failure."""
|
||||||
|
|
||||||
|
def generate(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
temperature: float = 0.0,
|
||||||
|
max_tokens: int = 256,
|
||||||
|
) -> str:
|
||||||
|
"""Autoregressively generate text from the same model, if supported."""
|
||||||
|
raise EngineUnavailable(
|
||||||
|
f"{self.label} engine does not support text generation"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -28,16 +101,84 @@ class EngineConfig:
|
|||||||
gguf: str = ""
|
gguf: str = ""
|
||||||
context_tokens: int = 4096
|
context_tokens: int = 4096
|
||||||
threads: int | None = None
|
threads: int | None = None
|
||||||
|
# GPU offload (llama.cpp). 0 keeps the CPU-only default; a positive count
|
||||||
|
# offloads that many layers, -1 offloads all of them. Requires a
|
||||||
|
# llama-cpp-python built with a GPU backend (Vulkan/ROCm/CUDA).
|
||||||
|
gpu_layers: int = 0
|
||||||
|
gpu_device: int | None = None
|
||||||
|
gpu_split: int = 0
|
||||||
|
|
||||||
|
|
||||||
class SemIfEngine:
|
def _require_gpu_offload() -> None:
|
||||||
"""One pinned SemIf model, loaded once and used for every decision."""
|
"""Fail loudly when GPU layers are requested but the build cannot offload."""
|
||||||
|
import llama_cpp
|
||||||
|
|
||||||
|
if not llama_cpp.llama_supports_gpu_offload():
|
||||||
|
raise EngineUnavailable(
|
||||||
|
"engine.gpu_layers is set but this llama-cpp-python build has no GPU "
|
||||||
|
"backend. Rebuild it with one, e.g. "
|
||||||
|
"CMAKE_ARGS='-DGGML_VULKAN=on' (Vulkan), '-DGGML_HIP=on' (ROCm) or "
|
||||||
|
"'-DGGML_CUDA=on' (CUDA)."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _install_gpu_state_reset(model) -> None:
|
||||||
|
"""Force a full cache reset between scored prompts when running on the GPU.
|
||||||
|
|
||||||
|
SemIf's `_Engine.clear` calls `llama_memory_clear(memory, False)`: it resets
|
||||||
|
the cache metadata but leaves the stored data. The CPU backend tolerates that
|
||||||
|
(the slots are overwritten before use), but the Vulkan backend keeps stale
|
||||||
|
hybrid-attention/recurrent state, so repeated `score` calls drift and return
|
||||||
|
wrong probabilities. Clearing the data as well restores determinism and
|
||||||
|
matches the CPU path. Applied only when offloading, so CPU behaviour is
|
||||||
|
untouched.
|
||||||
|
"""
|
||||||
|
engine = model.engine
|
||||||
|
library = engine.lib
|
||||||
|
|
||||||
|
def clear():
|
||||||
|
library.llama_memory_clear(engine.memory, True)
|
||||||
|
|
||||||
|
engine.clear = clear
|
||||||
|
|
||||||
|
|
||||||
|
def _offloading_params(original, config: EngineConfig):
|
||||||
|
"""Wrap SemIf's CPU-only model-params factory to offload layers to the GPU.
|
||||||
|
|
||||||
|
`semif_phase1.llamacpp_backend` is CPU-only by construction: its
|
||||||
|
`_cpu_model_params` hardcodes `n_gpu_layers = 0`. The backend looks that name
|
||||||
|
up on its own module while loading, so wrapping it for the duration of the
|
||||||
|
load lets the same path offload without patching (and losing) the re-cloned
|
||||||
|
engine source. The caller restores the original afterwards, so a CPU engine
|
||||||
|
loaded later in the same process is unaffected.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def offloading(library):
|
||||||
|
params = original(library)
|
||||||
|
params.n_gpu_layers = config.gpu_layers
|
||||||
|
params.split_mode = config.gpu_split
|
||||||
|
if config.gpu_device is not None:
|
||||||
|
params.main_gpu = config.gpu_device
|
||||||
|
return params
|
||||||
|
|
||||||
|
return offloading
|
||||||
|
|
||||||
|
|
||||||
|
class SemIfEngine(DecisionEngine):
|
||||||
|
"""One pinned SemIf model, loaded once and used for every decision.
|
||||||
|
|
||||||
|
The default `engine.provider`: the local llama.cpp GGUF. Text generation
|
||||||
|
from the same model backs `llm.provider == "semif"`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
label = "semif"
|
||||||
|
|
||||||
def __init__(self, config: EngineConfig):
|
def __init__(self, config: EngineConfig):
|
||||||
self.config = config
|
self.config = config
|
||||||
self._model = None
|
self._model = None
|
||||||
self._tokenizer = None
|
self._tokenizer = None
|
||||||
self._metadata = None
|
self._metadata = None
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
def _ensure_loaded(self) -> tuple:
|
def _ensure_loaded(self) -> tuple:
|
||||||
if self._model is not None:
|
if self._model is not None:
|
||||||
@@ -57,6 +198,11 @@ class SemIfEngine:
|
|||||||
"SemIf is not installed here. Install it on the target box with "
|
"SemIf is not installed here. Install it on the target box with "
|
||||||
"`pip install -e '.[test,llamacpp]'`."
|
"`pip install -e '.[test,llamacpp]'`."
|
||||||
) from exc
|
) from exc
|
||||||
|
if self.config.gpu_layers:
|
||||||
|
_require_gpu_offload()
|
||||||
|
original_params = backend._cpu_model_params
|
||||||
|
if self.config.gpu_layers:
|
||||||
|
backend._cpu_model_params = _offloading_params(original_params, self.config)
|
||||||
try:
|
try:
|
||||||
model, tokenizer, metadata = backend.load_model(
|
model, tokenizer, metadata = backend.load_model(
|
||||||
self.config.source,
|
self.config.source,
|
||||||
@@ -67,14 +213,33 @@ class SemIfEngine:
|
|||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise EngineUnavailable(f"Failed to load the SemIf model: {exc}") from exc
|
raise EngineUnavailable(f"Failed to load the SemIf model: {exc}") from exc
|
||||||
|
finally:
|
||||||
|
backend._cpu_model_params = original_params
|
||||||
|
if self.config.gpu_layers:
|
||||||
|
_install_gpu_state_reset(model)
|
||||||
|
# The backend hardcodes n_gpu_layers=0 in its metadata; record what we
|
||||||
|
# actually asked llama.cpp to offload instead.
|
||||||
|
metadata = dict(metadata)
|
||||||
|
metadata["n_gpu_layers"] = self.config.gpu_layers
|
||||||
|
if self.config.gpu_device is not None:
|
||||||
|
metadata["main_gpu"] = self.config.gpu_device
|
||||||
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
|
self._model, self._tokenizer, self._metadata = model, tokenizer, metadata
|
||||||
return model, tokenizer, metadata
|
return model, tokenizer, metadata
|
||||||
|
|
||||||
|
@property
|
||||||
|
def context_tokens(self) -> int:
|
||||||
|
return int(self.config.context_tokens or 4096)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def loaded(self) -> bool:
|
def loaded(self) -> bool:
|
||||||
return self._model is not None
|
return self._model is not None
|
||||||
|
|
||||||
|
def warm(self) -> None:
|
||||||
|
"""Load the model (idempotent), raising `EngineUnavailable` on failure."""
|
||||||
|
self._ensure_loaded()
|
||||||
|
|
||||||
def call(self, request: DecisionRequest) -> DecisionResult:
|
def call(self, request: DecisionRequest) -> DecisionResult:
|
||||||
|
with self._lock:
|
||||||
model, tokenizer, metadata = self._ensure_loaded()
|
model, tokenizer, metadata = self._ensure_loaded()
|
||||||
from semif_phase1 import llamacpp_backend as backend
|
from semif_phase1 import llamacpp_backend as backend
|
||||||
|
|
||||||
@@ -106,7 +271,12 @@ class SemIfEngine:
|
|||||||
context (there is no high-level chat-completion object on the CPU
|
context (there is no high-level chat-completion object on the CPU
|
||||||
backend), stopping at the tokenizer's eos token. The KV cache is cleared
|
backend), stopping at the tokenizer's eos token. The KV cache is cleared
|
||||||
at the start, so interleaving scoring and generation on one model is safe.
|
at the start, so interleaving scoring and generation on one model is safe.
|
||||||
|
|
||||||
|
It shares `self._lock` with `call`, so a generation serializes against
|
||||||
|
decisions on the one loaded model — short JSON replies are seconds of
|
||||||
|
contention, and there is only ever one copy of the GGUF.
|
||||||
"""
|
"""
|
||||||
|
with self._lock:
|
||||||
model, tokenizer, metadata = self._ensure_loaded()
|
model, tokenizer, metadata = self._ensure_loaded()
|
||||||
try:
|
try:
|
||||||
import numpy
|
import numpy
|
||||||
@@ -147,3 +317,4 @@ def _sample_token(logits, temperature: float, rng) -> int:
|
|||||||
probabilities = numpy.exp(scaled)
|
probabilities = numpy.exp(scaled)
|
||||||
probabilities /= probabilities.sum()
|
probabilities /= probabilities.sum()
|
||||||
return int(rng.choice(probabilities.size, p=probabilities))
|
return int(rng.choice(probabilities.size, p=probabilities))
|
||||||
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Messaging gateway: external messenger intake/reply for the SemIf agent.
|
||||||
|
|
||||||
|
The gateway is the agent's **command** surface and nothing else. A
|
||||||
|
`GatewayAdapter` owns a transport (SimpleX first), and `GatewayService` maps
|
||||||
|
inbound text onto the scheduler's existing gate/score/queue/dispatch pipeline
|
||||||
|
and routes results, questions, and repairs back to the originating chat.
|
||||||
|
|
||||||
|
Messaging *UX* — invite links, reading a contact's messages, composing sends —
|
||||||
|
does not live here; it belongs to the standalone bridge services in
|
||||||
|
`semif_agent.bridges`. Keeping the command surface free of that functionality
|
||||||
|
is a hard boundary (see AGENTS.md "gateway isolation").
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||||
|
from .service import GatewayService
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"GatewayAdapter",
|
||||||
|
"InboundMessage",
|
||||||
|
"OutboundMessage",
|
||||||
|
"GatewayService",
|
||||||
|
]
|
||||||
|
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""The messenger command-gateway adapter contract.
|
||||||
|
|
||||||
|
An adapter owns one command transport (SimpleX WebSocket, and later Telegram,
|
||||||
|
Signal, ...). It delivers inbound text as `InboundMessage` and drains outbound
|
||||||
|
replies from a stdlib queue. Everything about the SemIf scheduler — gating,
|
||||||
|
scoring, queueing, run ownership, questions, repairs — lives in `GatewayService`;
|
||||||
|
an adapter must not know it exists. Neither knows anything about messaging UX
|
||||||
|
(invite links, reading, composing): that is the bridge services' job.
|
||||||
|
|
||||||
|
The transport is intentionally a plain `queue.Queue`: the adapter's event loop
|
||||||
|
puts an outbound message into the queue, the service puts replies into it. This
|
||||||
|
keeps scheduler work (which is synchronous and can block on the decision engine)
|
||||||
|
off the adapter's event loop.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import queue
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class InboundMessage:
|
||||||
|
"""One (possibly batched) inbound text message from an external chat."""
|
||||||
|
|
||||||
|
text: str
|
||||||
|
chat_id: str
|
||||||
|
chat_type: str = "dm" # dm | group
|
||||||
|
contact_id: str | None = None
|
||||||
|
display_name: str | None = None
|
||||||
|
raw: dict[str, Any] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OutboundMessage:
|
||||||
|
"""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"
|
||||||
|
|
||||||
|
#: 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
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def run(self, on_inbound: InboundHandler, outbound: "queue.Queue[OutboundMessage | None]") -> None:
|
||||||
|
"""Block, delivering inbound messages and sending queued outbound ones.
|
||||||
|
|
||||||
|
A `None` sentinel in `outbound` asks `run` to return.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Release transport resources. Best-effort; must not raise."""
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
"""Optional LLM cleanup of a skill's result line for the messenger gateway.
|
||||||
|
|
||||||
|
The scheduler's run summary is deterministic and technical — ``<skill>:
|
||||||
|
<ok|failed> — <action_log>``, where the action log is whatever the skill body
|
||||||
|
wrote (often mechanical: ``PUT 201 …``, ``sent via /_send to contact 12``).
|
||||||
|
This layer rewrites only that result detail into one grounded, friendly
|
||||||
|
sentence for a chat front end.
|
||||||
|
|
||||||
|
It is generation, never a decision: the success/failure verdict and the routing
|
||||||
|
are already settled by SemIf and the runner, and the rewrite is never fed back
|
||||||
|
into assessment, tracing, or the decision log. The prompt forbids adding,
|
||||||
|
inferring, or dropping facts, and `humanize` falls back to the original text on
|
||||||
|
any error, timeout, empty reply, or runaway length — a cleanup failure
|
||||||
|
must never swallow or corrupt a real result.
|
||||||
|
|
||||||
|
It reuses the scheduler's configured ``llm`` client (its endpoint/model/sampler)
|
||||||
|
and passes a short per-call ``timeout`` so a slow cleanup cannot hold the
|
||||||
|
gateway's poll loop for the client's full authoring budget. It is deliberately
|
||||||
|
gateway-only: the runner and the REPL keep the raw, deterministic summary.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
#: The strict rephrasing instruction. Grounding is enforced by the prompt and
|
||||||
|
#: by the caller's fallback, not by a second model call.
|
||||||
|
SYSTEM_PROMPT = (
|
||||||
|
"You rewrite an assistant's raw action result into one short, friendly "
|
||||||
|
"sentence for a chat reply.\n"
|
||||||
|
"Rules:\n"
|
||||||
|
"- Use ONLY the facts in the result. Do not add, guess, or infer anything.\n"
|
||||||
|
"- Preserve whether the action succeeded or failed exactly as stated.\n"
|
||||||
|
"- Do not mention servers, HTTP status codes, command names, file paths, "
|
||||||
|
"or internal bookkeeping unless that is the only content.\n"
|
||||||
|
"- One sentence. No preamble, no explanation, no quotes, no markdown.\n"
|
||||||
|
"- If the result is already a plain sentence, return it unchanged."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_reply(raw: str) -> str:
|
||||||
|
"""Normalize a model reply into one bare sentence, or "" if unusable."""
|
||||||
|
text = (raw or "").strip()
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
# Drop a wrapping pair of quotes the model may add.
|
||||||
|
if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'“”‘’":
|
||||||
|
text = text[1:-1].strip()
|
||||||
|
# Collapse newlines / runs of whitespace to a single line.
|
||||||
|
return " ".join(text.split())
|
||||||
|
|
||||||
|
|
||||||
|
class Humanizer:
|
||||||
|
"""Rewrite a result line with an LLM, falling back to the source verbatim."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
client,
|
||||||
|
*,
|
||||||
|
enabled: bool = True,
|
||||||
|
timeout: float = 20.0,
|
||||||
|
max_tokens: int = 200,
|
||||||
|
max_chars: int = 600,
|
||||||
|
):
|
||||||
|
self.client = client
|
||||||
|
self.enabled = bool(enabled) and client is not None
|
||||||
|
self.timeout = float(timeout)
|
||||||
|
self.max_tokens = int(max_tokens)
|
||||||
|
self.max_chars = int(max_chars)
|
||||||
|
|
||||||
|
def humanize(self, text: str) -> str:
|
||||||
|
"""Return a grounded rewrite of `text`, or `text` unchanged.
|
||||||
|
|
||||||
|
Never raises: any failure (unreachable client, timeout, empty or
|
||||||
|
unusable reply, runaway length) returns the original text.
|
||||||
|
"""
|
||||||
|
source = (text or "").strip()
|
||||||
|
if not self.enabled or not source:
|
||||||
|
return text
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": SYSTEM_PROMPT},
|
||||||
|
{"role": "user", "content": source},
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
raw = self.client.chat(
|
||||||
|
messages, max_tokens=self.max_tokens, timeout=self.timeout
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return text
|
||||||
|
cleaned = _clean_reply(raw)
|
||||||
|
if not cleaned:
|
||||||
|
return text
|
||||||
|
if len(cleaned) > self.max_chars:
|
||||||
|
return text
|
||||||
|
return cleaned
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
"""LXMF (Reticulum) command-gateway adapter.
|
||||||
|
|
||||||
|
The gateway is the agent's **command** surface: allowlisted contacts send LXMF
|
||||||
|
messages to the bot and their text is fed to the scheduler, whose reply is sent
|
||||||
|
back. All the messaging *UX* surface (reading a contact's messages, composing on
|
||||||
|
the user's behalf, showing a contact link) would live in a separate bridge
|
||||||
|
service, never here — see AGENTS.md "gateway isolation".
|
||||||
|
|
||||||
|
This adapter is the policy layer over the neutral `LxmfDaemon` transport in
|
||||||
|
`semif_agent.lxmf_transport`: it applies the allowlist, batches rapid messages,
|
||||||
|
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
|
||||||
|
|
||||||
|
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, 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, 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))
|
||||||
|
self.batch_delay = float(cfg.get("text_batch_delay", 0.8))
|
||||||
|
config_dir = cfg.get("config_dir") or os.path.join(
|
||||||
|
".runtime", "lxmf", "reticulum"
|
||||||
|
)
|
||||||
|
storage_path = cfg.get("storage_path") or os.path.join(
|
||||||
|
".runtime", "lxmf", "router"
|
||||||
|
)
|
||||||
|
self.daemon = LxmfDaemon(
|
||||||
|
config_dir=config_dir,
|
||||||
|
storage_path=storage_path,
|
||||||
|
display_name=cfg.get("display_name", "semif"),
|
||||||
|
announce_interval=float(cfg.get("announce_interval", 3600)),
|
||||||
|
stamp_cost=cfg.get("stamp_cost"),
|
||||||
|
desired_method=cfg.get("desired_method", "direct"),
|
||||||
|
propagation_node=cfg.get("propagation_node", ""),
|
||||||
|
trace=trace,
|
||||||
|
name=self.name,
|
||||||
|
)
|
||||||
|
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, 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 ----
|
||||||
|
|
||||||
|
def is_authorized(self, source_hash: str, display_name: str | None) -> bool:
|
||||||
|
if self.allow_all_users:
|
||||||
|
return True
|
||||||
|
candidates = {str(source_hash)}
|
||||||
|
if display_name:
|
||||||
|
candidates.add(str(display_name))
|
||||||
|
if not self.allowed_users:
|
||||||
|
return False
|
||||||
|
return any(user in candidates for user in self.allowed_users)
|
||||||
|
|
||||||
|
# ---- transport ----
|
||||||
|
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
on_inbound,
|
||||||
|
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, 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
|
||||||
|
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
|
||||||
|
).start()
|
||||||
|
self.daemon.run(self._on_item)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
timers = list(self._timers.values())
|
||||||
|
self._timers.clear()
|
||||||
|
for timer in timers:
|
||||||
|
timer.cancel()
|
||||||
|
self._voice_queue.put(None)
|
||||||
|
self.daemon.close()
|
||||||
|
|
||||||
|
# ---- inbound ----
|
||||||
|
|
||||||
|
def _on_item(self, message: dict) -> None:
|
||||||
|
source_hash = str(message.get("source_hash") or "")
|
||||||
|
if not source_hash:
|
||||||
|
return
|
||||||
|
display_name = message.get("display_name")
|
||||||
|
if not self.is_authorized(source_hash, display_name):
|
||||||
|
self.daemon._event(
|
||||||
|
"gateway_denied",
|
||||||
|
contact_id=source_hash,
|
||||||
|
display_name=display_name,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
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: 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{text}" if existing else text
|
||||||
|
self._buffered[chat] = message
|
||||||
|
timer = self._timers.get(chat)
|
||||||
|
if timer is not None:
|
||||||
|
timer.cancel()
|
||||||
|
timer = threading.Timer(self.batch_delay, self._flush, args=(chat,))
|
||||||
|
timer.daemon = True
|
||||||
|
self._timers[chat] = timer
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
def _flush(self, chat: str) -> None:
|
||||||
|
with self._lock:
|
||||||
|
text = self._buffers.pop(chat, "")
|
||||||
|
message = self._buffered.pop(chat, None)
|
||||||
|
self._timers.pop(chat, None)
|
||||||
|
if message is None or not text:
|
||||||
|
return
|
||||||
|
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=source_hash,
|
||||||
|
display_name=display_name,
|
||||||
|
chars=len(text),
|
||||||
|
)
|
||||||
|
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
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
"""GatewayService: map external messenger traffic onto the SemIf scheduler.
|
||||||
|
|
||||||
|
The scheduler is a single execution slot with one global `pending` run. The
|
||||||
|
service does not fake concurrency: inbound text is fed through the existing
|
||||||
|
gate (`submit_request` -> gate/score/queue/dispatch), results and deferred
|
||||||
|
questions are routed back to the originating chat, and while one chat owns a
|
||||||
|
`needs_input` pause that chat answers it. Another chat messaging during that
|
||||||
|
pause is told to wait rather than silently abandoning the first chat's run.
|
||||||
|
|
||||||
|
One service can front several transports at once (SimpleX, LXMF, ...). Each
|
||||||
|
adapter is addressed by its platform name, so a request source is
|
||||||
|
`"<platform>:<chat_id>"`, the single pending-run guard is shared across
|
||||||
|
platforms, and every reply is sent back through the queue of the platform that
|
||||||
|
originated it.
|
||||||
|
|
||||||
|
Ownership: a request id maps to the `(platform, chat)` that sent it. A run
|
||||||
|
re-queued by the scheduler (updated request) mints a new id; the scheduler's
|
||||||
|
`on_request_requeued` hook copies the owner across so the completion still
|
||||||
|
reaches the right chat.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .base import InboundMessage, OutboundMessage
|
||||||
|
from .humanize import Humanizer
|
||||||
|
|
||||||
|
#: The scheduler's run summary wraps the real result as
|
||||||
|
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
|
||||||
|
#: gateway) speaks just `<detail>`. Kept as a fallback for callers that hand
|
||||||
|
#: `_reply` a raw summary; the scheduler itself passes the unwrapped `result`.
|
||||||
|
_RESULT_SEP = " — "
|
||||||
|
|
||||||
|
_REPAIR_ACTIONS = {
|
||||||
|
"retry": "retry",
|
||||||
|
"repair": "repair_skill",
|
||||||
|
"fix": "repair_skill",
|
||||||
|
"repair_skill": "repair_skill",
|
||||||
|
"ask": "ask_user",
|
||||||
|
"ask_user": "ask_user",
|
||||||
|
"no": "no_repair",
|
||||||
|
"skip": "no_repair",
|
||||||
|
"cancel": "no_repair",
|
||||||
|
"no_repair": "no_repair",
|
||||||
|
}
|
||||||
|
|
||||||
|
_APPROVAL_ACTIONS = {
|
||||||
|
"yes": True,
|
||||||
|
"y": True,
|
||||||
|
"yeah": True,
|
||||||
|
"yep": True,
|
||||||
|
"yup": True,
|
||||||
|
"approve": True,
|
||||||
|
"approved": True,
|
||||||
|
"ok": True,
|
||||||
|
"okay": True,
|
||||||
|
"sure": True,
|
||||||
|
"confirm": True,
|
||||||
|
"affirmative": True,
|
||||||
|
"go ahead": True,
|
||||||
|
"do it": True,
|
||||||
|
"no": False,
|
||||||
|
"n": False,
|
||||||
|
"nope": False,
|
||||||
|
"deny": False,
|
||||||
|
"denied": False,
|
||||||
|
"cancel": False,
|
||||||
|
"skip": False,
|
||||||
|
"never mind": False,
|
||||||
|
"nevermind": False,
|
||||||
|
"dont": False,
|
||||||
|
"don't": False,
|
||||||
|
"stop": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
#: An owner target is `(platform, chat_id)`.
|
||||||
|
Target = tuple[str, str]
|
||||||
|
|
||||||
|
#: 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.
|
||||||
|
|
||||||
|
Returns the detail the skill actually produced. A line with no wrapper is
|
||||||
|
returned unchanged.
|
||||||
|
"""
|
||||||
|
if _RESULT_SEP in text:
|
||||||
|
return text.split(_RESULT_SEP, 1)[1].strip()
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _reply_kind(status: str) -> str:
|
||||||
|
"""Classify a scheduler outcome for a result-only front end."""
|
||||||
|
if status in ("running", "ran"):
|
||||||
|
return "result"
|
||||||
|
if status == "needs_input":
|
||||||
|
return "question"
|
||||||
|
if status == "queued":
|
||||||
|
return "status"
|
||||||
|
return "notice"
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_adapters(adapters) -> dict:
|
||||||
|
"""Accept a single adapter or a list/dict of them, keyed by platform name."""
|
||||||
|
if isinstance(adapters, dict):
|
||||||
|
return {str(name): adapter for name, adapter in adapters.items()}
|
||||||
|
if hasattr(adapters, "name") and not isinstance(
|
||||||
|
adapters, (list, tuple, set, frozenset)
|
||||||
|
):
|
||||||
|
return {adapters.name: adapters}
|
||||||
|
result: dict = {}
|
||||||
|
for adapter in adapters:
|
||||||
|
result[adapter.name] = adapter
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class GatewayService:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
scheduler,
|
||||||
|
adapters,
|
||||||
|
config: dict | None = None,
|
||||||
|
poll_interval: float = 1.0,
|
||||||
|
humanizer: Humanizer | None = None,
|
||||||
|
):
|
||||||
|
self.scheduler = scheduler
|
||||||
|
self.adapters = _normalize_adapters(adapters)
|
||||||
|
self.platforms = list(self.adapters.keys())
|
||||||
|
self.config = config or {}
|
||||||
|
self.poll_interval = float(poll_interval)
|
||||||
|
#: Per-platform outbound queue; the adapter drains its own.
|
||||||
|
self.outbound: "dict[str, queue.Queue[OutboundMessage | None]]" = {
|
||||||
|
platform: queue.Queue() for platform in self.platforms
|
||||||
|
}
|
||||||
|
self._platform_cfg: dict[str, dict] = {
|
||||||
|
platform: self._config_for(platform) for platform in self.platforms
|
||||||
|
}
|
||||||
|
#: Optional LLM result cleanup (gateway-only presentation). Built from
|
||||||
|
#: the scheduler's `llm` client unless one is injected; a no-op unless
|
||||||
|
#: `gateway.humanize.enabled` (or a per-platform override) turns it on.
|
||||||
|
if humanizer is not None:
|
||||||
|
self.humanizer = humanizer
|
||||||
|
self._humanize_default = bool(humanizer.enabled)
|
||||||
|
else:
|
||||||
|
humanize_cfg = self.config.get("humanize")
|
||||||
|
humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {}
|
||||||
|
self._humanize_default = bool(humanize_cfg.get("enabled", False))
|
||||||
|
self.humanizer = self._build_humanizer(humanize_cfg)
|
||||||
|
#: Let an adapter that needs it gate input on the scheduler being free
|
||||||
|
#: (the voice gateway holds the wake word until the current request
|
||||||
|
#: reaches a result). Generic hook; only some adapters implement it.
|
||||||
|
for adapter in self.adapters.values():
|
||||||
|
setter = getattr(adapter, "set_input_ready", None)
|
||||||
|
if callable(setter):
|
||||||
|
setter(self.input_ready)
|
||||||
|
#: Tell the scheduler's speech channel which sources this service can
|
||||||
|
#: stream a read-aloud to, so a skill asks before it posts one.
|
||||||
|
speech = getattr(self.scheduler, "speech", None)
|
||||||
|
if speech is not None:
|
||||||
|
setter = getattr(speech, "set_stream_check", None)
|
||||||
|
if callable(setter):
|
||||||
|
setter(self.stream_ready)
|
||||||
|
self._owners: dict[str, Target] = {}
|
||||||
|
self._parents: dict[str, str] = {}
|
||||||
|
self._pending_owner: Target | None = None
|
||||||
|
self._question_for_chat: dict[Target, str] = {}
|
||||||
|
self._repair_for_chat: dict[Target, str] = {}
|
||||||
|
self._approval_for_chat: dict[Target, str] = {}
|
||||||
|
self._surfaced: set[str] = set()
|
||||||
|
self._route_lock = threading.Lock()
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
|
||||||
|
# ---- config ----
|
||||||
|
|
||||||
|
def _config_for(self, platform: str) -> dict:
|
||||||
|
"""Per-platform settings from a nested (`{platform: {...}}`) or, for a
|
||||||
|
single-adapter service, a flat config."""
|
||||||
|
nested = self.config.get(platform)
|
||||||
|
if isinstance(nested, dict):
|
||||||
|
return nested
|
||||||
|
if len(self.platforms) == 1:
|
||||||
|
return self.config
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def outbound_for(self, platform: str) -> "queue.Queue[OutboundMessage | None]":
|
||||||
|
return self.outbound[platform]
|
||||||
|
|
||||||
|
def _home_channel(self, platform: str) -> str:
|
||||||
|
return str(self._platform_cfg.get(platform, {}).get("home_channel", "") or "")
|
||||||
|
|
||||||
|
def _result_only(self, platform: str) -> bool:
|
||||||
|
"""Whether this platform speaks only the skill result line.
|
||||||
|
|
||||||
|
The adapter declares the default (the voice adapter sets `result_only`);
|
||||||
|
a per-platform config `result_only` overrides it either way.
|
||||||
|
"""
|
||||||
|
cfg = self._platform_cfg.get(platform, {})
|
||||||
|
if "result_only" in cfg:
|
||||||
|
return bool(cfg["result_only"])
|
||||||
|
return bool(getattr(self.adapters.get(platform), "result_only", False))
|
||||||
|
|
||||||
|
# ---- optional LLM result cleanup ----
|
||||||
|
|
||||||
|
def _build_humanizer(self, cfg: dict) -> Humanizer | None:
|
||||||
|
"""Build the result humanizer from config + the scheduler's `llm`.
|
||||||
|
|
||||||
|
Global defaults live in `gateway.humanize`; a per-platform
|
||||||
|
`gateway.<platform>.humanize` (bool or `{enabled, timeout, max_tokens,
|
||||||
|
max_chars}`) overrides the enable flag. Returns None when no `llm`
|
||||||
|
client is available, so a client-less scheduler degrades to no cleanup.
|
||||||
|
The instance is always built `enabled`; the global default is kept
|
||||||
|
separately so a per-platform override can turn it on or off.
|
||||||
|
"""
|
||||||
|
client = getattr(self.scheduler, "llm", None)
|
||||||
|
if client is None:
|
||||||
|
return None
|
||||||
|
return Humanizer(
|
||||||
|
client,
|
||||||
|
enabled=True,
|
||||||
|
timeout=float(cfg.get("timeout", 20.0)),
|
||||||
|
max_tokens=int(cfg.get("max_tokens", 200)),
|
||||||
|
max_chars=int(cfg.get("max_chars", 600)),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _humanize_enabled(self, platform: str, skill_ref: str | None = None) -> bool:
|
||||||
|
"""Whether this result is cleaned up.
|
||||||
|
|
||||||
|
Precedence: the **skill's own config** (`data/skills/<category>/<name>/
|
||||||
|
config.json` -> `{"humanize": bool}`) wins; otherwise the per-platform
|
||||||
|
override (`gateway.<platform>.humanize`), otherwise the global default
|
||||||
|
(`gateway.humanize.enabled`). A missing `llm` client disables it.
|
||||||
|
"""
|
||||||
|
if self.humanizer is None:
|
||||||
|
return False
|
||||||
|
skill_override = self._skill_humanize_override(skill_ref)
|
||||||
|
if skill_override is not None:
|
||||||
|
return skill_override
|
||||||
|
override = self._platform_cfg.get(platform, {}).get("humanize")
|
||||||
|
if isinstance(override, bool):
|
||||||
|
return override
|
||||||
|
if isinstance(override, dict) and "enabled" in override:
|
||||||
|
return bool(override["enabled"])
|
||||||
|
return self._humanize_default
|
||||||
|
|
||||||
|
def _skill_humanize_override(self, skill_ref: str | None) -> bool | None:
|
||||||
|
"""The skill's own `humanize` config value, or None when unset.
|
||||||
|
|
||||||
|
A skill opts in/out of result cleanup regardless of the platform default
|
||||||
|
via its recorded config: `data/skills/<category>/<name>/config.json` ->
|
||||||
|
`{"humanize": false}`. Read from the scheduler's skill store; a missing
|
||||||
|
store/config/key (or an unparseable ref) means no override.
|
||||||
|
"""
|
||||||
|
if not skill_ref or "." not in skill_ref:
|
||||||
|
return None
|
||||||
|
store = getattr(self.scheduler, "body_store", None)
|
||||||
|
if store is None:
|
||||||
|
return None
|
||||||
|
category, name = skill_ref.split(".", 1)
|
||||||
|
try:
|
||||||
|
config = store.read_config(category, name) or {}
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
if "humanize" in config:
|
||||||
|
return bool(config["humanize"])
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _fallback_target(self) -> Target | None:
|
||||||
|
for platform in self.platforms:
|
||||||
|
home = self._home_channel(platform)
|
||||||
|
if home:
|
||||||
|
return (platform, home)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Start the background queue-drain loop (codegen re-queues, etc.)."""
|
||||||
|
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
if self._thread is not None:
|
||||||
|
self._thread.join(timeout=2.0)
|
||||||
|
for platform in self.platforms:
|
||||||
|
self.outbound[platform].put(None)
|
||||||
|
|
||||||
|
def _poll_loop(self) -> None:
|
||||||
|
while not self._stop.wait(self.poll_interval):
|
||||||
|
try:
|
||||||
|
with self._route_lock:
|
||||||
|
self.drain()
|
||||||
|
self.surface()
|
||||||
|
except Exception:
|
||||||
|
self.scheduler.trace.append("gateway_error", "?", phase="poll")
|
||||||
|
|
||||||
|
# ---- routing ----
|
||||||
|
|
||||||
|
def source_for(self, platform: str, chat_id: str) -> str:
|
||||||
|
return f"{platform}:{chat_id}"
|
||||||
|
|
||||||
|
def _owner_from_source(self, source: str) -> Target | None:
|
||||||
|
for platform in self.platforms:
|
||||||
|
prefix = f"{platform}:"
|
||||||
|
if source.startswith(prefix):
|
||||||
|
return (platform, source[len(prefix):])
|
||||||
|
return None
|
||||||
|
|
||||||
|
def input_ready(self) -> bool:
|
||||||
|
"""Whether a new command may start now.
|
||||||
|
|
||||||
|
False while the single scheduler slot is executing a run; True when the
|
||||||
|
scheduler is idle or paused for the user's answer to a question (the run
|
||||||
|
is not running, so the answer must be accepted). The voice gateway uses
|
||||||
|
this to hold the wake word until the current request has reached a
|
||||||
|
result. Reads the scheduler's flags without its lock on purpose — the
|
||||||
|
lock is held for the whole run, so acquiring it here would block the
|
||||||
|
audio loop for the duration of the run.
|
||||||
|
"""
|
||||||
|
scheduler = self.scheduler
|
||||||
|
if getattr(scheduler, "pending", None) is not None:
|
||||||
|
return True
|
||||||
|
return getattr(scheduler, "current", None) is None
|
||||||
|
|
||||||
|
def stream_ready(self, source: str) -> bool:
|
||||||
|
"""Whether this service can stream a read-aloud to `source`.
|
||||||
|
|
||||||
|
The owning platform's adapter decides: the voice gateway always can
|
||||||
|
(when `read.enabled`); the LXMF adapter only for a chat that last
|
||||||
|
messaged by voice (a text chat keeps the saved-file summary). A source
|
||||||
|
with no known owner is not streamed.
|
||||||
|
"""
|
||||||
|
target = self._owner_from_source(source)
|
||||||
|
if target is None:
|
||||||
|
return False
|
||||||
|
platform, chat = target
|
||||||
|
adapter = self.adapters.get(platform)
|
||||||
|
if adapter is None:
|
||||||
|
return False
|
||||||
|
check = getattr(adapter, "speech_stream_ready", None)
|
||||||
|
if callable(check):
|
||||||
|
try:
|
||||||
|
return bool(check(chat))
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return bool(getattr(adapter, "supports_speech_stream", False))
|
||||||
|
|
||||||
|
def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None:
|
||||||
|
"""Handle one authorized inbound command. Called by the adapter."""
|
||||||
|
if platform is None:
|
||||||
|
platform = self.platforms[0] if self.platforms else ""
|
||||||
|
with self._route_lock:
|
||||||
|
reply_to: Target = (platform, msg.chat_id)
|
||||||
|
#: A single command-vocabulary key for this reply (punctuation- and
|
||||||
|
#: case-insensitive), so a spoken "Approve." / "Yes." matches the
|
||||||
|
#: approval and repair maps exactly like a typed "yes".
|
||||||
|
action = _normalize_action(msg.text)
|
||||||
|
pending = self.scheduler.pending
|
||||||
|
if pending is not None and self._pending_owner is None:
|
||||||
|
self._pending_owner = self._owner_from_source(pending.request.source)
|
||||||
|
if pending is not None and pending.request.source == self.source_for(
|
||||||
|
platform, msg.chat_id
|
||||||
|
):
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
elif pending is not None and self._pending_owner not in (None, reply_to):
|
||||||
|
self._reply(
|
||||||
|
*reply_to,
|
||||||
|
"I'm waiting for a reply in another conversation; please resend in a moment.",
|
||||||
|
kind="notice",
|
||||||
|
)
|
||||||
|
elif reply_to in self._question_for_chat:
|
||||||
|
question_id = self._question_for_chat.pop(reply_to)
|
||||||
|
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 action in _REPAIR_ACTIONS:
|
||||||
|
offer_id = self._repair_for_chat.pop(reply_to)
|
||||||
|
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 action in _APPROVAL_ACTIONS:
|
||||||
|
approval_id = self._approval_for_chat.pop(reply_to)
|
||||||
|
approved = _APPROVAL_ACTIONS[action]
|
||||||
|
status, detail = self.scheduler.answer_approval(approval_id, approved)
|
||||||
|
self._surfaced.add(approval_id)
|
||||||
|
self._reply(*reply_to, detail, kind="notice")
|
||||||
|
else:
|
||||||
|
reply = self.scheduler.submit_request(
|
||||||
|
msg.text, source=self.source_for(platform, msg.chat_id)
|
||||||
|
)
|
||||||
|
if reply.run_id:
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
self.drain()
|
||||||
|
self.surface(origin=reply_to)
|
||||||
|
|
||||||
|
def drain(self) -> None:
|
||||||
|
"""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
|
||||||
|
target = owner or self._fallback_target()
|
||||||
|
if target:
|
||||||
|
self._reply(
|
||||||
|
*target, reply.text, kind=_reply_kind(reply.status),
|
||||||
|
skill_ref=reply.skill_ref, result=reply.result,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _hidden(self, reply) -> bool:
|
||||||
|
"""Hide an intermediate chain step at `result` verbosity.
|
||||||
|
|
||||||
|
The default end-user view is just the final answer; a chained request's
|
||||||
|
intermediate "continue" steps are only surfaced at `query`/`decision`
|
||||||
|
verbosity.
|
||||||
|
"""
|
||||||
|
if not getattr(reply, "intermediate", False):
|
||||||
|
return False
|
||||||
|
return getattr(self.scheduler, "verbosity", "result") == "result"
|
||||||
|
|
||||||
|
def surface(self, origin: Target | None = None) -> None:
|
||||||
|
"""Send any newly posted authoring questions / repair offers."""
|
||||||
|
questions = self.scheduler.pending_questions()
|
||||||
|
live_ids = {q["id"] for q in questions}
|
||||||
|
self._question_for_chat = {
|
||||||
|
chat: qid for chat, qid in self._question_for_chat.items() if qid in live_ids
|
||||||
|
}
|
||||||
|
for item in questions:
|
||||||
|
if item["id"] in self._surfaced:
|
||||||
|
continue
|
||||||
|
self._surfaced.add(item["id"])
|
||||||
|
target = self._resolve_target(item.get("run_id"), origin)
|
||||||
|
if target:
|
||||||
|
self._question_for_chat[target] = item["id"]
|
||||||
|
self._reply(
|
||||||
|
*target,
|
||||||
|
f"(authoring {item['category']}.{item['skill']}) {item['question']}",
|
||||||
|
kind="question",
|
||||||
|
)
|
||||||
|
|
||||||
|
repairs = self.scheduler.pending_repairs()
|
||||||
|
live_ids = {r["id"] for r in repairs}
|
||||||
|
self._repair_for_chat = {
|
||||||
|
chat: rid for chat, rid in self._repair_for_chat.items() if rid in live_ids
|
||||||
|
}
|
||||||
|
for offer in repairs:
|
||||||
|
if offer["id"] in self._surfaced:
|
||||||
|
continue
|
||||||
|
self._surfaced.add(offer["id"])
|
||||||
|
target = self._resolve_target(offer.get("run_id"), origin)
|
||||||
|
if target:
|
||||||
|
self._repair_for_chat[target] = offer["id"]
|
||||||
|
self._reply(
|
||||||
|
*target,
|
||||||
|
(
|
||||||
|
f"{offer['category']}.{offer['skill']} failed: "
|
||||||
|
f"{offer['failure'][:200]}\nReply retry / repair / ask / no."
|
||||||
|
),
|
||||||
|
kind="notice",
|
||||||
|
)
|
||||||
|
|
||||||
|
approvals = self.scheduler.pending_approvals()
|
||||||
|
live_ids = {a["id"] for a in approvals}
|
||||||
|
self._approval_for_chat = {
|
||||||
|
chat: aid for chat, aid in self._approval_for_chat.items() if aid in live_ids
|
||||||
|
}
|
||||||
|
for item in approvals:
|
||||||
|
if item["id"] in self._surfaced:
|
||||||
|
continue
|
||||||
|
self._surfaced.add(item["id"])
|
||||||
|
target = self._resolve_target(item.get("run_id"), origin)
|
||||||
|
if target:
|
||||||
|
self._approval_for_chat[target] = item["id"]
|
||||||
|
label = (
|
||||||
|
item["category"]
|
||||||
|
if item["kind"] == "category"
|
||||||
|
else f"{item['category']}.{item['skill']}"
|
||||||
|
)
|
||||||
|
self._reply(
|
||||||
|
*target,
|
||||||
|
(
|
||||||
|
f"Approve creating new {item['kind']} {label}: "
|
||||||
|
f"{item['description']}\nReply yes / no."
|
||||||
|
),
|
||||||
|
kind="notice",
|
||||||
|
)
|
||||||
|
|
||||||
|
for fired in self.scheduler.timers.drain():
|
||||||
|
target = self._resolve_target(fired.run_id, origin)
|
||||||
|
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:
|
||||||
|
"""Copy run ownership across a scheduler requeue. Must not lock."""
|
||||||
|
owner = self._owners.get(parent_id)
|
||||||
|
if owner:
|
||||||
|
self._owners[child_id] = owner
|
||||||
|
self._parents[child_id] = parent_id
|
||||||
|
|
||||||
|
def _owner_of(self, run_id: str) -> Target | None:
|
||||||
|
seen = 0
|
||||||
|
while run_id and seen < 16:
|
||||||
|
owner = self._owners.get(run_id)
|
||||||
|
if owner:
|
||||||
|
return owner
|
||||||
|
run_id = self._parents.get(run_id)
|
||||||
|
seen += 1
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _resolve_target(self, run_id: str | None, origin: Target | None) -> Target | None:
|
||||||
|
owner = self._owner_of(run_id or "")
|
||||||
|
if owner:
|
||||||
|
return owner
|
||||||
|
if origin:
|
||||||
|
return origin
|
||||||
|
return self._fallback_target()
|
||||||
|
|
||||||
|
# ---- outbound ----
|
||||||
|
|
||||||
|
def _trace(self, kind: str, **fields) -> None:
|
||||||
|
"""Best-effort trace (a test double's scheduler may have no trace log)."""
|
||||||
|
trace = getattr(self.scheduler, "trace", None)
|
||||||
|
if trace is not None:
|
||||||
|
trace.append(kind, "?", **fields)
|
||||||
|
|
||||||
|
def _reply(
|
||||||
|
self,
|
||||||
|
platform: str,
|
||||||
|
chat_id: str,
|
||||||
|
text: str,
|
||||||
|
kind: str = "reply",
|
||||||
|
skill_ref: str | None = None,
|
||||||
|
result: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
result_only = self._result_only(platform)
|
||||||
|
humanize = kind == "result" and self._humanize_enabled(platform, skill_ref)
|
||||||
|
if result_only:
|
||||||
|
# A spoken front end says the skill's result, not the scheduler's
|
||||||
|
# bookkeeping: drop queue/urgency chatter.
|
||||||
|
if kind == "status":
|
||||||
|
return
|
||||||
|
if kind == "result" and (result_only or humanize):
|
||||||
|
# The scheduler hands us the skill's own unwrapped detail; fall back
|
||||||
|
# to unwrapping `<skill>: <ok|failed> — <detail>` for raw-string
|
||||||
|
# callers.
|
||||||
|
text = result if result is not None else _result_detail(text)
|
||||||
|
if humanize:
|
||||||
|
started = time.time()
|
||||||
|
text = self.humanizer.humanize(text)
|
||||||
|
self._trace(
|
||||||
|
"humanize",
|
||||||
|
elapsed_s=round(time.time() - started, 3),
|
||||||
|
chars=len(text),
|
||||||
|
)
|
||||||
|
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
|
||||||
|
if prefix:
|
||||||
|
text = f"{prefix}{text}"
|
||||||
|
if not text:
|
||||||
|
return
|
||||||
|
target_queue = self.outbound.get(platform)
|
||||||
|
if target_queue is None:
|
||||||
|
return
|
||||||
|
self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text))
|
||||||
|
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
|
||||||
|
|
||||||
|
def _enqueue_stream(self, target: Target, read) -> None:
|
||||||
|
"""Queue a read-aloud stream for the platform that can stream it.
|
||||||
|
|
||||||
|
Only an adapter that declares `supports_speech_stream` (the voice
|
||||||
|
gateway) can speak a long-form stream; a platform that cannot is traced
|
||||||
|
and skipped rather than handed a message it would drop silently.
|
||||||
|
"""
|
||||||
|
platform, chat_id = target
|
||||||
|
adapter = self.adapters.get(platform)
|
||||||
|
if adapter is None or not getattr(adapter, "supports_speech_stream", False):
|
||||||
|
self._trace(
|
||||||
|
"gateway_stream_unsupported",
|
||||||
|
platform=platform,
|
||||||
|
key=getattr(read, "key", ""),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self._trace(
|
||||||
|
"gateway_stream_queued",
|
||||||
|
platform=platform,
|
||||||
|
key=getattr(read, "key", ""),
|
||||||
|
start=getattr(read, "start", 0),
|
||||||
|
)
|
||||||
|
self.outbound[platform].put(
|
||||||
|
OutboundMessage(chat_id=str(chat_id), text="", stream=read)
|
||||||
|
)
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""SimpleX command-gateway adapter.
|
||||||
|
|
||||||
|
The gateway is the agent's **command** surface: allowlisted contacts DM the bot
|
||||||
|
and their text is fed to the scheduler, whose reply is sent back. All the
|
||||||
|
messaging *UX* surface (invite links, reading a contact's messages, composing on
|
||||||
|
the user's behalf) lives in separate bridge services, never here — see
|
||||||
|
AGENTS.md "gateway isolation".
|
||||||
|
|
||||||
|
This adapter is the policy layer over the neutral `SimplexDaemon` transport in
|
||||||
|
`semif_agent.simplex_ws`: it applies the allowlist, batches rapid messages, and
|
||||||
|
hands authorized text to the scheduler. It must not grow address/inbox/send
|
||||||
|
endpoints; those belong to a bridge.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from semif_agent.simplex_ws import SimplexDaemon, send_text_command
|
||||||
|
|
||||||
|
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||||
|
|
||||||
|
|
||||||
|
class SimplexAdapter(GatewayAdapter):
|
||||||
|
name = "simplex"
|
||||||
|
|
||||||
|
def __init__(self, cfg: dict | None = None, trace=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))
|
||||||
|
self.batch_delay = float(cfg.get("text_batch_delay", 0.8))
|
||||||
|
self.daemon = SimplexDaemon(
|
||||||
|
cfg.get("ws_url", "ws://127.0.0.1:5225"),
|
||||||
|
user_id=int(cfg.get("user_id", 1)),
|
||||||
|
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||||
|
reconnect=cfg.get("reconnect", {}) or {},
|
||||||
|
trace=trace,
|
||||||
|
name=self.name,
|
||||||
|
)
|
||||||
|
self.ws_url = self.daemon.ws_url
|
||||||
|
self._buffers: dict[str, str] = {}
|
||||||
|
self._buffered: dict[str, InboundMessage] = {}
|
||||||
|
self._flush_tasks: dict[str, asyncio.Task] = {}
|
||||||
|
self._on_inbound = None
|
||||||
|
|
||||||
|
# ---- requirements ----
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
return self.daemon.check_requirements()
|
||||||
|
|
||||||
|
# ---- authorization ----
|
||||||
|
|
||||||
|
def is_authorized(self, contact_id: str, display_name: str | None) -> bool:
|
||||||
|
if self.allow_all_users:
|
||||||
|
return True
|
||||||
|
candidates = {contact_id}
|
||||||
|
if display_name:
|
||||||
|
candidates.add(display_name)
|
||||||
|
if not self.allowed_users:
|
||||||
|
return False
|
||||||
|
return any(user in candidates for user in self.allowed_users)
|
||||||
|
|
||||||
|
# ---- transport ----
|
||||||
|
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
on_inbound,
|
||||||
|
outbound: "queue.Queue[OutboundMessage | None]",
|
||||||
|
) -> None:
|
||||||
|
self._on_inbound = on_inbound
|
||||||
|
|
||||||
|
def _pump() -> None:
|
||||||
|
# Translate the service's OutboundMessage queue onto the daemon's
|
||||||
|
# (chat_id, text) queue without letting scheduler work touch the
|
||||||
|
# daemon's event loop.
|
||||||
|
while True:
|
||||||
|
message = outbound.get()
|
||||||
|
if message is None:
|
||||||
|
self.daemon.enqueue(None)
|
||||||
|
return
|
||||||
|
self.daemon.enqueue(message.chat_id, message.text)
|
||||||
|
|
||||||
|
threading.Thread(target=_pump, name="simplex-outbound-pump", daemon=True).start()
|
||||||
|
self.daemon.run(self._on_item)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.daemon.close()
|
||||||
|
|
||||||
|
def send_command(self, chat_id: str, text: str) -> str:
|
||||||
|
return send_text_command(chat_id, text)
|
||||||
|
|
||||||
|
# ---- inbound ----
|
||||||
|
|
||||||
|
def _on_item(self, message: dict) -> None:
|
||||||
|
contact_id = str(message.get("contact_id") or "")
|
||||||
|
display_name = message.get("display_name")
|
||||||
|
if not self.is_authorized(contact_id, display_name):
|
||||||
|
self.daemon._event(
|
||||||
|
"gateway_denied", contact_id=contact_id, display_name=display_name
|
||||||
|
)
|
||||||
|
return
|
||||||
|
inbound = InboundMessage(
|
||||||
|
text=message.get("text") or "",
|
||||||
|
chat_id=contact_id,
|
||||||
|
chat_type="dm",
|
||||||
|
contact_id=contact_id,
|
||||||
|
display_name=display_name,
|
||||||
|
raw=message.get("raw") or {},
|
||||||
|
)
|
||||||
|
self._schedule_flush(inbound, self._on_inbound)
|
||||||
|
|
||||||
|
def _schedule_flush(self, message: InboundMessage, on_inbound) -> None:
|
||||||
|
chat = message.chat_id
|
||||||
|
existing = self._buffers.get(chat)
|
||||||
|
self._buffers[chat] = f"{existing}\n{message.text}" if existing else message.text
|
||||||
|
self._buffered[chat] = message
|
||||||
|
task = self._flush_tasks.get(chat)
|
||||||
|
if task is not None:
|
||||||
|
task.cancel()
|
||||||
|
self._flush_tasks[chat] = asyncio.ensure_future(self._flush(chat, on_inbound))
|
||||||
|
|
||||||
|
async def _flush(self, chat: str, on_inbound) -> None:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(self.batch_delay)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
return
|
||||||
|
text = self._buffers.pop(chat, "")
|
||||||
|
message = self._buffered.pop(chat, None)
|
||||||
|
self._flush_tasks.pop(chat, None)
|
||||||
|
if message is None or not text:
|
||||||
|
return
|
||||||
|
message.text = text
|
||||||
|
self.daemon._event(
|
||||||
|
"gateway_message",
|
||||||
|
contact_id=message.contact_id,
|
||||||
|
display_name=message.display_name,
|
||||||
|
chars=len(text),
|
||||||
|
)
|
||||||
|
await asyncio.to_thread(on_inbound, message)
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
"""Voice command-gateway adapter.
|
||||||
|
|
||||||
|
The gateway is the agent's **command** surface. This adapter is the policy layer
|
||||||
|
over the neutral `VoiceDaemon` transport in `semif_agent.voice_transport`: it
|
||||||
|
listens on the local microphone, applies the wake word + VAD endpointing +
|
||||||
|
speech-to-text, and hands the transcribed command to the scheduler; the reply is
|
||||||
|
spoken back through text-to-speech. All the routing — gate/score/queue/dispatch,
|
||||||
|
`needs_input` questions, repairs, approvals — lives in `GatewayService`, exactly
|
||||||
|
as for the SimpleX and LXMF adapters.
|
||||||
|
|
||||||
|
Unlike a messenger transport there is no remote peer and no allowlist: the
|
||||||
|
microphone is local, so physical access is the authorization. A single
|
||||||
|
configured `chat_id` identifies the session, and `home_channel` defaults to it
|
||||||
|
so background notifications (timers, repair offers) are spoken too.
|
||||||
|
|
||||||
|
Gateway isolation still holds: this adapter takes commands and speaks replies,
|
||||||
|
nothing else. It never records, stores, or exposes audio; transcription is
|
||||||
|
transient and the only artifact is the same text a typed command would carry.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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, 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):
|
||||||
|
name = "voice"
|
||||||
|
#: Speak the skill's result line only — the spoken front end should not read
|
||||||
|
#: out queue/urgency bookkeeping or the `<skill>: ok —` wrapper. Override
|
||||||
|
#: with `gateway.voice.result_only: false` for the full scheduler output.
|
||||||
|
result_only = True
|
||||||
|
|
||||||
|
def __init__(self, cfg: dict | None = None, trace=None):
|
||||||
|
cfg = cfg or {}
|
||||||
|
self.chat_id = str(cfg.get("chat_id", "voice") or "voice")
|
||||||
|
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(
|
||||||
|
self,
|
||||||
|
on_inbound,
|
||||||
|
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. 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),
|
||||||
|
)
|
||||||
|
self._inbound.put(
|
||||||
|
InboundMessage(
|
||||||
|
text=text,
|
||||||
|
chat_id=self.chat_id,
|
||||||
|
chat_type="dm",
|
||||||
|
contact_id=self.chat_id,
|
||||||
|
display_name=self.display_name,
|
||||||
|
raw={"barge_in": True} if barge_in else {},
|
||||||
|
)
|
||||||
|
)
|
||||||
+97
-65
@@ -1,80 +1,98 @@
|
|||||||
"""Self-assessment LLM client.
|
"""OpenAI-compatible provider for skill title + description authoring.
|
||||||
|
|
||||||
Talks to a local OpenAI-compatible server (e.g. ollama, llama.cpp server) for
|
New categories and skills are named by a small, local OpenAI-compatible model
|
||||||
the observe -> assess phase of the skill loop. Real, not mocked; the endpoint
|
on the `llm` endpoint, deliberately separate from the larger `codegen` model
|
||||||
must be reachable. Uses only the stdlib HTTP client so the core stays
|
that writes runnable bodies. It uses the same provider machinery as
|
||||||
dependency-free.
|
`CodegenClient` (`provider.OpenAICompatClient`): stdlib-only HTTP, a real SSE
|
||||||
|
stream, a token budget, and an idle watchdog — just with its own endpoint,
|
||||||
|
model, sampler parameters, and error type. `_parse_json` is also borrowed by
|
||||||
|
the authoring parsers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
from .provider import OpenAICompatClient, ProviderError, SemIfEngineClient
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
class LLMError(ProviderError):
|
||||||
class Assessment:
|
"""The configured `llm` endpoint could not be reached or stalled."""
|
||||||
success: bool
|
|
||||||
summary: str
|
|
||||||
updated_request: str | None = None
|
|
||||||
extra: dict[str, Any] = field(default_factory=dict)
|
|
||||||
|
|
||||||
|
|
||||||
class LLMClient:
|
class LLMClient(OpenAICompatClient):
|
||||||
def __init__(self, base_url: str, model: str, timeout: float = 120.0):
|
"""Small-model author of skill/category titles + descriptions.
|
||||||
self.base_url = base_url.rstrip("/")
|
|
||||||
self.model = model
|
|
||||||
self.timeout = timeout
|
|
||||||
|
|
||||||
def _chat(self, messages: list[dict], temperature: float = 0.0) -> str:
|
Short JSON replies, so the timeout is modest and generation is single-shot.
|
||||||
url = f"{self.base_url}/chat/completions"
|
No sampler parameters are sent unless the `llm` block in `config.json` sets
|
||||||
body = json.dumps(
|
them: an unset `temperature`/`top_p`/`presence_penalty`/`frequency_penalty`
|
||||||
{"model": self.model, "messages": messages, "temperature": temperature}
|
is omitted so the server's model default applies. Every value is overridable
|
||||||
).encode("utf-8")
|
from config.
|
||||||
request = urllib.request.Request(
|
|
||||||
url, data=body, headers={"Content-Type": "application/json"}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
||||||
payload = json.loads(response.read().decode("utf-8"))
|
|
||||||
except urllib.error.URLError as exc:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"LLM endpoint unreachable at {url}: {exc}. Is your local server running?"
|
|
||||||
) from exc
|
|
||||||
return payload["choices"][0]["message"]["content"]
|
|
||||||
|
|
||||||
def assess(self, skill: str, request_text: str, action_log: str) -> Assessment:
|
`disable_thinking` defaults **on**: the small local model is often a
|
||||||
system = (
|
reasoning model whose hidden chain-of-thought consumes
|
||||||
"You are the self-assessment step of an agent skill run. Decide whether "
|
the short reply budget and leaves `content` empty — the same cap problem
|
||||||
"the skill achieved its goal. Reply with JSON only: "
|
codegen documents, but here the reply is a ~30-token JSON object, so the
|
||||||
'{"success": true|false, "summary": "<brief>", "updated_request": '
|
thinking is pure overhead. Set `llm.disable_thinking: false` for a
|
||||||
'"<requeued request text or null>"}. success is true only if the goal was met.'
|
non-reasoning endpoint that rejects the parameter.
|
||||||
)
|
"""
|
||||||
user = (
|
|
||||||
f"Skill: {skill}\n"
|
error_class = LLMError
|
||||||
f"Goal request: {request_text}\n"
|
degeneration_error_class = LLMError
|
||||||
f"What was done:\n{action_log}\n"
|
label = "llm"
|
||||||
)
|
|
||||||
try:
|
def __init__(
|
||||||
raw = self._chat(
|
self,
|
||||||
[
|
base_url: str,
|
||||||
{"role": "system", "content": system},
|
model: str,
|
||||||
{"role": "user", "content": user},
|
timeout: float = 600.0,
|
||||||
]
|
stream: bool = False,
|
||||||
)
|
idle_warn: float = 30.0,
|
||||||
parsed = self._parse_json(raw)
|
idle_timeout: float = 120.0,
|
||||||
except Exception as exc:
|
context_window: float = 0.0,
|
||||||
return Assessment(success=False, summary=f"assessment failed: {exc}")
|
smart_limit: int = 250000,
|
||||||
success = bool(parsed.get("success"))
|
warn_limit: int = 500000,
|
||||||
summary = str(parsed.get("summary", ""))
|
max_fill_ratio: float = 0.9,
|
||||||
updated = parsed.get("updated_request")
|
warn_fill_ratio: float = 0.7,
|
||||||
return Assessment(
|
max_output: float = 0.85,
|
||||||
success=success,
|
chars_per_token: float = 4.0,
|
||||||
summary=summary,
|
degeneration_interval: int = 8000,
|
||||||
updated_request=None if updated is None else str(updated),
|
degeneration_window: int = 2000,
|
||||||
|
degeneration_min_chars: int = 4000,
|
||||||
|
temperature: float | None = None,
|
||||||
|
top_p: float | None = None,
|
||||||
|
presence_penalty: float | None = None,
|
||||||
|
frequency_penalty: float | None = None,
|
||||||
|
disable_thinking: bool = True,
|
||||||
|
api_key: str = "",
|
||||||
|
extra_headers: dict[str, str] | None = None,
|
||||||
|
user_agent: str | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
base_url=base_url,
|
||||||
|
model=model,
|
||||||
|
timeout=timeout,
|
||||||
|
stream=stream,
|
||||||
|
idle_warn=idle_warn,
|
||||||
|
idle_timeout=idle_timeout,
|
||||||
|
context_window=context_window,
|
||||||
|
smart_limit=smart_limit,
|
||||||
|
warn_limit=warn_limit,
|
||||||
|
max_fill_ratio=max_fill_ratio,
|
||||||
|
warn_fill_ratio=warn_fill_ratio,
|
||||||
|
max_output=max_output,
|
||||||
|
chars_per_token=chars_per_token,
|
||||||
|
degeneration_interval=degeneration_interval,
|
||||||
|
degeneration_window=degeneration_window,
|
||||||
|
degeneration_min_chars=degeneration_min_chars,
|
||||||
|
temperature=temperature,
|
||||||
|
top_p=top_p,
|
||||||
|
presence_penalty=presence_penalty,
|
||||||
|
frequency_penalty=frequency_penalty,
|
||||||
|
disable_thinking=disable_thinking,
|
||||||
|
api_key=api_key,
|
||||||
|
extra_headers=extra_headers,
|
||||||
|
user_agent=user_agent,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -84,3 +102,17 @@ class LLMClient:
|
|||||||
if start != -1 and end != -1:
|
if start != -1 and end != -1:
|
||||||
text = text[start : end + 1]
|
text = text[start : end + 1]
|
||||||
return json.loads(text)
|
return json.loads(text)
|
||||||
|
|
||||||
|
|
||||||
|
class SemIfLLMClient(SemIfEngineClient):
|
||||||
|
"""`llm` authoring backed by the loaded SemIf engine model.
|
||||||
|
|
||||||
|
The `llm.provider = "semif"` option: the same in-process GGUF the decision
|
||||||
|
engine already loaded generates the title/description (and any other `llm`
|
||||||
|
text) instead of calling an HTTP endpoint. Same `chat(...)` surface, same
|
||||||
|
graceful error contract — raises `LLMError` so the scheduler traces a
|
||||||
|
`draft_failed` and the LLM bridge reports 502 rather than crashing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_class = LLMError
|
||||||
|
label = "semif:llm"
|
||||||
@@ -42,6 +42,14 @@ class DecisionLog:
|
|||||||
}
|
}
|
||||||
if extra:
|
if extra:
|
||||||
row["extra"] = extra
|
row["extra"] = extra
|
||||||
|
result_extra = getattr(result, "extra", None) or {}
|
||||||
|
timing = {
|
||||||
|
key: result_extra[key]
|
||||||
|
for key in ("input_tokens", "forward_seconds", "total_seconds")
|
||||||
|
if key in result_extra
|
||||||
|
}
|
||||||
|
if timing:
|
||||||
|
row.setdefault("extra", {})["timing"] = timing
|
||||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with self.path.open("a") as handle:
|
with self.path.open("a") as handle:
|
||||||
handle.write(json.dumps(row) + "\n")
|
handle.write(json.dumps(row) + "\n")
|
||||||
|
|||||||
@@ -0,0 +1,572 @@
|
|||||||
|
"""Low-level LXMF (Reticulum) transport (neutral).
|
||||||
|
|
||||||
|
This module owns the LXMF/Reticulum mechanics only: standing up a Reticulum
|
||||||
|
instance and an `LXMRouter`, loading (or creating) the delivery identity,
|
||||||
|
announcing reachability, normalizing inbound messages into plain dicts, and
|
||||||
|
draining an outbound send queue. It knows nothing about the SemIf scheduler,
|
||||||
|
the command gateway, or any bridge — a front end builds on top of it.
|
||||||
|
|
||||||
|
`RNS` and `LXMF` are imported lazily inside the methods that need them so
|
||||||
|
importing this module stays stdlib-only on a machine without the optional
|
||||||
|
`lxmf` dependency (the gateway refuses to start with an install hint instead).
|
||||||
|
|
||||||
|
Unlike the SimpleX transport there is no external daemon binary: Reticulum and
|
||||||
|
the LXMF router run in-process. The bot's reachable address is its LXMF
|
||||||
|
delivery destination hash (32 hex chars); the identity is persisted under the
|
||||||
|
router storage path so the address is stable across restarts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
#: One received direct message, normalized into a plain dict.
|
||||||
|
InboundDict = dict[str, Any]
|
||||||
|
#: Callback invoked for each received message.
|
||||||
|
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."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, bytes):
|
||||||
|
return value.decode("utf-8", "replace")
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_message(message: Any) -> InboundDict:
|
||||||
|
"""Normalize one LXMF message object into a plain dict.
|
||||||
|
|
||||||
|
Tolerates both a real `LXMessage` (bytes `content`/`title`, `source_hash`,
|
||||||
|
`get_source()`) and a lightweight fake, so the policy layer is testable
|
||||||
|
without the optional `lxmf` package installed.
|
||||||
|
"""
|
||||||
|
raw_source_hash = getattr(message, "source_hash", b"") or b""
|
||||||
|
if isinstance(raw_source_hash, (bytes, bytearray)):
|
||||||
|
source_hash = bytes(raw_source_hash).hex()
|
||||||
|
else:
|
||||||
|
source_hash = str(raw_source_hash)
|
||||||
|
|
||||||
|
content_fn = getattr(message, "content_as_string", None)
|
||||||
|
if callable(content_fn):
|
||||||
|
try:
|
||||||
|
content = _as_text(content_fn())
|
||||||
|
except Exception:
|
||||||
|
content = ""
|
||||||
|
else:
|
||||||
|
content = _as_text(getattr(message, "content", None))
|
||||||
|
|
||||||
|
title_fn = getattr(message, "title_as_string", None)
|
||||||
|
if callable(title_fn):
|
||||||
|
try:
|
||||||
|
title = _as_text(title_fn())
|
||||||
|
except Exception:
|
||||||
|
title = ""
|
||||||
|
else:
|
||||||
|
title = _as_text(getattr(message, "title", None))
|
||||||
|
|
||||||
|
display_name = ""
|
||||||
|
source = None
|
||||||
|
get_source = getattr(message, "get_source", None)
|
||||||
|
if callable(get_source):
|
||||||
|
try:
|
||||||
|
source = get_source()
|
||||||
|
except Exception:
|
||||||
|
source = None
|
||||||
|
if source is None:
|
||||||
|
source = getattr(message, "source", None)
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class LxmfDaemon:
|
||||||
|
"""One in-process Reticulum instance + LXMF router.
|
||||||
|
|
||||||
|
`run(on_message)` blocks, announcing the delivery destination periodically
|
||||||
|
— 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.
|
||||||
|
|
||||||
|
Beware: the identity is persisted under `storage_path`; a single profile
|
||||||
|
must not be shared by two processes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
config_dir: str,
|
||||||
|
storage_path: str,
|
||||||
|
display_name: str | None = "semif",
|
||||||
|
announce_interval: float = 3600.0,
|
||||||
|
stamp_cost: int | None = None,
|
||||||
|
desired_method: str = "direct",
|
||||||
|
propagation_node: str = "",
|
||||||
|
on_connected: ConnectedHandler | None = None,
|
||||||
|
trace=None,
|
||||||
|
name: str = "lxmf",
|
||||||
|
):
|
||||||
|
self.config_dir = str(config_dir)
|
||||||
|
self.storage_path = str(storage_path)
|
||||||
|
self.display_name = str(display_name) if display_name else None
|
||||||
|
self.announce_interval = float(announce_interval or 0.0)
|
||||||
|
self.stamp_cost = int(stamp_cost) if stamp_cost is not None else None
|
||||||
|
self.desired_method = str(desired_method or "direct").lower()
|
||||||
|
self.propagation_node = str(propagation_node or "")
|
||||||
|
self.on_connected = on_connected
|
||||||
|
self.trace = trace
|
||||||
|
self.name = name
|
||||||
|
self.identity_path = os.path.join(self.storage_path, "identity")
|
||||||
|
self._router = None
|
||||||
|
self._reticulum = None
|
||||||
|
self._destination = None
|
||||||
|
self._address = ""
|
||||||
|
#: 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 ----
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
if not self.config_dir:
|
||||||
|
return False, "lxmf config_dir is required"
|
||||||
|
try:
|
||||||
|
import RNS # noqa: F401
|
||||||
|
import LXMF # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
return False, "pip install lxmf"
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
@property
|
||||||
|
def address(self) -> str:
|
||||||
|
"""The bot's LXMF delivery address (32 hex chars), or "" before ready."""
|
||||||
|
return self._address
|
||||||
|
|
||||||
|
def ensure_reticulum(self):
|
||||||
|
"""Initialize the Reticulum instance on the calling thread.
|
||||||
|
|
||||||
|
Reticulum installs process signal handlers, which only works on the
|
||||||
|
main thread. Call this once from the main thread before spawning the
|
||||||
|
transport thread so the in-process router can coexist with other
|
||||||
|
gateway adapters; `run()` reuses the instance when it already exists.
|
||||||
|
"""
|
||||||
|
import RNS
|
||||||
|
|
||||||
|
existing = RNS.Reticulum.get_instance()
|
||||||
|
if existing is not None:
|
||||||
|
self._reticulum = existing
|
||||||
|
return existing
|
||||||
|
os.makedirs(self.config_dir, exist_ok=True)
|
||||||
|
self._reticulum = RNS.Reticulum(configdir=self.config_dir)
|
||||||
|
return self._reticulum
|
||||||
|
|
||||||
|
def prepare(self, on_message: MessageHandler | None = None):
|
||||||
|
"""Main-thread-sensitive setup: Reticulum instance + LXMF router.
|
||||||
|
|
||||||
|
Both `RNS.Reticulum` and `LXMF.LXMRouter` install process signal
|
||||||
|
handlers, which only works on the main thread. `run_gateway` calls this
|
||||||
|
once on the main thread before the transport threads start; `run()`
|
||||||
|
calls it again (idempotent) when used standalone.
|
||||||
|
"""
|
||||||
|
if self._router is not None:
|
||||||
|
if on_message is not None:
|
||||||
|
self._on_message = on_message
|
||||||
|
return self._router
|
||||||
|
import LXMF
|
||||||
|
import RNS
|
||||||
|
|
||||||
|
if on_message is not None:
|
||||||
|
self._on_message = on_message
|
||||||
|
os.makedirs(self.config_dir, exist_ok=True)
|
||||||
|
os.makedirs(self.storage_path, exist_ok=True)
|
||||||
|
|
||||||
|
self.ensure_reticulum()
|
||||||
|
self._router = LXMF.LXMRouter(storagepath=self.storage_path)
|
||||||
|
identity = self._load_identity(RNS)
|
||||||
|
self._destination = self._router.register_delivery_identity(
|
||||||
|
identity, display_name=self.display_name, stamp_cost=self.stamp_cost
|
||||||
|
)
|
||||||
|
if self._destination is None:
|
||||||
|
raise RuntimeError("could not register LXMF delivery identity")
|
||||||
|
self._address = RNS.hexrep(self._destination.hash, delimit=False)
|
||||||
|
self._router.register_delivery_callback(self._handle)
|
||||||
|
if self.propagation_node:
|
||||||
|
try:
|
||||||
|
self._router.set_outbound_propagation_node(
|
||||||
|
bytes.fromhex(self.propagation_node)
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
def run(self, on_message: MessageHandler) -> None:
|
||||||
|
self.prepare(on_message)
|
||||||
|
|
||||||
|
threading.Thread(
|
||||||
|
target=self._pump, name="lxmf-outbound-pump", daemon=True
|
||||||
|
).start()
|
||||||
|
self._announce("startup")
|
||||||
|
if self.on_connected is not None:
|
||||||
|
try:
|
||||||
|
self.on_connected()
|
||||||
|
except Exception as exc:
|
||||||
|
self._event(
|
||||||
|
"lxmf_error", phase="on_connected", message=str(exc)[:300]
|
||||||
|
)
|
||||||
|
|
||||||
|
self._announce_loop()
|
||||||
|
|
||||||
|
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, audio))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
self._outbound.put(None)
|
||||||
|
try:
|
||||||
|
import RNS
|
||||||
|
|
||||||
|
RNS.Reticulum.exit_handler()
|
||||||
|
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):
|
||||||
|
os.makedirs(self.storage_path, exist_ok=True)
|
||||||
|
if os.path.isfile(self.identity_path):
|
||||||
|
identity = RNS.Identity.from_file(self.identity_path)
|
||||||
|
if identity is not None:
|
||||||
|
return identity
|
||||||
|
identity = RNS.Identity()
|
||||||
|
try:
|
||||||
|
identity.to_file(self.identity_path)
|
||||||
|
os.chmod(self.identity_path, 0o600)
|
||||||
|
except Exception as exc:
|
||||||
|
self._event("lxmf_identity_save_failed", message=str(exc)[:300])
|
||||||
|
return identity
|
||||||
|
|
||||||
|
# ---- announce ----
|
||||||
|
|
||||||
|
def _announce_wait(self) -> float:
|
||||||
|
if self.announce_interval <= 0:
|
||||||
|
return 3600.0
|
||||||
|
return self.announce_interval
|
||||||
|
|
||||||
|
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._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])
|
||||||
|
|
||||||
|
# ---- inbound ----
|
||||||
|
|
||||||
|
def _handle(self, message: Any) -> None:
|
||||||
|
try:
|
||||||
|
normalized = normalize_message(message)
|
||||||
|
except Exception as exc:
|
||||||
|
self._event("lxmf_parse_error", message=str(exc)[:300])
|
||||||
|
return
|
||||||
|
self._event(
|
||||||
|
"lxmf_message",
|
||||||
|
source=normalized.get("source_hash"),
|
||||||
|
chars=len(normalized.get("content") or ""),
|
||||||
|
)
|
||||||
|
if self._on_message is not None:
|
||||||
|
self._on_message(normalized)
|
||||||
|
|
||||||
|
# ---- outbound ----
|
||||||
|
|
||||||
|
def _pump(self) -> None:
|
||||||
|
while True:
|
||||||
|
item = self._outbound.get()
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
chat_id, text, audio = item
|
||||||
|
try:
|
||||||
|
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,
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
if self._router is None or self._destination is None:
|
||||||
|
raise RuntimeError("LXMF router is not ready")
|
||||||
|
import LXMF
|
||||||
|
import RNS
|
||||||
|
|
||||||
|
try:
|
||||||
|
dest_hash = bytes.fromhex(str(destination_hex).strip())
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(f"invalid LXMF address {destination_hex!r}") from exc
|
||||||
|
|
||||||
|
if not RNS.Transport.has_path(dest_hash):
|
||||||
|
RNS.Transport.request_path(dest_hash)
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
while not RNS.Transport.has_path(dest_hash) and time.time() < deadline:
|
||||||
|
time.sleep(0.1)
|
||||||
|
identity = RNS.Identity.recall(dest_hash)
|
||||||
|
if identity is None:
|
||||||
|
raise RuntimeError(f"unknown LXMF destination {destination_hex}")
|
||||||
|
|
||||||
|
dest = RNS.Destination(
|
||||||
|
identity, RNS.Destination.OUT, RNS.Destination.SINGLE, "lxmf", "delivery"
|
||||||
|
)
|
||||||
|
method = (
|
||||||
|
LXMF.LXMessage.OPPORTUNISTIC
|
||||||
|
if self.desired_method == "opportunistic"
|
||||||
|
else LXMF.LXMessage.DIRECT
|
||||||
|
)
|
||||||
|
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), audio=bool(audio)
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- tracing ----
|
||||||
|
|
||||||
|
def _event(self, kind: str, **fields) -> None:
|
||||||
|
if self.trace is not None:
|
||||||
|
self.trace.append(kind, "?", **fields)
|
||||||
@@ -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,703 @@
|
|||||||
|
"""Shared OpenAI-compatible chat provider.
|
||||||
|
|
||||||
|
Both the small title/description author (`LLMClient` in `llm.py`) and the big
|
||||||
|
skill-body writer (`CodegenClient` in `codegen.py`) use the same transport
|
||||||
|
machinery: stdlib-only HTTP, a real SSE stream, a layered token budget, an idle
|
||||||
|
watchdog, and an optional SemIf degeneration hook. This module holds that
|
||||||
|
provider logic once; subclasses set `base_url`/`model`, their sampler
|
||||||
|
parameters, and the error classes they raise so existing callers keep catching
|
||||||
|
their own types.
|
||||||
|
|
||||||
|
It also holds `SemIfEngineClient`, the non-HTTP sibling that generates text
|
||||||
|
from the in-process SemIf engine model (`engine.SemIfEngine.generate`) behind
|
||||||
|
the same ``chat(...)`` surface, so the `llm` task can be served by the loaded
|
||||||
|
decision model instead of an HTTP endpoint.
|
||||||
|
|
||||||
|
Stdlib-only and imports nothing from the agent's own modules, so `codegen.py`
|
||||||
|
(which imports `skills.py`, which imports `llm.py`) can depend on it without a
|
||||||
|
cycle.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import select
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from typing import Callable, NamedTuple
|
||||||
|
|
||||||
|
DEFAULT_CONTEXT_WINDOW = 100000
|
||||||
|
|
||||||
|
|
||||||
|
class ProviderError(RuntimeError):
|
||||||
|
"""The configured OpenAI-compatible endpoint could not be reached."""
|
||||||
|
|
||||||
|
|
||||||
|
class TokenBudget(NamedTuple):
|
||||||
|
"""Per-request token limits derived from the detected context window.
|
||||||
|
|
||||||
|
`total_limit` caps prompt + output; `output_limit` caps just the streamed
|
||||||
|
output (the enforced one — it already bakes in the prompt estimate);
|
||||||
|
`warn_point` is the total fill at which a one-shot console warning fires.
|
||||||
|
An `output_limit` of 0 means no cap is configured.
|
||||||
|
"""
|
||||||
|
|
||||||
|
window: int
|
||||||
|
total_limit: int
|
||||||
|
output_limit: int
|
||||||
|
warn_point: int | None
|
||||||
|
prompt_est: int
|
||||||
|
|
||||||
|
|
||||||
|
class OpenAICompatClient:
|
||||||
|
"""OpenAI-compatible chat provider shared by the authoring clients.
|
||||||
|
|
||||||
|
Subclasses set `base_url`/`model` (and their sampler parameters) and the
|
||||||
|
error classes they raise: `error_class` for transport/parse/budget failures
|
||||||
|
and `degeneration_error_class` for a watchdog abort, so existing callers
|
||||||
|
keep catching their own types. `label` prefixes console diagnostics.
|
||||||
|
|
||||||
|
The transport always reads the response as an SSE token stream so the
|
||||||
|
layered token budget, the idle watchdog, and the total wall-clock budget
|
||||||
|
can abort a runaway generation in real time — never via a server-side
|
||||||
|
`max_tokens` cap, because Qwen3-style models reason first and a cap
|
||||||
|
truncates the hidden reasoning, leaving `content` empty.
|
||||||
|
|
||||||
|
`stream=True` additionally echoes tokens (including the chain-of-thought)
|
||||||
|
to stdout as they arrive; echo is console-only and the returned content
|
||||||
|
is identical either way. A silent stream (no bytes for `idle_warn`
|
||||||
|
seconds) prints a warning, and one that stays silent for `idle_timeout`
|
||||||
|
seconds raises CodegenError instead of blocking on the total timeout — a
|
||||||
|
wedged generation is surfaced in minutes, not ~20.
|
||||||
|
|
||||||
|
The context window is lazily queried once from ollama's `/api/show`
|
||||||
|
(`parameters.num_ctx`, falling back to `model_info.<arch>.context_length`,
|
||||||
|
then the `context_window` config, then 100000); the per-request budget
|
||||||
|
caps output at `max_output` (absolute tokens if >= 1, else a fraction of
|
||||||
|
the window) and total fill at `smart_limit`/`warn_limit`.
|
||||||
|
|
||||||
|
An optional `degeneration_check` callback (passed per `chat` call) is fed
|
||||||
|
the last `degeneration_window` chars of content+reasoning every
|
||||||
|
`degeneration_interval` chars once `degeneration_min_chars` have
|
||||||
|
accumulated; a non-None return aborts the stream with DegenerationError.
|
||||||
|
It lets a SemIf continue/stop decision cut off a generation that is
|
||||||
|
looping instead of converging, before it fills the context window.
|
||||||
|
|
||||||
|
Sampler parameters are **opt-in**: `temperature`/`top_p`/
|
||||||
|
`presence_penalty`/`frequency_penalty` default to `None` and a `None`
|
||||||
|
parameter is omitted from the request payload entirely, so the server's
|
||||||
|
model/Modelfile default applies. A caller that knows the right value for its
|
||||||
|
model sets it (constructor or per-`chat` override); this provider never
|
||||||
|
guesses a value on the user's behalf. `max_tokens` and `reasoning_effort`
|
||||||
|
work the same way: sent only when explicitly set.
|
||||||
|
|
||||||
|
`disable_thinking` sends `reasoning_effort: "none"` so a reasoning model
|
||||||
|
answers directly instead of spending the (short) reply budget on hidden
|
||||||
|
chain-of-thought. It is off by default because codegen *wants* the
|
||||||
|
reasoning; the `llm` title/description author turns it on. Ollama honors it
|
||||||
|
on the `/v1` compat endpoint (its native `think:false` is not plumbed
|
||||||
|
through `/v1`).
|
||||||
|
|
||||||
|
`api_key` (when set) is sent as `Authorization: Bearer <key>` on every
|
||||||
|
request — the OpenCode Console inference API and most hosted
|
||||||
|
OpenAI-compatible gateways require it. `extra_headers` are merged on top
|
||||||
|
(custom auth schemes, routing hints) and `user_agent` overrides the default
|
||||||
|
client string. `query_context` gates the ollama `/api/show` probe: a
|
||||||
|
hosted/non-ollama endpoint (see `console.OpenCodeConsoleClient`) sets it
|
||||||
|
False so no stray `/api/show` request is sent and the window comes from
|
||||||
|
`context_window`/the default.
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_class = ProviderError
|
||||||
|
degeneration_error_class = ProviderError
|
||||||
|
label = "provider"
|
||||||
|
query_context = True
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str,
|
||||||
|
model: str,
|
||||||
|
timeout: float = 1200.0,
|
||||||
|
stream: bool = False,
|
||||||
|
idle_warn: float = 60.0,
|
||||||
|
idle_timeout: float = 180.0,
|
||||||
|
context_window: float = 0.0,
|
||||||
|
smart_limit: int = 250000,
|
||||||
|
warn_limit: int = 500000,
|
||||||
|
max_fill_ratio: float = 0.9,
|
||||||
|
warn_fill_ratio: float = 0.7,
|
||||||
|
max_output: float = 0.85,
|
||||||
|
chars_per_token: float = 4.0,
|
||||||
|
degeneration_interval: int = 8000,
|
||||||
|
degeneration_window: int = 2000,
|
||||||
|
degeneration_min_chars: int = 4000,
|
||||||
|
temperature: float | None = None,
|
||||||
|
top_p: float | None = None,
|
||||||
|
presence_penalty: float | None = None,
|
||||||
|
frequency_penalty: float | None = None,
|
||||||
|
max_attempts: int = 3,
|
||||||
|
disable_thinking: bool = False,
|
||||||
|
api_key: str = "",
|
||||||
|
extra_headers: dict[str, str] | None = None,
|
||||||
|
user_agent: str | None = None,
|
||||||
|
):
|
||||||
|
self.base_url = base_url.rstrip("/")
|
||||||
|
self.model = model
|
||||||
|
self.timeout = timeout
|
||||||
|
self.stream = stream
|
||||||
|
self.idle_warn = idle_warn
|
||||||
|
self.idle_timeout = idle_timeout
|
||||||
|
self.context_window = context_window
|
||||||
|
self.smart_limit = smart_limit
|
||||||
|
self.warn_limit = warn_limit
|
||||||
|
self.max_fill_ratio = max_fill_ratio
|
||||||
|
self.warn_fill_ratio = warn_fill_ratio
|
||||||
|
self.max_output = max_output
|
||||||
|
self.chars_per_token = chars_per_token
|
||||||
|
self.degeneration_interval = degeneration_interval
|
||||||
|
self.degeneration_window = degeneration_window
|
||||||
|
self.degeneration_min_chars = degeneration_min_chars
|
||||||
|
self.temperature = temperature
|
||||||
|
self.top_p = top_p
|
||||||
|
self.presence_penalty = presence_penalty
|
||||||
|
self.frequency_penalty = frequency_penalty
|
||||||
|
self.max_attempts = max_attempts
|
||||||
|
self.disable_thinking = disable_thinking
|
||||||
|
self.api_key = api_key
|
||||||
|
self.extra_headers = dict(extra_headers or {})
|
||||||
|
self.user_agent = user_agent
|
||||||
|
self._window: int | None = None
|
||||||
|
|
||||||
|
def _headers(self) -> dict[str, str]:
|
||||||
|
"""Request headers: JSON content type plus optional auth/extra/UA.
|
||||||
|
|
||||||
|
A non-empty `api_key` becomes `Authorization: Bearer <key>` (required by
|
||||||
|
the OpenCode Console inference API and most hosted gateways);
|
||||||
|
`extra_headers` merge on top (last writer wins) and `user_agent`
|
||||||
|
overrides the library default. The ollama context probe uses the same
|
||||||
|
headers so an authenticated gateway never sees an unauthenticated
|
||||||
|
request.
|
||||||
|
"""
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if self.api_key:
|
||||||
|
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||||
|
if self.user_agent:
|
||||||
|
headers["User-Agent"] = self.user_agent
|
||||||
|
if self.extra_headers:
|
||||||
|
headers.update(self.extra_headers)
|
||||||
|
return headers
|
||||||
|
|
||||||
|
def chat(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
max_tokens: int | None = None,
|
||||||
|
temperature: float | None = None,
|
||||||
|
top_p: float | None = None,
|
||||||
|
presence_penalty: float | None = None,
|
||||||
|
frequency_penalty: float | None = None,
|
||||||
|
timeout: float | None = None,
|
||||||
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
) -> str:
|
||||||
|
# A per-call `timeout` overrides the constructor value for this request
|
||||||
|
# only (used by short auxiliary calls such as the gateway's result
|
||||||
|
# cleanup, which must not inherit the authoring client's long budget).
|
||||||
|
deadline = self.timeout if timeout is None else timeout
|
||||||
|
budget = self._compute_budget(messages)
|
||||||
|
if self.stream:
|
||||||
|
self._print_budget(budget)
|
||||||
|
url = f"{self.base_url}/chat/completions"
|
||||||
|
payload: dict = {
|
||||||
|
"model": self.model,
|
||||||
|
"messages": messages,
|
||||||
|
"stream": True,
|
||||||
|
"stream_options": {"include_usage": True},
|
||||||
|
}
|
||||||
|
# Sampler parameters are opt-in: a per-call override wins, otherwise the
|
||||||
|
# constructor value; a None value is omitted entirely so the server's
|
||||||
|
# model/Modelfile default applies.
|
||||||
|
sampler = {
|
||||||
|
"temperature": self.temperature if temperature is None else temperature,
|
||||||
|
"top_p": self.top_p if top_p is None else top_p,
|
||||||
|
"presence_penalty": (
|
||||||
|
self.presence_penalty if presence_penalty is None else presence_penalty
|
||||||
|
),
|
||||||
|
"frequency_penalty": (
|
||||||
|
self.frequency_penalty if frequency_penalty is None else frequency_penalty
|
||||||
|
),
|
||||||
|
}
|
||||||
|
payload.update({k: v for k, v in sampler.items() if v is not None})
|
||||||
|
if self.disable_thinking:
|
||||||
|
payload["reasoning_effort"] = "none"
|
||||||
|
if max_tokens is not None:
|
||||||
|
payload["max_tokens"] = max_tokens
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
request = urllib.request.Request(
|
||||||
|
url, data=body, headers=self._headers()
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=deadline) as response:
|
||||||
|
return self._read_stream(
|
||||||
|
response, budget, degeneration_check, timeout=deadline
|
||||||
|
)
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} endpoint unreachable at {url}: {exc}. Is your local server running?"
|
||||||
|
) from exc
|
||||||
|
except TimeoutError as exc:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} request timed out after {deadline:.0f}s at {url}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
def _native_base_url(self) -> str:
|
||||||
|
"""Ollama's `/api/show` lives on the native API, not the /v1 compat."""
|
||||||
|
if self.base_url.endswith("/v1"):
|
||||||
|
return self.base_url[: -len("/v1")]
|
||||||
|
return self.base_url
|
||||||
|
|
||||||
|
def _query_context_window(self) -> int | None:
|
||||||
|
"""POST /api/show {model} for the runtime context window. Any failure
|
||||||
|
(unreachable, non-ollama endpoint, malformed reply) returns None so the
|
||||||
|
caller falls back to config or the default. Uses a short request
|
||||||
|
timeout so a slow show endpoint never wedges the actual generation."""
|
||||||
|
url = f"{self._native_base_url()}/api/show"
|
||||||
|
request = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
data=json.dumps({"model": self.model}).encode("utf-8"),
|
||||||
|
headers=self._headers(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
request, timeout=min(self.timeout, 10.0)
|
||||||
|
) as response:
|
||||||
|
data = json.loads(response.read().decode("utf-8"))
|
||||||
|
except (urllib.error.URLError, TimeoutError, ValueError, KeyError):
|
||||||
|
return None
|
||||||
|
params = data.get("parameters")
|
||||||
|
if isinstance(params, dict):
|
||||||
|
num_ctx = params.get("num_ctx")
|
||||||
|
if isinstance(num_ctx, int) and num_ctx > 0:
|
||||||
|
return num_ctx
|
||||||
|
elif isinstance(params, str):
|
||||||
|
# ollama serves parameters as modelfile text, not a dict:
|
||||||
|
# "num_ctx 100000\n..." — pull the num_ctx line if present.
|
||||||
|
for line in params.splitlines():
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) == 2 and parts[0] == "num_ctx":
|
||||||
|
try:
|
||||||
|
num_ctx = int(parts[1])
|
||||||
|
except ValueError:
|
||||||
|
break
|
||||||
|
if num_ctx > 0:
|
||||||
|
return num_ctx
|
||||||
|
model_info = data.get("model_info") or {}
|
||||||
|
for key, value in model_info.items():
|
||||||
|
if key.endswith(".context_length") and isinstance(value, int) and value > 0:
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _context_window(self) -> int:
|
||||||
|
"""Detected context window, queried once and cached.
|
||||||
|
|
||||||
|
`query_context=False` (hosted/non-ollama endpoints) skips the
|
||||||
|
`/api/show` probe entirely: the window is taken from `context_window`
|
||||||
|
config or `DEFAULT_CONTEXT_WINDOW`, so no stray request is sent.
|
||||||
|
"""
|
||||||
|
if self._window is not None:
|
||||||
|
return self._window
|
||||||
|
window = self._query_context_window() if self.query_context else None
|
||||||
|
if window is None:
|
||||||
|
window = (
|
||||||
|
int(self.context_window)
|
||||||
|
if self.context_window > 0
|
||||||
|
else DEFAULT_CONTEXT_WINDOW
|
||||||
|
)
|
||||||
|
self._window = window
|
||||||
|
return window
|
||||||
|
|
||||||
|
def _compute_budget(self, messages: list[dict]) -> TokenBudget:
|
||||||
|
window = self._context_window()
|
||||||
|
max_out = (
|
||||||
|
int(self.max_output)
|
||||||
|
if self.max_output >= 1
|
||||||
|
else int(self.max_output * window)
|
||||||
|
)
|
||||||
|
total_limit = int(min(self.smart_limit, window * self.max_fill_ratio))
|
||||||
|
prompt_est = int(
|
||||||
|
sum(len(str(m.get("content") or "")) for m in messages)
|
||||||
|
/ self.chars_per_token
|
||||||
|
)
|
||||||
|
if total_limit > 0 and prompt_est >= total_limit:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} prompt (~{prompt_est} tokens) already exceeds the "
|
||||||
|
f"total budget of {total_limit} tokens"
|
||||||
|
)
|
||||||
|
if total_limit > 0 and max_out > 0:
|
||||||
|
output_limit = min(max_out, total_limit - prompt_est)
|
||||||
|
else:
|
||||||
|
output_limit = 0
|
||||||
|
warn_point = None
|
||||||
|
if self.warn_limit > 0 and self.warn_fill_ratio > 0:
|
||||||
|
warn_point = min(self.warn_limit, int(window * self.warn_fill_ratio))
|
||||||
|
return TokenBudget(window, total_limit, output_limit, warn_point, prompt_est)
|
||||||
|
|
||||||
|
def _print_budget(self, budget: TokenBudget) -> None:
|
||||||
|
if budget.window and budget.output_limit > 0:
|
||||||
|
print(
|
||||||
|
f"[{self.label}] context window {budget.window} tokens · "
|
||||||
|
f"output cap {budget.output_limit} tokens "
|
||||||
|
f"({budget.output_limit / budget.window * 100:.0f}%) · "
|
||||||
|
f"peak total fill ~{budget.total_limit} tokens"
|
||||||
|
)
|
||||||
|
elif budget.window:
|
||||||
|
print(
|
||||||
|
f"[{self.label}] context window {budget.window} tokens · "
|
||||||
|
f"peak total fill ~{budget.total_limit} tokens"
|
||||||
|
)
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
def _log_usage(self, budget: TokenBudget, usage: dict) -> None:
|
||||||
|
"""Report exact token usage once `include_usage` yields a usage chunk.
|
||||||
|
|
||||||
|
Logs real prompt/completion/total tokens, % of the detected window, and
|
||||||
|
the zone (SMART < smart_limit, WARN < warn_limit, else DUMB) measured
|
||||||
|
against absolute total-token thresholds.
|
||||||
|
"""
|
||||||
|
prompt = usage.get("prompt_tokens")
|
||||||
|
completion = usage.get("completion_tokens")
|
||||||
|
total = usage.get("total_tokens")
|
||||||
|
if not isinstance(total, int):
|
||||||
|
return
|
||||||
|
if not isinstance(prompt, int):
|
||||||
|
prompt = total - (completion if isinstance(completion, int) else 0)
|
||||||
|
if not isinstance(completion, int):
|
||||||
|
completion = total - prompt
|
||||||
|
pct = total / budget.window * 100 if budget.window else 0.0
|
||||||
|
if self.smart_limit > 0 and total < self.smart_limit:
|
||||||
|
zone = "SMART"
|
||||||
|
elif self.warn_limit > 0 and total < self.warn_limit:
|
||||||
|
zone = "WARN"
|
||||||
|
else:
|
||||||
|
zone = "DUMB"
|
||||||
|
print(
|
||||||
|
f"[{self.label}] usage: prompt {prompt} · completion {completion} · "
|
||||||
|
f"total {total} tokens · {pct:.0f}% of window · {zone}"
|
||||||
|
)
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
def _enforce_budget(self, budget: TokenBudget, out_chars: int, warned: bool) -> bool:
|
||||||
|
"""Abort when the output cap is exceeded; one-shot warn near the fill
|
||||||
|
threshold. Returns the updated warned state."""
|
||||||
|
output_est = out_chars / self.chars_per_token
|
||||||
|
if budget.output_limit > 0 and output_est >= budget.output_limit:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} output exceeded {budget.output_limit} token budget "
|
||||||
|
f"(~{out_chars} chars at {self.chars_per_token:g} chars/token)"
|
||||||
|
)
|
||||||
|
if budget.warn_point is not None and not warned:
|
||||||
|
total = budget.prompt_est + output_est
|
||||||
|
if total >= budget.warn_point:
|
||||||
|
sys.stdout.write(
|
||||||
|
f"\n[{self.label}] total fill ~{int(total)} tokens — "
|
||||||
|
f"near the {budget.output_limit} token output budget\n"
|
||||||
|
)
|
||||||
|
sys.stdout.flush()
|
||||||
|
return True
|
||||||
|
return warned
|
||||||
|
|
||||||
|
def _read_stream(
|
||||||
|
self,
|
||||||
|
response,
|
||||||
|
budget: TokenBudget,
|
||||||
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
timeout: float | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Read an OpenAI-compatible SSE stream; echo tokens if `stream`.
|
||||||
|
|
||||||
|
Only `content` deltas are accumulated into the returned body;
|
||||||
|
reasoning (chain-of-thought) is echoed to the console but never part
|
||||||
|
of the result. Backends disagree on the field name: ollama streams it
|
||||||
|
as `reasoning`, DeepSeek/vllm-style as `reasoning_content`, so read both.
|
||||||
|
|
||||||
|
Reads are gated by `select` so the socket never blocks-and-times-out:
|
||||||
|
a socket that delivers no bytes for `idle_warn` seconds prints a
|
||||||
|
warning, and `idle_timeout` seconds of silence raises CodegenError.
|
||||||
|
The total wall-clock budget `self.timeout` is enforced against the
|
||||||
|
whole stream and checked on every loop iteration, so even a
|
||||||
|
continuously-streaming generation that never sends `[DONE]` is cut
|
||||||
|
short. The token budget aborts as soon as the output cap is reached.
|
||||||
|
Thresholds <= 0 disable the idle checks. If the underlying socket
|
||||||
|
can't be reached, falls back to a plain blocking read
|
||||||
|
(`_read_stream_blocking`, which enforces the same budgets).
|
||||||
|
|
||||||
|
An optional `degeneration_check` (last `window` chars of content +
|
||||||
|
reasoning, every `interval` chars past `min_chars`) can abort a
|
||||||
|
generation that is looping instead of converging — a non-None return
|
||||||
|
is the abort reason.
|
||||||
|
"""
|
||||||
|
parts: list[str] = []
|
||||||
|
sock = self._stream_socket(response)
|
||||||
|
if sock is None:
|
||||||
|
return self._read_stream_blocking(
|
||||||
|
response, budget, degeneration_check, timeout=timeout
|
||||||
|
)
|
||||||
|
deadline = self.timeout if timeout is None else timeout
|
||||||
|
start = time.monotonic()
|
||||||
|
last_activity = start
|
||||||
|
warned = False
|
||||||
|
warned_fill = False
|
||||||
|
out_chars = 0
|
||||||
|
usage: dict | None = None
|
||||||
|
recent: list[str] = []
|
||||||
|
recent_len = 0
|
||||||
|
last_check: int | None = None
|
||||||
|
while True:
|
||||||
|
if time.monotonic() - start >= deadline:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} request exceeded {deadline:.0f}s total budget"
|
||||||
|
)
|
||||||
|
ready, _, _ = select.select([sock], [], [], 1.0)
|
||||||
|
now = time.monotonic()
|
||||||
|
if not ready:
|
||||||
|
idle = now - last_activity
|
||||||
|
if self.idle_warn > 0 and not warned and idle >= self.idle_warn:
|
||||||
|
sys.stdout.write(
|
||||||
|
f"\n[{self.label}] no tokens for {idle:.0f}s — still waiting, "
|
||||||
|
f"will fail after {self.idle_timeout:.0f}s of silence\n"
|
||||||
|
)
|
||||||
|
sys.stdout.flush()
|
||||||
|
warned = True
|
||||||
|
if self.idle_timeout > 0 and idle >= self.idle_timeout:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} stream stalled: no tokens for {idle:.0f}s "
|
||||||
|
f"(idle_timeout={self.idle_timeout:.0f}s)"
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
raw = response.readline()
|
||||||
|
except OSError as exc:
|
||||||
|
raise self.error_class(f"{self.label} stream read failed: {exc}") from exc
|
||||||
|
if not raw:
|
||||||
|
break
|
||||||
|
last_activity = time.monotonic()
|
||||||
|
continues, text, reasoning, frame_usage = self._consume_frame(
|
||||||
|
raw.decode("utf-8").strip()
|
||||||
|
)
|
||||||
|
if frame_usage is not None:
|
||||||
|
usage = frame_usage
|
||||||
|
if self.stream and (text or reasoning):
|
||||||
|
sys.stdout.write(text + reasoning)
|
||||||
|
sys.stdout.flush()
|
||||||
|
if text:
|
||||||
|
parts.append(text)
|
||||||
|
out_chars += len(text) + len(reasoning)
|
||||||
|
if text or reasoning:
|
||||||
|
recent.append(text + reasoning)
|
||||||
|
recent_len = self._trim_recent(recent, recent_len)
|
||||||
|
warned_fill = self._enforce_budget(budget, out_chars, warned_fill)
|
||||||
|
reason, last_check = self._check_degeneration(
|
||||||
|
degeneration_check, recent, out_chars, last_check
|
||||||
|
)
|
||||||
|
if reason:
|
||||||
|
raise self.degeneration_error_class(f"{self.label} degeneration detected: {reason}")
|
||||||
|
if not continues:
|
||||||
|
break
|
||||||
|
if usage is not None:
|
||||||
|
self._log_usage(budget, usage)
|
||||||
|
if parts and self.stream:
|
||||||
|
sys.stdout.write("\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
def _read_stream_blocking(
|
||||||
|
self,
|
||||||
|
response,
|
||||||
|
budget: TokenBudget,
|
||||||
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
timeout: float | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Fallback reader when the response socket can't be located.
|
||||||
|
|
||||||
|
A plain blocking read relies on the per-read socket timeout for
|
||||||
|
silence, but that bounds individual reads, not the whole stream — so
|
||||||
|
enforce the same total wall-clock budget (the per-call `timeout`, else
|
||||||
|
`self.timeout`) and the token budget in the loop, or a
|
||||||
|
continuously-streaming runaway would never be cut short.
|
||||||
|
"""
|
||||||
|
parts: list[str] = []
|
||||||
|
deadline = self.timeout if timeout is None else timeout
|
||||||
|
start = time.monotonic()
|
||||||
|
warned_fill = False
|
||||||
|
out_chars = 0
|
||||||
|
usage: dict | None = None
|
||||||
|
recent: list[str] = []
|
||||||
|
recent_len = 0
|
||||||
|
last_check: int | None = None
|
||||||
|
for raw in response:
|
||||||
|
if time.monotonic() - start >= deadline:
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} request exceeded {deadline:.0f}s total budget"
|
||||||
|
)
|
||||||
|
continues, text, reasoning, frame_usage = self._consume_frame(
|
||||||
|
raw.decode("utf-8").strip()
|
||||||
|
)
|
||||||
|
if frame_usage is not None:
|
||||||
|
usage = frame_usage
|
||||||
|
if self.stream and (text or reasoning):
|
||||||
|
sys.stdout.write(text + reasoning)
|
||||||
|
sys.stdout.flush()
|
||||||
|
if text:
|
||||||
|
parts.append(text)
|
||||||
|
out_chars += len(text) + len(reasoning)
|
||||||
|
if text or reasoning:
|
||||||
|
recent.append(text + reasoning)
|
||||||
|
recent_len = self._trim_recent(recent, recent_len)
|
||||||
|
warned_fill = self._enforce_budget(budget, out_chars, warned_fill)
|
||||||
|
reason, last_check = self._check_degeneration(
|
||||||
|
degeneration_check, recent, out_chars, last_check
|
||||||
|
)
|
||||||
|
if reason:
|
||||||
|
raise self.degeneration_error_class(f"{self.label} degeneration detected: {reason}")
|
||||||
|
if not continues:
|
||||||
|
break
|
||||||
|
if usage is not None:
|
||||||
|
self._log_usage(budget, usage)
|
||||||
|
if parts and self.stream:
|
||||||
|
sys.stdout.write("\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
def _trim_recent(self, recent: list[str], recent_len: int) -> int:
|
||||||
|
"""Keep the rolling (content+reasoning) buffer bounded.
|
||||||
|
|
||||||
|
Only the last `degeneration_window + degeneration_interval` chars are
|
||||||
|
ever needed: the check runs every `interval` chars against the last
|
||||||
|
`window` chars, so older text can be dropped. Returns the new length.
|
||||||
|
"""
|
||||||
|
budget = self.degeneration_window + self.degeneration_interval
|
||||||
|
while recent and recent_len > budget:
|
||||||
|
recent_len -= len(recent.pop(0))
|
||||||
|
return recent_len
|
||||||
|
|
||||||
|
def _check_degeneration(
|
||||||
|
self,
|
||||||
|
check: Callable[[str], str | None] | None,
|
||||||
|
recent: list[str],
|
||||||
|
out_chars: int,
|
||||||
|
last_check: int | None,
|
||||||
|
) -> tuple[str | None, int | None]:
|
||||||
|
"""Run the degeneration callback on the last `window` chars of
|
||||||
|
content+reasoning, every `interval` chars once `min_chars` have
|
||||||
|
accumulated. Returns (reason, new_last_check); a non-None reason means
|
||||||
|
the caller should abort."""
|
||||||
|
if check is None or out_chars < self.degeneration_min_chars:
|
||||||
|
return None, last_check
|
||||||
|
if last_check is None or out_chars - last_check >= self.degeneration_interval:
|
||||||
|
window = self.degeneration_window or len(recent)
|
||||||
|
reason = check("".join(recent)[-window:])
|
||||||
|
return reason, out_chars
|
||||||
|
return None, last_check
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _consume_frame(line: str) -> tuple[bool, str, str, dict | None]:
|
||||||
|
"""Process one SSE line.
|
||||||
|
|
||||||
|
Returns (continue, content, reasoning, usage). `content` feeds the
|
||||||
|
returned body; `reasoning` is only ever echoed; `usage` is the exact
|
||||||
|
token usage carried on the final chunk when `include_usage` was
|
||||||
|
requested (None otherwise). (False, "", "", None) on [DONE].
|
||||||
|
"""
|
||||||
|
if not line.startswith("data:"):
|
||||||
|
return True, "", "", None
|
||||||
|
data = line[len("data:") :].strip()
|
||||||
|
if data == "[DONE]":
|
||||||
|
return False, "", "", None
|
||||||
|
try:
|
||||||
|
chunk = json.loads(data)
|
||||||
|
except ValueError:
|
||||||
|
return True, "", "", None
|
||||||
|
usage = chunk.get("usage")
|
||||||
|
if not isinstance(usage, dict):
|
||||||
|
usage = None
|
||||||
|
choices = chunk.get("choices") or []
|
||||||
|
choice = choices[0] if choices else {}
|
||||||
|
delta = choice.get("delta", {}) or {}
|
||||||
|
text = delta.get("content") or ""
|
||||||
|
reasoning = delta.get("reasoning_content") or delta.get("reasoning") or ""
|
||||||
|
return True, text, reasoning, usage
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _stream_socket(response):
|
||||||
|
"""Reach the underlying socket across Python-version response shapes."""
|
||||||
|
fp = getattr(response, "fp", response)
|
||||||
|
raw = getattr(fp, "raw", None)
|
||||||
|
sock = getattr(raw, "_sock", None) if raw is not None else None
|
||||||
|
if sock is None:
|
||||||
|
sock = getattr(fp, "sock", None)
|
||||||
|
if sock is None:
|
||||||
|
sock = getattr(response, "sock", None)
|
||||||
|
return sock
|
||||||
|
|
||||||
|
|
||||||
|
class SemIfEngineClient:
|
||||||
|
"""Text generation backed by the in-process SemIf engine model.
|
||||||
|
|
||||||
|
A drop-in sibling of `OpenAICompatClient` for the small `llm` task: instead
|
||||||
|
of speaking HTTP to an ollama/Console endpoint it drives the already-loaded
|
||||||
|
decision GGUF through `engine.generate(...)`. It exposes the same
|
||||||
|
``chat(messages, max_tokens=..., temperature=..., ...)`` surface every `llm`
|
||||||
|
caller uses, so the provider choice is invisible to callers — title/
|
||||||
|
description authoring, gateway result cleanup, and the LLM bridge all reuse
|
||||||
|
it unchanged.
|
||||||
|
|
||||||
|
The engine is duck-typed (any object with ``generate(messages, temperature,
|
||||||
|
max_tokens)``); this module stays free of imports from the agent's own
|
||||||
|
modules, so subclasses in `llm.py` set the `LLMError` contract without a
|
||||||
|
cycle. Sampler/`timeout`/`degeneration_check` arguments are accepted for
|
||||||
|
signature compatibility and ignored: the engine generation is bounded by
|
||||||
|
`max_tokens` and serializes on the engine's own lock.
|
||||||
|
|
||||||
|
Any engine failure (`EngineUnavailable`, a missing GGUF, a sampling error)
|
||||||
|
is re-raised as `error_class` so the scheduler's graceful `draft_failed`
|
||||||
|
path and the LLM bridge's 502 path keep their existing contracts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_class = ProviderError
|
||||||
|
label = "semif"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
engine,
|
||||||
|
temperature: float = 0.0,
|
||||||
|
max_tokens: int = 256,
|
||||||
|
disable_thinking: bool = True,
|
||||||
|
):
|
||||||
|
self.engine = engine
|
||||||
|
self.temperature = temperature
|
||||||
|
self.max_tokens = max_tokens
|
||||||
|
# The engine's `generate` always decodes with thinking disabled; the knob
|
||||||
|
# is accepted so the class mirrors the other providers' constructors.
|
||||||
|
self.disable_thinking = disable_thinking
|
||||||
|
|
||||||
|
def chat(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
max_tokens: int | None = None,
|
||||||
|
temperature: float | None = None,
|
||||||
|
top_p: float | None = None,
|
||||||
|
presence_penalty: float | None = None,
|
||||||
|
frequency_penalty: float | None = None,
|
||||||
|
timeout: float | None = None,
|
||||||
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
) -> str:
|
||||||
|
resolved_max = self.max_tokens if max_tokens is None else max_tokens
|
||||||
|
resolved_temp = self.temperature if temperature is None else temperature
|
||||||
|
try:
|
||||||
|
return self.engine.generate(
|
||||||
|
messages, temperature=resolved_temp, max_tokens=resolved_max
|
||||||
|
)
|
||||||
|
except Exception as exc: # EngineUnavailable and anything the engine raises
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} generation failed: {exc}"
|
||||||
|
) from exc
|
||||||
+16
-55
@@ -1,83 +1,44 @@
|
|||||||
"""Urgency priority queue.
|
"""FIFO request queue with a maximum depth.
|
||||||
|
|
||||||
Items are sorted by descending urgency weight, then FIFO arrival, then most
|
Requests are dispatched strictly in arrival order: there is no urgency scoring
|
||||||
recent first. Queued items age upward so they cannot starve, and the queue has
|
and no preemption, so the running process always finishes before the next queued
|
||||||
a maximum depth.
|
request is picked up.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import heapq
|
from collections import deque
|
||||||
import itertools
|
|
||||||
import time
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Iterator
|
from typing import Iterator
|
||||||
|
|
||||||
from .decisions import Request
|
from .decisions import Request
|
||||||
|
|
||||||
MIN_RECENCY = 0.0
|
|
||||||
|
|
||||||
|
class RequestQueue:
|
||||||
|
"""A bounded first-in-first-out queue of pending requests."""
|
||||||
|
|
||||||
@dataclass
|
def __init__(self, max_size: int = 100):
|
||||||
class QueueItem:
|
|
||||||
weight: float
|
|
||||||
seq: int
|
|
||||||
recency: float
|
|
||||||
request: Request
|
|
||||||
|
|
||||||
def key(self) -> tuple:
|
|
||||||
return (-self.weight, self.seq)
|
|
||||||
|
|
||||||
|
|
||||||
class UrgencyQueue:
|
|
||||||
"""A max-by-urgency priority queue with FIFO/recency tie-breaking."""
|
|
||||||
|
|
||||||
def __init__(self, max_size: int = 100, age_rate: float = 0.0):
|
|
||||||
self.max_size = max_size
|
self.max_size = max_size
|
||||||
self.age_rate = age_rate
|
self._entries: deque[Request] = deque()
|
||||||
self._entries: list[tuple] = []
|
|
||||||
self._counter = itertools.count()
|
|
||||||
|
|
||||||
def push(self, request: Request, weight: float, recency: float | None = None) -> bool:
|
def push(self, request: Request) -> bool:
|
||||||
"""Insert an item. Returns False if the queue is full."""
|
"""Append an item. Returns False if the queue is full."""
|
||||||
if len(self._entries) >= self.max_size:
|
if len(self._entries) >= self.max_size:
|
||||||
return False
|
return False
|
||||||
item = QueueItem(
|
self._entries.append(request)
|
||||||
weight=weight,
|
|
||||||
seq=next(self._counter),
|
|
||||||
recency=recency if recency is not None else time.time(),
|
|
||||||
request=request,
|
|
||||||
)
|
|
||||||
entry = (*item.key(), next(self._counter), item)
|
|
||||||
heapq.heappush(self._entries, entry)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def pop(self) -> Request | None:
|
def pop(self) -> Request | None:
|
||||||
if not self._entries:
|
if not self._entries:
|
||||||
return None
|
return None
|
||||||
return heapq.heappop(self._entries)[-1].request
|
return self._entries.popleft()
|
||||||
|
|
||||||
def peek(self) -> Request | None:
|
def peek(self) -> Request | None:
|
||||||
if not self._entries:
|
if not self._entries:
|
||||||
return None
|
return None
|
||||||
return self._entries[0][-1].request
|
return self._entries[0]
|
||||||
|
|
||||||
def age(self, dt: float = 1.0) -> None:
|
|
||||||
"""Pull queued priorities toward critical so old items catch up."""
|
|
||||||
if self.age_rate <= 0:
|
|
||||||
return
|
|
||||||
rebuilt = []
|
|
||||||
for entry in self._entries:
|
|
||||||
item = entry[-1]
|
|
||||||
item.weight += self.age_rate * dt * (1.0 - item.weight)
|
|
||||||
rebuilt.append((*item.key(), next(self._counter), item))
|
|
||||||
self._entries = rebuilt
|
|
||||||
heapq.heapify(self._entries)
|
|
||||||
|
|
||||||
def __len__(self) -> int:
|
def __len__(self) -> int:
|
||||||
return len(self._entries)
|
return len(self._entries)
|
||||||
|
|
||||||
def items(self) -> Iterator[tuple[float, Request]]:
|
def items(self) -> Iterator[Request]:
|
||||||
for entry in sorted(self._entries, key=lambda e: e[:-1]):
|
yield from self._entries
|
||||||
item = entry[-1]
|
|
||||||
yield item.weight, item.request
|
|
||||||
@@ -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)
|
||||||
+2336
-242
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))
|
||||||
@@ -0,0 +1,773 @@
|
|||||||
|
"""Low-level SimpleX Chat daemon WebSocket protocol (neutral transport).
|
||||||
|
|
||||||
|
This module owns the wire protocol only: connecting to a local `simplex-chat`
|
||||||
|
daemon, parsing received events into plain message dicts, running correlated
|
||||||
|
request/response round-trips (e.g. the contact-address lookup), accepting
|
||||||
|
contact requests, and draining an outbound send queue. It knows nothing about
|
||||||
|
the SemIf scheduler, the command gateway, or the forwarding bridge — both
|
||||||
|
front ends build on top of it.
|
||||||
|
|
||||||
|
Keeping this layer neutral is deliberate (see AGENTS.md "gateway isolation"):
|
||||||
|
the command gateway and the third-party bridge services have different jobs,
|
||||||
|
and neither inherits the other's surface by sharing this module.
|
||||||
|
|
||||||
|
`websockets` is imported lazily inside the functions that need it so importing
|
||||||
|
this module stays stdlib-only on a websocket-free machine.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import queue
|
||||||
|
import random
|
||||||
|
import threading
|
||||||
|
from typing import Any, Awaitable, Callable
|
||||||
|
|
||||||
|
#: One received direct text message, normalized across the v7 wire shapes.
|
||||||
|
InboundDict = dict[str, Any]
|
||||||
|
#: Callback invoked in the event loop for each received direct text message.
|
||||||
|
MessageHandler = Callable[[InboundDict], None]
|
||||||
|
#: Async callback invoked in the event loop once a connection is established.
|
||||||
|
ConnectedHandler = Callable[[], Awaitable[None]]
|
||||||
|
|
||||||
|
|
||||||
|
def contact_entry(contact: dict) -> dict | None:
|
||||||
|
"""Normalize one daemon `Contact` into a contact dict, or None.
|
||||||
|
|
||||||
|
The single source of truth for contact identity across the wire: the same
|
||||||
|
shape appears in `newChatItems` items and in the `/_contacts` list. v7's
|
||||||
|
`Contact.displayName` is null and the real peer name lives in
|
||||||
|
`profile.displayName`; `localDisplayName` is the daemon's **unique** local
|
||||||
|
name, auto-suffixed on collisions (e.g. a second contact becomes
|
||||||
|
`pepper_1`). We keep both: `display_name` is the peer's profile name (what
|
||||||
|
a human recognizes, but it can collide) and `local_name` is the daemon's
|
||||||
|
unique name, so two peers with the same profile name stay distinguishable.
|
||||||
|
When the daemon reports connection state (the `/_contacts` list does),
|
||||||
|
`connected` and `auth_errors` are included so callers can prefer a live
|
||||||
|
peer over a dead one.
|
||||||
|
"""
|
||||||
|
contact_id = str(contact.get("contactId") or contact.get("chatId") or "")
|
||||||
|
if not contact_id:
|
||||||
|
return None
|
||||||
|
profile = contact.get("profile") or {}
|
||||||
|
local_name = (
|
||||||
|
contact.get("localDisplayName")
|
||||||
|
or contact.get("displayName")
|
||||||
|
or profile.get("displayName")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
display_name = (
|
||||||
|
profile.get("displayName")
|
||||||
|
or contact.get("displayName")
|
||||||
|
or local_name
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
entry = {"id": contact_id, "display_name": display_name, "local_name": local_name}
|
||||||
|
active = contact.get("activeConn") or {}
|
||||||
|
conn = active.get("connStatus") or {}
|
||||||
|
status = contact.get("contactStatus")
|
||||||
|
if status is not None or conn:
|
||||||
|
entry["connected"] = status == "active" and conn.get("type") == "ready"
|
||||||
|
if isinstance(active.get("authErrCounter"), int):
|
||||||
|
entry["auth_errors"] = active["authErrCounter"]
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def contact_link(resp: dict) -> dict:
|
||||||
|
"""Pull `{connShortLink, connFullLink}` out of a daemon address response.
|
||||||
|
|
||||||
|
`/_show_address` nests it as `contactLink.connLinkContact`; `/_address`
|
||||||
|
returns it directly as `connLinkContact`. Tolerate both (and a flat
|
||||||
|
`contactLink`) so callers read the real daemon shape rather than calling
|
||||||
|
`/_address` again on an existing link and reporting nothing.
|
||||||
|
"""
|
||||||
|
for candidate in (
|
||||||
|
(resp.get("contactLink") or {}).get("connLinkContact"),
|
||||||
|
resp.get("connLinkContact"),
|
||||||
|
resp.get("contactLink"),
|
||||||
|
resp,
|
||||||
|
):
|
||||||
|
if isinstance(candidate, dict) and (
|
||||||
|
candidate.get("connShortLink") or candidate.get("connFullLink")
|
||||||
|
):
|
||||||
|
return candidate
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _text_from_content(content: dict) -> str | None:
|
||||||
|
"""Extract the text of a text message from a `CIContent` union, or None.
|
||||||
|
|
||||||
|
Handles the same two shapes as `parse_direct_text_item`: the API form
|
||||||
|
(`{"type": "rcvMsgContent", "msgContent": {...}}`) and the DB/Aeson form
|
||||||
|
(`{"rcvMsgContent": {"msgContent": {...}}}`), for both received and sent
|
||||||
|
messages. Non-text content (files, calls, events) yields None.
|
||||||
|
"""
|
||||||
|
for key in ("rcvMsgContent", "sndMsgContent"):
|
||||||
|
if content.get("type") == key:
|
||||||
|
msg_content = content.get("msgContent") or {}
|
||||||
|
elif isinstance(content.get(key), dict):
|
||||||
|
msg_content = content[key].get("msgContent") or {}
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if msg_content.get("type") == "text":
|
||||||
|
return str(msg_content.get("text", "")).strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_chat_item(item: dict) -> dict | None:
|
||||||
|
"""Normalize one `ChatItem` into a history entry, or None.
|
||||||
|
|
||||||
|
Returns `{item_id, text, status, unread, direction, sent_at}`. `status` is
|
||||||
|
the raw `meta.itemStatus.type` (`rcvNew` / `rcvRead` / `snd*`), and `unread`
|
||||||
|
is True only for an unread received message. Items without an id are
|
||||||
|
dropped rather than fabricated.
|
||||||
|
"""
|
||||||
|
meta = item.get("meta") or {}
|
||||||
|
item_id = meta.get("itemId")
|
||||||
|
if item_id is None:
|
||||||
|
return None
|
||||||
|
text = _text_from_content(item.get("content") or {})
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
status_obj = meta.get("itemStatus") or {}
|
||||||
|
status = status_obj.get("type") or ""
|
||||||
|
entry = {
|
||||||
|
"item_id": str(item_id),
|
||||||
|
"text": text,
|
||||||
|
"status": status,
|
||||||
|
"unread": status == "rcvNew",
|
||||||
|
"direction": (item.get("chatDir") or {}).get("type") or "",
|
||||||
|
"sent_at": meta.get("itemTs") or "",
|
||||||
|
}
|
||||||
|
# A failed send carries the agent-level reason (`{"type":"auth"}` etc.);
|
||||||
|
# surface it so a caller can report *why* a message did not go out.
|
||||||
|
agent_error = status_obj.get("agentError") or {}
|
||||||
|
if agent_error:
|
||||||
|
entry["error"] = agent_error.get("type") or str(agent_error)
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
|
def parse_chat(achat: dict) -> dict | None:
|
||||||
|
"""Normalize one `AChat` into a chat summary, or None for a non-direct chat.
|
||||||
|
|
||||||
|
Returns `{contact_id, display_name, unread_count, min_unread_item_id,
|
||||||
|
unread, messages}` from `chatInfo` + `chatStats` + `chatItems`. A group or
|
||||||
|
local chat (no direct contact) yields None.
|
||||||
|
"""
|
||||||
|
info = achat.get("chatInfo") or {}
|
||||||
|
if info.get("type") != "direct":
|
||||||
|
return None
|
||||||
|
entry = contact_entry(info.get("contact") or {})
|
||||||
|
if entry is None:
|
||||||
|
return None
|
||||||
|
stats = achat.get("chatStats") or {}
|
||||||
|
try:
|
||||||
|
unread_count = int(stats.get("unreadCount") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
unread_count = 0
|
||||||
|
messages: list[dict] = []
|
||||||
|
for item in achat.get("chatItems") or []:
|
||||||
|
parsed = parse_chat_item(item)
|
||||||
|
if parsed is not None:
|
||||||
|
messages.append(parsed)
|
||||||
|
min_unread = stats.get("minUnreadItemId")
|
||||||
|
return {
|
||||||
|
"contact_id": entry["id"],
|
||||||
|
"display_name": entry["display_name"],
|
||||||
|
"unread_count": unread_count,
|
||||||
|
"min_unread_item_id": str(min_unread) if min_unread is not None else "",
|
||||||
|
"unread": bool(stats.get("unreadChat")) or unread_count > 0,
|
||||||
|
"messages": messages,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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, 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":
|
||||||
|
return None
|
||||||
|
chat_item = item.get("chatItem") or {}
|
||||||
|
direction = (chat_item.get("chatDir") or {}).get("type", "")
|
||||||
|
if direction and "Snd" in direction:
|
||||||
|
return None # own echo
|
||||||
|
content = chat_item.get("content") or {}
|
||||||
|
# simplex-chat v7 tags the content union by constructor: a received text
|
||||||
|
# message is {"type": "rcvMsgContent", "msgContent": {"type": "text",
|
||||||
|
# "text": ...}}. The daemon's DB/Aeson encoding nests under the
|
||||||
|
# constructor key instead ({"rcvMsgContent": {"msgContent": ...}}), so
|
||||||
|
# accept both shapes.
|
||||||
|
if content.get("type") == "rcvMsgContent":
|
||||||
|
msg_content = content.get("msgContent") or {}
|
||||||
|
elif isinstance(content.get("rcvMsgContent"), dict):
|
||||||
|
msg_content = content["rcvMsgContent"].get("msgContent") or {}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if msg_content.get("type") != "text":
|
||||||
|
return None
|
||||||
|
text = str(msg_content.get("text", "")).strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
contact = dict(chat_info.get("contact") or {})
|
||||||
|
if not contact.get("contactId") and not contact.get("chatId"):
|
||||||
|
contact["chatId"] = chat_info.get("chatId")
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_text_command(chat_id: str, text: str) -> str:
|
||||||
|
"""Structured APISendMessages command for a direct contact.
|
||||||
|
|
||||||
|
The CLI shortcut `@<id> <text>` is silently rejected over WebSocket (it
|
||||||
|
resolves the ref as a display name), so always use the JSON form.
|
||||||
|
"""
|
||||||
|
composed = [{"msgContent": {"type": "text", "text": text}}]
|
||||||
|
return f"/_send @{chat_id} json {json.dumps(composed)}"
|
||||||
|
|
||||||
|
|
||||||
|
def accept_command(resp: dict) -> str | None:
|
||||||
|
"""The `/_accept` command for a `receivedContactRequest`, or None.
|
||||||
|
|
||||||
|
v7 names the field contactRequestId_ (the trailing underscore is the
|
||||||
|
generated-API optional marker) and /_accept takes the *request* id; older
|
||||||
|
events exposed contactId. Fall back so both shapes work.
|
||||||
|
"""
|
||||||
|
req = resp.get("contactRequest") or {}
|
||||||
|
req_id = req.get("contactRequestId")
|
||||||
|
if req_id is None:
|
||||||
|
req_id = req.get("contactId_") or req.get("contactId")
|
||||||
|
if req_id is None:
|
||||||
|
return None
|
||||||
|
return f"/_accept {req_id}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_send_response(resp: dict) -> dict:
|
||||||
|
"""Normalize a `/_send` response into `{item_id, status, error}`.
|
||||||
|
|
||||||
|
A successful send comes back as `newChatItems` carrying the freshly created
|
||||||
|
`chatItem` (its `meta.itemId` and initial `meta.itemStatus`, usually
|
||||||
|
`sndNew`). A rejected send comes back as `chatCmdError`. `item_id` is None
|
||||||
|
on any rejection so the caller can tell "no message was created" from
|
||||||
|
"created but later failed at the agent layer".
|
||||||
|
"""
|
||||||
|
if not isinstance(resp, dict):
|
||||||
|
return {"item_id": None, "status": "", "error": "empty daemon response"}
|
||||||
|
if resp.get("type") == "chatCmdError" or resp.get("error"):
|
||||||
|
detail = resp.get("chatError") or resp.get("error") or "chat command failed"
|
||||||
|
return {"item_id": None, "status": "", "error": str(detail)[:300]}
|
||||||
|
for item in resp.get("chatItems") or []:
|
||||||
|
meta = (item.get("chatItem") or {}).get("meta") or {}
|
||||||
|
item_id = meta.get("itemId")
|
||||||
|
if item_id is None:
|
||||||
|
continue
|
||||||
|
status = (meta.get("itemStatus") or {}).get("type") or ""
|
||||||
|
error = ((meta.get("itemStatus") or {}).get("agentError") or {}).get("type") or ""
|
||||||
|
return {"item_id": str(item_id), "status": status, "error": error}
|
||||||
|
return {"item_id": None, "status": "", "error": "daemon returned no message id"}
|
||||||
|
|
||||||
|
|
||||||
|
def read_command(chat_id: str, item_ids=None) -> str:
|
||||||
|
"""Structured command that marks a chat, or specific items, read.
|
||||||
|
|
||||||
|
v7 exposes `/_read chat @<id>` (the whole chat) and `/_read chat items @<id>
|
||||||
|
<comma-separated item ids>` (a precise subset). The item form is used so
|
||||||
|
consuming the next unread message clears exactly that message and leaves the
|
||||||
|
rest of the chat untouched. With no usable item ids it falls back to the
|
||||||
|
whole-chat form.
|
||||||
|
"""
|
||||||
|
chat_ref = f"@{str(chat_id).strip().lstrip('@')}"
|
||||||
|
if item_ids:
|
||||||
|
ids = ",".join(str(i).strip() for i in item_ids if str(i).strip())
|
||||||
|
if ids:
|
||||||
|
return f"/_read chat items {chat_ref} {ids}"
|
||||||
|
return f"/_read chat {chat_ref}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_read_response(resp: dict) -> dict:
|
||||||
|
"""Normalize a `/_read chat` response into `{ok, type, error}`.
|
||||||
|
|
||||||
|
A successful item read comes back as `itemsReadForChat` and a whole-chat
|
||||||
|
read as the chat's `ok`; a rejected command comes back as `chatCmdError`.
|
||||||
|
`ok` is True only when the daemon did not report an error, so a caller never
|
||||||
|
treats a rejected (or empty) response as a consumed message.
|
||||||
|
"""
|
||||||
|
if not isinstance(resp, dict) or not resp:
|
||||||
|
return {"ok": False, "type": "", "error": "empty daemon response"}
|
||||||
|
if resp.get("type") == "chatCmdError" or resp.get("error"):
|
||||||
|
detail = resp.get("chatError") or resp.get("error") or "read command failed"
|
||||||
|
return {"ok": False, "type": "chatCmdError", "error": str(detail)[:300]}
|
||||||
|
return {"ok": True, "type": resp.get("type") or "", "error": ""}
|
||||||
|
|
||||||
|
|
||||||
|
class SimplexDaemon:
|
||||||
|
"""One WebSocket connection to a `simplex-chat` daemon.
|
||||||
|
|
||||||
|
`run(on_message)` blocks, reconnecting on transport failure, delivering each
|
||||||
|
received direct text message to `on_message` in the event loop and draining
|
||||||
|
`enqueue()`d sends from an internal queue. `request_address()` is safe to
|
||||||
|
call from another thread (the bridge's HTTP handler). Beware: the same
|
||||||
|
daemon/profile must not be shared by two processes — each front end points
|
||||||
|
at its own daemon.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
ws_url: str,
|
||||||
|
*,
|
||||||
|
user_id: int = 1,
|
||||||
|
auto_accept: bool = True,
|
||||||
|
reconnect: dict | None = None,
|
||||||
|
on_connected: ConnectedHandler | None = None,
|
||||||
|
trace=None,
|
||||||
|
name: str = "simplex",
|
||||||
|
):
|
||||||
|
self.ws_url = str(ws_url)
|
||||||
|
self.user_id = int(user_id)
|
||||||
|
self.auto_accept = bool(auto_accept)
|
||||||
|
settings = reconnect or {}
|
||||||
|
self.reconnect_initial = float(settings.get("initial", 1.0))
|
||||||
|
self.reconnect_max = float(settings.get("max", 60.0))
|
||||||
|
self.reconnect_jitter = float(settings.get("jitter", 0.2))
|
||||||
|
self.on_connected = on_connected
|
||||||
|
self.trace = trace
|
||||||
|
self.name = name
|
||||||
|
self._corr = 0
|
||||||
|
self._pending: dict[str, asyncio.Future] = {}
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self._ws = None
|
||||||
|
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._on_message: MessageHandler | None = None
|
||||||
|
self._active_user_id: int | None = None
|
||||||
|
|
||||||
|
# ---- requirements ----
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
if not self.ws_url:
|
||||||
|
return False, "simplex ws_url is required"
|
||||||
|
try:
|
||||||
|
import websockets # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
return False, "pip install websockets"
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
def run(self, on_message: MessageHandler) -> None:
|
||||||
|
asyncio.run(self._serve(on_message))
|
||||||
|
|
||||||
|
def enqueue(self, chat_id: str | None, text: str = "") -> None:
|
||||||
|
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
|
||||||
|
if chat_id is None:
|
||||||
|
self._outbound.put(None)
|
||||||
|
else:
|
||||||
|
self._outbound.put((str(chat_id), text))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
self._outbound.put(None)
|
||||||
|
|
||||||
|
async def _serve(self, on_message: MessageHandler) -> None:
|
||||||
|
import websockets
|
||||||
|
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self._on_message = on_message
|
||||||
|
backoff = self.reconnect_initial
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
async with websockets.connect(self.ws_url, max_size=None) as ws:
|
||||||
|
self._ws = ws
|
||||||
|
backoff = self.reconnect_initial
|
||||||
|
self._event("gateway_connected", url=self.ws_url)
|
||||||
|
sender = asyncio.create_task(self._outbound_loop(ws))
|
||||||
|
# The on_connected hook may issue correlated commands (e.g.
|
||||||
|
# the startup contact-address lookup), so run it
|
||||||
|
# CONCURRENTLY with the read loop: awaiting it inline would
|
||||||
|
# block the loop that resolves its own response and the
|
||||||
|
# request would time out.
|
||||||
|
hook = asyncio.create_task(self._notify_connected())
|
||||||
|
try:
|
||||||
|
async for raw in ws:
|
||||||
|
await self._consume(raw)
|
||||||
|
finally:
|
||||||
|
hook.cancel()
|
||||||
|
sender.cancel()
|
||||||
|
except Exception as exc: # reconnect on any transport failure
|
||||||
|
self._event("gateway_error", message=str(exc)[:300])
|
||||||
|
finally:
|
||||||
|
self._ws = None
|
||||||
|
self._fail_pending("simplex gateway disconnected")
|
||||||
|
delay = min(backoff, self.reconnect_max)
|
||||||
|
delay *= 1 + random.random() * self.reconnect_jitter
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._stop_wait(), timeout=delay)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
pass
|
||||||
|
backoff = min(max(delay, self.reconnect_initial), self.reconnect_max)
|
||||||
|
|
||||||
|
async def _stop_wait(self) -> None:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
async def _notify_connected(self) -> None:
|
||||||
|
"""Run the optional `on_connected` hook; a hook failure must not drop
|
||||||
|
the socket (it is traced and the connection stays up)."""
|
||||||
|
if self.on_connected is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await self.on_connected()
|
||||||
|
except Exception as exc:
|
||||||
|
self._event(
|
||||||
|
"gateway_error",
|
||||||
|
phase="on_connected",
|
||||||
|
message=str(exc)[:300],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _outbound_loop(self, ws) -> None:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
while True:
|
||||||
|
item = await loop.run_in_executor(None, self._outbound.get)
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
chat_id, text = item
|
||||||
|
try:
|
||||||
|
self._corr += 1
|
||||||
|
await ws.send(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"corrId": f"sf-{self._corr}",
|
||||||
|
"cmd": send_text_command(chat_id, text),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._event("gateway_sent", chat_id=chat_id, chars=len(text))
|
||||||
|
except Exception as exc:
|
||||||
|
self._event("gateway_error", phase="send", message=str(exc)[:300])
|
||||||
|
|
||||||
|
# ---- request/response + address ----
|
||||||
|
|
||||||
|
async def _roundtrip(self, command: str, timeout: float) -> dict:
|
||||||
|
"""Send a command and await its correlated `resp` from the event loop."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None or self._loop is None:
|
||||||
|
raise RuntimeError("simplex gateway is not connected")
|
||||||
|
self._corr += 1
|
||||||
|
corr = f"req-{self._corr}"
|
||||||
|
future = self._loop.create_future()
|
||||||
|
self._pending[corr] = future
|
||||||
|
await ws.send(json.dumps({"corrId": corr, "cmd": command}))
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(future, timeout)
|
||||||
|
finally:
|
||||||
|
self._pending.pop(corr, None)
|
||||||
|
|
||||||
|
def _fail_pending(self, reason: str) -> None:
|
||||||
|
pending, self._pending = self._pending, {}
|
||||||
|
for future in pending.values():
|
||||||
|
if not future.done():
|
||||||
|
future.set_exception(RuntimeError(reason))
|
||||||
|
|
||||||
|
async def address(self, timeout: float = 20.0) -> dict:
|
||||||
|
"""Show the daemon user's contact address, creating it on first call.
|
||||||
|
|
||||||
|
`/_show_address <userId>` returns an existing link; when there is none,
|
||||||
|
`/_address <userId>` creates one. Returns
|
||||||
|
`{short_link, full_link, created}`.
|
||||||
|
"""
|
||||||
|
resp = await self._roundtrip(f"/_show_address {self.user_id}", timeout)
|
||||||
|
link: dict = {}
|
||||||
|
created = False
|
||||||
|
if resp.get("type") == "userContactLink":
|
||||||
|
link = contact_link(resp)
|
||||||
|
if not (link.get("connShortLink") or link.get("connFullLink")):
|
||||||
|
resp = await self._roundtrip(f"/_address {self.user_id}", timeout)
|
||||||
|
link = contact_link(resp)
|
||||||
|
created = True
|
||||||
|
return {
|
||||||
|
"short_link": link.get("connShortLink") or "",
|
||||||
|
"full_link": link.get("connFullLink") or "",
|
||||||
|
"created": created,
|
||||||
|
}
|
||||||
|
|
||||||
|
def request_address(self, timeout: float = 20.0) -> dict:
|
||||||
|
"""Thread-safe address lookup 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 link.
|
||||||
|
"""
|
||||||
|
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.address(timeout=timeout), loop)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex address request timed out") from exc
|
||||||
|
|
||||||
|
# ---- send ----
|
||||||
|
|
||||||
|
async def send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict:
|
||||||
|
"""Send a direct text message and return the daemon's correlated reply.
|
||||||
|
|
||||||
|
Unlike `enqueue` (fire-and-forget, used by the command gateway), this
|
||||||
|
awaits the `/_send` response so the caller sees whether the message was
|
||||||
|
created and its initial status. The daemon reports agent-level failures
|
||||||
|
(auth, quota) asynchronously, so a caller that needs delivery truth must
|
||||||
|
still poll `chat_history` for the item's terminal status.
|
||||||
|
"""
|
||||||
|
return await self._roundtrip(send_text_command(chat_id, text), timeout)
|
||||||
|
|
||||||
|
def request_send(self, chat_id: str, text: str, timeout: float = 20.0) -> dict:
|
||||||
|
"""Thread-safe correlated send for callers off the event loop.
|
||||||
|
|
||||||
|
Raises `RuntimeError` when no live connection exists and `TimeoutError`
|
||||||
|
when the daemon does not answer in time — never a fabricated success.
|
||||||
|
"""
|
||||||
|
loop = self._loop
|
||||||
|
if loop is None or not loop.is_running():
|
||||||
|
raise RuntimeError("simplex gateway is not connected")
|
||||||
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
self.send(chat_id, text, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex send request timed out") from exc
|
||||||
|
|
||||||
|
# ---- read ----
|
||||||
|
|
||||||
|
async def mark_read(
|
||||||
|
self, chat_id: str, item_ids=None, timeout: float = 20.0
|
||||||
|
) -> dict:
|
||||||
|
"""Mark a direct chat, or specific items, read on the daemon.
|
||||||
|
|
||||||
|
`/_read chat items @<id> <ids>` clears exactly the reported items'
|
||||||
|
`rcv_new` status (leaving other unread messages intact);
|
||||||
|
`/_read chat @<id>` clears the whole chat. Returns `{ok, type, error}`.
|
||||||
|
A transport failure raises (via `_roundtrip`) — never a fabricated
|
||||||
|
success.
|
||||||
|
"""
|
||||||
|
resp = await self._roundtrip(read_command(chat_id, item_ids), timeout)
|
||||||
|
return parse_read_response(resp)
|
||||||
|
|
||||||
|
def request_mark_read(
|
||||||
|
self, chat_id: str, item_ids=None, timeout: float = 20.0
|
||||||
|
) -> dict:
|
||||||
|
"""Thread-safe read-mark for callers off the event loop.
|
||||||
|
|
||||||
|
Raises `RuntimeError` when no live connection exists and `TimeoutError`
|
||||||
|
when the daemon does not answer in time — never a fabricated success.
|
||||||
|
"""
|
||||||
|
loop = self._loop
|
||||||
|
if loop is None or not loop.is_running():
|
||||||
|
raise RuntimeError("simplex gateway is not connected")
|
||||||
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
self.mark_read(chat_id, item_ids, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex read request timed out") from exc
|
||||||
|
|
||||||
|
# ---- contacts ----
|
||||||
|
|
||||||
|
async def active_user(self, timeout: float = 20.0) -> int:
|
||||||
|
"""Resolve the active user id via `/user`, caching it after first use.
|
||||||
|
|
||||||
|
Falls back to the configured `user_id` when the daemon does not report
|
||||||
|
one, so a profile with a single user keeps working even on a shape drift.
|
||||||
|
"""
|
||||||
|
if self._active_user_id is not None:
|
||||||
|
return self._active_user_id
|
||||||
|
resp = await self._roundtrip("/user", timeout)
|
||||||
|
user = resp.get("user") or {}
|
||||||
|
user_id = user.get("userId")
|
||||||
|
self._active_user_id = int(user_id) if user_id is not None else self.user_id
|
||||||
|
return self._active_user_id
|
||||||
|
|
||||||
|
async def contacts(self, timeout: float = 20.0) -> list[dict]:
|
||||||
|
"""The daemon's contact list as `[{"id", "display_name"}]`.
|
||||||
|
|
||||||
|
`/_contacts <userId>` returns `contactsList` with a `Contact` array.
|
||||||
|
A `chatCmdError` or malformed reply yields an empty list rather than a
|
||||||
|
fabricated contact.
|
||||||
|
"""
|
||||||
|
user_id = await self.active_user(timeout)
|
||||||
|
resp = await self._roundtrip(f"/_contacts {user_id}", timeout)
|
||||||
|
contacts: list[dict] = []
|
||||||
|
for contact in resp.get("contacts") or []:
|
||||||
|
entry = contact_entry(contact)
|
||||||
|
if entry is not None:
|
||||||
|
contacts.append(entry)
|
||||||
|
return contacts
|
||||||
|
|
||||||
|
def request_contacts(self, timeout: float = 20.0) -> list[dict]:
|
||||||
|
"""Thread-safe contact-list lookup 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 list.
|
||||||
|
"""
|
||||||
|
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.contacts(timeout=timeout), loop)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex contacts request timed out") from exc
|
||||||
|
|
||||||
|
# ---- chats / history ----
|
||||||
|
|
||||||
|
async def chats(
|
||||||
|
self, unread_only: bool = True, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Chat previews from the daemon, optionally only those with unread.
|
||||||
|
|
||||||
|
`/_get chats <userId> count=<n> {"type":"filters","favorite":false,
|
||||||
|
"unread":<bool>}` returns `apiChats`. This reads the daemon's persistent
|
||||||
|
state, unlike the bridge's in-memory receive buffer. A `chatCmdError`
|
||||||
|
or malformed reply yields an empty list rather than fabricated chats.
|
||||||
|
"""
|
||||||
|
user_id = await self.active_user(timeout)
|
||||||
|
query = {"type": "filters", "favorite": False, "unread": bool(unread_only)}
|
||||||
|
command = f"/_get chats {user_id} count={max(1, int(count))} {json.dumps(query)}"
|
||||||
|
resp = await self._roundtrip(command, timeout)
|
||||||
|
if resp.get("type") != "apiChats":
|
||||||
|
return []
|
||||||
|
chats: list[dict] = []
|
||||||
|
for achat in resp.get("chats") or []:
|
||||||
|
parsed = parse_chat(achat)
|
||||||
|
if parsed is not None:
|
||||||
|
chats.append(parsed)
|
||||||
|
return chats
|
||||||
|
|
||||||
|
async def chat_history(
|
||||||
|
self, contact_id: str, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Recent messages of one direct chat, newest-aware, from the daemon.
|
||||||
|
|
||||||
|
`/_get chat @<contactId> count=<n>` returns `apiChat`; each message
|
||||||
|
carries `meta.itemStatus` (`rcvNew`/`rcvRead`), so callers can tell
|
||||||
|
unread from read. A malformed reply yields an empty list.
|
||||||
|
"""
|
||||||
|
chat_ref = str(contact_id).strip().lstrip("@")
|
||||||
|
command = f"/_get chat @{chat_ref} count={max(1, int(count))}"
|
||||||
|
resp = await self._roundtrip(command, timeout)
|
||||||
|
if resp.get("type") != "apiChat":
|
||||||
|
return []
|
||||||
|
chat = resp.get("chat")
|
||||||
|
parsed = parse_chat(chat) if isinstance(chat, dict) else None
|
||||||
|
return parsed["messages"] if parsed is not None else []
|
||||||
|
|
||||||
|
def request_chats(
|
||||||
|
self, unread_only: bool = True, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Thread-safe chat-preview lookup 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 list.
|
||||||
|
"""
|
||||||
|
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.chats(unread_only=unread_only, count=count, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex chats request timed out") from exc
|
||||||
|
|
||||||
|
def request_chat_history(
|
||||||
|
self, contact_id: str, count: int = 20, timeout: float = 20.0
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Thread-safe per-chat history lookup 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 list.
|
||||||
|
"""
|
||||||
|
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.chat_history(contact_id, count=count, timeout=timeout), loop
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex chat history request timed out") from exc
|
||||||
|
|
||||||
|
# ---- inbound ----
|
||||||
|
|
||||||
|
async def _consume(self, raw: Any) -> None:
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
corr_id = data.get("corrId")
|
||||||
|
if corr_id is not None:
|
||||||
|
# A correlated command response (round-trip): resolve the waiting
|
||||||
|
# requester. Fire-and-forget commands (`_send`, `_accept`) never
|
||||||
|
# register a future, so their responses are dropped here.
|
||||||
|
future = self._pending.pop(corr_id, None)
|
||||||
|
if future is not None and not future.done():
|
||||||
|
future.set_result(data.get("resp") or {})
|
||||||
|
return
|
||||||
|
resp = data.get("resp") or {}
|
||||||
|
kind = resp.get("type")
|
||||||
|
if kind == "receivedContactRequest":
|
||||||
|
await self._maybe_accept(resp)
|
||||||
|
return
|
||||||
|
if kind != "newChatItems":
|
||||||
|
return
|
||||||
|
for item in resp.get("chatItems", []) or []:
|
||||||
|
message = parse_direct_text_item(item)
|
||||||
|
if message is not None and self._on_message is not None:
|
||||||
|
self._on_message(message)
|
||||||
|
|
||||||
|
async def _maybe_accept(self, resp: dict) -> None:
|
||||||
|
if not self.auto_accept:
|
||||||
|
return
|
||||||
|
command = accept_command(resp)
|
||||||
|
if command is None:
|
||||||
|
return
|
||||||
|
self._corr += 1
|
||||||
|
await self._ws.send(json.dumps({"corrId": f"sf-{self._corr}", "cmd": command}))
|
||||||
|
req = resp.get("contactRequest") or {}
|
||||||
|
contact_id = req.get("contactId_") or req.get("contactId")
|
||||||
|
self._event(
|
||||||
|
"gateway_accepted",
|
||||||
|
contact_request_id=command.split()[-1],
|
||||||
|
contact_id=str(contact_id) if contact_id is not None else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- tracing ----
|
||||||
|
|
||||||
|
def _event(self, kind: str, **fields) -> None:
|
||||||
|
if self.trace is not None:
|
||||||
|
self.trace.append(kind, "?", **fields)
|
||||||
+352
-41
@@ -1,17 +1,89 @@
|
|||||||
"""The skill execution loop: observe -> predict -> act -> observe -> assess.
|
"""The skill execution loop: observe -> act -> observe -> assess.
|
||||||
|
|
||||||
Every SemIf decision made during a run is logged as a training row; the
|
The body is a single `act(ctx, request)` phase. It reads resolved values from
|
||||||
assessment outcome is kept on the row so the dream pass can weigh failed runs.
|
`ctx.config` (the runner resolves the contract from the tiered config and asks
|
||||||
|
the human for anything unresolved), performs the real action, and returns an
|
||||||
|
`ActionResult`. Any SemIf sub-decisions it made ride back on
|
||||||
|
`ActionResult.decisions` and are logged by the runner with the run outcome.
|
||||||
|
|
||||||
|
Assessment is a SemIf decision, not generation: `assess:outcome` decides
|
||||||
|
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
|
||||||
|
config (global -> category -> skill) plus any per-fire answers, and if contract
|
||||||
|
variables are still unresolved it pauses with a `needs_input` instead of
|
||||||
|
invoking the skill. The answer is then either recorded as config (SemIf "record
|
||||||
|
or ask again" choice) or kept as a per-fire input, and the resolution
|
||||||
|
continues.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from .decisions import Request
|
from .decisions import DecisionRequest, Option, Request
|
||||||
from .llm import Assessment, LLMClient
|
|
||||||
from .log import DecisionLog
|
from .log import DecisionLog
|
||||||
from .skills import ActionContext, Prediction, Skill
|
from .skills import (
|
||||||
|
CANNED_CATEGORIES,
|
||||||
|
DETERMINISTIC_CATEGORIES,
|
||||||
|
HOUSEKEEPING_CATEGORY,
|
||||||
|
ActionContext,
|
||||||
|
Skill,
|
||||||
|
SkillStore,
|
||||||
|
bound_output,
|
||||||
|
render_ledger,
|
||||||
|
render_recall,
|
||||||
|
resolve_skill_config,
|
||||||
|
unresolved_variables,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def deterministic_summary(category: str, name: str, success: bool, action_log: str, new_state: str) -> str:
|
||||||
|
"""The run summary, computed without generation.
|
||||||
|
|
||||||
|
Same inputs always produce the same string. Feeds both `RunResult.summary`
|
||||||
|
and `assessment_summary`; consumers keep reading whichever field they read
|
||||||
|
before.
|
||||||
|
"""
|
||||||
|
outcome = "ok" if success else "failed"
|
||||||
|
detail = (action_log or new_state or "").strip()
|
||||||
|
return f"{category}.{name}: {outcome} — {detail}"
|
||||||
|
|
||||||
|
|
||||||
|
# Variable names whose resolved value must never be written to the decision log
|
||||||
|
# (which is a training artifact): credentials, tokens, secrets.
|
||||||
|
_SECRET_NAME_RE = re.compile(r"pass|token|secret|key|credential|auth", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolved_inputs(skill: Skill, config: dict) -> str:
|
||||||
|
"""Render the resolved contract values for the assessment state.
|
||||||
|
|
||||||
|
Gives the outcome decision the full query -> resolution -> action path so it
|
||||||
|
can weigh a wrong resolution, not just a bad action. Secret-named variables
|
||||||
|
are redacted so credentials never reach the decision log.
|
||||||
|
"""
|
||||||
|
contract = skill.contract or {}
|
||||||
|
if not contract:
|
||||||
|
return "(none)"
|
||||||
|
lines = []
|
||||||
|
for name in contract:
|
||||||
|
value = config.get(name)
|
||||||
|
if value is None:
|
||||||
|
rendered = "(unset)"
|
||||||
|
elif _SECRET_NAME_RE.search(name):
|
||||||
|
rendered = "***"
|
||||||
|
else:
|
||||||
|
rendered = str(value)
|
||||||
|
lines.append(f"- {name}: {rendered}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -21,24 +93,170 @@ class RunResult:
|
|||||||
summary: str
|
summary: str
|
||||||
action_log: str
|
action_log: str
|
||||||
new_state: 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
|
decisions_logged: int = 0
|
||||||
|
assessment_summary: str = ""
|
||||||
error: str | None = None
|
error: str | None = None
|
||||||
needs_input: str | None = None
|
needs_input: str | None = None
|
||||||
prediction: Prediction | None = None
|
pre_act: bool = False
|
||||||
|
|
||||||
|
|
||||||
class SkillRunner:
|
class SkillRunner:
|
||||||
def __init__(self, ctx: ActionContext, llm: LLMClient, log: DecisionLog):
|
def __init__(
|
||||||
|
self,
|
||||||
|
ctx: ActionContext,
|
||||||
|
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.ctx = ctx
|
||||||
self.llm = llm
|
|
||||||
self.log = log
|
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 ----
|
||||||
|
|
||||||
|
def _skill_context(self, skill: Skill, request: Request) -> ActionContext:
|
||||||
|
"""Tiered config merged into an ActionContext for one run."""
|
||||||
|
answered = request.meta.get("config_answers", {})
|
||||||
|
if self.store is not None:
|
||||||
|
merged = resolve_skill_config(self.store, skill, self.ctx.config, answered)
|
||||||
|
else:
|
||||||
|
merged = {**self.ctx.config}
|
||||||
|
merged.update(skill.config or {})
|
||||||
|
merged.update(answered)
|
||||||
|
return ActionContext(
|
||||||
|
engine=self.ctx.engine,
|
||||||
|
config=merged,
|
||||||
|
timers=self.ctx.timers,
|
||||||
|
# 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]:
|
||||||
|
if not skill.contract:
|
||||||
|
return []
|
||||||
|
answered = request.meta.get("config_answers", {})
|
||||||
|
if self.store is not None:
|
||||||
|
missing = unresolved_variables(self.store, skill, self.ctx.config, answered)
|
||||||
|
else:
|
||||||
|
merged = {**self.ctx.config}
|
||||||
|
merged.update(skill.config or {})
|
||||||
|
merged.update(answered)
|
||||||
|
missing = [name for name in skill.contract if name not in merged]
|
||||||
|
# A variable the human chose to skip (empty answer) stays unresolved but
|
||||||
|
# must never be re-asked: the run proceeds with it left unset.
|
||||||
|
skipped = request.meta.get("config_skipped", ())
|
||||||
|
return [name for name in missing if name not in skipped]
|
||||||
|
|
||||||
|
def _variable_question(self, skill: Skill, variable: str) -> str:
|
||||||
|
desc = (skill.contract or {}).get(variable, "")
|
||||||
|
return (
|
||||||
|
f"To run {skill.category}.{skill.name} I need `{variable}`. {desc}\n"
|
||||||
|
"Reply with the value, or leave it empty to skip."
|
||||||
|
)
|
||||||
|
|
||||||
|
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool:
|
||||||
|
"""SemIf choice: record this answer as skill config, or ask again each
|
||||||
|
fire. The engine is always real; an unavailable engine propagates and
|
||||||
|
the scheduler marks the app fatal."""
|
||||||
|
decision = DecisionRequest(
|
||||||
|
state=(
|
||||||
|
f"[config] skill {skill.category}.{skill.name} got "
|
||||||
|
f"{variable} = {value}"
|
||||||
|
),
|
||||||
|
question=(
|
||||||
|
f"Record `{variable}` as this skill's config, or ask again "
|
||||||
|
"each time it fires?"
|
||||||
|
),
|
||||||
|
options=[
|
||||||
|
Option("record", "Record it in the skill config."),
|
||||||
|
Option("ask_again", "Ask again each time the skill fires."),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
result = self.ctx.engine.call(decision)
|
||||||
|
self.log.append(
|
||||||
|
decision,
|
||||||
|
result,
|
||||||
|
extra={
|
||||||
|
"phase": "config:record",
|
||||||
|
"run_id": request.id,
|
||||||
|
"skill": f"{skill.category}.{skill.name}",
|
||||||
|
"variable": variable,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return result.selected == "record"
|
||||||
|
|
||||||
|
def _record_answer(self, skill: Skill, request: Request) -> None:
|
||||||
|
"""Persist (or stash per-fire) the human's answer to the last question.
|
||||||
|
|
||||||
|
An empty answer (or the literal "skip") leaves the variable unset and
|
||||||
|
marks it skipped for this run, so the run continues instead of re-asking.
|
||||||
|
`request.user_input` is cleared after consumption so a contract answer
|
||||||
|
does not leak into a later act-driven pause or the skill's own
|
||||||
|
user_input checks.
|
||||||
|
"""
|
||||||
|
variable = request.meta.pop("awaiting_var", None)
|
||||||
|
answer = request.user_input
|
||||||
|
request.user_input = None
|
||||||
|
if variable is None or answer is None:
|
||||||
|
return
|
||||||
|
value = answer.strip()
|
||||||
|
if not value or value.lower() == "skip":
|
||||||
|
request.meta.setdefault("config_skipped", set()).add(variable)
|
||||||
|
return
|
||||||
|
if self._decide_record(skill, request, variable, value):
|
||||||
|
skill.config = {**(skill.config or {}), variable: value}
|
||||||
|
if self.store is not None:
|
||||||
|
self.store.write_config(skill.category, skill.name, skill.config)
|
||||||
|
else:
|
||||||
|
request.meta.setdefault("config_answers", {})[variable] = value
|
||||||
|
|
||||||
|
# ---- run / resume ----
|
||||||
|
|
||||||
def run(self, skill: Skill, request: Request) -> RunResult:
|
def run(self, skill: Skill, request: Request) -> RunResult:
|
||||||
baseline = request.text
|
baseline = request.text
|
||||||
|
missing = self._unresolved(skill, request)
|
||||||
|
if missing:
|
||||||
|
variable = missing[0]
|
||||||
|
request.meta["awaiting_var"] = variable
|
||||||
|
return RunResult(
|
||||||
|
skill=skill.name,
|
||||||
|
success=False,
|
||||||
|
summary="",
|
||||||
|
action_log="",
|
||||||
|
new_state=baseline,
|
||||||
|
needs_input=self._variable_question(skill, variable),
|
||||||
|
pre_act=True,
|
||||||
|
)
|
||||||
|
ctx = self._skill_context(skill, request)
|
||||||
try:
|
try:
|
||||||
prediction = skill.predict(self.ctx, request) if skill.predict else Prediction(text="")
|
action = skill.act(ctx, request)
|
||||||
action = skill.act(self.ctx, request, prediction)
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return RunResult(
|
return RunResult(
|
||||||
skill=skill.name,
|
skill=skill.name,
|
||||||
@@ -56,19 +274,30 @@ class SkillRunner:
|
|||||||
action_log=action.action_log,
|
action_log=action.action_log,
|
||||||
new_state=baseline,
|
new_state=baseline,
|
||||||
needs_input=action.needs_input,
|
needs_input=action.needs_input,
|
||||||
prediction=prediction,
|
|
||||||
)
|
)
|
||||||
return self._finish(skill, request, prediction, action)
|
return self._finish(skill, request, ctx, action)
|
||||||
|
|
||||||
def resume(self, skill: Skill, request: Request, prediction: Prediction) -> RunResult:
|
def resume(
|
||||||
"""Re-invoke act with the human's answer (on request.user_input) and finish.
|
self,
|
||||||
|
skill: Skill,
|
||||||
|
request: Request,
|
||||||
|
pre_act: bool = False,
|
||||||
|
) -> RunResult:
|
||||||
|
"""Re-invoke the run with the human's answer (on request.user_input).
|
||||||
|
|
||||||
predict is not re-run: its SemIf sub-decisions were already made and are
|
For a pre-act pause (contract collection) the answer is recorded and the
|
||||||
logged here, at completion, so their run_ok label reflects the outcome.
|
whole resolution + act path is re-run — more variables may be missing,
|
||||||
|
pausing again until satisfied. For an act-driven pause, `act` is
|
||||||
|
re-invoked; because the body is single-phase there is no frozen
|
||||||
|
prediction to replay, so `act` runs again from the top.
|
||||||
"""
|
"""
|
||||||
|
if pre_act:
|
||||||
|
self._record_answer(skill, request)
|
||||||
|
return self.run(skill, request)
|
||||||
baseline = request.text
|
baseline = request.text
|
||||||
|
ctx = self._skill_context(skill, request)
|
||||||
try:
|
try:
|
||||||
action = skill.act(self.ctx, request, prediction)
|
action = skill.act(ctx, request)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return RunResult(
|
return RunResult(
|
||||||
skill=skill.name,
|
skill=skill.name,
|
||||||
@@ -86,48 +315,130 @@ class SkillRunner:
|
|||||||
action_log=action.action_log,
|
action_log=action.action_log,
|
||||||
new_state=baseline,
|
new_state=baseline,
|
||||||
needs_input=action.needs_input,
|
needs_input=action.needs_input,
|
||||||
prediction=prediction,
|
|
||||||
)
|
)
|
||||||
return self._finish(skill, request, prediction, action)
|
return self._finish(skill, request, ctx, action)
|
||||||
|
|
||||||
|
def _assess(
|
||||||
|
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||||
|
) -> str:
|
||||||
|
"""SemIf assessment: is there any *additional work* to be done?
|
||||||
|
|
||||||
|
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)
|
||||||
|
observed = bound_output(action.action_log, self.result_chars)
|
||||||
|
if not observed:
|
||||||
|
observed = bound_output(action.new_state, self.result_chars)
|
||||||
|
state = (
|
||||||
|
f"skill: {label}\n"
|
||||||
|
f"skill action: {skill.description}\n"
|
||||||
|
f"goal: {request.text}\n"
|
||||||
|
f"resolved inputs:\n{resolved}\n"
|
||||||
|
f"action log:\n{observed}"
|
||||||
|
)
|
||||||
|
recall = render_recall(request)
|
||||||
|
if recall:
|
||||||
|
state += f"\n{recall}"
|
||||||
|
ledger = render_ledger(request.run_ledger)
|
||||||
|
if ledger:
|
||||||
|
state += f"\nsteps already taken:\n{ledger}"
|
||||||
|
decision = DecisionRequest(
|
||||||
|
state=state,
|
||||||
|
question="Is there any additional work to be done to satisfy the request?",
|
||||||
|
options=[
|
||||||
|
Option(
|
||||||
|
"done",
|
||||||
|
"No — the request is satisfied. A definitive 'nothing found' "
|
||||||
|
"or 'nothing to do' result (empty inbox, no unread messages, "
|
||||||
|
"no matching event) counts as done.",
|
||||||
|
),
|
||||||
|
Option(
|
||||||
|
"continue",
|
||||||
|
"Yes — this step worked, but the request is not yet satisfied; "
|
||||||
|
"another skill should run next toward the same request.",
|
||||||
|
),
|
||||||
|
Option(
|
||||||
|
"failed",
|
||||||
|
"The step did not work: the result is an error, a refusal, or "
|
||||||
|
"an unresolved action.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
result = self.ctx.engine.call(decision)
|
||||||
|
self.log.append(
|
||||||
|
decision,
|
||||||
|
result,
|
||||||
|
extra={"phase": "assess:outcome", "run_id": request.id, "skill": label},
|
||||||
|
)
|
||||||
|
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(
|
def _finish(
|
||||||
self, skill: Skill, request: Request, prediction: Prediction, action
|
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||||
) -> RunResult:
|
) -> RunResult:
|
||||||
baseline = request.text
|
action_log = bound_output(action.action_log, self.result_chars)
|
||||||
observed = action.new_state
|
observed = bound_output(action.new_state, self.result_chars)
|
||||||
try:
|
if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES:
|
||||||
assessment: Assessment = self.llm.assess(skill.name, baseline, action.action_log)
|
summary = deterministic_summary(
|
||||||
except Exception as exc:
|
skill.category, skill.name, True, action_log, observed
|
||||||
|
)
|
||||||
return RunResult(
|
return RunResult(
|
||||||
skill=skill.name,
|
skill=skill.name,
|
||||||
success=False,
|
success=True,
|
||||||
summary="",
|
summary=summary,
|
||||||
action_log="",
|
action_log=action_log,
|
||||||
new_state=observed,
|
new_state=observed,
|
||||||
error=str(exc),
|
assessment_summary=summary,
|
||||||
|
outcome="done",
|
||||||
)
|
)
|
||||||
|
verdict = self._assess(skill, request, ctx, action)
|
||||||
|
success = verdict != "failed"
|
||||||
|
|
||||||
run_ok = assessment.success
|
decisions = getattr(action, "decisions", [])
|
||||||
decisions = getattr(prediction, "decisions", [])
|
|
||||||
for decision, result in decisions:
|
for decision, result in decisions:
|
||||||
self.log.append(
|
self.log.append(
|
||||||
decision,
|
decision,
|
||||||
result,
|
result,
|
||||||
extra={
|
extra={
|
||||||
"phase": "predict",
|
"phase": "act",
|
||||||
"skill": skill.name,
|
"skill": skill.name,
|
||||||
"run_ok": run_ok,
|
"run_ok": success,
|
||||||
"run_id": request.id,
|
"run_id": request.id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
summary = deterministic_summary(
|
||||||
|
skill.category, skill.name, success, action_log, observed
|
||||||
|
)
|
||||||
return RunResult(
|
return RunResult(
|
||||||
skill=skill.name,
|
skill=skill.name,
|
||||||
success=assessment.success,
|
success=success,
|
||||||
summary=assessment.summary,
|
summary=summary,
|
||||||
action_log=action.action_log,
|
action_log=action_log,
|
||||||
new_state=observed,
|
new_state=observed,
|
||||||
updated_request=assessment.updated_request,
|
outcome=verdict,
|
||||||
decisions_logged=len(decisions),
|
decisions_logged=len(decisions),
|
||||||
prediction=prediction,
|
assessment_summary=summary,
|
||||||
)
|
)
|
||||||
+1437
-172
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||||
+496
-18
@@ -7,11 +7,14 @@ const state = {
|
|||||||
tree: { categories: {} },
|
tree: { categories: {} },
|
||||||
status: { current: null, pending: null, queue: [], tau: 0.6 },
|
status: { current: null, pending: null, queue: [], tau: 0.6 },
|
||||||
dream: {},
|
dream: {},
|
||||||
|
timers: { pending: [], fired: [] },
|
||||||
selectedRunId: null,
|
selectedRunId: null,
|
||||||
selectedDecisionId: null,
|
selectedDecisionId: null,
|
||||||
phaseFilter: "",
|
phaseFilter: "",
|
||||||
scrub: 0,
|
scrub: 0,
|
||||||
flowSteps: [],
|
flowSteps: [],
|
||||||
|
answerFeedback: null,
|
||||||
|
pendingSubmit: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
async function getJSON(url, opts) {
|
async function getJSON(url, opts) {
|
||||||
@@ -21,20 +24,29 @@ async function getJSON(url, opts) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function refreshAll() {
|
async function refreshAll() {
|
||||||
const [trace, tree, status, dream] = await Promise.all([
|
const [trace, tree, status, dream, timers] = await Promise.all([
|
||||||
getJSON("/api/trace"),
|
getJSON("/api/trace"),
|
||||||
getJSON("/api/tree"),
|
getJSON("/api/tree"),
|
||||||
getJSON("/api/status"),
|
getJSON("/api/status"),
|
||||||
getJSON("/api/dream"),
|
getJSON("/api/dream"),
|
||||||
|
getJSON("/api/timers"),
|
||||||
]);
|
]);
|
||||||
state.runs = trace.runs;
|
state.runs = trace.runs;
|
||||||
state.tree = tree;
|
state.tree = tree;
|
||||||
state.status = status;
|
state.status = status;
|
||||||
state.dream = dream;
|
state.dream = dream;
|
||||||
|
state.timers = timers;
|
||||||
if (state.selectedRunId && !state.runs.some((r) => r.run_id === state.selectedRunId)) {
|
if (state.selectedRunId && !state.runs.some((r) => r.run_id === state.selectedRunId)) {
|
||||||
state.selectedRunId = null;
|
state.selectedRunId = null;
|
||||||
state.selectedDecisionId = null;
|
state.selectedDecisionId = null;
|
||||||
}
|
}
|
||||||
|
const pending = state.pendingSubmit;
|
||||||
|
if (pending && pending.requestId && state.runs.some((r) => r.run_id === pending.requestId)) {
|
||||||
|
state.selectedRunId = pending.requestId;
|
||||||
|
state.selectedDecisionId = null;
|
||||||
|
state.scrub = 0;
|
||||||
|
state.pendingSubmit = null;
|
||||||
|
}
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +65,7 @@ function shortPhase(phase) {
|
|||||||
return phase.replace("navigate:", "nav:");
|
return phase.replace("navigate:", "nav:");
|
||||||
}
|
}
|
||||||
|
|
||||||
const ALL_PHASES = ["gate", "choice", "score", "navigate:category", "navigate:leaf", "predict"];
|
const ALL_PHASES = ["navigate:category", "navigate:leaf", "act"];
|
||||||
|
|
||||||
function optionProbs(row) {
|
function optionProbs(row) {
|
||||||
return (row.options || []).map((o) => ({
|
return (row.options || []).map((o) => ({
|
||||||
@@ -118,14 +130,41 @@ function eventRow(evt) {
|
|||||||
div.textContent = `assessed → ${evt.success ? "ok" : "fail"}`;
|
div.textContent = `assessed → ${evt.success ? "ok" : "fail"}`;
|
||||||
div.title = evt.summary || "";
|
div.title = evt.summary || "";
|
||||||
} else if (evt.kind === "queued") {
|
} else if (evt.kind === "queued") {
|
||||||
div.textContent = `queued (${evt.label})`;
|
div.textContent = "queued";
|
||||||
} else if (evt.kind === "preempted") {
|
|
||||||
div.textContent = `preempted ${evt.preempted}`;
|
|
||||||
} else if (evt.kind === "skill_writing") {
|
} else if (evt.kind === "skill_writing") {
|
||||||
div.textContent = `writing skill ${evt.skill} — ${evt.description} (${evt.model || "codegen"})`;
|
div.textContent = `writing skill ${evt.skill} — ${evt.description} (${evt.model || "codegen"})`;
|
||||||
|
if (evt.contract_ref) {
|
||||||
|
div.title = `CODEGEN.md @ ${evt.contract_ref}${evt.contract_dirty ? "*" : ""}`;
|
||||||
|
}
|
||||||
} else if (evt.kind === "skill_created") {
|
} else if (evt.kind === "skill_created") {
|
||||||
div.textContent = `created ${evt.skill}${evt.written ? " (body written)" : " (stub)"}`;
|
div.textContent = `created ${evt.skill}${evt.written ? " (body written)" : " (stub)"}`;
|
||||||
div.title = evt.body || evt.description || "";
|
div.title = evt.body || evt.description || "";
|
||||||
|
} else if (evt.kind === "skill_testing") {
|
||||||
|
div.textContent = `test attempt ${evt.attempt}: ${evt.passed ? "passed" : "failed"}`;
|
||||||
|
div.title = evt.output || "";
|
||||||
|
} else if (evt.kind === "skill_ready") {
|
||||||
|
div.textContent = `ready: ${evt.skill}`;
|
||||||
|
} else if (evt.kind === "codegen_regen") {
|
||||||
|
div.textContent = `regen → ${evt.selected}`;
|
||||||
|
} else if (evt.kind === "skill_write_failed") {
|
||||||
|
div.textContent = `body write failed: ${evt.skill}`;
|
||||||
|
div.title = evt.message || "";
|
||||||
|
} else if (evt.kind === "skill_restarted") {
|
||||||
|
div.textContent = `restarted body write: ${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_deleted") {
|
||||||
|
div.textContent = `deleted skill: ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_build_cancelled") {
|
||||||
|
div.textContent = `cancelled build: ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_regen_started") {
|
||||||
|
div.textContent = `regenerating skill: ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "config_cleared") {
|
||||||
|
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_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") {
|
} else if (evt.kind === "needs_input") {
|
||||||
div.textContent = "needs input";
|
div.textContent = "needs input";
|
||||||
div.title = evt.question || "";
|
div.title = evt.question || "";
|
||||||
@@ -133,6 +172,8 @@ function eventRow(evt) {
|
|||||||
div.textContent = `answered: ${evt.text || ""}`;
|
div.textContent = `answered: ${evt.text || ""}`;
|
||||||
} else if (evt.kind === "pending_abandoned") {
|
} else if (evt.kind === "pending_abandoned") {
|
||||||
div.textContent = "pending input abandoned";
|
div.textContent = "pending input abandoned";
|
||||||
|
} else if (evt.kind === "timer_fired") {
|
||||||
|
div.textContent = `${evt.timer_kind} fired: ${evt.label}`;
|
||||||
}
|
}
|
||||||
return div;
|
return div;
|
||||||
}
|
}
|
||||||
@@ -196,6 +237,10 @@ function renderFlow() {
|
|||||||
el.innerHTML = "";
|
el.innerHTML = "";
|
||||||
|
|
||||||
if (!run) {
|
if (!run) {
|
||||||
|
if (state.pendingSubmit) {
|
||||||
|
renderPendingFlow(el);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const empty = document.createElement("div");
|
const empty = document.createElement("div");
|
||||||
empty.className = "muted";
|
empty.className = "muted";
|
||||||
empty.textContent = "select a run from the timeline";
|
empty.textContent = "select a run from the timeline";
|
||||||
@@ -215,6 +260,45 @@ function renderFlow() {
|
|||||||
if (i > state.scrub) node.classList.add("dim");
|
if (i > state.scrub) node.classList.add("dim");
|
||||||
el.appendChild(node);
|
el.appendChild(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (run.decisions.length === 0 && runInFlight(run)) {
|
||||||
|
if (steps.length) el.appendChild(edge(steps[steps.length - 1].data));
|
||||||
|
el.appendChild(pendingIndicatorNode("decisions in process…"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const RESTING_EVENTS = ["ran", "rejected", "dropped", "error", "assessed", "needs_input", "pending_abandoned"];
|
||||||
|
|
||||||
|
function runInFlight(run) {
|
||||||
|
return !run.events.some((evt) => RESTING_EVENTS.includes(evt.kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPendingFlow(el) {
|
||||||
|
const node = document.createElement("div");
|
||||||
|
node.className = "node event-node pending-request";
|
||||||
|
const kind = document.createElement("div");
|
||||||
|
kind.className = "evt-kind";
|
||||||
|
kind.textContent = "submitted";
|
||||||
|
node.appendChild(kind);
|
||||||
|
const body = document.createElement("div");
|
||||||
|
body.className = "node-question";
|
||||||
|
body.textContent = state.pendingSubmit.text;
|
||||||
|
node.appendChild(body);
|
||||||
|
el.appendChild(node);
|
||||||
|
el.appendChild(edge({ kind: "event" }));
|
||||||
|
el.appendChild(pendingIndicatorNode("decisions in process…"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pendingIndicatorNode(text) {
|
||||||
|
const node = document.createElement("div");
|
||||||
|
node.className = "node pending-indicator";
|
||||||
|
const dot = document.createElement("span");
|
||||||
|
dot.className = "spinner";
|
||||||
|
node.appendChild(dot);
|
||||||
|
const label = document.createElement("span");
|
||||||
|
label.textContent = text;
|
||||||
|
node.appendChild(label);
|
||||||
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
function edge(prev) {
|
function edge(prev) {
|
||||||
@@ -327,16 +411,16 @@ function eventNode(evt) {
|
|||||||
body.className = "node-question";
|
body.className = "node-question";
|
||||||
if (evt.kind === "assessed") {
|
if (evt.kind === "assessed") {
|
||||||
body.textContent = evt.summary || "";
|
body.textContent = evt.summary || "";
|
||||||
if (evt.updated_request) {
|
} else if (evt.kind === "continued") {
|
||||||
const req = document.createElement("div");
|
body.textContent = `→ next step: ${evt.skill || ""}`;
|
||||||
req.className = "muted";
|
const outcome = document.createElement("div");
|
||||||
req.textContent = `→ requeued: ${evt.updated_request}`;
|
outcome.className = "muted";
|
||||||
node.appendChild(req);
|
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") {
|
} else if (evt.kind === "queued") {
|
||||||
body.textContent = `urgency ${evt.label} (weight ${Number(evt.weight || 0).toFixed(2)})`;
|
body.textContent = "queued";
|
||||||
} else if (evt.kind === "preempted") {
|
|
||||||
body.textContent = `interrupted ${evt.preempted}, requeued with state`;
|
|
||||||
} else if (evt.kind === "dropped") {
|
} else if (evt.kind === "dropped") {
|
||||||
body.textContent = evt.reason || "";
|
body.textContent = evt.reason || "";
|
||||||
} else if (evt.kind === "skill_writing") {
|
} else if (evt.kind === "skill_writing") {
|
||||||
@@ -349,6 +433,12 @@ function eventNode(evt) {
|
|||||||
desc.className = "muted";
|
desc.className = "muted";
|
||||||
desc.textContent = evt.description || "";
|
desc.textContent = evt.description || "";
|
||||||
body.appendChild(desc);
|
body.appendChild(desc);
|
||||||
|
if (evt.contract_ref) {
|
||||||
|
const ref = document.createElement("div");
|
||||||
|
ref.className = "muted";
|
||||||
|
ref.textContent = `CODEGEN.md @ ${evt.contract_ref}${evt.contract_dirty ? "*" : ""}`;
|
||||||
|
body.appendChild(ref);
|
||||||
|
}
|
||||||
const badge = document.createElement("span");
|
const badge = document.createElement("span");
|
||||||
badge.className = "writing-badge";
|
badge.className = "writing-badge";
|
||||||
badge.textContent = "writing skill body…";
|
badge.textContent = "writing skill body…";
|
||||||
@@ -369,6 +459,68 @@ function eventNode(evt) {
|
|||||||
node.appendChild(p);
|
node.appendChild(p);
|
||||||
}
|
}
|
||||||
node.classList.add(evt.written ? "ok" : "stub");
|
node.classList.add(evt.written ? "ok" : "stub");
|
||||||
|
} else if (evt.kind === "skill_testing") {
|
||||||
|
node.classList.add(evt.passed ? "ok" : "fail");
|
||||||
|
body.textContent = `test attempt ${evt.attempt}: ${evt.passed ? "passed" : "failed"}`;
|
||||||
|
if (evt.output) {
|
||||||
|
const out = document.createElement("div");
|
||||||
|
out.className = "muted";
|
||||||
|
out.textContent = evt.output.slice(0, 200);
|
||||||
|
body.appendChild(out);
|
||||||
|
}
|
||||||
|
} else if (evt.kind === "skill_ready") {
|
||||||
|
node.classList.add("ok");
|
||||||
|
const title = document.createElement("div");
|
||||||
|
title.className = "skill-title";
|
||||||
|
title.textContent = `${evt.skill} — ready`;
|
||||||
|
body.appendChild(title);
|
||||||
|
if (evt.contract_vars) {
|
||||||
|
const vars = document.createElement("div");
|
||||||
|
vars.className = "muted";
|
||||||
|
vars.textContent = `contract: ${evt.contract_vars.join(", ")}`;
|
||||||
|
body.appendChild(vars);
|
||||||
|
}
|
||||||
|
} else if (evt.kind === "codegen_regen") {
|
||||||
|
body.textContent = `regen decision → ${evt.selected || ""}`;
|
||||||
|
if (evt.reason) {
|
||||||
|
const out = document.createElement("div");
|
||||||
|
out.className = "muted";
|
||||||
|
out.textContent = evt.reason.slice(0, 160);
|
||||||
|
body.appendChild(out);
|
||||||
|
}
|
||||||
|
} else if (evt.kind === "skill_write_failed") {
|
||||||
|
node.classList.add("stub");
|
||||||
|
const title = document.createElement("div");
|
||||||
|
title.className = "skill-title";
|
||||||
|
title.textContent = `${evt.skill} — body write failed`;
|
||||||
|
body.appendChild(title);
|
||||||
|
const msg = document.createElement("div");
|
||||||
|
msg.className = "muted";
|
||||||
|
msg.textContent = evt.message || "";
|
||||||
|
body.appendChild(msg);
|
||||||
|
const btn = document.createElement("button");
|
||||||
|
btn.className = "restart-btn";
|
||||||
|
btn.textContent = "restart";
|
||||||
|
btn.addEventListener("click", () => restartSkill(evt.category, evt.skill));
|
||||||
|
node.appendChild(btn);
|
||||||
|
} else if (evt.kind === "skill_restarted") {
|
||||||
|
body.textContent = `restarted body write for ${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_deleted") {
|
||||||
|
node.classList.add("stub");
|
||||||
|
body.textContent = `deleted ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_build_cancelled") {
|
||||||
|
node.classList.add("stub");
|
||||||
|
body.textContent = `cancelled build for ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "skill_regen_started") {
|
||||||
|
body.textContent = `regenerating ${evt.category}.${evt.skill}`;
|
||||||
|
} else if (evt.kind === "config_cleared") {
|
||||||
|
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_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") {
|
} else if (evt.kind === "needs_input") {
|
||||||
node.classList.add("needs-input");
|
node.classList.add("needs-input");
|
||||||
body.textContent = `awaiting input: ${evt.question || ""}`;
|
body.textContent = `awaiting input: ${evt.question || ""}`;
|
||||||
@@ -376,6 +528,9 @@ function eventNode(evt) {
|
|||||||
body.textContent = `answered: ${evt.text || ""}`;
|
body.textContent = `answered: ${evt.text || ""}`;
|
||||||
} else if (evt.kind === "pending_abandoned") {
|
} else if (evt.kind === "pending_abandoned") {
|
||||||
body.textContent = "pending input abandoned";
|
body.textContent = "pending input abandoned";
|
||||||
|
} else if (evt.kind === "timer_fired") {
|
||||||
|
node.classList.add("ok");
|
||||||
|
body.textContent = `${evt.timer_kind} fired: ${evt.label}`;
|
||||||
} else {
|
} else {
|
||||||
body.textContent = evt.summary || evt.text || "";
|
body.textContent = evt.summary || evt.text || "";
|
||||||
}
|
}
|
||||||
@@ -425,6 +580,117 @@ function kv(k, v) {
|
|||||||
|
|
||||||
/* ---------------- skill tree ---------------- */
|
/* ---------------- skill tree ---------------- */
|
||||||
|
|
||||||
|
async function restartSkill(category, name) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON("/api/restart", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ category, skill: name }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`restart failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function housekeepingAction(path, category, name) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON(path, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ category, skill: name }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`${path} failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setSkillMode(category, mode) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON("/api/new-skill-mode", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ category, mode }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`mode change failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
function actionBtn(label, title, onClick) {
|
||||||
|
const btn = document.createElement("button");
|
||||||
|
btn.className = "restart-btn";
|
||||||
|
btn.textContent = label;
|
||||||
|
btn.title = title;
|
||||||
|
btn.addEventListener("click", onClick);
|
||||||
|
return btn;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function answerQuestion(id, text) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON("/api/questions", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ id, text }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`answer failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveRepair(id, action) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON("/api/repair", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ id, action }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`repair failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveApproval(id, approve) {
|
||||||
|
try {
|
||||||
|
const res = await getJSON("/api/approvals", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ id, approve }),
|
||||||
|
});
|
||||||
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
} catch (err) {
|
||||||
|
flash(`approval failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
await refreshAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
function skillStatusBadge(status, category, name) {
|
||||||
|
const span = document.createElement("span");
|
||||||
|
if (status === "writing") {
|
||||||
|
span.className = "sbadge writing";
|
||||||
|
span.textContent = "writing…";
|
||||||
|
} else if (status === "stub") {
|
||||||
|
span.className = "sbadge stub";
|
||||||
|
span.textContent = "stub";
|
||||||
|
const btn = document.createElement("button");
|
||||||
|
btn.className = "restart-btn";
|
||||||
|
btn.textContent = "restart";
|
||||||
|
btn.title = `write the body for ${category}.${name}`;
|
||||||
|
btn.addEventListener("click", () => restartSkill(category, name));
|
||||||
|
span.appendChild(btn);
|
||||||
|
}
|
||||||
|
return span;
|
||||||
|
}
|
||||||
|
|
||||||
function renderTree() {
|
function renderTree() {
|
||||||
const el = $("#skill-tree");
|
const el = $("#skill-tree");
|
||||||
el.innerHTML = "";
|
el.innerHTML = "";
|
||||||
@@ -435,6 +701,18 @@ function renderTree() {
|
|||||||
const name = document.createElement("div");
|
const name = document.createElement("div");
|
||||||
name.className = "cat-name";
|
name.className = "cat-name";
|
||||||
name.textContent = cat;
|
name.textContent = cat;
|
||||||
|
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);
|
||||||
|
}
|
||||||
div.appendChild(name);
|
div.appendChild(name);
|
||||||
for (const skill of skills) {
|
for (const skill of skills) {
|
||||||
const row = document.createElement("div");
|
const row = document.createElement("div");
|
||||||
@@ -446,6 +724,44 @@ function renderTree() {
|
|||||||
desc.textContent = skill.description;
|
desc.textContent = skill.description;
|
||||||
row.appendChild(nm);
|
row.appendChild(nm);
|
||||||
row.appendChild(desc);
|
row.appendChild(desc);
|
||||||
|
if (skill.integration && skill.integration.service && skill.integration.service !== "unknown") {
|
||||||
|
const ig = document.createElement("span");
|
||||||
|
ig.className = "sdesc";
|
||||||
|
ig.textContent = `${skill.integration.service} · ${skill.integration.transport}`;
|
||||||
|
row.appendChild(ig);
|
||||||
|
}
|
||||||
|
if (skill.status === "ready" && skill.integration_source && skill.integration_source !== "declared") {
|
||||||
|
const un = document.createElement("span");
|
||||||
|
un.className = "sbadge stub";
|
||||||
|
un.textContent = "unverified";
|
||||||
|
un.title = "no valid INTEGRATION declaration; the body was inferred";
|
||||||
|
row.appendChild(un);
|
||||||
|
}
|
||||||
|
row.appendChild(skillStatusBadge(skill.status, cat, skill.name));
|
||||||
|
if (skill.origin !== "builtin") {
|
||||||
|
row.appendChild(
|
||||||
|
actionBtn("delete", `delete ${cat}.${skill.name}`, () =>
|
||||||
|
housekeepingAction("/api/delete", cat, skill.name)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
row.appendChild(
|
||||||
|
actionBtn("regen", `regenerate ${cat}.${skill.name}`, () =>
|
||||||
|
housekeepingAction("/api/regen", cat, skill.name)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
row.appendChild(
|
||||||
|
actionBtn("clear config", `clear recorded config for ${cat}.${skill.name}`, () =>
|
||||||
|
housekeepingAction("/api/clear-config", cat, skill.name)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (skill.status === "writing") {
|
||||||
|
row.appendChild(
|
||||||
|
actionBtn("cancel", `cancel the build for ${cat}.${skill.name}`, () =>
|
||||||
|
housekeepingAction("/api/cancel-build", cat, skill.name)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
div.appendChild(row);
|
div.appendChild(row);
|
||||||
}
|
}
|
||||||
el.appendChild(div);
|
el.appendChild(div);
|
||||||
@@ -454,6 +770,32 @@ function renderTree() {
|
|||||||
|
|
||||||
/* ---------------- status / dream ---------------- */
|
/* ---------------- status / dream ---------------- */
|
||||||
|
|
||||||
|
function renderTimers() {
|
||||||
|
const el = $("#timers");
|
||||||
|
el.innerHTML = "";
|
||||||
|
const pending = state.timers.pending || [];
|
||||||
|
const fired = state.timers.fired || [];
|
||||||
|
if (!pending.length && !fired.length) {
|
||||||
|
const empty = document.createElement("div");
|
||||||
|
empty.className = "muted";
|
||||||
|
empty.textContent = "no timers (in-process; not kept across restarts)";
|
||||||
|
el.appendChild(empty);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const t of pending) {
|
||||||
|
const row = document.createElement("div");
|
||||||
|
row.className = "pending-line";
|
||||||
|
row.textContent = `⏳ ${t.kind} ${t.label} → ${t.due_at_local.slice(0, 16).replace("T", " ")}`;
|
||||||
|
el.appendChild(row);
|
||||||
|
}
|
||||||
|
for (const f of fired.slice(-5).reverse()) {
|
||||||
|
const row = document.createElement("div");
|
||||||
|
row.className = "pending-line";
|
||||||
|
row.textContent = `⏰ ${f.message}`;
|
||||||
|
el.appendChild(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function renderStatus() {
|
function renderStatus() {
|
||||||
const el = $("#status");
|
const el = $("#status");
|
||||||
el.innerHTML = "";
|
el.innerHTML = "";
|
||||||
@@ -481,15 +823,117 @@ function renderStatus() {
|
|||||||
q.className = "muted";
|
q.className = "muted";
|
||||||
q.style.marginTop = "8px";
|
q.style.marginTop = "8px";
|
||||||
q.textContent = state.status.queue
|
q.textContent = state.status.queue
|
||||||
.map((item) => `${item.id} w=${item.weight.toFixed(2)} ${item.text}`)
|
.map((item) => `${item.id} ${item.text}`)
|
||||||
.join("\n") || "queue empty";
|
.join("\n") || "queue empty";
|
||||||
el.appendChild(q);
|
el.appendChild(q);
|
||||||
|
|
||||||
const pending = state.status.pending;
|
const pending = state.status.pending;
|
||||||
$("#answer-form").classList.toggle("hidden", !pending);
|
$("#answer-form").classList.toggle("hidden", !pending);
|
||||||
if (pending) {
|
if (pending) {
|
||||||
$("#answer-input").placeholder = `${pending.skill}: ${pending.question}`;
|
$("#answer-input").placeholder = `${pending.skill}: ${pending.question} (empty to skip)`;
|
||||||
|
const p = document.createElement("div");
|
||||||
|
p.className = "pending-line";
|
||||||
|
p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`;
|
||||||
|
el.appendChild(p);
|
||||||
}
|
}
|
||||||
|
renderQuestions();
|
||||||
|
renderAnswerFeedback();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderQuestions() {
|
||||||
|
const el = $("#status");
|
||||||
|
for (const q of state.status.questions || []) {
|
||||||
|
const box = document.createElement("div");
|
||||||
|
box.className = "pending-line";
|
||||||
|
const label = document.createElement("div");
|
||||||
|
label.textContent = `? ${q.skill}: ${q.question}`;
|
||||||
|
const form = document.createElement("form");
|
||||||
|
const input = document.createElement("input");
|
||||||
|
input.type = "text";
|
||||||
|
input.placeholder = "answer (empty to skip)";
|
||||||
|
const btn = document.createElement("button");
|
||||||
|
btn.type = "submit";
|
||||||
|
btn.textContent = "answer";
|
||||||
|
form.appendChild(input);
|
||||||
|
form.appendChild(btn);
|
||||||
|
form.addEventListener("submit", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
answerQuestion(q.id, input.value.trim());
|
||||||
|
input.value = "";
|
||||||
|
});
|
||||||
|
box.appendChild(label);
|
||||||
|
box.appendChild(form);
|
||||||
|
el.appendChild(box);
|
||||||
|
}
|
||||||
|
for (const r of state.status.repairs || []) {
|
||||||
|
const box = document.createElement("div");
|
||||||
|
box.className = "pending-line";
|
||||||
|
const label = document.createElement("div");
|
||||||
|
label.textContent = `repair ${r.skill}: ${r.failure.slice(0, 160)}`;
|
||||||
|
box.appendChild(label);
|
||||||
|
const actions = document.createElement("div");
|
||||||
|
for (const action of ["retry", "repair_skill", "ask_user", "no_repair"]) {
|
||||||
|
const btn = document.createElement("button");
|
||||||
|
btn.type = "button";
|
||||||
|
btn.textContent = action;
|
||||||
|
btn.className = action === r.selected ? "primary" : "";
|
||||||
|
btn.addEventListener("click", () => resolveRepair(r.id, action));
|
||||||
|
actions.appendChild(btn);
|
||||||
|
}
|
||||||
|
box.appendChild(actions);
|
||||||
|
el.appendChild(box);
|
||||||
|
}
|
||||||
|
for (const a of state.status.approvals || []) {
|
||||||
|
const box = document.createElement("div");
|
||||||
|
box.className = "pending-line";
|
||||||
|
const target = a.kind === "category" ? a.category : `${a.category}.${a.skill}`;
|
||||||
|
const label = document.createElement("div");
|
||||||
|
label.textContent = `approve new ${a.kind} ${target}: ${a.description}`;
|
||||||
|
box.appendChild(label);
|
||||||
|
const actions = document.createElement("div");
|
||||||
|
const yes = document.createElement("button");
|
||||||
|
yes.type = "button";
|
||||||
|
yes.textContent = "approve";
|
||||||
|
yes.className = "primary";
|
||||||
|
yes.addEventListener("click", () => resolveApproval(a.id, true));
|
||||||
|
const no = document.createElement("button");
|
||||||
|
no.type = "button";
|
||||||
|
no.textContent = "deny";
|
||||||
|
no.addEventListener("click", () => resolveApproval(a.id, false));
|
||||||
|
actions.appendChild(yes);
|
||||||
|
actions.appendChild(no);
|
||||||
|
box.appendChild(actions);
|
||||||
|
el.appendChild(box);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAnswerFeedback() {
|
||||||
|
const el = $("#answer-feedback");
|
||||||
|
const fb = state.answerFeedback;
|
||||||
|
el.className = "hidden";
|
||||||
|
if (!fb) return;
|
||||||
|
if (fb.inflight) {
|
||||||
|
el.className = "";
|
||||||
|
el.textContent = "answering…";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fb.status === "error") {
|
||||||
|
el.className = "feedback-error";
|
||||||
|
el.textContent = `✗ ${fb.detail}`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let line = `✓ consumed "${fb.text}"`;
|
||||||
|
if (fb.status === "needs_input") {
|
||||||
|
el.className = "feedback-awaiting";
|
||||||
|
line += ` → awaiting: ${fb.detail}`;
|
||||||
|
if (fb.askedQuestion && fb.detail === fb.askedQuestion) {
|
||||||
|
line += " (answer received; the skill asked again)";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
el.className = "";
|
||||||
|
line += ` → ${fb.detail}`;
|
||||||
|
}
|
||||||
|
el.textContent = line;
|
||||||
}
|
}
|
||||||
|
|
||||||
function stat(k, v) {
|
function stat(k, v) {
|
||||||
@@ -550,6 +994,12 @@ $("#submit-form").addEventListener("submit", async (e) => {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const text = $("#query-input").value.trim();
|
const text = $("#query-input").value.trim();
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
|
$("#query-input").value = "";
|
||||||
|
state.pendingSubmit = { text, requestId: null };
|
||||||
|
state.selectedRunId = null;
|
||||||
|
state.selectedDecisionId = null;
|
||||||
|
state.scrub = 0;
|
||||||
|
render();
|
||||||
try {
|
try {
|
||||||
const res = await getJSON("/api/submit", {
|
const res = await getJSON("/api/submit", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -557,10 +1007,15 @@ $("#submit-form").addEventListener("submit", async (e) => {
|
|||||||
body: JSON.stringify({ text }),
|
body: JSON.stringify({ text }),
|
||||||
});
|
});
|
||||||
flash(`[${res.status}] ${res.detail}`);
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
if (res.request_id) {
|
||||||
|
state.pendingSubmit.requestId = res.request_id;
|
||||||
|
} else {
|
||||||
|
state.pendingSubmit = null;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
flash(`submit failed: ${err.message}`);
|
flash(`submit failed: ${err.message}`);
|
||||||
|
state.pendingSubmit = null;
|
||||||
}
|
}
|
||||||
$("#query-input").value = "";
|
|
||||||
await refreshAll();
|
await refreshAll();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -568,6 +1023,14 @@ $("#answer-form").addEventListener("submit", async (e) => {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const text = $("#answer-input").value.trim();
|
const text = $("#answer-input").value.trim();
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
|
const btn = $("#answer-btn");
|
||||||
|
const pending = state.status.pending || {};
|
||||||
|
const runId = pending.run_id || null;
|
||||||
|
const askedQuestion = pending.question || null;
|
||||||
|
$("#answer-input").value = "";
|
||||||
|
btn.disabled = true;
|
||||||
|
state.answerFeedback = { inflight: true };
|
||||||
|
renderAnswerFeedback();
|
||||||
try {
|
try {
|
||||||
const res = await getJSON("/api/answer", {
|
const res = await getJSON("/api/answer", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -575,11 +1038,25 @@ $("#answer-form").addEventListener("submit", async (e) => {
|
|||||||
body: JSON.stringify({ text }),
|
body: JSON.stringify({ text }),
|
||||||
});
|
});
|
||||||
flash(`[${res.status}] ${res.detail}`);
|
flash(`[${res.status}] ${res.detail}`);
|
||||||
|
state.answerFeedback = { status: res.status, detail: res.detail, text, askedQuestion };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
flash(`answer failed: ${err.message}`);
|
flash(`answer failed: ${err.message}`);
|
||||||
|
state.answerFeedback = {
|
||||||
|
status: "error",
|
||||||
|
detail: `answer failed: ${err.message}`,
|
||||||
|
text,
|
||||||
|
askedQuestion,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
$("#answer-input").value = "";
|
|
||||||
await refreshAll();
|
await refreshAll();
|
||||||
|
if (runId && state.runs.some((r) => r.run_id === runId)) {
|
||||||
|
state.selectedRunId = runId;
|
||||||
|
state.selectedDecisionId = null;
|
||||||
|
state.scrub = 0;
|
||||||
|
render();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
$("#refresh-btn").addEventListener("click", async () => {
|
$("#refresh-btn").addEventListener("click", async () => {
|
||||||
@@ -605,6 +1082,7 @@ function render() {
|
|||||||
renderFlow();
|
renderFlow();
|
||||||
renderInspector();
|
renderInspector();
|
||||||
renderTree();
|
renderTree();
|
||||||
|
renderTimers();
|
||||||
renderStatus();
|
renderStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,14 +15,15 @@
|
|||||||
<section class="inputbar">
|
<section class="inputbar">
|
||||||
<form id="submit-form">
|
<form id="submit-form">
|
||||||
<input id="query-input" type="text" autocomplete="off" spellcheck="false"
|
<input id="query-input" type="text" autocomplete="off" spellcheck="false"
|
||||||
placeholder="type a request, e.g. 'send my girlfriend an email that I'm running late'">
|
placeholder="type a request, e.g. 'what is the next event on my nextcloud calendar?'">
|
||||||
<button type="submit">submit</button>
|
<button type="submit">submit</button>
|
||||||
</form>
|
</form>
|
||||||
<form id="answer-form" class="hidden">
|
<form id="answer-form" class="hidden">
|
||||||
<input id="answer-input" type="text" autocomplete="off" spellcheck="false"
|
<input id="answer-input" type="text" autocomplete="off" spellcheck="false"
|
||||||
placeholder="answer the pending question">
|
placeholder="answer the pending question (empty to skip)">
|
||||||
<button type="submit">answer</button>
|
<button type="submit" id="answer-btn">answer</button>
|
||||||
</form>
|
</form>
|
||||||
|
<div id="answer-feedback" class="hidden"></div>
|
||||||
<button id="refresh-btn" type="button" title="reload trace">refresh</button>
|
<button id="refresh-btn" type="button" title="reload trace">refresh</button>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -55,6 +56,10 @@
|
|||||||
<button id="relabel-btn" type="button" class="small" disabled>relabel…</button>
|
<button id="relabel-btn" type="button" class="small" disabled>relabel…</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="inspector" class="inspector"></div>
|
<div id="inspector" class="inspector"></div>
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2>Timers</h2>
|
||||||
|
</div>
|
||||||
|
<div id="timers" class="status"></div>
|
||||||
<div class="panel-head">
|
<div class="panel-head">
|
||||||
<h2>Skill tree</h2>
|
<h2>Skill tree</h2>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ html, body {
|
|||||||
|
|
||||||
.inputbar {
|
.inputbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
padding: 10px 16px;
|
padding: 10px 16px;
|
||||||
background: var(--panel-2);
|
background: var(--panel-2);
|
||||||
@@ -56,6 +57,19 @@ html, body {
|
|||||||
|
|
||||||
.inputbar form { display: flex; flex: 1; gap: 8px; }
|
.inputbar form { display: flex; flex: 1; gap: 8px; }
|
||||||
|
|
||||||
|
#answer-feedback {
|
||||||
|
flex: 1 1 100%;
|
||||||
|
padding: 6px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--ok);
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#answer-feedback.feedback-error { color: var(--fail); border-color: var(--fail); }
|
||||||
|
#answer-feedback.feedback-awaiting { color: var(--warn); border-color: var(--warn); }
|
||||||
|
|
||||||
#query-input {
|
#query-input {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
background: var(--bg);
|
background: var(--bg);
|
||||||
@@ -169,10 +183,8 @@ select {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.pill.gate { background: #2b3a52; color: #9ec1ff; }
|
.pill.gate { background: #2b3a52; color: #9ec1ff; }
|
||||||
.pill.choice { background: #4a3a2b; color: #ffd59e; }
|
|
||||||
.pill.score { background: #3a2b4a; color: #d59eff; }
|
|
||||||
.pill.navigate { background: #2b4a3a; color: #9effd5; }
|
.pill.navigate { background: #2b4a3a; color: #9effd5; }
|
||||||
.pill.predict { background: #2b464a; color: #9eeaff; }
|
.pill.act { background: #2b464a; color: #9eeaff; }
|
||||||
.pill.assess { background: #4a2b2b; color: #ff9e9e; }
|
.pill.assess { background: #4a2b2b; color: #ff9e9e; }
|
||||||
|
|
||||||
.human-star { color: var(--human); }
|
.human-star { color: var(--human); }
|
||||||
@@ -303,6 +315,31 @@ select {
|
|||||||
50% { opacity: 0.35; }
|
50% { opacity: 0.35; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- pending submit ---------- */
|
||||||
|
|
||||||
|
.node.pending-indicator {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
width: auto;
|
||||||
|
color: var(--warn);
|
||||||
|
font-size: 12px;
|
||||||
|
border-style: dashed;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node.pending-indicator:hover { border-color: var(--line); }
|
||||||
|
|
||||||
|
.pending-indicator .spinner {
|
||||||
|
width: 9px;
|
||||||
|
height: 9px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--warn);
|
||||||
|
animation: writing-pulse 1.2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node.event-node.pending-request { border-left: 3px solid var(--accent); }
|
||||||
|
|
||||||
/* ---------- inspector / tree / status ---------- */
|
/* ---------- inspector / tree / status ---------- */
|
||||||
|
|
||||||
.right { border-right: none; }
|
.right { border-right: none; }
|
||||||
@@ -324,10 +361,46 @@ pre.json {
|
|||||||
.skill-row { display: flex; gap: 6px; align-items: baseline; padding-left: 8px; font-size: 11px; }
|
.skill-row { display: flex; gap: 6px; align-items: baseline; padding-left: 8px; font-size: 11px; }
|
||||||
.skill-row .sdesc { color: var(--muted); }
|
.skill-row .sdesc { color: var(--muted); }
|
||||||
|
|
||||||
|
.sbadge {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 10px;
|
||||||
|
white-space: nowrap;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
.sbadge.writing { color: var(--warn); }
|
||||||
|
.sbadge.stub { color: var(--muted); }
|
||||||
|
|
||||||
|
.restart-btn {
|
||||||
|
padding: 1px 6px;
|
||||||
|
font-size: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.lock-btn {
|
||||||
|
margin-left: 6px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
}
|
||||||
|
|
||||||
.stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
|
.stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
|
||||||
.stat-grid .stat { background: var(--panel-2); border-radius: 4px; padding: 4px 6px; }
|
.stat-grid .stat { background: var(--panel-2); border-radius: 4px; padding: 4px 6px; }
|
||||||
.stat-grid .stat .v { font-weight: 700; }
|
.stat-grid .stat .v { font-weight: 700; }
|
||||||
|
|
||||||
|
.pending-line {
|
||||||
|
margin: 8px 0 4px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
background: var(--panel-2);
|
||||||
|
border-radius: 4px;
|
||||||
|
border-left: 3px solid var(--warn);
|
||||||
|
color: var(--warn);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- scrubber ---------- */
|
/* ---------- scrubber ---------- */
|
||||||
|
|
||||||
.scrub-label { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); }
|
.scrub-label { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); }
|
||||||
|
|||||||
@@ -0,0 +1,287 @@
|
|||||||
|
"""In-process timer and alarm service.
|
||||||
|
|
||||||
|
A skill body schedules a timer or alarm through `ctx.timers`. One background
|
||||||
|
daemon thread wakes at the earliest due time, records a `timer_fired` trace
|
||||||
|
event, and exposes the fired timer so a front end can notify the user (the REPL
|
||||||
|
prints it, the gateway routes it to the originating chat, the dashboard shows
|
||||||
|
it). Timers live in the process that set them and do **not** survive a restart
|
||||||
|
(persistence is future work) — so the agent never claims a timer outlived a
|
||||||
|
shutdown it did not.
|
||||||
|
|
||||||
|
This is real local compute, not a simulation: the thread fires on the host
|
||||||
|
clock and the notification carries the real due/fired times.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import heapq
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, tzinfo
|
||||||
|
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_timezone(config) -> tzinfo | None:
|
||||||
|
"""The tzinfo named by `config["timezone"]`, or None for host local.
|
||||||
|
|
||||||
|
An empty/absent name or an unknown zone falls back to the host's local
|
||||||
|
timezone (None), so a misconfigured value never breaks a run.
|
||||||
|
"""
|
||||||
|
name = str((config or {}).get("timezone", "") or "").strip()
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return ZoneInfo(name)
|
||||||
|
except (ZoneInfoNotFoundError, ValueError, KeyError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def local_now(config=None) -> datetime:
|
||||||
|
"""Current time, aware: the configured timezone, else the host's local zone."""
|
||||||
|
tz = resolve_timezone(config)
|
||||||
|
if tz is None:
|
||||||
|
return datetime.now().astimezone()
|
||||||
|
return datetime.now(tz)
|
||||||
|
|
||||||
|
|
||||||
|
def format_duration(seconds: float) -> str:
|
||||||
|
"""Human text for a duration, e.g. 300 -> '5 minutes', 5400 -> '1 hour 30 minutes'."""
|
||||||
|
total = int(round(float(seconds)))
|
||||||
|
if total < 60:
|
||||||
|
return f"{total} second" + ("s" if total != 1 else "")
|
||||||
|
minutes, secs = divmod(total, 60)
|
||||||
|
if minutes < 60:
|
||||||
|
text = f"{minutes} minute" + ("s" if minutes != 1 else "")
|
||||||
|
if secs:
|
||||||
|
text += f" {secs} second" + ("s" if secs != 1 else "")
|
||||||
|
return text
|
||||||
|
hours, minutes = divmod(minutes, 60)
|
||||||
|
text = f"{hours} hour" + ("s" if hours != 1 else "")
|
||||||
|
if minutes:
|
||||||
|
text += f" {minutes} minute" + ("s" if minutes != 1 else "")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Timer:
|
||||||
|
"""One scheduled timer or alarm."""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
run_id: str
|
||||||
|
kind: str # "timer" | "alarm"
|
||||||
|
label: str
|
||||||
|
source: str
|
||||||
|
due_at: float # epoch seconds
|
||||||
|
created_at: float = field(default_factory=time.time)
|
||||||
|
# tzinfo used to format the due time for the user (None = host local).
|
||||||
|
tz: tzinfo | None = None
|
||||||
|
|
||||||
|
def due_datetime(self) -> datetime:
|
||||||
|
if self.tz is not None:
|
||||||
|
return datetime.fromtimestamp(self.due_at, tz=self.tz)
|
||||||
|
return datetime.fromtimestamp(self.due_at).astimezone()
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"run_id": self.run_id,
|
||||||
|
"kind": self.kind,
|
||||||
|
"label": self.label,
|
||||||
|
"source": self.source,
|
||||||
|
"due_at": self.due_at,
|
||||||
|
"due_at_local": self.due_datetime().isoformat(),
|
||||||
|
"created_at": self.created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FiredTimer:
|
||||||
|
"""A timer that has fired; the notification a front end delivers."""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
run_id: str
|
||||||
|
kind: str
|
||||||
|
label: str
|
||||||
|
source: str
|
||||||
|
due_at: float
|
||||||
|
fired_at: float
|
||||||
|
message: str
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"run_id": self.run_id,
|
||||||
|
"kind": self.kind,
|
||||||
|
"label": self.label,
|
||||||
|
"source": self.source,
|
||||||
|
"due_at": self.due_at,
|
||||||
|
"fired_at": self.fired_at,
|
||||||
|
"message": self.message,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TimerService:
|
||||||
|
"""Owns scheduled timers/alarms and the single firing thread.
|
||||||
|
|
||||||
|
Thread-safe: bodies schedule from the scheduler thread while the firing
|
||||||
|
thread delivers. `drain()` hands fired timers to the active front end once;
|
||||||
|
`fired()` keeps a bounded history for the dashboard.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, trace=None, history: int = 50, timezone: str | None = None):
|
||||||
|
self.trace = trace
|
||||||
|
self._history_limit = int(history)
|
||||||
|
self._tz = resolve_timezone({"timezone": timezone})
|
||||||
|
self._lock = threading.RLock()
|
||||||
|
self._cv = threading.Condition(self._lock)
|
||||||
|
self._heap: list[tuple[float, int, Timer]] = []
|
||||||
|
self._seq = 0
|
||||||
|
self._timers: dict[str, Timer] = {}
|
||||||
|
self._fired: list[FiredTimer] = []
|
||||||
|
self._undrained: list[FiredTimer] = []
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self._stop = False
|
||||||
|
|
||||||
|
# ---- scheduling ----
|
||||||
|
|
||||||
|
def set_timer(self, seconds: float, label: str, run_id: str = "", source: str = "") -> Timer:
|
||||||
|
"""Schedule a countdown timer that fires `seconds` from now."""
|
||||||
|
seconds = float(seconds)
|
||||||
|
if seconds <= 0:
|
||||||
|
raise ValueError("timer duration must be positive")
|
||||||
|
return self._schedule("timer", time.time() + seconds, label, run_id, source)
|
||||||
|
|
||||||
|
def set_alarm(self, at: datetime, label: str, run_id: str = "", source: str = "") -> Timer:
|
||||||
|
"""Schedule an alarm for a wall-clock moment.
|
||||||
|
|
||||||
|
A naive `at` is interpreted in the host's local timezone; an aware one is
|
||||||
|
converted to epoch directly.
|
||||||
|
"""
|
||||||
|
return self._schedule("alarm", at.timestamp(), label, run_id, source)
|
||||||
|
|
||||||
|
def _schedule(self, kind: str, due_at: float, label: str, run_id: str, source: str) -> Timer:
|
||||||
|
timer = Timer(
|
||||||
|
id=uuid.uuid4().hex[:12],
|
||||||
|
run_id=str(run_id or ""),
|
||||||
|
kind=kind,
|
||||||
|
label=str(label or ""),
|
||||||
|
source=str(source or ""),
|
||||||
|
due_at=float(due_at),
|
||||||
|
tz=self._tz,
|
||||||
|
)
|
||||||
|
with self._cv:
|
||||||
|
self._seq += 1
|
||||||
|
heapq.heappush(self._heap, (timer.due_at, self._seq, timer))
|
||||||
|
self._timers[timer.id] = timer
|
||||||
|
self._ensure_thread()
|
||||||
|
self._cv.notify_all()
|
||||||
|
return timer
|
||||||
|
|
||||||
|
def cancel(self, timer_id: str) -> bool:
|
||||||
|
"""Cancel a scheduled timer. Returns False when it already fired/gone."""
|
||||||
|
with self._lock:
|
||||||
|
return self._timers.pop(timer_id, None) is not None
|
||||||
|
|
||||||
|
# ---- inspection ----
|
||||||
|
|
||||||
|
def pending(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
timers = sorted(self._timers.values(), key=lambda t: t.due_at)
|
||||||
|
return [t.as_dict() for t in timers]
|
||||||
|
|
||||||
|
def fired(self) -> list[dict]:
|
||||||
|
"""Bounded history of fired timers, oldest first."""
|
||||||
|
with self._lock:
|
||||||
|
return [f.as_dict() for f in self._fired]
|
||||||
|
|
||||||
|
def drain(self) -> list[FiredTimer]:
|
||||||
|
"""Pop and return timers fired since the last drain (for push front ends)."""
|
||||||
|
with self._lock:
|
||||||
|
fired = self._undrained
|
||||||
|
self._undrained = []
|
||||||
|
return fired
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Stop the firing thread (does not cancel scheduled timers)."""
|
||||||
|
with self._cv:
|
||||||
|
self._stop = True
|
||||||
|
self._cv.notify_all()
|
||||||
|
thread = self._thread
|
||||||
|
if thread is not None:
|
||||||
|
thread.join(timeout=2.0)
|
||||||
|
|
||||||
|
# ---- firing thread ----
|
||||||
|
|
||||||
|
def _ensure_thread(self) -> None:
|
||||||
|
if self._thread is None or not self._thread.is_alive():
|
||||||
|
self._stop = False
|
||||||
|
self._thread = threading.Thread(target=self._run, name="timers", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def _run(self) -> None:
|
||||||
|
while True:
|
||||||
|
with self._cv:
|
||||||
|
if self._stop:
|
||||||
|
return
|
||||||
|
# Drop cancelled timers from the head of the heap.
|
||||||
|
while self._heap and self._heap[0][2].id not in self._timers:
|
||||||
|
heapq.heappop(self._heap)
|
||||||
|
if not self._heap:
|
||||||
|
self._cv.wait()
|
||||||
|
continue
|
||||||
|
due_at, _seq, timer = self._heap[0]
|
||||||
|
remaining = due_at - time.time()
|
||||||
|
if remaining > 0:
|
||||||
|
self._cv.wait(timeout=remaining)
|
||||||
|
continue
|
||||||
|
heapq.heappop(self._heap)
|
||||||
|
if self._timers.pop(timer.id, None) is None:
|
||||||
|
continue
|
||||||
|
self._fire(timer)
|
||||||
|
|
||||||
|
def _fire(self, timer: Timer) -> None:
|
||||||
|
fired_at = time.time()
|
||||||
|
fired = FiredTimer(
|
||||||
|
id=timer.id,
|
||||||
|
run_id=timer.run_id,
|
||||||
|
kind=timer.kind,
|
||||||
|
label=timer.label,
|
||||||
|
source=timer.source,
|
||||||
|
due_at=timer.due_at,
|
||||||
|
fired_at=fired_at,
|
||||||
|
message=self._message(timer, fired_at),
|
||||||
|
)
|
||||||
|
with self._lock:
|
||||||
|
self._fired.append(fired)
|
||||||
|
if len(self._fired) > self._history_limit:
|
||||||
|
self._fired = self._fired[-self._history_limit:]
|
||||||
|
self._undrained.append(fired)
|
||||||
|
if self.trace is not None:
|
||||||
|
try:
|
||||||
|
self.trace.append(
|
||||||
|
"timer_fired",
|
||||||
|
timer.run_id,
|
||||||
|
timer_id=timer.id,
|
||||||
|
timer_kind=timer.kind,
|
||||||
|
label=timer.label,
|
||||||
|
source=timer.source,
|
||||||
|
due_at=timer.due_at,
|
||||||
|
fired_at=fired_at,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _to_local(self, ts: float) -> datetime:
|
||||||
|
if self._tz is not None:
|
||||||
|
return datetime.fromtimestamp(ts, tz=self._tz)
|
||||||
|
return datetime.fromtimestamp(ts).astimezone()
|
||||||
|
|
||||||
|
def _message(self, timer: Timer, fired_at: float) -> str:
|
||||||
|
when = self._to_local(fired_at).strftime("%H:%M")
|
||||||
|
if timer.kind == "alarm":
|
||||||
|
body = timer.label or "Alarm"
|
||||||
|
return f"Alarm: {body} — it's {when}."
|
||||||
|
body = timer.label or "Timer"
|
||||||
|
return f"Timer finished: {body} ({when})."
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
scheduler.
|
scheduler.
|
||||||
|
|
||||||
Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events
|
Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events
|
||||||
(submit, dropped, queued, preempted, 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
|
`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
|
each run's flow without touching the decision-log contract. Both files are
|
||||||
append-only; replays read them in order.
|
append-only; replays read them in order.
|
||||||
@@ -19,8 +19,10 @@ class TraceLog:
|
|||||||
def __init__(self, path: str = "data/runs.jsonl"):
|
def __init__(self, path: str = "data/runs.jsonl"):
|
||||||
self.path = Path(path)
|
self.path = Path(path)
|
||||||
|
|
||||||
def append(self, kind: str, run_id: str, **fields) -> None:
|
def append(self, kind: str, run_id: str, ts: float | None = None, **fields) -> None:
|
||||||
row = {"kind": kind, "run_id": run_id, "ts": time.time(), **fields}
|
# `ts` lets a caller record the moment an event *happened* (e.g. the last
|
||||||
|
# speech frame of an utterance) rather than when the row was written.
|
||||||
|
row = {"kind": kind, "run_id": run_id, "ts": time.time() if ts is None else ts, **fields}
|
||||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with self.path.open("a") as handle:
|
with self.path.open("a") as handle:
|
||||||
handle.write(json.dumps(row) + "\n")
|
handle.write(json.dumps(row) + "\n")
|
||||||
|
|||||||
@@ -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),
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,250 @@
|
|||||||
|
"""Remote Winnow decision engine: a `/v1/systemone` typed-decision HTTP API.
|
||||||
|
|
||||||
|
An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`),
|
||||||
|
selected per machine with ``engine.provider == "winnow"`` in config.json — the
|
||||||
|
same provider pattern as ``llm`` / ``codegen``. The agent's flat decision
|
||||||
|
contract (state + question + typed options) maps onto Winnow's ``choice``
|
||||||
|
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.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from .decisions import DecisionRequest, DecisionResult, Option
|
||||||
|
from .engine import DecisionEngine, EngineUnavailable
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WinnowConfig:
|
||||||
|
"""Per-machine settings for the remote Winnow engine (`engine.winnow`)."""
|
||||||
|
|
||||||
|
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.
|
||||||
|
retries: int = 0
|
||||||
|
api_key: str = ""
|
||||||
|
extra_headers: dict | None = None
|
||||||
|
user_agent: str = "semif-agent"
|
||||||
|
|
||||||
|
|
||||||
|
class WinnowEngine(DecisionEngine):
|
||||||
|
"""One Winnow `/v1/systemone` endpoint, used for every decision.
|
||||||
|
|
||||||
|
Scoring maps `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 = "winnow"
|
||||||
|
|
||||||
|
def __init__(self, config: WinnowConfig):
|
||||||
|
self.config = config
|
||||||
|
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
|
||||||
|
|
||||||
|
# ---- 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 _post(self, path: str, payload: dict) -> dict:
|
||||||
|
"""POST JSON, returning the parsed object or raising `EngineUnavailable`."""
|
||||||
|
url = self.config.base_url.rstrip("/") + path
|
||||||
|
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", 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"Winnow response from {url} is not a JSON object"
|
||||||
|
)
|
||||||
|
return parsed
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
detail = ""
|
||||||
|
try:
|
||||||
|
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"Winnow request to {url} failed: {type(last).__name__}: {last}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- DecisionEngine ----
|
||||||
|
|
||||||
|
def warm(self) -> None:
|
||||||
|
"""Verify the endpoint is reachable (`GET /health`), else raise."""
|
||||||
|
url = self.config.base_url.rstrip("/") + "/health"
|
||||||
|
request = urllib.request.Request(url, method="GET", headers=self._headers())
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
request, timeout=self.config.timeout
|
||||||
|
) as response:
|
||||||
|
if getattr(response, "status", 200) != 200:
|
||||||
|
raise EngineUnavailable(
|
||||||
|
f"Winnow health check returned HTTP {response.status}"
|
||||||
|
)
|
||||||
|
except EngineUnavailable:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise EngineUnavailable(f"Winnow unreachable at {url}: {exc}") from exc
|
||||||
|
self._loaded = True
|
||||||
|
|
||||||
|
def call(self, request: DecisionRequest) -> DecisionResult:
|
||||||
|
option_ids = [option.id for option in request.options]
|
||||||
|
payload = {
|
||||||
|
"state": request.state,
|
||||||
|
"model": self.config.model,
|
||||||
|
"questions": {
|
||||||
|
"decision": {
|
||||||
|
"type": "choice",
|
||||||
|
"instructions": request.question,
|
||||||
|
"criteria": {
|
||||||
|
option.id: option.description for option in request.options
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
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("Winnow response is missing answers.decision")
|
||||||
|
if answer.get("type") not in (None, "choice"):
|
||||||
|
raise EngineUnavailable(
|
||||||
|
f"Winnow answer type {answer.get('type')!r} is not 'choice'"
|
||||||
|
)
|
||||||
|
raw = answer.get("probabilities")
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
raise EngineUnavailable("Winnow answer is missing probabilities")
|
||||||
|
if set(raw) != set(option_ids):
|
||||||
|
raise EngineUnavailable(
|
||||||
|
"Winnow probabilities do not match the requested options: "
|
||||||
|
f"{sorted(raw)} != {sorted(option_ids)}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
values = [float(raw[option_id]) for option_id in option_ids]
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise EngineUnavailable(
|
||||||
|
f"Winnow 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(
|
||||||
|
"Winnow returned a non-finite or out-of-range probability"
|
||||||
|
)
|
||||||
|
total = sum(values)
|
||||||
|
if total <= 0.0:
|
||||||
|
raise EngineUnavailable("Winnow 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"),
|
||||||
|
"confidence": answer.get("confidence"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def generate(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
temperature: float = 0.0,
|
||||||
|
max_tokens: int = 256,
|
||||||
|
) -> str:
|
||||||
|
"""Text generation via the same server's `/v1/chat/completions`.
|
||||||
|
|
||||||
|
Backs `llm.provider == "semif"` when the decision engine is Winnow.
|
||||||
|
"""
|
||||||
|
payload = {
|
||||||
|
"model": self.config.model,
|
||||||
|
"messages": messages,
|
||||||
|
"max_tokens": max_tokens,
|
||||||
|
"temperature": temperature,
|
||||||
|
}
|
||||||
|
with self._lock:
|
||||||
|
body = self._post("/v1/chat/completions", payload)
|
||||||
|
choices = body.get("choices")
|
||||||
|
if not isinstance(choices, list) or not choices:
|
||||||
|
raise EngineUnavailable("Winnow chat response has no choices")
|
||||||
|
first = choices[0]
|
||||||
|
message = first.get("message") if isinstance(first, dict) else None
|
||||||
|
content = message.get("content") if isinstance(message, dict) else None
|
||||||
|
if not isinstance(content, str):
|
||||||
|
raise EngineUnavailable("Winnow chat response has no message content")
|
||||||
|
self._loaded = True
|
||||||
|
return content.strip()
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Shared test fixtures.
|
||||||
|
|
||||||
|
`ScriptedEngine` is a deterministic in-process stand-in for the SemIf decision
|
||||||
|
engine used ONLY by pure-stdlib unit tests of scheduling mechanics (pausing,
|
||||||
|
resuming, routing, authoring). The real engine is the decision-maker in
|
||||||
|
production and in the integration tests; this double exists so a mechanics test
|
||||||
|
can drive the loop without loading a GGUF locally, exactly as a
|
||||||
|
loopback HTTP server stands in for a live service elsewhere.
|
||||||
|
|
||||||
|
It is not a mock of SemIf scoring: it answers each `DecisionRequest` with a
|
||||||
|
chosen option, so a test can assert what the *mechanics* did with that answer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from semif_agent.decisions import DecisionResult
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedEngine:
|
||||||
|
"""Answers decisions deterministically from a per-phase option policy.
|
||||||
|
|
||||||
|
`default` is the option id returned for any decision not covered by
|
||||||
|
`choices`. `choices` maps a substring of the decision `question` (or the
|
||||||
|
option ids) to the option id to select; the first matching key wins.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, choices: dict[str, str] | None = None, default: str | None = None):
|
||||||
|
self.choices = dict(choices or {})
|
||||||
|
self.default = default
|
||||||
|
self.calls: list = []
|
||||||
|
|
||||||
|
def call(self, request):
|
||||||
|
self.calls.append(request)
|
||||||
|
option_ids = [option.id for option in request.options]
|
||||||
|
selected = None
|
||||||
|
haystack = f"{request.question} {' '.join(option_ids)}"
|
||||||
|
for key, option_id in self.choices.items():
|
||||||
|
if key in haystack:
|
||||||
|
selected = option_id
|
||||||
|
break
|
||||||
|
if selected is None:
|
||||||
|
selected = self.default or option_ids[0]
|
||||||
|
if selected not in option_ids:
|
||||||
|
selected = option_ids[0]
|
||||||
|
return DecisionResult(
|
||||||
|
request=request,
|
||||||
|
option_ids=option_ids,
|
||||||
|
probabilities=[1.0 if o == selected else 0.0 for o in option_ids],
|
||||||
|
)
|
||||||
@@ -1,70 +1,166 @@
|
|||||||
"""End-to-end pipeline test. Run ONLY on the box with real SemIf + real LLM.
|
"""End-to-end pipeline test. Run ONLY where real SemIf + a real LLM are available.
|
||||||
|
|
||||||
python -m pytest tests/integration -q
|
python -m pytest tests/integration -q
|
||||||
|
|
||||||
The decision engine is real (llamacpp GGUF) and self-assessment is a real
|
The decision engine is real (llamacpp GGUF), and the `llm` and `codegen`
|
||||||
local LLM endpoint. If either is unavailable this fails loudly — no mocking.
|
providers are real OpenAI-compatible endpoints. If any is unavailable this
|
||||||
|
fails loudly — no mocking.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
import time
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from semif_agent.cli import build_scheduler, load_config
|
from semif_agent.cli import (
|
||||||
from semif_agent.codegen import CodegenClient, generate_skill_body
|
build_codegen_client,
|
||||||
from semif_agent.decisions import Request
|
build_engine_config,
|
||||||
|
build_scheduler,
|
||||||
|
load_config,
|
||||||
|
)
|
||||||
|
from semif_agent.codegen import (
|
||||||
|
CodegenClient,
|
||||||
|
generate_skill_body,
|
||||||
|
generate_skill_tests,
|
||||||
|
parse_contract,
|
||||||
|
parse_integration,
|
||||||
|
)
|
||||||
|
from semif_agent.decisions import DecisionRequest, Option, Request
|
||||||
from semif_agent.dream import dream
|
from semif_agent.dream import dream
|
||||||
from semif_agent.engine import EngineUnavailable
|
from semif_agent.engine import EngineUnavailable, SemIfEngine
|
||||||
|
from semif_agent.log import DecisionLog
|
||||||
|
from semif_agent.scheduler import SkillWrite
|
||||||
|
from semif_agent.skill import SkillRunner
|
||||||
from semif_agent.skills import (
|
from semif_agent.skills import (
|
||||||
ActionResult,
|
ActionResult,
|
||||||
|
ActionContext,
|
||||||
CategoryDraft,
|
CategoryDraft,
|
||||||
Prediction,
|
CreateCategory,
|
||||||
Skill,
|
Skill,
|
||||||
SkillBodyStore,
|
|
||||||
SkillDraft,
|
SkillDraft,
|
||||||
|
SkillStore,
|
||||||
build_skills,
|
build_skills,
|
||||||
build_tree,
|
build_tree,
|
||||||
generate_category,
|
generate_category,
|
||||||
generate_skill,
|
generate_skill_spec,
|
||||||
materialize_skill,
|
materialize_skill,
|
||||||
|
navigate,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def require_real(config: dict):
|
def require_real(config: dict):
|
||||||
from semif_agent.engine import SemIfEngine, EngineConfig
|
from semif_agent.engine import SemIfEngine
|
||||||
|
|
||||||
engine = SemIfEngine(
|
engine = SemIfEngine(build_engine_config(config))
|
||||||
EngineConfig(
|
|
||||||
backend=config.get("engine", {}).get("backend", "llamacpp"),
|
|
||||||
source=config.get("engine", {}).get("source", ""),
|
|
||||||
revision=config.get("engine", {}).get("revision", ""),
|
|
||||||
gguf=config.get("engine", {}).get("gguf", ""),
|
|
||||||
context_tokens=int(config.get("engine", {}).get("context_tokens", 4096)),
|
|
||||||
threads=config.get("engine", {}).get("threads"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
engine._ensure_loaded()
|
engine._ensure_loaded()
|
||||||
except EngineUnavailable as exc:
|
except EngineUnavailable as exc:
|
||||||
pytest.fail(f"real engine unavailable: {exc}")
|
pytest.fail(f"real engine unavailable: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
def _isolate_runtime(config: dict, tmp_path) -> None:
|
||||||
|
"""Point every runtime artifact at tmp_path.
|
||||||
|
|
||||||
|
Without this, persisted authoring output in the runtime `data/categories.json`
|
||||||
|
and `data/skills/` leaks into the tree and navigation routes to a stale stub
|
||||||
|
instead of the injected fixture — an environment-dependent failure.
|
||||||
|
"""
|
||||||
|
config["log"] = str(tmp_path / "decisions.jsonl")
|
||||||
|
config["trace"] = str(tmp_path / "runs.jsonl")
|
||||||
|
config["category_registry"] = str(tmp_path / "categories.json")
|
||||||
|
config["skill_bodies"] = str(tmp_path / "skills")
|
||||||
|
|
||||||
|
|
||||||
|
def _install_tracking_fixture(scheduler):
|
||||||
|
"""A deterministic runnable leaf for end-to-end runs.
|
||||||
|
|
||||||
|
The pipeline tests need a target whose flow is stable; the hardcoded
|
||||||
|
email/tracking examples were removed because they faked their integrations.
|
||||||
|
This injects a runnable tracking leaf instead — the decision engine, the
|
||||||
|
`llm`/`codegen` providers, and the decision log all remain real.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(
|
||||||
|
action_log="tracking fixture: checked the package status",
|
||||||
|
new_state="package status checked",
|
||||||
|
)
|
||||||
|
|
||||||
|
scheduler.tree["tracking"] = [
|
||||||
|
Skill(
|
||||||
|
name="tracking.check",
|
||||||
|
category="tracking",
|
||||||
|
description="Check the delivery status of a package.",
|
||||||
|
act=act,
|
||||||
|
category_description="Package tracking: checking the delivery status of parcels and shipments.",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_engine_gpu_offload_is_deterministic_and_matches_cpu(tmp_path):
|
||||||
|
"""With a GPU-backed llama-cpp-python and `engine.gpu_layers` set, offload
|
||||||
|
must be deterministic across repeated calls and match the CPU path.
|
||||||
|
|
||||||
|
Regression: SemIf's `_Engine.clear` resets only cache metadata
|
||||||
|
(`llama_memory_clear(mem, False)`). The CPU backend tolerates that, but the
|
||||||
|
Vulkan backend keeps stale hybrid-attention state, so successive `score`
|
||||||
|
calls drifted (0.08 -> 0.36 -> 0.43). The wrapper clears the data too. This
|
||||||
|
is the honest correctness check: "it loaded" is not enough on Qwen3.5's
|
||||||
|
hybrid architecture.
|
||||||
|
"""
|
||||||
|
import llama_cpp
|
||||||
|
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
if not llama_cpp.llama_supports_gpu_offload():
|
||||||
|
pytest.skip("llama-cpp-python has no GPU backend")
|
||||||
|
base = build_engine_config(config)
|
||||||
|
if not base.gpu_layers:
|
||||||
|
pytest.skip("engine.gpu_layers is 0 (CPU-only); set it to exercise offload")
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
|
request = DecisionRequest(
|
||||||
|
state=(
|
||||||
|
"The user said: 'check the weather in Paris tomorrow and tell me if "
|
||||||
|
"I need an umbrella'."
|
||||||
|
),
|
||||||
|
question="Is this input an actionable request, or non-action chatter?",
|
||||||
|
options=[
|
||||||
|
Option(id="action", description="An actionable request to perform a task."),
|
||||||
|
Option(
|
||||||
|
id="non_action",
|
||||||
|
description="Chit-chat, a statement, or too vague to act on.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
cpu = SemIfEngine(replace(base, gpu_layers=0)).call(request).probabilities
|
||||||
|
gpu_engine = SemIfEngine(base)
|
||||||
|
runs = [gpu_engine.call(request).probabilities for _ in range(3)]
|
||||||
|
print(f"cpu={cpu} gpu={runs}")
|
||||||
|
for run in runs[1:]:
|
||||||
|
assert max(abs(a - b) for a, b in zip(runs[0], run)) < 1e-5, (
|
||||||
|
"GPU offload must be deterministic across repeated calls"
|
||||||
|
)
|
||||||
|
diff = max(abs(a - b) for a, b in zip(cpu, runs[0]))
|
||||||
|
assert diff < 2e-3, f"GPU offload changed the option probabilities by {diff}"
|
||||||
|
|
||||||
|
|
||||||
def test_pipeline_end_to_end(tmp_path):
|
def test_pipeline_end_to_end(tmp_path):
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
config["log"] = str(tmp_path / "decisions.jsonl")
|
_isolate_runtime(config, tmp_path)
|
||||||
config["trace"] = str(tmp_path / "runs.jsonl")
|
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
|
_install_tracking_fixture(scheduler)
|
||||||
|
|
||||||
inputs = [
|
inputs = [
|
||||||
"send my girlfriend an email that says I'm going to be late to the party",
|
|
||||||
"tell me if my package was delivered",
|
"tell me if my package was delivered",
|
||||||
|
"what is the delivery status of my parcel",
|
||||||
]
|
]
|
||||||
for text in inputs:
|
for text in inputs:
|
||||||
status, detail = scheduler.submit(text)
|
reply = scheduler.submit(text)
|
||||||
print(f"[{status}] {detail}")
|
print(f"[{reply.status}] {reply.text}")
|
||||||
assert status in ("running", "preempted", "queued", "rejected")
|
assert reply.status in ("running", "queued", "rejected")
|
||||||
|
|
||||||
scheduler.run_queue()
|
scheduler.run_queue()
|
||||||
|
|
||||||
@@ -73,7 +169,6 @@ def test_pipeline_end_to_end(tmp_path):
|
|||||||
|
|
||||||
phases = [r.get("extra", {}).get("phase") for r in rows]
|
phases = [r.get("extra", {}).get("phase") for r in rows]
|
||||||
assert "navigate:category" in phases, "navigation decisions must be logged"
|
assert "navigate:category" in phases, "navigation decisions must be logged"
|
||||||
assert "navigate:leaf" in phases, "navigation decisions must be logged"
|
|
||||||
for row in rows:
|
for row in rows:
|
||||||
assert row.get("extra", {}).get("run_id"), "every decision must carry a run_id"
|
assert row.get("extra", {}).get("run_id"), "every decision must carry a run_id"
|
||||||
|
|
||||||
@@ -88,47 +183,194 @@ def test_pipeline_end_to_end(tmp_path):
|
|||||||
skills = scheduler.status()
|
skills = scheduler.status()
|
||||||
assert "queue:" in skills
|
assert "queue:" in skills
|
||||||
|
|
||||||
contacts_path = Path(config.get("skills", {}).get("contacts", "data/contacts.json"))
|
|
||||||
assert contacts_path.is_file()
|
|
||||||
|
|
||||||
|
def test_navigation_routes_noise_into_the_response_tree(tmp_path):
|
||||||
def test_busy_choice_path(tmp_path):
|
"""There is no up-front handle/ignore gate any more: every input is
|
||||||
|
dispatched, and chatter that is not a task must land in the closed `response`
|
||||||
|
tree (a canned reply), never in an integration category or codegen."""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
config["log"] = str(tmp_path / "decisions.jsonl")
|
_isolate_runtime(config, tmp_path)
|
||||||
config["trace"] = str(tmp_path / "runs.jsonl")
|
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
|
lookups = [
|
||||||
|
"tell me the next event in my nextcloud calendar",
|
||||||
|
"what is the next event in my nextcloud calendar?",
|
||||||
|
"tell me the next even in my calendar",
|
||||||
|
]
|
||||||
|
noise = [
|
||||||
|
"hello there",
|
||||||
|
"thanks!",
|
||||||
|
"the sky is blue",
|
||||||
|
"what's up",
|
||||||
|
# Stray statements not addressed to the agent: these have no action to
|
||||||
|
# perform, so they must fall to the `response` catchall, not author a
|
||||||
|
# category. Regression: an under-covering `response` description sent
|
||||||
|
# "the sky is blue"/"1+1=2"/"random thought here" to create_category.
|
||||||
|
"1+1=2",
|
||||||
|
"random thought here",
|
||||||
|
]
|
||||||
|
for text in lookups:
|
||||||
|
result = navigate(
|
||||||
|
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
|
||||||
|
)
|
||||||
|
print(f"[lookup] {text!r} -> {result!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
|
||||||
|
)
|
||||||
|
print(f"[noise] {text!r} -> {result!r}")
|
||||||
|
assert getattr(result, "category", None) == "response", f"noise left the response tree: {text!r}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_navigation_routes_vague_fragment_to_clarify(tmp_path):
|
||||||
|
"""A fragment too vague to act on ("what") is non-action: it lands on the
|
||||||
|
catchall `response.clarify` rather than authoring a redundant clarify skill.
|
||||||
|
Regression: "what" scored action 0.513 / non_action 0.487 and authored an
|
||||||
|
"unclear"/"clarify_intent" category."""
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
_isolate_runtime(config, tmp_path)
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
|
result = navigate(
|
||||||
|
scheduler.engine,
|
||||||
|
scheduler.log,
|
||||||
|
scheduler.trace,
|
||||||
|
Request("what"),
|
||||||
|
scheduler.tree,
|
||||||
|
)
|
||||||
|
print(f"[vague] 'what' -> {result!r}")
|
||||||
|
assert getattr(result, "category", None) == "response", result
|
||||||
|
assert getattr(result, "name", None) == "response.clarify", result
|
||||||
|
|
||||||
|
|
||||||
|
def test_navigation_routes_uncovered_requests_to_create(tmp_path):
|
||||||
|
"""A request no skill covers must author a skill, not get a canned reply: the
|
||||||
|
actionability guard keeps the closed `response` tree for non-request input
|
||||||
|
only. Regression: "what is 255 * 12?" landed in `response.unable` because the
|
||||||
|
response scope said it covered "inputs the agent cannot act on"."""
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
_isolate_runtime(config, tmp_path)
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
|
requests = [
|
||||||
|
"what is 255 * 12?",
|
||||||
|
"what is the capital of France?",
|
||||||
|
"convert 10 km to miles",
|
||||||
|
"tell me a joke",
|
||||||
|
]
|
||||||
|
for text in requests:
|
||||||
|
result = navigate(
|
||||||
|
scheduler.engine,
|
||||||
|
scheduler.log,
|
||||||
|
scheduler.trace,
|
||||||
|
Request(text),
|
||||||
|
scheduler.tree,
|
||||||
|
action_tau=scheduler.action_tau,
|
||||||
|
)
|
||||||
|
print(f"[request] {text!r} -> {result!r}")
|
||||||
|
assert isinstance(result, CreateCategory), (
|
||||||
|
f"request did not author a skill: {text!r} -> {result!r}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_navigate_routes_unmatched_action_to_create_skill(tmp_path):
|
||||||
|
"""Two-stage leaf: navigation picks the closest existing skill, then the
|
||||||
|
intent guard decides reuse-vs-create. A send request must reach create_skill
|
||||||
|
for simplex — not silently run the read skill that merely shares the word
|
||||||
|
'message'; a read request must reuse next_message.
|
||||||
|
|
||||||
|
Regression: the old single-stage leaf put create_skill in the softmax with
|
||||||
|
the real skills, so a send phrasing could win on a weak plurality while the
|
||||||
|
read skill stayed high. Now create_skill is never an option; the guard's
|
||||||
|
action comparison is the door. Asserts the routing outcome only — the draft
|
||||||
|
queue is stubbed and the read leaf's act is a stub, so no codegen write and
|
||||||
|
no network.
|
||||||
|
"""
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
_isolate_runtime(config, tmp_path)
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
|
def read_act(ctx, request):
|
||||||
|
return ActionResult(action_log="read fixture", new_state="read")
|
||||||
|
|
||||||
|
scheduler.tree["simplex"] = [
|
||||||
|
Skill(
|
||||||
|
name="next_message",
|
||||||
|
category="simplex",
|
||||||
|
description="Read the next unread SimpleX message bridge.",
|
||||||
|
act=read_act,
|
||||||
|
),
|
||||||
|
Skill(
|
||||||
|
name="connect_link",
|
||||||
|
category="simplex",
|
||||||
|
description="Show (creating if needed) the SimpleX contact link others use to connect to this agent.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
queued: list = []
|
||||||
|
scheduler._queue_draft = lambda request, category, kind: queued.append(
|
||||||
|
(category, kind)
|
||||||
|
)
|
||||||
|
|
||||||
|
for text in [
|
||||||
|
"send a simplex message to pepper saying hi",
|
||||||
|
"send a new simplex message to pepper: hey",
|
||||||
|
]:
|
||||||
|
before = len(scheduler.log.read())
|
||||||
|
result = scheduler._dispatch(Request(text))
|
||||||
|
leaf_rows = [
|
||||||
|
r for r in scheduler.log.read()[before:]
|
||||||
|
if r.get("extra", {}).get("phase") == "navigate:leaf"
|
||||||
|
]
|
||||||
|
print(f"[nav] {leaf_rows[-1]['predicted_probs'] if leaf_rows else '-'} :: {text!r} -> {result.kind}")
|
||||||
|
assert result.kind == "create_skill", f"send must route to create_skill, got {result!r}"
|
||||||
|
assert queued and all(category == "simplex" for category, _ in queued)
|
||||||
|
|
||||||
|
read = scheduler._dispatch(Request("read the next simplex message"))
|
||||||
|
print(f"[nav control] read -> {read.kind} {read.skill}")
|
||||||
|
assert read.kind == "ran", "a read request must still run the read skill"
|
||||||
|
assert read.skill == "next_message"
|
||||||
|
|
||||||
|
|
||||||
|
def test_busy_queue_path(tmp_path):
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
_isolate_runtime(config, tmp_path)
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
_install_tracking_fixture(scheduler)
|
||||||
|
|
||||||
scheduler.busy("driving on the freeway", skill="driving")
|
scheduler.busy("driving on the freeway", skill="driving")
|
||||||
status, detail = scheduler.submit("send my girlfriend an email that says I'm going to be late")
|
reply = scheduler.submit("tell me if my package was delivered")
|
||||||
print(f"[{status}] {detail}")
|
print(f"[{reply.status}] {reply.text}")
|
||||||
assert status in ("preempted", "queued", "dropped")
|
assert reply.status == "queued"
|
||||||
scheduler.idle()
|
scheduler.idle()
|
||||||
|
|
||||||
|
|
||||||
def test_engine_generation_normal_mode(tmp_path):
|
def test_engine_is_pluggable(tmp_path):
|
||||||
"""The pinned decision model must also generate text in the normal way."""
|
"""The configured decision engine satisfies the `DecisionEngine` contract
|
||||||
|
(`call` + `warm` + `generate`), whether the local `semif` provider or a
|
||||||
|
remote `winnow` one. The engine is selected by `engine.provider`."""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
out = scheduler.engine.generate(
|
from semif_agent.engine import DecisionEngine
|
||||||
[
|
|
||||||
{"role": "system", "content": "Reply with the single word ok."},
|
assert isinstance(scheduler.engine, DecisionEngine)
|
||||||
{"role": "user", "content": "say ok"},
|
assert hasattr(scheduler.engine, "call")
|
||||||
],
|
assert hasattr(scheduler.engine, "generate")
|
||||||
max_tokens=16,
|
|
||||||
)
|
|
||||||
print(f"generation: {out!r}")
|
|
||||||
assert isinstance(out, str) and out.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def test_generate_category(tmp_path):
|
def test_generate_category(tmp_path):
|
||||||
"""Authoring a category stub through the real decision model."""
|
"""Authoring a category stub through the real `llm` provider."""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
draft = generate_category(
|
draft = generate_category(
|
||||||
scheduler.engine,
|
scheduler.llm,
|
||||||
Request("tell me if my package was delivered"),
|
Request("tell me if my package was delivered"),
|
||||||
scheduler.tree,
|
scheduler.tree,
|
||||||
)
|
)
|
||||||
@@ -138,53 +380,227 @@ def test_generate_category(tmp_path):
|
|||||||
|
|
||||||
|
|
||||||
def test_generate_skill(tmp_path):
|
def test_generate_skill(tmp_path):
|
||||||
"""Authoring a skill leaf stub through the real decision model."""
|
"""Authoring a de-identified skill spec through the real `llm` provider."""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
draft = generate_skill(
|
draft = generate_skill_spec(
|
||||||
scheduler.engine,
|
scheduler.llm,
|
||||||
Request("tell me if my package was delivered"),
|
Request("tell me if my package was delivered"),
|
||||||
"tracking",
|
"tracking",
|
||||||
scheduler.tree,
|
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 isinstance(draft, SkillDraft)
|
||||||
assert draft.name and draft.description
|
assert draft.name and draft.description
|
||||||
|
assert draft.goal
|
||||||
|
|
||||||
|
|
||||||
def test_generate_skill_body_codegen(tmp_path):
|
def test_generate_skill_body_codegen(tmp_path):
|
||||||
"""A real OpenAI-compatible model writes a runnable skill body.
|
"""A real OpenAI-compatible model writes a real-integration skill body +
|
||||||
|
data contract + hermetic test, and the auto-run test passes.
|
||||||
|
|
||||||
Slow: uses the big codegen model (qwen38-iq3s by default). Run this one in
|
The body must perform the action via a stdlib transport and declare
|
||||||
the background and poll — long-lived ssh sessions get SIGHUP'd.
|
INTEGRATION; the test is a hermetic mechanics check (loopback for HTTP), not
|
||||||
|
proof of the live integration. Slow: uses the configured codegen model.
|
||||||
|
Run this one in the background and poll —
|
||||||
|
long-lived ssh sessions get SIGHUP'd.
|
||||||
"""
|
"""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
codegen_cfg = config.get("codegen", {})
|
# Build the client exactly as build_scheduler does, so the test exercises the
|
||||||
client = CodegenClient(
|
# configured provider (e.g. the hosted Console, which needs auth + a
|
||||||
base_url=codegen_cfg.get("base_url", "http://localhost:11434/v1"),
|
# User-Agent) rather than assuming an unauthenticated ollama endpoint.
|
||||||
model=codegen_cfg.get("model", "qwen38-iq3s"),
|
config["codegen"] = {**(config.get("codegen") or {}), "stream": True}
|
||||||
timeout=float(codegen_cfg.get("timeout", 1200.0)),
|
client = build_codegen_client(config)
|
||||||
stream=True,
|
|
||||||
)
|
|
||||||
tree = build_tree(build_skills({"skills": {}}))
|
tree = build_tree(build_skills({"skills": {}}))
|
||||||
draft = SkillDraft(
|
draft = SkillDraft(
|
||||||
name="check_service",
|
name="check_service",
|
||||||
description="Check whether a service is reachable.",
|
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"
|
||||||
|
),
|
||||||
|
integration={"service": "http_service", "transport": "http"},
|
||||||
)
|
)
|
||||||
code = generate_skill_body(
|
code = generate_skill_body(
|
||||||
client,
|
client,
|
||||||
Request("is my home server reachable right now?"),
|
|
||||||
"tracking",
|
"tracking",
|
||||||
draft,
|
draft,
|
||||||
tree,
|
tree,
|
||||||
)
|
)
|
||||||
print(f"generated {len(code)} bytes of skill body")
|
print(f"generated {len(code)} bytes of skill body")
|
||||||
|
integration = parse_integration(code)
|
||||||
|
print(f"integration: {integration}")
|
||||||
|
assert integration["transport"] in ("http", "caldav")
|
||||||
|
assert "urllib.request" in code or "http.client" in code, (
|
||||||
|
"a service-backed body must call the service with a stdlib transport"
|
||||||
|
)
|
||||||
|
assert "127.0.0.1" not in code and "localhost" not in code, (
|
||||||
|
"the body must take its endpoint from ctx.config, never a fixture"
|
||||||
|
)
|
||||||
|
contract = parse_contract(code)
|
||||||
|
print(f"data contract: {contract}")
|
||||||
|
test = generate_skill_tests(
|
||||||
|
client,
|
||||||
|
"tracking",
|
||||||
|
draft,
|
||||||
|
code,
|
||||||
|
contract,
|
||||||
|
)
|
||||||
|
print(f"generated {len(test)} bytes of skill test")
|
||||||
|
|
||||||
|
store = SkillStore(str(tmp_path / "skills"))
|
||||||
|
store.write_body("tracking", draft.name, code)
|
||||||
|
store.write_contract("tracking", draft.name, contract)
|
||||||
|
store.write_test("tracking", draft.name, test)
|
||||||
|
from semif_agent.codegen import run_skill_test
|
||||||
|
|
||||||
|
passed, output = run_skill_test(store.dir("tracking", draft.name), timeout=60)
|
||||||
|
print(f"auto-run test: passed={passed}\n{output[:400]}")
|
||||||
|
assert passed, "the auto-run test must pass"
|
||||||
|
|
||||||
draft.code = code
|
draft.code = code
|
||||||
store = SkillBodyStore(str(tmp_path / "skills"))
|
|
||||||
skill = materialize_skill(draft, "tracking", store)
|
skill = materialize_skill(draft, "tracking", store)
|
||||||
assert callable(skill.predict) and callable(skill.act)
|
assert callable(skill.act)
|
||||||
|
assert skill.contract == contract
|
||||||
|
assert skill.integration["transport"] in ("http", "caldav")
|
||||||
|
|
||||||
|
|
||||||
|
def test_fidelity_gate_is_a_real_semif_decision(tmp_path):
|
||||||
|
"""The fidelity gate is a real logged SemIf decision (`authoring:fidelity`).
|
||||||
|
|
||||||
|
A body with no valid INTEGRATION declaration produces static findings, which
|
||||||
|
force `reconsider` regardless of the model's probability; a clean,
|
||||||
|
declared body is accepted. Both verdicts are recorded as decision rows.
|
||||||
|
"""
|
||||||
|
config = load_config()
|
||||||
|
require_real(config)
|
||||||
|
config["log"] = str(tmp_path / "decisions.jsonl")
|
||||||
|
config["trace"] = str(tmp_path / "runs.jsonl")
|
||||||
|
scheduler, config = build_scheduler(config)
|
||||||
|
# The gate needs codegen configured to run; point it at a dead endpoint so
|
||||||
|
# a reconsider can't complete a rewrite (the gate still logs its decision).
|
||||||
|
scheduler.codegen = CodegenClient(
|
||||||
|
base_url="http://127.0.0.1:1/v1", model="test", timeout=2
|
||||||
|
)
|
||||||
|
|
||||||
|
job = SkillWrite(
|
||||||
|
request=Request("tell me if my package was delivered"),
|
||||||
|
category="tracking",
|
||||||
|
draft=SkillDraft(
|
||||||
|
name="track_delivery", description="Check a package's delivery status."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
undeclared = '''\
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
CONTRACT = {}
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="delivered", new_state="delivered")
|
||||||
|
'''
|
||||||
|
gated = scheduler._fidelity_gate(job, undeclared)
|
||||||
|
rows = [r for r in scheduler.log.read() if r.get("extra", {}).get("phase") == "authoring:fidelity"]
|
||||||
|
assert rows, "the fidelity gate must be a logged decision row"
|
||||||
|
print(f"undeclared reconsider: {rows[-1]['extra']['reconsider']} {rows[-1]['predicted_probs']}")
|
||||||
|
assert rows[-1]["extra"]["reconsider"] is True, (
|
||||||
|
"an undeclared body must be reconsidered"
|
||||||
|
)
|
||||||
|
assert gated == undeclared, "no codegen means the gate returns the body unchanged"
|
||||||
|
|
||||||
|
declared = '''
|
||||||
|
INTEGRATION = {"service": "carrier", "transport": "http", "config_vars": ["tracking_url"]}
|
||||||
|
CONTRACT = {"tracking_url": "Carrier status endpoint."}
|
||||||
|
import json
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
with urllib.request.urlopen(ctx.config["tracking_url"], timeout=15) as response:
|
||||||
|
payload = json.loads(response.read().decode("utf-8"))
|
||||||
|
return ActionResult(
|
||||||
|
action_log=f"carrier returned status {payload['status']}",
|
||||||
|
new_state=payload["status"],
|
||||||
|
)
|
||||||
|
'''
|
||||||
|
scheduler._fidelity_gate(job, declared)
|
||||||
|
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):
|
def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
||||||
@@ -204,22 +620,25 @@ def test_create_skill_empty_category_does_not_wedge(tmp_path):
|
|||||||
scheduler.tree["travel_planning"] = []
|
scheduler.tree["travel_planning"] = []
|
||||||
|
|
||||||
for _ in range(2):
|
for _ in range(2):
|
||||||
status, detail = scheduler.submit("look up flights to japan for february")
|
reply = scheduler.submit("look up flights to japan for february")
|
||||||
print(f"[{status}] {detail}")
|
print(f"[{reply.status}] {reply.text}")
|
||||||
assert status in ("running", "preempted", "queued", "rejected", "error")
|
assert reply.status in ("running", "queued", "rejected", "error")
|
||||||
assert scheduler.current is None, "scheduler must never stay wedged after a submit"
|
assert scheduler.current is None, "scheduler must never stay wedged after a submit"
|
||||||
|
|
||||||
status, detail = scheduler.submit("tell me if my package was delivered")
|
reply = scheduler.submit("tell me if my package was delivered")
|
||||||
print(f"[{status}] {detail}")
|
print(f"[{reply.status}] {reply.text}")
|
||||||
assert scheduler.current is None
|
assert scheduler.current is None
|
||||||
|
|
||||||
|
|
||||||
def test_create_category_chain_runs_new_skill(tmp_path):
|
def test_create_simplex_send_skill(tmp_path):
|
||||||
"""A request that needs a brand-new category must end with a skill run.
|
"""A send request with no matching leaf must author a new simplex skill.
|
||||||
|
|
||||||
Deterministic chain: create_category -> create_skill in the new category ->
|
The `simplex` category already ships the read (`next_message`) and
|
||||||
run that skill (the leaf answers the request, not the category stub). Slow:
|
`connect_link` seeds; "send a message" is a genuinely unmatched action, so
|
||||||
uses real codegen (~7 min). Run in the background.
|
navigation routes it to create_skill. Deterministic chain: create_skill ->
|
||||||
|
async codegen body write -> re-dispatch of the original request -> run the
|
||||||
|
new leaf. Slow: uses real codegen (~25-45 min) and the worker runs in the
|
||||||
|
background, so the test polls the trace. Run in the background.
|
||||||
"""
|
"""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
require_real(config)
|
require_real(config)
|
||||||
@@ -229,17 +648,62 @@ def test_create_category_chain_runs_new_skill(tmp_path):
|
|||||||
config["skill_bodies"] = str(tmp_path / "skills")
|
config["skill_bodies"] = str(tmp_path / "skills")
|
||||||
config["codegen"] = {**config.get("codegen", {}), "stream": True}
|
config["codegen"] = {**config.get("codegen", {}), "stream": True}
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
scheduler.tree = {}
|
|
||||||
|
|
||||||
status, detail = scheduler.submit("track my drone delivery in real time")
|
seeded = {s.name for s in scheduler.tree.get("simplex", [])}
|
||||||
print(f"[{status}] {detail}")
|
assert {"next_message", "send_message", "connect_link"} <= seeded, (
|
||||||
|
f"the simplex seeds must be loaded, got {seeded}"
|
||||||
|
)
|
||||||
|
|
||||||
|
reply = scheduler.submit("send a simplex message to pepper saying hi")
|
||||||
|
print(f"[{reply.status}] {reply.text}")
|
||||||
|
assert reply.status in ("running", "queued", "rejected")
|
||||||
|
assert "new skill for simplex" in reply.text, (
|
||||||
|
"a send request must route to create_skill for simplex"
|
||||||
|
)
|
||||||
|
assert scheduler.current is None, "gate must be free again right after the draft is queued"
|
||||||
|
|
||||||
|
draft_deadline = time.monotonic() + 10 * 60
|
||||||
|
while time.monotonic() < draft_deadline:
|
||||||
rows = scheduler.trace.read()
|
rows = scheduler.trace.read()
|
||||||
kinds = [e["kind"] for e in rows]
|
if any(e["kind"] == "skill_writing" for e in rows):
|
||||||
assert "category_created" in kinds, "category stub must be authored first"
|
break
|
||||||
created = next(e for e in rows if e["kind"] == "skill_created")
|
time.sleep(5)
|
||||||
assert created["written"] is True, "codegen must produce a runnable body"
|
rows = scheduler.trace.read()
|
||||||
assessed = next(e for e in rows if e["kind"] == "assessed")
|
assert not any(e["kind"] == "draft_failed" for e in rows), (
|
||||||
|
"the skill draft must be authored"
|
||||||
|
)
|
||||||
|
writing = [e for e in rows if e["kind"] == "skill_writing"]
|
||||||
|
assert writing and writing[-1]["category"] == "simplex", (
|
||||||
|
"the async body write must be launched for simplex"
|
||||||
|
)
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 55 * 60
|
||||||
|
created = assessed = None
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
rows = scheduler.trace.read()
|
||||||
|
created = next(
|
||||||
|
(
|
||||||
|
e
|
||||||
|
for e in rows
|
||||||
|
if e["kind"] == "skill_created"
|
||||||
|
and e.get("category") == "simplex"
|
||||||
|
and e.get("written")
|
||||||
|
and e.get("skill") not in seeded
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if created:
|
||||||
|
assessed = next(
|
||||||
|
(e for e in rows if e["kind"] == "assessed" and e.get("skill") == created["skill"]),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if assessed:
|
||||||
|
break
|
||||||
|
time.sleep(10)
|
||||||
|
assert created is not None, (
|
||||||
|
"codegen must produce a runnable simplex send body"
|
||||||
|
)
|
||||||
|
assert assessed is not None, "the created skill must run after the body lands"
|
||||||
assert assessed["skill"] == created["skill"], "the created skill must run"
|
assert assessed["skill"] == created["skill"], "the created skill must run"
|
||||||
|
|
||||||
|
|
||||||
@@ -258,10 +722,7 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
|||||||
|
|
||||||
seen = []
|
seen = []
|
||||||
|
|
||||||
def predict(ctx, request):
|
def act(ctx, request):
|
||||||
return Prediction(text="", decisions=[])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
if request.user_input:
|
if request.user_input:
|
||||||
seen.append(request.user_input)
|
seen.append(request.user_input)
|
||||||
return ActionResult(
|
return ActionResult(
|
||||||
@@ -278,7 +739,6 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
|||||||
name="track.manual",
|
name="track.manual",
|
||||||
category="tracking",
|
category="tracking",
|
||||||
description="Resolve a tracking number with the human.",
|
description="Resolve a tracking number with the human.",
|
||||||
predict=predict,
|
|
||||||
act=act,
|
act=act,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -288,9 +748,9 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
|||||||
assert scheduler.pending is not None
|
assert scheduler.pending is not None
|
||||||
assert scheduler.current is not None
|
assert scheduler.current is not None
|
||||||
|
|
||||||
status, detail = scheduler.answer("AB123")
|
reply = scheduler.answer("AB123")
|
||||||
print(f"[{status}] {detail}")
|
print(f"[{reply.status}] {reply.text}")
|
||||||
assert status == "ran"
|
assert reply.status == "ran"
|
||||||
assert seen == ["AB123"]
|
assert seen == ["AB123"]
|
||||||
assert scheduler.pending is None
|
assert scheduler.pending is None
|
||||||
assert scheduler.current is None
|
assert scheduler.current is None
|
||||||
@@ -298,3 +758,72 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
|
|||||||
rows = scheduler.trace.read()
|
rows = scheduler.trace.read()
|
||||||
kinds = [e["kind"] for e in rows]
|
kinds = [e["kind"] for e in rows]
|
||||||
assert "needs_input" in kinds and "answered" in kinds and "assessed" in kinds
|
assert "needs_input" in kinds and "answered" in kinds and "assessed" in kinds
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_result_is_assessed_as_success(tmp_path):
|
||||||
|
"""A query skill whose correct answer is "nothing" is a successful run.
|
||||||
|
|
||||||
|
The `assess:outcome` options must treat a definitive empty/none result
|
||||||
|
(empty inbox, no matching event) as success; otherwise a healthy read is
|
||||||
|
marked failed and the repair loop offers to rewrite 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="no unread SimpleX messages.",
|
||||||
|
new_state="no unread SimpleX messages",
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""Core bridge tests: the shared LLM bridge and the discovery registry.
|
||||||
|
|
||||||
|
Bridge implementations ship with their packs; their hermetic tests live in the
|
||||||
|
pack (see `packs/*/bridge/test_*.py`, run by `tests/test_packs.py`). This file
|
||||||
|
covers what stays in the core: the shared, pack-less LLM bridge and the registry
|
||||||
|
surface (`known_infos`/`describe_bridges`/`derived_config_vars`) that discovers
|
||||||
|
the packs' bridges and renders the catalog codegen reads. The decision engine and
|
||||||
|
a real model are never involved.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.bridges.llm import LLMBridge
|
||||||
|
from semif_agent.bridges.registry import (
|
||||||
|
derived_config_vars,
|
||||||
|
describe_bridges,
|
||||||
|
known_infos,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get(url, token=None):
|
||||||
|
headers = {"X-Semif-Token": token} if token else {}
|
||||||
|
request = urllib.request.Request(url, headers=headers)
|
||||||
|
with urllib.request.urlopen(request, timeout=5) as response:
|
||||||
|
return json.loads(response.read().decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def post(url, payload, token=None):
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if token:
|
||||||
|
headers["X-Semif-Token"] = token
|
||||||
|
request = urllib.request.Request(url, data=body, headers=headers)
|
||||||
|
with urllib.request.urlopen(request, timeout=5) as response:
|
||||||
|
return json.loads(response.read().decode("utf-8"))
|
||||||
|
|
||||||
|
# ---- LLM bridge ----
|
||||||
|
|
||||||
|
class FakeLLMClient:
|
||||||
|
"""Stands in for the scheduler's configured `llm` client."""
|
||||||
|
|
||||||
|
def __init__(self, reply="ok", error=None):
|
||||||
|
self.reply = reply
|
||||||
|
self.error = error
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def chat(self, messages, max_tokens=None):
|
||||||
|
self.calls.append((messages, max_tokens))
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.reply
|
||||||
|
|
||||||
|
|
||||||
|
def start_llm_bridge(client=None, **config):
|
||||||
|
bridge = LLMBridge(config, client=client)
|
||||||
|
port = bridge.start()
|
||||||
|
return bridge, f"http://127.0.0.1:{port}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_chat_returns_model_text():
|
||||||
|
client = FakeLLMClient(reply='{"title": "x", "description": ""}')
|
||||||
|
bridge, base = start_llm_bridge(client)
|
||||||
|
try:
|
||||||
|
messages = [{"role": "user", "content": "add lunch tomorrow"}]
|
||||||
|
assert post(f"{base}/chat", {"messages": messages}) == {
|
||||||
|
"text": client.reply
|
||||||
|
}
|
||||||
|
assert client.calls == [(messages, None)]
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_forwards_max_tokens():
|
||||||
|
client = FakeLLMClient()
|
||||||
|
bridge, base = start_llm_bridge(client)
|
||||||
|
try:
|
||||||
|
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 64})
|
||||||
|
assert client.calls[0][1] == 64
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_rejects_bad_body():
|
||||||
|
bridge, base = start_llm_bridge(FakeLLMClient())
|
||||||
|
try:
|
||||||
|
for payload in ({"messages": []}, {"messages": [{"role": "user"}]}, {}):
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
post(f"{base}/chat", payload)
|
||||||
|
assert exc.value.code == 400
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_without_a_client_is_unavailable():
|
||||||
|
bridge, base = start_llm_bridge(None)
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
|
||||||
|
assert exc.value.code == 502
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_maps_client_error_to_502():
|
||||||
|
bridge, base = start_llm_bridge(FakeLLMClient(error=RuntimeError("down")))
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
|
||||||
|
assert exc.value.code == 502
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_bridge_health_and_token():
|
||||||
|
bridge, base = start_llm_bridge(FakeLLMClient(), token="sekret")
|
||||||
|
try:
|
||||||
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
|
get(f"{base}/health")
|
||||||
|
assert exc.value.code == 401
|
||||||
|
assert get(f"{base}/health", token="sekret") == {"ok": True, "platform": "llm"}
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ---- catalog / codegen surface ----
|
||||||
|
|
||||||
|
def test_known_infos_include_llm():
|
||||||
|
infos = {info.name: info for info in known_infos()}
|
||||||
|
assert "llm" in infos
|
||||||
|
info = infos["llm"]
|
||||||
|
assert info.service == "llm"
|
||||||
|
assert info.url_config_var == "llm_bridge_url"
|
||||||
|
assert info.auth_header == "X-Semif-Token"
|
||||||
|
assert info.auth_config_var == "llm_bridge_token"
|
||||||
|
assert any("/chat" in endpoint for endpoint in info.endpoints)
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_bridge_documents_its_config_vars_and_auth():
|
||||||
|
for info in known_infos():
|
||||||
|
docs = dict(info.config_var_docs)
|
||||||
|
assert set(info.config_vars) <= set(docs), info.name
|
||||||
|
assert all(description.strip() for description in docs.values()), info.name
|
||||||
|
if info.auth_header or info.auth_config_var:
|
||||||
|
assert info.auth_header and info.auth_config_var, info.name
|
||||||
|
assert info.auth_config_var in info.config_vars, info.name
|
||||||
|
|
||||||
|
|
||||||
|
def test_derived_config_vars_come_from_each_bridge_block():
|
||||||
|
config = {
|
||||||
|
"bridges": {
|
||||||
|
"simplex": {"host": "127.0.0.1", "port": 5227, "token": "s"},
|
||||||
|
"llm": {"host": "127.0.0.1", "port": 5229, "token": ""},
|
||||||
|
"nextcloud": {"host": "127.0.0.1", "port": 5230, "token": "n"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
derived = derived_config_vars(config)
|
||||||
|
assert derived["simplex_bridge_url"] == "http://127.0.0.1:5227"
|
||||||
|
assert derived["simplex_bridge_token"] == "s"
|
||||||
|
assert derived["llm_bridge_url"] == "http://127.0.0.1:5229"
|
||||||
|
assert derived["llm_bridge_token"] == ""
|
||||||
|
assert derived["nextcloud_bridge_url"] == "http://127.0.0.1:5230"
|
||||||
|
assert derived["nextcloud_bridge_token"] == "n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_derived_config_vars_normalize_bind_all_host():
|
||||||
|
config = {"bridges": {"llm": {"host": "0.0.0.0", "port": 5229}}}
|
||||||
|
assert derived_config_vars(config)["llm_bridge_url"] == "http://127.0.0.1:5229"
|
||||||
|
|
||||||
|
|
||||||
|
def test_derived_config_vars_skip_unconfigured_bridges():
|
||||||
|
# No block at all: nothing derived, so the contract variable stays
|
||||||
|
# unresolved and the operator is asked for it.
|
||||||
|
assert derived_config_vars({}) == {}
|
||||||
|
# A block without a port is not a callable address: no URL, but the token
|
||||||
|
# var is still satisfiable (empty = no auth).
|
||||||
|
derived = derived_config_vars({"bridges": {"nextcloud": {"token": ""}}})
|
||||||
|
assert "nextcloud_bridge_url" not in derived
|
||||||
|
assert derived["nextcloud_bridge_token"] == ""
|
||||||
|
|
||||||
|
|
||||||
+1572
-60
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,220 @@
|
|||||||
|
"""Codegen privacy invariant: the (primarily-cloud) codegen endpoint is shown
|
||||||
|
ONLY a de-identified spec.
|
||||||
|
|
||||||
|
The user's request, question answers, and run output must never reach a codegen
|
||||||
|
prompt (body, retry, regen, or testgen). These tests assert that structurally
|
||||||
|
(the builders take no `Request`) and behaviourally (no captured message contains
|
||||||
|
a sentinel that only ever lived in the request/run data).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
from semif_agent.codegen import (
|
||||||
|
_regen_body_prompt,
|
||||||
|
_retry_prompt,
|
||||||
|
build_skill_body_prompt,
|
||||||
|
build_testgen_base_prompt,
|
||||||
|
generate_skill_body,
|
||||||
|
generate_skill_tests,
|
||||||
|
regenerate_skill_body,
|
||||||
|
)
|
||||||
|
from semif_agent.decisions import Request
|
||||||
|
from semif_agent.llm import LLMClient
|
||||||
|
from semif_agent.log import DecisionLog
|
||||||
|
from semif_agent.scheduler import Scheduler
|
||||||
|
from semif_agent.skill import RunResult
|
||||||
|
from semif_agent.skills import ActionResult, CategoryRegistry, Skill, SkillDraft
|
||||||
|
from semif_agent.trace import TraceLog
|
||||||
|
|
||||||
|
from tests.conftest import ScriptedEngine
|
||||||
|
|
||||||
|
#: Values that ONLY appear in the user's request / run output. Any of these in a
|
||||||
|
#: codegen message would be a leak.
|
||||||
|
SENTINELS = [
|
||||||
|
"Dana",
|
||||||
|
"dana@corp.example",
|
||||||
|
"Project Falcon",
|
||||||
|
"Oct 15",
|
||||||
|
"hunter2",
|
||||||
|
"4111 1111 1111 1111",
|
||||||
|
]
|
||||||
|
|
||||||
|
GOOD_BODY = """\
|
||||||
|
import urllib.request
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
INTEGRATION = {"service": "probe_service", "transport": "http", "config_vars": ["probe_url"]}
|
||||||
|
CONTRACT = {"probe_url": "The service base URL."}
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
url = ctx.config["probe_url"]
|
||||||
|
with urllib.request.urlopen(f"{url}/status", timeout=15) as resp:
|
||||||
|
body = resp.read().decode("utf-8")
|
||||||
|
return ActionResult(action_log=f"GET {url}/status", new_state=body)
|
||||||
|
"""
|
||||||
|
|
||||||
|
GOOD_TEST = "import sys\nprint('ok')\n"
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingCodegen:
|
||||||
|
"""Minimal codegen client double that captures every outbound message list."""
|
||||||
|
|
||||||
|
stream = False
|
||||||
|
max_attempts = 1
|
||||||
|
|
||||||
|
def __init__(self, reply: str):
|
||||||
|
self.reply = reply
|
||||||
|
self.calls: list[list[dict]] = []
|
||||||
|
|
||||||
|
def chat(self, messages, max_tokens=None, degeneration_check=None, timeout=None):
|
||||||
|
self.calls.append(messages)
|
||||||
|
return self.reply
|
||||||
|
|
||||||
|
def all_text(self) -> str:
|
||||||
|
return "\n".join(
|
||||||
|
message.get("content", "")
|
||||||
|
for messages in self.calls
|
||||||
|
for message in messages
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _draft() -> SkillDraft:
|
||||||
|
return SkillDraft(
|
||||||
|
name="check_status",
|
||||||
|
description="Check the status of a generic HTTP service.",
|
||||||
|
goal="request a service status endpoint and report the response body",
|
||||||
|
integration={"service": "probe_service", "transport": "http"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_clean(text: str) -> None:
|
||||||
|
for sentinel in SENTINELS:
|
||||||
|
assert sentinel not in text, f"codegen message leaked {sentinel!r}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_builders_take_no_request():
|
||||||
|
"""Structural guard: every codegen prompt builder works from the spec only."""
|
||||||
|
for func in (
|
||||||
|
build_skill_body_prompt,
|
||||||
|
_retry_prompt,
|
||||||
|
_regen_body_prompt,
|
||||||
|
build_testgen_base_prompt,
|
||||||
|
generate_skill_body,
|
||||||
|
regenerate_skill_body,
|
||||||
|
generate_skill_tests,
|
||||||
|
):
|
||||||
|
params = inspect.signature(func).parameters
|
||||||
|
assert "request" not in params, f"{func.__name__} must not take a Request"
|
||||||
|
assert "requirements" not in params, (
|
||||||
|
f"{func.__name__} must not take elicitation answers"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_body_and_retry_prompts_carry_only_the_deidentified_goal():
|
||||||
|
tree = {"tracking": []}
|
||||||
|
draft = _draft()
|
||||||
|
body = build_skill_body_prompt("tracking", draft, tree, "THE CONTRACT")
|
||||||
|
retry = _retry_prompt("tracking", draft, "THE CONTRACT", ValueError("bad"))
|
||||||
|
for messages in (body, retry):
|
||||||
|
_assert_clean("\n".join(m.get("content", "") for m in messages))
|
||||||
|
assert draft.goal in body[1]["content"]
|
||||||
|
assert draft.goal in retry[1]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_skill_body_never_sees_run_or_request_data():
|
||||||
|
client = _RecordingCodegen(GOOD_BODY)
|
||||||
|
code = generate_skill_body(client, "tracking", _draft(), {"tracking": []})
|
||||||
|
assert "def act" in code
|
||||||
|
_assert_clean(client.all_text())
|
||||||
|
|
||||||
|
|
||||||
|
def test_regenerate_skill_body_evidence_is_deidentified():
|
||||||
|
client = _RecordingCodegen(GOOD_BODY)
|
||||||
|
evidence = {
|
||||||
|
"failure_kind": "a real run against the live service failed",
|
||||||
|
"goal": _draft().goal,
|
||||||
|
"previous_body": GOOD_BODY,
|
||||||
|
}
|
||||||
|
regenerate_skill_body(client, "tracking", _draft(), GOOD_BODY, evidence)
|
||||||
|
_assert_clean(client.all_text())
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_skill_tests_never_sees_the_request():
|
||||||
|
client = _RecordingCodegen(GOOD_TEST)
|
||||||
|
tests = generate_skill_tests(
|
||||||
|
client, "tracking", _draft(), GOOD_BODY, {"probe_url": "URL"}, contract_md="TESTGEN"
|
||||||
|
)
|
||||||
|
assert tests.strip()
|
||||||
|
_assert_clean(client.all_text())
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_never_stores_the_request_or_answers(tmp_path):
|
||||||
|
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||||
|
registry.register_skill(
|
||||||
|
"tracking",
|
||||||
|
"check_status",
|
||||||
|
"Check a service.",
|
||||||
|
goal="request a service status endpoint and report the response body",
|
||||||
|
)
|
||||||
|
row = registry.read()["tracking"]["skills"][0]
|
||||||
|
assert row["goal"] == "request a service status endpoint and report the response body"
|
||||||
|
assert "request_text" not in row
|
||||||
|
assert "requirements" not in row
|
||||||
|
_assert_clean(str(row))
|
||||||
|
|
||||||
|
|
||||||
|
def _scheduler(tmp_path) -> Scheduler:
|
||||||
|
return Scheduler(
|
||||||
|
engine=ScriptedEngine(default="retry"),
|
||||||
|
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
|
||||||
|
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
|
||||||
|
config={
|
||||||
|
"skills": {},
|
||||||
|
"category_registry": str(tmp_path / "categories.json"),
|
||||||
|
"skill_bodies": str(tmp_path / "skills"),
|
||||||
|
"skill_packs": str(tmp_path / "seeds"),
|
||||||
|
},
|
||||||
|
trace=TraceLog(str(tmp_path / "runs.jsonl")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_repair_evidence_is_deidentified(tmp_path):
|
||||||
|
"""The bundle handed to codegen on repair carries no request or run output."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="ran", new_state="ran")
|
||||||
|
|
||||||
|
skill = Skill(
|
||||||
|
name="check_status",
|
||||||
|
category="tracking",
|
||||||
|
description="Check a service.",
|
||||||
|
act=act,
|
||||||
|
)
|
||||||
|
request = Request(
|
||||||
|
"email Dana at dana@corp.example about Project Falcon on Oct 15; card 4111 1111 1111 1111"
|
||||||
|
)
|
||||||
|
outcome = RunResult(
|
||||||
|
skill="check_status",
|
||||||
|
success=False,
|
||||||
|
summary="failed to reach dana@corp.example",
|
||||||
|
action_log="POST https://svc returned 401 for hunter2",
|
||||||
|
new_state="Dana, Project Falcon, Oct 15",
|
||||||
|
outcome="failed",
|
||||||
|
error="connection refused for Project Falcon",
|
||||||
|
)
|
||||||
|
scheduler._propose_repair(skill, request, outcome)
|
||||||
|
offer = scheduler.repairs[-1]
|
||||||
|
evidence = offer.evidence
|
||||||
|
# Only the de-identified fields are present.
|
||||||
|
assert "request" not in evidence
|
||||||
|
assert "action_log" not in evidence
|
||||||
|
assert "new_state" not in evidence
|
||||||
|
assert "summary" not in evidence
|
||||||
|
assert "error" not in evidence
|
||||||
|
assert evidence["failure_kind"]
|
||||||
|
_assert_clean(repr(evidence))
|
||||||
|
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""The layered config: index includes, !secret resolution, and schema validation.
|
||||||
|
|
||||||
|
These exercise the Home-Assistant-style split directly: config.json is a thin
|
||||||
|
index over fragments, secrets live in a separate file referenced as
|
||||||
|
``"!secret <key>"``, and the core + pack schemas own defaults and validate a
|
||||||
|
live config.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from semif_agent.config import (
|
||||||
|
ConfigError,
|
||||||
|
generate_example_config,
|
||||||
|
iter_secret_refs,
|
||||||
|
load_config_file,
|
||||||
|
load_secrets,
|
||||||
|
missing_secret_refs,
|
||||||
|
resolve_secrets,
|
||||||
|
split_config,
|
||||||
|
validate_config,
|
||||||
|
write_split_config,
|
||||||
|
)
|
||||||
|
from semif_agent.packs import load_packs
|
||||||
|
|
||||||
|
|
||||||
|
def _write(path: Path, data: dict) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(json.dumps(data))
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_includes_deep_merge_later_wins(tmp_path):
|
||||||
|
_write(tmp_path / "config" / "core.json", {"tau": 0.6, "queue": {"max_size": 10}})
|
||||||
|
_write(tmp_path / "config" / "gateway.json", {"gateway": {"simplex": {"enabled": True}}})
|
||||||
|
_write(
|
||||||
|
tmp_path / "config.json",
|
||||||
|
{"include": ["config/core.json", "config/gateway.json"]},
|
||||||
|
)
|
||||||
|
config = load_config_file(tmp_path / "config.json")
|
||||||
|
assert config["tau"] == 0.6
|
||||||
|
assert config["queue"]["max_size"] == 10
|
||||||
|
assert config["gateway"]["simplex"]["enabled"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_include_cycle_is_an_error(tmp_path):
|
||||||
|
_write(tmp_path / "a.json", {"include": ["b.json"]})
|
||||||
|
_write(tmp_path / "b.json", {"include": ["a.json"]})
|
||||||
|
try:
|
||||||
|
load_config_file(tmp_path / "a.json")
|
||||||
|
except ConfigError as exc:
|
||||||
|
assert "cycle" in str(exc)
|
||||||
|
else:
|
||||||
|
raise AssertionError("expected a cycle error")
|
||||||
|
|
||||||
|
|
||||||
|
def test_secret_resolution_and_missing_refs(tmp_path):
|
||||||
|
_write(tmp_path / "secrets.json", {"nextcloud_app_password": "s3cret"})
|
||||||
|
secrets = load_secrets(tmp_path / "secrets.json")
|
||||||
|
config = {
|
||||||
|
"bridges": {"nextcloud": {"app_password": "!secret nextcloud_app_password"}},
|
||||||
|
"llm": {"api_key": "!secret absent_key"},
|
||||||
|
}
|
||||||
|
assert list(iter_secret_refs(config)) == ["nextcloud_app_password", "absent_key"]
|
||||||
|
resolved = resolve_secrets(config, secrets)
|
||||||
|
assert resolved["bridges"]["nextcloud"]["app_password"] == "s3cret"
|
||||||
|
# A missing secret resolves to "" at load (startup never hard-fails) ...
|
||||||
|
assert resolved["llm"]["api_key"] == ""
|
||||||
|
# ... and is reported by the validator.
|
||||||
|
assert missing_secret_refs(config, secrets) == ["absent_key"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_example_marks_secrets_and_never_leaks_values(tmp_path):
|
||||||
|
packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")})
|
||||||
|
example = generate_example_config(packs)
|
||||||
|
# Every secret-typed key is a !secret ref, never a value.
|
||||||
|
assert example["codegen"]["api_key"] == "!secret codegen_api_key"
|
||||||
|
assert example["bridges"]["nextcloud"]["app_password"] == "!secret nextcloud_app_password"
|
||||||
|
assert example["bridges"]["nextcloud"]["token"] == "!secret nextcloud_token"
|
||||||
|
# The pack's non-secret defaults are present.
|
||||||
|
assert example["bridges"]["nextcloud"]["port"] == 5230
|
||||||
|
assert example["packs"]["essentials"]["enabled"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_config_reports_types_unknowns_and_secrets(tmp_path):
|
||||||
|
_write(tmp_path / "secrets.json", {})
|
||||||
|
config = {
|
||||||
|
"tau": "not-a-number",
|
||||||
|
"totally_unknown_key": 1,
|
||||||
|
"codegen": {"api_key": "!secret codegen_api_key"},
|
||||||
|
}
|
||||||
|
problems = validate_config(config, packs=[])
|
||||||
|
assert any("tau: expected float" in p for p in problems)
|
||||||
|
assert any("warning: totally_unknown_key: unknown config key" in p for p in problems)
|
||||||
|
assert "codegen_api_key" in missing_secret_refs(config, load_secrets(tmp_path / "secrets.json"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_then_load_roundtrip(tmp_path):
|
||||||
|
packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")})
|
||||||
|
merged = generate_example_config(packs)
|
||||||
|
written = write_split_config(tmp_path, merged, packs)
|
||||||
|
assert any(p.endswith("config/core.json") for p in written)
|
||||||
|
assert any(p.endswith("config/packs/nextcloud.json") for p in written)
|
||||||
|
# The written index reloads to the same core values.
|
||||||
|
reloaded = load_config_file(tmp_path / "config.json")
|
||||||
|
assert reloaded["tau"] == merged["tau"]
|
||||||
|
assert reloaded["bridges"]["nextcloud"]["port"] == 5230
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_config_places_shared_bridge_outside_packs(tmp_path):
|
||||||
|
packs = load_packs({"skill_packs": str(Path(__file__).resolve().parent.parent / "packs")})
|
||||||
|
merged = generate_example_config(packs)
|
||||||
|
files = split_config(merged, packs)
|
||||||
|
assert "bridges" in files["config/bridges.json"]
|
||||||
|
assert "llm" in files["config/bridges.json"]["bridges"]
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
"""Stdlib tests for the OpenCode Console provider.
|
||||||
|
|
||||||
|
A throwaway stdlib HTTP server stands in for the Console endpoint; the client
|
||||||
|
is real, not mocked. These are hermetic mechanics checks (bearer header, the
|
||||||
|
skipped ollama probe, the preserved error contracts, the model-list parse) —
|
||||||
|
only a real Console call proves the hosted integration. No external network.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
from semif_agent.codegen import CodegenError, DegenerationError
|
||||||
|
from semif_agent.console import (
|
||||||
|
OPENCODE_BASE_URL,
|
||||||
|
ConsoleCodegenClient,
|
||||||
|
ConsoleLLMClient,
|
||||||
|
OpenCodeConsoleClient,
|
||||||
|
OpenCodeError,
|
||||||
|
)
|
||||||
|
from semif_agent.llm import LLMClient, LLMError
|
||||||
|
from semif_agent.provider import ProviderError
|
||||||
|
|
||||||
|
|
||||||
|
def _sse_frame(payload: dict) -> str:
|
||||||
|
return f"data: {json.dumps(payload)}\n\n"
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeConsole(BaseHTTPRequestHandler):
|
||||||
|
"""Records every request (method, path, lowercased headers). Answers GET
|
||||||
|
/models with an OpenAI list and POST with a one-delta SSE reply."""
|
||||||
|
|
||||||
|
reply: str = "{}"
|
||||||
|
models: list = ["kimi-k2.7-code", "glm-5.3"]
|
||||||
|
calls: list = []
|
||||||
|
bodies: list = []
|
||||||
|
|
||||||
|
def _record(self) -> None:
|
||||||
|
type(self).calls.append(
|
||||||
|
(self.command, self.path, {k.lower(): v for k, v in self.headers.items()})
|
||||||
|
)
|
||||||
|
|
||||||
|
def do_GET(self) -> None:
|
||||||
|
self._record()
|
||||||
|
body = json.dumps(
|
||||||
|
{"object": "list", "data": [{"id": m} for m in self.models]}
|
||||||
|
).encode("utf-8")
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length)
|
||||||
|
try:
|
||||||
|
type(self).bodies.append(json.loads(raw.decode("utf-8")))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
self._record()
|
||||||
|
body = (
|
||||||
|
_sse_frame({"choices": [{"delta": {"content": self.reply}}]})
|
||||||
|
+ "data: [DONE]\n\n"
|
||||||
|
).encode("utf-8")
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "text/event-stream")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def log_message(self, *args) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _server(reply: str = "{}", models: list | None = None):
|
||||||
|
attrs = {"reply": reply, "calls": [], "bodies": []}
|
||||||
|
if models is not None:
|
||||||
|
attrs["models"] = models
|
||||||
|
handler = type("Handler", (_FakeConsole,), attrs)
|
||||||
|
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||||
|
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||||
|
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_llm_pins_defaults_and_error_contract():
|
||||||
|
client = ConsoleLLMClient(api_key="k", model="m")
|
||||||
|
assert client.base_url == OPENCODE_BASE_URL
|
||||||
|
assert client.label == "opencode:llm"
|
||||||
|
assert client.error_class is LLMError
|
||||||
|
assert client.degeneration_error_class is LLMError
|
||||||
|
assert client.query_context is False
|
||||||
|
# Console rejects reasoning_effort → forced off despite LLMClient's default.
|
||||||
|
assert client.disable_thinking is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_llm_never_sends_reasoning_effort_even_if_requested():
|
||||||
|
client = ConsoleLLMClient(api_key="k", model="m", disable_thinking=True)
|
||||||
|
assert client.disable_thinking is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_codegen_pins_defaults_and_error_contract():
|
||||||
|
client = ConsoleCodegenClient(api_key="k", model="m")
|
||||||
|
assert client.base_url == OPENCODE_BASE_URL
|
||||||
|
assert client.label == "opencode:codegen"
|
||||||
|
assert client.error_class is CodegenError
|
||||||
|
assert client.degeneration_error_class is DegenerationError
|
||||||
|
assert client.query_context is False
|
||||||
|
# Sampler params are opt-in: unset means None, never sent to the Console.
|
||||||
|
assert client.presence_penalty is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_error_is_provider_error():
|
||||||
|
assert issubclass(OpenCodeError, ProviderError)
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_sends_bearer_and_skips_ollama_probe():
|
||||||
|
httpd, base = _server(reply='{"ok": true}')
|
||||||
|
try:
|
||||||
|
client = ConsoleLLMClient(base_url=base, api_key="secret", model="m", timeout=10)
|
||||||
|
out = client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
assert out == '{"ok": true}'
|
||||||
|
calls = httpd.RequestHandlerClass.calls
|
||||||
|
# query_context=False → the only request is the chat completion.
|
||||||
|
assert [c[1] for c in calls] == ["/chat/completions"]
|
||||||
|
assert calls[0][2]["authorization"] == "Bearer secret"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_chat_omits_sampler_params_by_default():
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
ConsoleLLMClient(base_url=base, api_key="k", model="m", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "hi"}]
|
||||||
|
)
|
||||||
|
body = httpd.RequestHandlerClass.bodies[0]
|
||||||
|
for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
|
||||||
|
assert key not in body
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_chat_sends_configured_sampler_params():
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
ConsoleCodegenClient(
|
||||||
|
base_url=base,
|
||||||
|
api_key="k",
|
||||||
|
model="m",
|
||||||
|
timeout=10,
|
||||||
|
presence_penalty=1.5,
|
||||||
|
).chat([{"role": "user", "content": "hi"}])
|
||||||
|
body = httpd.RequestHandlerClass.bodies[0]
|
||||||
|
assert body["presence_penalty"] == 1.5
|
||||||
|
assert "temperature" not in body
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_plain_llm_without_key_sends_no_auth_header():
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
LLMClient(base_url=base, model="m", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "hi"}]
|
||||||
|
)
|
||||||
|
chat = [
|
||||||
|
c for c in httpd.RequestHandlerClass.calls if c[1].endswith("/chat/completions")
|
||||||
|
]
|
||||||
|
assert chat and "authorization" not in chat[0][2]
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_extra_headers_are_merged():
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
client = ConsoleLLMClient(
|
||||||
|
base_url=base,
|
||||||
|
api_key="k",
|
||||||
|
extra_headers={"X-Route": "edge"},
|
||||||
|
model="m",
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
headers = httpd.RequestHandlerClass.calls[0][2]
|
||||||
|
assert headers["x-route"] == "edge"
|
||||||
|
assert headers["authorization"] == "Bearer k"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_sends_default_user_agent():
|
||||||
|
"""The Console gateway 403s urllib's default Python-urllib UA."""
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
ConsoleLLMClient(base_url=base, model="m", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "hi"}]
|
||||||
|
)
|
||||||
|
ua = httpd.RequestHandlerClass.calls[0][2].get("user-agent")
|
||||||
|
assert ua and "semif-agent" in ua
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_console_user_agent_can_be_overridden():
|
||||||
|
httpd, base = _server(reply="{}")
|
||||||
|
try:
|
||||||
|
ConsoleLLMClient(
|
||||||
|
base_url=base, model="m", timeout=10, user_agent="my-agent/9"
|
||||||
|
).chat([{"role": "user", "content": "hi"}])
|
||||||
|
assert httpd.RequestHandlerClass.calls[0][2]["user-agent"] == "my-agent/9"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_models_parses_catalog():
|
||||||
|
httpd, base = _server(models=["kimi-k2.7-code", "glm-5.3"])
|
||||||
|
try:
|
||||||
|
client = OpenCodeConsoleClient(base_url=base, api_key="k", model="m", timeout=10)
|
||||||
|
assert client.list_models(url=f"{base}/models") == ["kimi-k2.7-code", "glm-5.3"]
|
||||||
|
assert httpd.RequestHandlerClass.calls[0][2]["authorization"] == "Bearer k"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_provider_endpoint_selects_console_and_resolves_key(monkeypatch):
|
||||||
|
from semif_agent import cli
|
||||||
|
|
||||||
|
console = cli._provider_endpoint(
|
||||||
|
{"provider": "opencode"}, "http://localhost:11434/v1"
|
||||||
|
)
|
||||||
|
assert console["base_url"] == OPENCODE_BASE_URL
|
||||||
|
assert console["api_key"] == ""
|
||||||
|
|
||||||
|
ollama = cli._provider_endpoint({"provider": "ollama"}, "http://localhost:11434/v1")
|
||||||
|
assert ollama["base_url"] == "http://localhost:11434/v1"
|
||||||
|
assert ollama["api_key"] == ""
|
||||||
|
|
||||||
|
literal = cli._provider_endpoint({"provider": "opencode", "api_key": "lit"}, "x")
|
||||||
|
assert literal["api_key"] == "lit"
|
||||||
|
|
||||||
|
# api_key_env is gone: it is ignored, never resolved from the environment.
|
||||||
|
monkeypatch.setenv("MY_CONSOLE_KEY", "envkey")
|
||||||
|
legacy = cli._provider_endpoint(
|
||||||
|
{"provider": "opencode", "api_key_env": "MY_CONSOLE_KEY"}, "x"
|
||||||
|
)
|
||||||
|
assert legacy["api_key"] == ""
|
||||||
|
|
||||||
|
explicit = cli._provider_endpoint(
|
||||||
|
{"provider": "opencode", "base_url": "https://example.test/v1"}, "x"
|
||||||
|
)
|
||||||
|
assert explicit["base_url"] == "https://example.test/v1"
|
||||||
@@ -34,11 +34,11 @@ def test_result_selected_and_probs():
|
|||||||
|
|
||||||
def test_request_requeue_preserves_state():
|
def test_request_requeue_preserves_state():
|
||||||
original = Request(text="t", priority=0.7)
|
original = Request(text="t", priority=0.7)
|
||||||
original.resume["from_skill"] = "email.compose"
|
original.resume["from_skill"] = "response.clarify"
|
||||||
updated = original.copy_for_requeue()
|
updated = original.copy_for_requeue()
|
||||||
assert updated.id == original.id
|
assert updated.id == original.id
|
||||||
assert updated.priority == original.priority
|
assert updated.priority == original.priority
|
||||||
assert updated.resume["from_skill"] == "email.compose"
|
assert updated.resume["from_skill"] == "response.clarify"
|
||||||
assert updated.reentries == original.reentries + 1
|
assert updated.reentries == original.reentries + 1
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+406
-20
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
The scheduler is constructed with the lazy SemIfEngine (never loaded), so this
|
The scheduler is constructed with the lazy SemIfEngine (never loaded), so this
|
||||||
runs anywhere without SemIf. Submit degrades to a JSON error, which is the
|
runs anywhere without SemIf. Submit degrades to a JSON error, which is the
|
||||||
expected behaviour on the thin dev box; relabel works against a seeded log.
|
expected behaviour without an engine; relabel works against a seeded log.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -16,26 +16,55 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque
|
|||||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||||
from semif_agent.llm import LLMClient
|
from semif_agent.llm import LLMClient
|
||||||
from semif_agent.log import DecisionLog
|
from semif_agent.log import DecisionLog
|
||||||
from semif_agent.scheduler import Scheduler
|
from semif_agent.scheduler import PendingApproval, PendingQuestion, RepairOffer, Scheduler
|
||||||
from semif_agent.skills import ActionResult, Prediction, Skill
|
from semif_agent.skills import ActionResult, Skill
|
||||||
from semif_agent.trace import TraceLog
|
from semif_agent.trace import TraceLog
|
||||||
|
|
||||||
|
from tests.conftest import ScriptedEngine
|
||||||
|
|
||||||
def build_scheduler(tmp_path):
|
|
||||||
|
def build_scheduler(tmp_path, engine=None):
|
||||||
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
||||||
trace = TraceLog(str(tmp_path / "runs.jsonl"))
|
trace = TraceLog(str(tmp_path / "runs.jsonl"))
|
||||||
engine = SemIfEngine(EngineConfig())
|
engine = engine if engine is not None else ScriptedEngine(default="success")
|
||||||
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
|
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
|
||||||
scheduler = Scheduler(
|
scheduler = Scheduler(
|
||||||
engine=engine,
|
engine=engine,
|
||||||
llm=llm,
|
llm=llm,
|
||||||
log=log,
|
log=log,
|
||||||
config={"skills": {}},
|
config={
|
||||||
|
"skills": {},
|
||||||
|
# Dashboard mechanics tests exercise the authoring path, an opt-in
|
||||||
|
# now that new-skill creation is denied by default.
|
||||||
|
"new_skill_creation": "allow",
|
||||||
|
"skill_packs": str(tmp_path / "seeds"),
|
||||||
|
"skill_bodies": str(tmp_path / "skills"),
|
||||||
|
"category_registry": str(tmp_path / "categories.json"),
|
||||||
|
"deleted_skills": str(tmp_path / "deleted_skills.json"),
|
||||||
|
},
|
||||||
trace=trace,
|
trace=trace,
|
||||||
)
|
)
|
||||||
return scheduler
|
return scheduler
|
||||||
|
|
||||||
|
|
||||||
|
def _generated_skill(scheduler, category, name):
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="ok", new_state="ok")
|
||||||
|
|
||||||
|
skill = Skill(
|
||||||
|
name=name,
|
||||||
|
category=category,
|
||||||
|
description="A generated skill.",
|
||||||
|
act=act,
|
||||||
|
origin="generated",
|
||||||
|
)
|
||||||
|
scheduler.tree.setdefault(category, []).append(skill)
|
||||||
|
scheduler.body_store.write_body(
|
||||||
|
category, name, "def act(ctx, request):\n return None\n"
|
||||||
|
)
|
||||||
|
return skill
|
||||||
|
|
||||||
|
|
||||||
def seed_decision(log, decision_id="abc123"):
|
def seed_decision(log, decision_id="abc123"):
|
||||||
request = DecisionRequest(
|
request = DecisionRequest(
|
||||||
id=decision_id,
|
id=decision_id,
|
||||||
@@ -81,8 +110,159 @@ def test_tree_endpoint(tmp_path):
|
|||||||
try:
|
try:
|
||||||
status, payload = server.get("/api/tree")
|
status, payload = server.get("/api/tree")
|
||||||
assert status == 200
|
assert status == 200
|
||||||
assert "email" in payload["categories"]
|
assert "response" in payload["categories"]
|
||||||
assert any(s["name"] == "email.compose" for s in payload["categories"]["email"])
|
assert any(s["name"] == "response.clarify" for s in payload["categories"]["response"])
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tree_endpoint_carries_skill_status(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="ok", new_state=request.text)
|
||||||
|
|
||||||
|
scheduler.tree["tracking"] = [
|
||||||
|
Skill(name="ready", category="tracking", description="r", act=act),
|
||||||
|
Skill(name="stub", category="tracking", description="s"),
|
||||||
|
]
|
||||||
|
stub = next(s for s in scheduler.tree["tracking"] if s.name == "stub")
|
||||||
|
stub.writing = True
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/tree")
|
||||||
|
assert status == 200
|
||||||
|
by_name = {s["name"]: s["status"] for s in payload["categories"]["tracking"]}
|
||||||
|
assert by_name["ready"] == "ready"
|
||||||
|
assert by_name["stub"] == "writing"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_restart_without_codegen_returns_error_json(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.tree["tracking"] = [
|
||||||
|
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||||
|
]
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post("/api/restart", {"category": "tracking", "skill": "track_live"})
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "error"
|
||||||
|
assert "codegen" in payload["detail"]
|
||||||
|
|
||||||
|
status, payload = server.post("/api/restart", {"category": "tracking", "skill": "missing"})
|
||||||
|
assert payload["status"] == "error"
|
||||||
|
assert "no skill" in payload["detail"]
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tree_endpoint_carries_origin_and_modes(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
_generated_skill(scheduler, "tracking", "track_live")
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/tree")
|
||||||
|
assert status == 200
|
||||||
|
by_name = {s["name"]: s for s in payload["categories"]["tracking"]}
|
||||||
|
assert by_name["track_live"]["origin"] == "generated"
|
||||||
|
assert any(
|
||||||
|
s["origin"] == "builtin"
|
||||||
|
for s in payload["categories"]["housekeeping"]
|
||||||
|
)
|
||||||
|
assert payload["new_skill_modes"]["housekeeping"] == "deny"
|
||||||
|
assert payload["new_skill_modes"]["response"] == "deny"
|
||||||
|
assert payload["new_skill_modes"]["tracking"] == "allow"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_endpoint_removes_skill(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
_generated_skill(scheduler, "tracking", "track_live")
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/delete", {"category": "tracking", "skill": "track_live"}
|
||||||
|
)
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert all(s.name != "track_live" for s in scheduler.tree["tracking"])
|
||||||
|
assert not scheduler.body_store.dir("tracking", "track_live").exists()
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_clear_config_endpoint(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
skill = _generated_skill(scheduler, "tracking", "track_live")
|
||||||
|
skill.config = {"api_key": "x"}
|
||||||
|
scheduler.body_store.write_config("tracking", "track_live", {"api_key": "x"})
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/clear-config", {"category": "tracking", "skill": "track_live"}
|
||||||
|
)
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert scheduler.body_store.read_config("tracking", "track_live") == {}
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_build_endpoint(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
skill = _generated_skill(scheduler, "tracking", "track_live")
|
||||||
|
skill.writing = True
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/cancel-build", {"category": "tracking", "skill": "track_live"}
|
||||||
|
)
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert all(s.name != "track_live" for s in scheduler.tree["tracking"])
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_regen_endpoint_without_codegen_errors(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
_generated_skill(scheduler, "tracking", "track_live")
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/regen", {"category": "tracking", "skill": "track_live"}
|
||||||
|
)
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "error"
|
||||||
|
assert "codegen" in payload["detail"]
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_skill_mode_endpoint_roundtrip(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.tree["tracking"] = []
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/new-skill-modes")
|
||||||
|
assert status == 200
|
||||||
|
assert payload["modes"]["tracking"] == "allow"
|
||||||
|
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/new-skill-mode", {"category": "tracking", "mode": "ask"}
|
||||||
|
)
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
|
||||||
|
status, payload = server.get("/api/tree")
|
||||||
|
assert payload["new_skill_modes"]["tracking"] == "ask"
|
||||||
|
|
||||||
|
status, payload = server.post(
|
||||||
|
"/api/new-skill-mode", {"category": "housekeeping", "mode": "allow"}
|
||||||
|
)
|
||||||
|
assert payload["status"] == "error"
|
||||||
finally:
|
finally:
|
||||||
server.close()
|
server.close()
|
||||||
|
|
||||||
@@ -97,14 +277,95 @@ def test_trace_endpoint_empty(tmp_path):
|
|||||||
server.close()
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
def test_submit_without_engine_returns_error_json(tmp_path):
|
def test_submit_without_engine_returns_fatal_json(tmp_path):
|
||||||
scheduler = build_scheduler(tmp_path)
|
"""The decision engine is always real; if it is unavailable the app is
|
||||||
|
fatal, and the dashboard reports it instead of a soft error."""
|
||||||
|
scheduler = build_scheduler(tmp_path, engine=SemIfEngine(EngineConfig()))
|
||||||
server = Server(scheduler)
|
server = Server(scheduler)
|
||||||
try:
|
try:
|
||||||
status, payload = server.post("/api/submit", {"text": "do something"})
|
status, payload = server.post("/api/submit", {"text": "do something"})
|
||||||
assert status == 200
|
assert status == 200
|
||||||
assert payload["status"] == "error"
|
assert payload["status"] == "fatal"
|
||||||
assert "engine" in payload["detail"]
|
assert "not available" in payload["detail"]
|
||||||
|
assert scheduler.fatal is not None
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_returns_request_id_matching_trace(tmp_path):
|
||||||
|
"""Submit hands the front end the request id so it can open the new run's
|
||||||
|
flow container and follow it as decisions land."""
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post("/api/submit", {"text": "hello"})
|
||||||
|
assert status == 200
|
||||||
|
request_id = payload["request_id"]
|
||||||
|
assert request_id
|
||||||
|
|
||||||
|
status, trace = server.get("/api/trace")
|
||||||
|
assert status == 200
|
||||||
|
assert any(run["run_id"] == request_id for run in trace["runs"])
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
class _ChainEngine:
|
||||||
|
"""Deterministic two-step chain: step 1 -> continue, step 2 -> done."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.assessments = iter(["continue", "done"])
|
||||||
|
|
||||||
|
def call(self, request):
|
||||||
|
ids = [o.id for o in request.options]
|
||||||
|
q = request.question
|
||||||
|
if "additional work to be done" in q:
|
||||||
|
selected = next(self.assessments, "done")
|
||||||
|
elif "logical next step" in q:
|
||||||
|
selected = "demo"
|
||||||
|
elif "what does this skill do" in q:
|
||||||
|
selected = "same"
|
||||||
|
elif "Is this input a request" in q:
|
||||||
|
selected = "action"
|
||||||
|
else:
|
||||||
|
selected = ids[0]
|
||||||
|
if selected not in ids:
|
||||||
|
selected = ids[0]
|
||||||
|
return DecisionResult(
|
||||||
|
request=request,
|
||||||
|
option_ids=ids,
|
||||||
|
probabilities=[1.0 if i == selected else 0.0 for i in ids],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_completes_a_multi_step_chain(tmp_path):
|
||||||
|
"""A `continue` step is queued, not run inline, so a multi-step request only
|
||||||
|
finishes when a front end drains `run_queue()`. The dashboard must do that,
|
||||||
|
as the CLI and gateway do, or the child is stranded in the queue forever."""
|
||||||
|
scheduler = build_scheduler(tmp_path, engine=_ChainEngine())
|
||||||
|
counter = {"n": 0}
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
counter["n"] += 1
|
||||||
|
return ActionResult(action_log=f"step {counter['n']} done", new_state="x")
|
||||||
|
|
||||||
|
scheduler.tree["demo"] = [
|
||||||
|
Skill(name="step", category="demo", description="Do a demo step.", act=act)
|
||||||
|
]
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post("/api/submit", {"text": "do the thing"})
|
||||||
|
assert status == 200
|
||||||
|
# The reply is the final step, not the hidden intermediate.
|
||||||
|
assert payload["status"] == "ran"
|
||||||
|
assert "step 2 done" in payload["detail"]
|
||||||
|
assert counter["n"] == 2
|
||||||
|
# Nothing is left stranded in the queue.
|
||||||
|
assert list(scheduler.queue.items()) == []
|
||||||
|
# The chain ran both steps and linked them.
|
||||||
|
status, trace = server.get("/api/trace")
|
||||||
|
kinds = [e["kind"] for run in trace["runs"] for e in run["events"]]
|
||||||
|
assert "continued" in kinds
|
||||||
finally:
|
finally:
|
||||||
server.close()
|
server.close()
|
||||||
|
|
||||||
@@ -158,7 +419,9 @@ def test_skill_writing_and_created_events_in_payload(tmp_path):
|
|||||||
category="tracking",
|
category="tracking",
|
||||||
skill="track_live",
|
skill="track_live",
|
||||||
description="Follow a package in real time.",
|
description="Follow a package in real time.",
|
||||||
model="qwen38-iq3s",
|
model="test-codegen",
|
||||||
|
contract_ref="a1b2c3d",
|
||||||
|
contract_dirty=True,
|
||||||
)
|
)
|
||||||
scheduler.trace.append(
|
scheduler.trace.append(
|
||||||
"skill_created",
|
"skill_created",
|
||||||
@@ -179,7 +442,9 @@ def test_skill_writing_and_created_events_in_payload(tmp_path):
|
|||||||
writing = next(e for e in run["events"] if e["kind"] == "skill_writing")
|
writing = next(e for e in run["events"] if e["kind"] == "skill_writing")
|
||||||
assert writing["skill"] == "track_live"
|
assert writing["skill"] == "track_live"
|
||||||
assert "real time" in writing["description"]
|
assert "real time" in writing["description"]
|
||||||
assert writing["model"] == "qwen38-iq3s"
|
assert writing["model"] == "test-codegen"
|
||||||
|
assert writing["contract_ref"] == "a1b2c3d"
|
||||||
|
assert writing["contract_dirty"] is True
|
||||||
created = next(e for e in run["events"] if e["kind"] == "skill_created")
|
created = next(e for e in run["events"] if e["kind"] == "skill_created")
|
||||||
assert created["written"] is True
|
assert created["written"] is True
|
||||||
assert created["body"] == "data/skills/tracking/track_live.py"
|
assert created["body"] == "data/skills/tracking/track_live.py"
|
||||||
@@ -188,10 +453,7 @@ def test_skill_writing_and_created_events_in_payload(tmp_path):
|
|||||||
|
|
||||||
|
|
||||||
def need_input_skill(seen):
|
def need_input_skill(seen):
|
||||||
def predict(ctx, request):
|
def act(ctx, request):
|
||||||
return Prediction(text="", decisions=[])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
if request.user_input:
|
if request.user_input:
|
||||||
seen.append(request.user_input)
|
seen.append(request.user_input)
|
||||||
return ActionResult(action_log="ok", new_state=f"done {request.user_input}")
|
return ActionResult(action_log="ok", new_state=f"done {request.user_input}")
|
||||||
@@ -205,7 +467,6 @@ def need_input_skill(seen):
|
|||||||
name="track.manual",
|
name="track.manual",
|
||||||
category="tracking",
|
category="tracking",
|
||||||
description="Resolve a tracking number with the human.",
|
description="Resolve a tracking number with the human.",
|
||||||
predict=predict,
|
|
||||||
act=act,
|
act=act,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -224,13 +485,15 @@ def test_answer_without_pending_returns_error_json(tmp_path):
|
|||||||
|
|
||||||
def test_status_includes_pending(tmp_path):
|
def test_status_includes_pending(tmp_path):
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(tmp_path)
|
||||||
scheduler._run_skill(need_input_skill([]), Request("track my package"))
|
request = Request("track my package")
|
||||||
|
scheduler._run_skill(need_input_skill([]), request)
|
||||||
server = Server(scheduler)
|
server = Server(scheduler)
|
||||||
try:
|
try:
|
||||||
status, payload = server.get("/api/status")
|
status, payload = server.get("/api/status")
|
||||||
assert status == 200
|
assert status == 200
|
||||||
assert payload["pending"]["skill"] == "track.manual"
|
assert payload["pending"]["skill"] == "track.manual"
|
||||||
assert payload["pending"]["question"] == "What's the tracking number?"
|
assert payload["pending"]["question"] == "What's the tracking number?"
|
||||||
|
assert payload["pending"]["run_id"] == request.id
|
||||||
finally:
|
finally:
|
||||||
server.close()
|
server.close()
|
||||||
|
|
||||||
@@ -250,3 +513,126 @@ def test_answer_roundtrip_via_api(tmp_path):
|
|||||||
assert payload["pending"] is None
|
assert payload["pending"] is None
|
||||||
finally:
|
finally:
|
||||||
server.close()
|
server.close()
|
||||||
|
|
||||||
|
def test_answer_accepts_empty_via_api(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
seen.append(request.user_input)
|
||||||
|
if request.user_input is None:
|
||||||
|
return ActionResult(
|
||||||
|
action_log="ask", new_state=request.text, needs_input="Tracking number?"
|
||||||
|
)
|
||||||
|
return ActionResult(action_log="empty answer", new_state="unresolved")
|
||||||
|
|
||||||
|
skill = Skill(name="track.manual", category="tracking", description="", act=act)
|
||||||
|
scheduler._run_skill(skill, Request("track my package"))
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.post("/api/answer", {"text": ""})
|
||||||
|
assert status == 200
|
||||||
|
assert payload["status"] == "ran"
|
||||||
|
assert seen == [None, ""], "empty answer must be forwarded to act"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_questions_endpoint_roundtrip(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.questions.append(
|
||||||
|
PendingQuestion(
|
||||||
|
id="q1", run_id="run-1", category="tracking", skill="probe",
|
||||||
|
question="Which service should it use?",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/questions")
|
||||||
|
assert status == 200
|
||||||
|
assert payload["questions"][0]["id"] == "q1"
|
||||||
|
assert payload["questions"][0]["kind"] == "repair"
|
||||||
|
|
||||||
|
status, payload = server.post("/api/questions", {"id": "q1", "text": "Nextcloud"})
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert scheduler.pending_questions() == []
|
||||||
|
|
||||||
|
status, payload = server.post("/api/questions", {"id": "missing", "text": "x"})
|
||||||
|
assert payload["status"] == "error"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_carries_questions_and_repairs(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.questions.append(
|
||||||
|
PendingQuestion(
|
||||||
|
id="q1", run_id="run-1", category="tracking", skill="probe", question="Q?"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
scheduler.repairs.append(
|
||||||
|
RepairOffer(
|
||||||
|
id="r1", run_id="run-1", category="tracking", skill="tracking.check",
|
||||||
|
selected="retry", reason="boom", request_text="track", failure="boom",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
scheduler.approvals.append(
|
||||||
|
PendingApproval(
|
||||||
|
id="a1", run_id="run-1", kind="skill", category="tracking",
|
||||||
|
skill="track_live", description="Follow a package.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/status")
|
||||||
|
assert payload["questions"][0]["id"] == "q1"
|
||||||
|
assert payload["repairs"][0]["id"] == "r1"
|
||||||
|
assert payload["approvals"][0]["id"] == "a1"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_approvals_endpoint_roundtrip(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.approvals.append(
|
||||||
|
PendingApproval(
|
||||||
|
id="a1", run_id="run-1", kind="category", category="travel",
|
||||||
|
skill="", description="Trips.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/approvals")
|
||||||
|
assert status == 200
|
||||||
|
assert payload["approvals"][0]["id"] == "a1"
|
||||||
|
assert payload["approvals"][0]["kind"] == "category"
|
||||||
|
|
||||||
|
status, payload = server.post("/api/approvals", {"id": "a1", "approve": True})
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert scheduler.pending_approvals() == []
|
||||||
|
|
||||||
|
status, payload = server.post("/api/approvals", {"id": "missing", "approve": False})
|
||||||
|
assert payload["status"] == "error"
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_repairs_endpoint_declines(tmp_path):
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
scheduler.repairs.append(
|
||||||
|
RepairOffer(
|
||||||
|
id="r1", run_id="run-1", category="tracking", skill="tracking.check",
|
||||||
|
selected="repair_skill", reason="boom", request_text="track", failure="boom",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
server = Server(scheduler)
|
||||||
|
try:
|
||||||
|
status, payload = server.get("/api/repairs")
|
||||||
|
assert status == 200
|
||||||
|
assert payload["repairs"][0]["selected"] == "repair_skill"
|
||||||
|
|
||||||
|
status, payload = server.post("/api/repair", {"id": "r1", "action": "no_repair"})
|
||||||
|
assert payload["status"] == "ok"
|
||||||
|
assert scheduler.pending_repairs() == []
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""Engine config wiring: the per-machine GPU-offload knobs and the loader patch.
|
||||||
|
|
||||||
|
Pure stdlib: no SemIf, no llama.cpp, no GGUF. The SemIf backend is CPU-only by
|
||||||
|
construction, so the patch that lets it offload is exercised against a fake
|
||||||
|
backend module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.cli import build_engine, build_engine_config
|
||||||
|
from semif_agent.engine import (
|
||||||
|
DecisionEngine,
|
||||||
|
EngineConfig,
|
||||||
|
SemIfEngine,
|
||||||
|
_install_gpu_state_reset,
|
||||||
|
_offloading_params,
|
||||||
|
)
|
||||||
|
from semif_agent.ollama_systemone import OllamaSystemOneEngine
|
||||||
|
from semif_agent.winnow import WinnowEngine
|
||||||
|
|
||||||
|
PINS = {
|
||||||
|
"engine": {
|
||||||
|
"source": "Qwen/Qwen3.5-4B",
|
||||||
|
"revision": "0" * 40,
|
||||||
|
"gguf_url": "https://example.com/Qwen_Qwen3.5-4B-Q4_K_M.gguf",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_engine_config_defaults_to_cpu():
|
||||||
|
cfg = build_engine_config({"engine": {"backend": "llamacpp"}}, PINS)
|
||||||
|
assert cfg.gpu_layers == 0
|
||||||
|
assert cfg.gpu_device is None
|
||||||
|
assert cfg.gpu_split == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_engine_config_reads_gpu_knobs():
|
||||||
|
cfg = build_engine_config(
|
||||||
|
{"engine": {"gpu_layers": -1, "gpu_device": 1, "gpu_split": 0}}, PINS
|
||||||
|
)
|
||||||
|
assert cfg.gpu_layers == -1
|
||||||
|
assert cfg.gpu_device == 1
|
||||||
|
assert cfg.gpu_split == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_gpu_offload_wrapper_rewrites_model_params():
|
||||||
|
def original(library):
|
||||||
|
return SimpleNamespace(n_gpu_layers=0, main_gpu=0, split_mode=1)
|
||||||
|
|
||||||
|
offloading = _offloading_params(
|
||||||
|
original, EngineConfig(gpu_layers=99, gpu_device=1, gpu_split=0)
|
||||||
|
)
|
||||||
|
params = offloading(object())
|
||||||
|
assert params.n_gpu_layers == 99
|
||||||
|
assert params.main_gpu == 1
|
||||||
|
assert params.split_mode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_gpu_offload_wrapper_leaves_main_gpu_when_device_unset():
|
||||||
|
def original(library):
|
||||||
|
return SimpleNamespace(n_gpu_layers=0, main_gpu=7, split_mode=1)
|
||||||
|
|
||||||
|
offloading = _offloading_params(original, EngineConfig(gpu_layers=-1))
|
||||||
|
params = offloading(object())
|
||||||
|
assert params.n_gpu_layers == -1
|
||||||
|
assert params.main_gpu == 7 # untouched
|
||||||
|
assert params.split_mode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_gpu_state_reset_clears_cache_data():
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class FakeLib:
|
||||||
|
def llama_memory_clear(self, memory, data):
|
||||||
|
calls.append((memory, data))
|
||||||
|
|
||||||
|
engine = SimpleNamespace(lib=FakeLib(), memory="mem")
|
||||||
|
engine.clear = lambda: engine.lib.llama_memory_clear(engine.memory, False)
|
||||||
|
_install_gpu_state_reset(SimpleNamespace(engine=engine))
|
||||||
|
engine.clear()
|
||||||
|
assert calls == [("mem", True)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_engine_defaults_to_the_local_semif_provider():
|
||||||
|
engine = build_engine({"engine": {"backend": "llamacpp"}}, PINS)
|
||||||
|
assert isinstance(engine, SemIfEngine)
|
||||||
|
assert isinstance(engine, DecisionEngine)
|
||||||
|
assert engine.label == "semif"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_engine_selects_the_winnow_provider():
|
||||||
|
engine = build_engine(
|
||||||
|
{
|
||||||
|
"engine": {
|
||||||
|
"provider": "winnow",
|
||||||
|
"winnow": {"base_url": "http://example:8091", "model": "Winnow-12B"},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
PINS,
|
||||||
|
)
|
||||||
|
assert isinstance(engine, WinnowEngine)
|
||||||
|
assert isinstance(engine, DecisionEngine)
|
||||||
|
assert engine.label == "winnow"
|
||||||
|
assert engine.config.base_url == "http://example:8091"
|
||||||
|
assert engine.config.model == "Winnow-12B"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_engine_winnow_requires_a_model():
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_engine_selects_the_ollama_systemone_provider():
|
||||||
|
engine = build_engine(
|
||||||
|
{
|
||||||
|
"engine": {
|
||||||
|
"provider": "ollama",
|
||||||
|
"ollama": {
|
||||||
|
"base_url": "http://example:11434",
|
||||||
|
"model": "clef-flash",
|
||||||
|
"context_tokens": 8192,
|
||||||
|
"keep_alive": "5m",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
PINS,
|
||||||
|
)
|
||||||
|
assert isinstance(engine, OllamaSystemOneEngine)
|
||||||
|
assert isinstance(engine, DecisionEngine)
|
||||||
|
assert engine.label == "ollama"
|
||||||
|
assert engine.config.base_url == "http://example:11434"
|
||||||
|
assert engine.config.model == "clef-flash"
|
||||||
|
assert engine.context_tokens == 8192
|
||||||
|
assert engine.config.keep_alive == "5m"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_engine_ollama_requires_a_model():
|
||||||
|
with pytest.raises(SystemExit):
|
||||||
|
build_engine({"engine": {"provider": "ollama", "ollama": {}}}, PINS)
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,544 @@
|
|||||||
|
"""Pure-stdlib tests for the housekeeping meta skills and per-category modes.
|
||||||
|
|
||||||
|
These cover the deterministic mechanics: name resolution, registry/store
|
||||||
|
deletion, tombstones, the lock gate, and the scheduler operations the meta
|
||||||
|
skills call. The SemIf routing of a natural-language housekeeping request is a
|
||||||
|
real-engine concern, verified by the integration tests on a provisioned host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.decisions import Request
|
||||||
|
from semif_agent.llm import LLMClient
|
||||||
|
from semif_agent.log import DecisionLog
|
||||||
|
from semif_agent.scheduler import Scheduler, SkillWrite
|
||||||
|
from semif_agent.skills import (
|
||||||
|
ActionContext,
|
||||||
|
CategoryRegistry,
|
||||||
|
DeletedSkills,
|
||||||
|
Skill,
|
||||||
|
SkillDraft,
|
||||||
|
SkillStore,
|
||||||
|
apply_tombstones,
|
||||||
|
build_housekeeping_skills,
|
||||||
|
parse_meta_command,
|
||||||
|
resolve_skill_ref,
|
||||||
|
UNABLE_MESSAGE,
|
||||||
|
_cancel_build_act,
|
||||||
|
_delete_skill_act,
|
||||||
|
)
|
||||||
|
from semif_agent.trace import TraceLog
|
||||||
|
|
||||||
|
from tests.conftest import ScriptedEngine
|
||||||
|
|
||||||
|
SEED_BODY = """\
|
||||||
|
from semif_agent.skills import ActionResult
|
||||||
|
|
||||||
|
INTEGRATION = {"service": "probe", "transport": "compute", "config_vars": []}
|
||||||
|
|
||||||
|
CONTRACT = {}
|
||||||
|
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
return ActionResult(action_log="probe ran", new_state="ok")
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _scheduler(tmp_path, choices=None, default="success"):
|
||||||
|
return Scheduler(
|
||||||
|
engine=ScriptedEngine(choices=choices, default=default),
|
||||||
|
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
|
||||||
|
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
|
||||||
|
config={
|
||||||
|
"skills": {},
|
||||||
|
"category_registry": str(tmp_path / "categories.json"),
|
||||||
|
"skill_bodies": str(tmp_path / "skills"),
|
||||||
|
"skill_packs": str(tmp_path / "seeds"),
|
||||||
|
"deleted_skills": str(tmp_path / "deleted_skills.json"),
|
||||||
|
},
|
||||||
|
trace=TraceLog(str(tmp_path / "runs.jsonl")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_skill(scheduler, category, name, origin="generated"):
|
||||||
|
def act(ctx, request):
|
||||||
|
return None
|
||||||
|
|
||||||
|
skill = Skill(
|
||||||
|
name=name,
|
||||||
|
category=category,
|
||||||
|
description=f"{name} description",
|
||||||
|
act=act,
|
||||||
|
origin=origin,
|
||||||
|
)
|
||||||
|
scheduler.tree.setdefault(category, []).append(skill)
|
||||||
|
scheduler.registry.register_skill(category, name, skill.description)
|
||||||
|
scheduler.body_store.write_body(
|
||||||
|
category, name, "def act(ctx, request):\n return None\n"
|
||||||
|
)
|
||||||
|
return skill
|
||||||
|
|
||||||
|
|
||||||
|
def _write_seed(root: Path, category, name):
|
||||||
|
directory = root / category / name
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
(directory / "skill.py").write_text(SEED_BODY)
|
||||||
|
(directory / "contract.json").write_text("{}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- built-ins ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_housekeeping_skills():
|
||||||
|
skills = build_housekeeping_skills()
|
||||||
|
assert {s.name for s in skills} == {
|
||||||
|
"delete_skill",
|
||||||
|
"clear_config",
|
||||||
|
"regen_skill",
|
||||||
|
"cancel_build",
|
||||||
|
}
|
||||||
|
assert all(s.category == "housekeeping" for s in skills)
|
||||||
|
assert all(s.origin == "builtin" for s in skills)
|
||||||
|
assert all(not s.is_noop() for s in skills)
|
||||||
|
assert all(s.category_description for s in skills)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- deterministic meta-command recognition ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_meta_command_forms():
|
||||||
|
assert parse_meta_command("delete skill") == "delete_skill"
|
||||||
|
assert parse_meta_command("delete skill nextcloud.foo") == "delete_skill"
|
||||||
|
assert parse_meta_command("remove skill simplex.next_message") == "delete_skill"
|
||||||
|
assert parse_meta_command("clear config variables") == "clear_config"
|
||||||
|
assert parse_meta_command("clear the config variables for nextcloud.foo") == "clear_config"
|
||||||
|
assert parse_meta_command("clear the settings for simplex.next_message") == "clear_config"
|
||||||
|
assert parse_meta_command("reset a skill's settings") == "clear_config"
|
||||||
|
assert parse_meta_command("regen skill") == "regen_skill"
|
||||||
|
assert parse_meta_command("regenerate the simplex skill") == "regen_skill"
|
||||||
|
assert parse_meta_command("rewrite the code for nextcloud.foo") == "regen_skill"
|
||||||
|
assert parse_meta_command("cancel skill build") == "cancel_build"
|
||||||
|
assert parse_meta_command("cancel the skill build") == "cancel_build"
|
||||||
|
assert parse_meta_command("abort the build") == "cancel_build"
|
||||||
|
assert parse_meta_command("stop building the new skill") == "cancel_build"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_meta_command_leaves_normal_requests_alone():
|
||||||
|
for text in (
|
||||||
|
"what is on my calendar",
|
||||||
|
"read my next simplex message",
|
||||||
|
"hello there",
|
||||||
|
"set a timer for 5 minutes",
|
||||||
|
"send a message to pepper",
|
||||||
|
"what is 255 * 12?",
|
||||||
|
"stop building the deck",
|
||||||
|
"fix my bike",
|
||||||
|
):
|
||||||
|
assert parse_meta_command(text) is None, text
|
||||||
|
|
||||||
|
|
||||||
|
def test_dispatch_routes_meta_command_deterministically(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
|
||||||
|
# clear config runs immediately (no confirmation).
|
||||||
|
result = scheduler._dispatch(Request("clear config variables for nextcloud.foo"))
|
||||||
|
assert result.kind == "ran"
|
||||||
|
assert result.skill == "clear_config"
|
||||||
|
|
||||||
|
# delete routes to the meta skill and pauses for confirmation.
|
||||||
|
delete = scheduler._dispatch(Request("delete skill nextcloud.foo"))
|
||||||
|
assert delete.kind == "needs_input"
|
||||||
|
assert delete.skill == "delete_skill"
|
||||||
|
assert any(e["kind"] == "meta_command" for e in scheduler.trace.read())
|
||||||
|
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
|
||||||
|
# ---- name resolution ----
|
||||||
|
|
||||||
|
|
||||||
|
def _tree():
|
||||||
|
return {
|
||||||
|
"nextcloud": [
|
||||||
|
Skill(name="next_event", category="nextcloud", description="d"),
|
||||||
|
],
|
||||||
|
"simplex": [
|
||||||
|
Skill(name="next_message", category="simplex", description="d"),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_skill_ref_dotted_and_bare():
|
||||||
|
tree = _tree()
|
||||||
|
assert resolve_skill_ref(tree, "delete skill nextcloud.next_event") == (
|
||||||
|
"nextcloud",
|
||||||
|
"next_event",
|
||||||
|
)
|
||||||
|
assert resolve_skill_ref(tree, "delete skill next_message") == (
|
||||||
|
"simplex",
|
||||||
|
"next_message",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_skill_ref_none_and_boundary():
|
||||||
|
tree = {"time": [Skill(name="time", category="time", description="d")]}
|
||||||
|
assert resolve_skill_ref(tree, "delete skill nothing") is None
|
||||||
|
assert resolve_skill_ref(tree, "sometimes I wonder") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_skill_ref_ambiguous():
|
||||||
|
tree = {
|
||||||
|
"a": [Skill(name="ping", category="a", description="d")],
|
||||||
|
"b": [Skill(name="ping", category="b", description="d")],
|
||||||
|
}
|
||||||
|
assert resolve_skill_ref(tree, "delete skill ping") == [("a", "ping"), ("b", "ping")]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- registry / store / tombstones ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_unregister_skill(tmp_path):
|
||||||
|
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||||
|
registry.register_skill("delivery", "track", "Track.")
|
||||||
|
registry.unregister_skill("delivery", "track")
|
||||||
|
assert registry.read()["delivery"]["skills"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_skill_store_delete_and_path_guard(tmp_path):
|
||||||
|
store = SkillStore(str(tmp_path / "skills"))
|
||||||
|
store.write_body("nextcloud", "foo", "x = 1\n")
|
||||||
|
assert store.delete("nextcloud", "foo") is True
|
||||||
|
assert not store.dir("nextcloud", "foo").exists()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
store.delete("..", "escape")
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleted_skills_roundtrip(tmp_path):
|
||||||
|
deleted = DeletedSkills(str(tmp_path / "deleted.json"))
|
||||||
|
assert deleted.read() == set()
|
||||||
|
deleted.add("nextcloud", "foo")
|
||||||
|
assert deleted.contains("nextcloud", "foo")
|
||||||
|
deleted.remove("nextcloud", "foo")
|
||||||
|
assert deleted.read() == set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_apply_tombstones():
|
||||||
|
tree = {
|
||||||
|
"nextcloud": [Skill(name="foo", category="nextcloud", description="d")],
|
||||||
|
"simplex": [Skill(name="bar", category="simplex", description="d")],
|
||||||
|
}
|
||||||
|
deleted = DeletedSkills("/nonexistent/deleted.json")
|
||||||
|
deleted.read = lambda: {"nextcloud.foo"} # type: ignore[assignment]
|
||||||
|
removed = apply_tombstones(tree, deleted)
|
||||||
|
assert removed == 1
|
||||||
|
assert tree["nextcloud"] == []
|
||||||
|
assert [s.name for s in tree["simplex"]] == ["bar"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_seed_is_durable(tmp_path):
|
||||||
|
_write_seed(tmp_path / "seeds", "nextcloud", "probe")
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
assert any(s.name == "probe" for s in scheduler.tree["nextcloud"])
|
||||||
|
assert scheduler.tree["nextcloud"][0].origin == "seed"
|
||||||
|
|
||||||
|
status, _ = scheduler.delete_skill("nextcloud", "probe")
|
||||||
|
assert status == "ok"
|
||||||
|
|
||||||
|
reloaded = _scheduler(tmp_path)
|
||||||
|
assert all(s.name != "probe" for s in reloaded.tree.get("nextcloud", []))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- new-skill modes ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_housekeeping_and_response_are_hard_locked(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
assert scheduler._category_mode("housekeeping") == "deny"
|
||||||
|
assert scheduler._category_mode("response") == "deny"
|
||||||
|
status, _ = scheduler.set_category_mode("housekeeping", "allow")
|
||||||
|
assert status == "error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_category_mode_config_roundtrip(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.tree["notes"] = []
|
||||||
|
# New-skill creation is denied by default (the global fallback).
|
||||||
|
assert scheduler._category_mode("notes") == "deny"
|
||||||
|
|
||||||
|
status, _ = scheduler.set_category_mode("notes", "ask")
|
||||||
|
assert status == "ok"
|
||||||
|
assert scheduler._category_mode("notes") == "ask"
|
||||||
|
config = scheduler.body_store.read_category_config("notes")
|
||||||
|
assert config["new_skill_creation"] == "ask"
|
||||||
|
|
||||||
|
scheduler.set_category_mode("notes", "deny")
|
||||||
|
assert scheduler._category_locked("notes") is True
|
||||||
|
assert any(
|
||||||
|
e["kind"] == "category_mode_set" for e in scheduler.trace.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_category_mode_inherits_global_and_overrides(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.tree["notes"] = []
|
||||||
|
scheduler.new_skill_mode = "ask"
|
||||||
|
assert scheduler._category_mode("notes") == "ask"
|
||||||
|
|
||||||
|
scheduler.set_category_mode("notes", "deny")
|
||||||
|
assert scheduler._category_mode("notes") == "deny"
|
||||||
|
|
||||||
|
# An empty mode clears the override so the category inherits the global.
|
||||||
|
scheduler.set_category_mode("notes", "")
|
||||||
|
assert scheduler._category_mode("notes") == "ask"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dispatch_skill_blocked_when_denied(tmp_path):
|
||||||
|
"""A denied category answers with the plain refusal: the user is never told
|
||||||
|
that new-skill creation (or its config) exists."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.tree["notes"] = []
|
||||||
|
scheduler.set_category_mode("notes", "deny")
|
||||||
|
result = scheduler._dispatch_skill(Request("make a note"), "notes")
|
||||||
|
assert result.kind == "ran"
|
||||||
|
assert result.summary == UNABLE_MESSAGE
|
||||||
|
for leak in ("denied", "new_skill_creation", "config.json", "category", "skill"):
|
||||||
|
assert leak not in result.summary
|
||||||
|
assert any(e["kind"] == "skill_create_blocked" for e in scheduler.trace.read())
|
||||||
|
|
||||||
|
|
||||||
|
def test_dispatch_create_category_denied_is_silent(tmp_path):
|
||||||
|
"""Global `deny` answers a request that would author a category with the
|
||||||
|
plain refusal, and still traces the block for operators."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.new_skill_mode = "deny"
|
||||||
|
scheduler.tree = {}
|
||||||
|
result = scheduler._dispatch(Request("book a trip to japan"))
|
||||||
|
assert result.kind == "ran"
|
||||||
|
assert result.summary == UNABLE_MESSAGE
|
||||||
|
assert result.result == UNABLE_MESSAGE
|
||||||
|
assert any(
|
||||||
|
e["kind"] == "category_create_blocked" for e in scheduler.trace.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_stub_under_deny_is_silent(tmp_path):
|
||||||
|
"""A leftover empty leaf in a denied category refuses plainly instead of
|
||||||
|
telling the user to `restart` the body write."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.tree["notes"] = []
|
||||||
|
scheduler.set_category_mode("notes", "deny")
|
||||||
|
stub = Skill(name="stub", category="notes", description="d")
|
||||||
|
result = scheduler._run_skill(stub, Request("make a note"))
|
||||||
|
assert result.summary == UNABLE_MESSAGE
|
||||||
|
assert "restart" not in result.summary
|
||||||
|
assert any(e["kind"] == "skill_create_blocked" for e in scheduler.trace.read())
|
||||||
|
|
||||||
|
|
||||||
|
def test_restart_skill_blocked_when_denied(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.tree["notes"] = [
|
||||||
|
Skill(name="stub", category="notes", description="d")
|
||||||
|
]
|
||||||
|
scheduler.set_category_mode("notes", "deny")
|
||||||
|
status, _ = scheduler.restart_skill("notes", "stub")
|
||||||
|
assert status == "error"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- operations ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_skill_removes_tree_registry_and_folder(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
status, detail = scheduler.delete_skill("nextcloud", "foo")
|
||||||
|
assert status == "ok"
|
||||||
|
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
assert scheduler.body_store.read_contract("nextcloud", "foo") == {}
|
||||||
|
assert not scheduler.body_store.dir("nextcloud", "foo").exists()
|
||||||
|
assert all(
|
||||||
|
s.get("name") != "foo"
|
||||||
|
for s in scheduler.registry.read()["nextcloud"]["skills"]
|
||||||
|
)
|
||||||
|
assert scheduler.deleted.contains("nextcloud", "foo")
|
||||||
|
assert any(e["kind"] == "skill_deleted" for e in scheduler.trace.read())
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_refuses_builtin(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
status, _ = scheduler.delete_skill("housekeeping", "delete_skill")
|
||||||
|
assert status == "error"
|
||||||
|
status, _ = scheduler.delete_skill("response", "response.clarify")
|
||||||
|
assert status == "error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_clear_skill_config(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
skill.config = {"api_key": "x"}
|
||||||
|
scheduler.body_store.write_config("nextcloud", "foo", {"api_key": "x"})
|
||||||
|
|
||||||
|
status, detail = scheduler.clear_skill_config("nextcloud", "foo")
|
||||||
|
assert status == "ok"
|
||||||
|
assert "api_key" in detail
|
||||||
|
assert scheduler.body_store.read_config("nextcloud", "foo") == {}
|
||||||
|
assert skill.config == {}
|
||||||
|
assert any(e["kind"] == "config_cleared" for e in scheduler.trace.read())
|
||||||
|
|
||||||
|
|
||||||
|
def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.codegen = object()
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def fake_start(request, category, draft, repair_evidence=None, reason_kind="run_failure"):
|
||||||
|
captured.update(
|
||||||
|
category=category,
|
||||||
|
repair_evidence=repair_evidence,
|
||||||
|
reason_kind=reason_kind,
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
|
||||||
|
status, _ = scheduler.regen_skill("nextcloud", "foo", "it crashes")
|
||||||
|
assert status == "running"
|
||||||
|
assert captured["reason_kind"] == "manual"
|
||||||
|
assert captured["repair_evidence"]["guidance"] == "it crashes"
|
||||||
|
assert any(
|
||||||
|
e["kind"] == "skill_regen_started" for e in scheduler.trace.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_regen_skill_stub_has_no_evidence(tmp_path, monkeypatch):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
scheduler.codegen = object()
|
||||||
|
scheduler.tree["nextcloud"] = [
|
||||||
|
Skill(name="stub", category="nextcloud", description="d")
|
||||||
|
]
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def fake_start(request, category, draft, repair_evidence=None, reason_kind="run_failure"):
|
||||||
|
captured.update(repair_evidence=repair_evidence, reason_kind=reason_kind)
|
||||||
|
|
||||||
|
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
|
||||||
|
status, _ = scheduler.regen_skill("nextcloud", "stub", "make it work")
|
||||||
|
assert status == "running"
|
||||||
|
assert captured["repair_evidence"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_skill_build_discards_and_deletes(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
skill.writing = True
|
||||||
|
scheduler._writes.append(
|
||||||
|
SkillWrite(
|
||||||
|
request=Request("build foo"),
|
||||||
|
category="nextcloud",
|
||||||
|
draft=SkillDraft(name="foo", description="d"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
status, detail = scheduler.cancel_skill_build("nextcloud", "foo")
|
||||||
|
assert status == "ok"
|
||||||
|
assert "cancelled" in detail
|
||||||
|
assert ("nextcloud", "foo") in scheduler._cancelled
|
||||||
|
assert not any(w.draft.name == "foo" for w in scheduler._writes)
|
||||||
|
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
assert not scheduler.body_store.dir("nextcloud", "foo").exists()
|
||||||
|
assert any(
|
||||||
|
e["kind"] == "skill_build_cancelled" for e in scheduler.trace.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_consume_cancelled_discards_queued_write(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
job = SkillWrite(
|
||||||
|
request=Request("build foo"),
|
||||||
|
category="nextcloud",
|
||||||
|
draft=SkillDraft(name="foo", description="d"),
|
||||||
|
)
|
||||||
|
scheduler._cancelled.add(("nextcloud", "foo"))
|
||||||
|
assert scheduler._consume_cancelled(job) is True
|
||||||
|
assert ("nextcloud", "foo") not in scheduler._cancelled
|
||||||
|
assert any(
|
||||||
|
e["kind"] == "skill_write_cancelled" for e in scheduler.trace.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- meta-skill act flows ----
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_skill_act_confirms_then_deletes(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||||
|
request = Request("delete skill nextcloud.foo")
|
||||||
|
|
||||||
|
first = _delete_skill_act(ctx, request)
|
||||||
|
assert first.needs_input and "confirm" in first.needs_input.lower()
|
||||||
|
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
request.user_input = "yes"
|
||||||
|
second = _delete_skill_act(ctx, request)
|
||||||
|
assert second.needs_input is None
|
||||||
|
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_skill_act_asks_for_target_when_absent(tmp_path):
|
||||||
|
"""A name-free request ("delete skill") asks for the target as an input
|
||||||
|
variable, then confirms, then deletes."""
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||||
|
request = Request("delete skill")
|
||||||
|
|
||||||
|
first = _delete_skill_act(ctx, request)
|
||||||
|
assert first.needs_input and "which skill" in first.needs_input.lower()
|
||||||
|
|
||||||
|
request.user_input = "nextcloud.foo"
|
||||||
|
second = _delete_skill_act(ctx, request)
|
||||||
|
assert second.needs_input and "confirm" in second.needs_input.lower()
|
||||||
|
|
||||||
|
request.user_input = "yes"
|
||||||
|
third = _delete_skill_act(ctx, request)
|
||||||
|
assert third.needs_input is None
|
||||||
|
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_skill_act_declined_keeps_skill(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||||
|
request = Request("delete skill nextcloud.foo")
|
||||||
|
_delete_skill_act(ctx, request)
|
||||||
|
request.user_input = "no"
|
||||||
|
result = _delete_skill_act(ctx, request)
|
||||||
|
assert result.needs_input is None
|
||||||
|
assert "cancelled" in result.action_log
|
||||||
|
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_build_act_targets_writing_skill(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
skill.writing = True
|
||||||
|
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||||
|
|
||||||
|
request = Request("cancel the skill build")
|
||||||
|
first = _cancel_build_act(ctx, request)
|
||||||
|
assert first.needs_input and "cancel" in first.needs_input.lower()
|
||||||
|
request.user_input = "yes"
|
||||||
|
second = _cancel_build_act(ctx, request)
|
||||||
|
assert second.needs_input is None
|
||||||
|
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_build_act_reports_when_nothing_writing(tmp_path):
|
||||||
|
scheduler = _scheduler(tmp_path)
|
||||||
|
_add_skill(scheduler, "nextcloud", "foo")
|
||||||
|
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||||
|
result = _cancel_build_act(ctx, Request("cancel the skill build"))
|
||||||
|
assert result.needs_input is None
|
||||||
|
assert "no skill build" in result.action_log
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""Pure-stdlib tests for the gateway's optional LLM result cleanup.
|
||||||
|
|
||||||
|
The `Humanizer` is a thin, always-falls-back rephraser over an injected client;
|
||||||
|
the gateway wires it to the scheduler's `llm` client and only for result lines.
|
||||||
|
No engine and no real LLM endpoint are involved — a fake client records the
|
||||||
|
call and returns a canned reply.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from semif_agent.gateway.humanize import Humanizer, _clean_reply
|
||||||
|
from semif_agent.gateway.service import GatewayService
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, reply="", error=None):
|
||||||
|
self.reply = reply
|
||||||
|
self.error = error
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def chat(self, messages, max_tokens=None, timeout=None, **kwargs):
|
||||||
|
self.calls.append(
|
||||||
|
{"messages": messages, "max_tokens": max_tokens, "timeout": timeout}
|
||||||
|
)
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.reply
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAdapter:
|
||||||
|
name = "simplex"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeScheduler:
|
||||||
|
def __init__(self, llm):
|
||||||
|
self.llm = llm
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Humanizer: rewriting + fallback ----
|
||||||
|
|
||||||
|
def test_humanize_rewrites_and_passes_timeout():
|
||||||
|
client = FakeClient(reply="Your event was added to the calendar.")
|
||||||
|
h = Humanizer(client, timeout=7.0, max_tokens=64)
|
||||||
|
assert h.humanize("PUT 201 created") == "Your event was added to the calendar."
|
||||||
|
call = client.calls[0]
|
||||||
|
assert call["timeout"] == 7.0
|
||||||
|
assert call["max_tokens"] == 64
|
||||||
|
assert "PUT 201 created" in call["messages"][1]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_collapses_whitespace_and_strips_quotes():
|
||||||
|
client = FakeClient(reply='"Done.\n All good."')
|
||||||
|
assert Humanizer(client).humanize("ok") == "Done. All good."
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_falls_back_on_client_error():
|
||||||
|
client = FakeClient(error=RuntimeError("unreachable"))
|
||||||
|
assert Humanizer(client).humanize("raw result") == "raw result"
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_falls_back_on_empty_reply():
|
||||||
|
client = FakeClient(reply=" ")
|
||||||
|
assert Humanizer(client).humanize("raw result") == "raw result"
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_falls_back_on_runaway_length():
|
||||||
|
client = FakeClient(reply="x" * 1000)
|
||||||
|
assert Humanizer(client, max_chars=100).humanize("raw") == "raw"
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_disabled_is_passthrough_without_calling():
|
||||||
|
client = FakeClient(reply="should not be used")
|
||||||
|
h = Humanizer(client, enabled=False)
|
||||||
|
assert h.humanize("raw result") == "raw result"
|
||||||
|
assert client.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_humanize_no_client_is_disabled():
|
||||||
|
h = Humanizer(None)
|
||||||
|
assert h.enabled is False
|
||||||
|
assert h.humanize("raw result") == "raw result"
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_reply_handles_empty():
|
||||||
|
assert _clean_reply("") == ""
|
||||||
|
assert _clean_reply(None) == ""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- gateway wiring ----
|
||||||
|
|
||||||
|
def build_service(llm, config):
|
||||||
|
return GatewayService(FakeScheduler(llm), FakeAdapter(), config=config)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_humanizes_only_result_lines():
|
||||||
|
llm = FakeClient(reply="It is 12:00.")
|
||||||
|
service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}})
|
||||||
|
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
|
||||||
|
service._reply("simplex", "c", "queued", kind="status")
|
||||||
|
service._reply("simplex", "c", "Which account?", kind="question")
|
||||||
|
assert [service.outbound["simplex"].get_nowait().text for _ in range(3)] == [
|
||||||
|
"It is 12:00.",
|
||||||
|
"queued",
|
||||||
|
"Which account?",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_humanize_off_by_default():
|
||||||
|
llm = FakeClient(reply="should not be used")
|
||||||
|
service = build_service(llm, {"simplex": {}})
|
||||||
|
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00"
|
||||||
|
assert llm.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_per_platform_override_enables():
|
||||||
|
llm = FakeClient(reply="It is 12:00.")
|
||||||
|
service = build_service(
|
||||||
|
llm, {"humanize": {"enabled": False}, "simplex": {"humanize": True}}
|
||||||
|
)
|
||||||
|
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "It is 12:00."
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_per_platform_override_disables():
|
||||||
|
llm = FakeClient(reply="should not be used")
|
||||||
|
service = build_service(
|
||||||
|
llm, {"humanize": {"enabled": True}, "simplex": {"humanize": False}}
|
||||||
|
)
|
||||||
|
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00"
|
||||||
|
assert llm.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_humanize_keeps_wrapper_when_result_only_off():
|
||||||
|
# Humanize unwraps the scheduler wrapper, like result_only, but only for
|
||||||
|
# the result line — status chatter still flows on a plain chat platform.
|
||||||
|
llm = FakeClient(reply="Done.")
|
||||||
|
service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}})
|
||||||
|
service._reply("simplex", "c", "track.manual: ok — sent", kind="result")
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "Done."
|
||||||
|
|
||||||
|
|
||||||
|
# ---- per-skill override (the skill's own config.json) ----
|
||||||
|
|
||||||
|
class FakeStore:
|
||||||
|
"""Stands in for the scheduler's `body_store` (SkillStore)."""
|
||||||
|
|
||||||
|
def __init__(self, configs):
|
||||||
|
self.configs = configs # {(category, name): {...}}
|
||||||
|
|
||||||
|
def read_config(self, category, name):
|
||||||
|
return self.configs.get((category, name), {})
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSchedulerWithStore(FakeScheduler):
|
||||||
|
def __init__(self, llm, store):
|
||||||
|
super().__init__(llm)
|
||||||
|
self.body_store = store
|
||||||
|
|
||||||
|
|
||||||
|
def build_service_with_store(llm, config, store):
|
||||||
|
return GatewayService(
|
||||||
|
FakeSchedulerWithStore(llm, store), FakeAdapter(), config=config
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_skill_config_disables_humanize():
|
||||||
|
"""A skill whose own config sets humanize:false is not cleaned up, even
|
||||||
|
when the platform/global default is on."""
|
||||||
|
llm = FakeClient(reply="should not be used")
|
||||||
|
store = FakeStore({("time", "now"): {"humanize": False}})
|
||||||
|
service = build_service_with_store(
|
||||||
|
llm, {"humanize": {"enabled": True}, "simplex": {}}, store
|
||||||
|
)
|
||||||
|
service._reply(
|
||||||
|
"simplex", "c", "time.now: ok — 12:00", kind="result",
|
||||||
|
skill_ref="time.now", result="12:00",
|
||||||
|
)
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00"
|
||||||
|
assert llm.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_skill_config_enables_humanize_over_platform():
|
||||||
|
"""A skill's own humanize:true wins over a disabled platform/global default."""
|
||||||
|
llm = FakeClient(reply="It is 12:00.")
|
||||||
|
store = FakeStore({("time", "now"): {"humanize": True}})
|
||||||
|
service = build_service_with_store(
|
||||||
|
llm,
|
||||||
|
{"humanize": {"enabled": False}, "simplex": {"humanize": False}},
|
||||||
|
store,
|
||||||
|
)
|
||||||
|
service._reply(
|
||||||
|
"simplex", "c", "time.now: ok — 12:00", kind="result",
|
||||||
|
skill_ref="time.now", result="12:00",
|
||||||
|
)
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "It is 12:00."
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_skill_config_absent_falls_back_to_platform():
|
||||||
|
"""No skill override -> the platform/global default applies."""
|
||||||
|
llm = FakeClient(reply="It is 12:00.")
|
||||||
|
store = FakeStore({})
|
||||||
|
service = build_service_with_store(
|
||||||
|
llm, {"humanize": {"enabled": True}, "simplex": {}}, store
|
||||||
|
)
|
||||||
|
service._reply(
|
||||||
|
"simplex", "c", "time.now: ok — 12:00", kind="result",
|
||||||
|
skill_ref="time.now", result="12:00",
|
||||||
|
)
|
||||||
|
assert service.outbound["simplex"].get_nowait().text == "It is 12:00."
|
||||||
+68
-39
@@ -2,39 +2,37 @@
|
|||||||
|
|
||||||
A skill can pause its run by returning ActionResult(..., needs_input="<q>");
|
A skill can pause its run by returning ActionResult(..., needs_input="<q>");
|
||||||
the scheduler keeps the run pending, and `answer` resumes it by re-invoking
|
the scheduler keeps the run pending, and `answer` resumes it by re-invoking
|
||||||
only `act` with the human's answer on request.user_input. No mocking: the
|
only `act` with the human's answer on request.user_input. Assessment is now a
|
||||||
scheduler uses the lazy engine (never loaded) and a real-but-unreachable LLM
|
SemIf decision, so these mechanics tests drive the loop with a deterministic
|
||||||
endpoint, so assessments degrade to failure — which is fine for these tests.
|
scripted engine (see conftest) rather than loading the real GGUF.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
|
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
|
||||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
|
||||||
from semif_agent.llm import LLMClient
|
from semif_agent.llm import LLMClient
|
||||||
from semif_agent.log import DecisionLog
|
from semif_agent.log import DecisionLog
|
||||||
from semif_agent.scheduler import Scheduler
|
from semif_agent.scheduler import Scheduler
|
||||||
from semif_agent.skills import ActionResult, Prediction, Skill
|
from semif_agent.skills import ActionResult, Skill
|
||||||
from semif_agent.trace import TraceLog
|
from semif_agent.trace import TraceLog
|
||||||
|
|
||||||
|
from tests.conftest import ScriptedEngine
|
||||||
|
|
||||||
def build_scheduler(tmp_path):
|
|
||||||
|
def build_scheduler(tmp_path, choices=None):
|
||||||
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
|
||||||
trace = TraceLog(str(tmp_path / "runs.jsonl"))
|
trace = TraceLog(str(tmp_path / "runs.jsonl"))
|
||||||
engine = SemIfEngine(EngineConfig())
|
engine = ScriptedEngine(choices=choices, default="success")
|
||||||
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
|
llm = LLMClient(base_url="http://localhost:1/v1", model="test")
|
||||||
return Scheduler(
|
return Scheduler(
|
||||||
engine=engine,
|
engine=engine,
|
||||||
llm=llm,
|
llm=llm,
|
||||||
log=log,
|
log=log,
|
||||||
config={"skills": {}},
|
config={"skills": {}, "skill_packs": str(tmp_path / "seeds")},
|
||||||
trace=trace,
|
trace=trace,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def need_input_skill(seen):
|
def need_input_skill(seen):
|
||||||
def predict(ctx, request):
|
def act(ctx, request):
|
||||||
return Prediction(text="", decisions=[])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
if request.user_input:
|
if request.user_input:
|
||||||
seen.append(request.user_input)
|
seen.append(request.user_input)
|
||||||
return ActionResult(
|
return ActionResult(
|
||||||
@@ -50,7 +48,6 @@ def need_input_skill(seen):
|
|||||||
name="track.manual",
|
name="track.manual",
|
||||||
category="tracking",
|
category="tracking",
|
||||||
description="Resolve a tracking number with the human.",
|
description="Resolve a tracking number with the human.",
|
||||||
predict=predict,
|
|
||||||
act=act,
|
act=act,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -68,10 +65,10 @@ def test_skill_pause_and_answer(tmp_path):
|
|||||||
assert scheduler.pending.question == "What's the tracking number?"
|
assert scheduler.pending.question == "What's the tracking number?"
|
||||||
assert scheduler.current is not None
|
assert scheduler.current is not None
|
||||||
assert scheduler.current.skill == "track.manual"
|
assert scheduler.current.skill == "track.manual"
|
||||||
assert scheduler.log.read() == [], "predict decisions must be deferred until completion"
|
assert scheduler.log.read() == [], "sub-decisions must be deferred until completion"
|
||||||
|
|
||||||
status, detail = scheduler.answer("AB123")
|
reply = scheduler.answer("AB123")
|
||||||
assert status == "ran"
|
assert reply.status == "ran"
|
||||||
assert seen == ["AB123"]
|
assert seen == ["AB123"]
|
||||||
assert scheduler.pending is None
|
assert scheduler.pending is None
|
||||||
assert scheduler.current is None
|
assert scheduler.current is None
|
||||||
@@ -85,12 +82,12 @@ def test_skill_pause_and_answer(tmp_path):
|
|||||||
|
|
||||||
def test_answer_without_pending_is_error(tmp_path):
|
def test_answer_without_pending_is_error(tmp_path):
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(tmp_path)
|
||||||
status, detail = scheduler.answer("hello")
|
reply = scheduler.answer("hello")
|
||||||
assert status == "error"
|
assert reply.status == "error"
|
||||||
assert "waiting for input" in detail
|
assert "waiting for input" in reply.text
|
||||||
|
|
||||||
|
|
||||||
def test_predict_decisions_logged_on_completion(tmp_path):
|
def test_act_decisions_logged_on_completion(tmp_path):
|
||||||
decision = DecisionRequest(
|
decision = DecisionRequest(
|
||||||
state="s", question="which?", options=[Option("a", "A."), Option("b", "B.")]
|
state="s", question="which?", options=[Option("a", "A."), Option("b", "B.")]
|
||||||
)
|
)
|
||||||
@@ -98,27 +95,32 @@ def test_predict_decisions_logged_on_completion(tmp_path):
|
|||||||
request=decision, option_ids=["a", "b"], probabilities=[0.3, 0.7]
|
request=decision, option_ids=["a", "b"], probabilities=[0.3, 0.7]
|
||||||
)
|
)
|
||||||
|
|
||||||
def predict(ctx, request):
|
def act(ctx, request):
|
||||||
return Prediction(text="", decisions=[(decision, result)])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
if request.user_input:
|
if request.user_input:
|
||||||
return ActionResult(action_log="ok", new_state="done")
|
return ActionResult(
|
||||||
|
action_log="ok", new_state="done", decisions=[(decision, result)]
|
||||||
|
)
|
||||||
return ActionResult(
|
return ActionResult(
|
||||||
action_log="ask", new_state=request.text, needs_input="confirm?"
|
action_log="ask", new_state=request.text, needs_input="confirm?"
|
||||||
)
|
)
|
||||||
|
|
||||||
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
|
skill = Skill(name="t.x", category="t", description="", act=act)
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(
|
||||||
|
tmp_path,
|
||||||
|
choices={"additional work to be done": "failed"},
|
||||||
|
)
|
||||||
|
|
||||||
scheduler._run_skill(skill, Request("x"))
|
scheduler._run_skill(skill, Request("x"))
|
||||||
assert scheduler.log.read() == []
|
assert scheduler.log.read() == []
|
||||||
|
|
||||||
scheduler.answer("yes")
|
scheduler.answer("yes")
|
||||||
rows = scheduler.log.read()
|
rows = scheduler.log.read()
|
||||||
assert len(rows) == 1
|
act_rows = [r for r in rows if r.get("extra", {}).get("phase") == "act"]
|
||||||
assert rows[0]["extra"]["phase"] == "predict"
|
assert len(act_rows) == 1
|
||||||
assert rows[0]["extra"]["run_ok"] is False
|
assert act_rows[0]["extra"]["run_ok"] is False
|
||||||
|
phases = [r.get("extra", {}).get("phase") for r in rows]
|
||||||
|
assert "assess:outcome" in phases
|
||||||
|
assert "assess:requeue" not in phases
|
||||||
|
|
||||||
|
|
||||||
def test_busy_abandons_pending(tmp_path):
|
def test_busy_abandons_pending(tmp_path):
|
||||||
@@ -145,10 +147,7 @@ def test_idle_abandons_pending(tmp_path):
|
|||||||
def test_resume_can_ask_again(tmp_path):
|
def test_resume_can_ask_again(tmp_path):
|
||||||
seen = []
|
seen = []
|
||||||
|
|
||||||
def predict(ctx, request):
|
def act(ctx, request):
|
||||||
return Prediction(text="", decisions=[])
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
|
||||||
if request.user_input == "AB123":
|
if request.user_input == "AB123":
|
||||||
return ActionResult(action_log="done", new_state="resolved")
|
return ActionResult(action_log="done", new_state="resolved")
|
||||||
if request.user_input:
|
if request.user_input:
|
||||||
@@ -162,16 +161,46 @@ def test_resume_can_ask_again(tmp_path):
|
|||||||
action_log="ask", new_state=request.text, needs_input="Tracking number?"
|
action_log="ask", new_state=request.text, needs_input="Tracking number?"
|
||||||
)
|
)
|
||||||
|
|
||||||
skill = Skill(name="t.x", category="t", description="", predict=predict, act=act)
|
skill = Skill(name="t.x", category="t", description="", act=act)
|
||||||
scheduler = build_scheduler(tmp_path)
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
|
||||||
scheduler._run_skill(skill, Request("track"))
|
scheduler._run_skill(skill, Request("track"))
|
||||||
status, detail = scheduler.answer("XYZ")
|
reply = scheduler.answer("XYZ")
|
||||||
assert status == "needs_input"
|
assert reply.status == "needs_input"
|
||||||
assert seen == ["XYZ"]
|
assert seen == ["XYZ"]
|
||||||
assert scheduler.pending is not None
|
assert scheduler.pending is not None
|
||||||
|
|
||||||
status, detail = scheduler.answer("AB123")
|
reply = scheduler.answer("AB123")
|
||||||
assert status == "ran"
|
assert reply.status == "ran"
|
||||||
assert scheduler.pending is None
|
assert scheduler.pending is None
|
||||||
assert scheduler.current is None
|
assert scheduler.current is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_answer_is_accepted_and_forwarded(tmp_path):
|
||||||
|
"""An act-driven pause always accepts an empty answer: it is forwarded to
|
||||||
|
`act` as user_input='' (never rejected). A body that cannot proceed without
|
||||||
|
the info simply produces a failed run, which assessment handles."""
|
||||||
|
scheduler = build_scheduler(tmp_path)
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def act(ctx, request):
|
||||||
|
seen.append(request.user_input)
|
||||||
|
if request.user_input is None:
|
||||||
|
return ActionResult(
|
||||||
|
action_log="ask",
|
||||||
|
new_state=request.text,
|
||||||
|
needs_input="What's the tracking number?",
|
||||||
|
)
|
||||||
|
return ActionResult(action_log="empty answer", new_state="unresolved")
|
||||||
|
|
||||||
|
skill = Skill(name="track.manual", category="tracking", description="", act=act)
|
||||||
|
result = scheduler._run_skill(skill, Request("track my package"))
|
||||||
|
assert result.kind == "needs_input"
|
||||||
|
|
||||||
|
reply = scheduler.answer("")
|
||||||
|
assert reply.status == "ran", reply.text
|
||||||
|
assert seen == [None, ""], "the empty answer must reach act"
|
||||||
|
assert scheduler.pending is None
|
||||||
|
assert scheduler.current is None
|
||||||
|
answered = [e for e in scheduler.trace.read() if e["kind"] == "answered"]
|
||||||
|
assert answered and answered[-1]["skipped"] is True
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
"""Pure-stdlib tests for the `llm` authoring provider.
|
||||||
|
|
||||||
|
A throwaway stdlib HTTP server stands in for the OpenAI-compatible endpoint —
|
||||||
|
the LLMClient itself is real, not mocked.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.decisions import Request
|
||||||
|
from semif_agent.llm import LLMClient, LLMError, SemIfLLMClient
|
||||||
|
from semif_agent.skills import (
|
||||||
|
CategoryDraft,
|
||||||
|
SkillDraft,
|
||||||
|
build_skills,
|
||||||
|
build_tree,
|
||||||
|
generate_category,
|
||||||
|
generate_skill_spec,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _sse_frame(payload: dict) -> str:
|
||||||
|
return f"data: {json.dumps(payload)}\n\n"
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeOpenAI(BaseHTTPRequestHandler):
|
||||||
|
"""Single-shot SSE server: the reply arrives as one content delta. The
|
||||||
|
`/api/show` window query is answered too but never recorded."""
|
||||||
|
|
||||||
|
reply: str = ""
|
||||||
|
received: list = []
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length).decode("utf-8")
|
||||||
|
if self.path.rstrip("/").endswith("/api/show"):
|
||||||
|
body = json.dumps({"parameters": {"num_ctx": 32768}}).encode("utf-8")
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
return
|
||||||
|
type(self).received.append(json.loads(raw))
|
||||||
|
body = (
|
||||||
|
_sse_frame({"choices": [{"delta": {"content": self.reply}}]})
|
||||||
|
+ "data: [DONE]\n\n"
|
||||||
|
).encode("utf-8")
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "text/event-stream")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def log_message(self, format, *args) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_server(reply: str) -> tuple[ThreadingHTTPServer, str]:
|
||||||
|
handler = type("Handler", (_FakeOpenAI,), {"reply": reply, "received": []})
|
||||||
|
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||||
|
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||||
|
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_json_extracts_object_from_prose():
|
||||||
|
parsed = LLMClient._parse_json('Sure, here: {"a": 1, "b": "two"} — done.')
|
||||||
|
assert parsed == {"a": 1, "b": "two"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_json_handles_bare_object():
|
||||||
|
assert LLMClient._parse_json('{"ok": true}') == {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_returns_streamed_content():
|
||||||
|
httpd, base = _fake_server('{"title": "track_live", "description": "Follow it."}')
|
||||||
|
try:
|
||||||
|
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||||
|
out = client.chat([{"role": "user", "content": "name this"}])
|
||||||
|
assert out == '{"title": "track_live", "description": "Follow it."}'
|
||||||
|
assert httpd.RequestHandlerClass.received[0]["model"] == "test"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_category_via_provider():
|
||||||
|
httpd, base = _fake_server(
|
||||||
|
'{"title": "Track Delivery", "description": "Track parcels end to end."}'
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||||
|
draft = generate_category(
|
||||||
|
client, Request("where is my parcel?"), build_tree(build_skills({"skills": {}}))
|
||||||
|
)
|
||||||
|
assert isinstance(draft, CategoryDraft)
|
||||||
|
assert draft.name == "track_delivery"
|
||||||
|
assert draft.description == "Track parcels end to end."
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_skill_via_provider():
|
||||||
|
httpd, base = _fake_server(
|
||||||
|
'{"title": "track.live", "description": "Follow a package in real time.", '
|
||||||
|
'"goal": "poll a parcel tracking endpoint and report status", '
|
||||||
|
'"service": "tracking", "transport": "http"}'
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
client = LLMClient(base_url=base, model="test", timeout=10)
|
||||||
|
draft = generate_skill_spec(
|
||||||
|
client,
|
||||||
|
Request("track my drone delivery"),
|
||||||
|
"tracking",
|
||||||
|
build_tree(build_skills({"skills": {}})),
|
||||||
|
)
|
||||||
|
assert isinstance(draft, SkillDraft)
|
||||||
|
assert draft.name == "track.live"
|
||||||
|
assert draft.goal == "poll a parcel tracking endpoint and report status"
|
||||||
|
assert draft.integration == {"service": "tracking", "transport": "http"}
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_omits_sampler_params_by_default():
|
||||||
|
"""No sampler params are sent unless the `llm` config sets them, so the
|
||||||
|
server's model default applies."""
|
||||||
|
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||||
|
try:
|
||||||
|
LLMClient(base_url=base, model="test", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "name this"}]
|
||||||
|
)
|
||||||
|
body = httpd.RequestHandlerClass.received[0]
|
||||||
|
for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
|
||||||
|
assert key not in body
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_sends_configured_sampler_params():
|
||||||
|
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||||
|
try:
|
||||||
|
LLMClient(
|
||||||
|
base_url=base,
|
||||||
|
model="test",
|
||||||
|
timeout=10,
|
||||||
|
temperature=0.2,
|
||||||
|
top_p=0.9,
|
||||||
|
presence_penalty=0.0,
|
||||||
|
frequency_penalty=0.0,
|
||||||
|
).chat([{"role": "user", "content": "name this"}])
|
||||||
|
body = httpd.RequestHandlerClass.received[0]
|
||||||
|
assert body["temperature"] == 0.2
|
||||||
|
assert body["top_p"] == 0.9
|
||||||
|
assert body["presence_penalty"] == 0.0
|
||||||
|
assert body["frequency_penalty"] == 0.0
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_disables_thinking_by_default():
|
||||||
|
"""The title/description author sends reasoning_effort:none so a reasoning
|
||||||
|
model answers the short JSON directly (its CoT otherwise eats the 128-token
|
||||||
|
reply budget and leaves `content` empty)."""
|
||||||
|
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||||
|
try:
|
||||||
|
LLMClient(base_url=base, model="test", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "name this"}]
|
||||||
|
)
|
||||||
|
assert httpd.RequestHandlerClass.received[0]["reasoning_effort"] == "none"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_thinking_can_be_re_enabled():
|
||||||
|
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||||
|
try:
|
||||||
|
LLMClient(base_url=base, model="test", timeout=10, disable_thinking=False).chat(
|
||||||
|
[{"role": "user", "content": "name this"}]
|
||||||
|
)
|
||||||
|
assert "reasoning_effort" not in httpd.RequestHandlerClass.received[0]
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_codegen_keeps_thinking():
|
||||||
|
"""Codegen wants the chain-of-thought: the knob must not leak into it."""
|
||||||
|
from semif_agent.codegen import CodegenClient
|
||||||
|
|
||||||
|
httpd, base = _fake_server("def act(ctx, request):\n pass\n")
|
||||||
|
try:
|
||||||
|
CodegenClient(base_url=base, model="test", timeout=10).chat(
|
||||||
|
[{"role": "user", "content": "write a body"}]
|
||||||
|
)
|
||||||
|
assert "reasoning_effort" not in httpd.RequestHandlerClass.received[0]
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreachable_endpoint_raises_llm_error():
|
||||||
|
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
|
||||||
|
with pytest.raises(LLMError):
|
||||||
|
client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeEngine:
|
||||||
|
"""Duck-typed stand-in for SemIfEngine: records generate() calls."""
|
||||||
|
|
||||||
|
def __init__(self, reply: str = "", error: Exception | None = None):
|
||||||
|
self.reply = reply
|
||||||
|
self.error = error
|
||||||
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
|
def generate(self, messages, temperature: float = 0.0, max_tokens: int = 256) -> str:
|
||||||
|
self.calls.append(
|
||||||
|
{"messages": messages, "temperature": temperature, "max_tokens": max_tokens}
|
||||||
|
)
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.reply
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_generates_via_engine():
|
||||||
|
"""provider == "semif": the loaded engine model answers; a per-call
|
||||||
|
max_tokens override wins over the client default."""
|
||||||
|
engine = _FakeEngine('{"title": "track_live", "description": "Follow it."}')
|
||||||
|
client = SemIfLLMClient(engine, temperature=0.0, max_tokens=256)
|
||||||
|
out = client.chat([{"role": "user", "content": "name this"}], max_tokens=128)
|
||||||
|
assert out == '{"title": "track_live", "description": "Follow it."}'
|
||||||
|
call = engine.calls[0]
|
||||||
|
assert call["max_tokens"] == 128
|
||||||
|
assert call["temperature"] == 0.0
|
||||||
|
assert call["messages"] == [{"role": "user", "content": "name this"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_accepts_http_provider_kwargs():
|
||||||
|
"""It is a drop-in for the HTTP clients: sampler/timeout/degeneration
|
||||||
|
arguments are accepted and ignored, defaults apply."""
|
||||||
|
engine = _FakeEngine("hello")
|
||||||
|
out = SemIfLLMClient(engine).chat(
|
||||||
|
[{"role": "user", "content": "hi"}],
|
||||||
|
top_p=0.9,
|
||||||
|
presence_penalty=0.1,
|
||||||
|
frequency_penalty=0.0,
|
||||||
|
timeout=5.0,
|
||||||
|
degeneration_check=lambda _text: None,
|
||||||
|
)
|
||||||
|
assert out == "hello"
|
||||||
|
assert engine.calls[0]["max_tokens"] == 256
|
||||||
|
assert engine.calls[0]["temperature"] == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_wraps_engine_failure_as_llm_error():
|
||||||
|
client = SemIfLLMClient(_FakeEngine(error=RuntimeError("boom")))
|
||||||
|
with pytest.raises(LLMError):
|
||||||
|
client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_llm_client_selects_provider():
|
||||||
|
"""build_llm_client maps llm.provider to the right client class; the semif
|
||||||
|
branch needs no model and wraps the supplied engine."""
|
||||||
|
from semif_agent import cli
|
||||||
|
from semif_agent.console import ConsoleLLMClient
|
||||||
|
|
||||||
|
engine = _FakeEngine("x")
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "semif"}}, engine), SemIfLLMClient
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "ollama", "model": "m"}}, engine),
|
||||||
|
LLMClient,
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "opencode", "model": "m"}}, engine),
|
||||||
|
ConsoleLLMClient,
|
||||||
|
)
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"""Pure-stdlib tests for the neutral LXMF (Reticulum) transport.
|
||||||
|
|
||||||
|
`lxmf`/`rns` are optional and lazy-imported, so these tests exercise the
|
||||||
|
stdlib-only helpers and the missing-dependency contract without the real
|
||||||
|
package (and without touching a real Reticulum network). The live transport is
|
||||||
|
a live-integration concern.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from semif_agent.gateway.lxmf import LxmfAdapter
|
||||||
|
from semif_agent.lxmf_transport import (
|
||||||
|
AM_OPUS_OGG,
|
||||||
|
FIELD_AUDIO,
|
||||||
|
LxmfDaemon,
|
||||||
|
audio_fields,
|
||||||
|
normalize_message,
|
||||||
|
parse_audio_field,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- requirements ----
|
||||||
|
|
||||||
|
def test_requires_config_dir():
|
||||||
|
ok, hint = LxmfDaemon(config_dir="", storage_path="x").check_requirements()
|
||||||
|
assert ok is False
|
||||||
|
assert "config_dir" in hint
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_check_requirements_never_raises():
|
||||||
|
# Either lxmf is installed (True) or an install hint is returned (False);
|
||||||
|
# the adapter must never raise on a machine without the optional dep.
|
||||||
|
ok, hint = LxmfAdapter({}).check_requirements()
|
||||||
|
assert isinstance(ok, bool)
|
||||||
|
if not ok:
|
||||||
|
assert "lxmf" in hint
|
||||||
|
|
||||||
|
|
||||||
|
# ---- adapter defaults ----
|
||||||
|
|
||||||
|
def test_adapter_uses_runtime_lxmf_paths_by_default():
|
||||||
|
adapter = LxmfAdapter({})
|
||||||
|
assert adapter.config_dir.endswith(".runtime/lxmf/reticulum")
|
||||||
|
assert adapter.storage_path.endswith(".runtime/lxmf/router")
|
||||||
|
assert adapter.daemon.address == ""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- normalization ----
|
||||||
|
|
||||||
|
def test_normalize_message_tolerates_fakes():
|
||||||
|
class _Src:
|
||||||
|
display_name = "alice"
|
||||||
|
|
||||||
|
class _Msg:
|
||||||
|
source_hash = bytes.fromhex("ab" * 16)
|
||||||
|
content = b"hello"
|
||||||
|
title = b"subj"
|
||||||
|
timestamp = 123.0
|
||||||
|
|
||||||
|
def get_source(self):
|
||||||
|
return _Src()
|
||||||
|
|
||||||
|
normalized = normalize_message(_Msg())
|
||||||
|
assert normalized["source_hash"] == "ab" * 16
|
||||||
|
assert normalized["content"] == "hello"
|
||||||
|
assert normalized["title"] == "subj"
|
||||||
|
assert normalized["display_name"] == "alice"
|
||||||
|
assert normalized["timestamp"] == 123.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_message_prefers_as_string_helpers():
|
||||||
|
class _Msg:
|
||||||
|
source_hash = b"\x01\x02"
|
||||||
|
content = b"raw"
|
||||||
|
title = b"rawtitle"
|
||||||
|
|
||||||
|
def content_as_string(self):
|
||||||
|
return "decoded content"
|
||||||
|
|
||||||
|
def title_as_string(self):
|
||||||
|
return "decoded title"
|
||||||
|
|
||||||
|
normalized = normalize_message(_Msg())
|
||||||
|
assert normalized["source_hash"] == "0102"
|
||||||
|
assert normalized["content"] == "decoded content"
|
||||||
|
assert normalized["title"] == "decoded title"
|
||||||
|
assert normalized["display_name"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_message_handles_none_content():
|
||||||
|
class _Msg:
|
||||||
|
source_hash = b""
|
||||||
|
content = None
|
||||||
|
title = None
|
||||||
|
|
||||||
|
def content_as_string(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def title_as_string(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
normalized = normalize_message(_Msg())
|
||||||
|
assert normalized["source_hash"] == ""
|
||||||
|
assert normalized["content"] == ""
|
||||||
|
assert normalized["title"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- voice (Sideband push-to-talk) audio field ----
|
||||||
|
|
||||||
|
def test_parse_audio_field_opus_ogg_uses_the_container_path():
|
||||||
|
audio = parse_audio_field([0x10, b"OggS-payload"])
|
||||||
|
assert audio == {
|
||||||
|
"codec": 0x10,
|
||||||
|
"codec_name": "opus_ogg",
|
||||||
|
"data": b"OggS-payload",
|
||||||
|
"kind": "opus_ogg",
|
||||||
|
"codec2_rate": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_audio_field_codec2_maps_to_a_bitrate():
|
||||||
|
audio = parse_audio_field([0x08, b"\x00\x01"])
|
||||||
|
assert audio["codec_name"] == "codec2_2400"
|
||||||
|
assert audio["kind"] == "codec2"
|
||||||
|
assert audio["codec2_rate"] == 2400
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_audio_field_450_codec2_has_no_binding():
|
||||||
|
# 450PWB/450 have no pycodec2 bindings, so they stay undecodable.
|
||||||
|
audio = parse_audio_field([0x01, b"\x00\x01"])
|
||||||
|
assert audio["kind"] == "unknown"
|
||||||
|
assert audio["codec2_rate"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_audio_field_rejects_malformed():
|
||||||
|
assert parse_audio_field("nope") is None
|
||||||
|
assert parse_audio_field([0x10]) is None
|
||||||
|
assert parse_audio_field([0x10, "not-bytes"]) is None
|
||||||
|
assert parse_audio_field(["x", b"data"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_message_extracts_audio_field():
|
||||||
|
class _Msg:
|
||||||
|
source_hash = bytes.fromhex("ab" * 16)
|
||||||
|
content = b""
|
||||||
|
title = b""
|
||||||
|
fields = {0x07: [0x10, b"OggS"]}
|
||||||
|
|
||||||
|
normalized = normalize_message(_Msg())
|
||||||
|
assert normalized["audio"]["codec_name"] == "opus_ogg"
|
||||||
|
assert normalized["audio"]["data"] == b"OggS"
|
||||||
|
assert normalized["audio"]["kind"] == "opus_ogg"
|
||||||
|
assert normalized["fields"][0x07][0] == 0x10
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_message_without_fields_has_no_audio():
|
||||||
|
class _Msg:
|
||||||
|
content = b"plain text"
|
||||||
|
|
||||||
|
normalized = normalize_message(_Msg())
|
||||||
|
assert normalized["audio"] is None
|
||||||
|
assert normalized["fields"] == {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---- outbound voice replies ----
|
||||||
|
|
||||||
|
def test_audio_fields_wraps_ogg_as_sideband_hq_ptt():
|
||||||
|
fields = audio_fields(b"OggS-payload")
|
||||||
|
assert fields == {FIELD_AUDIO: [AM_OPUS_OGG, b"OggS-payload"]}
|
||||||
|
assert AM_OPUS_OGG == 0x10
|
||||||
|
|
||||||
|
|
||||||
|
def test_audio_fields_none_for_text_or_empty():
|
||||||
|
assert audio_fields(None) is None
|
||||||
|
assert audio_fields(b"") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_enqueue_carries_audio_on_the_outbound_queue():
|
||||||
|
daemon = LxmfDaemon(config_dir="x", storage_path="y")
|
||||||
|
daemon.enqueue("ab" * 16, "hello", audio=b"OggS")
|
||||||
|
assert daemon._outbound.get_nowait() == ("ab" * 16, "hello", b"OggS")
|
||||||
|
# The stop sentinel is unchanged.
|
||||||
|
daemon.enqueue(None)
|
||||||
|
assert daemon._outbound.get_nowait() is None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- interface-transition re-announce ----
|
||||||
|
|
||||||
|
def test_announce_records_time_and_reason():
|
||||||
|
daemon = LxmfDaemon(config_dir="x", storage_path="y")
|
||||||
|
announced = []
|
||||||
|
|
||||||
|
class _Router:
|
||||||
|
def announce(self, destination_hash):
|
||||||
|
announced.append(destination_hash)
|
||||||
|
|
||||||
|
class _Destination:
|
||||||
|
hash = b"\x00" * 16
|
||||||
|
|
||||||
|
daemon._router = _Router()
|
||||||
|
daemon._destination = _Destination()
|
||||||
|
assert daemon._last_announce == 0.0
|
||||||
|
daemon._announce("startup")
|
||||||
|
assert announced == [b"\x00" * 16]
|
||||||
|
assert daemon._last_announce > 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_scan_interfaces_flags_only_newly_online(monkeypatch):
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
|
||||||
|
class _Iface:
|
||||||
|
def __init__(self, name, online):
|
||||||
|
self._name = name
|
||||||
|
self.online = online
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self._name
|
||||||
|
|
||||||
|
a = _Iface("A", False)
|
||||||
|
b = _Iface("B", True)
|
||||||
|
fake_rns = types.SimpleNamespace(
|
||||||
|
Transport=types.SimpleNamespace(interfaces=[a, b])
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(sys.modules, "RNS", fake_rns)
|
||||||
|
|
||||||
|
daemon = LxmfDaemon(config_dir="x", storage_path="y")
|
||||||
|
daemon._interface_states = {"A": False, "B": True}
|
||||||
|
|
||||||
|
assert daemon._scan_interfaces() is False # steady state: nothing changed
|
||||||
|
a.online = True
|
||||||
|
assert daemon._scan_interfaces() is True # A came online
|
||||||
|
assert daemon._scan_interfaces() is False # now recorded online
|
||||||
|
fake_rns.Transport.interfaces.append(_Iface("C", True))
|
||||||
|
assert daemon._scan_interfaces() is True # a fresh peer interface
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Guard: no deployment-specific artifacts in tracked files.
|
||||||
|
|
||||||
|
The repo is generic. Hostnames, addresses, usernames, absolute home paths, and
|
||||||
|
the local model choices of any one deployment must not leak into tracked files —
|
||||||
|
they belong in the gitignored ``local/`` folder (see ``local/ENVIRONMENT.md``).
|
||||||
|
This test fails if a denylisted term reappears anywhere in the tree.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
# Generated/ignored trees and binary assets. ``local/`` is the intended home
|
||||||
|
# for deployment specifics and is gitignored, so it is exempt.
|
||||||
|
SKIP_DIRS = {".git", ".runtime", "local", "data", ".pytest_cache", "__pycache__"}
|
||||||
|
SKIP_SUFFIXES = {
|
||||||
|
".pyc", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico",
|
||||||
|
".woff", ".woff2", ".ttf", ".pdf", ".zip", ".gz",
|
||||||
|
}
|
||||||
|
SKIP_NAMES = {Path(__file__).name}
|
||||||
|
# Fallback (non-git) walk: skip gitignored per-machine artifacts by name/pattern.
|
||||||
|
SKIP_GLOBS = ("config.json", "*.bak.*", "*.log")
|
||||||
|
|
||||||
|
# label -> regex. Kept specific so a legitimate generic term is not flagged.
|
||||||
|
DENYLIST = {
|
||||||
|
"deployment hostname": r"jarvis|guppy",
|
||||||
|
"operator username": r"\babby\b",
|
||||||
|
"ssh key comment": r"shitass",
|
||||||
|
"git owner": r"gabby",
|
||||||
|
"git host": r"manyworlds",
|
||||||
|
"lan address": r"192\.168\.8\.",
|
||||||
|
"local codegen model": r"qwen38",
|
||||||
|
"local llm model": r"qwen3\.5:4b",
|
||||||
|
"stale llm default": r"qwen2\.5:3b",
|
||||||
|
"absolute home path": r"/home/abby",
|
||||||
|
"old venv path": r"semif-venv",
|
||||||
|
"machine descriptor": r"\b(?:dev box|dev machine|staging box)\b",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _git_tracked_files() -> list[Path] | None:
|
||||||
|
"""Tracked files from git (so gitignored per-machine files are exempt).
|
||||||
|
|
||||||
|
Returns ``None`` when git is unavailable or this is not a checkout, so the
|
||||||
|
guard still works on an extracted tarball via the walk fallback.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
out = subprocess.run(
|
||||||
|
["git", "-C", str(REPO_ROOT), "ls-files", "-z"],
|
||||||
|
capture_output=True,
|
||||||
|
check=True,
|
||||||
|
).stdout
|
||||||
|
except (OSError, subprocess.CalledProcessError):
|
||||||
|
return None
|
||||||
|
names = [n for n in out.decode("utf-8", "surrogateescape").split("\0") if n]
|
||||||
|
return [REPO_ROOT / n for n in names]
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_tracked_text_files():
|
||||||
|
"""Yield candidate files, pruning ignored trees and binary assets."""
|
||||||
|
tracked = _git_tracked_files()
|
||||||
|
if tracked is not None:
|
||||||
|
candidates = tracked
|
||||||
|
else:
|
||||||
|
candidates = []
|
||||||
|
for dirpath, dirnames, filenames in os.walk(REPO_ROOT):
|
||||||
|
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
||||||
|
for name in filenames:
|
||||||
|
path = Path(dirpath) / name
|
||||||
|
if any(path.match(g) for g in SKIP_GLOBS):
|
||||||
|
continue
|
||||||
|
candidates.append(path)
|
||||||
|
for path in candidates:
|
||||||
|
if path.name in SKIP_NAMES or path.suffix in SKIP_SUFFIXES:
|
||||||
|
continue
|
||||||
|
yield path
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_deployment_specific_artifacts():
|
||||||
|
hits: list[str] = []
|
||||||
|
for path in _iter_tracked_text_files():
|
||||||
|
try:
|
||||||
|
text = path.read_text(encoding="utf-8")
|
||||||
|
except (UnicodeDecodeError, OSError):
|
||||||
|
continue
|
||||||
|
for label, pattern in DENYLIST.items():
|
||||||
|
for match in re.finditer(pattern, text, re.IGNORECASE):
|
||||||
|
line = text.count("\n", 0, match.start()) + 1
|
||||||
|
hits.append(
|
||||||
|
f"{path.relative_to(REPO_ROOT)}:{line}: {label} "
|
||||||
|
f"-> {match.group(0)!r}"
|
||||||
|
)
|
||||||
|
assert not hits, "deployment-specific artifacts in tracked files:\n" + "\n".join(
|
||||||
|
hits
|
||||||
|
)
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
"""Pure-stdlib tests for the Ollama System One decision engine provider.
|
||||||
|
|
||||||
|
The engine is exercised over a real loopback HTTP server (the transport is not
|
||||||
|
mocked): the handler records requests and returns canned ollama
|
||||||
|
``/api/version``, ``/api/show``, and ``/v1/systemone`` responses, so the tests
|
||||||
|
prove the decision-contract mapping, the ollama-specific probing, and the strict
|
||||||
|
distribution validation. No model, no GGUF, no external network.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.decisions import DecisionRequest, Option
|
||||||
|
from semif_agent.engine import EngineUnavailable
|
||||||
|
from semif_agent.ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
|
||||||
|
|
||||||
|
|
||||||
|
class _Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *args): # keep the test output quiet
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _read(self) -> dict:
|
||||||
|
length = int(self.headers.get("content-length", 0) or 0)
|
||||||
|
raw = self.rfile.read(length) if length else b"{}"
|
||||||
|
return json.loads(raw or b"{}")
|
||||||
|
|
||||||
|
def _send(self, status: int, payload: dict) -> None:
|
||||||
|
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.server.state.setdefault("gets", []).append(self.path)
|
||||||
|
if self.path == "/api/version":
|
||||||
|
self._send(
|
||||||
|
self.server.state.get("version_status", 200),
|
||||||
|
{"version": "0.40.13"},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._send(404, {"error": "not found"})
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
body = self._read()
|
||||||
|
self.server.state.setdefault("requests", []).append(
|
||||||
|
(self.path, body, {k.lower(): v for k, v in self.headers.items()})
|
||||||
|
)
|
||||||
|
if self.path == "/api/show":
|
||||||
|
status = self.server.state.get("show_status", 200)
|
||||||
|
response = self.server.state.get("show_response")
|
||||||
|
if response is None:
|
||||||
|
response = _default_show()
|
||||||
|
self._send(status, response)
|
||||||
|
elif self.path == "/v1/systemone":
|
||||||
|
status = self.server.state.get("systemone_status", 200)
|
||||||
|
response = self.server.state.get("systemone_response")
|
||||||
|
if response is None:
|
||||||
|
response = _default_systemone(body)
|
||||||
|
self._send(status, response)
|
||||||
|
else:
|
||||||
|
self._send(404, {"error": "not found"})
|
||||||
|
|
||||||
|
|
||||||
|
def _default_show() -> dict:
|
||||||
|
return {
|
||||||
|
"model": "clef-flash",
|
||||||
|
"parameters": "num_ctx 16384",
|
||||||
|
"capabilities": ["decision"],
|
||||||
|
"model_info": {"clef.context_length": 262144},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _default_systemone(body: dict) -> dict:
|
||||||
|
criteria = body["questions"]["decision"]["criteria"]
|
||||||
|
keys = list(criteria)
|
||||||
|
probs = {
|
||||||
|
key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1))
|
||||||
|
for index, key in enumerate(keys)
|
||||||
|
}
|
||||||
|
# Return the keys in REVERSE order to prove the engine aligns by id, not by
|
||||||
|
# position in the returned object.
|
||||||
|
return {
|
||||||
|
"model": "clef-flash",
|
||||||
|
"answers": {
|
||||||
|
"decision": {
|
||||||
|
"type": "choice",
|
||||||
|
"choice": keys[0],
|
||||||
|
"probabilities": dict(reversed(list(probs.items()))),
|
||||||
|
"confidence": 0.8,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"usage": {"input_tokens": 42, "output_tokens": 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def ollama():
|
||||||
|
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
||||||
|
server.state = {}
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
base = f"http://127.0.0.1:{server.server_address[1]}"
|
||||||
|
yield server, base
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def _engine(base: str, **cfg) -> OllamaSystemOneEngine:
|
||||||
|
return OllamaSystemOneEngine(
|
||||||
|
OllamaSystemOneConfig(base_url=base, model="clef-flash", timeout=5.0, **cfg)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _decision(*option_ids: str) -> DecisionRequest:
|
||||||
|
return DecisionRequest(
|
||||||
|
state="the user said hello",
|
||||||
|
question="Which category handles this request?",
|
||||||
|
options=[Option(oid, f"description for {oid}") for oid in option_ids],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_maps_decision_to_a_choice_question(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
result = _engine(base).call(_decision("response", "calendar"))
|
||||||
|
|
||||||
|
assert result.option_ids == ["response", "calendar"]
|
||||||
|
assert result.prob("response") == pytest.approx(0.9)
|
||||||
|
assert result.prob("calendar") == pytest.approx(0.1)
|
||||||
|
assert result.selected == "response"
|
||||||
|
assert result.extra["input_tokens"] == 42
|
||||||
|
assert result.extra["choice"] == "response"
|
||||||
|
assert result.extra["confidence"] == 0.8
|
||||||
|
assert result.extra["served_model"] == "clef-flash"
|
||||||
|
|
||||||
|
path, body, _ = server.state["requests"][-1]
|
||||||
|
assert path == "/v1/systemone"
|
||||||
|
assert body["model"] == "clef-flash"
|
||||||
|
assert body["state"] == "the user said hello"
|
||||||
|
question = body["questions"]["decision"]
|
||||||
|
assert question["type"] == "choice"
|
||||||
|
assert question["instructions"] == "Which category handles this request?"
|
||||||
|
assert question["criteria"] == {
|
||||||
|
"response": "description for response",
|
||||||
|
"calendar": "description for calendar",
|
||||||
|
}
|
||||||
|
# keep_alive is omitted unless configured.
|
||||||
|
assert "keep_alive" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_sends_a_configured_keep_alive(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
_engine(base, keep_alive="5m").call(_decision("a", "b"))
|
||||||
|
_, body, _ = server.state["requests"][-1]
|
||||||
|
assert body["keep_alive"] == "5m"
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_sends_null_for_a_bare_label(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
request = DecisionRequest(
|
||||||
|
state="state",
|
||||||
|
question="question",
|
||||||
|
options=[Option("a", ""), Option("b", " ")],
|
||||||
|
)
|
||||||
|
_engine(base).call(request)
|
||||||
|
_, body, _ = server.state["requests"][-1]
|
||||||
|
assert body["questions"]["decision"]["criteria"] == {"a": None, "b": None}
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_normalizes_an_unnormalized_distribution(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {
|
||||||
|
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}}
|
||||||
|
}
|
||||||
|
result = _engine(base).call(_decision("a", "b"))
|
||||||
|
assert result.probs == pytest.approx({"a": 0.5, "b": 0.5})
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_mismatched_probability_keys(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {
|
||||||
|
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}}
|
||||||
|
}
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_a_choice_outside_the_requested_options(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {
|
||||||
|
"answers": {
|
||||||
|
"decision": {
|
||||||
|
"type": "choice",
|
||||||
|
"choice": "other",
|
||||||
|
"probabilities": {"a": 0.8, "b": 0.2},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_all_zero_distribution(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {
|
||||||
|
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}}
|
||||||
|
}
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_out_of_range_probability(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {
|
||||||
|
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.5, "b": 0.5}}}
|
||||||
|
}
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_http_error_with_the_ollama_error_body(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_status"] = 400
|
||||||
|
with pytest.raises(EngineUnavailable, match="400"):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_rejects_missing_answer(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["systemone_response"] = {"answers": {}}
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_requires_at_least_two_options(ollama):
|
||||||
|
_, base = ollama
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(_decision("a"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_requires_a_non_empty_state(ollama):
|
||||||
|
_, base = ollama
|
||||||
|
request = DecisionRequest(
|
||||||
|
state=" ",
|
||||||
|
question="q",
|
||||||
|
options=[Option("a", "a"), Option("b", "b")],
|
||||||
|
)
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).call(request)
|
||||||
|
|
||||||
|
|
||||||
|
def test_call_sends_bearer_token(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
_engine(base, api_key="secret").call(_decision("a", "b"))
|
||||||
|
_, _, headers = server.state["requests"][-1]
|
||||||
|
assert headers.get("authorization") == "Bearer secret"
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_is_unavailable(ollama):
|
||||||
|
_, base = ollama
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).generate([{"role": "user", "content": "hi"}])
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_probes_ollama_native_endpoints_and_marks_loaded(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
engine = _engine(base, context_tokens=0)
|
||||||
|
assert engine.loaded is False
|
||||||
|
engine.warm()
|
||||||
|
assert engine.loaded is True
|
||||||
|
assert "/api/version" in server.state["gets"]
|
||||||
|
assert [path for path, _, _ in server.state["requests"]] == ["/api/show"]
|
||||||
|
# context_tokens=0 follows the model's real num_ctx from /api/show.
|
||||||
|
assert engine.context_tokens == 16384
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_falls_back_to_the_architecture_context_length(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["show_response"] = {
|
||||||
|
"capabilities": ["decision"],
|
||||||
|
"parameters": "",
|
||||||
|
"model_info": {"clef.context_length": 8192},
|
||||||
|
}
|
||||||
|
engine = _engine(base, context_tokens=0)
|
||||||
|
engine.warm()
|
||||||
|
assert engine.context_tokens == 8192
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_keeps_an_explicit_context_window(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
engine = _engine(base, context_tokens=4096)
|
||||||
|
engine.warm()
|
||||||
|
assert engine.context_tokens == 4096
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_rejects_a_model_without_the_decision_capability(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["show_response"] = {
|
||||||
|
"capabilities": ["completion", "thinking"],
|
||||||
|
"parameters": "num_ctx 4096",
|
||||||
|
}
|
||||||
|
with pytest.raises(EngineUnavailable, match="decision"):
|
||||||
|
_engine(base).warm()
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_rejects_a_missing_model(ollama):
|
||||||
|
server, base = ollama
|
||||||
|
server.state["show_status"] = 404
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
_engine(base).warm()
|
||||||
|
|
||||||
|
|
||||||
|
def test_warm_rejects_an_unreachable_server():
|
||||||
|
engine = OllamaSystemOneEngine(
|
||||||
|
OllamaSystemOneConfig(
|
||||||
|
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
|
||||||
|
)
|
||||||
|
)
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
engine.warm()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreachable_endpoint_raises_engine_unavailable():
|
||||||
|
engine = OllamaSystemOneEngine(
|
||||||
|
OllamaSystemOneConfig(
|
||||||
|
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
|
||||||
|
)
|
||||||
|
)
|
||||||
|
with pytest.raises(EngineUnavailable):
|
||||||
|
engine.call(_decision("a", "b"))
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
"""The committed pack skills are real, inspectable, and hermetically tested.
|
||||||
|
|
||||||
|
A pack ships starter integrations in the repo in the CODEGEN.md folder format,
|
||||||
|
grouped by concern under ``packs/<name>/skills/<category>/<leaf>/``. These tests
|
||||||
|
keep every pack skill honest: the declared integration must match the code, the
|
||||||
|
contract must cover what the body reads, and the hermetic mechanics test must
|
||||||
|
pass. They are not proof of the live integration — only a real run against the
|
||||||
|
user's service is (see AGENTS.md).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.codegen import (
|
||||||
|
integration_findings,
|
||||||
|
parse_contract,
|
||||||
|
parse_integration,
|
||||||
|
run_skill_test,
|
||||||
|
)
|
||||||
|
from semif_agent.packs import (
|
||||||
|
disabled_categories,
|
||||||
|
load_packs,
|
||||||
|
merge_packs,
|
||||||
|
pack_enabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
PACKS = Path(__file__).resolve().parent.parent / "packs"
|
||||||
|
SKILL_DIRS = sorted(path.parent for path in PACKS.glob("*/skills/*/*/skill.py"))
|
||||||
|
BRIDGE_TESTS = sorted(PACKS.glob("*/bridge/test_*.py"))
|
||||||
|
PACK_REQUIREMENTS = sorted(PACKS.glob("*/requirements.txt"))
|
||||||
|
|
||||||
|
|
||||||
|
def seed_id(seed: Path) -> str:
|
||||||
|
return f"{seed.parent.name}.{seed.name}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_pack_manifests_are_valid():
|
||||||
|
packs = load_packs({"skill_packs": str(PACKS)})
|
||||||
|
assert {p.name for p in packs} >= {
|
||||||
|
"nextcloud",
|
||||||
|
"simplex",
|
||||||
|
"outlook",
|
||||||
|
"browser",
|
||||||
|
"essentials",
|
||||||
|
}
|
||||||
|
for pack in packs:
|
||||||
|
assert pack.concern, f"{pack.name} must declare a concern"
|
||||||
|
assert pack.categories, f"{pack.name} must declare its categories"
|
||||||
|
|
||||||
|
|
||||||
|
def test_pack_enabled_resolution():
|
||||||
|
packs = {p.name: p for p in load_packs({"skill_packs": str(PACKS)})}
|
||||||
|
# A bridge pack follows its bridge's enabled flag.
|
||||||
|
assert pack_enabled({"bridges": {"nextcloud": {"enabled": False}}}, packs["nextcloud"]) is False
|
||||||
|
assert pack_enabled({"bridges": {"nextcloud": {"enabled": True}}}, packs["nextcloud"]) is True
|
||||||
|
# An explicit packs.<name>.enabled wins over the bridge flag.
|
||||||
|
assert (
|
||||||
|
pack_enabled(
|
||||||
|
{"bridges": {"nextcloud": {"enabled": False}}, "packs": {"nextcloud": {"enabled": True}}},
|
||||||
|
packs["nextcloud"],
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
# A bridge-less pack uses enabled_by_default.
|
||||||
|
assert pack_enabled({}, packs["essentials"]) is True
|
||||||
|
assert pack_enabled({"packs": {"essentials": {"enabled": False}}}, packs["essentials"]) is False
|
||||||
|
# browser defaults off (needs the optional deps).
|
||||||
|
assert pack_enabled({}, packs["browser"]) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_packs_loads_enabled_and_skips_disabled():
|
||||||
|
packs = load_packs({"skill_packs": str(PACKS)})
|
||||||
|
tree: dict = {}
|
||||||
|
config = {"bridges": {"nextcloud": {"enabled": True}, "outlook": {"enabled": False}}}
|
||||||
|
merge_packs(tree, packs, config)
|
||||||
|
assert "nextcloud" in tree
|
||||||
|
assert "time" in tree and "calculator" in tree # the essentials pack
|
||||||
|
assert "outlook" not in tree # disabled pack contributes nothing
|
||||||
|
assert "browser" not in tree
|
||||||
|
assert disabled_categories(config, packs) >= {"outlook", "browser"}
|
||||||
|
# A pack skill is labeled `seed` (a committed starter), not `generated`.
|
||||||
|
assert all(s.origin == "seed" for s in tree["nextcloud"])
|
||||||
|
# The pack's category description rides on the skill (feeds navigation).
|
||||||
|
assert tree["nextcloud"][0].category_description
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"req_file",
|
||||||
|
PACK_REQUIREMENTS,
|
||||||
|
ids=[f"{p.parent.name}/{p.name}" for p in PACK_REQUIREMENTS],
|
||||||
|
)
|
||||||
|
def test_pack_requirements_are_pinned_and_consistent(req_file):
|
||||||
|
"""A pack owns its python deps: `packs/<name>/requirements.txt`.
|
||||||
|
|
||||||
|
Every line is pinned (a shipped integration installs exact versions) and the
|
||||||
|
manifest's human-readable `requires` summary stays consistent with the file.
|
||||||
|
"""
|
||||||
|
packs = {p.name: p for p in load_packs({"skill_packs": str(PACKS)})}
|
||||||
|
pack = packs[req_file.parent.name]
|
||||||
|
assert pack.requirements_file == req_file
|
||||||
|
lines = [
|
||||||
|
line.strip()
|
||||||
|
for line in req_file.read_text().splitlines()
|
||||||
|
if line.strip() and not line.strip().startswith("#")
|
||||||
|
]
|
||||||
|
assert lines, f"{req_file} declares no requirements"
|
||||||
|
for line in lines:
|
||||||
|
assert "==" in line, f"{req_file}: pin the version ({line!r})"
|
||||||
|
for dep in pack.requires:
|
||||||
|
assert any(dep.lower() in line.lower() for line in lines), (
|
||||||
|
f"{req_file}: manifest requires {dep!r} but requirements.txt omits it"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifestless_pack_root_is_one_implicit_pack(tmp_path):
|
||||||
|
directory = tmp_path / "my_skills" / "widgets" / "frobnicate"
|
||||||
|
directory.mkdir(parents=True)
|
||||||
|
(directory / "skill.py").write_text("def act(ctx, request):\n return None\n")
|
||||||
|
packs = load_packs({"skill_packs": str(tmp_path / "my_skills")})
|
||||||
|
assert len(packs) == 1
|
||||||
|
assert ("widgets", "frobnicate") in packs[0].store.list_skills()
|
||||||
|
|
||||||
|
|
||||||
|
def test_expected_seeds_exist():
|
||||||
|
ids = {seed_id(seed) for seed in SKILL_DIRS}
|
||||||
|
assert "nextcloud.next_event" in ids
|
||||||
|
assert "nextcloud.create_event" in ids
|
||||||
|
assert "simplex.next_message" in ids
|
||||||
|
assert "simplex.send_message" in ids
|
||||||
|
assert "simplex.connect_link" in ids
|
||||||
|
assert "time.now" in ids
|
||||||
|
assert "time.date" in ids
|
||||||
|
assert "time.set_timer" in ids
|
||||||
|
assert "time.set_alarm" in ids
|
||||||
|
assert "nextcloud.create_task" in ids
|
||||||
|
assert "calculator.calculate" in ids
|
||||||
|
assert "skills.list_categories" in ids
|
||||||
|
assert "skills.list_skills" in ids
|
||||||
|
assert "browser.open_page" in ids
|
||||||
|
assert "browser.read_page" in ids
|
||||||
|
assert "browser.screenshot" in ids
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS])
|
||||||
|
def test_seed_declares_a_real_integration(seed):
|
||||||
|
code = (seed / "skill.py").read_text()
|
||||||
|
integration = parse_integration(code)
|
||||||
|
assert integration["service"]
|
||||||
|
assert integration["transport"]
|
||||||
|
assert integration_findings(integration, "declared", code) == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS])
|
||||||
|
def test_seed_contract_is_flat_and_covered_by_declaration(seed):
|
||||||
|
code = (seed / "skill.py").read_text()
|
||||||
|
contract = parse_contract(code)
|
||||||
|
integration = parse_integration(code)
|
||||||
|
assert set(integration["config_vars"]) == set(contract)
|
||||||
|
mirror = json.loads((seed / "contract.json").read_text())
|
||||||
|
assert mirror == contract, "contract.json must mirror the CONTRACT constant"
|
||||||
|
if integration["transport"] == "compute":
|
||||||
|
# A local compute skill acts on the machine itself and needs no
|
||||||
|
# configuration; an empty contract is legitimate.
|
||||||
|
return
|
||||||
|
assert contract, "an external-integration seed must declare a CONTRACT constant"
|
||||||
|
for name, description in contract.items():
|
||||||
|
assert name.islower() and " " not in name, name
|
||||||
|
assert isinstance(description, str) and description.strip()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS])
|
||||||
|
def test_seed_has_manifest_description(seed):
|
||||||
|
manifest = json.loads((seed / "manifest.json").read_text())
|
||||||
|
assert manifest["description"].strip()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("seed", SKILL_DIRS, ids=[seed_id(s) for s in SKILL_DIRS])
|
||||||
|
def test_seed_hermetic_test_passes(seed, monkeypatch):
|
||||||
|
root = str(seed.parents[4])
|
||||||
|
existing = os.environ.get("PYTHONPATH", "")
|
||||||
|
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
|
||||||
|
passed, output = run_skill_test(seed, timeout=30)
|
||||||
|
assert passed, output
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"test_file", BRIDGE_TESTS, ids=[f"{p.parent.parent.name}/{p.name}" for p in BRIDGE_TESTS]
|
||||||
|
)
|
||||||
|
def test_pack_bridge_test_passes(test_file):
|
||||||
|
"""A bridge ships with its pack; its hermetic test runs from the pack.
|
||||||
|
|
||||||
|
The bridge tests are pytest modules (they use fixtures and `pytest.raises`),
|
||||||
|
so they run in a subprocess with the checkout on `PYTHONPATH` — the same
|
||||||
|
import path a real run uses. A pack that declares a bridge but ships no test
|
||||||
|
is a hole; this parametrization picks up exactly the tests that exist, and
|
||||||
|
`test_pack_manifests_are_valid` keeps the packs present.
|
||||||
|
"""
|
||||||
|
root = str(PACKS.parent)
|
||||||
|
env = {
|
||||||
|
**os.environ,
|
||||||
|
"PYTHONPATH": root + os.pathsep + os.environ.get("PYTHONPATH", ""),
|
||||||
|
}
|
||||||
|
proc = subprocess.run(
|
||||||
|
[sys.executable, "-m", "pytest", str(test_file), "-q", "-p", "no:cacheprovider"],
|
||||||
|
cwd=root,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=300,
|
||||||
|
env=env,
|
||||||
|
)
|
||||||
|
assert proc.returncode == 0, (proc.stdout or "") + (proc.stderr or "")
|
||||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user