Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests: authoring-mechanics helpers opt in explicitly; the default-deny and
silent-refusal cases are asserted.
2026-10-13 15:01:12 +00:00
gabby 78b4621ba0 Abstract seeds into modular skill packs + split config
Group committed starter skills into packs (semif_agent/packs.py) that bind a
concern to its categories, bridge(s), requirements, and config schema:

- seeds/ -> packs/<name>/ with a pack.json manifest + skills/<category>/<leaf>/.
  Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and
  essentials (time + calculator, no bridge).
- PackRegistry discovers packs (a root with no manifest is one implicit pack);
  merge_packs loads every enabled pack. Pack enable is one switch
  (packs.<name>.enabled -> bridges.<bridge>.enabled -> enabled_by_default);
  disabling a pack drops its categories (incl. generated bodies) and its bridge.
- CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay).

Adopt a Home-Assistant-style layered config (semif_agent/config.py):

- config.json is a thin index ({"include": [...]}) over config/core.json,
  config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged.
- Secrets live in the gitignored secrets.json, referenced as "!secret <key>";
  api_key_env is removed.
- CORE_SCHEMA + each pack's config schema own defaults and GENERATE the
  committed config.example.json; new `check-config` (validate + --write-example)
  and `config-init` (seed the split layout) commands.
- scripts/config_merge.py (stdlib) lets bootstrap read the merged config.

Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge),
new tests/test_config.py. All unit tests pass (772).
2026-10-13 14:20:35 +00:00
162 changed files with 9829 additions and 17047 deletions

No files matched your search

+5
View File
@@ -12,6 +12,8 @@ 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, # Machine-specific material: deployment notes (hostnames, addresses, SSH,
# model choices), GPU offload probe, benchmark harness. Deliberately not part # model choices), GPU offload probe, benchmark harness. Deliberately not part
@@ -19,3 +21,6 @@ config.json
local/ local/
*.egg-info/ *.egg-info/
*.bak.* *.bak.*
# Skill packs live in their own repositories (one per pack) and are cloned into
# packs/<name>/ at setup. They are not tracked here. See PACKGEN.md.
packs/
+66
View File
@@ -0,0 +1,66 @@
---
name: Pack Generation
description: Author a new semif-agent skill pack (its own packs/<name>/ repository) — the pack.json manifest, its skill leaves, its bridge reference, and its config schema. Use when adding a new concern/product bundle as its own pack repo, or when adding a new bridge service to back one.
---
# Pack Generation
This skill walks you through adding a **pack** to semif-agent. The full contract
is the repository file `PACKGEN.md` (at the repo root, i.e. `../../../PACKGEN.md`
relative to this skill). Read it before making changes — it is the source of
truth and this skill is only the workflow.
## When to use
- The user wants a new concern/product bundle (its own `packs/<name>/` repo).
- The user wants a new third-party service backed by a bridge that ships with
its pack (`packs/<name>/bridge/`).
- The user is adding skills that should ship as a pack rather than be
authored at runtime.
## Workflow
1. **Read `PACKGEN.md`** in full.
2. **Decide the concern and categories.** Write one- to two-sentence,
navigation-grade category descriptions — SemIf routes on them.
3. **Bridge check.** If the pack talks to a third-party system, confirm a bridge
already fronts it (a shipped pack's `bridge/`, or the shared LLM bridge). If
not, author the bridge first (see the "Authoring a new bridge" section of
`PACKGEN.md`), ship it under `packs/<name>/bridge/`, and give it a pack config
block.
4. **Create the pack** (its own repository, `pack.<name>`):
`packs/<name>/pack.json` with `name`, `title`, `concern`, `categories`,
`bridges`, `requires`, `enabled_by_default`, and the `config` schema. Model
it on `packs/essentials/pack.json` (bridge-less) or
`packs/simplex/pack.json` (bridge-backed). If the pack needs python deps,
ship them at `packs/<name>/requirements.txt` (pinned, pip format) — never in
the agent repo's `requirements/` (see `PACKGEN.md`, "Pack python deps").
5. **Add each leaf** under `skills/<category>/<leaf>/` — `skill.py`,
`manifest.json`, `contract.json`, `skill.test.py` — following `CODEGEN.md`
and `TESTGEN.md`. Do not restate those rules; follow them. Ship each bridge
under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
6. **Regenerate and validate config:**
`python -m semif_agent.cli check-config --write-example config.example.json`
then `python -m semif_agent.cli check-config`.
7. **Run the tests:**
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
(it runs every pack's skill and bridge tests, including the new ones).
8. **Cross-link** the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
pack).
9. **Verify a real run** against the user's actual service — a passing hermetic
test proves mechanics only, never the live integration.
10. **Register and publish:** add the pack to the `semif-packs` pack-index repo
(an entry in its `packs.json`: name + clone URL, plus title/description for
the interview), then commit and push the pack's own repository
(`pack.<name>`). `scripts/bootstrap.sh` reads the index and clones it into
`packs/`.
## Guardrails
- A pack is declarative, committed in its own repository; never put a credential
in it (secrets live in the gitignored `secrets.json`).
- A bridge **ships with its pack** (`packs/<name>/bridge/`); the core keeps only
the shared contract + discovery. Never widen the gateway.
- `concern` and `categories` are required; every category needs a description.
- Regenerate `config.example.json` from the schema after any schema change; the
example and the live config are never hand-edited.
+643 -219
View File
File diff suppressed because it is too large. Load diff
+68 -23
View File
@@ -6,10 +6,19 @@ body must be written.
The mocking/testing side of a skill is NOT specified here — it has its own 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. 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 ## What a skill is
Semif-agent is an end-user application: an everyday person asks it to do a task, Semif-agent is an end-user application: an everyday person asks it to do a task,
and it does that task using a combination of native python modules, user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based decision engine known as SemIf. and it does that task using native python modules — including direct HTTP
requests to a service's own API — user-provided data, and, where warranted, a
catalog of basic services known as bridges. A skill is the thing that performs
one of those tasks: it is the leaf in the skill tree that the agent navigates to
when it has resolved a request to a single, concrete action. Navigation is
performed by an llm-based decision engine known as SemIf.
A skill is three things: A skill is three things:
@@ -21,7 +30,8 @@ A skill is three things:
talks to and how) and the `CONTRACT` constant (the values the runner must talks to and how) and the `CONTRACT` constant (the values the runner must
provide). provide).
The committed seed `seeds/nextcloud/create_event/` is the **authoritative worked The `nextcloud` pack's create_event skill
(`packs/nextcloud/skills/nextcloud/create_event/`, from its own repo) is the **authoritative worked
example** of all three. Read its `manifest.json`, its `skill.py` (which declares 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 `INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
body should look and behave like it. body should look and behave like it.
@@ -176,6 +186,14 @@ Rules:
hand; a title is generated by the LLM, not assembled by string concatenation 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. 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 registry entry
The body writer does **not** author a manifest. The `llm` provider authors the The body writer does **not** author a manifest. The `llm` provider authors the
@@ -285,8 +303,12 @@ def act(ctx, request) -> ActionResult:
`ctx.config` (the resolved values for this skill, including its own config), `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 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). notification, as the `time.set_timer` and `time.set_alarm` seeds do).
`ctx.admin` exists for the built-in housekeeping meta skills only; an ordinary `ctx.catalog` is a **read-only** view of the agent's own skill tree for an
body must never touch it. 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. - `request` is the `Request` being handled.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None, - `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact decisions: list = [])` is imported from `semif_agent.skills`; return that exact
@@ -388,7 +410,7 @@ INTEGRATION = {
skills that perform no external action at all (pure analysis/formatting); an skills that perform no external action at all (pure analysis/formatting); an
action skill must not use it. action skill must not use it.
- `config_vars` — the `ctx.config` keys the body reads for this integration. In - `config_vars` — the `ctx.config` keys the body reads for this integration. In
the committed seeds this is exactly the body's `CONTRACT` key set; an empty the shipped seeds this is exactly the body's `CONTRACT` key set; an empty
list is allowed for `compute`. Declaring a variable the body never reads is a list is allowed for `compute`. Declaring a variable the body never reads is a
mismatch the fidelity check flags. mismatch the fidelity check flags.
@@ -553,29 +575,44 @@ therefore run as a later step of a chain.
- **Keep the body small — it is ingested whole.** The fidelity decision reads - **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 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" rejected outright (the pipeline retries once with a "make it shorter"
instruction). Delegate protocol details to a bridge instead of hand-rolling a instruction). Delegate **complex** protocol details to a bridge instead of
client, and keep `act` to one purpose; a long body is a signal that the hand-rolling a client (a simple HTTP call needs no bridge), and keep `act` to
integration belongs in a bridge. 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 - **The function is `act` exactly.** The module is imported under its registered
leaf name; the entry point is a module-level `act(ctx, request)`. leaf name; the entry point is a module-level `act(ctx, request)`.
## Bridge services ## Bridge services
Some real systems are reached through a **bridge service**: a standalone local A body reaches a real service with a stdlib transport. A **plain HTTP API** is
process that stands up a small, token-guarded HTTP API in front of the system called directly — `urllib.request` / `http.client`, endpoint and credentials read
and owns its native protocol and credentials. The concrete catalog of bridges — from `ctx.config` — and needs no bridge. Some systems, however, are reached
which services exist, their base-URL config var, auth, config vars, and the through a **bridge service**: a standalone local process that stands up a small,
exact endpoints with their request/response/error shapes — is injected into the token-guarded HTTP API in front of the system and owns its native protocol,
prompt at authoring time (render it with 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 `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 section is only the generic pattern; the catalog is the source of truth for the
bridge-specific details. bridge-specific details.
A body must never speak a service's native protocol directly — no WebSocket to
`simplex-chat`, no direct daemon access. It calls the bridge's HTTP API with the
base URL from the bridge's config variable, exactly like any other HTTP
integration:
```python ```python
INTEGRATION = { INTEGRATION = {
"service": "<the bridge's service id, from the catalog>", "service": "<the bridge's service id, from the catalog>",
@@ -586,6 +623,9 @@ INTEGRATION = {
Rules: 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 - **Read every value from `ctx.config`.** The base URL, any token, and any
default (recipient/contact/target) come from the config vars the catalog default (recipient/contact/target) come from the config vars the catalog
lists. Never hardcode a host, port, or bridge address in the body. lists. Never hardcode a host, port, or bridge address in the body.
@@ -613,6 +653,9 @@ Rules:
- Single purpose, single file, single module. - Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category. - 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 - `act` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar
to write to. to write to.
@@ -654,12 +697,14 @@ A generated skill is accepted only if:
11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary, 11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
and is consistent with the body's `ctx.config` reads and behavior. and is consistent with the body's `ctx.config` reads and behavior.
12. It does no network, file, or engine work at import time. 12. It does no network, file, or engine work at import time.
13. If it is a messaging skill, it uses a bridge service over HTTP (never a 13. If the service it targets is fronted by a bridge, it calls that bridge over
service's native protocol), resolves recipients with a SemIf sub-decision, HTTP (never the service's native protocol); otherwise it may call the
and sends only on explicit user intent. 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 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 over the engine's artifact budget is rejected as too long) — delegate
protocol details to a bridge rather than hand-rolling them. 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 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 body outright. The rest are not statically rejected: a missing or inconsistent
+468
View File
@@ -0,0 +1,468 @@
# PACKGEN.md — the contract for new packs
This file is the authoritative spec for what a **pack** is and how to author a
new one. It is the third sibling of the skill contracts: `CODEGEN.md` governs a
skill's runnable **body**, `TESTGEN.md` governs its **test**, and this file
governs the **pack** that bundles a concern, its skills, its bridge reference,
and its settings into one thing.
Read this before adding a pack. A pack is what makes a new
product/concern a first-class part of the agent instead of scattered edits to
`skills.py` and `config.py`.
## What a pack is
Semif-agent ships a set of starter integrations. Each is a **pack**: a folder
`packs/<name>/` holding a `pack.json` manifest plus a `skills/` store of leaves
in the exact generated-skill format. Each pack lives in its **own repository**
(`pack.<name>`, listed in the `semif-packs` pack-index repo); `scripts/bootstrap.sh`
clones them into the gitignored `packs/<name>/`. The manifest binds the pieces
that would otherwise be scattered by convention:
- the **concern** (what product/job this is) and its **title**;
- its **categories** (the tree buckets it owns, each with a scope description);
- the **bridge(s)** it talks to, referenced by name — and **ships** the bridge
code itself under `bridge/` (see "Authoring a new bridge");
- its **runtime requirements** (optional heavy deps);
- its **enable flag**; and
- its **config schema** (the defaults and validation for its settings).
A pack is loaded by `semif_agent/packs.py` (`PackRegistry` discovers packs,
`merge_packs` loads every **enabled** pack into the tree at startup) and its
`config` schema is read by `semif_agent/config.py` to generate
`config.example.json` and to validate a live config.
Three boundaries must stay crisp:
- A **skill** is one leaf action (`packs/<name>/skills/<category>/<leaf>/`),
governed by `CODEGEN.md`/`TESTGEN.md`. A pack contains skills; it is not one.
- A **bridge** is a standalone process in front of a third-party system,
warranted when the system needs state (especially auth state), a native or
heavy protocol, or one sanitized surface; a system with a plain HTTP API needs
no bridge — its skill calls the API directly. A bridge **ships with its pack**
(`packs/<name>/bridge/`); the core keeps only the shared contract
(`semif_agent/bridges/base.py`) and the discovery registry
(`semif_agent/bridges/registry.py`). The one shared, pack-less bridge is the
**LLM bridge** (a core built-in many packs call). A pack's `bridges` list names
the bridge(s) it ships; a pack never edits core bridge code.
- A pack is **declarative structure**, committed in its own repository.
Per-machine values are the split config; credentials live in `secrets.json`.
A pack repo never holds a secret.
## Folder layout
```
packs/<name>/
pack.json # the manifest (this file's subject)
requirements.txt # optional: the pack's own python deps (pip format)
skills/<category>/<leaf>/
skill.py # the body — CODEGEN.md
manifest.json # {"description": "..."} navigation text
contract.json # mirror of the body's CONTRACT — TESTGEN.md
skill.test.py # hermetic mechanics test — TESTGEN.md
bridge/ # only for a bridge-backed pack (see below)
__init__.py # the pack's bridge package
<bridge>.py # the BridgeService subclass (bridge name)
<bridge>_client.py # optional protocol client (e.g. nextcloud_client.py)
test_<bridge>_bridge.py # hermetic bridge test (loopback HTTP)
scripts/ # optional concern helpers (e.g. an auth or
# setup script), run from the checkout
```
- The `<category>` directory name is the tree bucket; the `<leaf>` directory
name is the leaf's `name`. The runner joins them as `category.name` only in
run summaries.
- Every leaf carries the four artifacts above. Their contents are governed by
`CODEGEN.md` (body + `CONTRACT` + `INTEGRATION`) and `TESTGEN.md`
(test + `contract.json` mirror); do not restate those rules here.
- `bridge/` ships the pack's bridge (one module per name in `bridges`, plus
optional sibling modules it imports relatively). It is absent for a
bridge-less pack. See "Authoring a new bridge".
- `requirements.txt` is the pack's own optional python deps (standard pip
format); it is absent for a stdlib-only pack. See "Pack python deps".
- `manifest.json` holds a single non-empty `description` — the navigation text
SemIf routes on. It is the seed analog of the registry entry a generated
skill gets from the `llm` provider.
- A root with no `pack.json` is treated as **one implicit, manifest-less pack**
whose store is the root itself (a plain skills directory still works), but a
pack repo should always have a manifest.
The shipped packs are the authoritative worked examples: `essentials` is
the minimal bridge-less pack; `nextcloud`, `simplex`, `outlook`, and `browser`
are bridge-backed packs.
## `pack.json` — the manifest
A single JSON object. Fields (from `packs._parse_pack`):
| Field | Type | Required | Meaning |
| -------------------- | --------------- | -------- | ------- |
| `name` | string | no\* | Pack id (snake_case). Defaults to the folder name. |
| `title` | string | no | Human display name. Defaults to `name`. |
| `concern` | string | **yes** | One- to two-sentence statement of the product/job the pack serves. (`description` is accepted as a legacy alias.) |
| `categories` | object | **yes** | `{category_id: scope_description}` — the tree buckets this pack owns. |
| `bridges` | array of string | no | Bridge names this pack ships and talks to. Each name is a `bridge/<name>.py` module in the pack; `simplex`/`llm`/`nextcloud`/`outlook`/`browser` are the shipped names. Empty for a bridge-less pack. |
| `requires` | array of string | no | Optional heavy deps named at a glance (e.g. `playwright`). Informational — the pinned install list is the pack's own `requirements.txt` (see "Pack python deps"), and the code's `check_requirements` is what enforces them at runtime. |
| `enabled_by_default` | bool | no | Default `true`. Whether the pack loads when nothing else decides. |
| `config` | object | no | The pack's config schema (see below). |
\* `name` is optional in the parser but should always be set explicitly.
Rules:
- **`concern` and `categories` are required** (`tests/test_packs.py` fails
without them). A pack with no declared concern is not a pack.
- **Category ids are the tree keys.** They are the same ids the leaf folders
live under (`skills/<category>/<leaf>/`). When `categories` is omitted, the
pack's categories are inferred from the `skills/` subdirectories — but declare
them, because the description is load-bearing.
- **A category description is navigation-critical.** It is what SemIf reads to
route a request into the bucket; a bare id with no description routes badly.
Write one to two sentences naming the concrete jobs the category does.
- **`bridges[0]` owns the config block.** For a bridge pack, the pack's `config`
schema maps onto `bridges.<bridges[0]>`; only the first bridge gets the block
(a pack normally fronts one bridge). Each name in `bridges` must have a
`bridge/<name>.py` module that defines its `BridgeService` subclass.
- Keep the manifest minimal: it binds metadata and settings, nothing executable.
## The config schema
`config` is a nested schema. A **leaf** is a dict with a `default`; a **block**
is a dict without one (recurse). Each leaf spec:
| Key | Type | Meaning |
| --------- | ------ | ------- |
| `type` | string | `bool` \| `int` \| `float` \| `str` \| `list` \| `dict`. Checked by `check-config` (`int`/`float` are interchangeable). |
| `default` | any | The value shipped in `config.example.json` and seeded by `config-init`. Required on a leaf. |
| `doc` | string | One-line plain-language description. Shown in the generated example. |
| `secret` | bool | `true` marks a credential: the example emits `"!secret <pack>_<key>"` instead of a value. |
Example (a bridge-backed pack, mirroring `packs/simplex/pack.json`):
```json
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
"port": {"type": "int", "default": 5227, "doc": "Bridge listen port."},
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
"reconnect": {
"initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."},
"max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."}
}
}
```
How the schema maps onto the live config (`config.default_config` /
`generate_example_config`):
- A **bridge pack** (`bridges` non-empty) maps its whole `config` schema onto
the `bridges.<bridges[0]>` block.
- A **bridge-less pack** maps only its `enabled` flag onto
`packs.<name>.enabled`; its other keys are not carried (a bridge-less pack is
configured through its skills' own config, not a pack block).
- Secret leaves become `"!secret <pack>_<key>"` in `config.example.json`, where
`<pack>_` is the pack name prefix (nested keys are prefixed with their path,
e.g. `simplex_reconnect_initial`). Never write a real credential into the
manifest.
Rules:
- Every leaf needs a `default` and a `doc`. A key with no `default` is treated
as a nested block.
- Put **operational** settings here (endpoints, accounts, defaults, timeouts) —
the values a skill body reads from `ctx.config`. Per-request arguments never
belong in config (see `CODEGEN.md`).
- `config.json`, `config/`, and `secrets.json` are gitignored and per-machine.
The manifest is committed structure only.
After changing a schema, regenerate and validate:
```sh
python -m semif_agent.cli check-config --write-example config.example.json
python -m semif_agent.cli check-config
```
`config-init` seeds the split `config/` layout from the schemas (bootstrap runs
it once, only when `config.json` is absent); afterwards only a human edits it.
The generated example and the live config are never hand-edited.
## Pack python deps
A pack owns the python packages its skills and bridge need. Put them in
`packs/<name>/requirements.txt` (standard pip requirements format, pinned) —
**not** in the agent repo's `requirements/`. A pack that is stdlib-only ships no
file.
How the injection works:
- `SkillPack.requirements_file` (`semif_agent/packs.py`) resolves
`packs/<name>/requirements.txt` when it exists.
- The install plan lists those packs: `setup.build_plan` /
`setup.plan_from_config` set `pack_requirements` to the selected/enabled packs
that ship one (`scripts/bootstrap.sh` reads the plan).
- Bootstrap installs each listed pack's file into `.runtime/venv` **after**
cloning the selected packs and creating the venv, and only for packs the host
actually selected (a host that never enables the pack installs nothing). The
`--browser` flag force-adds the browser pack's deps.
Rules:
- **Lazy-import** every heavy dep in the pack's bridge/skills so a host without
the pack still runs — the core stays stdlib-only. A missing dep is a per-call
`503` with an install hint (see "Authoring a new bridge"), never a crash.
- **Pin** the versions (this is a shipped integration, not an app you upgrade in
place). If a dep needs a non-pip step (a downloaded binary, a system package),
ship a helper under `scripts/` and document it in the pack's
`requirements.txt` header — the browser pack's Chromium download is the model.
- `requires` in the manifest is the human-readable summary of the heavy deps;
`requirements.txt` is the authoritative install list. Keep them consistent.
- Never put a credential or a per-machine value in `requirements.txt`; it is
committed structure like the rest of the pack.
## The enable switch
One switch governs the pack's skills **and** its bridge, so a host never offers
a skill whose bridge is off. `packs.pack_enabled` resolves in order:
1. an explicit `packs.<name>.enabled` in config (wins);
2. else, for a bridge pack, `bridges.<bridges[0]>.enabled` (the historical
switch);
3. else `enabled_by_default`.
Disabling a pack drops its categories entirely — including any generated body
authored into one — and stops its bridge. The switch lives in the pack's
`config/packs/<name>.json` fragment (written by `config-init`/`check-config`).
## Referencing a bridge by name
A pack whose skills talk to a third-party system lists that bridge in
`bridges`, **ships** it under `bridge/`, and carries its config block in
`config`. (A pack whose skills reach a plain HTTP API directly needs no bridge:
`bridges` stays empty and each leaf declares the endpoint in its own
`CONTRACT`.) The bridge itself is a `BridgeService` subclass in
`packs/<name>/bridge/<name>.py`; the core registry imports it by convention and
its `BridgeInfo` (name, service, description, URL config var, other config vars,
auth header, endpoints) is injected into every codegen prompt via
`describe_bridges()`, so bodies learn how to reach it without the pack restating
protocol details. The one exception is the shared, pack-less **LLM bridge**
(a core built-in).
Skill-facing config is **derived**, never duplicated: `derived_config_vars`
turns the bridge's `bridges.<name>` block (`host`/`port`/`token`) into the
`<url_config_var>` and `<auth_config_var>` values a body reads from
`ctx.config` (e.g. `simplex_bridge_url`, `simplex_bridge_token`). Bodies call
the bridge over the ordinary `http` transport; their hermetic tests are
loopback HTTP like any other HTTP body.
Rules:
- The bridge block's `enabled`/`host`/`port`/`token` are the pack's config
schema; the URL/token config vars are derived and must not be declared again.
- A pack ships its own bridge and never imports or edits another pack's or the
core's. Gateway isolation is non-negotiable — read/send/address capability is
a bridge, never a gateway feature.
## Authoring a new bridge
A **bridge** is a standalone process that stands up a simple, secure localhost
HTTP layer in front of one third-party system. Author one when a skill body
cannot sanely talk to the system itself — because it holds auth/session state,
needs a native or heavy protocol, or should be reached through one sanitized
surface. A system with a plain HTTP API needs no bridge: its skill calls the API
directly. Adding a bridge means:
1. **Write the bridge class** in the pack's `bridge/<name>.py`, subclassing
`BridgeService` (`semif_agent/bridges/base.py`). Set the `name` attribute and
a module-level/class `INFO = BridgeInfo(...)`. Ship `bridge/__init__.py` (the
package marker) and any sibling modules the bridge imports relatively (e.g.
`bridge/<name>_client.py` for the protocol client):
```python
from semif_agent.bridges.base import BridgeInfo, BridgeService
class WidgetBridge(BridgeService):
name = "widget"
INFO = BridgeInfo(
name="widget",
service="widget_service",
description="The user's Widget account: widgets and their status.",
url_config_var="widget_bridge_url",
endpoints=(
"GET /widgets — list widgets",
"POST /widgets — create a widget",
),
config_vars=("widget_bridge_token",),
config_var_docs=(("widget_bridge_token", "Shared secret for the X-Semif-Token header."),),
auth_header="X-Semif-Token",
auth_config_var="widget_bridge_token",
)
def check_requirements(self) -> tuple[bool, str | None]:
return True, None # stdlib-only
def handle_get(self, path, query): ...
def handle_post(self, path, payload): ...
```
The base class owns the HTTP/JSON/auth plumbing (`start`/`stop`, the
`X-Semif-Token` guard); a subclass implements only its routes. Override
`start`/`stop`/`_stop_transport` only if the bridge owns a service daemon.
Anchor checkout-relative paths (e.g. a token store under `.runtime/`) with
`semif_agent.bridges.base.checkout_root()`, never from the bridge's own
`__file__` — the bridge ships in its pack, so its path is pack-relative.
2. **Declare it** in the pack's `bridges` list and ship its module at
`bridge/<name>.py`. That is what makes it discoverable, describable to
codegen, and runnable via `python -m semif_agent.cli bridge` — there is no
core `CATALOG` to edit.
3. **Carry its config block** in the pack's `config` schema
(`enabled`/`host`/`port`/`token` plus service vars). The schema is what gives
the bridge its config defaults and validation.
4. **Override `BridgeService.from_config`** only when the bridge needs more than
its own block: the scheduler's configured `llm` client (the shared LLM
bridge) or top-level fallback values (like Nextcloud's `nextcloud_*`). A
plain bridge uses the default and needs no override.
5. **Heavy/optional deps:** `check_requirements()` must **never raise** and must
return `(ok, install_hint)`. `run_bridges` aborts **all** bridges when one
reports `ok=False`, so a bridge with an optional dependency (like the
browser) must return `(True, None)` and surface a per-call `503` with an
install hint instead — a missing browser must not take down simplex/llm/
nextcloud. Lazy-import every heavy dep so the core stays stdlib-only.
6. **Report real failures:** a transport/HTTP/bad-reply failure is a `502`, a
missing connection/dep is a `503`, bad input a `400` — never a fabricated
success. The bridge owns its own state (cursors, daemons); bodies keep none.
7. **Test it hermetically:** add `bridge/test_<name>_bridge.py` driving the real
routes over a loopback `http.server` (inject a fake driver where a real
service would be needed). No external network, no real daemon. Import the
bridge through the core registry
(`load_pack_bridge_module("<pack>", "<name>")`) so the test also proves the
pack's bridge is discoverable; `tests/test_packs.py` runs it from the
checkout. `describe_bridges()` picks the new bridge up automatically.
8. **Regenerate** `config.example.json` and run `check-config` (see above), and
document the bridge in `AGENTS.md` (bridges section). Never widen the
gateway for a new capability.
## Acceptance criteria
A new pack is accepted only if:
1. `packs/<name>/pack.json` parses as JSON, declares a non-empty `concern` and
a non-empty `categories` map, and every `bridges` name has a
`bridge/<name>.py` module defining its `BridgeService` subclass.
2. Every leaf under `skills/<category>/<leaf>/` is a complete skill folder
(`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`) satisfying
`CODEGEN.md` and `TESTGEN.md`: a module-level `act`, a flat `CONTRACT` whose
every key is read from `ctx.config`, an `INTEGRATION` consistent with the
code, a non-empty `manifest.json` `description`, and `contract.json` an exact
mirror of the body's `CONTRACT`.
3. The leaf's hermetic mechanics test passes
(`python skill.test.py` from the leaf folder). This proves mechanics only —
only a real run against the user's service proves the integration.
4. Each category id in the manifest is the id its leaves live under, and each
category has a navigation-grade scope description.
5. The `config` schema is well-formed (every leaf has `default` + `doc`; secrets
marked `secret`), maps onto `bridges.<bridges[0]>` (or `packs.<name>` for a
bridge-less pack), and the regenerated `config.example.json` + `check-config`
are clean.
6. A bridge-backed pack ships its bridge test (`bridge/test_<bridge>_bridge.py`)
and it passes hermetically (loopback HTTP, no external network, no daemon).
7. Nothing deployment-specific (hostname, address, username, absolute home
path, local model name) appears in any committed file —
`tests/test_no_env_leaks.py` enforces this for the agent repo; keep a pack
repo clean too. Secrets live in `secrets.json`.
8. If the pack ships a `requirements.txt`, it is pinned, lives with the pack (not
the agent repo's `requirements/`), and its deps are lazy-imported so a host
without the pack is unaffected.
`tests/test_packs.py` enforces items 1–6 and 8 mechanically for every shipped
pack (valid manifest, concern + categories, integration matches code, contract
flat and mirrored, manifest description, hermetic skill test, hermetic bridge
test, pinned pack requirements)
and keeps the shipped pack ids present.
## Worked example — a minimal bridge-less pack
The smallest complete pack needs a manifest and one leaf. `packs/essentials/`
is the committed model; a hypothetical `packs/hello/`:
```
packs/hello/
pack.json
skills/hello/greet/
skill.py
manifest.json
contract.json
skill.test.py
```
`pack.json`:
```json
{
"name": "hello",
"title": "Hello",
"concern": "A trivial local greeting utility that needs no account, network, or bridge.",
"categories": {
"hello": "Greetings: producing a friendly greeting for the user."
},
"bridges": [],
"requires": [],
"enabled_by_default": true,
"config": {
"enabled": {"type": "bool", "default": true, "doc": "Load the hello skills."}
}
}
```
`skills/hello/greet/manifest.json`:
```json
{ "description": "Produce a friendly greeting." }
```
The leaf's `skill.py` (a `compute`-transport body — no external action, empty
`CONTRACT`) and `skill.test.py` follow `CODEGEN.md`/`TESTGEN.md`; the shipped
`packs/essentials/skills/time/now/` is the reference for exactly this shape.
For a bridge-backed pack, start from `packs/simplex/pack.json` (bridge
reference + `host`/`port`/`token` + service vars), `packs/simplex/bridge/` (the
bridge module, its package marker, and its hermetic test), and
`packs/simplex/skills/simplex/send_message/` (a body that calls the bridge over
HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/` (its
`bridge/nextcloud.py` overrides `from_config`).
## Checklist
1. Decide the concern and the category ids; write navigation-grade category
descriptions.
2. If a third-party system is involved and it needs state/auth, a native or
heavy protocol, or one sanitized surface, author a bridge first (see
"Authoring a new bridge") and ship it under `bridge/`. A system with a plain
HTTP API needs no bridge — the skill calls it directly.
3. Create the pack (its own repository, `pack.<name>`): `packs/<name>/pack.json`
with `name`, `title`, `concern`, `categories`, `bridges` (if any), `requires`,
`enabled_by_default`, and the `config` schema. If the pack needs python deps,
ship them pinned at `packs/<name>/requirements.txt` (see "Pack python deps").
4. Add each leaf under `skills/<category>/<leaf>/` following `CODEGEN.md` and
`TESTGEN.md` (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`),
and each bridge under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
5. Regenerate and validate config:
`python -m semif_agent.cli check-config --write-example config.example.json`
then `python -m semif_agent.cli check-config`.
6. Run the tests:
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
(it runs every pack's skill and bridge tests, including the new ones).
7. Cross-link the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
pack).
8. Verify a real run against the user's actual service — the only proof the
integration works.
9. Register the pack in the `semif-packs` index repo — add an entry (name + clone
URL, plus title/description for the interview) to its `packs.json` — then push
the pack's own repository (`pack.<name>`); `scripts/bootstrap.sh` reads the
index and clones the pack into `packs/`.
+231 -113
View File
@@ -269,11 +269,12 @@ receives the user's request, question answers, or run output.
| `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` | | `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
| `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, de-identified goal + description, **de-identified evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` | | `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, de-identified goal + description, **de-identified evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` |
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py:33`): each The **bridge catalog** is `describe_bridges()` (`bridges/registry.py`): each
known bridge's name, service, description, base-URL config var, auth header + known bridge's name, service, description, base-URL config var, auth header +
token var, documented config vars, and endpoints. It is the single runtime token var, documented config vars, and endpoints. It is the single runtime
source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic
pattern — so a bridge can be added without touching either contract file. pattern — so a bridge can be added without touching either contract file (a
bridge ships with its pack; the registry discovers it by convention).
The **evidence bundle** handed to a corrective regen is de-identified: a generic The **evidence bundle** handed to a corrective regen is de-identified: a generic
failure kind, the integration, the goal, and the previous body, rendered as-is failure kind, the integration, the goal, and the previous body, rendered as-is
@@ -351,16 +352,21 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing. with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a - **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard. Redux-DevTools-style dashboard.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM. - **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM,
including Sideband push-to-talk **voice messages** on LXMF (local transcription,
and voice replies synthesized with Piper).
- **Voice gateway** — a local microphone front end: wake word + speech-to-text + - **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper). text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front - **Standalone bridge services** — an optional token-guarded localhost HTTP
of third-party systems, so generated bodies never speak native protocols. layer for third-party systems that need state/auth, a native protocol, or a
sanitized surface; a plain HTTP API is called directly.
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the - **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
authoritative worked example), `nextcloud.next_event` (Nextcloud CalDAV), authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
`nextcloud.create_task` (Nextcloud task list), calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`, and `simplex.next_message` / `simplex.send_message` / `simplex.connect_link`,
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer). `calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer),
and `skills.list_categories` / `skills.list_skills` (report the agent's own
skill categories, or the skills inside a named category).
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app. - **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays - **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed. importable and testable without the heavy engine installed.
@@ -399,16 +405,31 @@ semif_agent/
voice_transport.py neutral voice transport: mic capture, wake word, VAD, voice_transport.py neutral voice transport: mic capture, wake word, VAD,
speech-to-text (faster-whisper), text-to-speech (Piper) speech-to-text (faster-whisper), text-to-speech (Piper)
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud, bridges/ bridge contract + discovery (base.py, registry.py, inbox.py,
Outlook, browser) llm.py); the concrete bridges ship in their packs
seeds/ committed starter skills (nextcloud, simplex, outlook, browser) config.py layered config: index includes + !secret + schema/example
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in packs.py SkillPack + PackRegistry (bundles skills by concern/bridge)
requirements/ staging.txt — the pinned engine deps packs/ skill packs, each cloned from its own repo (pack.<name>)
into this gitignored dir — each ships its own bridge/ — the
pack list lives in the semif-packs index repo (see PACKGEN.md)
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
requirements/ core.txt (test runner), engine.txt (local decision engine),
transports.txt (websockets/lxmf), voice.txt (microphone
stack), transcribe.txt (faster-whisper, LXMF voice
messages), tts.txt (piper-tts + PyAV, LXMF voice replies),
codec2.txt (pycodec2, LXMF Codec2 PTT);
staging.txt = union of the non-hardware files;
a pack's own deps live with the pack at
packs/<name>/requirements.txt
tests/ stdlib unit tests + tests/integration (real engine + LLM) tests/ stdlib unit tests + tests/integration (real engine + LLM)
CODEGEN.md the contract fed to the skill-body codegen model CODEGEN.md the contract fed to the skill-body codegen model
TESTGEN.md the contract fed to the test/contract codegen model TESTGEN.md the contract fed to the test/contract codegen model
PACKGEN.md the contract for authoring a skill pack (packs/<name>/)
AGENTS.md the operational guide (read this before touching code) AGENTS.md the operational guide (read this before touching code)
config.example.json per-machine config template (seeded to config.json once) config.json per-machine config INDEX ({"include": [...]}); seeded once
config/ split config fragments (core, gateway, bridges, packs/*)
secrets.json gitignored credentials, referenced as "!secret <key>"
config.example.json GENERATED per-machine config reference (from the schemas)
pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs
local/ gitignored: this deployment's notes (hosts, addresses, models) local/ gitignored: this deployment's notes (hosts, addresses, models)
``` ```
@@ -418,30 +439,43 @@ local/ gitignored: this deployment's notes (hosts, addresses, model
## Installation ## Installation
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
decision engine, a pinned GGUF, and an OpenAI-compatible endpoint for codegen. decision engine (local or remote). `scripts/bootstrap.sh` provisions what this
`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree machine needs inside a gitignored `.runtime/` tree in the checkout — and only
in the checkout. what it needs, based on the answers to a short first-run interview.
### Prerequisites: ollama models ### Prerequisites: the decision engine, and optional models
Two OpenAI-compatible endpoints (usually ollama), which may be on different The **decision engine** routes every request. It runs one of three ways,
machines: chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run
`scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because it
is slower on CPU).
**Skill authoring is opt-in** (`new_skill_creation`: `deny` by default). When it
is off, no `llm`/`codegen` endpoint is needed at all — the agent only runs the
shipped packs. When it is on, two OpenAI-compatible endpoints are required
(usually ollama, possibly on different machines):
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host.
- **`llm`** — a small, fast model that authors the title + description of a - **`llm`** — a small, fast model that authors the title + description of a
newly created category/skill. Deliberately its own endpoint/model, so it can newly created category/skill. Its `provider` can be `"ollama"` (default),
stay local even when `codegen` is remote; it uses the same provider transport
(`provider.py`) and an unreachable endpoint is graceful (the request is not
re-dispatched), never fatal. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded `"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no decision engine model generates in-process, with no endpoint and no
`llm.model` at all (see the `llm.semif` block in `config.json`). `llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU - **`codegen`** — a large, code-capable model that writes skill bodies. This is
by default; to offload it to a GPU, set `engine.gpu_layers` in `config.json` and slow and ideally on a beefier host.
run `scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because
it is slower on CPU).
### Option A: one-command provisioning (`bootstrap.sh`) ### Option A: one-command provisioning (`bootstrap.sh`)
@@ -451,41 +485,63 @@ On a fresh Ubuntu machine, from a checkout of this repo:
scripts/bootstrap.sh scripts/bootstrap.sh
``` ```
With no `config.json` yet, the script seeds one from `config.example.json`; edit On a fresh machine the script **asks a few questions** and writes this machine's
it to set `llm.model`/`codegen.model` (and the endpoints). Flags override those config from the answers:
values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`,
`--codegen-model` — and are never written back to `config.json`.
The script is idempotent (every stage no-ops on existing state) and: 1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index
repo (`semif-packs`): SimpleX, browser, Nextcloud, Outlook, Gutendex (the
`essentials` pack is always on). Only the packs you pick are cloned.
4. **Gateways** — how you talk to the agent: SimpleX, LXMF, voice (or none —
REPL + dashboard only).
5. **Timezone** — an IANA name for timers and reported times.
It then installs **only what those answers require**. Both ends of the spectrum
are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator, skill listing). No account, no network, no gateway, no heavy
downloads.
- **maximum** — every pack, a remote Winnow or Ollama System One decision
engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is
idempotent — on a rerun the interview is **skipped** and the existing config is
used; pass `--reconfigure` to re-run it. `--voice` / `--browser` additionally
install those optional stacks even if the plan did not pick them.
The script:
1. installs system prereqs + enables linger; 1. installs system prereqs + enables linger;
2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine; 2. clones/updates the skill packs, then runs the setup interview and writes
3. creates `.runtime/venv` and installs the pinned deps from `config/` + `secrets.json` (first run or `--reconfigure`);
`requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since 3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the
the llama.cpp path never imports torch); SemIf engine;
4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`; 4. creates `.runtime/venv` and installs only the needed dep files:
5. pre-fetches the HF tokenizer into `.runtime/hf/`; `requirements/core.txt` always, `engine.txt` for a local engine,
6. downloads and sha256-verifies the pinned `simplex-chat` binary; `transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for
7. seeds `config.json` from `config.example.json` **only if it does not already the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
exist** — it never rewrites `config.json` (only a human edits that file); plus `tts.txt` when `voice.reply_with_voice` is on, and `codec2.txt` + system
8. renders and enables systemd **user** units: `libcodec2` best-effort for non-HQ Codec2 PTT — and each selected pack's own
`semif-simplex` (bot daemon), `semif-gateway` (agent gateway), `packs/<name>/requirements.txt` — e.g. the browser pack's Playwright deps);
`semif-simplex-forward` (the bridge's own daemon), `semif-bridge`; 5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
9. prints the bot's SimpleX contact address. and pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
SimpleX gateway or the simplex pack is selected;
7. renders and enables only the systemd **user** units the answers need
(`semif-simplex` bot daemon, `semif-gateway` agent, `semif-simplex-forward`
bridge daemon, `semif-bridge`), retiring any a reconfigure dropped;
8. prints the SimpleX contact address(es) when those services are active.
Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`, Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it
`--copy-data SRC`) override the values read from `config.json` for that run only. pulls `llm.model` from the target host's ollama when configured, and never
`--voice` additionally installs the optional voice-gateway stack auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF
(`requirements/voice.txt` + system PortAudio) and downloads its models (the tokenizer revision, simplex-chat version/url+sha256) live in the committed
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into `pins.json`, not in `config.json`.
`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache).
Run `scripts/bootstrap.sh -h` for the full list.
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`,
warning (never auto-pulling) if the remote codegen host is missing its model.
Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision,
simplex-chat version/url+sha256) live in the committed `pins.json`, not in
`config.json`.
### Option B: core only (stdlib) ### Option B: core only (stdlib)
@@ -496,25 +552,42 @@ python3 -m pytest tests/ -q --ignore=tests/integration
``` ```
For a full install on a machine you manage, follow the same steps bootstrap For a full install on a machine you manage, follow the same steps bootstrap
performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF, performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF,
tokenizer cache), then create `config.json` from the template and adjust paths: tokenizer cache), then generate the split config:
```sh ```sh
cp config.example.json config.json python -m semif_agent.cli setup --interview # or --yes / --answers FILE
python -m semif_agent.cli config-init # schema defaults, no interview
``` ```
### Configuration ### Configuration
`config.json` is **gitignored, per-machine, and required** — the agent refuses The per-machine config is **gitignored, per-machine, and required** — the agent
to start without it. `scripts/bootstrap.sh` seeds it from `config.example.json` refuses to start without it. `config.json` is a thin **index**
once; afterwards only a human edits it (nothing writes `config.json`). Pinned (`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments
external refs live in the committed `pins.json`, so `config.json` holds only under `config/` hold the values and are deep-merged in order. Credentials live in
per-machine settings: the gitignored `secrets.json` and are referenced from any fragment as
`"!secret <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` runs
`setup` to generate the split config from your answers; afterwards only a human
edits it (`--reconfigure` re-runs the interview).
```sh ```sh
cp config.example.json config.json # if not already created by bootstrap python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli config-init # seed schema defaults (no interview)
python -m semif_agent.cli check-config # validate against the schemas
``` ```
The committed `config.example.json` is **generated** from the core schema
(`semif_agent/config.py`) and each pack's `config` schema; regenerate it after
changing a schema:
```sh
python -m semif_agent.cli check-config --write-example config.example.json
```
Pinned external refs live in the committed `pins.json`, so the config holds only
per-machine settings.
Key blocks: Key blocks:
| Block | What it controls | | Block | What it controls |
@@ -525,8 +598,9 @@ Key blocks:
| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
| `tau` | decision threshold; `max_reentries` requeue bound | | `tau` | decision threshold; `max_reentries` requeue bound |
| `queue` | `max_size` | | `queue` | `max_size` |
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | | `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `gateway.lxmf` | LXMF gateway: allowlist, Reticulum paths, `result_only` replies, Sideband voice transcription (`voice.enabled` + `voice.stt` model) and voice replies (`voice.reply_with_voice` + `voice.tts` voice) |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD | | `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) | | `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
@@ -544,9 +618,12 @@ host/port/token, so there is no duplicate top-level key to keep in sync. A bridg
with no block (or no port) leaves the variable unresolved and the operator is with no block (or no port) leaves the variable unresolved and the operator is
asked for it. asked for it.
`llm.model` and `codegen.model` are **required** (no default): set each to a `llm.model` and `codegen.model` are **required only when authoring is enabled**
model its endpoint serves. A missing model fails fast at startup with a clear (`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves.
config error rather than sending a request to a model that isn't there. An empty `codegen.model` means "no authoring path" — the minimum config leaves it
empty and the agent simply runs the shipped packs. With authoring on, a missing
model fails fast at startup with a clear config error rather than sending a
request to a model that isn't there.
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`, Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too. `data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
@@ -562,6 +639,7 @@ Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
All subcommands go through the CLI: All subcommands go through the CLI:
```sh ```sh
python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli run # interactive REPL python -m semif_agent.cli run # interactive REPL
python -m semif_agent.cli run --script inputs.jsonl python -m semif_agent.cli run --script inputs.jsonl
python -m semif_agent.cli dream # cost report python -m semif_agent.cli dream # cost report
@@ -644,7 +722,7 @@ without it). `allowed_users` entries match a numeric contactId or a display
name. The daemon must run in **bot mode** (`simplex-chat -p PORT name. The daemon must run in **bot mode** (`simplex-chat -p PORT
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean --create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
"chat relay" and yield a relay address, not a user contact address. Add the "chat relay" and yield a relay address, not a user contact address. Add the
bot's contact link to reach it: `scripts/simplex-address.py` shows/creates it bot's contact link to reach it: `packs/simplex/scripts/simplex-address.py` shows/creates it
(bootstrap prints it), and the gateway prints it once on connect. (bootstrap prints it), and the gateway prints it once on connect.
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**; **LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
@@ -658,6 +736,32 @@ matches the peer's LXMF address (32 hex) or a best-effort display name.
and an optional `propagation_node` enables store-and-forward. Add the printed and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it. address as a contact in your LXMF client and DM it.
**Voice commands (Sideband push-to-talk).** Set
`gateway.lxmf.voice.enabled: true` and a Sideband PTT voice message is
transcribed into a command, just like typed text. HQ PTT (Opus/OGG) is decoded
and transcribed by faster-whisper, which needs only `requirements/transcribe.txt`
(installed by the install plan — no microphone, no voice stack). Non-HQ Codec2
PTT is decoded by the optional `pycodec2` bindings (`requirements/codec2.txt`,
installed best-effort alongside the system `libcodec2`); without it a Codec2
message is reported back rather than dropped. The audio is transient and never
leaves the machine. The model is `gateway.lxmf.voice.stt.model` (default
`base.en`).
**Voice replies.** With `gateway.lxmf.voice.reply_with_voice: true` (the
default), a chat that last messaged by voice is answered with a synthesized
voice message: the reply text is spoken with Piper and sent back as a Sideband
HQ push-to-talk message, with the text also carried as the message content so a
text-only client still sees it. A later text message from that chat reverts it to
text replies. This needs only `piper-tts` + PyAV (`requirements/tts.txt`,
installed by the install plan — still no microphone); a missing stack or a
synthesis failure falls back to a text reply rather than dropping it. The voice
is `gateway.lxmf.voice.tts.voice` (default `en_US-lessac-medium`).
**Result-only replies.** The LXMF gateway sends only the skill's result line:
the scheduler's queue/urgency bookkeeping is dropped and the `<skill>: ok —`
wrapper is stripped, so a DM is the answer, not the internals. Override with
`gateway.lxmf.result_only: false` for the full scheduler output.
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends > **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links, > replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges. > or composes messages. That is messaging UX and lives in the bridges.
@@ -724,11 +828,13 @@ python -m semif_agent.cli gateway --platform voice
`cli bridge` runs standalone bridges: each is a process that stands up a small, `cli bridge` runs standalone bridges: each is a process that stands up a small,
token-guarded localhost HTTP API in front of one third-party system (and, where token-guarded localhost HTTP API in front of one third-party system (and, where
the system needs one, owns its own daemon/profile). Generated skill bodies call the system needs one, owns its own daemon/profile). A bridge is a deliberate
them like any HTTP service (base URL from a config var), so they never speak a choice for a system that needs state (especially auth state), a native or heavy
native protocol directly. protocol, or one sanitized surface — a skill may call a plain HTTP API directly.
When a bridge fronts a service, generated skill bodies call it like any HTTP
service (base URL from a config var) and never speak the native protocol.
The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own The first bridge is **SimpleX** (`packs/simplex/bridge/simplex.py`), with its own
simplex-chat daemon separate from the gateway's. Its HTTP surface: simplex-chat daemon separate from the gateway's. Its HTTP surface:
``` ```
@@ -750,10 +856,11 @@ acking is a client-side read receipt, not an API call.
Skills call the forwarding bridge at the address derived from `bridges.simplex` Skills call the forwarding bridge at the address derived from `bridges.simplex`
(`simplex_bridge_url`); the bridge catalog (`simplex_bridge_url`); the bridge catalog
is injected into every codegen prompt via `describe_bridges()`, so it is the is injected into every codegen prompt via `describe_bridges()`, so it is the
single source of bridge specifics. Adding a bridge = a class + a config block + single source of bridge specifics. Adding a bridge = a pack that ships its
a `CATALOG` entry. `bridge/<name>.py` + a config block; the core registry discovers it by convention.
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic The **LLM bridge** (`semif_agent/bridges/llm.py`) is the shared, pack-less one: a
generic
``` ```
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."} POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
@@ -769,17 +876,18 @@ carries just the local listener. Skills call it at the address derived from
it returns `502`, never a fabricated reply. It starts in the same it returns `502`, never a fabricated reply. It starts in the same
`semif-bridge.service` process as the other enabled bridges. `semif-bridge.service` process as the other enabled bridges.
The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it The **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py`) is the third: it
wraps the account's native protocols — WebDAV files, CalDAV calendar events and wraps the account's native protocols — WebDAV files, CalDAV calendar events and
tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a
body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is
plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
in the same `semif-bridge` process. The connection (base URL, username, app in the same `semif-bridge` process. The connection (base URL, username, app
password) is configured in `bridges.nextcloud` and falls back to the top-level password) is configured in `bridges.nextcloud`; `NextcloudBridge.from_config`
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` / also accepts the top-level `nextcloud_url` / `nextcloud_username` /
`nextcloud_default_calendar` the nextcloud seeds use, so the account is `nextcloud_app_password` / `nextcloud_default_calendar` as a fallback for a
configured once. Skills call it at the address derived from `bridges.nextcloud` hand-edited config, with a block value winning. Skills call it at the address
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface: derived from `bridges.nextcloud` (`nextcloud_bridge_url`, + optional
`nextcloud_bridge_token`). Its HTTP surface:
``` ```
GET /health GET /health
@@ -791,8 +899,8 @@ GET /files/read?path=<path> # text, or base64 for binary
GET /files/search?query=<text>&path=<dir> GET /files/search?query=<text>&path=<dir>
POST /files/write {"path","content","encoding"?,"overwrite"?} POST /files/write {"path","content","encoding"?,"overwrite"?}
POST /files/mkdir | /files/delete | /files/move | /files/copy POST /files/mkdir | /files/delete | /files/move | /files/copy
GET /calendars GET /calendars # includes "default" (configured default name)
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT; recurrences expand with a window
POST /calendars/events | /calendars/events/update | /calendars/events/delete POST /calendars/events | /calendars/events/update | /calendars/events/delete
GET /tasks?calendar=<name> # CalDAV VTODO GET /tasks?calendar=<name> # CalDAV VTODO
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
@@ -808,13 +916,13 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo
defaults resolve from `bridges.nextcloud` when a request names none and the defaults resolve from `bridges.nextcloud` when a request names none and the
account has several. account has several.
The **Outlook bridge** (`semif_agent/bridges/outlook.py`) wraps the user's The **Outlook bridge** (`packs/outlook/bridge/outlook.py`) wraps the user's
Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail, Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail,
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only, Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
so it starts instantly in the same `semif-bridge` process. Authorization is the so it starts instantly in the same `semif-bridge` process. Authorization is the
OAuth2 **device code flow**: register an Entra ID public-client app, put its OAuth2 **device code flow**: register an Entra ID public-client app, put its
`client_id` in `bridges.outlook`, and run `scripts/outlook-auth.py` once — the `client_id` in `bridges.outlook`, and run `packs/outlook/scripts/outlook-auth.py` once — the
tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and
refreshed automatically. The bridge starts without a token; an unauthenticated refreshed automatically. The bridge starts without a token; an unauthenticated
route returns `503` telling the operator to run that helper. Skills call it at the route returns `503` telling the operator to run that helper. Skills call it at the
@@ -843,12 +951,12 @@ POST /files/write {"path","content","encoding"?,"overwrite"?}
A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure
(transport, HTTP error, or a bad reply) is `502` — never a fabricated success. (transport, HTTP error, or a bad reply) is `502` — never a fabricated success.
Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`, Seven `packs/outlook/skills/outlook/*` skills ship (`next_message`, `send_message`,
`next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`); `next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`);
`send_message` composes the message through the LLM bridge and asks for `send_message` composes the message through the LLM bridge and asks for
confirmation before it sends. confirmation before it sends.
The **browser bridge** (`semif_agent/bridges/browser.py`) is real browser The **browser bridge** (`packs/browser/bridge/browser.py`) is real browser
automation via **Playwright**: open a URL, read a page's text or links, take a automation via **Playwright**: open a URL, read a page's text or links, take a
screenshot, and click/fill/press/select to complete a flow. It is the first screenshot, and click/fill/press/select to complete a flow. It is the first
bridge with a heavy optional dependency, so it is **disabled by default** and bridge with a heavy optional dependency, so it is **disabled by default** and
@@ -856,7 +964,7 @@ installed with `scripts/bootstrap.sh --browser` (Playwright + Chromium land unde
`.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch). `.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch).
If `playwright install` fails — notably on a host with an IPv6 address but no If `playwright install` fails — notably on a host with an IPv6 address but no
global IPv6 route, where Playwright's downloader prefers IPv6 and hangs — global IPv6 route, where Playwright's downloader prefers IPv6 and hangs —
bootstrap falls back to `scripts/playwright-browsers.py`, which downloads the bootstrap falls back to `packs/browser/scripts/playwright-browsers.py`, which downloads the
same pinned artifacts over IPv4. To skip the managed download altogether, set same pinned artifacts over IPv4. To skip the managed download altogether, set
`bridges.browser.channel` (a Playwright channel such as `chrome`/`msedge`) or `bridges.browser.channel` (a Playwright channel such as `chrome`/`msedge`) or
`bridges.browser.executable_path` (a browser binary) to use an already-installed `bridges.browser.executable_path` (a browser binary) to use an already-installed
@@ -890,7 +998,7 @@ POST /back | /forward {"timeout"?}
POST /reset {"purge"?} # close; purge deletes the profile POST /reset {"purge"?} # close; purge deletes the profile
``` ```
Three `seeds/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). Three `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`).
### Dream report ### Dream report
@@ -927,20 +1035,24 @@ bodies, no external network, no `mock_data.json`. Passing it proves the code
runs, not that the live integration works. That is what the real run and the runs, not that the live integration works. That is what the real run and the
repair loop are for. repair loop are for.
**Seeds** (`seeds/`) ship real starter integrations in the exact generated **Packs** ship real starter integrations in the exact generated folder format,
folder format, plus a `manifest.json`. `merge_seed_store` loads them into every plus a `manifest.json` and a `pack.json` manifest binding the concern to its
tree at startup; recorded config is written to the runtime store, so the categories, bridge, and config schema. Each pack lives in its **own repository**
committed seed never holds secrets. (`pack.<name>`, listed in the `semif-packs` index repo); `scripts/bootstrap.sh` clones them into
the gitignored `packs/<name>/`, and `merge_packs` loads every enabled pack into
the tree at startup. Recorded config is written to the runtime store, so a pack
repo never holds secrets. `PACKGEN.md` is the authoritative contract for
authoring a new pack (and a new bridge to back one).
- `nextcloud.create_event` — create an event on Nextcloud CalDAV (the - `nextcloud.create_event` — create an event on the user's Nextcloud calendar
authoritative worked example); resolves the target calendar with a SemIf through the Nextcloud bridge (`GET /calendars`, `POST /calendars/events`);
choice over the owned calendars (strong winner, else the configured default); resolves the target calendar with a SemIf choice over the owned calendars
config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`, (strong winner, else the configured default); config vars
`nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`, `nextcloud_bridge_url`, `nextcloud_bridge_token`, plus the LLM bridge
`llm_bridge_token`). (`llm_bridge_url`, `llm_bridge_token`).
- `nextcloud.next_event` — next upcoming event from Nextcloud CalDAV (recurring - `nextcloud.next_event` — next upcoming event through the Nextcloud bridge
events expanded server-side); config vars `nextcloud_url`, (`GET /calendars`, `GET /calendars/events`; recurring events expanded
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`. server-side); config vars `nextcloud_bridge_url`, `nextcloud_bridge_token`.
- `nextcloud.create_task` — add a task to a Nextcloud task list through the - `nextcloud.create_task` — add a task to a Nextcloud task list through the
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`, `nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
@@ -960,6 +1072,12 @@ committed seed never holds secrets.
cubes, square roots, cube roots, fractions, and percentages, and SemIf picks cubes, square roots, cube roots, fractions, and percentages, and SemIf picks
the operands when the request writes more numbers than the operation needs the operands when the request writes more numbers than the operation needs
(pure local compute, no config). (pure local compute, no config).
- `skills.list_categories` — list the categories of skills the agent has
(pure local compute, no config; reads the read-only `ctx.catalog`, not the
housekeeping-only `ctx.admin`).
- `skills.list_skills` — list the skills inside a category named in the request
("list skills in nextcloud"), asking for one when it is missing and reporting
an unknown category honestly (pure local compute, no config).
--- ---
@@ -993,7 +1111,7 @@ logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` /
contract → test → auto-run → re-dispatch); tiered config + first-fire contract → test → auto-run → re-dispatch); tiered config + first-fire
collection; runtime repair loop; the closed `response` canned tree; real collection; runtime repair loop; the closed `response` canned tree; real
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message standalone SimpleX bridge + pack skills (contact-list refresh, daemon-backed message
history / true unread); the LXMF gateway; and the voice gateway (wake word + history / true unread); the LXMF gateway; and the voice gateway (wake word +
speech-to-text + text-to-speech). speech-to-text + text-to-speech).
+10 -6
View File
@@ -6,6 +6,9 @@ test artifact. The runnable body contract lives in `CODEGEN.md`; this file is
deliberately separate so the body writer never embeds test data and the test is 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. 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 A finished skill leaf is a folder
`data/skills/<category>/<name>/` containing (among others) two artifacts: `data/skills/<category>/<name>/` containing (among others) two artifacts:
@@ -84,12 +87,13 @@ A stdlib-only Python script that:
Assert the server actually received the expected request (method, path, Assert the server actually received the expected request (method, path,
headers, body) where practical. The loopback address exists only in the test; headers, body) where practical. The loopback address exists only in the test;
the body must read its endpoint from config. the body must read its endpoint from config.
- For a messaging skill (a body that talks to a bridge service), stand up a - For a body that talks to a bridge service (or any fixed HTTP API), stand up a
loopback server implementing the bridge endpoints the body uses (the bridge loopback server implementing the endpoints the body uses (the bridge catalog
catalog injected into this prompt lists them) and assert the body built the injected into this prompt lists a bridge's; for a direct HTTP API, mirror the
real requests. If the catalog names an auth header, set the fixture token in routes the body calls) and assert the body built the real requests. If the
the fixture config and assert the body sent that header. Never connect to a catalog names an auth header, set the fixture token in the fixture config and
real service daemon or a live bridge. 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 - For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
resolution, argument construction, and error paths (missing or misconfigured resolution, argument construction, and error paths (missing or misconfigured
values) without performing the real I/O. values) without performing the real I/O.
+152 -112
View File
@@ -1,35 +1,27 @@
{ {
"_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.",
"tau": 0.6, "tau": 0.6,
"max_reentries": 3, "max_reentries": 3,
"query_recall_window": 30, "query_recall_window": 30,
"_query_recall_window_comment": "Seconds a completed run stays recallable to a follow-up request in the same chat/source. A follow-up within the window is given the previous run's ledger as 'previous request' context (and bodies can reuse its result via last_result), so a reference like \"send it to Sam\" resolves against what the agent just did. 0 disables recall entirely. Measured from the previous run's completion; only the last completed real skill run per source is remembered (canned responses and housekeeping meta skills are never recalled).", "new_skill_creation": "deny",
"new_skill_creation": "allow",
"_new_skill_creation_comment": "Global new-skill creation mode: \"allow\" (create without asking), \"deny\" (never author new skills/categories), or \"ask\" (author only after the human approves the proposal). A category can override this in data/skills/<category>/config.json with its own \"new_skill_creation\" value; the built-in housekeeping and response categories are always denied in code.",
"verbosity": "result", "verbosity": "result",
"_verbosity_comment": "How much of a completed request to surface. \"result\" (default): only the final answer — an end user does not care which skills ran or which decisions were made. \"query\": also show each intermediate step of a chained request (its query + run-ledger entry). \"decision\": also show every SemIf decision (phase + selected option + probabilities) for a step — a debugging view.",
"chain": { "chain": {
"_comment": "Chained multi-step completion. When a run's outcome assessment says more work is needed, the request is re-dispatched with a compact run ledger and routed to the logical next skill, until the request is satisfied, fails into repair, or the chain is capped by max_reentries. result_chars is the ONE shared speakable budget applied to every skill's output (its result string and its ledger entry): a result is read in a chat message or heard as speech, so it is truncated to this many characters at a word boundary. A long product of a skill belongs in a file I/O side effect, not the result string (see CODEGEN.md/TESTGEN.md). The voice front end (gateway.voice.max_speak_chars) and the humanizer (gateway.humanize.max_chars) are downstream caps and should not exceed it.",
"result_chars": 300 "result_chars": 300
}, },
"assess": { "assess": {
"_comment": "Thresholds for the three-way assess:outcome decision (is there additional work to be done to satisfy the request?): done (request satisfied), continue (the step worked but more work is needed; route the next step), failed (the step errored; offer repair). Verdict precedence is failed > done > continue, so a confident success/failure is honored and continue — the over-trigger — only wins when the model is genuinely unsure. Separate from the top-level tau so completion tuning does not move assessment/fidelity.",
"done_tau": 0.5, "done_tau": 0.5,
"fail_tau": 0.5 "fail_tau": 0.5
}, },
"timezone": "", "timezone": "",
"navigation": { "navigation": {
"_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then decides what the winner does for the request — same (it performs the next action the request needs), part (the request needs more than one action and this skill performs one required part), or different (a new leaf is authored) (phase navigate:intent, P(same)+P(part) >= intent_tau). All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.",
"intent_tau": 0.6, "intent_tau": 0.6,
"category_tau": 0.75, "category_tau": 0.75,
"action_tau": 0.5, "action_tau": 0.5,
"softmax_bypass_tau": 0.5 "softmax_bypass_tau": 0.5
}, },
"queue": {"max_size": 100}, "queue": {
"max_size": 100
},
"engine": { "engine": {
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
"_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).",
"_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.",
"provider": "semif", "provider": "semif",
"backend": "llamacpp", "backend": "llamacpp",
"context_tokens": 4096, "context_tokens": 4096,
@@ -38,25 +30,33 @@
"gpu_device": null, "gpu_device": null,
"gpu_split": 0, "gpu_split": 0,
"winnow": { "winnow": {
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). context_tokens must mirror the server's --ctx-size: generated skill bodies are sized from the active engine's context so a fidelity decision can always ingest one whole. timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
"base_url": "http://127.0.0.1:8091", "base_url": "http://127.0.0.1:8091",
"model": "", "model": "",
"context_tokens": 32768, "context_tokens": 32768,
"api_key": "", "api_key": "!secret engine_winnow_api_key",
"api_key_env": "",
"timeout": 120, "timeout": 120,
"retries": 0, "retries": 0,
"user_agent": "semif-agent", "user_agent": "semif-agent",
"extra_headers": {} "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": { "llm": {
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
"provider": "ollama", "provider": "ollama",
"base_url": "http://localhost:11434/v1", "base_url": "http://localhost:11434/v1",
"model": "", "model": "",
"api_key": "", "api_key": "!secret llm_api_key",
"api_key_env": "",
"user_agent": "", "user_agent": "",
"timeout": 600, "timeout": 600,
"stream": false, "stream": false,
@@ -69,18 +69,15 @@
"frequency_penalty": 0.0, "frequency_penalty": 0.0,
"disable_thinking": true, "disable_thinking": true,
"semif": { "semif": {
"_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.",
"temperature": 0.0, "temperature": 0.0,
"max_tokens": 256 "max_tokens": 256
} }
}, },
"codegen": { "codegen": {
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. PRIVACY: codegen is the primarily-cloud model, so it is shown ONLY a de-identified, reusable spec authored by the local `llm` (goal + generic service/transport) — never the user's request text, question answers, or any run output. After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama", "provider": "ollama",
"base_url": "http://localhost:11434/v1", "base_url": "http://localhost:11434/v1",
"model": "", "model": "",
"api_key": "", "api_key": "!secret codegen_api_key",
"api_key_env": "",
"user_agent": "", "user_agent": "",
"timeout": 3600, "timeout": 3600,
"stream": true, "stream": true,
@@ -99,32 +96,26 @@
"frequency_penalty": 1, "frequency_penalty": 1,
"max_attempts": 3, "max_attempts": 3,
"approval": { "approval": {
"_comment": "The optional creation-approval gate (new_skill_creation == \"ask\"): the single-slot draft worker blocks after it authors a proposal and before anything is registered, waiting up to wait_timeout seconds for a human approve/deny. Denial or timeout aborts creation. Set 0 to wait forever.",
"wait_timeout": 900 "wait_timeout": 900
}, },
"fidelity": { "fidelity": {
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). The state carries the WHOLE body (never a prefix) plus a deterministic operation inventory and the de-identified goal, and asks the positive question (is there a concrete operation that realizes the goal?). tau is this gate's own threshold, separate from the top-level tau. Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle (inventory + findings included), bounded by max_attempts; a still-fake body is accepted but traced, never a hard authoring failure.",
"enabled": true, "enabled": true,
"max_attempts": 1, "max_attempts": 1,
"tau": 0.6 "tau": 0.6
}, },
"repair": { "repair": {
"_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.",
"enabled": true, "enabled": true,
"max_attempts": 1 "max_attempts": 1
}, },
"test_timeout": 30, "test_timeout": 30,
"test_max_attempts": 3, "test_max_attempts": 3,
"_artifact_budget_comment": "Generated artifacts are ingested WHOLE by a decision (the fidelity gate reads the entire skill body), so each is size-bounded. max_body_tokens/max_test_tokens are hard ceilings; 0 derives each from the ACTIVE decision engine's context (engine.context_tokens for the local GGUF, engine.winnow.context_tokens for Winnow) minus decision_reserve_tokens — the headroom for everything else in the fidelity state (goal, description, integration, findings, operation inventory, question, options, engine prefill margin). A positive value overrides the derivation: lower it if you don't want to wait on a long fidelity evaluation, raise it if your engine has a larger window. chars_per_token above converts the token budget to the char limit the parser enforces; a body over budget is rejected (ArtifactTooLong) and the codegen retry ladder asks for a shorter one.",
"max_body_tokens": 0, "max_body_tokens": 0,
"max_test_tokens": 0, "max_test_tokens": 0,
"decision_reserve_tokens": 1024, "decision_reserve_tokens": 1024,
"contract_search": { "contract_search": {
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
"enabled": true "enabled": true
}, },
"degeneration": { "degeneration": {
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
"enabled": true, "enabled": true,
"threshold": 0.9, "threshold": 0.9,
"interval": 8000, "interval": 8000,
@@ -133,96 +124,23 @@
} }
}, },
"skill_bodies": "data/skills", "skill_bodies": "data/skills",
"skill_seeds": "seeds",
"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",
"simplex_chat": { "simplex_chat": {
"_comment": "Per-machine simplex-chat daemon settings. The pinned binary (version/bin_url/sha256) lives in the committed pins.json, not here. The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh renders both units from these values. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
"port": 5226, "port": 5226,
"display_name": "semif", "display_name": "semif",
"forward_port": 5228, "forward_port": 5228,
"forward_display_name": "semif-forward" "forward_display_name": "semif-forward"
}, },
"bridges": {
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
"simplex": {
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
"enabled": true,
"host": "127.0.0.1",
"port": 5227,
"token": "",
"max_inbox": 100,
"ws_url": "ws://127.0.0.1:5228",
"user_id": 1,
"auto_accept": true,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
},
"llm": {
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": ""
},
"nextcloud": {
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the nextcloud seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
"enabled": true,
"host": "127.0.0.1",
"port": 5230,
"token": "",
"url": "",
"username": "",
"app_password": "",
"default_calendar": "",
"default_task_calendar": "",
"default_addressbook": "",
"verify_tls": true,
"timeout": 30
},
"outlook": {
"_comment": "Outlook bridge: the user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — over one uniform local JSON API, so skill bodies never speak Graph or OAuth. No service daemon and no extra dependency (Graph is plain HTTPS); it runs inside the same `semif-bridge` process as the other enabled bridges. Authorization is the OAuth2 device code flow: register an Entra ID public-client app, put its `client_id` here, run `scripts/outlook-auth.py` once, and the tokens are stored (0600) under `.runtime/outlook/token.json` (override with `token_path`). `tenant` is usually `common` (personal + work accounts). `default_calendar`/`default_task_list`/`default_mail_folder` are used when a request names none; `default_timezone` (IANA name) labels created events/tasks whose start has no offset. `verify_tls` false skips certificate verification. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Disabled by default because it needs a client id + an authorization run first.",
"enabled": false,
"host": "127.0.0.1",
"port": 5231,
"token": "",
"client_id": "",
"tenant": "common",
"default_calendar": "",
"default_task_list": "",
"default_mail_folder": "inbox",
"default_timezone": "UTC",
"verify_tls": true,
"timeout": 30
},
"browser": {
"_comment": "Browser bridge: real browser automation via Playwright — open a URL, read a page's text/links, take a screenshot, and click/fill/press/select to complete a flow — behind one uniform local JSON API, so skill bodies never bundle a browser stack. Disabled by default because it needs the optional Playwright deps + browser binaries: install with `scripts/bootstrap.sh --browser` (browsers land under .runtime/browser). The bridge keeps a PERSISTENT profile under .runtime/browser/profile, so logins/cookies survive across calls and restarts (POST /reset with purge=true wipes it); `engine` is chromium|firefox|webkit and `headless` false shows the window. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. A missing Playwright/browser is a 503 install hint, never a startup failure (the other bridges keep running). Set `channel` (e.g. chrome/msedge) or `executable_path` (a browser binary) to use an already-installed browser and skip Playwright's managed download entirely; `executable_path` wins if both are set.",
"enabled": false,
"host": "127.0.0.1",
"port": 5232,
"token": "",
"engine": "chromium",
"headless": true,
"channel": "",
"executable_path": "",
"profile_dir": "",
"browsers_path": "",
"screenshot_dir": "",
"default_timeout": 30,
"max_text_chars": 20000
}
},
"gateway": { "gateway": {
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.",
"humanize": { "humanize": {
"_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `<skill>: <ok|failed> — <detail>` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.",
"enabled": true, "enabled": true,
"timeout": 20.0, "timeout": 20.0,
"max_tokens": 200, "max_tokens": 200,
"max_chars": 600 "max_chars": 600
}, },
"simplex": { "simplex": {
"_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. Groups/attachments are not supported.",
"enabled": true, "enabled": true,
"ws_url": "ws://127.0.0.1:5226", "ws_url": "ws://127.0.0.1:5226",
"allowed_users": [], "allowed_users": [],
@@ -231,10 +149,13 @@
"home_channel": "", "home_channel": "",
"reply_prefix": "", "reply_prefix": "",
"text_batch_delay": 0.8, "text_batch_delay": 0.8,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} "reconnect": {
"initial": 1.0,
"max": 60.0,
"jitter": 0.2
}
}, },
"lxmf": { "lxmf": {
"_comment": "LXMF (Reticulum) command adapter. Runs IN-PROCESS — there is no external daemon; `pip install lxmf` provides the transport (optional, lazy-imported; the gateway refuses to start with an install hint). The bot's reachable address is its LXMF delivery destination hash (32 hex chars), printed on connect. config_dir/storage_path hold Reticulum's config and the persisted identity under .runtime/lxmf/ so the address is stable across restarts (empty = the .runtime/lxmf defaults). allowed_users entries match the peer's LXMF address (32 hex chars) or a best-effort display name; default is deny-all unless allow_all_users is set. desired_method is 'direct' (reliable link) or 'opportunistic' (single packet). propagation_node is an optional LXMF propagation-node address (hex) for store-and-forward.",
"enabled": false, "enabled": false,
"allowed_users": [], "allowed_users": [],
"allow_all_users": false, "allow_all_users": false,
@@ -247,10 +168,33 @@
"storage_path": "", "storage_path": "",
"home_channel": "", "home_channel": "",
"reply_prefix": "", "reply_prefix": "",
"text_batch_delay": 0.8 "text_batch_delay": 0.8,
"result_only": true,
"voice": {
"enabled": false,
"reply_with_voice": true,
"max_speak_chars": 600,
"reply_bitrate": 24000,
"read": {
"enabled": true,
"chunk_chars": 300
},
"stt": {
"model": "base.en",
"device": "cpu",
"compute_type": "int8",
"language": "en"
},
"tts": {
"voice": "en_US-lessac-medium",
"voice_dir": "",
"speaker_id": 0,
"length_scale": 1.0,
"volume": 1.0
}
}
}, },
"voice": { "voice": {
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. The wake word is required before every command and is held while the scheduler is still running the current request, so a new command cannot start until it reaches a result. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.",
"enabled": false, "enabled": false,
"chat_id": "voice", "chat_id": "voice",
"display_name": "voice", "display_name": "voice",
@@ -258,20 +202,31 @@
"reply_prefix": "", "reply_prefix": "",
"result_only": true, "result_only": true,
"max_speak_chars": 600, "max_speak_chars": 600,
"read": {
"enabled": true,
"chunk_chars": 300
},
"listen_timeout_s": 3.0, "listen_timeout_s": 3.0,
"cue": { "cue": {
"_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; submit_notes is a short multi-note 'bling' played once the utterance is transcribed (each entry [frequency_hz, duration_ms], separated by note_gap_ms of silence). Set submit_notes to [] and submit_frequency > 0 for the older single submit beep, or leave both empty/0 for no submit sound. volume is 0..1.",
"enabled": true, "enabled": true,
"frequency": 880, "frequency": 880,
"duration_ms": 120, "duration_ms": 120,
"volume": 0.9, "volume": 0.9,
"submit_frequency": 0, "submit_frequency": 0,
"submit_duration_ms": 100, "submit_duration_ms": 100,
"submit_notes": [[1046.5, 70], [1568.0, 90]], "submit_notes": [
[
1046.5,
70
],
[
1568.0,
90
]
],
"note_gap_ms": 20 "note_gap_ms": 20
}, },
"wake": { "wake": {
"_comment": "model is an openWakeWord name/path. The default 'hey_computer' is a pinned community model whose scores run lower than the official models (measured ~0.26-0.82 on the phrase, <0.02 on negatives), so threshold 0.2 is tuned for it; the official models (e.g. hey_mycroft) score ~0.99 and are fine at 0.5.",
"model": "hey_computer", "model": "hey_computer",
"threshold": 0.2, "threshold": 0.2,
"inference_framework": "onnx", "inference_framework": "onnx",
@@ -291,7 +246,6 @@
"volume": 1.0 "volume": 1.0
}, },
"audio": { "audio": {
"_comment": "Capture-stream watchdog: read_timeout_s is how long a frame read waits before it counts as a stall; when the stream stalls continuously for stall_timeout_s (a wedged PortAudio/ALSA callback stops delivering frames) the input is closed and reopened so the voice front end recovers instead of hanging forever. 0 for either restores the old blocking read with no recovery.",
"input_device": "", "input_device": "",
"output_device": "", "output_device": "",
"sample_rate": 16000, "sample_rate": 16000,
@@ -303,7 +257,6 @@
"stall_timeout_s": 5.0 "stall_timeout_s": 5.0
}, },
"vad": { "vad": {
"_comment": "Endpointing. silence_ms is the trailing-silence endpoint once a command is underway. The wake detector can fire inside the wake phrase (and the cue beep follows), so the first speech captured is the phrase's tail, not the command: until min_command_ms of speech is in hand the endpoint uses initial_silence_ms instead, so a natural pause before the command does not end the capture. min_speech_ms rejects a blip; max_utterance_s caps a runaway.",
"silence_ms": 500, "silence_ms": 500,
"min_speech_ms": 120, "min_speech_ms": 120,
"max_utterance_s": 30, "max_utterance_s": 30,
@@ -311,8 +264,95 @@
"initial_silence_ms": 1500, "initial_silence_ms": 1500,
"aggressiveness": 2, "aggressiveness": 2,
"energy_threshold": 200.0 "energy_threshold": 200.0
},
"follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
} }
} }
}, },
"dashboard": {"port": 8765, "host": "127.0.0.1"} "dashboard": {
"port": 8765,
"host": "127.0.0.1"
},
"skill_packs": "packs",
"secrets_file": "secrets.json",
"_comment": "GENERATED from the core schema (semif_agent/config.py) and each pack's pack.json `config` schema \u2014 do not hand-edit; edit a pack's schema or the core schema. This is the reference example; the live per-machine config is split under config/ (see config.json's include list) and secrets live in the gitignored secrets.json, referenced as '!secret <key>'.",
"bridges": {
"llm": {
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": "!secret llm_token"
},
"browser": {
"enabled": false,
"host": "127.0.0.1",
"port": 5232,
"token": "!secret browser_token",
"engine": "chromium",
"headless": true,
"channel": "",
"executable_path": "",
"profile_dir": "",
"browsers_path": "",
"screenshot_dir": "",
"default_timeout": 30.0,
"max_text_chars": 20000
},
"nextcloud": {
"enabled": true,
"host": "127.0.0.1",
"port": 5230,
"token": "!secret nextcloud_token",
"url": "",
"username": "",
"app_password": "!secret nextcloud_app_password",
"default_calendar": "",
"default_task_calendar": "",
"default_addressbook": "",
"verify_tls": true,
"timeout": 30
},
"outlook": {
"enabled": false,
"host": "127.0.0.1",
"port": 5231,
"token": "!secret outlook_token",
"client_id": "",
"tenant": "common",
"token_path": ".runtime/outlook/token.json",
"default_calendar": "",
"default_task_list": "",
"default_mail_folder": "inbox",
"default_timezone": "UTC",
"verify_tls": true,
"timeout": 30
},
"simplex": {
"enabled": true,
"host": "127.0.0.1",
"port": 5227,
"token": "!secret simplex_token",
"max_inbox": 100,
"ws_url": "ws://127.0.0.1:5228",
"user_id": 1,
"auto_accept": true,
"reconnect": {
"initial": 1.0,
"max": 60.0,
"jitter": 0.2
}
}
},
"packs": {
"essentials": {
"enabled": true
},
"gutendex": {
"enabled": true
}
}
} }
+9
View File
@@ -175,6 +175,15 @@ Then on the gateway host set:
"gateway": { "voice": { "tts": { "voice": "<name>" } } } "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 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 integration** — a generated test passing proves mechanics, not that the voice
loads and sounds right. loads and sounds right.
+2 -1
View File
@@ -216,6 +216,7 @@ confirm is skipped; the **leaf** intent guard is never bypassed (the leaf softma
has no create option, so a confident winner is only the closest existing skill, 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. never a match) — it always runs and can reject into create.
New-skill creation is gated deterministically by the tri-state New-skill creation is gated deterministically by the tri-state
`new_skill_creation` mode — global default (`allow` / `deny` / `ask`) with a `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 per-category override in `data/skills/<category>/config.json`; the
`housekeeping` and `response` categories are always `deny` in code. `housekeeping` and `response` categories are always `deny` in code.
-21
View File
@@ -1,21 +0,0 @@
# Browser bridge deps (optional).
#
# Only needed on a host that runs the browser bridge (browser automation skills).
# Lazy-imported by semif_agent/bridges/browser_client.py, so the core stays
# stdlib-only and every other bridge keeps running without it. Install with
# scripts/bootstrap.sh --browser, or:
# .runtime/venv/bin/pip install -r requirements/browser.txt
# PLAYWRIGHT_BROWSERS_PATH=.runtime/browser \
# .runtime/venv/bin/python -m playwright install chromium
#
# The browser binaries are NOT shipped in the wheel: `playwright install`
# downloads Chromium into PLAYWRIGHT_BROWSERS_PATH. bootstrap.sh points that at
# the checkout's .runtime/browser (the containment rule); the bridge sets the
# same env var at launch, so the binaries live with the rest of the stack. Add
# `--with-deps` to the install command on a bare host to fetch the system
# libraries Chromium needs (needs sudo).
#
# Only `chromium` is installed by default; switch bridges.browser.engine to
# firefox/webkit and run `python -m playwright install firefox`/`webkit` for
# those.
playwright==1.63.0
+15
View File
@@ -0,0 +1,15 @@
# Codec2 voice-message decoding (optional).
#
# Sideband's non-HQ push-to-talk messages carry raw Codec2 frames
# (`LXMF.AM_CODEC2_*`); decoding them needs the `pycodec2` bindings, which
# compile against the system `libcodec2` (Debian/Ubuntu: `libcodec2-dev`). Only
# needed for `gateway.lxmf.voice` when the sender uses non-HQ PTT — HQ Opus
# works with `requirements/transcribe.txt` alone. Lazy-imported by
# semif_agent/voice_transport.py, so the core stays stdlib-only; a missing
# decoder is reported per-message, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the plan
# installs it best-effort), or manually:
# apt-get install -y libcodec2-dev
# .runtime/venv/bin/pip install -r requirements/codec2.txt
pycodec2==4.1.1
+9
View File
@@ -0,0 +1,9 @@
# Core agent deps (the agent itself is stdlib-only; this is the test runner).
#
# Every host installs this. The decision engine and messaging transports are
# separate, optional files (engine.txt, transports.txt) so a host installs only
# what its answers require. The voice stack (voice.txt) is hardware-dependent,
# and the browser stack ships WITH its pack (packs/browser/requirements.txt) —
# bootstrap installs each selected pack's own requirements.txt.
# `staging.txt` includes the repo-level files for a full provision.
pytest
+18
View File
@@ -0,0 +1,18 @@
# Local decision-engine deps (SemIf / llama.cpp, CPU path).
#
# Only needed on a host whose `engine.provider` is the local SemIf GGUF. A host
# pointed at a remote Winnow decision server (engine.provider == "winnow")
# installs neither this file nor the SemIf engine clone / GGUF / tokenizer.
#
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
# cp314 wheel (source build fails). So semif-phase1 is installed with
# `--no-deps` and exactly this set is brought in instead. The pins match the
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
# declared version) so the pip resolver stays quiet about it.
numpy==2.3.5
transformers==5.17.0
tokenizers==0.23.2
huggingface-hub==1.31.0
llama-cpp-python==0.3.35
+16 -22
View File
@@ -1,23 +1,17 @@
# Staging-machine engine deps (CPU llama.cpp path). # Full provision: every repo-level dependency this checkout can need, for a host
# that runs the local decision engine and all messaging transports. This is the
# union of the per-concern files below; a `scripts/bootstrap.sh` run installs
# only the subset its answers require, so prefer those files (engine.txt,
# transports.txt) when provisioning by hand.
# #
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/ # Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend # hardware/optional. Voice is a repo file installed with
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no # `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are
# cp314 wheel (source build fails). So semif-phase1 is installed with # installed by bootstrap when that pack is selected. transcribe.txt
# `--no-deps` and exactly this set is brought in instead. The pins match the # (faster-whisper only, for LXMF Sideband voice messages), tts.txt (piper-tts +
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's # PyAV, for LXMF voice replies) and codec2.txt (pycodec2, for non-HQ Codec2 PTT)
# declared version) so the pip resolver stays quiet about it. # are likewise optional and installed by bootstrap when `gateway.lxmf.voice` is
numpy==2.3.5 # enabled.
transformers==5.17.0 -r core.txt
tokenizers==0.23.2 -r engine.txt
huggingface-hub==1.31.0 -r transports.txt
llama-cpp-python==0.3.35
pytest
# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the
# gateway refuses to start without it. Not needed by the decision engine.
websockets==15.0.1
# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway
# refuses to start without it. Runs in-process — there is no daemon binary.
# rns pulls cryptography + pyserial transitively (resolved by pip).
lxmf==1.2.0
rns==1.5.7
+20
View File
@@ -0,0 +1,20 @@
# Voice-message transcription deps (optional).
#
# Only needed on a host whose LXMF gateway transcribes Sideband push-to-talk
# voice messages (`gateway.lxmf.voice.enabled`) but that does NOT run the voice
# gateway — `requirements/voice.txt` is hardware-dependent (PortAudio mic +
# speaker, wake word, TTS) and none of that is required here. faster-whisper
# decodes the Opus/OGG container itself (its bundled PyAV/ffmpeg) and
# transcribes, and is lazy-imported by semif_agent/voice_transport.py, so the
# core stays stdlib-only on every other host.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/transcribe.txt
faster-whisper==1.2.1
# PyAV 19.0.0 (2026-09-29) REMOVED the `metadata_errors` argument to av.open(),
# which faster-whisper 1.2.1 (the latest release) still passes — so any voice
# message fails to decode with `TypeError: open() got an unexpected keyword
# argument 'metadata_errors'`. faster-whisper's git master handles both, but it
# is unreleased; pin PyAV below 19 until a release ships the fix.
av<19
+13
View File
@@ -0,0 +1,13 @@
# Messaging transport deps (SimpleX + LXMF gateways/bridges).
#
# Only needed on a host that enables the SimpleX gateway or bridge (which uses
# `websockets` against its simplex-chat daemon) or the LXMF gateway (in-process
# `lxmf`/`rns`). Both are lazy-imported, so a host without them still runs every
# other front end; the gateway refuses to start with an install hint.
#
# `websockets` is shared by the command gateway and the forwarding bridge (the
# neutral `semif_agent/simplex_ws.py`). `lxmf` pulls `rns` (Reticulum) and
# cryptography transitively; both are pinned so the resolver stays quiet.
websockets==15.0.1
lxmf==1.2.0
rns==1.5.7
+22
View File
@@ -0,0 +1,22 @@
# Voice-reply (text-to-speech) deps for the LXMF gateway (optional).
#
# When the LXMF gateway handles Sideband push-to-talk voice messages
# (`gateway.lxmf.voice.enabled`) and is configured to reply with voice
# (`gateway.lxmf.voice.reply_with_voice`, the default), it synthesizes the reply
# with Piper and encodes it to the Opus/OGG container Sideband's HQ push-to-talk
# uses (`LXMF.AM_OPUS_OGG`). That needs piper-tts (text-to-speech) and PyAV
# (libopus encoding) — NOT the hardware voice stack in `requirements/voice.txt`
# (no microphone, wake word, or speaker) and NOT transcription
# (`requirements/transcribe.txt`, which already pulls PyAV for decoding).
# Lazy-imported by semif_agent/voice_transport.py, so the core stays stdlib-only;
# a missing stack makes the reply fall back to text, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/tts.txt
piper-tts==1.8.0
onnxruntime==1.30.0
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open() (see requirements/transcribe.txt); pin below 19 here
# too so the shared PyAV is the one both paths expect.
av<19
+4
View File
@@ -26,6 +26,10 @@
sounddevice==0.5.6 sounddevice==0.5.6
onnxruntime==1.30.0 onnxruntime==1.30.0
faster-whisper==1.2.1 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 piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1 webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps). # openwakeword runtime deps (installed here because openwakeword is --no-deps).
+640 -210
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Print the merged config.json as JSON, following its `include` list.
Stdlib-only on purpose: bootstrap.sh reads per-machine values from the config
before the venv exists, so it cannot import `semif_agent.config`. This is the
same include/deep-merge semantics (`semif_agent/config.py`), reduced to the
minimum bootstrap needs (secrets are not resolved — bootstrap only reads
non-secret values like ports and endpoints).
Usage: python3 scripts/config_merge.py [config.json]
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
def _deep_merge(base: dict, extra: dict) -> dict:
for key, value in extra.items():
if isinstance(value, dict) and isinstance(base.get(key), dict):
_deep_merge(base[key], value)
else:
base[key] = value
return base
def merge(path: Path, seen: set[Path] | None = None) -> dict:
seen = seen if seen is not None else set()
resolved = path.resolve()
if resolved in seen:
raise SystemExit(f"config include cycle at {path}")
seen.add(resolved)
data = json.loads(path.read_text())
includes = data.pop("include", None)
merged: dict = {}
if includes:
for entry in includes:
inc = Path(entry)
if not inc.is_absolute():
inc = path.parent / inc
_deep_merge(merged, merge(inc, seen))
return _deep_merge(merged, data)
if __name__ == "__main__":
source = Path(sys.argv[1] if len(sys.argv) > 1 else "config.json")
print(json.dumps(merge(source)))
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env python3
"""Authorize the Outlook bridge with Microsoft (OAuth2 device code flow).
The bridge reads the user's Microsoft account through Microsoft Graph; that
needs an access token, obtained once here with the **device code flow** (a public
client, no secret):
1. register an Entra ID app (see below) and put its client id in
`config.json` under `bridges.outlook.client_id`;
2. run this script;
3. open the printed URL on any device, enter the printed code, and sign in;
4. the resulting tokens are saved (0600) to `.runtime/outlook/token.json`,
which the bridge loads and refreshes automatically.
One-time app registration (Entra ID / Azure AD):
- "App registrations" -> "New registration".
- Supported account types: include personal Microsoft accounts if the user
has an @outlook.com/@hotmail.com account (e.g. "Accounts in any
organizational directory and personal Microsoft accounts").
- Authentication -> "Allow public client flows" = Yes (no redirect URI is
needed for device code).
- No API permissions need adding by hand: the script requests the delegated
scopes it needs and the user consents during sign-in.
Usage (from the checkout):
.runtime/venv/bin/python scripts/outlook-auth.py [--config config.json]
[--client-id ID]
[--tenant common]
[--token-path PATH]
"""
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.bridges.outlook_client import ( # noqa: E402
DEFAULT_TENANT,
OutlookError,
run_device_code_flow,
save_token,
)
DEFAULT_TOKEN_PATH = str(REPO_ROOT / ".runtime" / "outlook" / "token.json")
def _block(config_path: str) -> dict:
try:
with open(config_path, encoding="utf-8") as handle:
config = json.load(handle)
except (OSError, ValueError):
return {}
block = (config.get("bridges", {}) or {}).get("outlook", {}) or {}
return block if isinstance(block, dict) else {}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default="config.json")
parser.add_argument("--client-id", default=None, help="override bridges.outlook.client_id")
parser.add_argument("--tenant", default=None, help="override bridges.outlook.tenant (default common)")
parser.add_argument("--token-path", default=None, help="where to save the tokens")
args = parser.parse_args(argv)
block = _block(args.config)
client_id = str(args.client_id or block.get("client_id") or "").strip()
tenant = str(args.tenant or block.get("tenant") or DEFAULT_TENANT).strip() or DEFAULT_TENANT
token_path = str(args.token_path or block.get("token_path") or DEFAULT_TOKEN_PATH)
scopes = block.get("scopes") or None
if not client_id:
print(
"no Microsoft client id configured: set bridges.outlook.client_id in "
f"{args.config} (or pass --client-id)",
file=sys.stderr,
)
return 1
try:
token = run_device_code_flow(client_id, tenant, scopes)
except OutlookError as exc:
print(f"authorization failed: {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("\ncancelled", file=sys.stderr)
return 1
save_token(token_path, token)
print(f"saved Outlook authorization to {token_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-172
View File
@@ -1,172 +0,0 @@
#!/usr/bin/env python3
"""Prime Playwright's browser cache over IPv4 (a fallback for `playwright install`).
`playwright install` downloads through Playwright's own Node fetcher, which
forces `autoSelectFamily` with a custom dual-stack resolver that prefers IPv6.
On a host that has an IPv6 address (often a ULA) but no working global IPv6
route, that first IPv6 connection hangs instead of falling back to IPv4, so the
download stalls until the socket timeout and `playwright install` fails even
though the CDN is reachable over IPv4.
This helper downloads the exact pinned artifacts Playwright expects, forcing
IPv4, and lays them out under `PLAYWRIGHT_BROWSERS_PATH` with the
`INSTALLATION_COMPLETE` marker Playwright checks, so the normal install (and the
browser bridge) then works. It reads revisions/versions from the installed
Playwright's own `browsers.json`, so it tracks version bumps automatically.
Idempotent: an artifact with its marker present is skipped. Only Chromium (plus
its headless shell and ffmpeg) is handled; Firefox/WebKit have no such helper.
Usage:
scripts/playwright-browsers.py --browsers-path .runtime/browser
scripts/playwright-browsers.py --browsers-path .runtime/browser --engine chromium
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import stat
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
from pathlib import Path
#: The CDN mirror Playwright's fetcher falls back to and that serves the exact
#: Chrome-for-Testing layout over a redirect (IPv4 works).
CDN = "https://cdn.playwright.dev"
#: Executables that must stay executable after a pure-Python unzip (which does
#: not preserve permissions). Relative to each browser's directory.
_EXECUTABLES = {
"chromium": ("chrome-linux64/chrome",),
"chromium_headless_shell": ("chrome-headless-shell-linux64/chrome-headless-shell",),
"ffmpeg": ("ffmpeg-linux",),
}
def _arch_suffix() -> str:
machine = platform.machine().lower()
return "arm64" if machine in ("aarch64", "arm64") else "x64"
def _cft_paths(arch: str) -> dict[str, str]:
if arch == "arm64":
return {
"chromium": "linux-arm64/chrome-linux-arm64.zip",
"chromium_headless_shell": "linux-arm64/chrome-headless-shell-linux-arm64.zip",
"ffmpeg": "ffmpeg-linux-arm64.zip",
}
return {
"chromium": "linux64/chrome-linux64.zip",
"chromium_headless_shell": "linux64/chrome-headless-shell-linux64.zip",
"ffmpeg": "ffmpeg-linux.zip",
}
def _browsers_json() -> dict:
import playwright # the package the venv already has
path = Path(playwright.__file__).resolve().parent / "driver" / "package" / "browsers.json"
with open(path) as handle:
return json.load(handle)
def _artifacts(browsers_json: dict, arch: str) -> list[tuple[str, str]]:
"""List of `(directory_name, download_path)` Playwright expects."""
suffixes = _cft_paths(arch)
wanted = {
"chromium": ("chromium", "chromium"),
"chromium-headless-shell": ("chromium_headless_shell", "chromium_headless_shell"),
"ffmpeg": ("ffmpeg", "ffmpeg"),
}
out: list[tuple[str, str]] = []
for browser in browsers_json.get("browsers", []):
name = browser.get("name")
if name not in wanted or not browser.get("installByDefault", True):
continue
slug, key = wanted[name]
revision = browser["revision"]
if key == "ffmpeg":
path = f"builds/ffmpeg/{revision}/{suffixes['ffmpeg']}"
else:
path = f"builds/cft/{browser['browserVersion']}/{suffixes[key]}"
out.append((f"{slug}-{revision}", path))
return out
def _download(url: str, dest: str) -> None:
if shutil.which("curl"):
subprocess.run(
["curl", "-4", "-fL", "--retry", "3", "-m", "600", "-o", dest, url],
check=True,
)
return
# No curl: urllib may pick IPv6 on a broken host, but it is the best we have.
print(f" (curl not found; using urllib for {url})", flush=True)
request = urllib.request.Request(url, headers={"User-Agent": "semif-bootstrap"})
with urllib.request.urlopen(request, timeout=600) as response, open(dest, "wb") as handle:
shutil.copyfileobj(response, handle)
def _extract(archive: str, target: Path, directory_name: str) -> None:
if shutil.which("unzip"):
subprocess.run(["unzip", "-q", "-o", archive, "-d", str(target)], check=True)
else:
with zipfile.ZipFile(archive) as zf:
zf.extractall(target)
for relative in _EXECUTABLES.get(directory_name.split("-")[0], ()):
candidate = target / relative
if candidate.is_file():
candidate.chmod(candidate.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
def _install_one(browsers_path: Path, directory_name: str, download_path: str) -> bool:
target = browsers_path / directory_name
marker = target / "INSTALLATION_COMPLETE"
if marker.is_file():
print(f" = {directory_name} already installed")
return True
url = f"{CDN}/{download_path}"
print(f" + {directory_name} <- {url}")
target.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="semif-browser-") as tmp:
archive = os.path.join(tmp, "download.zip")
_download(url, archive)
_extract(archive, target, directory_name)
marker.write_text("")
return True
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Prime Playwright's browser cache over IPv4.")
parser.add_argument("--browsers-path", required=True, help="PLAYWRIGHT_BROWSERS_PATH to populate")
parser.add_argument("--engine", default="chromium", help="only 'chromium' is supported by this helper")
args = parser.parse_args(argv)
if args.engine != "chromium":
print(f"helper only primes chromium, not {args.engine!r}; nothing to do", file=sys.stderr)
return 0
browsers_path = Path(args.browsers_path).expanduser().resolve()
browsers_path.mkdir(parents=True, exist_ok=True)
arch = _arch_suffix()
artifacts = _artifacts(_browsers_json(), arch)
if not artifacts:
print("no chromium artifacts found in playwright's browsers.json", file=sys.stderr)
return 1
print(f"priming Playwright browsers into {browsers_path} ({arch}, IPv4)")
for directory_name, download_path in artifacts:
_install_one(browsers_path, directory_name, download_path)
print("done; 'playwright install chromium' should now be a no-op")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env python3
"""Print (creating if needed) the SimpleX bot's contact address.
The gateway talks to a local `simplex-chat` daemon running as a bot
(`--create-bot-display-name`, see simplex_chat in config.json). To connect a
phone/client to the bot you need the bot's *user* contact address, not a chat
relay address; this queries the daemon's WebSocket API, creating the address on
first run, and prints the short link (and full link). Requires the daemon to be
running.
Usage:
.runtime/venv/bin/python scripts/simplex-address.py [--config config.json]
[--ws-url ws://...]
[--user-id 1]
"""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
def _ws_url(config_path: str) -> str:
try:
with open(config_path) as fh:
cfg = json.load(fh)
except (OSError, ValueError):
return "ws://127.0.0.1:5226"
return str(cfg.get("gateway", {}).get("simplex", {}).get("ws_url") or "ws://127.0.0.1:5226")
async def _resolve(ws_url: str, user_id: int) -> dict:
try:
import websockets
except ImportError:
raise SystemExit("the `websockets` package is required (pip install websockets)")
async with websockets.connect(ws_url, max_size=None) as ws:
async def cmd(command: str) -> dict:
await ws.send(json.dumps({"corrId": "addr", "cmd": command}))
raw = await asyncio.wait_for(ws.recv(), timeout=20)
return json.loads(raw).get("resp", {}) or {}
resp = await cmd(f"/_show_address {user_id}")
if resp.get("type") == "userContactLink":
return resp.get("contactLink", {}) or {}
# No address yet -> create one (APICreateMyAddress).
resp = await cmd(f"/_address {user_id}")
if resp.get("type") == "userContactLinkCreated":
return {"connLinkContact": resp.get("connLinkContact", {}) or {}}
raise SystemExit(f"could not read or create address: {json.dumps(resp)[:300]}")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--config", default="config.json")
ap.add_argument("--ws-url", default=None)
ap.add_argument("--user-id", type=int, default=1)
args = ap.parse_args()
ws_url = args.ws_url or _ws_url(args.config)
try:
link = asyncio.run(_resolve(ws_url, args.user_id))
except OSError as exc:
print(f"cannot reach simplex-chat at {ws_url}: {exc}", file=sys.stderr)
return 1
except asyncio.TimeoutError:
print(f"simplex-chat at {ws_url} did not answer", file=sys.stderr)
return 1
conn = link.get("connLinkContact", {}) or link
short = conn.get("connShortLink")
full = conn.get("connFullLink")
if short:
print(short)
if full:
print(full)
if not (short or full):
print("no contact address found", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+1 -1
View File
@@ -11,7 +11,7 @@ Environment=PYTHONUNBUFFERED=1
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the # 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. # voice mic loop) leaves a trace in the journal instead of hanging silently.
Environment=PYTHONFAULTHANDLER=1 Environment=PYTHONFAULTHANDLER=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform @PLATFORMS@
Restart=always Restart=always
RestartSec=5 RestartSec=5
StandardOutput=journal StandardOutput=journal
+1 -1
View File
@@ -26,7 +26,7 @@ a host with the pinned engine:
.runtime/venv/bin/python scripts/tune_navigation.py .runtime/venv/bin/python scripts/tune_navigation.py
.runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6 .runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6
The tree is whatever the host currently has loaded (committed seeds + the runtime The tree is whatever the host currently has loaded (shipped packs + the runtime
`data/skills/`), so an expectation naming a skill that is not present is `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; 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 self-labeled decision rows are not evidence. Nothing is written to the runtime
-4
View File
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Open a web page in the browser bridge and report its title and readable text."
}
-121
View File
@@ -1,121 +0,0 @@
"""Open a web page in the browser bridge and report what is on it.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. It opens the
URL from the request, then reads the page's text through the bridge. The URL is
taken from the request, or asked for if the request does not contain one. A
missing URL or a bridge failure is reported honestly — never a fabricated page.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
EXCERPT_CHARS = 1200
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _headers(ctx):
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
return headers
def _base(ctx):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
return base
def _request(ctx, path, payload=None, params=None):
url = _base(ctx) + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = _headers(ctx)
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
"""The URL to open, or None. Uses the answer after a needs_input pause."""
if request.user_input is not None:
answer = (request.user_input or "").strip()
if not answer:
return None
match = _URL_RE.search(answer)
return match.group(0) if match else answer
match = _URL_RE.search(request.text or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
if not url:
return ActionResult(
action_log="no web address in the request",
new_state=request.text,
needs_input="Which web address (URL) should I open?",
)
if not url.lower().startswith(("http://", "https://")):
url = "https://" + url
try:
opened = _request(ctx, "/goto", {"url": url})
page = _request(ctx, "/content", params={"format": "text", "max_chars": EXCERPT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = opened.get("title") or page.get("title") or url
final_url = page.get("url") or opened.get("url") or url
status = opened.get("status")
body = (page.get("content") or "").strip()
excerpt = body[:EXCERPT_CHARS]
if len(body) > EXCERPT_CHARS or page.get("truncated"):
excerpt = excerpt.rstrip() + " …"
summary = f"Opened {title} ({final_url})"
if status is not None:
summary += f" [HTTP {status}]"
if excerpt:
report = f"{summary}:\n{excerpt}"
else:
report = f"{summary}: the page has no readable text."
return ActionResult(action_log=report, new_state=report)
-147
View File
@@ -1,147 +0,0 @@
"""Hermetic mechanics test for browser.open_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body asks the bridge to open a URL and reports the page (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.open_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
title = "Example Domain"
body = "This domain is for use in illustrative examples."
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": self.title, "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/content"):
self._send(
{
"url": "https://example.com/",
"title": self.title,
"format": "text",
"content": self.body,
"truncated": False,
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type(
"Handler",
(BridgeHandler,),
{"status": status, "requests": []},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="open https://example.com"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_the_page():
server, handler, url = start_server()
try:
action = run(url)
assert "Example Domain" in action.action_log, action.action_log
assert "illustrative examples" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "POST" and path == "/goto" for method, path, _ in handler.requests)
assert any(method == "GET" and path.startswith("/content") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_url_asks_for_one():
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": "http://127.0.0.1:1"})
action = skill.act(ctx, Request("open a web page"))
assert action.needs_input, "a request with no URL must ask for one"
print(action.needs_input)
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "open https://example.com", "a failed open must not fake a page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert "browser.open_page" not in action.action_log, action.action_log
assert action.new_state == "open https://example.com"
print(action.action_log)
def main():
test_reports_the_page()
test_missing_url_asks_for_one()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Read the readable text of a web page (a URL in the request, or the page the browser is already on) through the browser bridge."
}
-93
View File
@@ -1,93 +0,0 @@
"""Read the readable text of a web page through the browser bridge.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. If the
request names a URL it opens that page first, otherwise it reads the page the
browser is already on. A bridge failure is reported honestly — never invented
page text.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
TEXT_CHARS = 4000
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _request(ctx, path, payload=None, params=None):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
source = request.user_input if request.user_input is not None else request.text
match = _URL_RE.search(source or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
try:
if url:
_request(ctx, "/goto", {"url": url})
page = _request(ctx, "/content", params={"format": "text", "max_chars": TEXT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = page.get("title") or ""
final_url = page.get("url") or url or "the current page"
text = (page.get("content") or "").strip()
if not text:
report = f"{title or final_url} ({final_url}) has no readable text."
return ActionResult(action_log=report, new_state=report)
if len(text) > TEXT_CHARS or page.get("truncated"):
text = text[:TEXT_CHARS].rstrip() + " …"
heading = f"{title} ({final_url})" if title else str(final_url)
report = f"{heading}:\n{text}"
return ActionResult(action_log=report, new_state=report)
-138
View File
@@ -1,138 +0,0 @@
"""Hermetic mechanics test for browser.read_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body reads the page through the bridge (navigating first only when the
request names a URL) and fails honestly when the bridge is unavailable. It does
NOT prove the live integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.read_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
body = "First line.\nSecond line."
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": "Example", "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/content"):
self._send(
{
"url": "https://example.com/",
"title": "Example",
"format": "text",
"content": self.body,
"truncated": False,
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="read the current page"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reads_the_current_page_without_navigating():
server, handler, url = start_server()
try:
action = run(url)
assert "First line." in action.action_log, action.action_log
assert "Second line." in action.action_log, action.action_log
assert action.new_state == action.action_log
assert not any(path == "/goto" for _method, path, _ in handler.requests), "no URL means no navigation"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_navigates_when_the_request_names_a_url():
server, handler, url = start_server()
try:
action = run(url, "read https://example.com/")
assert "Example" in action.action_log, action.action_log
assert any(method == "POST" and path == "/goto" for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "read the current page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reads_the_current_page_without_navigating()
test_navigates_when_the_request_names_a_url()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Take a screenshot of a web page (a URL in the request, or the page the browser is already on) through the browser bridge and report the saved file."
}
-90
View File
@@ -1,90 +0,0 @@
"""Take a screenshot of a web page through the browser bridge.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. If the
request names a URL it opens that page first, otherwise it captures the page the
browser is already on, and reports the real path of the saved PNG. A bridge
failure is reported honestly — never a fabricated path.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _request(ctx, path, payload=None, params=None):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
source = request.user_input if request.user_input is not None else request.text
match = _URL_RE.search(source or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
try:
if url:
_request(ctx, "/goto", {"url": url})
shot = _request(ctx, "/screenshot", params={"full_page": "true"})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
path = shot.get("path") or ""
title = shot.get("title") or ""
page_url = shot.get("url") or url or "the current page"
size = shot.get("bytes")
where = f"{title} ({page_url})" if title else str(page_url)
detail = f"Saved a screenshot of {where} to {path}"
if isinstance(size, int):
detail += f" ({size} bytes)"
return ActionResult(action_log=detail, new_state=detail)
-125
View File
@@ -1,125 +0,0 @@
"""Hermetic mechanics test for browser.screenshot.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/screenshot` routes.
This proves the body captures the page through the bridge and reports the saved
path (and fails honestly when the bridge is unavailable). It does NOT prove the
live integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.screenshot must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
path_saved = "/home/user/.runtime/browser/screenshots/shot.png"
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": "Example", "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/screenshot"):
self._send(
{
"ok": True,
"path": self.path_saved,
"bytes": 12345,
"url": "https://example.com/",
"title": "Example",
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="take a screenshot of https://example.com/"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_the_saved_screenshot():
server, handler, url = start_server()
try:
action = run(url)
assert BridgeHandler.path_saved in action.action_log, action.action_log
assert "12345 bytes" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "GET" and path.startswith("/screenshot") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "take a screenshot of https://example.com/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_the_saved_screenshot()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Evaluate a simple arithmetic request (two operands, one operator) and say the answer, e.g. \"what is 15% of 80?\", \"3/4\", or \"square root of 144\"."
}
-460
View File
@@ -1,460 +0,0 @@
"""Evaluate a simple arithmetic request and say the answer out loud.
Real local compute: the `compute` transport is the codebase's home for a body
that acts on the machine itself, and arithmetic is exactly that — no external
service, no configuration. The body is deliberately bounded to **two operands
and one operator**.
The decision engine (SemIf) resolves the *operator* from the request text with a
single choice over the supported operations: addition, subtraction,
multiplication, division, exponents, squares, cubes, square roots, cube roots,
fractions, and percentages. The operands are the numbers written in the request;
when the request offers more numbers than the operation consumes, SemIf chooses
which numbers are the operands (one choice per operand slot). When too few
numbers are present the body pauses and asks for them, stashing the answer in
`request.meta` so the single-phase `act` re-run does not ask twice.
The result is phrased for the ear: every number is spelled out in words and an
inexact result is announced as "approximately ...". Square, cube, square-root
and cube-root requests are unary in plain language but are still "one operator,
two operands" underneath (the base and an implied 2, 3, 1/2 or 1/3).
"""
from __future__ import annotations
import math
import re
from collections import namedtuple
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "local_calculator", "transport": "compute", "config_vars": []}
CONTRACT = {}
# operator id -> (option description for SemIf, number of operands it consumes)
OPERATIONS: dict[str, tuple[str, int]] = {
"add": (
"Add two numbers together, stated as 'plus', 'added to', 'the sum of', or '+'.",
2,
),
"subtract": (
"Subtract one number from another, stated as 'minus', 'less', 'take away', or '-'.",
2,
),
"multiply": (
"Multiply two numbers, stated as 'times', 'multiplied by', or 'the product of'.",
2,
),
"divide": (
"Divide one number by another, stated as 'divided by' or with a division sign.",
2,
),
"exponent": (
"Raise a base to a power, stated as 'to the power of' or with a caret '^'.",
2,
),
"square": ("Square a single number, stated as 'squared'.", 1),
"cube": ("Cube a single number, stated as 'cubed'.", 1),
"square_root": ("The square root of a single number, stated as 'square root of'.", 1),
"cube_root": ("The cube root of a single number, stated as 'cube root of'.", 1),
"fraction": (
"The value of a plain fraction written with a slash, such as 3/4, when the "
"request does not say 'divided by'.",
2,
),
"percent": (
"Take a percentage of a number, stated as 'X% of Y' or 'X percent of Y'.",
2,
),
}
_ASKS = {
"add": "What two numbers should I add? (e.g. '3 and 4')",
"subtract": "What two numbers should I subtract? (e.g. '9 minus 4')",
"multiply": "What two numbers should I multiply? (e.g. '6 and 7')",
"divide": "What should I divide, and by what? (e.g. '10 divided by 4')",
"exponent": "What base and what power? (e.g. '2 to the power of 10')",
"square": "What number should I square?",
"cube": "What number should I cube?",
"square_root": "What number should I take the square root of?",
"cube_root": "What number should I take the cube root of?",
"fraction": "What fraction should I evaluate? (e.g. '3/4')",
"percent": "What percentage of what number? (e.g. '20% of 50')",
}
# ---- spoken number words ----
_UNITS = {
"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,
}
_TENS = {
"twenty": 20,
"thirty": 30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
}
_SCALES = {
"hundred": 100,
"thousand": 1000,
"million": 1000000,
"billion": 1000000000,
"trillion": 1000000000000,
}
_UNITS_WORD = {value: word for word, value in _UNITS.items()}
_TENS_WORD = {value: word for word, value in _TENS.items()}
_SCALE_WORDS = [
(1000000000000, "trillion"),
(1000000000, "billion"),
(1000000, "million"),
(1000, "thousand"),
]
_NUMBER_WORDS = set(_UNITS) | set(_TENS) | set(_SCALES)
_WORD_TOKEN = re.compile(
r"\b(?:"
+ "|".join(
re.escape(word)
for word in sorted(_NUMBER_WORDS | {"and", "negative"}, key=len, reverse=True)
)
+ r")\b",
re.I,
)
_DIGIT = re.compile(r"(?P<sign>negative\s+)?(?P<num>\d+(?:\.\d+)?|\.\d+)", re.I)
def _int_to_words(number: int) -> str:
if number < 0:
return "negative " + _int_to_words(-number)
if number < 20:
return _UNITS_WORD[number]
if number < 100:
tens, ones = divmod(number, 10)
word = _TENS_WORD[tens * 10]
return f"{word}-{_UNITS_WORD[ones]}" if ones else word
if number < 1000:
hundreds, rest = divmod(number, 100)
word = f"{_UNITS_WORD[hundreds]} hundred"
return f"{word} {_int_to_words(rest)}" if rest else word
for scale, name in _SCALE_WORDS:
if number >= scale:
leading, rest = divmod(number, scale)
word = f"{_int_to_words(leading)} {name}"
return f"{word} {_int_to_words(rest)}" if rest else word
return str(number)
def _speak_number(value: float) -> str:
"""A number as English words, so a spoken reply is unambiguous."""
value = float(value)
if not math.isfinite(value):
return "an undefined value"
if value < 0:
return "negative " + _speak_number(-value)
if abs(value - round(value)) < 1e-9:
return _int_to_words(int(round(value)))
if value >= 1e15:
return f"{value:.6g}"
whole = int(value)
fraction_digits = f"{value:.10f}".split(".", 1)[1].rstrip("0")
words = _int_to_words(whole) if whole else "zero"
if fraction_digits:
return f"{words} point " + " ".join(_UNITS_WORD[int(d)] for d in fraction_digits)
return words
# ---- request parsing ----
_Candidate = namedtuple("_Candidate", "value phrase start end")
def _normalize_leading_sign(text: str) -> str:
"""Turn a leading '-5' into 'negative 5' so a sign at the start of the
request is not confused with a spaced-out subtraction."""
return re.sub(r"^\s*[-\u2212]\s*(?=\d)", "negative ", text, count=1)
def _parse_word_number(words: list[str]) -> float | None:
total = 0
current = 0
negative = False
seen = False
for word in words:
if word == "negative":
negative = True
elif word == "and":
continue
elif word in _UNITS:
current += _UNITS[word]
seen = True
elif word in _TENS:
current += _TENS[word]
seen = True
elif word in _SCALES:
scale = _SCALES[word]
if scale == 100:
current = (current or 1) * 100
else:
total += (current or 1) * scale
current = 0
seen = True
else:
return None
if not seen:
return None
value = total + current
return float(-value if negative else value)
def _digit_candidates(text: str) -> list[_Candidate]:
candidates = []
for match in _DIGIT.finditer(text):
value = float(match.group("num"))
if match.group("sign"):
value = -value
candidates.append(
_Candidate(value, match.group(0).strip(), match.start(), match.end())
)
return candidates
def _word_candidates(text: str) -> list[_Candidate]:
matches = list(_WORD_TOKEN.finditer(text))
groups: list[list] = []
current: list = []
for match in matches:
if current:
gap = text[current[-1].end() : match.start()]
if not re.fullmatch(r"[\s\-]*", gap):
groups.append(current)
current = []
current.append(match)
if current:
groups.append(current)
candidates = []
for group in groups:
value = _parse_word_number([match.group(0).lower() for match in group])
if value is None:
continue
start, end = group[0].start(), group[-1].end()
candidates.append(_Candidate(value, text[start:end], start, end))
return candidates
def _find_candidates(text: str) -> list[_Candidate]:
"""Every number written in the request, in the order it appears."""
text = _normalize_leading_sign(text or "")
candidates = _digit_candidates(text) + _word_candidates(text)
candidates.sort(key=lambda candidate: (candidate.start, candidate.end))
ordered: list[_Candidate] = []
last_end = -1
for candidate in candidates:
if candidate.start >= last_end:
ordered.append(candidate)
last_end = candidate.end
return ordered
# ---- SemIf decisions ----
def _decide_operator(ctx, text: str, decisions: list) -> str:
decision = DecisionRequest(
state=text,
question="Which arithmetic operation does the user's request ask for?",
options=[
Option(name, description) for name, (description, _count) in OPERATIONS.items()
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
return result.selected
def _select_operands(ctx, text, candidates, needed, decisions):
"""The operand values the operation consumes.
When the request writes exactly the numbers the operation needs they are
read in order; when it writes more, SemIf chooses which numbers are the
operands, one choice per operand slot.
"""
if len(candidates) == needed:
return [candidate.value for candidate in candidates]
pool = list(candidates)
chosen = []
for slot in range(needed):
if slot == 0:
question = (
"Which of these numbers is the first number to use in the calculation?"
)
else:
question = (
"Which of these numbers is the second number to use in the calculation?"
)
decision = DecisionRequest(
state=text,
question=question,
options=[
Option(
str(index),
f"{candidate.phrase} (equal to {_speak_number(candidate.value)})",
)
for index, candidate in enumerate(pool)
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
try:
selected = int(result.selected)
except (TypeError, ValueError):
selected = 0
if not 0 <= selected < len(pool):
selected = 0
chosen.append(pool.pop(selected).value)
return chosen
# ---- arithmetic ----
class _CalcError(Exception):
"""The request cannot be computed (bad operand, undefined result)."""
def _compute(operator: str, operands: list[float]) -> float:
first = operands[0]
second = operands[1] if len(operands) > 1 else None
if operator == "square":
return first * first
if operator == "cube":
return first * first * first
if operator == "square_root":
if first < 0:
raise _CalcError("I can't take the square root of a negative number.")
return math.sqrt(first)
if operator == "cube_root":
return math.copysign(abs(first) ** (1.0 / 3.0), first)
if operator in ("divide", "fraction"):
if second == 0:
raise _CalcError("I can't divide by zero.")
return first / second
if operator == "percent":
return (first / 100.0) * second
if operator == "exponent":
try:
result = first ** second
except (OverflowError, ValueError):
raise _CalcError("That power is too large or is not a real number.")
if isinstance(result, complex):
raise _CalcError("That power is not a real number.")
return result
if operator == "add":
return first + second
if operator == "subtract":
return first - second
if operator == "multiply":
return first * second
raise _CalcError("I don't know how to compute that.")
def _round_for_speech(value: float) -> tuple[float, bool]:
"""The value to speak and whether it had to be rounded."""
value = float(value)
if not math.isfinite(value):
return value, True
if abs(value - round(value)) < 1e-9:
return float(round(value)), False
rounded = round(value, 4)
return rounded, abs(rounded - value) > 1e-9
def _report(operator: str, operands: list[float], value: float, approximate: bool) -> str:
first = _speak_number(operands[0])
second = _speak_number(operands[1]) if len(operands) > 1 else None
result = _speak_number(value)
prefix = "approximately " if approximate else ""
sentences = {
"add": f"{first} plus {second} is {prefix}{result}.",
"subtract": f"{first} minus {second} is {prefix}{result}.",
"multiply": f"{first} times {second} is {prefix}{result}.",
"divide": f"{first} divided by {second} is {prefix}{result}.",
"exponent": f"{first} to the power of {second} is {prefix}{result}.",
"square": f"{first} squared is {prefix}{result}.",
"cube": f"{first} cubed is {prefix}{result}.",
"square_root": f"The square root of {first} is {prefix}{result}.",
"cube_root": f"The cube root of {first} is {prefix}{result}.",
"fraction": f"The fraction {first} over {second} is {prefix}{result}.",
"percent": f"{first} percent of {second} is {prefix}{result}.",
}
message = sentences.get(operator, f"The answer is {prefix}{result}.")
return message[0].upper() + message[1:]
# ---- the skill phase ----
def act(ctx, request):
answers = request.meta.setdefault("calculator_answers", {})
awaiting = request.meta.get("calculator_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("calculator_awaiting", None)
text = request.text
decisions: list = []
operator = request.meta.get("calculator_operator")
if operator not in OPERATIONS:
operator = _decide_operator(ctx, text, decisions)
request.meta["calculator_operator"] = operator
needed = OPERATIONS[operator][1]
candidates = _find_candidates(text)
if answers.get("operands"):
candidates = candidates + _find_candidates(answers["operands"])
if len(candidates) < needed:
request.meta["calculator_awaiting"] = "operands"
return ActionResult(
action_log="waiting for the numbers to calculate",
new_state=request.text,
needs_input=_ASKS[operator],
decisions=decisions,
)
operands = _select_operands(ctx, text, candidates, needed, decisions)
try:
value = _compute(operator, operands)
except _CalcError as exc:
message = f"{exc}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
if not math.isfinite(value):
message = "That calculation does not have a finite answer."
return ActionResult(action_log=message, new_state=message, decisions=decisions)
rounded, approximate = _round_for_speech(value)
message = _report(operator, operands, rounded, approximate)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
-116
View File
@@ -1,116 +0,0 @@
"""Hermetic mechanics test for calculator.calculate.
Run from this folder: `python skill.test.py`. No external network and no
configuration — this body is pure local compute. A scripted `FakeEngine` stands
in for SemIf so the operator choice and the operand disambiguation are exercised
deterministically. This proves the body parses numbers (digits and words),
resolves one operator and up to two operands, spells the result out for the ear,
asks for missing numbers and resumes, and fails honestly on an undefined
calculation. It does NOT prove the live decision engine — only a real run does.
"""
import sys
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Picks the queued option id per call (default: the first option)."""
def __init__(self, picks=None):
self.picks = list(picks or [])
self.calls = []
def call(self, decision):
self.calls.append(decision)
option_ids = [option.id for option in decision.options]
chosen = self.picks.pop(0) if self.picks else option_ids[0]
if chosen not in option_ids:
chosen = option_ids[0]
return DecisionResult(
request=decision,
option_ids=option_ids,
probabilities=[1.0 if i == chosen else 0.0 for i in option_ids],
)
def run(text, picks=None):
engine = FakeEngine(picks)
ctx = ActionContext(engine=engine, config={})
request = Request(text)
action = skill.act(ctx, request)
return action, engine, request
def check(text, picks, expected):
action, engine, _ = run(text, picks)
assert action.action_log == expected, (text, action.action_log, expected)
assert action.needs_input is None, (text, action.needs_input)
return action, engine
def main():
# The operator is a SemIf choice; the answer is spoken in words.
check("what is 3 plus 4?", ["add"], "Three plus four is seven.")
check("9 minus 4", ["subtract"], "Nine minus four is five.")
check("6 times 7", ["multiply"], "Six times seven is forty-two.")
check("10 divided by 4", ["divide"], "Ten divided by four is two point five.")
check("2 to the power of 10", ["exponent"],
"Two to the power of ten is one thousand twenty-four.")
# Squares, cubes, roots, fractions, percentages.
check("7 squared", ["square"], "Seven squared is forty-nine.")
check("3 cubed", ["cube"], "Three cubed is twenty-seven.")
check("square root of 144", ["square_root"],
"The square root of one hundred forty-four is twelve.")
check("cube root of 27", ["cube_root"],
"The cube root of twenty-seven is three.")
check("3/4", ["fraction"],
"The fraction three over four is zero point seven five.")
check("20% of 50", ["percent"], "Twenty percent of fifty is ten.")
# An inexact result is announced as approximate.
check("square root of 2", ["square_root"],
"The square root of two is approximately one point four one four two.")
# Number words are read as operands too.
check("five plus five", ["add"], "Five plus five is ten.")
check("twenty one times two", ["multiply"],
"Twenty-one times two is forty-two.")
# A sign at the start of the request is part of the number.
check("-5 plus 3", ["add"], "Negative five plus three is negative two.")
# More numbers than the operation consumes: SemIf picks the operands.
_action, engine = check("add 1 2 3", ["add", "0", "0"], "One plus two is three.")
assert len(engine.calls) == 3, "operator + two operand choices expected"
# Undefined calculations are reported honestly, not fabricated.
action, _ = check("5 divided by 0", ["divide"], "I can't divide by zero.")
assert action.needs_input is None
# Too few numbers: ask once, then finish on the resume.
engine = FakeEngine(["add"])
ctx = ActionContext(engine=engine, config={})
request = Request("what is 3 plus?")
first = skill.act(ctx, request)
assert first.needs_input, "a missing operand should be asked for"
assert first.action_log == "waiting for the numbers to calculate"
request.user_input = "4"
second = skill.act(ctx, request)
assert second.action_log == "Three plus four is seven.", second.action_log
assert second.needs_input is None
print(second.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,8 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Create a calendar event from a request such as \"add Ashley's dance recital for 5pm Tuesday\"."
}
-628
View File
@@ -1,628 +0,0 @@
"""Create a calendar event on the user's Nextcloud calendar from a request.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` reads `request.text` and derives the event's per-request arguments. The
title and description are extracted by the local LLM bridge (`llm_bridge_url`,
`llm_bridge_token`) with one generic chat call, cached in `request.meta` so a
`needs_input` resume does not re-call it; the start date/time and duration are
parsed deterministically. Missing arguments are asked one at a time and the
answer is stashed in `request.meta`; because `act` is single-phase and re-runs
from the top after a `needs_input` pause, the body never re-asks a question it
already has an answer for. Calendars are discovered over PROPFIND and the target
is resolved by a single SemIf choice over every owned calendar (state = the user
query), asking which one the request refers to; a strong winner (probability >=
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is
used. The event is created with a real CalDAV PUT (iCalendar, UTC timestamps,
`If-None-Match: *`) and the real outcome is reported.
The date/time parse is deliberately bounded; the title/description come from the
model. When the model bridge is unavailable the body reports the real failure
rather than guessing.
"""
from __future__ import annotations
import base64
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
from datetime import datetime, time, timedelta, timezone
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are used.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
class BridgeError(Exception):
"""A real failure talking to the local LLM bridge."""
def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone`
config value when set, else host local. A test seam; never freezes time."""
return local_now(ctx.config)
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0", content_type="application/xml; charset=utf-8", extra_headers=None):
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
headers = {"Authorization": f"Basic {token}", "Depth": depth}
if body is not None:
headers["Content-Type"] = content_type
if extra_headers:
headers.update(extra_headers)
request = urllib.request.Request(
url + path, data=body, method=method, headers=headers
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.status, response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
_status, body = _request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")
calendars = []
for response in _multistatus(body).findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
# ---- LLM field extraction ----
def _extract_fields(ctx, request):
"""Ask the LLM bridge for the event title and description.
One generic `POST /chat` call to the local LLM bridge; the reply is the JSON
object the prompt asks for. Raises `BridgeError` when the bridge is
unreachable or the reply carries no usable object.
"""
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BridgeError("llm_bridge_url is not configured")
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
messages = [
{
"role": "system",
"content": (
"Extract the calendar event from the user's request. Reply with "
'ONLY a JSON object: {"title": "<short event title>", '
'"description": "<one short sentence, or empty>"}. The title must '
"not contain the date, the time, or words like add/schedule/create."
),
},
{"role": "user", "content": request.text},
]
payload = json.dumps({"messages": messages}).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(
base + "/chat", data=payload, method="POST", headers=headers
)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"llm bridge /chat: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"llm bridge /chat: {exc}") from exc
return _parse_fields(str(data.get("text") or ""))
def _parse_fields(text):
"""Pull the `{"title","description"}` object out of the model's reply."""
start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start:
raise BridgeError("llm bridge returned no JSON object")
try:
data = json.loads(text[start : end + 1])
except ValueError as exc:
raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc
if not isinstance(data, dict):
raise BridgeError("llm bridge returned JSON that is not an object")
return {
"title": str(data.get("title") or "").strip(),
"description": str(data.get("description") or "").strip(),
}
def _month_number(token):
return _MONTHS.get(token.lower()[:3])
def _resolve_month_day(month, day, year, now):
if not (month and 1 <= day <= 31):
return None
given_year = year is not None
year = year or now.year
try:
candidate = datetime(year, month, day).date()
except ValueError:
return None
if not given_year and candidate < now.date():
try:
candidate = datetime(year + 1, month, day).date()
except ValueError:
return None
return candidate
def _parse_when(text, now):
"""Best-effort extraction of date/time/duration from free text.
Returns a dict with `date` (datetime.date | None), `time` (datetime.time |
None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday`
(bool). The title and description come from the LLM bridge, so no matched
spans are tracked here.
"""
text = text or ""
result = {
"date": None,
"time": None,
"all_day": False,
"duration_minutes": None,
"from_weekday": False,
}
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match:
result["all_day"] = True
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match:
result["duration_minutes"] = int(match.group(1))
else:
for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30),
(r"\bfor\s+an?\s+hour\b", 60),
(r"\bfor\s+a\s+couple\s+of\s+hours\b", 120),
):
match = re.search(phrase, text, re.I)
if match:
result["duration_minutes"] = minutes
break
date = None
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
date = datetime(
int(match.group(1)), int(match.group(2)), int(match.group(3))
).date()
except ValueError:
date = None
if date is None:
match = re.search(
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now)
if date is None:
match = re.search(
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now)
if date is None:
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text)
if match:
first, second = int(match.group(1)), int(match.group(2))
month, day = (first, second) if first <= 12 else (second, first)
year = int(match.group(3)) if match.group(3) else None
if year is not None and year < 100:
year += 2000
date = _resolve_month_day(month, day, year, now)
if date is None:
match = re.search(
r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I
)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
date = now.date()
elif word in ("tomorrow", "tmrw", "tomorow"):
date = now.date() + timedelta(days=1)
else:
date = now.date() + timedelta(days=7)
if date is None:
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
prefix = text[max(0, match.start() - 6):match.start()]
if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7)
result["from_weekday"] = True
parsed_time = None
match = re.search(r"\bnoon\b", text, re.I)
if match:
parsed_time = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
else:
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed_time = time(int(match.group(1)), 0)
result["date"] = date
result["time"] = parsed_time
return result
# ---- calendar resolution ----
def _resolve_calendar(ctx, request, calendars, decisions):
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
default = None
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
default = calendar
break
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar ----
def _escape_ics(value):
return (
str(value)
.replace("\\", "\\\\")
.replace(";", "\\;")
.replace(",", "\\,")
.replace("\r\n", "\\n")
.replace("\n", "\\n")
.replace("\r", "\\n")
)
def _utc_stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//semif-agent//nextcloud.create_event//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{stamp}",
]
if all_day:
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
else:
lines.append(f"DTSTART:{_utc_stamp(start)}")
lines.append(f"DTEND:{_utc_stamp(end)}")
lines.append(f"SUMMARY:{_escape_ics(summary)}")
if description:
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
lines += ["END:VEVENT", "END:VCALENDAR", ""]
return "\r\n".join(lines).encode("utf-8")
# ---- skill phases ----
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(
action_log=f"waiting for {field}",
new_state=request.text,
needs_input=question,
)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
if answers.get(awaiting) != request.user_input.strip():
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
fields = request.meta.get("create_event_fields")
if fields is None:
try:
fields = _extract_fields(ctx, request)
except BridgeError as exc:
return ActionResult(
action_log=str(exc),
new_state=request.text,
)
request.meta["create_event_fields"] = fields
title = fields["title"]
description = fields["description"]
now = _now(ctx)
parsed = _parse_when(request.text, now)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
parsed["from_weekday"] = extra["from_weekday"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
local_tz = now.tzinfo or timezone.utc
all_day = bool(parsed["all_day"])
if all_day:
start_date = parsed["date"]
end_date = start_date + timedelta(days=1)
start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz)
end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz)
else:
start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz)
if start <= now and parsed.get("from_weekday"):
start += timedelta(days=7)
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
end = start + duration
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="no calendars found on the account",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
uid = f"{uuid.uuid4().hex}@semif-agent"
body = _build_ics(
uid, title, start, end, all_day, _utc_stamp(now), description=description
)
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try:
_request(
ctx,
"PUT",
path,
body=body,
depth="0",
content_type="text/calendar; charset=utf-8",
extra_headers={"If-None-Match": "*"},
)
except CalDavError as exc:
return ActionResult(
action_log=(
f"could not create {title!r} on "
f"{calendar!r}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if all_day:
when_text = f"{start_date.isoformat()} (all day)"
else:
when_text = (
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
f"{end.strftime('%H:%M %Z')}"
)
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
return ActionResult(
action_log=report,
new_state=report,
decisions=decisions,
)
-451
View File
@@ -1,451 +0,0 @@
"""Hermetic mechanics test for nextcloud.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
and description through the LLM bridge (caching the call across a `needs_input`
resume), parses the date/time from the request, asks for a missing field and
resumes, resolves the target calendar with a SemIf choice over the owned
calendars (a strong winner is used, otherwise the configured default), writes a
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
It does NOT prove the live integration — only a real run against the user's
Nextcloud does.
"""
import json
import sys
import threading
import urllib.parse
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
def next_weekday(now, weekday):
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
calendars = []
put_status = 201
requests = []
puts = []
llm_reply = DEFAULT_LLM_REPLY
llm_status = 200
llm_requests = []
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status, content_type):
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._read_body()
self.requests.append(("PROPFIND", self.path))
responses = []
for calendar in self.calendars:
responses.append(
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
f'{calendar["name"]}/</d:href>'
f"<d:propstat><d:prop>"
f'<d:displayname>{calendar["label"]}</d:displayname>'
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
f"</d:response>"
)
body = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
+ "".join(responses)
+ "</d:multistatus>"
)
self._send(body, 207, "application/xml; charset=utf-8")
def do_PUT(self):
body = self._read_body()
self.puts.append(
{"path": self.path, "body": body, "headers": dict(self.headers)}
)
self._send(b"", self.put_status, "text/plain")
def do_POST(self):
body = self._read_body()
if self.path != "/chat":
self._send(json.dumps({"error": "not found"}), 404, "application/json")
return
self.llm_requests.append(body)
if self.llm_status != 200:
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
return
self._send(
json.dumps({"text": json.dumps(self.llm_reply)}),
200,
"application/json",
)
def log_message(self, *args):
pass
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
handler = type(
"Handler",
(CalDavHandler,),
{
"calendars": calendars
if calendars is not None
else [
{"name": "personal", "label": "Personal"},
{"name": "work", "label": "Work"},
],
"put_status": put_status,
"requests": [],
"puts": [],
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
"llm_status": llm_status,
"llm_requests": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, default="personal", llm_url=None):
return {
"nextcloud_url": url,
"nextcloud_username": "alice",
"nextcloud_app_password": "secret",
"nextcloud_default_calendar": default,
"llm_bridge_url": url if llm_url is None else llm_url,
"llm_bridge_token": "",
}
def run(handler, url, text, default="personal", engine=None, llm_url=None):
engine = engine or FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
request = Request(text)
action = skill.act(ctx, request)
return action, request, engine
def test_example_creates_event_on_default_calendar():
server, handler, url = start_server(
llm_reply={
"title": "Ashley's dance recital",
"description": "Dance recital at 5pm.",
}
)
try:
# The query names no calendar, so the SemIf choice is a near-tie and the
# configured default ("personal") wins.
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
action, _request, engine = run(
handler,
url,
"add Ashley's dance recital to the calendar for 5pm Tuesday",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
assert engine.decisions[0].state == (
"add Ashley's dance recital to the calendar for 5pm Tuesday"
), engine.decisions[0]
assert "referred to in the user query" in engine.decisions[0].question
assert len(handler.puts) == 1, handler.puts
put = handler.puts[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
assert put["path"].endswith(".ics"), put
assert put["headers"].get("If-None-Match") == "*"
body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
assert "Ashley's dance recital" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(
handler, url, "add dentist appointment on 2026-11-10"
)
assert action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_day_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked"
assert "day" in action.needs_input.lower(), action.needs_input
request.user_input = "2026-11-10"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks():
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked"
assert "call the event" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
print(action.needs_input)
finally:
server.shutdown()
server.server_close()
def test_named_calendar_is_used():
server, handler, url = start_server(
llm_reply={"title": "team sync", "description": ""}
)
try:
engine = FakeEngine(pick="work")
action, _request, engine = run(
handler,
url,
"add team sync to my work calendar on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:team sync" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# Work edges out personal but stays below the strong-winner threshold, so
# the configured default ("personal") is used instead.
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/personal/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unknown_default_uses_semif_decision():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# The configured default is not among the account's calendars and the
# SemIf winner is weak: the winner is used anyway (never blocks).
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
default="missing",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert action.decisions and len(action.decisions) == 1, action.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try:
action, _request, _engine = run(
handler, url, "add conference all day on 2026-11-10"
)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART;VALUE=DATE:20261110" in body, body
assert "DTEND;VALUE=DATE:20261111" in body, body
assert "SUMMARY:conference" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server()
try:
action, request, _engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
llm_url="http://127.0.0.1:1",
)
assert "llm bridge" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed extraction must not fake a result"
assert handler.puts == [], "no event is created when the LLM bridge is down"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_error_status_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "HTTP 502" in action.action_log, action.action_log
assert action.new_state == request.text
assert handler.puts == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_server_error_is_reported_honestly():
server, handler, url = start_server(
put_status=500, llm_reply={"title": "standup", "description": ""}
)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "500" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_server_fails_honestly():
action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
)
assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
def main():
test_example_creates_event_on_default_calendar()
test_missing_time_asks_then_creates()
test_missing_day_asks_then_creates()
test_missing_title_asks()
test_named_calendar_is_used()
test_weak_winner_falls_back_to_default()
test_unknown_default_uses_semif_decision()
test_all_day_event()
test_llm_bridge_failure_is_reported_honestly()
test_llm_bridge_error_status_is_reported_honestly()
test_server_error_is_reported_honestly()
test_unreachable_server_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,6 +0,0 @@
{
"nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list task lists and create the task.",
"nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to phrase the task title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Add a single task to a Nextcloud task list from a request such as \"add a task to eat more hot dogs\"."
}
-204
View File
@@ -1,204 +0,0 @@
"""Add a single task to a Nextcloud task list.
Real integration: the Nextcloud bridge over HTTP, which fronts the user's
Nextcloud (CalDAV VTODO). The bridge URL/token and the LLM bridge URL/token are
operational values supplied through `ctx.config` (declared in CONTRACT); the task
summary and description are derived from `request.text`.
`GET /tasklists` returns only VTODO-capable task lists (the bridge excludes
event-only calendars and Nextcloud Deck boards), so a task can never be written
to a collection that rejects it. When the account has several task lists the
target is resolved by a single SemIf choice over them; otherwise the sole list is
used. The task is created for real with `POST /tasks` and the real outcome is
reported — a failure is never dressed up as success.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "nextcloud",
"transport": "http",
"config_vars": [
"nextcloud_bridge_url",
"nextcloud_bridge_token",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list task lists and create the task.",
"nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to phrase the task title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
def _headers(token):
"""Build request headers, sending the bridge token only when one is set."""
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
return headers
def _call(method, url, headers, payload=None, timeout=25):
"""Perform one HTTP call, returning (status, decoded_json_or_error_dict)."""
data = json.dumps(payload).encode("utf-8") if payload is not None else None
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
body = response.read().decode("utf-8")
return response.status, (json.loads(body) if body else {})
except urllib.error.HTTPError as exc:
try:
detail = json.loads(exc.read().decode("utf-8"))
except Exception:
detail = {"error": str(exc)}
return exc.code, detail
except (urllib.error.URLError, ValueError) as exc:
return None, {"error": str(exc)}
def _parse_json_object(text):
"""Pull the first JSON object out of a model reply, or return None."""
if not text:
return None
start = text.find("{")
end = text.rfind("}")
if start == -1 or end <= start:
return None
try:
data = json.loads(text[start : end + 1])
except ValueError:
return None
return data if isinstance(data, dict) else None
def _extract_task(ctx, request):
"""Ask the LLM bridge for (summary, description) of the task; else an error."""
llm_url = str(ctx.config.get("llm_bridge_url", "") or "").rstrip("/")
headers = _headers(ctx.config.get("llm_bridge_token", ""))
messages = [
{
"role": "system",
"content": (
"You turn a user's request into a single to-do task. Reply with "
'only a JSON object: {"summary": "<short task title>", '
'"description": "<extra detail, or an empty string>"}.'
),
},
{"role": "user", "content": request.text or ""},
]
status, payload = _call(
"POST",
f"{llm_url}/chat",
headers,
{"messages": messages, "max_tokens": 200},
)
if status != 200:
return (
None,
None,
f"could not phrase the task via the LLM bridge at {llm_url}: "
f"status {status}, {payload.get('error', payload)}",
)
data = _parse_json_object(payload.get("text") or "")
if not data or not str(data.get("summary") or "").strip():
return (
None,
None,
f"LLM bridge at {llm_url} returned no usable task text: "
f"{payload.get('text')!r}",
)
return (
str(data["summary"]).strip(),
str(data.get("description") or "").strip(),
None,
)
def act(ctx, request) -> ActionResult:
"""Add one task to the chosen Nextcloud task list and report the result."""
decisions = []
base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/")
nc_headers = _headers(ctx.config.get("nextcloud_bridge_token", ""))
# 1. Phrase the task from the request via the LLM bridge.
summary, description, llm_error = _extract_task(ctx, request)
if llm_error:
return ActionResult(
action_log=llm_error,
new_state=request.text,
decisions=decisions,
)
# 2. Find the task list to write to (the bridge returns only VTODO-capable
# task lists, so an event-only calendar can never be chosen).
status, payload = _call("GET", f"{base_url}/tasklists", nc_headers)
if status != 200:
return ActionResult(
action_log=(
f"could not list Nextcloud task lists from {base_url}: "
f"status {status}, {payload.get('error', payload)}"
),
new_state=request.text,
decisions=decisions,
)
task_lists = [c for c in (payload.get("tasklists") or []) if c.get("name")]
if not task_lists:
return ActionResult(
action_log="no Nextcloud task lists are available to add a task to",
new_state=request.text,
decisions=decisions,
)
if len(task_lists) == 1:
target = task_lists[0]["name"]
else:
decision = DecisionRequest(
state=request.text,
question="Which Nextcloud task list should the new task be added to?",
options=[
Option(c["name"], c.get("label") or c["name"]) for c in task_lists
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
target = result.selected
target_label = next(
(c.get("label") or c["name"] for c in task_lists if c["name"] == target),
target,
)
# 3. Create the task for real through the bridge.
status, payload = _call(
"POST",
f"{base_url}/tasks",
nc_headers,
{"calendar": target, "summary": summary, "description": description},
)
if status != 200 or not payload.get("ok"):
return ActionResult(
action_log=(
f"failed to add task \"{summary}\" to Nextcloud task list "
f"\"{target_label}\": status {status}, {payload.get('error', payload)}"
),
new_state=request.text,
decisions=decisions,
)
uid = payload.get("uid", "")
calendar = payload.get("calendar", target)
report = (
f'added task "{summary}" to Nextcloud task list "{target_label}" '
f"(calendar={calendar}, uid={uid})"
)
return ActionResult(action_log=report, new_state=report, decisions=decisions)
-345
View File
@@ -1,345 +0,0 @@
"""Hermetic mechanics test for nextcloud.create_task.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud bridge (`GET /tasklists`, `POST /tasks`) and the
LLM bridge's `POST /chat`. This proves the body phrases the task through the LLM
bridge, picks a task list (the sole one, or a SemIf choice when there are
several), creates the task through the bridge, and fails honestly when the LLM
bridge or the Nextcloud bridge errors. It does NOT prove the live integration —
only a real run against the user's Nextcloud does.
"""
import json
import socket
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def make_handler(routes, seen):
"""Build a request handler that records every request and replays `routes`."""
class Handler(BaseHTTPRequestHandler):
def _respond(self):
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
body = json.loads(raw.decode("utf-8")) if raw else None
except ValueError:
body = raw.decode("utf-8", "replace")
seen.append(
{
"method": self.command,
"path": self.path,
"headers": {k.lower(): v for k, v in self.headers.items()},
"body": body,
}
)
key = (self.command, self.path.split("?")[0])
status, payload = routes.get(key, (404, {"error": "no route"}))
data = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
do_GET = _respond
do_POST = _respond
def log_message(self, *args):
pass
return Handler
def start_server(routes):
seen = []
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(routes, seen))
threading.Thread(target=server.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d" % server.server_address[1]
return server, seen, url
def stop(server):
server.shutdown()
server.server_close()
def closed_port_url():
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
return "http://127.0.0.1:%d" % port
class FakeResult:
"""Minimal stand-in for a DecisionResult: the body only reads `.selected`."""
def __init__(self, selected):
self.selected = selected
class FakeEngine:
"""Test-only decision engine; records the requests the body asked for."""
def __init__(self, choice=None):
self.choice = choice
self.calls = []
def call(self, decision):
self.calls.append(decision)
return FakeResult(self.choice)
def test_happy_path_single_task_list():
llm_routes = {
("POST", "/chat"): (
200,
{
"text": '{"summary": "Eat hot dogs", '
'"description": "Buy and eat hot dogs"}'
},
)
}
nc_routes = {
("GET", "/tasklists"): (
200,
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
),
("POST", "/tasks"): (
200,
{"ok": True, "uid": "uid-1", "calendar": "tasks"},
),
}
llm_server, llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
engine = FakeEngine()
ctx = ActionContext(
engine=engine,
config={
"nextcloud_bridge_url": nc_url,
"nextcloud_bridge_token": "nc-secret",
"llm_bridge_url": llm_url,
"llm_bridge_token": "llm-secret",
},
)
request = Request("Add a task in next cloud for eating hot dogs.")
result = skill.act(ctx, request)
assert not engine.calls, "a single task list must not need a decision"
assert "Eat hot dogs" in result.action_log, result.action_log
assert "Tasks" in result.action_log, result.action_log
assert "uid-1" in result.action_log, result.action_log
assert len(llm_seen) == 1, llm_seen
chat = llm_seen[0]
assert chat["method"] == "POST", chat
assert chat["path"] == "/chat", chat
assert chat["headers"].get("x-semif-token") == "llm-secret", chat["headers"]
assert chat["body"]["messages"][1]["content"] == request.text, chat["body"]
assert "summary" in chat["body"]["messages"][0]["content"], chat["body"]
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
listing = nc_seen[0]
assert listing["method"] == "GET", listing
assert listing["headers"].get("x-semif-token") == "nc-secret", listing["headers"]
create = nc_seen[1]
assert create["method"] == "POST", create
assert create["headers"].get("x-semif-token") == "nc-secret", create["headers"]
assert create["body"] == {
"calendar": "tasks",
"summary": "Eat hot dogs",
"description": "Buy and eat hot dogs",
}, create["body"]
print("happy path:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def test_multiple_task_lists_asks_and_omits_token_header():
llm_routes = {
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
}
nc_routes = {
("GET", "/tasklists"): (
200,
{
"tasklists": [
{"name": "tasks", "label": "Tasks"},
{"name": "work", "label": "Work"},
]
},
),
("POST", "/tasks"): (200, {"ok": True, "uid": "uid-2", "calendar": "work"}),
}
llm_server, llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
engine = FakeEngine(choice="work")
ctx = ActionContext(
engine=engine,
config={
"nextcloud_bridge_url": nc_url,
"nextcloud_bridge_token": "",
"llm_bridge_url": llm_url,
"llm_bridge_token": "",
},
)
result = skill.act(
ctx, Request("Add a task in next cloud for eating hot dogs.")
)
assert len(engine.calls) == 1, "two task lists must trigger one decision"
decision = engine.calls[0]
assert [o.id for o in decision.options] == ["tasks", "work"], decision.options
assert result.decisions, "the decision must be recorded on the result"
assert "x-semif-token" not in llm_seen[0]["headers"], llm_seen[0]["headers"]
create = nc_seen[-1]
assert create["path"] == "/tasks", create
assert create["body"]["calendar"] == "work", create["body"]
assert create["body"]["description"] == "", create["body"]
assert "x-semif-token" not in create["headers"], create["headers"]
assert "Work" in result.action_log, result.action_log
print("decision path:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def test_llm_bridge_failure_leaves_nextcloud_untouched():
llm_routes = {("POST", "/chat"): (502, {"error": "model down"})}
nc_routes = {
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
}
llm_server, _llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"nextcloud_bridge_url": nc_url,
"llm_bridge_url": llm_url,
},
)
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
assert "could not phrase the task" in result.action_log, result.action_log
assert "model down" in result.action_log, result.action_log
assert nc_seen == [], "Nextcloud must not be touched when phrasing fails"
print("llm failure:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def test_llm_reply_without_task_text():
llm_routes = {("POST", "/chat"): (200, {"text": "I cannot help with that."})}
nc_routes = {
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
}
llm_server, _llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
)
result = skill.act(ctx, Request("do something vague"))
assert "no usable task text" in result.action_log, result.action_log
assert nc_seen == [], "Nextcloud must not be touched without a task title"
print("unusable llm reply:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def test_no_task_lists_available():
llm_routes = {
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
}
nc_routes = {("GET", "/tasklists"): (200, {"tasklists": []})}
llm_server, _llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
)
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
assert "no Nextcloud task lists" in result.action_log, result.action_log
assert [r["path"] for r in nc_seen] == ["/tasklists"], nc_seen
print("no task lists:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def test_unreachable_nextcloud_bridge():
llm_routes = {
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
}
llm_server, _llm_seen, llm_url = start_server(llm_routes)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"nextcloud_bridge_url": closed_port_url(),
"llm_bridge_url": llm_url,
},
)
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
assert "could not list Nextcloud task lists" in result.action_log, result.action_log
print("unreachable nextcloud:", result.action_log)
finally:
stop(llm_server)
def test_task_creation_failure_is_reported():
llm_routes = {
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
}
nc_routes = {
("GET", "/tasklists"): (
200,
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
),
("POST", "/tasks"): (502, {"error": "CalDAV rejected the VTODO"}),
}
llm_server, _llm_seen, llm_url = start_server(llm_routes)
nc_server, nc_seen, nc_url = start_server(nc_routes)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
)
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
assert "failed to add task" in result.action_log, result.action_log
assert "CalDAV rejected the VTODO" in result.action_log, result.action_log
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
print("creation failure:", result.action_log)
finally:
stop(llm_server)
stop(nc_server)
def main():
test_happy_path_single_task_list()
test_multiple_task_lists_asks_and_omits_token_header()
test_llm_bridge_failure_leaves_nextcloud_untouched()
test_llm_reply_without_task_text()
test_no_task_lists_available()
test_unreachable_nextcloud_bridge()
test_task_creation_failure_is_reported()
print("ok")
if __name__ == "__main__":
main()
-6
View File
@@ -1,6 +0,0 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report the next upcoming event on the user's Nextcloud calendar."
}
-416
View File
@@ -1,416 +0,0 @@
"""Report the next upcoming event on the user's Nextcloud calendar.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` discovers the user's calendars over PROPFIND and resolves which one the
request means with a single SemIf choice over every owned calendar (state = the
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
otherwise the configured default calendar is used; with no configured default
the weak winner stands. It then issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has not
ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
lives here; a server that ignores expansion is reported honestly rather than
guessed at.
"""
from __future__ import annotations
import base64
import re
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "nextcloud_calendar",
"transport": "caldav",
"config_vars": [
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
],
}
CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
DURATION_RE = re.compile(
r"^(?P<sign>[+-])?P"
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone`
config value when set, else host local. A test seam; never freezes time."""
return local_now(ctx.config)
# ---- transport ----
def _request(ctx, method, path, body=None, depth="0"):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
password = str(ctx.config.get("nextcloud_app_password", "") or "")
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = urllib.request.Request(
url + path,
data=body,
method=method,
headers={
"Authorization": f"Basic {token}",
"Depth": depth,
"Content-Type": "application/xml; charset=utf-8",
},
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return response.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, OSError) as exc:
raise CalDavError(f"{method} {path}: {exc}") from exc
# ---- CalDAV discovery + query ----
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
calendars = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
def _report_body(start, end):
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
return (
'<?xml version="1.0" encoding="utf-8"?>'
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop>"
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
"</c:calendar-data>"
"</d:prop>"
"<c:filter>"
'<c:comp-filter name="VCALENDAR">'
'<c:comp-filter name="VEVENT">'
f'<c:time-range start="{start_text}" end="{end_text}"/>'
"</c:comp-filter>"
"</c:comp-filter>"
"</c:filter>"
"</c:calendar-query>"
).encode("utf-8")
def _calendar_payloads(body):
root = _multistatus(body)
payloads = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
if data.text:
payloads.append(data.text)
return payloads
# ---- calendar resolution ----
def _default_calendar(ctx, calendars):
"""The configured default calendar, if it is one of the account's."""
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
return calendar
return None
def _resolve_calendar(ctx, request, calendars, decisions):
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands.
"""
default = _default_calendar(ctx, calendars)
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar parsing ----
def _unfold(text):
lines = []
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
def _parse_property(line):
match = PROPERTY_RE.match(line)
if match is None:
return "", {}, ""
name = match.group("name").upper()
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None
total = timedelta(
weeks=int(match.group("weeks") or 0),
days=int(match.group("days") or 0),
hours=int(match.group("hours") or 0),
minutes=int(match.group("minutes") or 0),
seconds=int(match.group("seconds") or 0),
)
return -total if match.group("sign") == "-" else total
def _parse_events(payloads, default_tz):
events = []
for payload in payloads:
current = None
for line in _unfold(payload):
name, params, value = _parse_property(line)
if name == "BEGIN" and value.strip().upper() == "VEVENT":
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"):
return event["start"] + timedelta(days=1)
return event["start"]
def _pick_next(events, now):
current_or_future = [event for event in events if _event_end(event) >= now]
if not current_or_future:
return None
return min(current_or_future, key=lambda event: event["start"])
def _format_when(event):
start = event["start"]
if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z")
# ---- skill phases ----
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
now = _now(ctx)
local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
body = _request(
ctx,
"REPORT",
_calendar_path(ctx, calendar),
_report_body(window_start, window_end),
depth="1",
)
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
-259
View File
@@ -1,259 +0,0 @@
"""Hermetic mechanics test for nextcloud.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision (a strong winner is used, otherwise the configured default,
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
when the service errors. It does NOT prove the live integration — only a real
run against the user's Nextcloud does.
"""
import base64
import sys
import threading
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
"""Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc)
past = now - timedelta(days=2)
soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date()
def stamp(value):
return value.strftime("%Y%m%dT%H%M%SZ")
return (
"BEGIN:VCALENDAR\nVERSION:2.0\n"
"BEGIN:VEVENT\nUID:past@example\n"
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
"SUMMARY:Already happened\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:soon@example\n"
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:allday@example\n"
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
"SUMMARY:Offsite\nEND:VEVENT\n"
"END:VCALENDAR"
)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
def _record(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
self.requests.append(
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._record()
responses = "".join(
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
"<d:propstat><d:prop>"
f"<d:displayname>{label}</d:displayname>"
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
for name, label in CALENDARS[: self.calendar_count]
)
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:response>"
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
"<d:propstat><d:prop>"
f"<c:calendar-data>{ICS}</c:calendar-data>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
"</d:response></d:multistatus>"
)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url, default="personal"):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
}
def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
commands = [entry["command"] for entry in handler.requests]
assert commands == ["PROPFIND", "REPORT"], commands
report = handler.requests[1]
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
assert report["depth"] == "1", report["depth"]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
assert report["authorization"] == expected_auth, report["authorization"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner falls back to the configured default calendar.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A single calendar needs no SemIf decision.
server, handler, url = start_server(calendar_count=1)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
try:
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Create an Outlook calendar event from a request such as \"add dentist appointment on 2026-11-10 at 2pm\"."
}
-334
View File
@@ -1,334 +0,0 @@
"""Create an event on the user's Outlook calendar from a request.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. `act` derives the event's title, date, time and
duration from `request.text`; missing pieces are asked one at a time and the
answers are stashed in `request.meta` (act re-runs from the top after a
`needs_input` pause, so a question is never asked twice). The event is created
with a real `POST /calendars/events` and the real outcome reported. The user's
IANA timezone (the top-level `timezone` config value, when set) labels the start.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, time, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
_COMMAND_WORDS = re.compile(
r"\b(add|create|new|put|make|set\s*up|set|schedule|book|"
r"i\s+need\s+to|i\s+have\s+to|calendar|"
r"for|on|at|from|my|the|a|an|to)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _now(ctx):
return local_now(ctx.config)
def _post(ctx, path, payload):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
def _month_number(token):
return _MONTHS.get(token.lower()[:3])
def _resolve_month_day(month, day, year, now):
if not (month and 1 <= day <= 31):
return None
given_year = year is not None
year = year or now.year
try:
candidate = datetime(year, month, day).date()
except ValueError:
return None
if not given_year and candidate < now.date():
try:
candidate = datetime(year + 1, month, day).date()
except ValueError:
return None
return candidate
def _parse_when(text, now):
"""`{"date","date_span","time","time_span","all_day","duration_minutes","from_weekday"}`."""
text = text or ""
result = {
"date": None,
"date_span": None,
"time": None,
"time_span": None,
"all_day": False,
"duration_minutes": None,
"from_weekday": False,
}
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match:
result["all_day"] = True
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match:
result["duration_minutes"] = int(match.group(1))
else:
for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30),
(r"\bfor\s+an?\s+hour\b", 60),
):
match = re.search(phrase, text, re.I)
if match:
result["duration_minutes"] = minutes
break
date = None
span = None
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
date = datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date()
span = match.span()
except ValueError:
date = None
if date is None:
match = re.search(
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I
)
if match:
month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now)
span = match.span() if date else None
if date is None:
match = re.search(
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
text,
re.I,
)
if match:
month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now)
span = match.span() if date else None
if date is None:
match = re.search(r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
date = now.date()
elif word in ("tomorrow", "tmrw", "tomorow"):
date = now.date() + timedelta(days=1)
else:
date = now.date() + timedelta(days=7)
span = match.span()
if date is None:
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
prefix = text[max(0, match.start() - 6) : match.start()]
if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7)
result["from_weekday"] = True
span = match.span()
parsed_time = None
time_span = None
match = re.search(r"\bnoon\b", text, re.I)
if match:
parsed_time = time(12, 0)
time_span = match.span()
elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0)
time_span = re.search(r"\bmidnight\b", text, re.I).span()
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
time_span = match.span()
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed_time = time(hour, minute)
time_span = match.span()
result["date"] = date
result["date_span"] = span
result["time"] = parsed_time
result["time_span"] = time_span
return result
def _title(text, parsed):
remove = [parsed.get("date_span"), parsed.get("time_span")]
out = text
for span in sorted((s for s in remove if s), key=lambda s: s[0], reverse=True):
out = out[: span[0]] + " " + out[span[1] :]
phrase = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", out, re.I)
if phrase:
out = out[: phrase.start()] + " " + out[phrase.end() :]
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", out)).strip(" .,:;-")
return cleaned
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
now = _now(ctx)
parsed = _parse_when(request.text, now)
title = _title(request.text, parsed)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
all_day = bool(parsed["all_day"])
if all_day:
start = datetime.combine(parsed["date"], time(0, 0))
else:
start = datetime.combine(parsed["date"], parsed["time"])
if start <= now.replace(tzinfo=None) and parsed.get("from_weekday"):
start += timedelta(days=7)
timezone_name = str(ctx.config.get("timezone", "") or "").strip()
payload = {
"subject": title,
"start": start.strftime("%Y-%m-%dT%H:%M:%S"),
"all_day": all_day,
}
if not all_day:
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
payload["end"] = (start + duration).strftime("%Y-%m-%dT%H:%M:%S")
if timezone_name:
payload["timezone"] = timezone_name
try:
data = _post(ctx, "/calendars/events", payload)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if all_day:
when_text = f"{start.date().isoformat()} (all day)"
else:
when_text = start.strftime("%Y-%m-%d %H:%M")
report = f"Created {title!r} on {when_text}."
return ActionResult(action_log=report, new_state=report)
-162
View File
@@ -1,162 +0,0 @@
"""Hermetic mechanics test for outlook.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/calendars/events` route and records
the payload. This proves the body derives the title/date/time, asks for a missing
piece and resumes, creates the event with a real POST, and fails honestly when
the bridge errors. It does NOT prove the live integration — only a real run
against the user's Microsoft account does.
"""
import json
import sys
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.create_event must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
status = 200
posts = []
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
if self.path != "/calendars/events":
self._send({"error": "not found"}, 404)
return
self.posts.append(json.loads(body.decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
self._send({"ok": True, "id": "e1", "subject": self.posts[-1].get("subject")}, 201)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def context(url, tz=""):
config = {"outlook_bridge_url": url, "outlook_bridge_token": ""}
if tz:
config["timezone"] = tz
return ActionContext(engine=FakeEngine(), config=config)
def test_explicit_datetime():
server, handler, url = start_server()
try:
action = skill.act(context(url), Request("add dentist appointment on 2026-11-10 at 2pm"))
assert action.needs_input is None, action.needs_input
post = handler.posts[0]
assert post["subject"] == "dentist appointment", post
assert post["start"] == "2026-11-10T14:00:00", post
assert post["end"] == "2026-11-10T15:00:00", post
assert post["all_day"] is False, post
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_timezone_is_sent():
server, handler, url = start_server()
try:
skill.act(
context(url, tz="America/Chicago"),
Request("add lunch on 2026-11-10 at noon"),
)
assert handler.posts[0]["timezone"] == "America/Chicago", handler.posts[0]
print(handler.posts[0])
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server()
try:
skill.act(context(url), Request("add conference all day on 2026-11-10"))
post = handler.posts[0]
assert post["all_day"] is True, post
assert "end" not in post, post
assert post["subject"] == "conference", post
print(post)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server()
try:
ctx = context(url)
request = Request("add dentist appointment on 2026-11-10")
action = skill.act(ctx, request)
assert action.needs_input, "a missing start time must be asked"
assert handler.posts == []
request.user_input = "2pm"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["start"] == "2026-11-10T14:00:00", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
request = Request("add dentist appointment on 2026-11-10 at 2pm")
action = skill.act(context(url), request)
assert "502" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_explicit_datetime()
test_timezone_is_sent()
test_all_day_event()
test_missing_time_asks_then_creates()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Add a task to the user's Microsoft To Do list, e.g. \"remind me to call the dentist tomorrow\"."
}
-193
View File
@@ -1,193 +0,0 @@
"""Add a task to the user's Microsoft To Do list.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. `act` derives the task title and an optional due
date from `request.text`; a missing title is asked one at a time and the answer
is stashed in `request.meta` (act re-runs from the top after a `needs_input`
pause, so a question is never asked twice). The task is created with a real
`POST /tasks` and the real outcome reported.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_WEEKDAYS = {
"monday": 0,
"mon": 0,
"tuesday": 1,
"tue": 1,
"tues": 1,
"wednesday": 2,
"wed": 2,
"thursday": 3,
"thu": 3,
"thur": 3,
"thurs": 3,
"friday": 4,
"fri": 4,
"saturday": 5,
"sat": 5,
"sunday": 6,
"sun": 6,
}
_WEEKDAY_RE = re.compile(
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
)
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_MONTH_ALT = (
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
)
_COMMAND_WORDS = re.compile(
r"\b(add|create|new|put|make|set\s*up|set|schedule|remind\s+me(?:\s+to)?|"
r"i\s+need\s+to|i\s+have\s+to|tasks|task|to-?dos|to-?do|todo|lists|list|for|by|due|on|"
r"my|the|a|an|to)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _now(ctx):
return local_now(ctx.config)
def _post(ctx, path, payload):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
def _match_due(text, now):
"""Return `(due_date | None, matched_span | None)` for the due date."""
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
if match:
try:
return datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date(), match.span()
except ValueError:
return None, None
match = re.search(r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I)
if match:
month = _MONTHS.get(match.group(1).lower()[:3])
year = int(match.group(3)) if match.group(3) else now.year
try:
candidate = datetime(year, month, int(match.group(2))).date()
except (TypeError, ValueError):
return None, None
if not match.group(3) and candidate < now.date():
candidate = candidate.replace(year=year + 1)
return candidate, match.span()
match = re.search(r"\b(today|tonight|tomorrow|tmrw|next\s+week)\b", text, re.I)
if match:
word = re.sub(r"\s+", " ", match.group(1).lower())
if word in ("today", "tonight"):
return now.date(), match.span()
if word in ("tomorrow", "tmrw"):
return now.date() + timedelta(days=1), match.span()
return now.date() + timedelta(days=7), match.span()
match = _WEEKDAY_RE.search(text)
if match:
target = _WEEKDAYS[match.group(1).lower()]
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
return date, match.span()
return None, None
def _title(text, span):
stripped = text
if span is not None:
stripped = text[: span[0]] + " " + text[span[1] :]
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", stripped)).strip(" .,:;-")
return cleaned
def _ask(request, field, question):
request.meta["create_task_awaiting"] = field
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
def act(ctx, request):
answers = request.meta.setdefault("create_task_answers", {})
awaiting = request.meta.get("create_task_awaiting")
if request.user_input is not None and awaiting:
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_task_awaiting", None)
now = _now(ctx)
due, span = _match_due(request.text, now)
title = _title(request.text, span)
if answers.get("title"):
title = answers["title"].strip()
if answers.get("due"):
extra_due, _ = _match_due(answers["due"], now)
if extra_due is not None:
due = extra_due
if not title:
return _ask(request, "title", "What's the task?")
payload = {"title": title}
if due is not None:
payload["due"] = f"{due.isoformat()}T00:00:00"
try:
data = _post(ctx, "/tasks", payload)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
when = f" due {due.isoformat()}" if due is not None else ""
report = f"Added task {title!r}{when}."
return ActionResult(action_log=report, new_state=report)
-144
View File
@@ -1,144 +0,0 @@
"""Hermetic mechanics test for outlook.create_task.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/tasks` route and records the
payload. This proves the body derives a title + due date, asks for a missing
title and resumes, creates the task with a real POST, and fails honestly when the
bridge errors. It does NOT prove the live integration — only a real run against
the user's Microsoft account does.
"""
import json
import sys
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.create_task must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
status = 200
posts = []
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
if self.path != "/tasks":
self._send({"error": "not found"}, 404)
return
self.posts.append(json.loads(body.decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
self._send({"ok": True, "id": "t1", "title": self.posts[-1].get("title")}, 201)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url):
return {"outlook_bridge_url": url, "outlook_bridge_token": ""}
def test_plain_task():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("add buy milk to my tasks"))
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "buy milk", handler.posts[0]
assert "due" not in handler.posts[0], handler.posts[0]
assert "buy milk" in action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_task_with_due_date():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("remind me to call the dentist tomorrow"))
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "call dentist", handler.posts[0]
assert handler.posts[0]["due"] == "2026-10-08T00:00:00", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks_then_creates():
server, handler, url = start_server()
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
request = Request("add a task")
action = skill.act(ctx, request)
assert action.needs_input, "a missing title must be asked"
assert handler.posts == []
request.user_input = "water the plants"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.posts[0]["title"] == "water the plants", handler.posts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
request = Request("add buy milk to my tasks")
action = skill.act(ctx, request)
assert "502" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_plain_task()
test_task_with_due_date()
test_missing_title_asks_then_creates()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
@@ -1,3 +0,0 @@
{
"description": "Look up a person in the user's Outlook contacts by name, email, or company."
}
-86
View File
@@ -1,86 +0,0 @@
"""Look up a person in the user's Outlook contacts.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It searches the contacts for the words in the
request and reports the matches, or the real failure honestly.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_STOPWORDS = re.compile(
r"\b(find|search|look\s*up|show|get|whats|what's|contact|contacts|email|e-?mail|"
r"address|phone|number|details|for|my|me|the|of|a|an)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def _query(text):
return re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
def act(ctx, request):
try:
data = _get(ctx, "/contacts", {"query": _query(request.text)})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
contacts = data.get("contacts") or []
if not contacts:
return ActionResult(action_log="No matching contacts.", new_state="No matching contacts.")
lines = []
for contact in contacts[:5]:
name = contact.get("display_name") or "(no name)"
emails = ", ".join(contact.get("emails") or [])
phones = ", ".join(contact.get("phones") or [])
bits = " | ".join(part for part in (emails, phones) if part)
lines.append(f"- {name}: {bits}" if bits else f"- {name}")
report = "Contacts:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
-132
View File
@@ -1,132 +0,0 @@
"""Hermetic mechanics test for outlook.list_contacts.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/contacts` route and records the
query it received. This proves the body searches the contacts and reports the
matches (and fails honestly when the bridge is unavailable). It does NOT prove
the live integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.list_contacts must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
contacts = []
status = 200
queries = []
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
parsed = urlparse(self.path)
if parsed.path == "/contacts":
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
self._send({"contacts": self.contacts}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(contacts=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"contacts": contacts
if contacts is not None
else [
{
"id": "c1",
"display_name": "Bob Smith",
"emails": ["bob@example.com"],
"phones": ["555-1234"],
}
],
"status": status,
"queries": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="find Bob's email"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_matching_contacts():
server, handler, url = start_server()
try:
action = run(url)
assert "Bob Smith" in action.action_log, action.action_log
assert "bob@example.com" in action.action_log, action.action_log
assert handler.queries and "Bob" in handler.queries[0], handler.queries
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_matches_is_reported():
server, _handler, url = start_server(contacts=[])
try:
action = run(url)
assert "no matching contacts" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "find Bob's email"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_matching_contacts()
test_no_matches_is_reported()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "List the user's OneDrive files, optionally in a named folder."
}
-92
View File
@@ -1,92 +0,0 @@
"""List the user's OneDrive files.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It lists a OneDrive folder (root by default) and
reports the entries, or the real failure honestly.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_STOPWORDS = re.compile(
r"\b(list|show|what'?s|whats|in|my|the|onedrive|files|file|folder|drive|of|me)\b",
re.I,
)
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def _folder(text):
cleaned = re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
return cleaned or "/"
def act(ctx, request):
path = _folder(request.text)
try:
data = _get(ctx, "/files", {"path": path})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
entries = data.get("entries") or []
if not entries:
return ActionResult(
action_log=f"{data.get('path') or path} is empty.",
new_state=f"{data.get('path') or path} is empty.",
)
lines = []
for entry in entries[:20]:
name = entry.get("name") or "(unnamed)"
kind = "folder" if entry.get("is_folder") else "file"
size = entry.get("size")
detail = f"{kind}"
if kind == "file" and size is not None:
detail += f", {size} bytes"
lines.append(f"- {name} ({detail})")
report = f"Files in {data.get('path') or path}:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
-141
View File
@@ -1,141 +0,0 @@
"""Hermetic mechanics test for outlook.list_files.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/files` route and records the path
it received. This proves the body lists OneDrive and reports the entries (and
fails honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.list_files must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
entries = []
status = 200
paths = []
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
parsed = urlparse(self.path)
if parsed.path == "/files":
path = parse_qs(parsed.query).get("path", ["/"])[0]
self.paths.append(path)
self._send({"path": path, "entries": self.entries}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(entries=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"entries": entries
if entries is not None
else [
{"id": "d1", "name": "Docs", "is_folder": True, "size": 0},
{"id": "f1", "name": "notes.txt", "is_folder": False, "size": 5},
],
"status": status,
"paths": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="list my files"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_lists_root_files():
server, handler, url = start_server()
try:
action = run(url)
assert "Docs (folder)" in action.action_log, action.action_log
assert "notes.txt (file, 5 bytes)" in action.action_log, action.action_log
assert handler.paths and handler.paths[0] == "/", handler.paths
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_named_folder_is_requested():
server, handler, url = start_server()
try:
run(url, "list files in Documents")
assert handler.paths and handler.paths[0] == "Documents", handler.paths
print(handler.paths)
finally:
server.shutdown()
server.server_close()
def test_empty_folder_is_reported():
server, _handler, url = start_server(entries=[])
try:
action = run(url)
assert "empty" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "list my files"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_lists_root_files()
test_named_folder_is_requested()
test_empty_folder_is_reported()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Read the user's upcoming Outlook calendar events."
}
-89
View File
@@ -1,89 +0,0 @@
"""Read the user's upcoming Outlook calendar events.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It asks the bridge for the upcoming events and
reports them, or reports the real failure honestly.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_COUNT = 5
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def act(ctx, request):
try:
data = _get(ctx, "/calendars/events")
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
events = data.get("events") or []
if not events:
return ActionResult(action_log="There are no upcoming events.", new_state="No upcoming events.")
lines = []
for event in events[:DEFAULT_COUNT]:
subject = event.get("subject") or "(no subject)"
start = event.get("start") or ""
when = _describe_when(start, bool(event.get("all_day")))
location = event.get("location") or ""
where = f" at {location}" if location else ""
lines.append(f"- {subject}{where} — {when}")
report = "Upcoming events:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
def _describe_when(start, all_day):
"""A short human time: the date (all-day) or date + time."""
text = str(start or "").strip()
if not text:
return "time unknown"
date, _, rest = text.partition("T")
if all_day or not rest:
return f"{date} (all day)" if all_day else date
return f"{date} {rest[:5]}"
-136
View File
@@ -1,136 +0,0 @@
"""Hermetic mechanics test for outlook.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/calendars/events` route. This
proves the body asks the bridge for upcoming events and reports them (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.next_event must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
events = []
status = 200
def do_GET(self):
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/calendars/events"):
self._send({"calendar": "", "events": self.events}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(events=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"events": events
if events is not None
else [
{
"id": "e1",
"subject": "Standup",
"start": "2026-10-08T09:00:00.0000000",
"end": "2026-10-08T09:30:00.0000000",
"all_day": False,
"location": "Room 1",
}
],
"status": status,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="what's on my calendar"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_upcoming_events():
server, url = start_server()
try:
action = run(url)
assert "Standup" in action.action_log, action.action_log
assert "Room 1" in action.action_log, action.action_log
assert "2026-10-08 09:00" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_events_is_reported():
server, url = start_server(events=[])
try:
action = run(url)
assert "no upcoming events" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "what's on my calendar"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert action.new_state == "what's on my calendar"
print(action.action_log)
def main():
test_reports_upcoming_events()
test_no_events_is_reported()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Read the latest messages from the user's Outlook inbox."
}
-77
View File
@@ -1,77 +0,0 @@
"""Read the latest messages from the user's Outlook inbox.
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
speaks Graph or OAuth directly. It asks the bridge for the newest inbox messages
and reports them, or reports the real failure honestly.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
DEFAULT_COUNT = 5
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook bridge."""
def _get(ctx, path, params=None):
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise OutlookBridgeError("outlook_bridge_url is not configured")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, method="GET", headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
def act(ctx, request):
try:
data = _get(ctx, "/mail/messages", {"folder": "inbox", "count": DEFAULT_COUNT})
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
messages = data.get("messages") or []
if not messages:
return ActionResult(action_log="The inbox is empty.", new_state="The inbox is empty.")
lines = []
for message in messages[:DEFAULT_COUNT]:
sender = message.get("from") or "unknown sender"
subject = message.get("subject") or "(no subject)"
received = message.get("received") or ""
flag = " (unread)" if not message.get("is_read") else ""
lines.append(f"- {sender}: {subject}{flag} [{received}]")
report = "Recent inbox messages:\n" + "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
-140
View File
@@ -1,140 +0,0 @@
"""Hermetic mechanics test for outlook.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local Outlook bridge's `/mail/messages` route. This proves
the body asks the bridge for the inbox and reports the messages (and fails
honestly when the bridge is unavailable). It does NOT prove the live
integration — only a real run against the user's Microsoft account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("outlook.next_message must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
requests = []
status = 200
def do_GET(self):
self.requests.append(self.path)
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/mail/messages"):
self._send({"folder": "inbox", "messages": self.messages}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(messages=None, status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"messages": messages
if messages is not None
else [
{
"id": "m1",
"subject": "Lunch?",
"from": "Sam <sam@example.com>",
"received": "2026-10-08T12:00:00Z",
"is_read": False,
}
],
"requests": [],
"status": status,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="check my email"):
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_recent_messages():
server, handler, url = start_server()
try:
action = run(url)
assert "Lunch?" in action.action_log, action.action_log
assert "sam@example.com" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert handler.requests, "the bridge must be called"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported():
server, _handler, url = start_server(messages=[])
try:
action = run(url)
assert "empty" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "check my email", "a failed read must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert "outlook.next_message" not in action.action_log, action.action_log
assert action.new_state == "check my email"
print(action.action_log)
def main():
test_reports_recent_messages()
test_empty_inbox_is_reported()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-6
View File
@@ -1,6 +0,0 @@
{
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Compose and send an Outlook email, after confirming the message."
}
-201
View File
@@ -1,201 +0,0 @@
"""Send an Outlook email on the user's behalf, after a confirmation.
Real integration: the local Outlook bridge (Microsoft Graph) to resolve the
recipient and send, and the local LLM bridge to turn the request into a
`{recipient, subject, body}` draft. Connection comes from `ctx.config`
(`outlook_bridge_url`, `outlook_bridge_token`, `llm_bridge_url`,
`llm_bridge_token`); the body never speaks Graph, OAuth, or the model's protocol
directly.
Because sending is irreversible, the body **asks for confirmation before it
sends**: it composes the message, resolves the recipient (an explicit address is
used as-is; otherwise the contacts are searched and, when several match, a SemIf
choice picks one), then pauses with "Send ...? (yes/no)". A `yes` sends for real;
anything else cancels. A missing recipient is asked for.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "outlook",
"transport": "http",
"config_vars": [
"outlook_bridge_url",
"outlook_bridge_token",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
_YES = {"y", "yes", "send", "ok", "okay", "sure", "confirm"}
class OutlookBridgeError(Exception):
"""A real failure talking to the local Outlook or LLM bridge."""
def _request(ctx, service, path, *, method="GET", params=None, payload=None):
if service == "llm":
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
else:
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
if not base:
raise OutlookBridgeError(f"the {service} bridge URL is not configured")
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
data = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {"Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/json"
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise OutlookBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise OutlookBridgeError(f"{method} {path}: {exc}") from exc
def _compose(ctx, request):
"""Ask the LLM bridge for the recipient, subject, and body."""
messages = [
{
"role": "system",
"content": (
"Turn the user's request into an email. Reply with ONLY a JSON "
'object: {"recipient": "<name or email address>", '
'"subject": "<short subject>", "body": "<the message>"}.'
),
},
{"role": "user", "content": request.text},
]
data = _request(ctx, "llm", "/chat", method="POST", payload={"messages": messages})
text = str(data.get("text") or "")
start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start:
raise OutlookBridgeError("the LLM bridge returned no JSON object")
try:
draft = json.loads(text[start : end + 1])
except ValueError as exc:
raise OutlookBridgeError(f"the LLM bridge returned invalid JSON: {exc}") from exc
if not isinstance(draft, dict):
raise OutlookBridgeError("the LLM bridge returned JSON that is not an object")
return {
"recipient": str(draft.get("recipient") or "").strip(),
"subject": str(draft.get("subject") or "").strip(),
"body": str(draft.get("body") or "").strip(),
}
def _resolve_address(ctx, decisions, recipient):
"""An email address for `recipient`: used directly, or chosen from contacts."""
if "@" in recipient:
return recipient
data = _request(ctx, "outlook", "/contacts", params={"query": recipient})
contacts = [c for c in (data.get("contacts") or []) if c.get("emails")]
if not contacts:
return None
if len(contacts) == 1:
return str(contacts[0]["emails"][0])
options = [
Option(str(contact["emails"][0]), str(contact.get("display_name") or contact["emails"][0]))
for contact in contacts
]
decision = DecisionRequest(
state=recipient,
question="Which contact should the message be sent to?",
options=options,
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
return str(result.selected)
def _ask(request, question):
return ActionResult(action_log="waiting for input", new_state=request.text, needs_input=question)
def act(ctx, request):
meta = request.meta
awaiting = meta.get("send_message_awaiting")
decisions = []
# Resume: the user answered the recipient/address/confirmation question.
if request.user_input is not None and awaiting:
if awaiting == "confirm":
ready = meta.get("send_message_ready") or {}
meta.pop("send_message_awaiting", None)
if request.user_input.strip().lower() not in _YES:
return ActionResult(
action_log="Cancelled; the message was not sent.",
new_state="cancelled",
)
try:
result = _request(
ctx,
"outlook",
"/mail/send",
method="POST",
payload={"to": [ready.get("to", "")], "subject": ready.get("subject", ""), "body": ready.get("body", "")},
)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
report = f"Sent {ready.get('subject')!r} to {ready.get('to')}."
meta.pop("send_message_ready", None)
return ActionResult(action_log=report, new_state=report)
meta.setdefault("send_message_answers", {})[awaiting] = request.user_input.strip()
meta.pop("send_message_awaiting", None)
answers = meta.get("send_message_answers") or {}
draft = meta.get("send_message_composed")
if draft is None:
try:
draft = _compose(ctx, request)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
meta["send_message_composed"] = draft
recipient = answers.get("recipient") or draft["recipient"]
if not recipient:
meta["send_message_awaiting"] = "recipient"
return _ask(request, "Who should I send the message to?")
address = answers.get("address")
if not address:
try:
address = _resolve_address(ctx, decisions, recipient)
except OutlookBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if not address:
meta["send_message_awaiting"] = "address"
return _ask(request, f"What's the email address for {recipient!r}?")
meta["send_message_ready"] = {"to": address, "subject": draft["subject"], "body": draft["body"]}
meta["send_message_awaiting"] = "confirm"
action = _ask(request, f"Send {draft['subject']!r} to {address}? (yes/no)")
action.decisions = decisions
return action
-216
View File
@@ -1,216 +0,0 @@
"""Hermetic mechanics test for outlook.send_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local LLM bridge (`POST /chat`), the Outlook bridge's
contact lookup, and `POST /mail/send`. This proves the body composes a draft,
resolves the recipient, asks for confirmation BEFORE sending, sends for real on
`yes`, cancels otherwise, and fails honestly when the LLM bridge is down. It does
NOT prove the live integration — only a real run against the user's Microsoft
account does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Picks `pick` (else the first option) with full confidence."""
def __init__(self, pick=None):
self.pick = pick
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
ids = [option.id for option in decision.options]
chosen = self.pick if self.pick in ids else ids[0]
probs = [1.0 if option_id == chosen else 0.0 for option_id in ids]
return DecisionResult(request=decision, option_ids=ids, probabilities=probs)
class BridgeHandler(BaseHTTPRequestHandler):
draft = {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"}
contacts = [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}]
llm_status = 200
sends = []
queries = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def do_POST(self):
body = self._read()
if self.path == "/chat":
if self.llm_status != 200:
self._send({"error": "boom"}, self.llm_status)
return
self._send({"text": json.dumps(self.draft)}, 200)
return
if self.path == "/mail/send":
self.sends.append(json.loads(body.decode("utf-8")))
self._send({"ok": True, "to": self.sends[-1].get("to")}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/contacts":
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
self._send({"contacts": self.contacts}, 200)
return
self._send({"error": "not found"}, 404)
def _send(self, payload, status):
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 log_message(self, *args):
pass
def start_server(**overrides):
attrs = {
"draft": {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"},
"contacts": [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}],
"llm_status": 200,
"sends": [],
"queries": [],
}
attrs.update(overrides)
handler = type("Handler", (BridgeHandler,), attrs)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def context(url, engine):
return ActionContext(
engine=engine,
config={
"outlook_bridge_url": url,
"outlook_bridge_token": "",
"llm_bridge_url": url,
"llm_bridge_token": "",
},
)
def test_confirms_then_sends():
server, handler, url = start_server()
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert action.needs_input and "send" in action.needs_input.lower(), action.needs_input
assert handler.sends == [], "nothing may be sent before confirmation"
request.user_input = "yes"
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert handler.sends[0]["to"] == ["sam@example.com"], handler.sends
assert handler.sends[0]["subject"] == "Lunch", handler.sends
assert "sent" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_cancel_does_not_send():
server, handler, url = start_server()
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
skill.act(ctx, request)
request.user_input = "no"
action = skill.act(ctx, request)
assert handler.sends == [], "a cancelled message must not be sent"
assert "cancel" in action.action_log.lower(), action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_multiple_contacts_use_semif_choice():
contacts = [
{"id": "c1", "display_name": "Sam A", "emails": ["sam.a@example.com"]},
{"id": "c2", "display_name": "Sam B", "emails": ["sam.b@example.com"]},
]
server, handler, url = start_server(contacts=contacts)
try:
engine = FakeEngine(pick="sam.b@example.com")
ctx = context(url, engine)
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, engine.decisions
assert "sam.b@example.com" in action.needs_input, action.needs_input
request.user_input = "yes"
action = skill.act(ctx, request)
assert handler.sends[0]["to"] == ["sam.b@example.com"], handler.sends
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_explicit_address_is_used():
server, handler, url = start_server(
draft={"recipient": "bob@example.com", "subject": "Late", "body": "I'll be late"}
)
try:
ctx = context(url, FakeEngine(pick="sam@example.com"))
request = Request("email bob@example.com that I'll be late")
skill.act(ctx, request)
request.user_input = "yes"
skill.act(ctx, request)
assert handler.sends[0]["to"] == ["bob@example.com"], handler.sends
# No contact lookup is needed for an explicit address.
assert handler.queries == [], handler.queries
print(handler.sends[0])
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
ctx = context(url, FakeEngine())
request = Request("email Sam that lunch is tomorrow")
action = skill.act(ctx, request)
assert "502" in action.action_log, action.action_log
assert handler.sends == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_confirms_then_sends()
test_cancel_does_not_send()
test_multiple_contacts_use_semif_choice()
test_explicit_address_is_used()
test_llm_bridge_failure_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
}
-107
View File
@@ -1,107 +0,0 @@
"""Show the SimpleX contact link others use to connect to this agent.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
the `simplex-chat` daemon is the only thing that can read (or create) the
forwarding bot's *user contact address*; this body asks the bridge for it and
reports the link honestly. It never opens a WebSocket to the daemon and never
invents a link: if the bridge is not running or has no address, it says so.
`act` health-checks the bridge, then `GET /address` shows the existing link and
creates one on first call, returning `{short_link, full_link, created}`.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 30
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
if not payload.get("ok"):
return ActionResult(
action_log="simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
return ActionResult(
action_log=f"reading the contact link failed: {exc}",
new_state=request.text,
)
short = str(payload.get("short_link") or "").strip()
full = str(payload.get("full_link") or "").strip()
if not (short or full):
return ActionResult(
action_log=(
"the bridge returned no SimpleX "
"contact link; the bot has no address yet."
),
new_state=request.text,
)
verb = "created" if payload.get("created") else "current"
lines = [f"SimpleX contact link ({verb}): {short or full}"]
if short and full:
lines.append(f"Full link: {full}")
lines.append(
"Share this link with someone so they can add the agent and message it."
)
report = "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
-174
View File
@@ -1,174 +0,0 @@
"""Hermetic mechanics test for simplex.connect_link.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body health-
checks the bridge, fetches the contact link, reports a freshly created link, and
fails honestly when the bridge has no provider or is unreachable. It does NOT
prove the live integration — only a real run against the bridge and a real
simplex-chat daemon does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class BridgeHandler(BaseHTTPRequestHandler):
address = {}
address_status = 200
requests = []
tokens = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/health":
self._send({"ok": True, "platform": "simplex"})
elif url.path == "/address":
self._send(self.address, self.address_status)
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(address=None, address_status=200):
handler = type(
"Handler",
(BridgeHandler,),
{
"address": address or {},
"address_status": address_status,
"requests": [],
"tokens": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, token=""):
return {"simplex_bridge_url": url, "simplex_bridge_token": token}
def test_reports_existing_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
assert handler.requests == ["/health", "/address"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_reports_freshly_created_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#new", "full_link": "", "created": True}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
action = skill.act(ctx, request)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_provider_is_reported_honestly():
server, handler, url = start_server({"error": "address lookup is not available"}, 503)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_link_is_reported_honestly():
server, handler, url = start_server({"short_link": "", "full_link": "", "created": False})
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert action.action_log and "simplex.connect_link" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_existing_link()
test_reports_freshly_created_link()
test_no_provider_is_reported_honestly()
test_empty_link_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-5
View File
@@ -1,5 +0,0 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Read the next unread SimpleX message."
}
-303
View File
@@ -1,303 +0,0 @@
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf choice over them (state = the user
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
the configured default contact is used; with no configured default (or a default
with no unread message) the weak winner stands. It then pops and reports the
oldest unread message for that conversation.
When the live buffer is empty it falls back to the daemon's persistent unread
(`/unread` + `/history`), so a message that arrived before the bridge started is
still reported. After reporting a message, that single item is marked read on
the daemon through the bridge (`POST /read`), so the next call advances to the
next unread message instead of re-reporting the same one.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
messaging surface it uses.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
}
TIMEOUT_SECONDS = 20
# A SemIf probability at or above this counts as a "strong winner" for the
# conversation; below it the configured default contact is used instead.
CONTACT_WINNER_TAU = 0.6
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
def _post(ctx, path, payload):
data = json.dumps(payload).encode("utf-8")
headers = {**_headers(ctx), "Content-Type": "application/json"}
request = urllib.request.Request(
_base(ctx) + path, data=data, headers=headers, method="POST"
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"POST {path}: {exc}") from exc
def _mark_read(ctx, contact, item_id):
"""Mark one just-reported item read via the bridge.
Returns None on success, or a short honest reason string on failure. The
message was still reported, so a failed consume is surfaced as a note rather
than fabricated into a read failure.
"""
item = str(item_id or "").strip()
if not item:
return None
try:
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
except BridgeError as exc:
return str(exc)
if not payload.get("ok"):
return payload.get("error") or "the bridge did not mark it read"
return None
# ---- conversation resolution ----
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
seen = set()
for message in messages:
contact = str(message.get("contact_id") or "")
if not contact or contact in seen:
continue
seen.add(contact)
senders.append(
{"id": contact, "display_name": message.get("display_name") or contact}
)
return senders
def _is_healthy(sender):
"""A conversation is healthy when its connection is not known-bad.
`connected` is absent when the source did not report it (treat as unknown);
`auth_errors` counts failed sends on the connection and marks a stale peer.
"""
if sender.get("connected") is False:
return False
try:
return int(sender.get("auth_errors") or 0) == 0
except (TypeError, ValueError):
return True
def _default_sender(ctx, senders):
"""The configured default contact, if it has unread messages."""
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender
return None
def _resolve_contact(ctx, request, senders, decisions):
"""Resolve which conversation to read, mirroring nextcloud.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default contact, and with no configured default the weak winner stands.
"""
default = _default_sender(ctx, senders)
if len(senders) == 1:
return senders[0]["id"]
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CONTACT_WINNER_TAU:
return winner
if default is not None:
return default["id"]
return winner
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
senders = _senders(payload.get("messages") or [])
if senders:
return _read_live(ctx, request, senders)
# The live buffer only holds messages that arrived while the bridge was
# connected; fall back to the daemon's persistent unread so a message that
# landed before the bridge started is not silently missed.
return _read_persistent(ctx, request)
def _read_live(ctx, request, senders):
decisions = []
contact = _resolve_contact(ctx, request, senders, decisions)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
read_note = _mark_read(ctx, contact, message.get("item_id"))
return _report(
message.get("display_name") or contact,
message.get("text"),
decisions,
read_note,
)
def _read_persistent(ctx, request):
try:
payload = _get(ctx, "/unread")
except BridgeError as exc:
return ActionResult(
action_log=f"no unread SimpleX messages ({exc}).",
new_state="no unread SimpleX messages",
)
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
if not chats:
return ActionResult(
action_log="no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
senders = [
{
"id": str(chat.get("contact_id") or ""),
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
"connected": chat.get("connected"),
"auth_errors": chat.get("auth_errors"),
}
for chat in chats
if chat.get("contact_id")
]
decisions = []
healthy = [s for s in senders if _is_healthy(s)]
if len(healthy) == 1:
# Exactly one conversation is on a healthy connection (the rest are
# stale duplicates): read it without a coin-flip decision.
contact = healthy[0]["id"]
else:
contact = _resolve_contact(ctx, request, senders, decisions)
try:
history = _get(
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
if not messages:
# Fall back to the previewed unread messages from /unread.
chat = next(
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
)
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
if not messages:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = next(
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
)
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
return _report(sender, messages[0].get("text"), decisions, read_note)
def _report(sender, body, decisions, read_note=None):
report = f"SimpleX message from {sender}: {str(body or '')}"
if read_note:
report += f" (could not mark it read: {read_note})"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
-425
View File
@@ -1,425 +0,0 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
strong winner is used, otherwise the configured default, otherwise the weak
winner), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
unread_chats = []
history = {}
requests = []
tokens = []
read_calls = []
read_ok = True
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/inbox":
self._send({"messages": list(self.messages)})
elif url.path == "/inbox/next":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
found = None
for index, message in enumerate(self.messages):
if contact is None or message["contact_id"] == str(contact):
found = self.messages.pop(index)
break
self._send({"message": found})
elif url.path == "/unread":
self._send({"chats": list(self.unread_chats)})
elif url.path == "/history":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
self._send(
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
)
else:
self._send({"error": "not found"}, 404)
def do_POST(self):
url = urllib.parse.urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
if url.path != "/read":
self._send({"error": "not found"}, 404)
return
self.read_calls.append(payload)
if self.read_ok:
self._send(
{
"ok": True,
"contact_id": payload.get("contact"),
"item_ids": payload.get("item_ids"),
"status": "read",
}
)
else:
self._send({"ok": False, "error": "the daemon rejected the read"})
def log_message(self, *args):
pass
def start_server(messages, unread_chats=None, history=None, read_ok=True):
handler = type(
"Handler",
(BridgeHandler,),
{
"messages": list(messages),
"unread_chats": list(unread_chats or []),
"history": dict(history or {}),
"requests": [],
"tokens": [],
"read_calls": [],
"read_ok": read_ok,
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def message(identifier, contact, name, text):
return {
"id": identifier,
"item_id": str(identifier),
"contact_id": contact,
"display_name": name,
"text": text,
"received_at": 1.0,
}
def config(url, default="", token=""):
return {
"simplex_bridge_url": url,
"simplex_default_contact": default,
"simplex_bridge_token": token,
}
def test_multiple_senders_uses_semif_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
"the reported item must be marked read, and only it"
)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_strong_winner_overrides_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message from Bob")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
# Bob edges out Alice but stays below the strong-winner threshold, so the
# configured default ("Alice") is used instead.
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
assert "hello there" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_without_default_stands():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_single_sender_needs_no_decision():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported_honestly():
server, handler, url = start_server([])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
# An empty live buffer falls back to the daemon's persistent unread.
assert handler.requests == ["/inbox", "/unread"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_live_inbox_falls_back_to_persistent_unread():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 2,
"min_unread_item_id": "8",
"unread": True,
"messages": [],
}
],
history={
"3": [
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
]
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single unread chat needs no decision"
assert "hello" in action.action_log, action.action_log
assert "pepper" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_persistent_unread_prefers_a_healthy_conversation():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 2,
"messages": [],
},
{
"contact_id": "4",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 0,
"messages": [],
},
],
history={
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert engine.decisions == [], "one healthy chat must win without a decision"
assert "fresh hello" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
handler.requests
)
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_failed_read_marking_is_surfaced_honestly():
"""A message is still reported when consuming it fails, with an honest note
instead of a fabricated failure of the read."""
server, handler, url = start_server(
[message("m1", "4", "Alice", "hi")], read_ok=False
)
try:
ctx = ActionContext(engine=FakeEngine(), config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert "hi" in action.action_log, action.action_log
assert "could not mark it read" in action.action_log, action.action_log
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
test_weak_winner_falls_back_to_default_contact()
test_weak_winner_without_default_stands()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_empty_live_inbox_falls_back_to_persistent_unread()
test_persistent_unread_prefers_a_healthy_conversation()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
test_failed_read_marking_is_surfaced_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-7
View File
@@ -1,7 +0,0 @@
{
"simplex_bridge_url": "Base URL of the local SimpleX forwarding bridge that fronts the user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the SimpleX bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not clearly name a recipient; leave blank to always use the strongest candidate.",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to write the message text when the request does not state it.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Send a SimpleX message to a contact through the forwarding bridge."
}
-482
View File
@@ -1,482 +0,0 @@
"""Send a text message to a SimpleX contact through the local SimpleX bridge.
Real integration: the simplex bridge over HTTP. The bridge owns the SimpleX
daemon connection and its credentials; this body only calls the bridge's HTTP
API with the base URL and token resolved from `ctx.config`.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, last_result
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
"llm_bridge_url",
"llm_bridge_token",
],
}
CONTRACT = {
"simplex_bridge_url": (
"Base URL of the local SimpleX forwarding bridge that fronts the "
"user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash "
"needed)."
),
"simplex_bridge_token": (
"Shared secret for the SimpleX bridge, if one is configured; sent as "
"the X-Semif-Token header. Leave blank when the bridge requires no auth."
),
"simplex_default_contact": (
"Default SimpleX contact (contact id or display name) used when the "
"request does not clearly name a recipient; leave blank to always use "
"the strongest candidate."
),
"llm_bridge_url": (
"Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no "
"trailing slash needed); used to write the message text when the "
"request does not state it."
),
"llm_bridge_token": (
"Shared secret for the LLM bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth."
),
}
# A contact sub-decision winner is used only when its conditional probability
# clears this bar; otherwise the configured default contact wins.
CONFIDENCE_THRESHOLD = 0.5
_HTTP_TIMEOUT = 20
# Ordered: the literal message text the user dictated wins over anything else.
_MESSAGE_PATTERNS = (
r"\b(?:saying|say|that says|which says|that reads|reads)\b\s*[:\-]?\s*(.+)$",
r'["\u201c](.+?)["\u201d]',
r"\b(?:message|text)\s*(?:is|:)\s*(.+)$",
)
# --------------------------------------------------------------------------
# bridge transport
# --------------------------------------------------------------------------
def _headers(token: str, has_body: bool) -> dict:
headers = {"Accept": "application/json"}
if has_body:
headers["Content-Type"] = "application/json"
if token:
headers["X-Semif-Token"] = token
return headers
def _http_json(url: str, token: str, payload=None):
"""GET the url, or POST the payload as JSON, and decode the JSON reply."""
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url,
data=data,
headers=_headers(token, data is not None),
method="POST" if data is not None else "GET",
)
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT) as response:
raw = response.read().decode("utf-8")
if not raw.strip():
return {}
return json.loads(raw)
def _error_detail(exc) -> str:
"""Best-effort human-readable detail from an HTTP error response."""
try:
raw = exc.read().decode("utf-8", "replace")
except Exception:
raw = ""
if raw:
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
if isinstance(parsed, dict) and parsed.get("error"):
return str(parsed["error"])
return raw.strip()
return str(getattr(exc, "reason", "") or exc)
# --------------------------------------------------------------------------
# contacts
# --------------------------------------------------------------------------
def _contact_id(contact) -> str:
return str(contact.get("id") or contact.get("display_name") or "").strip()
def _display(contact) -> str:
return str(contact.get("display_name") or contact.get("id") or "").strip()
def _label(contact) -> str:
"""The unique name for a contact: the daemon's local name when known.
Two peers can share a profile display name; the local name is unique, so it
is the right label for a SemIf option and the right thing to match on.
"""
return str(
contact.get("local_name") or _display(contact) or contact.get("id") or ""
).strip()
def _is_healthy(contact) -> bool:
"""A contact is healthy when its connection is not known-bad.
`connected` is absent when the source did not report it (treat as unknown,
i.e. not disqualifying); `auth_errors` counts failed sends on the connection
and marks a stale/duplicate peer.
"""
if contact.get("connected") is False:
return False
try:
return int(contact.get("auth_errors") or 0) == 0
except (TypeError, ValueError):
return True
def _mentions(query: str, name: str) -> bool:
if not name:
return False
pattern = r"(?<!\w)" + re.escape(name.lower()) + r"(?!\w)"
return re.search(pattern, query.lower()) is not None
def _match_contact(contacts, ref: str):
"""Resolve an id or display name against the bridge's contact list."""
ref = (ref or "").strip()
if not ref:
return None
lowered = ref.lower()
for contact in contacts:
if _contact_id(contact).lower() == lowered:
return contact
exact = [
c
for c in contacts
if _label(c).lower() == lowered or _display(c).lower() == lowered
]
if exact:
return _preferred(exact)
matches = [
c
for c in contacts
if lowered in _display(c).lower() or lowered in _label(c).lower()
]
if len(matches) == 1:
return matches[0]
if matches:
return _preferred(matches)
return None
def _preferred(candidates):
"""Prefer a healthy candidate (the others are likely stale duplicates)."""
healthy = [c for c in candidates if _is_healthy(c)]
return (healthy or candidates)[0]
def _find_by_id(contacts, contact_id):
wanted = str(contact_id or "")
for contact in contacts:
if _contact_id(contact) == wanted:
return contact
return None
def _confidence(result, option_id) -> float:
prob = getattr(result, "prob", None)
if callable(prob):
try:
return float(prob(option_id))
except Exception:
return 0.0
probs = getattr(result, "probs", None)
if isinstance(probs, dict):
try:
return float(probs.get(option_id, 0.0))
except (TypeError, ValueError):
return 0.0
return 0.0
# --------------------------------------------------------------------------
# message text
# --------------------------------------------------------------------------
def _message_from_query(query: str) -> str:
"""Pull the literal message text out of the user's request, if stated."""
for pattern in _MESSAGE_PATTERNS:
match = re.search(pattern, query, flags=re.IGNORECASE | re.DOTALL)
if match:
text = match.group(1).strip().strip("\"'\u201c\u201d").strip()
if text:
return text
return ""
def _llm_message_text(ctx, query: str):
"""Ask the LLM bridge to write the message body. Returns (text, reason)."""
base_url = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base_url:
return None, "no llm bridge is configured"
token = str(ctx.config.get("llm_bridge_token", "") or "")
payload = {
"messages": [
{
"role": "system",
"content": (
"You write the exact text of a chat message a user wants to "
"send. Reply with the message text only: no quotes, no "
"preamble, no explanation."
),
},
{"role": "user", "content": query},
],
"max_tokens": 256,
}
try:
reply = _http_json(f"{base_url}/chat", token, payload)
except urllib.error.HTTPError as exc:
return None, f"the llm bridge returned HTTP {exc.code} {_error_detail(exc)}"
except (urllib.error.URLError, ValueError, OSError) as exc:
return None, f"could not reach the llm bridge: {exc}"
if not isinstance(reply, dict):
return None, "the llm bridge returned an unexpected reply"
text = str(reply.get("text", "")).strip().strip('"').strip()
if not text:
return None, "the llm bridge returned no text"
return text, ""
# --------------------------------------------------------------------------
# action
# --------------------------------------------------------------------------
def act(ctx, request) -> ActionResult:
"""Send the requested message to the requested SimpleX contact."""
base_url = str(ctx.config["simplex_bridge_url"]).strip().rstrip("/")
token = str(ctx.config.get("simplex_bridge_token", "") or "")
default_ref = str(ctx.config.get("simplex_default_contact", "") or "").strip()
query = (request.text or "").strip()
user_input = str(getattr(request, "user_input", "") or "").strip()
decisions = []
# --- the bridge's real contact list ------------------------------------
try:
payload = _http_json(f"{base_url}/contacts", token)
except urllib.error.HTTPError as exc:
return ActionResult(
action_log=(
f"the simplex bridge at {base_url} returned HTTP {exc.code} "
f"while listing contacts: {_error_detail(exc)}"
),
new_state=request.text,
)
except (urllib.error.URLError, ValueError, OSError) as exc:
return ActionResult(
action_log=(
f"could not reach the simplex bridge at {base_url} to list "
f"contacts: {exc}"
),
new_state=request.text,
)
raw_contacts = payload.get("contacts") if isinstance(payload, dict) else None
contacts = (
[c for c in raw_contacts if isinstance(c, dict)]
if isinstance(raw_contacts, list)
else []
)
# --- resolve the recipient --------------------------------------------
default_contact = _match_contact(contacts, default_ref)
named = [
c
for c in contacts
if _mentions(query, _display(c)) or _mentions(query, _label(c))
]
chosen = None
used_input_for_contact = False
if named or default_contact is not None:
candidates = list(named)
if default_contact is not None and all(
_contact_id(c) != _contact_id(default_contact) for c in candidates
):
candidates.append(default_contact)
healthy = [c for c in candidates if _is_healthy(c)]
if len(candidates) == 1:
chosen = candidates[0]
elif len(healthy) == 1:
# Exactly one candidate's connection is healthy (the rest are stale
# duplicates): pick it deterministically rather than coin-flipping.
chosen = healthy[0]
else:
decision = DecisionRequest(
state=query,
question="Which SimpleX contact should the message be sent to?",
options=[
Option(_contact_id(c), _label(c) or _contact_id(c))
for c in candidates
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
selected_id = getattr(result, "selected", None)
selected = _find_by_id(candidates, selected_id)
if (
selected is not None
and _confidence(result, selected_id) >= CONFIDENCE_THRESHOLD
):
chosen = selected
elif default_contact is not None:
chosen = default_contact
else:
chosen = selected if selected is not None else candidates[0]
elif user_input:
# The human answered the question asked on the previous pass.
chosen = _match_contact(contacts, user_input) or {
"id": user_input,
"display_name": user_input,
}
used_input_for_contact = True
if chosen is None:
known = ", ".join(_display(c) for c in contacts if _display(c)) or "none"
return ActionResult(
action_log=(
"the request does not identify a SimpleX contact to message; "
f"the bridge knows these contacts: {known}"
),
new_state=request.text,
needs_input="Which SimpleX contact should I message?",
decisions=decisions,
)
recipient = _contact_id(chosen) or _display(chosen)
display_name = _display(chosen) or recipient
# --- resolve the message text -----------------------------------------
# Prefer the literal text the user dictated; then the result of the previous
# step of a chain (never re-derive a computed value with the LLM); only then
# ask the LLM bridge for genuinely new text.
message_text = _message_from_query(query)
if not message_text and user_input and not used_input_for_contact:
message_text = user_input
if not message_text:
message_text = last_result(request)
if not message_text:
written, reason = _llm_message_text(ctx, query)
if written:
message_text = written
else:
return ActionResult(
action_log=(
f"the request does not state what the message to "
f"{display_name} should say and no message text could be "
f"written ({reason})"
),
new_state=request.text,
needs_input=f"What should the message to {display_name} say?",
decisions=decisions,
)
# --- send it through the bridge ---------------------------------------
try:
response = _http_json(
f"{base_url}/send", token, {"recipient": recipient, "text": message_text}
)
except urllib.error.HTTPError as exc:
return ActionResult(
action_log=(
f"the simplex bridge refused to send to {display_name}: "
f"HTTP {exc.code} {_error_detail(exc)}"
),
new_state=request.text,
decisions=decisions,
)
except (urllib.error.URLError, ValueError, OSError) as exc:
return ActionResult(
action_log=(
f"could not reach the simplex bridge at {base_url} to send the "
f"message to {display_name}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if not isinstance(response, dict):
return ActionResult(
action_log=(
f"the simplex bridge returned an unexpected reply while sending "
f"to {display_name}"
),
new_state=request.text,
decisions=decisions,
)
contact_id = str(response.get("contact_id") or recipient)
status = str(response.get("status") or "")
if not response.get("ok"):
detail = str(response.get("error") or "").strip() or json.dumps(response)
return ActionResult(
action_log=(
f"the message to {display_name} (contact {contact_id}) did not "
f"send (status {status or 'unknown'}: {detail})"
),
new_state=json.dumps(
{
"sent": False,
"contact_id": contact_id,
"display_name": display_name,
"status": status,
"error": detail,
"text": message_text,
}
),
decisions=decisions,
)
return ActionResult(
action_log=(
f"sent the message {message_text!r} to {display_name} "
f"(contact {contact_id}, status {status or 'ok'}) through the "
f"simplex bridge"
),
new_state=json.dumps(
{
"sent": True,
"contact_id": contact_id,
"display_name": display_name,
"status": status,
"text": message_text,
}
),
decisions=decisions,
)
-416
View File
@@ -1,416 +0,0 @@
"""Hermetic mechanics test for simplex.send_message.
Stands up loopback HTTP servers that imitate the simplex and llm bridges,
points the fixture config at them, and drives the body's real `act` so the
request construction, recipient/message resolution and error paths are
exercised without leaving the machine.
"""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import skill
from semif_agent.skills import ActionContext
# ---------------------------------------------------------------------------
# inline fixtures
# ---------------------------------------------------------------------------
CONTACTS = [
{"id": "c-pepper", "display_name": "pepper"},
{"id": "c-salt", "display_name": "salt"},
]
SIMPLEX_TOKEN = "s3cret-simplex-token"
LLM_TOKEN = "s3cret-llm-token"
LLM_REPLY = "a friendly hello"
class FakeRequest:
"""Minimal stand-in for the agent's Request object (test-only)."""
def __init__(self, text, user_input="", run_ledger=None):
self.text = text
self.user_input = user_input
self.run_ledger = list(run_ledger or [])
class FakeResult:
"""Stand-in for a decision result: exposes `selected` and `prob(id)`."""
def __init__(self, selected, confidence):
self.selected = selected
self._confidence = confidence
def prob(self, option_id):
return float(self._confidence) if option_id == self.selected else 0.0
class FakeEngine:
"""Test-only decision engine."""
def __init__(self, selected=None, confidence=1.0):
self.selected = selected
self.confidence = confidence
self.calls = []
def call(self, decision):
self.calls.append(decision)
selected = self.selected
if selected is None:
options = list(decision.options)
selected = options[0].id if options else None
return FakeResult(selected, self.confidence)
class _BaseHandler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def _send_json(self, code, obj):
body = json.dumps(obj).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
if not raw:
return None
try:
return json.loads(raw.decode("utf-8"))
except ValueError:
return None
class SimplexHandler(_BaseHandler):
contacts = []
send_error = False
seen = []
def do_GET(self):
SimplexHandler.seen.append(
{
"method": "GET",
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
}
)
if self.path == "/contacts":
self._send_json(200, {"contacts": SimplexHandler.contacts})
else:
self._send_json(404, {"error": "not found"})
def do_POST(self):
body = self._read_body()
SimplexHandler.seen.append(
{
"method": "POST",
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
"body": body,
}
)
if self.path != "/send":
self._send_json(404, {"error": "not found"})
return
if SimplexHandler.send_error:
self._send_json(400, {"error": "unknown recipient"})
return
recipient = (body or {}).get("recipient", "")
self._send_json(200, {"ok": True, "contact_id": recipient})
class LlmHandler(_BaseHandler):
reply = LLM_REPLY
seen = []
def do_POST(self):
body = self._read_body()
LlmHandler.seen.append(
{
"path": self.path,
"token": self.headers.get("X-Semif-Token"),
"body": body,
}
)
if self.path == "/chat":
self._send_json(200, {"text": LlmHandler.reply})
else:
self._send_json(404, {"error": "not found"})
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def start_server(handler):
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def base_url(server):
return f"http://127.0.0.1:{server.server_address[1]}"
def reset(contacts=None, send_error=False):
SimplexHandler.contacts = [dict(c) for c in (contacts if contacts is not None else CONTACTS)]
SimplexHandler.send_error = send_error
SimplexHandler.seen = []
LlmHandler.seen = []
LlmHandler.reply = LLM_REPLY
# ---------------------------------------------------------------------------
# tests
# ---------------------------------------------------------------------------
def test_happy_path():
"""A named contact plus an explicit message: GET /contacts then POST /send."""
reset()
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(server),
"simplex_bridge_token": SIMPLEX_TOKEN,
},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert result.action_log, "act must log what it did"
assert not result.needs_input, result.action_log
assert "sent" in result.action_log.lower(), result.action_log
gets = [r for r in SimplexHandler.seen if r["method"] == "GET"]
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert any(r["path"] == "/contacts" for r in gets), SimplexHandler.seen
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["path"] == "/send", SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-pepper", "text": "hey"}, posts[0]
for seen in SimplexHandler.seen:
assert seen["token"] == SIMPLEX_TOKEN, seen
state = json.loads(result.new_state)
assert state["sent"] is True, state
assert state["contact_id"] == "c-pepper", state
assert state["text"] == "hey", state
finally:
server.shutdown()
server.server_close()
def test_ambiguous_contact_uses_engine():
"""Two named contacts: the body must ask the engine and honour the pick."""
reset()
server = start_server(SimplexHandler)
try:
engine = FakeEngine(selected="c-salt", confidence=0.9)
ctx = ActionContext(
engine=engine,
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper and salt saying hi")
)
assert not result.needs_input, result.action_log
assert len(engine.calls) == 1, engine.calls
option_ids = [o.id for o in engine.calls[0].options]
assert set(option_ids) == {"c-pepper", "c-salt"}, option_ids
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-salt", "text": "hi"}, posts[0]
finally:
server.shutdown()
server.server_close()
def test_message_written_by_llm_bridge():
"""No literal text: the body must ask the llm bridge, then send its reply."""
reset()
simplex = start_server(SimplexHandler)
llm = start_server(LlmHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(simplex),
"simplex_bridge_token": SIMPLEX_TOKEN,
"llm_bridge_url": base_url(llm),
"llm_bridge_token": LLM_TOKEN,
},
)
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
assert not result.needs_input, result.action_log
assert len(LlmHandler.seen) == 1, LlmHandler.seen
chat = LlmHandler.seen[0]
assert chat["path"] == "/chat", chat
assert chat["token"] == LLM_TOKEN, chat
assert chat["body"]["messages"], chat
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {"recipient": "c-pepper", "text": LLM_REPLY}, posts[0]
finally:
simplex.shutdown()
simplex.server_close()
llm.shutdown()
llm.server_close()
def test_chained_result_is_sent():
"""As the later step of a chain, no literal text: send the prior step's result."""
reset()
simplex = start_server(SimplexHandler)
llm = start_server(LlmHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(simplex),
"simplex_bridge_token": SIMPLEX_TOKEN,
"llm_bridge_url": base_url(llm),
},
)
request = FakeRequest(
"send the result of 22 * 10 to pepper on simplex",
run_ledger=[
{
"query": "send the result of 22 * 10 to pepper on simplex",
"skill": "calculator.calculate",
"outcome": "Twenty-two times ten is two hundred twenty.",
}
],
)
result = skill.act(ctx, request)
assert not result.needs_input, result.action_log
# The prior result is used verbatim; the LLM bridge must NOT be asked to
# recompute it.
assert LlmHandler.seen == [], LlmHandler.seen
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {
"recipient": "c-pepper",
"text": "Twenty-two times ten is two hundred twenty.",
}, posts[0]
finally:
simplex.shutdown()
simplex.server_close()
llm.shutdown()
llm.server_close()
def test_missing_text_without_llm_asks():
"""A clear recipient but no message text and no llm bridge: ask the user."""
reset()
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
assert result.needs_input, result.action_log
assert "say" in result.needs_input.lower(), result.needs_input
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert posts == [], SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_unknown_contact_asks():
"""No matching contact in the bridge list: ask which contact to message."""
reset(contacts=[])
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert result.needs_input, result.action_log
assert "contact" in result.needs_input.lower(), result.needs_input
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert posts == [], SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_send_refused_is_reported():
"""A 400 from POST /send must be surfaced, not silently swallowed."""
reset(send_error=True)
server = start_server(SimplexHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": base_url(server)},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert not result.needs_input, result.action_log
assert "refused" in result.action_log.lower(), result.action_log
assert "400" in result.action_log, result.action_log
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_is_reported():
"""A dead bridge must produce a plain failure log, not an exception."""
reset()
server = start_server(SimplexHandler)
url = base_url(server)
server.shutdown()
server.server_close()
ctx = ActionContext(
engine=FakeEngine(),
config={"simplex_bridge_url": url},
)
result = skill.act(
ctx, FakeRequest("send a message to pepper on simplex saying hey")
)
assert not result.needs_input, result.action_log
assert "could not reach" in result.action_log.lower(), result.action_log
def main():
test_happy_path()
test_ambiguous_contact_uses_engine()
test_message_written_by_llm_bridge()
test_chained_result_is_sent()
test_missing_text_without_llm_asks()
test_unknown_contact_asks()
test_send_refused_is_reported()
test_unreachable_bridge_is_reported()
print("ok")
if __name__ == "__main__":
main()
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report today's date."
}
-21
View File
@@ -1,21 +0,0 @@
"""Report today's date.
Real local compute: reads the host clock and formats the calendar date in the
user's timezone — the top-level `timezone` config value (an IANA name) when set,
otherwise the host's local timezone. No external service.
"""
from __future__ import annotations
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def act(ctx, request):
today = local_now(ctx.config).date()
message = f"Today is {today.strftime('%A, %B')} {today.day}, {today.year}."
return ActionResult(action_log=message, new_state=message)
-29
View File
@@ -1,29 +0,0 @@
"""Hermetic mechanics test for time.date.
Run from this folder: `python skill.test.py`. No external network, no config.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what is today's date?"))
assert action.new_state, "act must report the date"
assert "Today is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Report the current local time of day."
}
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more