Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge),
new tests/test_config.py. All unit tests pass (772).
2026-10-13 14:20:35 +00:00
gabby b953475bf7 scheduler: surface failed authoring to the front end
A skill-body write or a draft authoring call that fails only printed to
stdout. On the voice gateway that goes to the journal, so the user heard
"authoring a new skill in the background; the request will re-run when it
is ready" and then nothing — the creation had failed silently.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Also fix command capture: after the wake word the daemon now waits
listen_timeout_s (default 3s) for the command's speech to begin instead of
assuming it is glued to the wake word, so a natural pause while the cue beep
plays no longer truncates the command.
2026-10-09 08:19:36 +00:00
gabby ae37abbc3f debug tasklist 2026-10-09 02:28:46 +00:00
gabby f1ea9f0c2c seeds: ship simplex.send_message (promoted from the runtime store)
Move the authored simplex.send_simplex_message skill out of data/skills/ into
the committed simplex seed folder as send_message. Expand its CONTRACT to cover
every declared config var (SimpleX bridge + LLM bridge) so it satisfies the seed
contract test, add its manifest.json, and update the navigation tuning labels,
the seed-existence test, the committed-seed tree assertions, the docs, and the
bridge backlog (item 3 shipped).
2026-10-09 00:32:07 +00:00
gabby b8f86849ea seeds: merge calendar and productivity_management into nextcloud
Consolidate the calendar and productivity_management seed categories into one
nextcloud category: create_event/next_event move from calendar, and
create_nextcloud_task becomes create_task (dropping the redundant prefix).
Replace the two CATEGORY_DESCRIPTIONS entries with a single nextcloud
description and update every reference across the repo (docs, bridge comments,
tests, navigation tuning labels, seed docstrings).
2026-10-09 00:23:32 +00:00
152 changed files with 14411 additions and 14737 deletions

No files matched your search

+6 -1
View File
@@ -12,10 +12,15 @@ data/skills/
data/drafts/
.pytest_cache/
config.json
config/
secrets.json
*.log
# Machine-specific material: deployment notes (hostnames, addresses, SSH,
# model choices), GPU offload probe, benchmark harness. Deliberately not part
# of the shipped agent.
local/
*.egg-info/
*.bak.*
*.bak.*
# Skill packs live in their own repositories (one per pack) and are cloned into
# packs/<name>/ at setup. They are not tracked here. See PACKGEN.md.
packs/
+66
View File
@@ -0,0 +1,66 @@
---
name: Pack Generation
description: Author a new semif-agent skill pack (its own packs/<name>/ repository) — the pack.json manifest, its skill leaves, its bridge reference, and its config schema. Use when adding a new concern/product bundle as its own pack repo, or when adding a new bridge service to back one.
---
# Pack Generation
This skill walks you through adding a **pack** to semif-agent. The full contract
is the repository file `PACKGEN.md` (at the repo root, i.e. `../../../PACKGEN.md`
relative to this skill). Read it before making changes — it is the source of
truth and this skill is only the workflow.
## When to use
- The user wants a new concern/product bundle (its own `packs/<name>/` repo).
- The user wants a new third-party service backed by a bridge that ships with
its pack (`packs/<name>/bridge/`).
- The user is adding skills that should ship as a pack rather than be
authored at runtime.
## Workflow
1. **Read `PACKGEN.md`** in full.
2. **Decide the concern and categories.** Write one- to two-sentence,
navigation-grade category descriptions — SemIf routes on them.
3. **Bridge check.** If the pack talks to a third-party system, confirm a bridge
already fronts it (a shipped pack's `bridge/`, or the shared LLM bridge). If
not, author the bridge first (see the "Authoring a new bridge" section of
`PACKGEN.md`), ship it under `packs/<name>/bridge/`, and give it a pack config
block.
4. **Create the pack** (its own repository, `pack.<name>`):
`packs/<name>/pack.json` with `name`, `title`, `concern`, `categories`,
`bridges`, `requires`, `enabled_by_default`, and the `config` schema. Model
it on `packs/essentials/pack.json` (bridge-less) or
`packs/simplex/pack.json` (bridge-backed). If the pack needs python deps,
ship them at `packs/<name>/requirements.txt` (pinned, pip format) — never in
the agent repo's `requirements/` (see `PACKGEN.md`, "Pack python deps").
5. **Add each leaf** under `skills/<category>/<leaf>/` — `skill.py`,
`manifest.json`, `contract.json`, `skill.test.py` — following `CODEGEN.md`
and `TESTGEN.md`. Do not restate those rules; follow them. Ship each bridge
under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
6. **Regenerate and validate config:**
`python -m semif_agent.cli check-config --write-example config.example.json`
then `python -m semif_agent.cli check-config`.
7. **Run the tests:**
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
(it runs every pack's skill and bridge tests, including the new ones).
8. **Cross-link** the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
pack).
9. **Verify a real run** against the user's actual service — a passing hermetic
test proves mechanics only, never the live integration.
10. **Register and publish:** add the pack to the `semif-packs` pack-index repo
(an entry in its `packs.json`: name + clone URL, plus title/description for
the interview), then commit and push the pack's own repository
(`pack.<name>`). `scripts/bootstrap.sh` reads the index and clones it into
`packs/`.
## Guardrails
- A pack is declarative, committed in its own repository; never put a credential
in it (secrets live in the gitignored `secrets.json`).
- A bridge **ships with its pack** (`packs/<name>/bridge/`); the core keeps only
the shared contract + discovery. Never widen the gateway.
- `concern` and `categories` are required; every category needs a description.
- Regenerate `config.example.json` from the schema after any schema change; the
example and the live config are never hand-edited.
+951 -334
View File
File diff suppressed because it is too large. Load diff
+122 -36
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
contract, `TESTGEN.md`. This file is about the runnable body only.
A skill that ships as a committed starter lives inside a **pack**; how a pack
bundles skills, references a bridge, and declares its settings is the separate
contract `PACKGEN.md`.
## What a skill is
Semif-agent is an end-user application: an everyday person asks it to do a task,
and it does that task using a combination of native python modules, user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based decision engine known as SemIf.
and it does that task using native python modules — including direct HTTP
requests to a service's own API — user-provided data, and, where warranted, a
catalog of basic services known as bridges. A skill is the thing that performs
one of those tasks: it is the leaf in the skill tree that the agent navigates to
when it has resolved a request to a single, concrete action. Navigation is
performed by an llm-based decision engine known as SemIf.
A skill is three things:
@@ -21,7 +30,8 @@ A skill is three things:
talks to and how) and the `CONTRACT` constant (the values the runner must
provide).
The committed seed `seeds/calendar/create_event/` is the **authoritative worked
The `nextcloud` pack's create_event skill
(`packs/nextcloud/skills/nextcloud/create_event/`, from its own repo) is the **authoritative worked
example** of all three. Read its `manifest.json`, its `skill.py` (which declares
`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
body should look and behave like it.
@@ -137,9 +147,10 @@ engine/runtime concerns, not body-level tools: a body makes direct typed
decisions and lets the runner own the model.
Note that the runner's own **assessment** of whether a run succeeded
(`assess:outcome`) is itself a SemIf decision over the body's `action_log`, the
goal, and the resolved inputs. The body does not self-assess; it reports
truthfully and lets SemIf judge.
(`assess:outcome`: is there any additional work to be done to satisfy the
request? → done / continue / failed) is itself a SemIf decision over the body's
`action_log`, the goal, the resolved inputs, and the steps already taken. The
body does not self-assess; it reports truthfully and lets SemIf judge.
### Choosing between deterministic code, SemIf, and LLM text
@@ -162,12 +173,12 @@ Rules:
real candidate set (fetched from the service), include any configured default as
one of the options, and threshold the winner: use it when its probability clears
the skill's confidence threshold, otherwise fall back to the configured default
(see `calendar.create_event` and `simplex.next_message`).
(see `nextcloud.create_event` and `simplex.next_message`).
- **Use the LLM bridge for text, not for routing or assessment.** Generated text
goes through the LLM bridge — a generic `POST /chat` whose base URL, token,
and endpoint shapes are in the bridge catalog injected below — never by
speaking a model's protocol directly. Keep the model extractive and bounded
(see how `calendar.create_event` asks only for a title and description), and
(see how `nextcloud.create_event` asks only for a title and description), and
report a real failure when the bridge is down rather than guessing the text.
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
selects, or assesses; deterministic code never invents a value it cannot
@@ -175,6 +186,14 @@ Rules:
hand; a title is generated by the LLM, not assembled by string concatenation
when it should be written; a date is parsed by code, not asked of a model.
**Connectivity is separate from these three sources.** The table is about
*values*, not about how a body reaches a service. A body calls a **plain HTTP
API directly** with a stdlib transport (endpoint and credentials read from
`ctx.config`); a bridge is only for a service that needs state (especially auth
state), a native or heavy protocol, or one sanitized surface. See "Bridge
services" below for when to use one — and the hard rule for a service a bridge
already fronts.
## The registry entry
The body writer does **not** author a manifest. The `llm` provider authors the
@@ -193,8 +212,7 @@ The registry is a map of category -> bucket:
{
"name": "<leaf_name>",
"description": "<what this leaf does, for navigation>",
"request_text": "<the originating request, optional>",
"requirements": {"<question>": "<answer>"}
"goal": "<the de-identified, reusable action statement>"
}
]
}
@@ -204,8 +222,10 @@ The registry is a map of category -> bucket:
- A leaf `name` is a single snake_case token (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`),
not dotted with the category; the category is the key it lives under, and the
runner joins them as `category.name` only when it builds the run summary.
- `request_text` and `requirements` are recorded by the scheduler so a stub can
be re-driven later; the body never sets them.
- `goal` is the de-identified, reusable action statement authored by the local
`llm`; the scheduler records it so a stub can be re-driven later. The
originating request and any user detail are never persisted here, and never
reach the codegen endpoint.
## Code body contract
@@ -283,8 +303,12 @@ def act(ctx, request) -> ActionResult:
`ctx.config` (the resolved values for this skill, including its own config),
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
`ctx.admin` exists for the built-in housekeeping meta skills only; an ordinary
body must never touch it.
`ctx.catalog` is a **read-only** view of the agent's own skill tree for an
introspection skill that reports what the agent can do: `ctx.catalog.categories()`
returns a `{category_id: description}` map and `ctx.catalog.skills(category)`
the leaf names inside one category (the `skills.list_categories` /
`skills.list_skills` seeds). `ctx.admin` exists for the built-in housekeeping
meta skills only; an ordinary body must never touch it.
- `request` is the `Request` being handled.
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
@@ -386,7 +410,7 @@ INTEGRATION = {
skills that perform no external action at all (pure analysis/formatting); an
action skill must not use it.
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
the committed seeds this is exactly the body's `CONTRACT` key set; an empty
the shipped seeds this is exactly the body's `CONTRACT` key set; an empty
list is allowed for `compute`. Declaring a variable the body never reads is a
mismatch the fidelity check flags.
@@ -422,7 +446,7 @@ return ActionResult(..., decisions=[(decision, result)])
options, so the request can override the stored default.
- When the winner is weak (its probability is below the skill's confidence
threshold), fall back to the configured default; with no configured default,
keep the weak winner. See how `calendar.create_event` resolves its calendar.
keep the weak winner. See how `nextcloud.create_event` resolves its calendar.
### Producing the result (output)
@@ -451,14 +475,44 @@ Rules:
the result is a broken output.
- **Never an empty or placeholder output.** If there is genuinely nothing (empty
inbox, no matching event), say so explicitly — that is a real result, and a
**successful** run: the `assess:outcome` step treats a definitive "nothing
found / nothing to do" result as success. Phrase it as the answer the user
asked for ("checked the inbox: no unread messages"), not as an absence or an
error, so the assessment does not read a healthy empty result as a failure.
**`done`** run: the `assess:outcome` step treats a definitive "nothing found /
nothing to do" result as done. Phrase it as the answer the user asked for
("checked the inbox: no unread messages"), not as an absence or an error, so
the assessment does not read a healthy empty result as a failure.
- **Keep the result speakable — it is bounded.** A skill's output is read in a
chat message or heard as speech, so the runner truncates `action_log` /
`new_state` to one shared budget (`chain.result_chars`, ~300 characters /
~20 seconds of speech) and feeds the bounded text to the assessment and the
run ledger. A result longer than that is a bad result. When a skill's real
product is long or structured (a file listing, a document body, a full
thread), write it to the service or a file as a **side effect** and return a
short summary plus a pointer (path / id) — never dump the payload into the
result string.
- **Never claim success you did not observe.** If the action failed, put the
real failure in `action_log` and set `new_state` back to `request.text` (see
the hard requirements).
### Multi-step chains
A request can take more than one action ("calculate 2*10 and send the result to
Pepper"). The runner does not ask one body to satisfy the whole request: it runs
the **next** skill, judges the outcome, and if more work remains re-dispatches
the request with a **run ledger** of the steps already taken. A body may
therefore run as a later step of a chain.
- `request.run_ledger` is a list of `{"query", "skill", "outcome"}` entries, one
per step already taken (empty on a first step). The most recent entry's
`outcome` is the previous step's result — the same bounded text the runner
shows the user.
- **If the request depends on the previous step's result, read it — never
recompute or fabricate it.** `from semif_agent.skills import last_result`
returns `run_ledger[-1]["outcome"]` (or `""`). Do not ask the LLM bridge to
redo a calculation or re-fetch a value an earlier step produced; that would
silently invent a working value. Prefer a literal value the user stated, then
the prior step's result, and only then generate novel text.
- A body still returns only its own step's `action_log` / `new_state`; the
runner owns the ledger and decides whether the chain continues.
### Rules (hard requirements)
- **Perform the real action.** If the skill's purpose involves an external
@@ -515,29 +569,50 @@ Rules:
for. `request.meta` is a scratch dict carried on the same request across the
pause, so a body can cache a computed value or an already-collected answer
there and reuse it on the resume pass instead of recomputing or re-asking —
see how `calendar.create_event` caches the extracted title/description and the
see how `nextcloud.create_event` caches the extracted title/description and the
answers it collected.
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
- **Keep the body small — it is ingested whole.** The fidelity decision reads
the *entire* body, so a body that exceeds the engine's context budget is
rejected outright (the pipeline retries once with a "make it shorter"
instruction). Delegate **complex** protocol details to a bridge instead of
hand-rolling a client (a simple HTTP call needs no bridge), and keep `act` to
one purpose; a long body is a signal that the integration belongs in a bridge.
- **The function is `act` exactly.** The module is imported under its registered
leaf name; the entry point is a module-level `act(ctx, request)`.
## Bridge services
Some real systems are reached through a **bridge service**: a standalone local
process that stands up a small, token-guarded HTTP API in front of the system
and owns its native protocol and credentials. The concrete catalog of bridges —
which services exist, their base-URL config var, auth, config vars, and the
exact endpoints with their request/response/error shapes — is injected into the
prompt at authoring time (render it with
A body reaches a real service with a stdlib transport. A **plain HTTP API** is
called directly — `urllib.request` / `http.client`, endpoint and credentials read
from `ctx.config` — and needs no bridge. Some systems, however, are reached
through a **bridge service**: a standalone local process that stands up a small,
token-guarded HTTP API in front of the system and owns its native protocol,
credentials, and connection state. Reach for a bridge only when a simple,
repeatable skill file would otherwise be inconsistent, inconvenient, or unsafe:
- **State, especially auth state.** The service needs an OAuth token, a session
cookie, a live daemon connection, a read cursor, or other state a stateless,
re-run-from-the-top `act` cannot own.
- **Sanitized connectivity.** You want one narrow, token-guarded, audited
surface instead of arbitrary bodies speaking the service's raw protocol.
- **A native or heavy protocol.** The service speaks WebSocket/DAV/OCS or needs
a third-party dependency (a browser, a mail client) a one-file stdlib body
must not carry.
When a bridge **does** front a service, the body calls the bridge and must never
reach around it to the service's native protocol — no WebSocket to
`simplex-chat`, no direct daemon access, no DAV/OCS hand-rolling. It calls the
bridge's HTTP API with the base URL from the bridge's config variable, exactly
like any other HTTP integration:
The concrete catalog of bridges — which services exist, their base-URL config
var, auth, config vars, and the exact endpoints with their request/response/error
shapes — is injected into the prompt at authoring time (render it with
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This
section is only the generic pattern; the catalog is the source of truth for the
bridge-specific details.
A body must never speak a service's native protocol directly — no WebSocket to
`simplex-chat`, no direct daemon access. It calls the bridge's HTTP API with the
base URL from the bridge's config variable, exactly like any other HTTP
integration:
```python
INTEGRATION = {
"service": "<the bridge's service id, from the catalog>",
@@ -548,6 +623,9 @@ INTEGRATION = {
Rules:
- **A plain HTTP service needs no bridge.** If the service exposes a normal HTTP
API and needs none of the three triggers above, call it directly with a stdlib
transport; declare its endpoint in `CONTRACT` and read it from `ctx.config`.
- **Read every value from `ctx.config`.** The base URL, any token, and any
default (recipient/contact/target) come from the config vars the catalog
lists. Never hardcode a host, port, or bridge address in the body.
@@ -557,7 +635,7 @@ Rules:
- **Resolve the recipient/target with a SemIf sub-decision.** When more than one
conversation or target is relevant, resolve which one with a
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
contacts or buffered senders), mirroring how `calendar.create_event` picks a
contacts or buffered senders), mirroring how `nextcloud.create_event` picks a
calendar. Use the catalog's default config var as the configured option when
the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the
@@ -575,8 +653,11 @@ Rules:
- Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category.
- Reach a plain HTTP API directly; use a bridge only for a service that needs
state/auth, a native or heavy protocol, or one sanitized surface — and never
reach around a bridge that fronts the service.
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `calendar.create_event` resolves which calendar
sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar
to write to.
- `act` performs the concrete real action and writes a human-readable
`action_log` that the SemIf assessment step can judge. Include what the
@@ -616,9 +697,14 @@ A generated skill is accepted only if:
11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
and is consistent with the body's `ctx.config` reads and behavior.
12. It does no network, file, or engine work at import time.
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
service's native protocol), resolves recipients with a SemIf sub-decision,
and sends only on explicit user intent.
13. If the service it targets is fronted by a bridge, it calls that bridge over
HTTP (never the service's native protocol); otherwise it may call the
service's HTTP API directly. A messaging skill resolves recipients with a
SemIf sub-decision and sends only on explicit user intent.
14. It is small enough to be ingested whole by the fidelity decision (a body
over the engine's artifact budget is rejected as too long) — delegate
complex protocol details to a bridge rather than hand-rolling them (a simple
HTTP call needs no bridge).
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
body outright. The rest are not statically rejected: a missing or inconsistent
+468
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/`.
+377 -168
View File
@@ -127,11 +127,15 @@ choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
- **Leaf.** The leaf softmax picks only among the existing skills (a create
option diluted its probability and let a crowded tree drift into create on a
weak plurality). The picked skill then goes through the **intent guard**
(`confirm_skill_fit`, phase `navigate:intent`): an action comparison at
`navigation.intent_tau` asking whether the skill performs the same action the
request asks for. Same → run it; different → author a new leaf in that
category. An empty (or single-skill) category skips the softmax and goes
straight to the guard.
(`confirm_skill_fit`, phase `navigate:intent`): at `navigation.intent_tau` it
decides what the skill does for the request, given the steps already taken
(the run ledger is part of its state). `same` (it performs the next action the
request needs) or `part` (the request needs more than one action and this
skill performs one required part) → run it; `different` (it does no action the
request asks for) → author a new leaf in that category. The guard only decides
whether the skill contributes; whether more work remains is `assess:outcome`'s
call. An empty (or single-skill) category skips the softmax and goes straight
to the guard.
- Both guards are deliberately permissive; with real descriptions the in-scope
cases score 0.9–1.0, so a borderline over-cover routes into a plausible
category and the leaf guard catches it.
@@ -151,12 +155,18 @@ observe baseline → act → observe outcome → assess
a live candidate set) are returned on `ActionResult.decisions` and logged as
training rows with the run outcome.
- `assess` is a **SemIf decision**, not generation:
- `assess:outcome` — success/failure at `tau`; its state includes the resolved
inputs (secrets redacted) so a wrong resolution is visible.
- `assess:requeue` — on failure, `complete` vs `retry` (bounded by
`max_reentries`).
- `assess:outcome` — is there any *additional work* to satisfy the request?
Three outcomes at threshold precedence `failed > done > continue`: `done`
(request satisfied), `continue` (this step worked but more work is needed →
the scheduler routes the logical next step with a bounded run ledger),
`failed` (the step errored → the repair path). Its state includes the skill
action, the goal, the resolved inputs (secrets redacted), the bounded action
log, and the steps already taken.
- The run summary is **deterministic** (same inputs ⇒ same string):
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
- Every skill's output is bounded to one **speakable budget** (`chain.result_chars`,
~300 chars): the result string and its run-ledger entry. A long product belongs
in a file I/O side effect, not the result (see `CODEGEN.md`).
- A skill can pause for human input two ways: `act` returns `needs_input` (act
re-runs on resume, with `request.user_input` set), or — for a contract
variable the runner cannot satisfy — a **pre-act** pause collects config
@@ -168,24 +178,28 @@ When navigation chooses a create branch, the scheduler queues the draft to a
single-slot `llm` worker and the body write to a separate single-slot codegen
worker. It is **asynchronous**, so the gate stays free while either model thinks:
1. **Stub.** The small `llm` provider (`generate_skill`) authors a title +
description on its own worker. The stub is registered and hot-merged into the
running tree as
soon as it lands; a `skill_writing` trace event is emitted.
2. **Elicitation** (`generate_elicitation`, default on): implementation
questions — which service/account, how to connect, where the credential
comes from, what success looks like. Every front end (REPL, dashboard,
gateway) defers to a question queue and the worker waits
(`codegen.elicitation.wait_timeout`).
3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
1. **Spec.** The small `llm` provider (`generate_skill_spec`) authors a title +
description **and a de-identified, reusable goal** (plus the generic
service/transport) on its own worker. The stub is registered and hot-merged
into the running tree as soon as it lands; a `skill_writing` trace event is
emitted. The goal is the *only* task data codegen is ever shown.
2. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
(`codegen`, your configured code-capable model) writes a single `act` against `CODEGEN.md`,
reading every operational value from `ctx.config` and declaring `INTEGRATION`
(service / transport / config_vars) plus its own flat `CONTRACT`
(variable → description; every key must be read from `ctx.config`).
(variable → description; every key must be read from `ctx.config`). **Privacy:**
codegen is the primarily-cloud model, so it receives only the de-identified
spec — never the user's request, question answers, or run output.
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
static `integration_findings`): is the action real, or simulated? One
corrective regen with the raw evidence bundle, then accept-with-badge
(`unverified`) rather than hard-fail.
static `integration_findings`): does the body contain a concrete,
side-effecting operation that really performs its goal? The state carries the
**whole** body (never a prefix) plus a deterministic operation inventory and
the de-identified goal — never the raw request — and asks the positive
question rather than asking the model to prove a negative. Because a decision
ingests the body whole, generated artifacts are size-bounded
(`max_body_chars`/`max_test_chars`, derived from the engine's context). One
corrective regen with the de-identified evidence bundle (inventory + findings
included), then accept with a trace rather than hard-fail.
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
constant — a flat map of snake_case variable name → semantic description, for
user input and SemIf only; `contract.json` is a persisted mirror.
@@ -203,9 +217,9 @@ onto the new leaf. On failure the leaf stays a restartable stub. A whole new
category runs the same chain deterministically:
`create_category` → `create_skill` → async body → re-dispatch.
A rejected/simulated body is traced (`fidelity_review`), badged `unverified`,
and never blocks authoring. Codegen failures (including timeouts) surface as a
graceful stub and are retryable with `restart <category> <skill>`.
A rejected/simulated body is traced (`fidelity_review`) and never blocks
authoring. Codegen failures (including timeouts) surface as a graceful stub and
are retryable with `restart <category> <skill>`.
### What each model sees
@@ -218,11 +232,13 @@ forward pass. There is no hidden system prompt and no growing conversation:
what you see in the table below is the entire input. Probabilities are
conditional on exactly the supplied options.
A **generative call** (`llm` for titles/descriptions, `codegen` for bodies and
tests) is a built OpenAI-style `messages` list. Its context is assembled from
the request, the tree, the elicitation answers, the runtime **bridge catalog**
(`describe_bridges()`), and — for bodies and tests — the contract files
(`CODEGEN.md`, `TESTGEN.md`).
A **generative call** (`llm` for titles/descriptions/goals, `codegen` for bodies
and tests) is a built OpenAI-style `messages` list. The trusted local `llm`
context is assembled from the request and the tree; the **codegen** context is
assembled only from the de-identified spec (goal + generic service/transport),
the tree, the runtime **bridge catalog** (`describe_bridges()`), and — for bodies
and tests — the contract files (`CODEGEN.md`, `TESTGEN.md`). Codegen never
receives the user's request, question answers, or run output.
#### SemIf decisions
@@ -232,11 +248,10 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog**
| `navigate:leaf` | `skills.py:736` | request text + current category | every skill name + description (+ `create_skill`) |
| `navigate:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) |
| `navigate:intent` | `skills.py:811` | `Requested action: <text>` + `Action of the existing skill: <description>` | `same` / `different` |
| `assess:outcome` | `skill.py:257` | skill label + goal + action log | `success` / `failure` |
| `assess:requeue` | `skill.py:279` | skill label + goal + action log + `outcome: failed` | `complete` / `retry` |
| `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
| `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` |
| `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` |
| `authoring:fidelity` | `scheduler.py:1836` | skill, goal, description, `INTEGRATION` JSON, static findings, operation inventory, **whole** body (no raw request) | `accept` / `reconsider` |
| `repair:choice` | `scheduler.py:658` | skill, request, integration, truncated failure | `retry` / `repair_skill` / `ask_user` / `no_repair` |
| degeneration watchdog¹ | `cli.py:128` | `[codegen <model>]` + last 2000 chars of the stream | `continue` / `stop` |
| `codegen_regen`¹ | `cli.py:165` | `[testgen <model>]` + last 1200 chars of the test error | `regen_code` / `regen_test` / `regen_contract` |
@@ -248,23 +263,22 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog**
| Call | Client | System context | User context | File |
| --- | --- | --- | --- | --- |
| `generate_category` | `llm` | authoring instruction: propose one broad category, JSON-only | request text + full tree summary | `skills.py:896` |
| `generate_skill` | `llm` | authoring instruction: propose one specific skill, JSON-only | request + category + existing skill names | `skills.py:947` |
| `generate_skill_body` | `codegen` | full **CODEGEN.md** | request, category, name, description, existing skills + tree summary, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:156` |
| body retry | `codegen` | full **CODEGEN.md** | rejection reason, request, category, name, description, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:474` |
| `generate_elicitation` | `codegen` | elicitation instructions + example questions + anti-patterns + `max_questions` | request, category, name, description, existing skills + tree summary, **bridge catalog** | `codegen.py:580` |
| `generate_data_contract` | `codegen` | full **TESTGEN.md** | skill, request, full body code, **bridge catalog** + the contract ask | `codegen.py:833` |
| `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, request, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
| `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, request, description, **raw evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` |
| `generate_skill_spec` | `llm` | authoring instruction: propose one specific skill + a **de-identified goal** and generic service/transport, JSON-only | request + category + existing skill names | `skills.py:947` |
| `generate_skill_body` | `codegen` | full **CODEGEN.md** | **de-identified spec** (goal + description), category, name, existing skills + tree summary, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:156` |
| body retry | `codegen` | full **CODEGEN.md** | rejection reason, de-identified spec (goal + description), integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:474` |
| `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
| `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, de-identified goal + description, **de-identified evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` |
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py:33`): each
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py`): each
known bridge's name, service, description, base-URL config var, auth header +
token var, documented config vars, and endpoints. It is the single runtime
source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic
pattern — so a bridge can be added without touching either contract file.
pattern — so a bridge can be added without touching either contract file (a
bridge ships with its pack; the registry discovers it by convention).
The **raw evidence bundle** handed to a corrective regen carries the request,
description, requirements, the observed failure fields (error, action log, new
state, summary) and the previous body, rendered as-is with no prose diagnosis.
The **evidence bundle** handed to a corrective regen is de-identified: a generic
failure kind, the integration, the goal, and the previous body, rendered as-is
with no prose diagnosis. It carries no request text and no run output.
### Data contracts and tiered config
@@ -329,7 +343,7 @@ fine-tuning loop — it is not yet the fine-tune itself.
to the closed `response` canned tree.
- **Real integrations by construction** — bodies must perform the real action,
read data from `ctx.config`, declare `INTEGRATION`, and report real failures.
- **Async skill authoring** — elicitation → body → fidelity → contract → test →
- **Async skill authoring** — spec → body → fidelity → contract → test →
auto-run, with a SemIf regeneration ladder on test failure. Gate stays free.
- **Tiered config + first-fire collection** — global/category/skill config with
a `record-vs-ask` decision per answer.
@@ -338,14 +352,21 @@ fine-tuning loop — it is not yet the fine-tune itself.
with prompt hashes, tokens and timing.
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
Redux-DevTools-style dashboard.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM.
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM,
including Sideband push-to-talk **voice messages** on LXMF (local transcription,
and voice replies synthesized with Piper).
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
of third-party systems, so generated bodies never speak native protocols.
- **Seeds** — shipped real starter skills: `calendar.create_event` (the
authoritative worked example), `calendar.next_event` (Nextcloud CalDAV), and
`simplex.next_message` / `simplex.connect_link`.
- **Standalone bridge services** — an optional token-guarded localhost HTTP
layer for third-party systems that need state/auth, a native protocol, or a
sanitized surface; a plain HTTP API is called directly.
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`,
`calculator.calculate` (two operands, one SemIf-chosen operator, spoken answer),
and `skills.list_categories` / `skills.list_skills` (report the agent's own
skill categories, or the skills inside a named category).
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed.
@@ -365,7 +386,7 @@ semif_agent/
summary; pre-act contract collection; resolved-input state
skills.py tree + registry, canned `response` tree, navigation,
create gates, intent guard, tiered config resolution
codegen.py OpenAI-compatible client; body/elicitation/test generation;
codegen.py OpenAI-compatible client; body/test generation;
parse/validate; CONTRACT + INTEGRATION extraction; test runner
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog);
SemIfEngineClient generates text from the in-process engine
@@ -384,15 +405,31 @@ semif_agent/
voice_transport.py neutral voice transport: mic capture, wake word, VAD,
speech-to-text (faster-whisper), text-to-speech (Piper)
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud)
seeds/ committed starter skills (calendar, simplex)
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
requirements/ staging.txt — the pinned engine deps
bridges/ bridge contract + discovery (base.py, registry.py, inbox.py,
llm.py); the concrete bridges ship in their packs
config.py layered config: index includes + !secret + schema/example
packs.py SkillPack + PackRegistry (bundles skills by concern/bridge)
packs/ skill packs, each cloned from its own repo (pack.<name>)
into this gitignored dir — each ships its own bridge/ — the
pack list lives in the semif-packs index repo (see PACKGEN.md)
scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in
requirements/ core.txt (test runner), engine.txt (local decision engine),
transports.txt (websockets/lxmf), voice.txt (microphone
stack), transcribe.txt (faster-whisper, LXMF voice
messages), tts.txt (piper-tts + PyAV, LXMF voice replies),
codec2.txt (pycodec2, LXMF Codec2 PTT);
staging.txt = union of the non-hardware files;
a pack's own deps live with the pack at
packs/<name>/requirements.txt
tests/ stdlib unit tests + tests/integration (real engine + LLM)
CODEGEN.md the contract fed to the skill-body codegen model
TESTGEN.md the contract fed to the test/contract codegen model
PACKGEN.md the contract for authoring a skill pack (packs/<name>/)
AGENTS.md the operational guide (read this before touching code)
config.example.json per-machine config template (seeded to config.json once)
config.json per-machine config INDEX ({"include": [...]}); seeded once
config/ split config fragments (core, gateway, bridges, packs/*)
secrets.json gitignored credentials, referenced as "!secret <key>"
config.example.json GENERATED per-machine config reference (from the schemas)
pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs
local/ gitignored: this deployment's notes (hosts, addresses, models)
```
@@ -402,30 +439,43 @@ local/ gitignored: this deployment's notes (hosts, addresses, model
## Installation
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
decision engine, a pinned GGUF, and an OpenAI-compatible endpoint for codegen.
`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree
in the checkout.
decision engine (local or remote). `scripts/bootstrap.sh` provisions what this
machine needs inside a gitignored `.runtime/` tree in the checkout — and only
what it needs, based on the answers to a short first-run interview.
### Prerequisites: ollama models
### Prerequisites: the decision engine, and optional models
Two OpenAI-compatible endpoints (usually ollama), which may be on different
machines:
The **decision engine** routes every request. It runs one of three ways,
chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run
`scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because it
is slower on CPU).
**Skill authoring is opt-in** (`new_skill_creation`: `deny` by default). When it
is off, no `llm`/`codegen` endpoint is needed at all — the agent only runs the
shipped packs. When it is on, two OpenAI-compatible endpoints are required
(usually ollama, possibly on different machines):
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host.
- **`llm`** — a small, fast model that authors the title + description of a
newly created category/skill. Deliberately its own endpoint/model, so it can
stay local even when `codegen` is remote; it uses the same provider transport
(`provider.py`) and an unreachable endpoint is graceful (the request is not
re-dispatched), never fatal. Its `provider` can be `"ollama"` (default),
newly created category/skill. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no
`llm.model` at all (see the `llm.semif` block in `config.json`).
The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU
by default; to offload it to a GPU, set `engine.gpu_layers` in `config.json` and
run `scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because
it is slower on CPU).
`llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host.
### Option A: one-command provisioning (`bootstrap.sh`)
@@ -435,41 +485,63 @@ On a fresh Ubuntu machine, from a checkout of this repo:
scripts/bootstrap.sh
```
With no `config.json` yet, the script seeds one from `config.example.json`; edit
it to set `llm.model`/`codegen.model` (and the endpoints). Flags override those
values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`,
`--codegen-model` — and are never written back to `config.json`.
On a fresh machine the script **asks a few questions** and writes this machine's
config from the answers:
The script is idempotent (every stage no-ops on existing state) and:
1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index
repo (`semif-packs`): SimpleX, browser, Nextcloud, Outlook, Gutendex (the
`essentials` pack is always on). Only the packs you pick are cloned.
4. **Gateways** — how you talk to the agent: SimpleX, LXMF, voice (or none —
REPL + dashboard only).
5. **Timezone** — an IANA name for timers and reported times.
It then installs **only what those answers require**. Both ends of the spectrum
are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator, skill listing). No account, no network, no gateway, no heavy
downloads.
- **maximum** — every pack, a remote Winnow or Ollama System One decision
engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is
idempotent — on a rerun the interview is **skipped** and the existing config is
used; pass `--reconfigure` to re-run it. `--voice` / `--browser` additionally
install those optional stacks even if the plan did not pick them.
The script:
1. installs system prereqs + enables linger;
2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine;
3. creates `.runtime/venv` and installs the pinned deps from
`requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since
the llama.cpp path never imports torch);
4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`;
5. pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads and sha256-verifies the pinned `simplex-chat` binary;
7. seeds `config.json` from `config.example.json` **only if it does not already
exist** — it never rewrites `config.json` (only a human edits that file);
8. renders and enables systemd **user** units:
`semif-simplex` (bot daemon), `semif-gateway` (agent gateway),
`semif-simplex-forward` (the bridge's own daemon), `semif-bridge`;
9. prints the bot's SimpleX contact address.
2. clones/updates the skill packs, then runs the setup interview and writes
`config/` + `secrets.json` (first run or `--reconfigure`);
3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the
SemIf engine;
4. creates `.runtime/venv` and installs only the needed dep files:
`requirements/core.txt` always, `engine.txt` for a local engine,
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for
the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
plus `tts.txt` when `voice.reply_with_voice` is on, and `codec2.txt` + system
`libcodec2` best-effort for non-HQ Codec2 PTT — and each selected pack's own
`packs/<name>/requirements.txt` — e.g. the browser pack's Playwright deps);
5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
and pre-fetches the HF tokenizer into `.runtime/hf/`;
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
SimpleX gateway or the simplex pack is selected;
7. renders and enables only the systemd **user** units the answers need
(`semif-simplex` bot daemon, `semif-gateway` agent, `semif-simplex-forward`
bridge daemon, `semif-bridge`), retiring any a reconfigure dropped;
8. prints the SimpleX contact address(es) when those services are active.
Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`,
`--copy-data SRC`) override the values read from `config.json` for that run only.
`--voice` additionally installs the optional voice-gateway stack
(`requirements/voice.txt` + system PortAudio) and downloads its models (the
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into
`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache).
Run `scripts/bootstrap.sh -h` for the full list.
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`,
warning (never auto-pulling) if the remote codegen host is missing its model.
Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision,
simplex-chat version/url+sha256) live in the committed `pins.json`, not in
`config.json`.
Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it
pulls `llm.model` from the target host's ollama when configured, and never
auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF
tokenizer revision, simplex-chat version/url+sha256) live in the committed
`pins.json`, not in `config.json`.
### Option B: core only (stdlib)
@@ -480,55 +552,78 @@ python3 -m pytest tests/ -q --ignore=tests/integration
```
For a full install on a machine you manage, follow the same steps bootstrap
performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF,
tokenizer cache), then create `config.json` from the template and adjust paths:
performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF,
tokenizer cache), then generate the split config:
```sh
cp config.example.json config.json
python -m semif_agent.cli setup --interview # or --yes / --answers FILE
python -m semif_agent.cli config-init # schema defaults, no interview
```
### Configuration
`config.json` is **gitignored, per-machine, and required** — the agent refuses
to start without it. `scripts/bootstrap.sh` seeds it from `config.example.json`
once; afterwards only a human edits it (nothing writes `config.json`). Pinned
external refs live in the committed `pins.json`, so `config.json` holds only
per-machine settings:
The per-machine config is **gitignored, per-machine, and required** — the agent
refuses to start without it. `config.json` is a thin **index**
(`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments
under `config/` hold the values and are deep-merged in order. Credentials live in
the gitignored `secrets.json` and are referenced from any fragment as
`"!secret <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` runs
`setup` to generate the split config from your answers; afterwards only a human
edits it (`--reconfigure` re-runs the interview).
```sh
cp config.example.json config.json # if not already created by bootstrap
python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli config-init # seed schema defaults (no interview)
python -m semif_agent.cli check-config # validate against the schemas
```
The committed `config.example.json` is **generated** from the core schema
(`semif_agent/config.py`) and each pack's `config` schema; regenerate it after
changing a schema:
```sh
python -m semif_agent.cli check-config --write-example config.example.json
```
Pinned external refs live in the committed `pins.json`, so the config holds only
per-machine settings.
Key blocks:
| Block | What it controls |
| --- | --- |
| `engine` | per-machine engine settings: backend, context, threads, optional GGUF path override (refs come from `pins.json`) |
| `llm` | small model endpoint that authors new category/skill title + description |
| `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget |
| `codegen` | skill-body model endpoint, timeouts, sampler, approval gate, fidelity, repair, test, degeneration watchdog, token budget |
| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
| `tau` | decision threshold; `max_reentries` requeue bound |
| `queue` | `max_size` |
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD, follow-up window |
| `gateway.lxmf` | LXMF gateway: allowlist, Reticulum paths, `result_only` replies, Sideband voice transcription (`voice.enabled` + `voice.stt` model) and voice replies (`voice.reply_with_voice` + `voice.tts` voice) |
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
| `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) |
| `bridges.browser` | Browser bridge: host/port/token + Playwright settings (engine/headless/profile dirs) |
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port |
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` /
`nextcloud_bridge_url` / `outlook_bridge_url` (+ their `_token`) from
`nextcloud_bridge_url` / `outlook_bridge_url` / `browser_bridge_url` (+ their
`_token`) from
`ctx.config`; each is **derived** at startup from its `bridges.<name>`
host/port/token, so there is no duplicate top-level key to keep in sync. A bridge
with no block (or no port) leaves the variable unresolved and the operator is
asked for it.
`llm.model` and `codegen.model` are **required** (no default): set each to a
model its endpoint serves. A missing model fails fast at startup with a clear
config error rather than sending a request to a model that isn't there.
`llm.model` and `codegen.model` are **required only when authoring is enabled**
(`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves.
An empty `codegen.model` means "no authoring path" — the minimum config leaves it
empty and the agent simply runs the shipped packs. With authoring on, a missing
model fails fast at startup with a clear config error rather than sending a
request to a model that isn't there.
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
@@ -544,6 +639,7 @@ Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
All subcommands go through the CLI:
```sh
python -m semif_agent.cli setup --interview # generate config/ from answers
python -m semif_agent.cli run # interactive REPL
python -m semif_agent.cli run --script inputs.jsonl
python -m semif_agent.cli dream # cost report
@@ -626,7 +722,7 @@ without it). `allowed_users` entries match a numeric contactId or a display
name. The daemon must run in **bot mode** (`simplex-chat -p PORT
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
"chat relay" and yield a relay address, not a user contact address. Add the
bot's contact link to reach it: `scripts/simplex-address.py` shows/creates it
bot's contact link to reach it: `packs/simplex/scripts/simplex-address.py` shows/creates it
(bootstrap prints it), and the gateway prints it once on connect.
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
@@ -640,6 +736,32 @@ matches the peer's LXMF address (32 hex) or a best-effort display name.
and an optional `propagation_node` enables store-and-forward. Add the printed
address as a contact in your LXMF client and DM it.
**Voice commands (Sideband push-to-talk).** Set
`gateway.lxmf.voice.enabled: true` and a Sideband PTT voice message is
transcribed into a command, just like typed text. HQ PTT (Opus/OGG) is decoded
and transcribed by faster-whisper, which needs only `requirements/transcribe.txt`
(installed by the install plan — no microphone, no voice stack). Non-HQ Codec2
PTT is decoded by the optional `pycodec2` bindings (`requirements/codec2.txt`,
installed best-effort alongside the system `libcodec2`); without it a Codec2
message is reported back rather than dropped. The audio is transient and never
leaves the machine. The model is `gateway.lxmf.voice.stt.model` (default
`base.en`).
**Voice replies.** With `gateway.lxmf.voice.reply_with_voice: true` (the
default), a chat that last messaged by voice is answered with a synthesized
voice message: the reply text is spoken with Piper and sent back as a Sideband
HQ push-to-talk message, with the text also carried as the message content so a
text-only client still sees it. A later text message from that chat reverts it to
text replies. This needs only `piper-tts` + PyAV (`requirements/tts.txt`,
installed by the install plan — still no microphone); a missing stack or a
synthesis failure falls back to a text reply rather than dropping it. The voice
is `gateway.lxmf.voice.tts.voice` (default `en_US-lessac-medium`).
**Result-only replies.** The LXMF gateway sends only the skill's result line:
the scheduler's queue/urgency bookkeeping is dropped and the `<skill>: ok —`
wrapper is stripped, so a DM is the answer, not the internals. Override with
`gateway.lxmf.result_only: false` for the full scheduler output.
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
> replies — nothing else. It never reads history, shows or creates invite links,
> or composes messages. That is messaging UX and lives in the bridges.
@@ -666,18 +788,32 @@ python -m semif_agent.cli gateway --platform voice
PortAudio has no volume control — use `alsamixer`/`amixer` (then
`sudo alsactl store`) to unmute and set the mic/speaker levels.
- **Models.** `gateway.voice.wake.model` is an openWakeWord model (default
`hey_mycroft`), `stt.model` a faster-whisper size (default `base.en`), and
`hey_computer`, spoken phrase "Hey Computer"), `stt.model` a faster-whisper
size (default `base.en`), and
`tts.voice` a Piper voice (default `en_US-lessac-medium`). Bootstrap downloads
the openWakeWord models into the venv's package dir (under `.runtime/venv`)
and the Piper voice into `.runtime/voice/tts`; the faster-whisper model lands
in the `.runtime/hf` cache.
the official openWakeWord models into the venv's package dir (under
`.runtime/venv`) and the Piper voice into `.runtime/voice/tts`; the
faster-whisper model lands in the `.runtime/hf` cache. openWakeWord ships no
"computer" model, so the default is a **pinned community model**
(openWakeWord-compatible, sha256-checked in `pins.json`) that
`scripts/voice-models.py` fetches into `.runtime/voice/wake`, where the
detector resolves it via `wake.model_dir`. Set `wake.model` to an official
name (e.g. `alexa`) or a path to switch. Because the community model's scores
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
official models score ~0.99 and use `0.5`).
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
the agent never transcribes itself (no barge-in yet). A short beep plays when
the wake word fires (`gateway.voice.cue`), so you know you're being heard; set
`cue.submit_frequency > 0` for a second beep once the utterance is
transcribed. After a reply, the next
utterance is accepted **without** the wake word for `follow_up_window_s`, so
answering a question is conversational. `max_speak_chars` truncates long
the agent never transcribes itself (no barge-in yet). The wake word is required
before every command and is held while the scheduler is still running the
current request, so a second command cannot start until the first reaches a
result. A short beep plays when
the wake word fires (`gateway.voice.cue`), so you know you're being heard; a
short multi-note "bling" (`cue.submit_notes`, each entry
`[frequency_hz, duration_ms]`, spaced by `cue.note_gap_ms`) plays once the
utterance is transcribed. (Set `cue.submit_notes` to `[]` and
`cue.submit_frequency > 0` for the older single submit beep.) After the wake
word, capture waits `listen_timeout_s` for the command to begin, so a pause before speaking
(e.g. while the cue beep plays) does not truncate it. `max_speak_chars`
truncates long
replies before speaking. `result_only` (default true for voice) speaks only the
skill's result line — scheduler bookkeeping is dropped and the
`<skill>: ok —` wrapper is stripped — so the spoken output is the answer, not
@@ -692,11 +828,13 @@ python -m semif_agent.cli gateway --platform voice
`cli bridge` runs standalone bridges: each is a process that stands up a small,
token-guarded localhost HTTP API in front of one third-party system (and, where
the system needs one, owns its own daemon/profile). Generated skill bodies call
them like any HTTP service (base URL from a config var), so they never speak a
native protocol directly.
the system needs one, owns its own daemon/profile). A bridge is a deliberate
choice for a system that needs state (especially auth state), a native or heavy
protocol, or one sanitized surface — a skill may call a plain HTTP API directly.
When a bridge fronts a service, generated skill bodies call it like any HTTP
service (base URL from a config var) and never speak the native protocol.
The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own
The first bridge is **SimpleX** (`packs/simplex/bridge/simplex.py`), with its own
simplex-chat daemon separate from the gateway's. Its HTTP surface:
```
@@ -718,10 +856,11 @@ acking is a client-side read receipt, not an API call.
Skills call the forwarding bridge at the address derived from `bridges.simplex`
(`simplex_bridge_url`); the bridge catalog
is injected into every codegen prompt via `describe_bridges()`, so it is the
single source of bridge specifics. Adding a bridge = a class + a config block +
a `CATALOG` entry.
single source of bridge specifics. Adding a bridge = a pack that ships its
`bridge/<name>.py` + a config block; the core registry discovers it by convention.
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the shared, pack-less one: a
generic
```
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
@@ -737,17 +876,18 @@ carries just the local listener. Skills call it at the address derived from
it returns `502`, never a fabricated reply. It starts in the same
`semif-bridge.service` process as the other enabled bridges.
The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it
The **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py`) is the third: it
wraps the account's native protocols — WebDAV files, CalDAV calendar events and
tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a
body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is
plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
in the same `semif-bridge` process. The connection (base URL, username, app
password) is configured in `bridges.nextcloud` and falls back to the top-level
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` /
`nextcloud_default_calendar` the calendar seeds use, so the account is
configured once. Skills call it at the address derived from `bridges.nextcloud`
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface:
password) is configured in `bridges.nextcloud`; `NextcloudBridge.from_config`
also accepts the top-level `nextcloud_url` / `nextcloud_username` /
`nextcloud_app_password` / `nextcloud_default_calendar` as a fallback for a
hand-edited config, with a block value winning. Skills call it at the address
derived from `bridges.nextcloud` (`nextcloud_bridge_url`, + optional
`nextcloud_bridge_token`). Its HTTP surface:
```
GET /health
@@ -759,8 +899,8 @@ GET /files/read?path=<path> # text, or base64 for binary
GET /files/search?query=<text>&path=<dir>
POST /files/write {"path","content","encoding"?,"overwrite"?}
POST /files/mkdir | /files/delete | /files/move | /files/copy
GET /calendars
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT
GET /calendars # includes "default" (configured default name)
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT; recurrences expand with a window
POST /calendars/events | /calendars/events/update | /calendars/events/delete
GET /tasks?calendar=<name> # CalDAV VTODO
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
@@ -776,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
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,
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
so it starts instantly in the same `semif-bridge` process. Authorization is the
OAuth2 **device code flow**: register an Entra ID public-client app, put its
`client_id` in `bridges.outlook`, and run `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
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
@@ -811,11 +951,55 @@ POST /files/write {"path","content","encoding"?,"overwrite"?}
A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure
(transport, HTTP error, or a bad reply) is `502` — never a fabricated success.
Seven `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`);
`send_message` composes the message through the LLM bridge and asks for
confirmation before it sends.
The **browser bridge** (`packs/browser/bridge/browser.py`) is real browser
automation via **Playwright**: open a URL, read a page's text or links, take a
screenshot, and click/fill/press/select to complete a flow. It is the first
bridge with a heavy optional dependency, so it is **disabled by default** and
installed with `scripts/bootstrap.sh --browser` (Playwright + Chromium land under
`.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch).
If `playwright install` fails — notably on a host with an IPv6 address but no
global IPv6 route, where Playwright's downloader prefers IPv6 and hangs —
bootstrap falls back to `packs/browser/scripts/playwright-browsers.py`, which downloads the
same pinned artifacts over IPv4. To skip the managed download altogether, set
`bridges.browser.channel` (a Playwright channel such as `chrome`/`msedge`) or
`bridges.browser.executable_path` (a browser binary) to use an already-installed
browser.
Unlike the others it owns a browser and keeps a **persistent profile**
(`.runtime/browser/profile`) so a login you do once survives across calls and
restarts — the browser analog of the SimpleX bridge owning its own daemon
(`POST /reset` with `purge=true` wipes it). A dedicated event-loop thread runs
Playwright's async API and serializes whole operations, because the sync API is
bound to its creating thread and the bridge serves each request on a new one.
`check_requirements()` never blocks startup, so a host without Playwright still
runs every other bridge; a missing package/browser is a `503` install hint on the
call, and a real navigation/timeout/selector failure is a `502`. Skills call it
at the address derived from `bridges.browser` (`browser_bridge_url`, + optional
`browser_bridge_token`). Its HTTP surface:
```
GET /health
GET /state # current url + title
GET /content?format=text|html&max_chars=<n> # whole page's rendered text
GET /text?selector=<css> # text of matching elements
GET /links?query=<text>&limit=<n> # anchors (label + href)
GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool>
POST /goto {"url","wait_until"?,"timeout"?}
POST /click {"selector"?|"text"?,"index"?,"timeout"?}
POST /fill {"selector","value","submit"?,"timeout"?}
POST /press {"key","selector"?,"timeout"?}
POST /select {"selector","value"?|"label"?,"timeout"?}
POST /wait {"selector"?|"text"?,"timeout"?}
POST /back | /forward {"timeout"?}
POST /reset {"purge"?} # close; purge deletes the profile
```
Three `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`).
### Dream report
```sh
@@ -851,24 +1035,49 @@ bodies, no external network, no `mock_data.json`. Passing it proves the code
runs, not that the live integration works. That is what the real run and the
repair loop are for.
**Seeds** (`seeds/`) ship real starter integrations in the exact generated
folder format, plus a `manifest.json`. `merge_seed_store` loads them into every
tree at startup; recorded config is written to the runtime store, so the
committed seed never holds secrets.
**Packs** ship real starter integrations in the exact generated folder format,
plus a `manifest.json` and a `pack.json` manifest binding the concern to its
categories, bridge, and config schema. Each pack lives in its **own repository**
(`pack.<name>`, listed in the `semif-packs` index repo); `scripts/bootstrap.sh` clones them into
the gitignored `packs/<name>/`, and `merge_packs` loads every enabled pack into
the tree at startup. Recorded config is written to the runtime store, so a pack
repo never holds secrets. `PACKGEN.md` is the authoritative contract for
authoring a new pack (and a new bridge to back one).
- `calendar.create_event` — create an event on Nextcloud CalDAV (the
authoritative worked example); resolves the target calendar with a SemIf
choice over the owned calendars (strong winner, else the configured default);
config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`,
`nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`,
`llm_bridge_token`).
- `calendar.next_event` — next upcoming event from Nextcloud CalDAV (recurring
events expanded server-side); config vars `nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`.
- `nextcloud.create_event` — create an event on the user's Nextcloud calendar
through the Nextcloud bridge (`GET /calendars`, `POST /calendars/events`);
resolves the target calendar with a SemIf choice over the owned calendars
(strong winner, else the configured default); config vars
`nextcloud_bridge_url`, `nextcloud_bridge_token`, plus the LLM bridge
(`llm_bridge_url`, `llm_bridge_token`).
- `nextcloud.next_event` — next upcoming event through the Nextcloud bridge
(`GET /calendars`, `GET /calendars/events`; recurring events expanded
server-side); config vars `nextcloud_bridge_url`, `nextcloud_bridge_token`.
- `nextcloud.create_task` — add a task to a Nextcloud task list through the
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
`llm_bridge_token`.
- `simplex.next_message` — read the next unread message via the forwarding
bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`,
`simplex_default_contact`.
- `simplex.send_message` — send a message to a contact resolved over the
bridge's contact list (a SemIf choice, defaulting to the configured contact);
config vars `simplex_bridge_url`, `simplex_bridge_token`,
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
`llm_bridge_token`) to write the text when the request states none.
- `simplex.connect_link` — show/create the forwarding bot's contact link.
- `calculator.calculate` — evaluate a bounded arithmetic request (two operands,
one operator) and speak the answer in words; the operator is a SemIf choice
over addition, subtraction, multiplication, division, exponents, squares,
cubes, square roots, cube roots, fractions, and percentages, and SemIf picks
the operands when the request writes more numbers than the operation needs
(pure local compute, no config).
- `skills.list_categories` — list the categories of skills the agent has
(pure local compute, no config; reads the read-only `ctx.catalog`, not the
housekeeping-only `ctx.admin`).
- `skills.list_skills` — list the skills inside a category named in the request
("list skills in nextcloud"), asking for one when it is missing and reporting
an unknown category honestly (pure local compute, no config).
---
@@ -898,11 +1107,11 @@ works.
**Done.** Core loop, FIFO queue, skill tree, real SemIf assessment, decision
logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` /
`create_skill` with the async authoring pipeline (elicitation → body → fidelity →
`create_skill` with the async authoring pipeline (spec → body → fidelity →
contract → test → auto-run → re-dispatch); tiered config + first-fire
collection; runtime repair loop; the closed `response` canned tree; real
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message
standalone SimpleX bridge + pack skills (contact-list refresh, daemon-backed message
history / true unread); the LXMF gateway; and the voice gateway (wake word +
speech-to-text + text-to-speech).
+16 -6
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
generated from the finished body rather than the other way around.
The pack that ships a skill as a committed starter — its manifest, categories,
bridge reference, and config schema — is the separate contract `PACKGEN.md`.
A finished skill leaf is a folder
`data/skills/<category>/<name>/` containing (among others) two artifacts:
@@ -26,6 +29,12 @@ integration, and the agent offers to fix the skill when that real run fails. A
test must never be "fixed" by simulating the action or by weakening an
assertion, and a simulated body is broken even if every test passes.
A skill's result is **bounded** to one speakable budget (it is read in a chat
message or spoken aloud; `chain.result_chars`, ~300 characters). Do not assert a
long/detailed payload: a skill whose real product is long or structured writes it
to the service or a file as a side effect and returns a short summary plus a
pointer. Order by the skill's own contract, not the fixture's size.
## contract.json
A **single JSON object**. Each key is the name of a variable the skill needs;
@@ -78,12 +87,13 @@ A stdlib-only Python script that:
Assert the server actually received the expected request (method, path,
headers, body) where practical. The loopback address exists only in the test;
the body must read its endpoint from config.
- For a messaging skill (a body that talks to a bridge service), stand up a
loopback server implementing the bridge endpoints the body uses (the bridge
catalog injected into this prompt lists them) and assert the body built the
real requests. If the catalog names an auth header, set the fixture token in
the fixture config and assert the body sent that header. Never connect to a
real service daemon or a live bridge.
- For a body that talks to a bridge service (or any fixed HTTP API), stand up a
loopback server implementing the endpoints the body uses (the bridge catalog
injected into this prompt lists a bridge's; for a direct HTTP API, mirror the
routes the body calls) and assert the body built the real requests. If the
catalog names an auth header, set the fixture token in the fixture config and
assert the body sent that header. Never connect to a real service daemon or a
live bridge.
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
resolution, argument construction, and error paths (missing or misconfigured
values) without performing the real I/O.
+179 -97
View File
@@ -1,21 +1,27 @@
{
"_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.",
"tau": 0.6,
"max_reentries": 3,
"creation_approval": false,
"query_recall_window": 30,
"new_skill_creation": "deny",
"verbosity": "result",
"chain": {
"result_chars": 300
},
"assess": {
"done_tau": 0.5,
"fail_tau": 0.5
},
"timezone": "",
"navigation": {
"_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then compares the winner's action to the request (phase navigate:intent, P(same) >= intent_tau) and a mismatch authors a new leaf. All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.",
"intent_tau": 0.6,
"category_tau": 0.75,
"action_tau": 0.5,
"softmax_bypass_tau": 0.5
},
"queue": {"max_size": 100},
"queue": {
"max_size": 100
},
"engine": {
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
"_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).",
"_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.",
"provider": "semif",
"backend": "llamacpp",
"context_tokens": 4096,
@@ -24,24 +30,33 @@
"gpu_device": null,
"gpu_split": 0,
"winnow": {
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
"base_url": "http://127.0.0.1:8091",
"model": "",
"api_key": "",
"api_key_env": "",
"context_tokens": 32768,
"api_key": "!secret engine_winnow_api_key",
"timeout": 120,
"retries": 0,
"user_agent": "semif-agent",
"extra_headers": {}
}
},
"ollama": {
"base_url": "http://127.0.0.1:11434",
"model": "",
"context_tokens": 16384,
"api_key": "!secret engine_ollama_api_key",
"timeout": 120,
"retries": 0,
"keep_alive": "",
"user_agent": "semif-agent",
"extra_headers": {}
},
"gguf": ""
},
"llm": {
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
"provider": "ollama",
"base_url": "http://localhost:11434/v1",
"model": "",
"api_key": "",
"api_key_env": "",
"api_key": "!secret llm_api_key",
"user_agent": "",
"timeout": 600,
"stream": false,
@@ -54,18 +69,15 @@
"frequency_penalty": 0.0,
"disable_thinking": true,
"semif": {
"_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.",
"temperature": 0.0,
"max_tokens": 256
}
},
"codegen": {
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
"provider": "ollama",
"base_url": "http://localhost:11434/v1",
"model": "",
"api_key": "",
"api_key_env": "",
"api_key": "!secret codegen_api_key",
"user_agent": "",
"timeout": 3600,
"stream": true,
@@ -83,31 +95,27 @@
"presence_penalty": 0,
"frequency_penalty": 1,
"max_attempts": 3,
"elicitation": {
"_comment": "Ask the product owner implementation questions before the body is written: which service/account, how to connect, where the credential comes from, what success looks like. Every front end defers questions to the questions panel; the single-slot writer asks them one at a time and waits answer_timeout seconds for each (the clock resets on every answer submit, so the user only ever sees the next question after answering the current one; a timeout stops the sequence). wait_timeout is the separate, longer wait for the optional creation-approval gate. Questions never ask for operational data values (collected at first fire) or config-vs-input cadence (the config step owns that).",
"enabled": true,
"max_questions": 4,
"answer_timeout": 30,
"approval": {
"wait_timeout": 900
},
"fidelity": {
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). Static INTEGRATION checks (declaration vs code) run alongside. The gate never diagnoses: a rejected body is regenerated with the raw evidence bundle, bounded by max_attempts; a still-fake body is accepted but traced/badged, never a hard authoring failure.",
"enabled": true,
"max_attempts": 1
"max_attempts": 1,
"tau": 0.6
},
"repair": {
"_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.",
"enabled": true,
"max_attempts": 1
},
"test_timeout": 30,
"test_max_attempts": 3,
"max_body_tokens": 0,
"max_test_tokens": 0,
"decision_reserve_tokens": 1024,
"contract_search": {
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
"enabled": true
},
"degeneration": {
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
"enabled": true,
"threshold": 0.9,
"interval": 8000,
@@ -116,80 +124,23 @@
}
},
"skill_bodies": "data/skills",
"skill_seeds": "seeds",
"log": "data/decisions.jsonl",
"trace": "data/runs.jsonl",
"category_registry": "data/categories.json",
"simplex_chat": {
"_comment": "Per-machine simplex-chat daemon settings. The pinned binary (version/bin_url/sha256) lives in the committed pins.json, not here. The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh renders both units from these values. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
"port": 5226,
"display_name": "semif",
"forward_port": 5228,
"forward_display_name": "semif-forward"
},
"bridges": {
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
"simplex": {
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
"enabled": true,
"host": "127.0.0.1",
"port": 5227,
"token": "",
"max_inbox": 100,
"ws_url": "ws://127.0.0.1:5228",
"user_id": 1,
"auto_accept": true,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
},
"llm": {
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": ""
},
"nextcloud": {
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_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
}
},
"gateway": {
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.",
"humanize": {
"_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `<skill>: <ok|failed> — <detail>` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.",
"enabled": true,
"timeout": 20.0,
"max_tokens": 200,
"max_chars": 600
},
"simplex": {
"_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. Groups/attachments are not supported.",
"enabled": true,
"ws_url": "ws://127.0.0.1:5226",
"allowed_users": [],
@@ -198,10 +149,13 @@
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
"reconnect": {
"initial": 1.0,
"max": 60.0,
"jitter": 0.2
}
},
"lxmf": {
"_comment": "LXMF (Reticulum) command adapter. Runs IN-PROCESS — there is no external daemon; `pip install lxmf` provides the transport (optional, lazy-imported; the gateway refuses to start with an install hint). The bot's reachable address is its LXMF delivery destination hash (32 hex chars), printed on connect. config_dir/storage_path hold Reticulum's config and the persisted identity under .runtime/lxmf/ so the address is stable across restarts (empty = the .runtime/lxmf defaults). allowed_users entries match the peer's LXMF address (32 hex chars) or a best-effort display name; default is deny-all unless allow_all_users is set. desired_method is 'direct' (reliable link) or 'opportunistic' (single packet). propagation_node is an optional LXMF propagation-node address (hex) for store-and-forward.",
"enabled": false,
"allowed_users": [],
"allow_all_users": false,
@@ -214,10 +168,33 @@
"storage_path": "",
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8
"text_batch_delay": 0.8,
"result_only": true,
"voice": {
"enabled": false,
"reply_with_voice": true,
"max_speak_chars": 600,
"reply_bitrate": 24000,
"read": {
"enabled": true,
"chunk_chars": 300
},
"stt": {
"model": "base.en",
"device": "cpu",
"compute_type": "int8",
"language": "en"
},
"tts": {
"voice": "en_US-lessac-medium",
"voice_dir": "",
"speaker_id": 0,
"length_scale": 1.0,
"volume": 1.0
}
}
},
"voice": {
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.",
"enabled": false,
"chat_id": "voice",
"display_name": "voice",
@@ -225,19 +202,33 @@
"reply_prefix": "",
"result_only": true,
"max_speak_chars": 600,
"follow_up_window_s": 5.0,
"read": {
"enabled": true,
"chunk_chars": 300
},
"listen_timeout_s": 3.0,
"cue": {
"_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.",
"enabled": true,
"frequency": 880,
"duration_ms": 120,
"volume": 0.9,
"submit_frequency": 0,
"submit_duration_ms": 100
"submit_duration_ms": 100,
"submit_notes": [
[
1046.5,
70
],
[
1568.0,
90
]
],
"note_gap_ms": 20
},
"wake": {
"model": "hey_mycroft",
"threshold": 0.5,
"model": "hey_computer",
"threshold": 0.2,
"inference_framework": "onnx",
"model_dir": ""
},
@@ -261,16 +252,107 @@
"frame_ms": 80,
"capture_sample_rate": 0,
"output_sample_rate": 0,
"dc_removal": true
"dc_removal": true,
"read_timeout_s": 1.0,
"stall_timeout_s": 5.0
},
"vad": {
"silence_ms": 500,
"min_speech_ms": 120,
"max_utterance_s": 30,
"min_command_ms": 700,
"initial_silence_ms": 1500,
"aggressiveness": 2,
"energy_threshold": 200.0
},
"follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
}
}
},
"dashboard": {"port": 8765, "host": "127.0.0.1"}
}
"dashboard": {
"port": 8765,
"host": "127.0.0.1"
},
"skill_packs": "packs",
"secrets_file": "secrets.json",
"_comment": "GENERATED from the core schema (semif_agent/config.py) and each pack's pack.json `config` schema \u2014 do not hand-edit; edit a pack's schema or the core schema. This is the reference example; the live per-machine config is split under config/ (see config.json's include list) and secrets live in the gitignored secrets.json, referenced as '!secret <key>'.",
"bridges": {
"llm": {
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": "!secret llm_token"
},
"browser": {
"enabled": false,
"host": "127.0.0.1",
"port": 5232,
"token": "!secret browser_token",
"engine": "chromium",
"headless": true,
"channel": "",
"executable_path": "",
"profile_dir": "",
"browsers_path": "",
"screenshot_dir": "",
"default_timeout": 30.0,
"max_text_chars": 20000
},
"nextcloud": {
"enabled": true,
"host": "127.0.0.1",
"port": 5230,
"token": "!secret nextcloud_token",
"url": "",
"username": "",
"app_password": "!secret nextcloud_app_password",
"default_calendar": "",
"default_task_calendar": "",
"default_addressbook": "",
"verify_tls": true,
"timeout": 30
},
"outlook": {
"enabled": false,
"host": "127.0.0.1",
"port": 5231,
"token": "!secret outlook_token",
"client_id": "",
"tenant": "common",
"token_path": ".runtime/outlook/token.json",
"default_calendar": "",
"default_task_list": "",
"default_mail_folder": "inbox",
"default_timezone": "UTC",
"verify_tls": true,
"timeout": 30
},
"simplex": {
"enabled": true,
"host": "127.0.0.1",
"port": 5227,
"token": "!secret simplex_token",
"max_inbox": 100,
"ws_url": "ws://127.0.0.1:5228",
"user_id": 1,
"auto_accept": true,
"reconnect": {
"initial": 1.0,
"max": 60.0,
"jitter": 0.2
}
}
},
"packs": {
"essentials": {
"enabled": true
},
"gutendex": {
"enabled": true
}
}
}
+9
View File
@@ -175,6 +175,15 @@ Then on the gateway host set:
"gateway": { "voice": { "tts": { "voice": "<name>" } } }
```
The LXMF gateway's voice replies resolve a Piper voice the same way from
`.runtime/voice/tts/` (`cli._build_gateway_adapter` anchors
`gateway.lxmf.voice.tts.voice_dir` there too), so the same trained voice can back
both the microphone gateway and Sideband push-to-talk replies:
```json
"gateway": { "lxmf": { "voice": { "tts": { "voice": "<name>" } } } }
```
Restart the gateway and speak a reply. **Only a real spoken reply proves the
integration** — a generated test passing proves mechanics, not that the voice
loads and sounds right.
+2 -2
View File
@@ -1,4 +1,4 @@
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 746.35px; background-color: white;" viewBox="4 4 746.3495483398438 4081.421875" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][Line truncated
<svg id="my-svg" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="flowchart" style="max-width: 763.308px; background-color: white;" viewBox="4 4 763.308349609375 3864" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#my-svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;fill:#28253D;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#my-svg .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#my-svg .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#my-svg .error-icon{fill:#ffffff;}#my-svg .error-text{fill:#000000;stroke:#000000;}#my-svg .edge-thickness-normal{stroke-width:2px;}#my-svg .edge-thickness-thick{stroke-width:3.5px;}#my-svg .edge-pattern-solid{stroke-dasharray:0;}#my-svg .edge-thickness-invisible{stroke-width:0;fill:none;}#my-svg .edge-pattern-dashed{stroke-dasharray:3;}#my-svg .edge-pattern-dotted{stroke-dasharray:2;}#my-svg .marker{fill:#000000;stroke:#000000;}#my-svg .marker.cross{stroke:#000000;}#my-svg svg{font-family:"Recursive Variable",arial,sans-serif;font-size:14px;}#my-svg p{margin:0;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) rect{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].cluster:not(.swimlane) path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster rect.swimlane-body{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-0"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-group path{stroke:#E879F9;fill:#FDF4FF;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-indicator{fill:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-0"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-0"].rough-node .collapsed-separator{stroke:#E879F9;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) rect{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].cluster:not(.swimlane) path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster rect.swimlane-body{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:nth-of-type(2){stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-title path:first-of-type,#my-svg [data-look="neo"][data-color-id="color-1"].swimlane.cluster .swimlane-body path:first-of-type{stroke:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group,#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-group path,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-group path{stroke:#2DD4BF;fill:#F0FDFA;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-indicator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-indicator{fill:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-1"].node .collapsed-separator,#my-svg [data-look="neo"][data-color-id="color-1"].rough-node .collapsed-separator{stroke:#2DD4BF;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) rect{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].cluster:not(.swimlane) path{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-title,#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster rect.swimlane-body{stroke:#FB923C;fill:#FFF7ED;}#my-svg [data-look="neo"][data-color-id="color-2"].swimlane.cluster .swimlane-title path:nth-of-type(2),#my-svg [data-look="neo"][data-coLine truncated
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
@@ -96,4 +96,4 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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") format("woff2-variations"); unicode-range: U+460-52F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; }
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated
@font-face { font-family: "Recursive Variable"; font-style: normal; font-display: swap; font-weight: 300 1000; src: url("data:font/woff2;base64,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 truncated

Before

Width:  |  Height:  |  Size: 367 KiB

After

Width:  |  Height:  |  Size: 364 KiB

+27 -27
View File
@@ -2,7 +2,7 @@
How one input travels through the agent. Every diamond marked **SemIf** is a
real decision-engine call that is logged as a training row; the LLM only ever
*generates* (skill drafts, bodies, questions). There is no up-front
*generates* (skill drafts, bodies, tests). There is no up-front
handle/ignore gate — every input is dispatched, and an explicit housekeeping
command is routed deterministically before navigation.
@@ -64,8 +64,8 @@ flowchart TD
%% ---------- reuse vs create ----------
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
HARD -- "yes" --> RUN
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>P same >= intent_tau?"]
INTENT -- "same" --> RUN
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>same / part / different?<br/>P same+part >= intent_tau"]
INTENT -- "same / part" --> RUN
INTENT -- "different" --> CREATESKILL
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
@@ -94,12 +94,11 @@ flowchart TD
ACTNI -- "no" --> ASSESS
%% ---------- assessment ----------
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>P success >= tau?<br/>a definitive empty result counts as success"] --> OK{"success?"}
OK -- "yes" --> SUMMARY
OK -- "no" --> REQ["SemIf choice<br/>phase 'assess:requeue'<br/>complete vs retry"]
REQ -- "retry" --> REQUEUE["requeue original request<br/>bounded by max_reentries"]
REQUEUE -.-> PUSH
REQ -- "complete" --> REPAIR
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>additional work to do?<br/>a definitive empty result counts as done"] --> OK{"outcome?"}
OK -- "done" --> SUMMARY
OK -- "continue" --> CHAIN["route the logical next step<br/>re-dispatch with the run ledger<br/>bounded by max_reentries + monotonic guard"]
CHAIN -.-> PUSH
OK -- "failed" --> REPAIR
SUMMARY["deterministic summary<br/>category.name: ok/failed - action_log"] --> OUT1["Output: ran<br/>SchedulerReply (run_id, skill_ref, result)<br/>REPL · gateway reply · dashboard trace"]
@@ -112,8 +111,8 @@ flowchart TD
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
classDef output fill:#fce8e6,stroke:#d93025;
classDef author fill:#e6f4ea,stroke:#34a853;
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill;
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT output;
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REPAIR,RECORD semfill;
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT,CHAIN output;
class CREATECAT,CREATESKILL,AUTHORING author;
```
@@ -134,26 +133,26 @@ flowchart TD
DRAFT --> GEN{"category or skill?"}
GEN -- "category" --> GC["generate_category()<br/>title + description"]
GEN -- "skill" --> GS["generate_skill()<br/>title + description"]
GEN -- "skill" --> GS["generate_skill_spec()<br/>title + description +<br/>de-identified goal +<br/>generic service/transport"]
GC --> APPROVE
GS --> APPROVE
APPROVE{"creation_approval<br/>on? (default off)"}
APPROVE -- "no / already approved" --> REGISTER
APPROVE -- "yes" --> PROMPT["Output: approval prompt<br/>REPL / dashboard / gateway<br/>deny or timeout aborts"]
APPROVE{"new-skill mode<br/>allow / deny / ask<br/>(global default, per-category override)"}
APPROVE -- "allow" --> REGISTER
APPROVE -- "deny" --> ABORT2["Output: creation denied<br/>nothing registered, not re-dispatched"]
APPROVE -- "ask (already approved)" --> REGISTER
APPROVE -- "ask" --> PROMPT["Output: approval prompt<br/>REPL / dashboard / gateway<br/>deny or timeout aborts"]
PROMPT -- "approved" --> REGISTER
PROMPT -- "denied / timeout / no front end" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
REGISTER["register stub in registry + tree<br/>seed category config (locks.new_skill)<br/>trace 'category_created' / 'skill_created'"]
REGISTER["register stub in registry + tree<br/>seed category config (new_skill_creation)<br/>trace 'category_created' / 'skill_created'"]
REGISTER -- "category" --> CHAIN["chain into skill job<br/>approved=true"]
CHAIN --> DRAFT
REGISTER -- "skill" --> WRITE["single-slot codegen worker<br/>SkillWrite queue<br/>leaf.writing = true, trace 'skill_writing'"]
WRITE --> ELICIT["generate_elicitation()<br/>implementation questions + integration hint"]
ELICIT --> QS["Output: questions<br/>posted one at a time<br/>answer_timeout per question"]
QS -- "answers / timeout" --> BODY
WRITE --> BODY
BODY["generate_skill_body()<br/>or regenerate_skill_body() for<br/>repair / fidelity / test / manual regen<br/>CODEGEN.md + bridge catalog<br/>declares INTEGRATION + flat CONTRACT"] --> FID["SemIf choice<br/>phase 'authoring:fidelity'<br/>accept / reconsider<br/>+ static integration_findings"]
BODY["generate_skill_body()<br/>de-identified spec only: goal + service/transport<br/>or regenerate_skill_body() for<br/>repair / fidelity / test / manual regen<br/>CODEGEN.md + bridge catalog<br/>declares INTEGRATION + flat CONTRACT"] --> FID["SemIf choice<br/>phase 'authoring:fidelity'<br/>accept / reconsider<br/>+ static integration_findings"]
FID -- "reconsider (once)" --> BODY
FID -- "accept" --> CONTRACT["parse_contract()<br/>read body's CONTRACT constant"]
@@ -176,7 +175,7 @@ flowchart TD
classDef output fill:#fce8e6,stroke:#d93025;
classDef author fill:#e6f4ea,stroke:#34a853;
class FID,CFG,REGEN semfill;
class PROMPT,ABORT,QS,FAIL,CANCELLED output;
class PROMPT,ABORT,ABORT2,FAIL,CANCELLED output;
class START,DIRECT,BACK,MAT,REQ author;
```
@@ -194,10 +193,9 @@ flowchart TD
| Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) |
| Canned | which reply | `navigate:response` | canned line |
| Leaf | which skill | `navigate:leaf` | skill |
| Intent guard | same action? | `navigate:intent` | run / create (never bypassed) |
| Intent guard | same / part / different? | `navigate:intent` | run / create (never bypassed) |
| Config record | record or ask? | `config:record` | persisted / per-fire |
| Outcome | did it succeed? | `assess:outcome` | ok / failed |
| Requeue | complete or retry? | `assess:requeue` | done / requeue |
| Outcome | additional work? | `assess:outcome` | done / continue / failed |
| Repair | how to recover? | `repair:choice` | offer |
| Fidelity | real action? | `authoring:fidelity` | accept / rewrite |
| Config search | where is the value? | `config:search` | auto-populate |
@@ -217,6 +215,8 @@ at or above `softmax_bypass_tau` (default 0.5) is already decisive, so its scope
confirm is skipped; the **leaf** intent guard is never bypassed (the leaf softmax
has no create option, so a confident winner is only the closest existing skill,
never a match) — it always runs and can reject into create.
New-skill creation is also gated deterministically by the per-category
`locks.new_skill` (the `housekeeping` and `response` categories are hard-locked
in code).
New-skill creation is gated deterministically by the tri-state
`new_skill_creation` mode — global default `deny` (opt in with `allow`, or
`ask` for approval-gated authoring) with a
per-category override in `data/skills/<category>/config.json`; the
`housekeeping` and `response` categories are always `deny` in code.
+19 -2
View File
@@ -9,9 +9,18 @@
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
},
"simplex_chat": {
"_comment": "Per-arch daemon binaries; bootstrap selects by `uname -m` (x86_64 | aarch64, arm64 normalized to aarch64). The pinned version is the same for every arch.",
"version": "v7.0.3",
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
"assets": {
"x86_64": {
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
},
"aarch64": {
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-aarch64",
"sha256": "2d2e62351f11bc51ae659618584722b38ea5a6796b806c9a388ee6e3124c90ac"
}
}
},
"voice": {
"_comment": "Piper TTS voice-training refs used by scripts/voice-train.sh (optional, off-bootstrap): the piper1-gpl training toolchain commit and the medium base checkpoint it fine-tunes from. See docs/VOICE-TRAIN.md.",
@@ -19,5 +28,13 @@
"piper_train_ref": "efffbfb226bfb511ebbcf55d0cecd8b35a89743d",
"base_checkpoint_url": "https://huggingface.co/datasets/rhasspy/piper-checkpoints/resolve/main/en/en_US/lessac/medium/epoch=2164-step=1355540.ckpt",
"base_checkpoint_sha256": "ab7e5b8dab40f834b7cc58ae4ad7b7009c954b901e4ddbb784bbe11ce379a1cd"
},
"wake_word": {
"_comment": "openWakeWord-compatible wake-word model refs fetched by scripts/voice-models.py into .runtime/voice/wake (deployment-independent, code-owned like the other pins). openWakeWord ships no 'computer' model, so this community-trained ONNX (Apache-2.0, same mel/embedding feature models) is pinned by sha256. 'phrase' is the spoken wake phrase.",
"hey_computer": {
"url": "https://huggingface.co/Soulcreek2/speechkit-wakeword-models/resolve/main/hey_computer.onnx",
"sha256": "3acbd9ffff04beba2d16ebdfd0d4c734d65fecdd22446f25f4d0afa6e5d7606b",
"phrase": "Hey Computer"
}
}
}
+15
View File
@@ -0,0 +1,15 @@
# Codec2 voice-message decoding (optional).
#
# Sideband's non-HQ push-to-talk messages carry raw Codec2 frames
# (`LXMF.AM_CODEC2_*`); decoding them needs the `pycodec2` bindings, which
# compile against the system `libcodec2` (Debian/Ubuntu: `libcodec2-dev`). Only
# needed for `gateway.lxmf.voice` when the sender uses non-HQ PTT — HQ Opus
# works with `requirements/transcribe.txt` alone. Lazy-imported by
# semif_agent/voice_transport.py, so the core stays stdlib-only; a missing
# decoder is reported per-message, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the plan
# installs it best-effort), or manually:
# apt-get install -y libcodec2-dev
# .runtime/venv/bin/pip install -r requirements/codec2.txt
pycodec2==4.1.1
+9
View File
@@ -0,0 +1,9 @@
# Core agent deps (the agent itself is stdlib-only; this is the test runner).
#
# Every host installs this. The decision engine and messaging transports are
# separate, optional files (engine.txt, transports.txt) so a host installs only
# what its answers require. The voice stack (voice.txt) is hardware-dependent,
# and the browser stack ships WITH its pack (packs/browser/requirements.txt) —
# bootstrap installs each selected pack's own requirements.txt.
# `staging.txt` includes the repo-level files for a full provision.
pytest
+18
View File
@@ -0,0 +1,18 @@
# Local decision-engine deps (SemIf / llama.cpp, CPU path).
#
# Only needed on a host whose `engine.provider` is the local SemIf GGUF. A host
# pointed at a remote Winnow decision server (engine.provider == "winnow")
# installs neither this file nor the SemIf engine clone / GGUF / tokenizer.
#
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
# cp314 wheel (source build fails). So semif-phase1 is installed with
# `--no-deps` and exactly this set is brought in instead. The pins match the
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
# declared version) so the pip resolver stays quiet about it.
numpy==2.3.5
transformers==5.17.0
tokenizers==0.23.2
huggingface-hub==1.31.0
llama-cpp-python==0.3.35
+16 -22
View File
@@ -1,23 +1,17 @@
# Staging-machine engine deps (CPU llama.cpp path).
# Full provision: every repo-level dependency this checkout can need, for a host
# that runs the local decision engine and all messaging transports. This is the
# union of the per-concern files below; a `scripts/bootstrap.sh` run installs
# only the subset its answers require, so prefer those files (engine.txt,
# transports.txt) when provisioning by hand.
#
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
# cp314 wheel (source build fails). So semif-phase1 is installed with
# `--no-deps` and exactly this set is brought in instead. The pins match the
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
# declared version) so the pip resolver stays quiet about it.
numpy==2.3.5
transformers==5.17.0
tokenizers==0.23.2
huggingface-hub==1.31.0
llama-cpp-python==0.3.35
pytest
# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the
# gateway refuses to start without it. Not needed by the decision engine.
websockets==15.0.1
# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway
# refuses to start without it. Runs in-process — there is no daemon binary.
# rns pulls cryptography + pyserial transitively (resolved by pip).
lxmf==1.2.0
rns==1.5.7
# Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
# hardware/optional. Voice is a repo file installed with
# `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are
# installed by bootstrap when that pack is selected. transcribe.txt
# (faster-whisper only, for LXMF Sideband voice messages), tts.txt (piper-tts +
# PyAV, for LXMF voice replies) and codec2.txt (pycodec2, for non-HQ Codec2 PTT)
# are likewise optional and installed by bootstrap when `gateway.lxmf.voice` is
# enabled.
-r core.txt
-r engine.txt
-r transports.txt
+20
View File
@@ -0,0 +1,20 @@
# Voice-message transcription deps (optional).
#
# Only needed on a host whose LXMF gateway transcribes Sideband push-to-talk
# voice messages (`gateway.lxmf.voice.enabled`) but that does NOT run the voice
# gateway — `requirements/voice.txt` is hardware-dependent (PortAudio mic +
# speaker, wake word, TTS) and none of that is required here. faster-whisper
# decodes the Opus/OGG container itself (its bundled PyAV/ffmpeg) and
# transcribes, and is lazy-imported by semif_agent/voice_transport.py, so the
# core stays stdlib-only on every other host.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/transcribe.txt
faster-whisper==1.2.1
# PyAV 19.0.0 (2026-09-29) REMOVED the `metadata_errors` argument to av.open(),
# which faster-whisper 1.2.1 (the latest release) still passes — so any voice
# message fails to decode with `TypeError: open() got an unexpected keyword
# argument 'metadata_errors'`. faster-whisper's git master handles both, but it
# is unreleased; pin PyAV below 19 until a release ships the fix.
av<19
+13
View File
@@ -0,0 +1,13 @@
# Messaging transport deps (SimpleX + LXMF gateways/bridges).
#
# Only needed on a host that enables the SimpleX gateway or bridge (which uses
# `websockets` against its simplex-chat daemon) or the LXMF gateway (in-process
# `lxmf`/`rns`). Both are lazy-imported, so a host without them still runs every
# other front end; the gateway refuses to start with an install hint.
#
# `websockets` is shared by the command gateway and the forwarding bridge (the
# neutral `semif_agent/simplex_ws.py`). `lxmf` pulls `rns` (Reticulum) and
# cryptography transitively; both are pinned so the resolver stays quiet.
websockets==15.0.1
lxmf==1.2.0
rns==1.5.7
+22
View File
@@ -0,0 +1,22 @@
# Voice-reply (text-to-speech) deps for the LXMF gateway (optional).
#
# When the LXMF gateway handles Sideband push-to-talk voice messages
# (`gateway.lxmf.voice.enabled`) and is configured to reply with voice
# (`gateway.lxmf.voice.reply_with_voice`, the default), it synthesizes the reply
# with Piper and encodes it to the Opus/OGG container Sideband's HQ push-to-talk
# uses (`LXMF.AM_OPUS_OGG`). That needs piper-tts (text-to-speech) and PyAV
# (libopus encoding) — NOT the hardware voice stack in `requirements/voice.txt`
# (no microphone, wake word, or speaker) and NOT transcription
# (`requirements/transcribe.txt`, which already pulls PyAV for decoding).
# Lazy-imported by semif_agent/voice_transport.py, so the core stays stdlib-only;
# a missing stack makes the reply fall back to text, never a crash.
#
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
# install plan picks it up on the next run), or manually:
# .runtime/venv/bin/pip install -r requirements/tts.txt
piper-tts==1.8.0
onnxruntime==1.30.0
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open() (see requirements/transcribe.txt); pin below 19 here
# too so the shared PyAV is the one both paths expect.
av<19
+4
View File
@@ -26,6 +26,10 @@
sounddevice==0.5.6
onnxruntime==1.30.0
faster-whisper==1.2.1
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
# still passes to av.open(), breaking every transcription; see
# requirements/transcribe.txt for the full note.
av<19
piper-tts==1.8.0
webrtcvad-wheels==2.0.14.post1
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Re-apply the audio baseline whenever a sound device is added, changed, or
# removed, so the internal speaker stays at full volume and unmuted (the
# baseline) after a USB mic, HDMI, or headset is plugged or unplugged.
#
# `udevadm monitor` is readable without root, so this runs as a long-lived
# systemd user service (see `audio-baseline.service`); each sound event
# triggers one idempotent apply of `audio-baseline.sh`.
set -u
BASELINE="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/audio-baseline.sh"
stdbuf -oL udevadm monitor --udev --subsystem-match=sound 2>/dev/null \
| while IFS= read -r line; do
# Event lines look like `UDEV [1696.123] add /devices/... (sound)`;
# the `[` distinguishes them from the 3-line startup banner.
case "$line" in
UDEV*\[*) "$BASELINE" ;;
esac
done
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Restore the internal analog speaker to full volume, unmuted.
#
# PortAudio/ALSA has no volume control, so the voice gateway's cue beep and
# spoken replies are silent when the card's Master is muted or at 0%. The mixer
# also resets when a sound device is added or removed (e.g. a USB mic or HDMI
# unplug), so this runs both at startup and on every hotplug event (see
# `audio-baseline-watch.sh`).
#
# The card is identified by its 'Speaker' control (HDMI cards only expose
# IEC958), so a shifting card index after a device change does not matter.
# Idempotent and safe to run repeatedly; exits 0 when no card is present yet
# (the watcher retries on the next hotplug event).
set -u
for dir in /proc/asound/card*/; do
[ -e "$dir" ] || continue
idx=${dir#/proc/asound/card}
idx=${idx%/}
amixer -c "$idx" scontrols 2>/dev/null | grep -q "'Speaker'" || continue
amixer -c "$idx" sset Master 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Speaker 100% unmute >/dev/null 2>&1 || true
amixer -c "$idx" sset Headphone 100% unmute >/dev/null 2>&1 || true
done
exit 0
+729 -221
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())
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env python3
"""Print (creating if needed) the SimpleX bot's contact address.
The gateway talks to a local `simplex-chat` daemon running as a bot
(`--create-bot-display-name`, see simplex_chat in config.json). To connect a
phone/client to the bot you need the bot's *user* contact address, not a chat
relay address; this queries the daemon's WebSocket API, creating the address on
first run, and prints the short link (and full link). Requires the daemon to be
running.
Usage:
.runtime/venv/bin/python scripts/simplex-address.py [--config config.json]
[--ws-url ws://...]
[--user-id 1]
"""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
def _ws_url(config_path: str) -> str:
try:
with open(config_path) as fh:
cfg = json.load(fh)
except (OSError, ValueError):
return "ws://127.0.0.1:5226"
return str(cfg.get("gateway", {}).get("simplex", {}).get("ws_url") or "ws://127.0.0.1:5226")
async def _resolve(ws_url: str, user_id: int) -> dict:
try:
import websockets
except ImportError:
raise SystemExit("the `websockets` package is required (pip install websockets)")
async with websockets.connect(ws_url, max_size=None) as ws:
async def cmd(command: str) -> dict:
await ws.send(json.dumps({"corrId": "addr", "cmd": command}))
raw = await asyncio.wait_for(ws.recv(), timeout=20)
return json.loads(raw).get("resp", {}) or {}
resp = await cmd(f"/_show_address {user_id}")
if resp.get("type") == "userContactLink":
return resp.get("contactLink", {}) or {}
# No address yet -> create one (APICreateMyAddress).
resp = await cmd(f"/_address {user_id}")
if resp.get("type") == "userContactLinkCreated":
return {"connLinkContact": resp.get("connLinkContact", {}) or {}}
raise SystemExit(f"could not read or create address: {json.dumps(resp)[:300]}")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--config", default="config.json")
ap.add_argument("--ws-url", default=None)
ap.add_argument("--user-id", type=int, default=1)
args = ap.parse_args()
ws_url = args.ws_url or _ws_url(args.config)
try:
link = asyncio.run(_resolve(ws_url, args.user_id))
except OSError as exc:
print(f"cannot reach simplex-chat at {ws_url}: {exc}", file=sys.stderr)
return 1
except asyncio.TimeoutError:
print(f"simplex-chat at {ws_url} did not answer", file=sys.stderr)
return 1
conn = link.get("connLinkContact", {}) or link
short = conn.get("connShortLink")
full = conn.get("connFullLink")
if short:
print(short)
if full:
print(full)
if not (short or full):
print("no contact address found", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+4 -1
View File
@@ -8,7 +8,10 @@ Type=simple
WorkingDirectory=@REPO@
Environment=HF_HOME=@REPO@/.runtime/hf
Environment=PYTHONUNBUFFERED=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
# voice mic loop) leaves a trace in the journal instead of hanging silently.
Environment=PYTHONFAULTHANDLER=1
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform @PLATFORMS@
Restart=always
RestartSec=5
StandardOutput=journal
+18 -8
View File
@@ -12,8 +12,11 @@ probability.
description plus `create_category`; `confirm_category_fit` confirms the
winner's scope. `navigation.category_tau` is that guard's P(covers) floor.
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
compares the winner's action to the request. `navigation.intent_tau` is that
guard's P(same) floor.
decides what the winner does for the request (`same` / `part` / `different`).
`navigation.intent_tau` is that guard's P(same or part) floor: `same` or
`part` runs the skill, and only `different` authors a new leaf. The guard
decides contribution only; whether more work remains is `assess:outcome`'s
call.
This replays a hand-labeled eval set through the **real** decision engine and
the **real** skill tree, measuring each guard's probability per request so the
@@ -23,7 +26,7 @@ a host with the pinned engine:
.runtime/venv/bin/python scripts/tune_navigation.py
.runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6
The tree is whatever the host currently has loaded (committed seeds + the runtime
The tree is whatever the host currently has loaded (shipped packs + the runtime
`data/skills/`), so an expectation naming a skill that is not present is
reported as N/A rather than counted wrong. Labels are hand-written ground truth;
self-labeled decision rows are not evidence. Nothing is written to the runtime
@@ -58,11 +61,13 @@ LEAF_EVAL: list[tuple[str, str]] = [
("check my next message on simplex", "simplex.next_message"),
("read the next simplex message", "simplex.next_message"),
("show me my simplex messages", "simplex.next_message"),
('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"),
("send a simplex message to pepper saying hi", "simplex.send_simplex_message"),
('send a message on simplex to pepper: "hey!"', "simplex.send_message"),
("send a simplex message to pepper saying hi", "simplex.send_message"),
("what is my simplex connection link?", "simplex.connect_link"),
("give me my simplex contact link", "simplex.connect_link"),
("tell me the next event in my nextcloud calendar", "calendar.next_event"),
("tell me the next event in my nextcloud calendar", "nextcloud.next_event"),
("what is 15% of 80?", "calculator.calculate"),
("square root of 144", "calculator.calculate"),
("translate my last simplex message to French", "create"),
("delete my next simplex message", "create"),
("book a flight to japan", "create"),
@@ -73,7 +78,9 @@ CATEGORY_EVAL: list[tuple[str, str]] = [
("what is my next message on simplex?", "simplex"),
("send a simplex message to pepper saying hi", "simplex"),
("what is my simplex connection link?", "simplex"),
("tell me the next event in my nextcloud calendar", "calendar"),
("tell me the next event in my nextcloud calendar", "nextcloud"),
("what is 15% of 80?", "calculator"),
("square root of 144", "calculator"),
("hello there", "response"),
("thanks!", "response"),
("what", "response"),
@@ -118,7 +125,10 @@ def measure(
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
events = trace.read()[before:]
guard = next((e for e in events if e["kind"] == "intent_guard"), None)
return {"picked": f"{nav.category}.{nav.name}", "p": guard["probs"]["same"] if guard else None}
# The guard accepts a skill that is the same action OR one required part of a
# compound request, so the "does it contribute" mass is same + part.
p = (guard["probs"]["same"] + guard["probs"]["part"]) if guard else None
return {"picked": f"{nav.category}.{nav.name}", "p": p}
def verdict(measured: dict, tau: float) -> str:
+58 -9
View File
@@ -6,9 +6,12 @@ Run after installing `requirements/voice.txt` (bootstrap does this with
`gateway.voice` from config.json so the downloaded models match the configured
names, or take explicit flags.
- **Wake word** (openWakeWord): downloaded by `openwakeword.utils.download_models`
into the venv's package resources dir (inside `.runtime/venv/`, so still
contained in the checkout). The detector resolves the model by name there.
- **Wake word** (openWakeWord): official models are downloaded by
`openwakeword.utils.download_models` into the venv's package resources dir
(inside `.runtime/venv/`, so still contained in the checkout); the detector
resolves the model by name there. A **pinned community model** (openWakeWord
ships no "computer" model) is fetched from `pins.json` `wake_word` into the
configured `model_dir` (`.runtime/voice/wake`) and verified by sha256.
- **TTS** (Piper): the voice `.onnx` + `.onnx.json` are fetched from the
`rhasspy/piper-voices` HF repo into `.runtime/voice/tts/`.
- **STT** (faster-whisper): instantiating the model warms it into the HF cache
@@ -18,12 +21,15 @@ names, or take explicit flags.
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import urllib.request
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RUNTIME = REPO_ROOT / ".runtime" / "voice"
PINS = REPO_ROOT / "pins.json"
PIPER_REPO = "rhasspy/piper-voices"
@@ -42,15 +48,56 @@ def piper_hf_path(voice: str) -> str:
return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx"
def download_wake(name: str) -> None:
def pinned_wake_models() -> dict:
"""Return the code-owned wake-word refs from `pins.json` (`name` -> ref)."""
try:
pins = json.loads(PINS.read_text())
except Exception:
return {}
block = pins.get("wake_word", {}) or {}
return {
name: ref
for name, ref in block.items()
if isinstance(ref, dict) and ref.get("url")
}
def _sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def download_wake_file(name: str, ref: dict, target_dir: Path) -> None:
"""Fetch a pinned community wake model into `target_dir`, verifying sha256."""
url = str(ref["url"])
expected = str(ref.get("sha256", "") or "")
target_dir.mkdir(parents=True, exist_ok=True)
dest = target_dir / f"{name}.onnx"
if dest.is_file() and (not expected or _sha256(dest) == expected):
print(f"== wake word: {dest.name} (present)")
return
print(f"== wake word: {url} -> {dest}")
with urllib.request.urlopen(url) as resp: # pinned https URL from pins.json
data = resp.read()
if expected and hashlib.sha256(data).hexdigest() != expected:
raise SystemExit(f"sha256 mismatch for {name}: refusing to write {dest}")
dest.write_bytes(data)
def download_wake(name: str, target_dir: Path) -> None:
import openwakeword.utils as utils
print(f"== wake word model: {name}")
# Default target: the venv's package resources dir (inside .runtime/venv).
# openWakeWord resolves the model (and its shared mel/embedding models) by
# name from there.
# Always fetch the shared feature (mel/embedding) + VAD models, and for an
# official name the phrase model itself, into the venv's package resources
# dir (inside .runtime/venv). An unknown name is skipped here.
utils.download_models(model_names=[name])
# A pinned community model (openWakeWord ships no "computer" model) is
# fetched into the configured model_dir so the detector resolves it by path.
ref = pinned_wake_models().get(name)
if ref:
download_wake_file(name, ref, target_dir)
def download_voice(voice: str, target: Path) -> None:
from huggingface_hub import hf_hub_download
@@ -86,6 +133,8 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default=str(REPO_ROOT / "config.json"))
parser.add_argument("--wake", default=None, help="openWakeWord model name")
parser.add_argument("--wake-dir", default=str(RUNTIME / "wake"),
help="target dir for a pinned community wake model")
parser.add_argument("--stt", default=None, help="faster-whisper model size/path")
parser.add_argument("--tts", default=None, help="Piper voice id")
parser.add_argument("--tts-dir", default=str(RUNTIME / "tts"))
@@ -95,12 +144,12 @@ def main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv)
voice_cfg = _config_voice(Path(args.config))
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_mycroft"
wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_computer"
stt = args.stt or (voice_cfg.get("stt", {}) or {}).get("model") or "base.en"
tts = args.tts or (voice_cfg.get("tts", {}) or {}).get("voice") or "en_US-lessac-medium"
if not args.skip_wake:
download_wake(wake)
download_wake(wake, Path(args.wake_dir))
if not args.skip_tts:
download_voice(tts, Path(args.tts_dir))
if not args.skip_stt:
@@ -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//calendar.create_event//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{stamp}",
]
if all_day:
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
else:
lines.append(f"DTSTART:{_utc_stamp(start)}")
lines.append(f"DTEND:{_utc_stamp(end)}")
lines.append(f"SUMMARY:{_escape_ics(summary)}")
if description:
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
lines += ["END:VEVENT", "END:VCALENDAR", ""]
return "\r\n".join(lines).encode("utf-8")
# ---- skill phases ----
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(
action_log=f"waiting for {field}",
new_state=request.text,
needs_input=question,
)
def act(ctx, request):
answers = request.meta.setdefault("create_event_answers", {})
awaiting = request.meta.get("create_event_awaiting")
if request.user_input is not None and awaiting:
if answers.get(awaiting) != request.user_input.strip():
answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None)
fields = request.meta.get("create_event_fields")
if fields is None:
try:
fields = _extract_fields(ctx, request)
except BridgeError as exc:
return ActionResult(
action_log=str(exc),
new_state=request.text,
)
request.meta["create_event_fields"] = fields
title = fields["title"]
description = fields["description"]
now = _now(ctx)
parsed = _parse_when(request.text, now)
if answers.get("title"):
title = answers["title"].strip()
for key in ("date", "time"):
if answers.get(key):
extra = _parse_when(answers[key], now)
if extra["date"] is not None:
parsed["date"] = extra["date"]
parsed["from_weekday"] = extra["from_weekday"]
if extra["time"] is not None:
parsed["time"] = extra["time"]
if extra["all_day"]:
parsed["all_day"] = True
if extra["duration_minutes"]:
parsed["duration_minutes"] = extra["duration_minutes"]
if not title:
return _ask(request, "title", "What should I call the event?")
if parsed["date"] is None:
return _ask(request, "date", f"What day should I schedule {title!r}?")
if not parsed["all_day"] and parsed["time"] is None:
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
local_tz = now.tzinfo or timezone.utc
all_day = bool(parsed["all_day"])
if all_day:
start_date = parsed["date"]
end_date = start_date + timedelta(days=1)
start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz)
end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz)
else:
start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz)
if start <= now and parsed.get("from_weekday"):
start += timedelta(days=7)
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
end = start + duration
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="no calendars found on the account",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
uid = f"{uuid.uuid4().hex}@semif-agent"
body = _build_ics(
uid, title, start, end, all_day, _utc_stamp(now), description=description
)
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try:
_request(
ctx,
"PUT",
path,
body=body,
depth="0",
content_type="text/calendar; charset=utf-8",
extra_headers={"If-None-Match": "*"},
)
except CalDavError as exc:
return ActionResult(
action_log=(
f"could not create {title!r} on "
f"{calendar!r}: {exc}"
),
new_state=request.text,
decisions=decisions,
)
if all_day:
when_text = f"{start_date.isoformat()} (all day)"
else:
when_text = (
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
f"{end.strftime('%H:%M %Z')}"
)
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
return ActionResult(
action_log=report,
new_state=report,
decisions=decisions,
)
-451
View File
@@ -1,451 +0,0 @@
"""Hermetic mechanics test for calendar.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
and description through the LLM bridge (caching the call across a `needs_input`
resume), parses the date/time from the request, asks for a missing field and
resumes, resolves the target calendar with a SemIf choice over the owned
calendars (a strong winner is used, otherwise the configured default), writes a
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
It does NOT prove the live integration — only a real run against the user's
Nextcloud does.
"""
import json
import sys
import threading
import urllib.parse
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda ctx: FIXED_NOW
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
def next_weekday(now, weekday):
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
calendars = []
put_status = 201
requests = []
puts = []
llm_reply = DEFAULT_LLM_REPLY
llm_status = 200
llm_requests = []
def _read_body(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status, content_type):
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._read_body()
self.requests.append(("PROPFIND", self.path))
responses = []
for calendar in self.calendars:
responses.append(
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
f'{calendar["name"]}/</d:href>'
f"<d:propstat><d:prop>"
f'<d:displayname>{calendar["label"]}</d:displayname>'
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
f"</d:response>"
)
body = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
+ "".join(responses)
+ "</d:multistatus>"
)
self._send(body, 207, "application/xml; charset=utf-8")
def do_PUT(self):
body = self._read_body()
self.puts.append(
{"path": self.path, "body": body, "headers": dict(self.headers)}
)
self._send(b"", self.put_status, "text/plain")
def do_POST(self):
body = self._read_body()
if self.path != "/chat":
self._send(json.dumps({"error": "not found"}), 404, "application/json")
return
self.llm_requests.append(body)
if self.llm_status != 200:
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
return
self._send(
json.dumps({"text": json.dumps(self.llm_reply)}),
200,
"application/json",
)
def log_message(self, *args):
pass
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
handler = type(
"Handler",
(CalDavHandler,),
{
"calendars": calendars
if calendars is not None
else [
{"name": "personal", "label": "Personal"},
{"name": "work", "label": "Work"},
],
"put_status": put_status,
"requests": [],
"puts": [],
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
"llm_status": llm_status,
"llm_requests": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, default="personal", llm_url=None):
return {
"nextcloud_url": url,
"nextcloud_username": "alice",
"nextcloud_app_password": "secret",
"nextcloud_default_calendar": default,
"llm_bridge_url": url if llm_url is None else llm_url,
"llm_bridge_token": "",
}
def run(handler, url, text, default="personal", engine=None, llm_url=None):
engine = engine or FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
request = Request(text)
action = skill.act(ctx, request)
return action, request, engine
def test_example_creates_event_on_default_calendar():
server, handler, url = start_server(
llm_reply={
"title": "Ashley's dance recital",
"description": "Dance recital at 5pm.",
}
)
try:
# The query names no calendar, so the SemIf choice is a near-tie and the
# configured default ("personal") wins.
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
action, _request, engine = run(
handler,
url,
"add Ashley's dance recital to the calendar for 5pm Tuesday",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
assert engine.decisions[0].state == (
"add Ashley's dance recital to the calendar for 5pm Tuesday"
), engine.decisions[0]
assert "referred to in the user query" in engine.decisions[0].question
assert len(handler.puts) == 1, handler.puts
put = handler.puts[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
assert put["path"].endswith(".ics"), put
assert put["headers"].get("If-None-Match") == "*"
body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
assert "Ashley's dance recital" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_time_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(
handler, url, "add dentist appointment on 2026-11-10"
)
assert action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_day_asks_then_creates():
server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked"
assert "day" in action.needs_input.lower(), action.needs_input
request.user_input = "2026-11-10"
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_title_asks():
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked"
assert "call the event" in action.needs_input.lower(), action.needs_input
assert handler.puts == []
print(action.needs_input)
finally:
server.shutdown()
server.server_close()
def test_named_calendar_is_used():
server, handler, url = start_server(
llm_reply={"title": "team sync", "description": ""}
)
try:
engine = FakeEngine(pick="work")
action, _request, engine = run(
handler,
url,
"add team sync to my work calendar on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:team sync" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# Work edges out personal but stays below the strong-winner threshold, so
# the configured default ("personal") is used instead.
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/personal/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unknown_default_uses_semif_decision():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try:
# The configured default is not among the account's calendars and the
# SemIf winner is weak: the winner is used anyway (never blocks).
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
action, _request, engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
default="missing",
engine=engine,
)
assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions
assert action.decisions and len(action.decisions) == 1, action.decisions
assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_all_day_event():
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try:
action, _request, _engine = run(
handler, url, "add conference all day on 2026-11-10"
)
assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8")
assert "DTSTART;VALUE=DATE:20261110" in body, body
assert "DTEND;VALUE=DATE:20261111" in body, body
assert "SUMMARY:conference" in body, body
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server()
try:
action, request, _engine = run(
handler,
url,
"add standup on 2026-11-10 at 9am",
llm_url="http://127.0.0.1:1",
)
assert "llm bridge" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed extraction must not fake a result"
assert handler.puts == [], "no event is created when the LLM bridge is down"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_llm_bridge_error_status_is_reported_honestly():
server, handler, url = start_server(llm_status=502)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "HTTP 502" in action.action_log, action.action_log
assert action.new_state == request.text
assert handler.puts == []
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_server_error_is_reported_honestly():
server, handler, url = start_server(
put_status=500, llm_reply={"title": "standup", "description": ""}
)
try:
action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "500" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_server_fails_honestly():
action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
)
assert action.action_log and "calendar.create_event" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
def main():
test_example_creates_event_on_default_calendar()
test_missing_time_asks_then_creates()
test_missing_day_asks_then_creates()
test_missing_title_asks()
test_named_calendar_is_used()
test_weak_winner_falls_back_to_default()
test_unknown_default_uses_semif_decision()
test_all_day_event()
test_llm_bridge_failure_is_reported_honestly()
test_llm_bridge_error_status_is_reported_honestly()
test_server_error_is_reported_honestly()
test_unreachable_server_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-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 calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands.
"""
default = _default_calendar(ctx, calendars)
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar parsing ----
def _unfold(text):
lines = []
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
def _parse_property(line):
match = PROPERTY_RE.match(line)
if match is None:
return "", {}, ""
name = match.group("name").upper()
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None
total = timedelta(
weeks=int(match.group("weeks") or 0),
days=int(match.group("days") or 0),
hours=int(match.group("hours") or 0),
minutes=int(match.group("minutes") or 0),
seconds=int(match.group("seconds") or 0),
)
return -total if match.group("sign") == "-" else total
def _parse_events(payloads, default_tz):
events = []
for payload in payloads:
current = None
for line in _unfold(payload):
name, params, value = _parse_property(line)
if name == "BEGIN" and value.strip().upper() == "VEVENT":
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"):
return event["start"] + timedelta(days=1)
return event["start"]
def _pick_next(events, now):
current_or_future = [event for event in events if _event_end(event) >= now]
if not current_or_future:
return None
return min(current_or_future, key=lambda event: event["start"])
def _format_when(event):
start = event["start"]
if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z")
# ---- skill phases ----
def act(ctx, request):
try:
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
now = _now(ctx)
local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
body = _request(
ctx,
"REPORT",
_calendar_path(ctx, calendar),
_report_body(window_start, window_end),
depth="1",
)
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
f"No events on calendar {calendar!r} through "
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"):
message += f" at {next_event['location']}"
return ActionResult(action_log=message, new_state=message, decisions=decisions)
-259
View File
@@ -1,259 +0,0 @@
"""Hermetic mechanics test for calendar.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision (a strong winner is used, otherwise the configured default,
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
when the service errors. It does NOT prove the live integration — only a real
run against the user's Nextcloud does.
"""
import base64
import sys
import threading
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics():
"""Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc)
past = now - timedelta(days=2)
soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date()
def stamp(value):
return value.strftime("%Y%m%dT%H%M%SZ")
return (
"BEGIN:VCALENDAR\nVERSION:2.0\n"
"BEGIN:VEVENT\nUID:past@example\n"
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
"SUMMARY:Already happened\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:soon@example\n"
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
"BEGIN:VEVENT\nUID:allday@example\n"
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
"SUMMARY:Offsite\nEND:VEVENT\n"
"END:VCALENDAR"
)
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class CalDavHandler(BaseHTTPRequestHandler):
requests = []
calendar_count = 2
report_status = 207
def _record(self):
length = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(length) if length else b""
self.requests.append(
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_PROPFIND(self):
self._record()
responses = "".join(
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
"<d:propstat><d:prop>"
f"<d:displayname>{label}</d:displayname>"
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
for name, label in CALENDARS[: self.calendar_count]
)
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:response>"
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
"<d:propstat><d:prop>"
f"<c:calendar-data>{ICS}</c:calendar-data>"
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
"</d:response></d:multistatus>"
)
def log_message(self, *args):
pass
def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url, default="personal"):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
}
def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
engine = FakeEngine(pick="work")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my work calendar?")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
commands = [entry["command"] for entry in handler.requests]
assert commands == ["PROPFIND", "REPORT"], commands
report = handler.requests[1]
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
assert report["depth"] == "1", report["depth"]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
assert report["authorization"] == expected_auth, report["authorization"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner falls back to the configured default calendar.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A single calendar needs no SemIf decision.
server, handler, url = start_server(calendar_count=1)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
try:
engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert "failed" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed query must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-4
View File
@@ -1,4 +0,0 @@
{
"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)
@@ -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\"."
}
@@ -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)
@@ -1,345 +0,0 @@
"""Hermetic mechanics test for productivity_management.create_nextcloud_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()
-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."
}
-258
View File
@@ -1,258 +0,0 @@
"""Read the next unread SimpleX message through the forwarding bridge.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf choice over them (state = the user
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
the configured default contact is used; with no configured default (or a default
with no unread message) the weak winner stands. It then pops and reports the
oldest unread message for that conversation.
When the live buffer is empty it falls back to the daemon's persistent unread
(`/unread` + `/history`), so a message that arrived before the bridge started is
still reported. (v7 has no mark-read command, so a persistent-unread message can
be reported again until the user reads it in their own client.)
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
messaging surface it uses.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
}
TIMEOUT_SECONDS = 20
# A SemIf probability at or above this counts as a "strong winner" for the
# conversation; below it the configured default contact is used instead.
CONTACT_WINNER_TAU = 0.6
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("simplex_bridge_url is not configured")
return url
def _headers(ctx):
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
return {"X-Semif-Token": token} if token else {}
def _get(ctx, path):
request = urllib.request.Request(
_base(ctx) + path, headers=_headers(ctx)
)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- conversation resolution ----
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
seen = set()
for message in messages:
contact = str(message.get("contact_id") or "")
if not contact or contact in seen:
continue
seen.add(contact)
senders.append(
{"id": contact, "display_name": message.get("display_name") or contact}
)
return senders
def _is_healthy(sender):
"""A conversation is healthy when its connection is not known-bad.
`connected` is absent when the source did not report it (treat as unknown);
`auth_errors` counts failed sends on the connection and marks a stale peer.
"""
if sender.get("connected") is False:
return False
try:
return int(sender.get("auth_errors") or 0) == 0
except (TypeError, ValueError):
return True
def _default_sender(ctx, senders):
"""The configured default contact, if it has unread messages."""
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender
return None
def _resolve_contact(ctx, request, senders, decisions):
"""Resolve which conversation to read, mirroring calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default contact, and with no configured default the weak winner stands.
"""
default = _default_sender(ctx, senders)
if len(senders) == 1:
return senders[0]["id"]
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CONTACT_WINNER_TAU:
return winner
if default is not None:
return default["id"]
return winner
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
senders = _senders(payload.get("messages") or [])
if senders:
return _read_live(ctx, request, senders)
# The live buffer only holds messages that arrived while the bridge was
# connected; fall back to the daemon's persistent unread so a message that
# landed before the bridge started is not silently missed.
return _read_persistent(ctx, request)
def _read_live(ctx, request, senders):
decisions = []
contact = _resolve_contact(ctx, request, senders, decisions)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
return _report(message.get("display_name") or contact, message.get("text"), decisions)
def _read_persistent(ctx, request):
try:
payload = _get(ctx, "/unread")
except BridgeError as exc:
return ActionResult(
action_log=f"no unread SimpleX messages ({exc}).",
new_state="no unread SimpleX messages",
)
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
if not chats:
return ActionResult(
action_log="no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
senders = [
{
"id": str(chat.get("contact_id") or ""),
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
"connected": chat.get("connected"),
"auth_errors": chat.get("auth_errors"),
}
for chat in chats
if chat.get("contact_id")
]
decisions = []
healthy = [s for s in senders if _is_healthy(s)]
if len(healthy) == 1:
# Exactly one conversation is on a healthy connection (the rest are
# stale duplicates): read it without a coin-flip decision.
contact = healthy[0]["id"]
else:
contact = _resolve_contact(ctx, request, senders, decisions)
try:
history = _get(
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
)
except BridgeError as exc:
return ActionResult(
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
if not messages:
# Fall back to the previewed unread messages from /unread.
chat = next(
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
)
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
if not messages:
return ActionResult(
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
sender = next(
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
)
return _report(sender, messages[0].get("text"), decisions)
def _report(sender, body, decisions):
report = f"SimpleX message from {sender}: {str(body or '')}"
return ActionResult(action_log=report, new_state=report, decisions=decisions)
-375
View File
@@ -1,375 +0,0 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
strong winner is used, otherwise the configured default, otherwise the weak
winner), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Test-only engine.
By default it picks the requested option id (else the first) with full
confidence. Pass `probs` (a mapping of option id -> probability) to script an
arbitrary distribution, e.g. a near-tie that must fall back to the default.
"""
def __init__(self, pick=None, probs=None):
self.pick = pick
self.probs = probs
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
if self.probs is not None:
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
else:
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
unread_chats = []
history = {}
requests = []
tokens = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
self.tokens.append(self.headers.get("X-Semif-Token"))
url = urllib.parse.urlparse(self.path)
if url.path == "/inbox":
self._send({"messages": list(self.messages)})
elif url.path == "/inbox/next":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
found = None
for index, message in enumerate(self.messages):
if contact is None or message["contact_id"] == str(contact):
found = self.messages.pop(index)
break
self._send({"message": found})
elif url.path == "/unread":
self._send({"chats": list(self.unread_chats)})
elif url.path == "/history":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
self._send(
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
)
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(messages, unread_chats=None, history=None):
handler = type(
"Handler",
(BridgeHandler,),
{
"messages": list(messages),
"unread_chats": list(unread_chats or []),
"history": dict(history or {}),
"requests": [],
"tokens": [],
},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def message(identifier, contact, name, text):
return {
"id": identifier,
"contact_id": contact,
"display_name": name,
"text": text,
"received_at": 1.0,
}
def config(url, default="", token=""):
return {
"simplex_bridge_url": url,
"simplex_default_contact": default,
"simplex_bridge_token": token,
}
def test_multiple_senders_uses_semif_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the conversation choice"
assert len(engine.decisions) == 1
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_strong_winner_overrides_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message from Bob")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
# Bob edges out Alice but stays below the strong-winner threshold, so the
# configured default ("Alice") is used instead.
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
assert "hello there" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_without_default_stands():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_single_sender_needs_no_decision():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == []
assert "hi" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported_honestly():
server, handler, url = start_server([])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "no unread" in action.action_log, action.action_log
# An empty live buffer falls back to the daemon's persistent unread.
assert handler.requests == ["/inbox", "/unread"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_live_inbox_falls_back_to_persistent_unread():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 2,
"min_unread_item_id": "8",
"unread": True,
"messages": [],
}
],
history={
"3": [
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
]
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == [], "a single unread chat needs no decision"
assert "hello" in action.action_log, action.action_log
assert "pepper" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
handler.requests
)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_persistent_unread_prefers_a_healthy_conversation():
server, handler, url = start_server(
[],
unread_chats=[
{
"contact_id": "3",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 2,
"messages": [],
},
{
"contact_id": "4",
"display_name": "pepper",
"unread_count": 1,
"unread": True,
"connected": True,
"auth_errors": 0,
"messages": [],
},
],
history={
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
},
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, Request("read my next simplex message"))
assert engine.decisions == [], "one healthy chat must win without a decision"
assert "fresh hello" in action.action_log, action.action_log
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
handler.requests
)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
def test_auth_token_is_sent_when_configured():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert "hi" in action.action_log, action.action_log
assert set(handler.tokens) == {"sekret"}, handler.tokens
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_multiple_senders_uses_semif_decision()
test_strong_winner_overrides_default_contact()
test_weak_winner_falls_back_to_default_contact()
test_weak_winner_without_default_stands()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_empty_live_inbox_falls_back_to_persistent_unread()
test_persistent_unread_prefers_a_healthy_conversation()
test_unreachable_bridge_fails_honestly()
test_auth_token_is_sent_when_configured()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
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 %d, %Y')} ({today.isoformat()})."
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."
}
-36
View File
@@ -1,36 +0,0 @@
"""Report the current local time.
Real local compute: reads the host clock and formats it in the user's
timezone — the top-level `timezone` config value (an IANA name such as
`America/Chicago`) when set, otherwise the host's local timezone. No external
service; the `compute` transport is the codebase's home for a body that acts on
the machine itself.
"""
from __future__ import annotations
from datetime import datetime
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def _offset_text(now: datetime) -> str:
offset = now.strftime("%z")
if not offset:
return ""
return f" UTC{offset[:3]}:{offset[3:]}"
def act(ctx, request):
now = local_now(ctx.config)
zone = now.tzname() or "local"
message = (
f"It is {now.strftime('%H:%M')} "
f"({now.strftime('%I:%M %p').lstrip('0')} {zone}{_offset_text(now)})."
)
return ActionResult(action_log=message, new_state=message)
-31
View File
@@ -1,31 +0,0 @@
"""Hermetic mechanics test for time.now.
Run from this folder: `python skill.test.py`. No external network, no config.
This proves the body reads the host clock and reports a real local time; it
does NOT prove anything about the host's timezone correctness.
"""
import sys
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
def main():
ctx = ActionContext(engine=None, config={})
action = skill.act(ctx, Request("what time is it?"))
assert action.new_state, "act must report the time"
assert "It is" in action.action_log, action.action_log
assert action.needs_input is None
print(action.action_log)
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Set an alarm for a specific time of day that notifies when it goes off."
}
-87
View File
@@ -1,87 +0,0 @@
"""Set an alarm for a specific time of day that notifies when it goes off.
Real local compute: parses a wall-clock time out of the request and schedules it
on the in-process timer service (`ctx.timers`). The wall-clock time is read in
the user's timezone — the top-level `timezone` config value when set, otherwise
the host's local timezone. A time already past rolls to the next day. When it
fires, the front end that set it notifies the user.
If no time can be parsed the body pauses and asks for one, stashing the answer
in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from datetime import datetime, time, timedelta
from semif_agent.skills import ActionResult
from semif_agent.timers import local_now
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
def _parse_time(text, now):
"""The next datetime matching a wall-clock time in `text`, or None."""
text = text or ""
parsed = None
if re.search(r"\bnoon\b", text, re.I):
parsed = time(12, 0)
elif re.search(r"\bmidnight\b", text, re.I):
parsed = time(0, 0)
else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match:
hour = int(match.group(1)) % 12
minute = int(match.group(2) or 0)
if match.group(3).lower() == "p":
hour += 12
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match:
hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60:
parsed = time(hour, minute)
else:
# A bare hour is only accepted when unambiguous (24-hour).
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24:
parsed = time(int(match.group(1)), 0)
if parsed is None:
return None
candidate = datetime.combine(now.date(), parsed, tzinfo=now.tzinfo)
if candidate <= now:
candidate += timedelta(days=1)
return candidate
def act(ctx, request):
if request.user_input is not None and request.meta.get("alarm_awaiting"):
if request.user_input.strip():
request.meta["alarm_time_text"] = request.user_input.strip()
request.meta.pop("alarm_awaiting", None)
text = request.meta.get("alarm_time_text") or request.text
now = local_now(ctx.config)
when = _parse_time(text, now)
if when is None:
request.meta["alarm_awaiting"] = True
return ActionResult(
action_log="waiting for a time",
new_state=request.text,
needs_input="What time should the alarm go off? (e.g. '5pm')",
)
if ctx.timers is None:
return ActionResult(
action_log="no timer service is available in this front end",
new_state=request.text,
)
label = when.strftime("%H:%M")
ctx.timers.set_alarm(when, label, run_id=request.id, source=request.source)
message = f"Alarm set for {when.strftime('%H:%M')} on {when.strftime('%A')}."
return ActionResult(action_log=message, new_state=message)
-84
View File
@@ -1,84 +0,0 @@
"""Hermetic mechanics test for time.set_alarm.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses wall-clock times (am/pm, 24-hour, noon/midnight), rolls a past time
to the next day, and pauses for input when no time is present.
"""
import sys
from datetime import datetime, timedelta
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimers:
def __init__(self):
self.alarms = []
def set_alarm(self, at, label, run_id="", source=""):
self.alarms.append((at, label))
return SimpleNamespace(id="a1", due_at=at.timestamp())
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
now = datetime.now().astimezone()
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert action.needs_input is None, action.needs_input
assert len(timers.alarms) == 1, timers.alarms
at, label = timers.alarms[0]
assert (at.hour, at.minute) == (17, 0), at
assert label == "17:00"
assert at > now, "an alarm must be in the future"
assert at <= now + timedelta(days=1)
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set an alarm for 17:30"))
assert timers.alarms[0][0].strftime("%H:%M") == "17:30", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("wake me at noon"))
assert timers.alarms[0][0].strftime("%H:%M") == "12:00", timers.alarms
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("alarm at midnight"))
assert timers.alarms[0][0].strftime("%H:%M") == "00:00", timers.alarms
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set an alarm")
action = skill.act(ctx, request)
assert action.needs_input, "an alarm with no time must ask for one"
assert timers.alarms == []
request.user_input = "6:15am"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.alarms[0][0].strftime("%H:%M") == "06:15", timers.alarms
print(action.action_log)
# No timer service fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set an alarm for 5pm"))
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
-1
View File
@@ -1 +0,0 @@
{}
-3
View File
@@ -1,3 +0,0 @@
{
"description": "Set a countdown timer that notifies when it finishes."
}
-128
View File
@@ -1,128 +0,0 @@
"""Set a countdown timer that notifies the user when it finishes.
Real local compute: parses a duration out of the request (digits or words) and
schedules it on the in-process timer service (`ctx.timers`). When it fires, the
front end that set it notifies the user — the REPL prints it, the gateway sends
it back to the originating chat, the dashboard shows it. The due time is shown
in the user's timezone (the top-level `timezone` config value, else host local).
A timer lives in the process that set it and does not survive a restart.
If no duration can be parsed the body pauses and asks for one, stashing the
answer in `request.meta` so the single-phase `act` re-run does not ask again.
"""
from __future__ import annotations
import re
from semif_agent.skills import ActionResult
from semif_agent.timers import format_duration
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
CONTRACT = {}
_DURATION_WORDS = {
"a": 1,
"an": 1,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12,
"fifteen": 15,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fortyfive": 45,
"sixty": 60,
"ninety": 90,
}
_UNIT_SECONDS = {
"second": 1,
"seconds": 1,
"sec": 1,
"secs": 1,
"s": 1,
"minute": 60,
"minutes": 60,
"min": 60,
"mins": 60,
"m": 60,
"hour": 3600,
"hours": 3600,
"hr": 3600,
"hrs": 3600,
"h": 3600,
}
_DIGIT_DURATION = re.compile(
r"\b(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b",
re.I,
)
_WORD_DURATION = re.compile(
r"\b(" + "|".join(sorted(_DURATION_WORDS, key=len, reverse=True)) + r")\s+"
r"(seconds?|secs?|minutes?|mins?|hours?|hrs?)\b",
re.I,
)
def _parse_duration(text):
"""Seconds for a duration phrase, or None when none is present."""
text = text or ""
if re.search(r"\bhalf\s+an?\s+hour\b", text, re.I):
return 1800
if re.search(r"\bquarter\s+(?:of\s+)?an?\s+hour\b", text, re.I):
return 900
if re.search(r"\ba\s+couple\s+of\s+(?:minutes?|mins?)\b", text, re.I):
return 120
if re.search(r"\ba\s+few\s+(?:minutes?|mins?)\b", text, re.I):
return 180
match = _DIGIT_DURATION.search(text)
if match:
unit = _UNIT_SECONDS.get(match.group(2).lower())
if unit:
return int(round(float(match.group(1)) * unit))
match = _WORD_DURATION.search(text)
if match:
value = _DURATION_WORDS.get(match.group(1).lower())
unit = _UNIT_SECONDS.get(match.group(2).lower())
if value and unit:
return value * unit
return None
def act(ctx, request):
if request.user_input is not None and request.meta.get("timer_awaiting"):
if request.user_input.strip():
request.meta["timer_duration_text"] = request.user_input.strip()
request.meta.pop("timer_awaiting", None)
text = request.meta.get("timer_duration_text") or request.text
seconds = _parse_duration(text)
if seconds is None:
request.meta["timer_awaiting"] = True
return ActionResult(
action_log="waiting for a duration",
new_state=request.text,
needs_input="How long should the timer run? (e.g. '5 minutes')",
)
if ctx.timers is None:
return ActionResult(
action_log="no timer service is available in this front end",
new_state=request.text,
)
label = format_duration(seconds)
timer = ctx.timers.set_timer(seconds, label, run_id=request.id, source=request.source)
due = timer.due_datetime().strftime("%H:%M")
message = f"Timer set for {label}; it will fire at {due}."
return ActionResult(action_log=message, new_state=message)
-90
View File
@@ -1,90 +0,0 @@
"""Hermetic mechanics test for time.set_timer.
Run from this folder: `python skill.test.py`. No external network, no real
sleeping: a fake timer service records what the body schedules. This proves the
body parses durations (digits and words) and schedules the right number of
seconds, and that an unparseable request pauses for input; it does NOT prove
the in-process timer actually fires (tests/test_timers.py covers the service).
"""
import sys
import time
from datetime import datetime
from types import SimpleNamespace
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeTimer:
def __init__(self, seconds):
self.due_at = time.time() + seconds
def due_datetime(self):
return datetime.fromtimestamp(self.due_at).astimezone()
class FakeTimers:
def __init__(self):
self.timers = []
def set_timer(self, seconds, label, run_id="", source=""):
self.timers.append((seconds, label))
return FakeTimer(seconds)
def ctx_with_timers():
timers = FakeTimers()
return ActionContext(engine=None, config={}, timers=timers), timers
def main():
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("please set a timer for five minutes"))
assert action.needs_input is None, action.needs_input
assert timers.timers == [(300, "5 minutes")], timers.timers
assert "300" not in action.action_log and "5 minutes" in action.action_log
print(action.action_log)
ctx, timers = ctx_with_timers()
action = skill.act(ctx, Request("set a timer for 90 seconds"))
assert timers.timers == [(90, "1 minute 30 seconds")], timers.timers
print(action.action_log)
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("timer for 1.5 hours"))
assert timers.timers == [(5400, "1 hour 30 minutes")], timers.timers
ctx, timers = ctx_with_timers()
skill.act(ctx, Request("set a timer for half an hour"))
assert timers.timers == [(1800, "30 minutes")], timers.timers
# An unparseable request pauses, then the answer is used on the re-run.
ctx, timers = ctx_with_timers()
request = Request("set a timer")
action = skill.act(ctx, request)
assert action.needs_input, "a timer with no duration must ask for one"
assert timers.timers == []
request.user_input = "ten minutes"
action = skill.act(ctx, request)
assert action.needs_input is None
assert timers.timers == [(600, "10 minutes")], timers.timers
print(action.action_log)
# No timer service (e.g. a front end without one) fails honestly.
ctx = ActionContext(engine=None, config={}, timers=None)
action = skill.act(ctx, Request("set a timer for 5 minutes"))
assert action.needs_input is None
assert "no timer service" in action.action_log, action.action_log
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+28 -9
View File
@@ -1,13 +1,21 @@
"""Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to
codegen-authored skill bodies
over a local, token-guarded HTTP API. It exists so a generated body never speaks
a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
surface instead, and the bridge owns the messy integration details and
credentials.
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook, a real
web browser via Playwright) to codegen-authored skill bodies over a local,
token-guarded HTTP API. A skill body can call a plain HTTP API directly; a
bridge is a deliberate choice for a system that needs state (especially auth
state), a native or heavy protocol, or one sanitized surface. When a bridge
fronts a service, a generated body never speaks that system's native protocol
(WebSocket, SMTP, CalDAV, an OpenAI-compatible chat API, a CLI's private flags)
directly: it calls a small, documented, uniform HTTP surface instead, and the
bridge owns the messy integration details and credentials.
Bridges **ship with their pack**: the core owns only the shared contract
(``bridges/base.py``) and the discovery registry (``bridges/registry.py``); a
bridge implementation lives in ``packs/<name>/bridge/`` and is imported by
convention from the pack that declares it. The one exception is the shared,
pack-less LLM bridge (``bridges/llm.py``), which many packs call.
Two boundaries matter:
@@ -16,21 +24,26 @@ Two boundaries matter:
own processes (`python -m semif_agent.cli bridge`) against their own service
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
every code-generation prompt (body, retry, regen, elicitation, testgen) and is
every code-generation prompt (body, retry, regen, testgen) and is
the single source of bridge specifics: the model learns which real services it
may build against, each one's base-URL config var, auth header/token var,
config-var docs, and its endpoints with request/response/error shapes. CODEGEN.md
and TESTGEN.md carry only the generic pattern.
"""
from .base import BridgeInfo, BridgeService
from .base import BridgeInfo, BridgeService, checkout_root
from .inbox import MessagingInbox
from .registry import (
build_bridge,
derived_config_vars,
describe_bridges,
discover_bridge_classes,
known_infos,
load_pack_bridge_class,
load_pack_bridge_module,
load_pack_bridge_package,
run_bridges,
set_bridge_packs,
)
__all__ = [
@@ -38,8 +51,14 @@ __all__ = [
"BridgeService",
"MessagingInbox",
"build_bridge",
"checkout_root",
"derived_config_vars",
"describe_bridges",
"discover_bridge_classes",
"known_infos",
"load_pack_bridge_class",
"load_pack_bridge_module",
"load_pack_bridge_package",
"run_bridges",
"set_bridge_packs",
]
+30
View File
@@ -14,9 +14,20 @@ import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
def checkout_root() -> Path:
"""The agent checkout root (anchors gitignored ``.runtime/`` artifacts).
``semif_agent/bridges/base.py`` -> repo root. A bridge implementation ships
inside its pack (``packs/<name>/bridge/...``), so it must not derive the root
from its own ``__file__``; it uses this helper instead.
"""
return Path(__file__).resolve().parents[2]
@dataclass(frozen=True)
class BridgeInfo:
"""Static, prompt-safe metadata about a bridge.
@@ -60,6 +71,25 @@ class BridgeService(ABC):
self._server: ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
@classmethod
def from_config(
cls,
block: dict | None,
config: dict | None = None,
trace=None,
llm=None,
) -> "BridgeService":
"""Build a bridge from its ``bridges.<name>`` block.
The registry constructs every bridge through this hook so a bridge that
needs more than its own block — the shared LLM client, or a top-level
fallback (e.g. Nextcloud's ``nextcloud_*`` values) — can declare that
itself instead of the core special-casing it by name. The default passes
the block and trace straight through; override in a pack bridge that
needs ``llm`` or the full ``config``.
"""
return cls(block, trace=trace)
# ---- lifecycle ----
@abstractmethod
+4 -1
View File
@@ -2,7 +2,7 @@
The bridge owns the read cursor so a read skill stays stateless. Generic over
transports: entries are normalized message dicts (`contact_id`, `display_name`,
`text`), which is exactly what `semif_agent.simplex_ws` yields.
`text`, `item_id`), which is exactly what `semif_agent.simplex_ws` yields.
"""
from __future__ import annotations
@@ -28,6 +28,9 @@ class MessagingInbox:
"contact_id": contact_id,
"display_name": display_name,
"text": message.get("text") or "",
# The transport's per-item id (SimpleX `itemId`), when known: lets a
# consumer mark exactly this message read on the daemon.
"item_id": str(message.get("item_id") or ""),
"received_at": time.time(),
}
with self._lock:
+6
View File
@@ -60,6 +60,12 @@ class LLMBridge(BridgeService):
#: the bridge is built without one; calls then report 502, never a guess.
self.client = client
@classmethod
def from_config(cls, block, config=None, trace=None, llm=None) -> "LLMBridge":
# The LLM bridge reuses the scheduler's already-configured `llm` client
# (endpoint/model/sampler configured once in the top-level `llm` block).
return cls(block, trace=trace, client=llm)
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
-604
View File
@@ -1,604 +0,0 @@
"""Nextcloud bridge: files, calendars, tasks, contacts, and notes over HTTP.
Nextcloud speaks several native protocols (WebDAV for files, CalDAV for events
and tasks, CardDAV for contacts, and OCS for the Notes app and server info). A
codegen-authored skill body must never speak those directly. This bridge owns the
connection — base URL, username, and app password — and exposes one uniform,
token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` and
`nextcloud_bridge_token` from `ctx.config` and calls a documented route.
There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only
(`urllib` + `xml.etree`) and starts instantly. The connection comes from
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook),
falling back to the top-level `nextcloud_url`/`nextcloud_username`/
`nextcloud_app_password`/`nextcloud_default_calendar` values the calendar seeds
already use, so the same account is configured in one place.
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate
input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated
success.
"""
from __future__ import annotations
import uuid
from .base import BridgeInfo, BridgeService
from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError
#: Nextcloud Deck backs each board with a VTODO-only calendar named like this.
_DECK_PREFIX = "app-generated--deck--"
_COMPONENT_KINDS = {
"VTODO": "task list",
"VEVENT": "event calendar",
"VJOURNAL": "journal",
}
def _supports(calendar: dict, component: str) -> bool:
"""Whether a calendar accepts `component`; unknown (empty) means allow."""
components = calendar.get("components") or []
return not components or component in components
def _is_deck_board(calendar: dict) -> bool:
return str(calendar.get("name") or "").startswith(_DECK_PREFIX)
def _component_kind(component: str) -> str:
return _COMPONENT_KINDS.get(component, "calendar of that kind")
def _join_components(calendar: dict) -> str:
components = calendar.get("components") or []
return ", ".join(components) if components else "an unknown component set"
def _task_list_hint(calendars: list[dict]) -> str:
names = [
c["name"]
for c in calendars
if _supports(c, "VTODO") and not _is_deck_board(c)
]
if names:
return "task lists: " + ", ".join(names)
return "no VTODO-capable task lists are available"
class NextcloudBridge(BridgeService):
name = "nextcloud"
INFO = BridgeInfo(
name="nextcloud",
service="nextcloud",
description=(
"Read and write the user's Nextcloud: files (WebDAV), calendar events "
"and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app)."
),
url_config_var="nextcloud_bridge_url",
endpoints=(
"GET /health -> 200 {\"ok\": true, \"platform\": \"nextcloud\"} — the "
"bridge is up",
"GET /user -> 200 {\"user\": {id, display_name, email, language, "
"locale}} — the account (OCS)",
"GET /capabilities -> 200 {Nextcloud server capabilities} (OCS)",
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{name, path, "
"type (file|dir), size, modified, etag, content_type}]} — list a "
"folder (default /)",
"GET /files/stat?path=<path> -> 200 {one entry, same fields as an "
"entries item}",
"GET /files/read?path=<path> -> 200 {\"path\", \"content\", "
"\"encoding\" (utf-8|base64), \"size\"} — file contents; binary is "
"base64",
"GET /files/search?query=<text>&path=<dir> -> 200 {\"results\": "
"[entry]} — filename search under a folder",
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\"}",
"POST /files/mkdir {\"path\"} -> 200 {\"ok\": true, \"path\"}",
"POST /files/delete {\"path\"} -> 200 {\"ok\": true, \"path\"}",
"POST /files/move {\"path\", \"destination\", \"overwrite\"?: bool} "
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
"POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} "
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
"GET /calendars -> 200 {\"calendars\": [{name, label, description, "
"color, ctag, components}]} — components lists the CalDAV component "
"types each collection accepts (VEVENT, VTODO, VJOURNAL)",
"GET /tasklists -> 200 {\"tasklists\": [{name, label, description, "
"color, ctag, components}]} — the user's task lists (calendars that "
"accept VTODO), excluding Nextcloud Deck boards; use this to pick a "
"target for POST /tasks",
"GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 "
"{\"calendar\", \"events\": [{uid, summary, start, end, all_day, "
"location, description, rrule, status, href, etag}]} — start/end "
"optional (ISO 8601); without them every event is returned",
"POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", "
"\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
"\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", "
"\"calendar\", \"etag\"}",
"POST /calendars/events/update {\"calendar\"?, \"uid\", \"summary\"?, "
"\"start\"?, \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
"\"rrule\"?} -> 200 {\"ok\": true, \"uid\", \"calendar\", \"etag\"} — "
"only the named fields change",
"POST /calendars/events/delete {\"calendar\"?, \"uid\"} -> 200 "
"{\"ok\": true, \"uid\", \"calendar\"}",
"GET /tasks?calendar=<name> -> 200 {\"calendar\", \"tasks\": [{uid, "
"summary, due, status, percent_complete, priority, description, href, "
"etag}]} — CalDAV VTODO; calendar must be a VTODO-capable task list "
"(see GET /tasklists), defaulting to the configured task calendar",
"POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, "
"\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", "
"\"calendar\", \"etag\"} — calendar must be a VTODO-capable task list "
"(see GET /tasklists); an event-only calendar is rejected with 400",
"POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, "
"\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} "
"-> 200 {ok, uid}",
"POST /tasks/complete {\"calendar\"?, \"uid\"} -> 200 {ok, uid} — "
"marks the task COMPLETED",
"POST /tasks/delete {\"calendar\"?, \"uid\"} -> 200 {ok}",
"GET /addressbooks -> 200 {\"addressbooks\": [{name, label, "
"description}]}",
"GET /contacts?addressbook=<name>&query=<text> -> 200 "
"{\"addressbook\", \"contacts\": [{uid, fn, n, emails, phones, org, "
"title, note, url, href, etag}]} — query filters by name/org/email/"
"phone",
"POST /contacts {\"addressbook\"?, \"uid\"?, \"fn\", \"emails\"?, "
"\"phones\"?, \"org\"?, \"title\"?, \"note\"?, \"url\"?, \"n\"?} -> "
"200 {ok, uid}",
"POST /contacts/update {\"addressbook\"?, \"uid\", ...fields} -> 200 "
"{ok, uid}",
"POST /contacts/delete {\"addressbook\"?, \"uid\"} -> 200 {ok}",
"GET /notes -> 200 {\"notes\": [{id, title, category, modified, ...}]} "
"— Nextcloud Notes app (metadata only)",
"GET /notes/get?id=<id> -> 200 {\"note\": {id, title, content, "
"category, ...}}",
"POST /notes {\"title\", \"content\"?, \"category\"?} -> 200 "
"{\"note\": {...}}",
"POST /notes/update {\"id\", \"title\"?, \"content\"?, "
"\"category\"?} -> 200 {\"note\": {...}}",
"POST /notes/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
"503 {\"error\": \"...\"} when the bridge has no Nextcloud connection "
"configured; 502 {\"error\": \"...\"} on a real Nextcloud failure "
"(transport, HTTP error, or bad reply)",
),
config_vars=("nextcloud_bridge_url", "nextcloud_bridge_token"),
config_var_docs=(
(
"nextcloud_bridge_url",
"Base URL of the local Nextcloud bridge (e.g. "
"http://127.0.0.1:5230); never hardcode it in the body.",
),
(
"nextcloud_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="nextcloud_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, fallback: dict | None = None, client=None):
super().__init__(config, trace)
cfg = config or {}
fb = fallback or {}
def pick(key: str, default=""):
value = cfg.get(key)
if value in (None, ""):
value = fb.get(key)
return default if value in (None, "") else value
self.url = str(pick("url")).strip()
self.username = str(pick("username")).strip()
self.app_password = str(pick("app_password"))
self.default_calendar = str(pick("default_calendar")).strip()
self.default_task_calendar = str(pick("default_task_calendar")).strip()
self.default_addressbook = str(pick("default_addressbook")).strip()
self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True)))
self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT))
#: A test seam: inject a client double. Production builds the real one.
self.client = client or NextcloudClient(
self.url,
self.username,
self.app_password,
timeout=self.timeout,
verify_tls=self.verify_tls,
default_calendar=self.default_calendar,
default_addressbook=self.default_addressbook,
)
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
# Stdlib only: no missing dependency can make the bridge unstartable. A
# missing connection surfaces as a 503 on the call, not a startup failure.
return True, None
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
if not self.client.configured:
return self._unconfigured()
try:
return self._get(path, query)
except NextcloudError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if not self.client.configured:
return self._unconfigured()
try:
return self._post(path, payload)
except NextcloudError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def _unconfigured(self) -> tuple[int, dict]:
return 503, {
"error": (
"the Nextcloud bridge has no connection configured (set "
"bridges.nextcloud.url/username/app_password, or the top-level "
"nextcloud_url/nextcloud_username/nextcloud_app_password)"
)
}
def _get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/user":
return 200, {"user": self.client.user_info()}
if path == "/capabilities":
return 200, self.client.capabilities()
if path == "/files":
return 200, self.client.list_files(self._q(query, "path", "/") or "/")
if path == "/files/stat":
return 200, self.client.stat(self._required_query(query, "path"))
if path == "/files/read":
return 200, self.client.read_file(self._required_query(query, "path"))
if path == "/files/search":
query_text = self._required_query(query, "query")
return 200, {
"results": self.client.search(
query_text, self._q(query, "path", "/") or "/"
)
}
if path == "/calendars":
return 200, {"calendars": self.client.list_calendars()}
if path == "/tasklists":
return 200, {"tasklists": self._task_lists()}
if path == "/calendars/events":
calendar = self._resolve_calendar(self._q(query, "calendar"))
return 200, {
"calendar": calendar,
"events": self.client.list_events(
calendar,
self._q(query, "start", "") or "",
self._q(query, "end", "") or "",
),
}
if path == "/tasks":
calendar = self._resolve_calendar(self._q(query, "calendar"), "VTODO")
return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)}
if path == "/addressbooks":
return 200, {"addressbooks": self.client.list_addressbooks()}
if path == "/contacts":
addressbook = self._resolve_addressbook(self._q(query, "addressbook"))
return 200, {
"addressbook": addressbook,
"contacts": self.client.list_contacts(
addressbook, self._q(query, "query", "") or ""
),
}
if path == "/notes":
return 200, {"notes": self.client.list_notes()}
if path == "/notes/get":
return 200, {"note": self.client.get_note(self._required_query(query, "id"))}
return 404, {"error": "not found"}
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
if path == "/files/write":
return 200, self.client.write_file(
self._required(payload, "path"),
self._required(payload, "content", allow_empty=True),
self._optional_str(payload, "encoding", "utf-8"),
self._optional_bool(payload, "overwrite", True),
)
if path == "/files/mkdir":
return 200, self.client.mkdir(self._required(payload, "path"))
if path == "/files/delete":
return 200, self.client.delete(self._required(payload, "path"))
if path == "/files/move":
return 200, self.client.move(
self._required(payload, "path"),
self._required(payload, "destination"),
self._optional_bool(payload, "overwrite", False),
)
if path == "/files/copy":
return 200, self.client.copy(
self._required(payload, "path"),
self._required(payload, "destination"),
self._optional_bool(payload, "overwrite", False),
)
if path == "/calendars/events":
return 200, self._create_event(payload)
if path == "/calendars/events/update":
return 200, self._update_event(payload)
if path == "/calendars/events/delete":
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
if path == "/tasks":
return 200, self._create_task(payload)
if path == "/tasks/update":
return 200, self._update_task(payload)
if path == "/tasks/complete":
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
return 200, self.client.complete_task(calendar, self._required(payload, "uid"))
if path == "/tasks/delete":
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
if path == "/contacts":
return 200, self._create_contact(payload)
if path == "/contacts/update":
return 200, self._update_contact(payload)
if path == "/contacts/delete":
addressbook = self._resolve_addressbook(
self._optional_str(payload, "addressbook")
)
return 200, self.client.delete_contact(
addressbook, self._required(payload, "uid")
)
if path == "/notes":
return 200, {
"note": self.client.create_note(
self._required(payload, "title"),
self._optional_str(payload, "content"),
self._optional_str(payload, "category"),
)
}
if path == "/notes/update":
return 200, {"note": self._update_note(payload)}
if path == "/notes/delete":
return 200, self.client.delete_note(self._required_id(payload))
return 404, {"error": "not found"}
# ---- calendar/task helpers ----
def _create_event(self, payload: dict) -> dict:
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
return self.client.create_event(
calendar,
uid,
summary=self._required(payload, "summary"),
start=self._required(payload, "start"),
end=self._optional_str(payload, "end"),
all_day=self._optional_bool(payload, "all_day", False),
location=self._optional_str(payload, "location"),
description=self._optional_str(payload, "description"),
rrule=self._optional_str(payload, "rrule"),
overwrite=self._optional_bool(payload, "overwrite", False),
)
def _update_event(self, payload: dict) -> dict:
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
uid = self._required(payload, "uid")
changes = {
key: payload[key]
for key in ("summary", "start", "end", "location", "description", "rrule")
if key in payload
}
if "all_day" in payload:
changes["all_day"] = self._optional_bool(payload, "all_day", False)
return self.client.update_event(calendar, uid, **changes)
def _create_task(self, payload: dict) -> dict:
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
return self.client.create_task(
calendar,
uid,
summary=self._required(payload, "summary"),
due=self._optional_str(payload, "due"),
priority=self._optional_int(payload, "priority"),
description=self._optional_str(payload, "description"),
)
def _update_task(self, payload: dict) -> dict:
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
uid = self._required(payload, "uid")
changes = {
key: payload[key]
for key in ("summary", "due", "priority", "description", "status", "percent_complete")
if key in payload
}
return self.client.update_task(calendar, uid, **changes)
# ---- contact helpers ----
def _create_contact(self, payload: dict) -> dict:
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
return self.client.create_contact(
addressbook,
uid,
fn=self._required(payload, "fn"),
n=self._optional_str(payload, "n"),
emails=self._string_list(payload, "emails"),
phones=self._string_list(payload, "phones"),
org=self._optional_str(payload, "org"),
title=self._optional_str(payload, "title"),
note=self._optional_str(payload, "note"),
url=self._optional_str(payload, "url"),
)
def _update_contact(self, payload: dict) -> dict:
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
uid = self._required(payload, "uid")
changes = {}
for key in ("fn", "n", "org", "title", "note", "url"):
if key in payload:
changes[key] = payload[key]
for key in ("emails", "phones"):
if key in payload:
changes[key] = self._string_list(payload, key)
return self.client.update_contact(addressbook, uid, **changes)
# ---- notes helpers ----
def _update_note(self, payload: dict) -> dict:
note_id = self._required_id(payload)
changes = {
key: payload[key] for key in ("title", "content", "category") if key in payload
}
return self.client.update_note(note_id, **changes)
# ---- default resolution ----
def _resolve_calendar(self, name, component: str | None = None) -> str:
"""Resolve a calendar name, honoring the CalDAV component it must accept.
An explicit name is validated when the collection's component set is
known: asking a task operation to write to an event-only calendar is a
real error (a `VTODO` PUT there is rejected), not a silent redirect. With
no name, a task operation falls back to the configured task calendar, then
the event default when it also accepts VTODO, then the sole user task
list. `component=None` (events, files) keeps the historical behavior.
"""
requested = str(name or "").strip()
if requested:
if component:
calendars = self.client.list_calendars()
match = next((c for c in calendars if c.get("name") == requested), None)
if match is not None and not _supports(match, component):
raise ValueError(
f"{requested!r} is not a {_component_kind(component)} "
f"(it accepts {_join_components(match)}); "
f"{_task_list_hint(calendars)}"
)
return requested
# The configured defaults, most specific first. For a task operation the
# event default is still consulted when it also accepts VTODO.
defaults = [self.default_task_calendar] if component == "VTODO" else []
defaults.append(self.default_calendar)
calendars = None
for default in defaults:
if not default:
continue
if not component:
return default
if calendars is None:
calendars = self.client.list_calendars()
match = next((c for c in calendars if c.get("name") == default), None)
if match is None or _supports(match, component):
return default
if calendars is None:
calendars = self.client.list_calendars()
if component:
calendars = [c for c in calendars if _supports(c, component)]
if component == "VTODO":
calendars = [c for c in calendars if not _is_deck_board(c)]
if len(calendars) == 1:
return calendars[0]["name"]
raise ValueError(
f"calendar is required (name one in the request, or set "
f"bridges.nextcloud.default_calendar"
+ (
" / default_task_calendar"
if component == "VTODO"
else ""
)
+ ")"
)
def _task_lists(self) -> list[dict]:
"""The user's task lists: VTODO-capable calendars, minus Deck boards."""
return [
calendar
for calendar in self.client.list_calendars()
if _supports(calendar, "VTODO") and not _is_deck_board(calendar)
]
def _resolve_addressbook(self, name) -> str:
name = str(name or self.default_addressbook or "").strip()
if name:
return name
addressbooks = self.client.list_addressbooks()
if len(addressbooks) == 1:
return addressbooks[0]["name"]
raise ValueError(
"addressbook is required (name one in the request, or set "
"bridges.nextcloud.default_addressbook)"
)
# ---- input helpers ----
@staticmethod
def _q(query: dict, key: str, default=None):
values = query.get(key)
if not values:
return default
return values[0]
@staticmethod
def _required_query(query: dict, key: str) -> str:
value = NextcloudBridge._q(query, key)
if value is None or not str(value).strip():
raise ValueError(f"{key} is required")
return str(value).strip()
@staticmethod
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
value = payload.get(key)
if not isinstance(value, str) or (not allow_empty and not value.strip()):
raise ValueError(f"{key} is required")
return value if allow_empty else value.strip()
@staticmethod
def _required_id(payload: dict):
value = payload.get("id")
if value is None or (isinstance(value, str) and not value.strip()):
raise ValueError("id is required")
return value
@staticmethod
def _optional_str(payload: dict, key: str, default: str = "") -> str:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, str):
raise ValueError(f"{key} must be a string")
return value
@staticmethod
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, bool):
raise ValueError(f"{key} must be a boolean")
return value
@staticmethod
def _optional_int(payload: dict, key: str):
value = payload.get(key)
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"{key} must be an integer")
return value
@staticmethod
def _string_list(payload: dict, key: str) -> list[str]:
value = payload.get(key)
if value is None:
return []
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise ValueError(f"{key} must be a list of strings")
return value
File diff suppressed because it is too large. Load diff
-398
View File
@@ -1,398 +0,0 @@
"""Outlook bridge: the user's Microsoft account (Graph) over HTTP.
Microsoft Graph is a plain HTTPS/JSON API, but a codegen-authored skill body
must still never speak it (or OAuth) directly. This bridge owns the connection —
the Entra ID client id, the tenant, and the stored refresh token — and exposes
one uniform, token-guarded localhost JSON API for mail, calendar, Microsoft To Do
tasks, contacts, and OneDrive files, so a body only reads `outlook_bridge_url`
and `outlook_bridge_token` from `ctx.config` and calls a documented route.
There is no service daemon and no third-party dependency: Graph is plain HTTPS,
so the bridge is stdlib-only (`urllib`) and starts instantly, like Nextcloud.
Authorization is the OAuth2 device code flow, run once with
`scripts/outlook-auth.py`; the resulting tokens are stored (0600) under the
checkout's `.runtime/outlook/token.json`. The bridge starts without them and an
unauthenticated route returns 503 telling the operator to run that helper.
The actual Graph work lives in `outlook_client.py`; the routes here validate
input and map a real failure (`OutlookError`) to a 502 — or a missing
authorization (`OutlookAuthRequired`) to a 503 — rather than a fabricated
success.
"""
from __future__ import annotations
from pathlib import Path
from .base import BridgeInfo, BridgeService
from .outlook_client import (
DEFAULT_SCOPES,
DEFAULT_TENANT,
DEFAULT_TIMEOUT,
OutlookAuthRequired,
OutlookClient,
OutlookError,
)
#: The checkout root (`semif_agent/bridges/outlook.py` -> repo root), used to
#: anchor the default token store under the gitignored `.runtime/` tree.
_REPO_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_TOKEN_PATH = str(_REPO_ROOT / ".runtime" / "outlook" / "token.json")
class OutlookBridge(BridgeService):
name = "outlook"
INFO = BridgeInfo(
name="outlook",
service="outlook",
description=(
"Read and write the user's Microsoft account (Outlook / Microsoft "
"365) through Microsoft Graph: mail, calendar events, Microsoft To "
"Do tasks, contacts, and OneDrive files."
),
url_config_var="outlook_bridge_url",
endpoints=(
"GET /health -> 200 {\"ok\": true, \"platform\": \"outlook\"} — the "
"bridge is up",
"GET /user -> 200 {\"user\": {id, display_name, mail, "
"user_principal_name}} — the signed-in account",
"GET /mail/folders -> 200 {\"folders\": [{id, name, total, unread}]}",
"GET /mail/messages?folder=<name|id>&count=<n>&search=<text>&unread=<bool> "
"-> 200 {\"folder\", \"messages\": [{id, subject, from, to, cc, "
"received, is_read, has_attachments, importance, preview, web_link}]} "
"— newest first; folder defaults to inbox (a well-known name like "
"sentitems/drafts/archive or a folder display name/id)",
"GET /mail/messages/get?id=<id> -> 200 {\"message\": {..., body, "
"body_type}} — the full message",
"POST /mail/send {\"to\": [addr, ...], \"cc\"?: [addr, ...], "
"\"subject\"?, \"body\"?, \"content_type\"?: text|html} -> 200 "
"{\"ok\": true, \"to\", \"cc\", \"subject\"} — sends immediately",
"POST /mail/draft {\"to\"?, \"cc\"?, \"subject\"?, \"body\"?, "
"\"content_type\"?} -> 200 {\"ok\": true, \"id\", \"subject\"} — "
"saves a draft in the Drafts folder",
"GET /calendars -> 200 {\"calendars\": [{id, name, color, "
"is_default, can_edit}]}",
"GET /calendars/events?calendar=<name|id>&start=<iso>&end=<iso> -> "
"200 {\"calendar\", \"events\": [{id, subject, start, end, timezone, "
"all_day, location, preview, show_as, is_online_meeting, web_link, "
"organizer}]} — start/end are ISO 8601 (default: now to +30 days); "
"recurring events are expanded, calendar defaults to the configured "
"or primary calendar",
"POST /calendars/events {\"calendar\"?, \"subject\", \"start\", "
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
"\"attendees\"?: [addr, ...], \"timezone\"?} -> 200 {\"ok\": true, "
"\"id\", \"subject\", \"calendar\", \"web_link\"} — start/end are "
"local ISO 8601 in the named timezone (default UTC when absent); end "
"defaults to +1h (+1 day when all_day)",
"POST /calendars/events/update {\"id\", \"subject\"?, \"start\"?, "
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
"\"timezone\"?} -> 200 {ok, id, subject} — only the named fields change",
"POST /calendars/events/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
"GET /tasklists -> 200 {\"tasklists\": [{id, name, is_owner, "
"is_default}]} — Microsoft To Do lists",
"GET /tasks?list=<name|id> -> 200 {\"list\", \"tasks\": [{id, title, "
"status, importance, due, completed, description, list_id}]} — list "
"defaults to the configured or default list",
"POST /tasks {\"list\"?, \"title\", \"due\"?, \"importance\"?, "
"\"description\"?} -> 200 {\"ok\": true, \"id\", \"title\", "
"\"list_id\"} — importance is low|normal|high; due is ISO 8601",
"POST /tasks/update {\"id\", \"list\"?, \"title\"?, \"due\"?, "
"\"importance\"?, \"status\"?, \"description\"?} -> 200 {ok, id, status}",
"POST /tasks/complete {\"id\", \"list\"?} -> 200 {ok, id, status} — "
"marks the task completed",
"POST /tasks/delete {\"id\", \"list\"?} -> 200 {\"ok\": true, \"id\"}",
"GET /contacts?query=<text>&count=<n> -> 200 {\"contacts\": [{id, "
"display_name, given_name, surname, emails, phones, company, "
"job_title}]} — query filters by name/email/company",
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{id, name, "
"path, size, modified, is_folder, content_type, web_url}]} — OneDrive "
"folder listing (default root)",
"GET /files/read?path=<path> -> 200 {\"path\", \"name\", \"content\", "
"\"encoding\" (utf-8|base64), \"size\", \"content_type\", \"modified\"} "
"— file contents; binary is base64",
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\", "
"\"id\", \"size\", \"web_url\"}",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
"503 {\"error\": \"...\"} when the bridge is not authenticated "
"(run scripts/outlook-auth.py) or has no client id configured; 502 "
"{\"error\": \"...\"} on a real Microsoft Graph failure (transport, "
"HTTP error, or bad reply)",
),
config_vars=("outlook_bridge_url", "outlook_bridge_token"),
config_var_docs=(
(
"outlook_bridge_url",
"Base URL of the local Outlook bridge (e.g. "
"http://127.0.0.1:5231); never hardcode it in the body.",
),
(
"outlook_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="outlook_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, client=None):
super().__init__(config, trace)
cfg = config or {}
self.client_id = str(cfg.get("client_id", "") or "").strip()
self.tenant = str(cfg.get("tenant", DEFAULT_TENANT) or DEFAULT_TENANT).strip() or DEFAULT_TENANT
self.token_path = str(cfg.get("token_path") or DEFAULT_TOKEN_PATH)
self.default_timezone = str(cfg.get("default_timezone", "UTC") or "UTC").strip() or "UTC"
self.default_mail_folder = str(cfg.get("default_mail_folder", "inbox") or "inbox").strip() or "inbox"
#: A test seam: inject a client double. Production builds the real one.
self.client = client or OutlookClient(
self.client_id,
tenant=self.tenant,
token_path=self.token_path,
scopes=cfg.get("scopes") or DEFAULT_SCOPES,
timeout=float(cfg.get("timeout", DEFAULT_TIMEOUT)),
verify_tls=bool(cfg.get("verify_tls", True)),
default_calendar=str(cfg.get("default_calendar", "") or "").strip(),
default_task_list=str(cfg.get("default_task_list", "") or "").strip(),
default_mail_folder=self.default_mail_folder,
default_timezone=self.default_timezone,
)
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
# Stdlib only: no missing dependency can make the bridge unstartable. A
# missing authorization surfaces as a 503 on the call, not a startup failure.
return True, None
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
if not self.client.configured:
return self._unconfigured()
try:
return self._get(path, query)
except OutlookAuthRequired as exc:
return 503, {"error": str(exc)[:300]}
except OutlookError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if not self.client.configured:
return self._unconfigured()
try:
return self._post(path, payload)
except OutlookAuthRequired as exc:
return 503, {"error": str(exc)[:300]}
except OutlookError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def _unconfigured(self) -> tuple[int, dict]:
return 503, {
"error": (
"the Outlook bridge has no connection configured (set "
"bridges.outlook.client_id, then run scripts/outlook-auth.py)"
)
}
def _get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/user":
return 200, {"user": self.client.me()}
if path == "/mail/folders":
return 200, {"folders": self.client.list_mail_folders()}
if path == "/mail/messages":
folder = self._q(query, "folder", "") or ""
return 200, {
"folder": folder or self.default_mail_folder,
"messages": self.client.list_messages(
folder,
self._int_query(query, "count", 25),
self._q(query, "search", "") or "",
self._bool_query(query, "unread", False),
),
}
if path == "/mail/messages/get":
return 200, {"message": self.client.get_message(self._required_query(query, "id"))}
if path == "/calendars":
return 200, {"calendars": self.client.list_calendars()}
if path == "/calendars/events":
return 200, {
"calendar": self._q(query, "calendar", "") or "",
"events": self.client.list_events(
self._q(query, "calendar", "") or "",
self._q(query, "start", "") or "",
self._q(query, "end", "") or "",
),
}
if path == "/tasklists":
return 200, {"tasklists": self.client.list_task_lists()}
if path == "/tasks":
task_list = self._q(query, "list", "") or ""
return 200, {"list": task_list, "tasks": self.client.list_tasks(task_list)}
if path == "/contacts":
return 200, {
"contacts": self.client.list_contacts(
self._q(query, "query", "") or "", self._int_query(query, "count", 50)
)
}
if path == "/files":
folder = self._q(query, "path", "/") or "/"
return 200, {"path": folder, "entries": self.client.list_files(folder)}
if path == "/files/read":
return 200, self.client.read_file(self._required_query(query, "path"))
return 404, {"error": "not found"}
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
if path == "/mail/send":
recipients = self._string_list(payload, "to")
if not recipients:
raise ValueError("to is required")
return 200, self.client.send_mail(
recipients,
self._optional_str(payload, "subject"),
self._optional_str(payload, "body"),
self._string_list(payload, "cc"),
self._optional_str(payload, "content_type", "text") or "text",
)
if path == "/mail/draft":
return 200, self.client.create_draft(
self._string_list(payload, "to"),
self._optional_str(payload, "subject"),
self._optional_str(payload, "body"),
self._string_list(payload, "cc"),
self._optional_str(payload, "content_type", "text") or "text",
)
if path == "/calendars/events":
return 200, self.client.create_event(
calendar=self._optional_str(payload, "calendar"),
subject=self._required(payload, "subject"),
start=self._required(payload, "start"),
end=self._optional_str(payload, "end"),
all_day=self._optional_bool(payload, "all_day", False),
location=self._optional_str(payload, "location"),
description=self._optional_str(payload, "description"),
attendees=self._string_list(payload, "attendees"),
timezone_name=self._optional_str(payload, "timezone"),
)
if path == "/calendars/events/update":
event_id = self._required(payload, "id")
changes = {
key: payload[key]
for key in ("subject", "start", "end", "location", "description")
if key in payload
}
if "all_day" in payload:
changes["all_day"] = self._optional_bool(payload, "all_day", False)
return 200, self.client.update_event(
event_id, timezone_name=self._optional_str(payload, "timezone"), **changes
)
if path == "/calendars/events/delete":
return 200, self.client.delete_event(self._required(payload, "id"))
if path == "/tasks":
return 200, self.client.create_task(
task_list=self._optional_str(payload, "list"),
title=self._required(payload, "title"),
due=self._optional_str(payload, "due"),
importance=self._optional_str(payload, "importance"),
description=self._optional_str(payload, "description"),
)
if path == "/tasks/update":
task_id = self._required(payload, "id")
changes = {
key: payload[key]
for key in ("title", "due", "importance", "status", "description")
if key in payload
}
return 200, self.client.update_task(
task_id, task_list=self._optional_str(payload, "list"), **changes
)
if path == "/tasks/complete":
return 200, self.client.complete_task(
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
)
if path == "/tasks/delete":
return 200, self.client.delete_task(
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
)
if path == "/files/write":
return 200, self.client.write_file(
self._required(payload, "path"),
self._required(payload, "content", allow_empty=True),
self._optional_str(payload, "encoding", "utf-8") or "utf-8",
self._optional_bool(payload, "overwrite", True),
)
return 404, {"error": "not found"}
# ---- input helpers ----
@staticmethod
def _q(query: dict, key: str, default=None):
values = query.get(key)
if not values:
return default
return values[0]
@staticmethod
def _required_query(query: dict, key: str) -> str:
value = OutlookBridge._q(query, key)
if value is None or not str(value).strip():
raise ValueError(f"{key} is required")
return str(value).strip()
@staticmethod
def _int_query(query: dict, key: str, default: int) -> int:
value = OutlookBridge._q(query, key)
if value is None or str(value).strip() == "":
return default
try:
return int(str(value))
except ValueError as exc:
raise ValueError(f"{key} must be an integer") from exc
@staticmethod
def _bool_query(query: dict, key: str, default: bool) -> bool:
value = OutlookBridge._q(query, key)
if value is None or str(value).strip() == "":
return default
return str(value).strip().lower() in ("1", "true", "yes", "on")
@staticmethod
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
value = payload.get(key)
if not isinstance(value, str) or (not allow_empty and not value.strip()):
raise ValueError(f"{key} is required")
return value if allow_empty else value.strip()
@staticmethod
def _optional_str(payload: dict, key: str, default: str = "") -> str:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, str):
raise ValueError(f"{key} must be a string")
return value
@staticmethod
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, bool):
raise ValueError(f"{key} must be a boolean")
return value
@staticmethod
def _string_list(payload: dict, key: str) -> list[str]:
value = payload.get(key)
if value is None:
return []
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise ValueError(f"{key} must be a list of strings")
return value
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more