Compare commits
36
Commits
fc0beb5798
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
addbe53392 | ||
|
|
894a85ec2d | ||
|
|
faebe8a53a | ||
|
|
a8ca65a6e4 | ||
|
|
a6b8617562 | ||
|
|
ec3e6b1b97 | ||
|
|
ed894bd329 | ||
|
|
b1a7bfd272 | ||
|
|
bf071ee529 | ||
|
|
c57983f1f5 | ||
|
|
2296801b22 | ||
|
|
d67ea26f3d | ||
|
|
41c18e6c47 | ||
|
|
16e8583921 | ||
|
|
1329de42c4 | ||
|
|
883c51de97 | ||
|
|
0b02a3feac | ||
|
|
f379c0a746 | ||
|
|
711dba2f03 | ||
|
|
78b4621ba0 | ||
|
|
b953475bf7 | ||
|
|
b15a9e1b45 | ||
|
|
3a5b90b1cb | ||
|
|
e4961ef492 | ||
|
|
6240392632 | ||
|
|
c010cdb44e | ||
|
|
9757ae893e | ||
|
|
1833932f1c | ||
|
|
def51f81dc | ||
|
|
ab0defca1e | ||
|
|
9ba14fdab0 | ||
|
|
c5ee87875f | ||
|
|
88700898be | ||
|
|
ff94ea938c | ||
|
|
a388c292bc | ||
|
|
e2cbf74797 |
No files matched your search
@@ -12,6 +12,8 @@ data/skills/
|
|||||||
data/drafts/
|
data/drafts/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
config.json
|
config.json
|
||||||
|
config/
|
||||||
|
secrets.json
|
||||||
*.log
|
*.log
|
||||||
# Machine-specific material: deployment notes (hostnames, addresses, SSH,
|
# Machine-specific material: deployment notes (hostnames, addresses, SSH,
|
||||||
# model choices), GPU offload probe, benchmark harness. Deliberately not part
|
# model choices), GPU offload probe, benchmark harness. Deliberately not part
|
||||||
@@ -19,3 +21,6 @@ config.json
|
|||||||
local/
|
local/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
*.bak.*
|
*.bak.*
|
||||||
|
# Skill packs live in their own repositories (one per pack) and are cloned into
|
||||||
|
# packs/<name>/ at setup. They are not tracked here. See PACKGEN.md.
|
||||||
|
packs/
|
||||||
@@ -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.
|
||||||
+116
-30
@@ -6,10 +6,19 @@ body must be written.
|
|||||||
The mocking/testing side of a skill is NOT specified here — it has its own
|
The mocking/testing side of a skill is NOT specified here — it has its own
|
||||||
contract, `TESTGEN.md`. This file is about the runnable body only.
|
contract, `TESTGEN.md`. This file is about the runnable body only.
|
||||||
|
|
||||||
|
A skill that ships as a committed starter lives inside a **pack**; how a pack
|
||||||
|
bundles skills, references a bridge, and declares its settings is the separate
|
||||||
|
contract `PACKGEN.md`.
|
||||||
|
|
||||||
## What a skill is
|
## What a skill is
|
||||||
|
|
||||||
Semif-agent is an end-user application: an everyday person asks it to do a task,
|
Semif-agent is an end-user application: an everyday person asks it to do a task,
|
||||||
and it does that task using a combination of native python modules, user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based decision engine known as SemIf.
|
and it does that task using native python modules — including direct HTTP
|
||||||
|
requests to a service's own API — user-provided data, and, where warranted, a
|
||||||
|
catalog of basic services known as bridges. A skill is the thing that performs
|
||||||
|
one of those tasks: it is the leaf in the skill tree that the agent navigates to
|
||||||
|
when it has resolved a request to a single, concrete action. Navigation is
|
||||||
|
performed by an llm-based decision engine known as SemIf.
|
||||||
|
|
||||||
A skill is three things:
|
A skill is three things:
|
||||||
|
|
||||||
@@ -21,7 +30,8 @@ A skill is three things:
|
|||||||
talks to and how) and the `CONTRACT` constant (the values the runner must
|
talks to and how) and the `CONTRACT` constant (the values the runner must
|
||||||
provide).
|
provide).
|
||||||
|
|
||||||
The committed seed `seeds/nextcloud/create_event/` is the **authoritative worked
|
The `nextcloud` pack's create_event skill
|
||||||
|
(`packs/nextcloud/skills/nextcloud/create_event/`, from its own repo) is the **authoritative worked
|
||||||
example** of all three. Read its `manifest.json`, its `skill.py` (which declares
|
example** of all three. Read its `manifest.json`, its `skill.py` (which declares
|
||||||
`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
|
`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
|
||||||
body should look and behave like it.
|
body should look and behave like it.
|
||||||
@@ -137,9 +147,10 @@ engine/runtime concerns, not body-level tools: a body makes direct typed
|
|||||||
decisions and lets the runner own the model.
|
decisions and lets the runner own the model.
|
||||||
|
|
||||||
Note that the runner's own **assessment** of whether a run succeeded
|
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
|
(`assess:outcome`: is there any additional work to be done to satisfy the
|
||||||
goal, and the resolved inputs. The body does not self-assess; it reports
|
request? → done / continue / failed) is itself a SemIf decision over the body's
|
||||||
truthfully and lets SemIf judge.
|
`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
|
### Choosing between deterministic code, SemIf, and LLM text
|
||||||
|
|
||||||
@@ -175,6 +186,14 @@ Rules:
|
|||||||
hand; a title is generated by the LLM, not assembled by string concatenation
|
hand; a title is generated by the LLM, not assembled by string concatenation
|
||||||
when it should be written; a date is parsed by code, not asked of a model.
|
when it should be written; a date is parsed by code, not asked of a model.
|
||||||
|
|
||||||
|
**Connectivity is separate from these three sources.** The table is about
|
||||||
|
*values*, not about how a body reaches a service. A body calls a **plain HTTP
|
||||||
|
API directly** with a stdlib transport (endpoint and credentials read from
|
||||||
|
`ctx.config`); a bridge is only for a service that needs state (especially auth
|
||||||
|
state), a native or heavy protocol, or one sanitized surface. See "Bridge
|
||||||
|
services" below for when to use one — and the hard rule for a service a bridge
|
||||||
|
already fronts.
|
||||||
|
|
||||||
## The registry entry
|
## The registry entry
|
||||||
|
|
||||||
The body writer does **not** author a manifest. The `llm` provider authors the
|
The body writer does **not** author a manifest. The `llm` provider authors the
|
||||||
@@ -193,8 +212,7 @@ The registry is a map of category -> bucket:
|
|||||||
{
|
{
|
||||||
"name": "<leaf_name>",
|
"name": "<leaf_name>",
|
||||||
"description": "<what this leaf does, for navigation>",
|
"description": "<what this leaf does, for navigation>",
|
||||||
"request_text": "<the originating request, optional>",
|
"goal": "<the de-identified, reusable action statement>"
|
||||||
"requirements": {"<question>": "<answer>"}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -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_]+)*`),
|
- 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
|
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.
|
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
|
- `goal` is the de-identified, reusable action statement authored by the local
|
||||||
be re-driven later; the body never sets them.
|
`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
|
## Code body contract
|
||||||
|
|
||||||
@@ -283,8 +303,12 @@ def act(ctx, request) -> ActionResult:
|
|||||||
`ctx.config` (the resolved values for this skill, including its own config),
|
`ctx.config` (the resolved values for this skill, including its own config),
|
||||||
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
|
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
|
||||||
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
|
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
|
||||||
`ctx.admin` exists for the built-in housekeeping meta skills only; an ordinary
|
`ctx.catalog` is a **read-only** view of the agent's own skill tree for an
|
||||||
body must never touch it.
|
introspection skill that reports what the agent can do: `ctx.catalog.categories()`
|
||||||
|
returns a `{category_id: description}` map and `ctx.catalog.skills(category)`
|
||||||
|
the leaf names inside one category (the `skills.list_categories` /
|
||||||
|
`skills.list_skills` seeds). `ctx.admin` exists for the built-in housekeeping
|
||||||
|
meta skills only; an ordinary body must never touch it.
|
||||||
- `request` is the `Request` being handled.
|
- `request` is the `Request` being handled.
|
||||||
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
|
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
|
||||||
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
|
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
|
||||||
@@ -386,7 +410,7 @@ INTEGRATION = {
|
|||||||
skills that perform no external action at all (pure analysis/formatting); an
|
skills that perform no external action at all (pure analysis/formatting); an
|
||||||
action skill must not use it.
|
action skill must not use it.
|
||||||
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
|
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
|
||||||
the committed seeds this is exactly the body's `CONTRACT` key set; an empty
|
the shipped seeds this is exactly the body's `CONTRACT` key set; an empty
|
||||||
list is allowed for `compute`. Declaring a variable the body never reads is a
|
list is allowed for `compute`. Declaring a variable the body never reads is a
|
||||||
mismatch the fidelity check flags.
|
mismatch the fidelity check flags.
|
||||||
|
|
||||||
@@ -451,14 +475,44 @@ Rules:
|
|||||||
the result is a broken output.
|
the result is a broken output.
|
||||||
- **Never an empty or placeholder output.** If there is genuinely nothing (empty
|
- **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
|
inbox, no matching event), say so explicitly — that is a real result, and a
|
||||||
**successful** run: the `assess:outcome` step treats a definitive "nothing
|
**`done`** run: the `assess:outcome` step treats a definitive "nothing found /
|
||||||
found / nothing to do" result as success. Phrase it as the answer the user
|
nothing to do" result as done. Phrase it as the answer the user asked for
|
||||||
asked for ("checked the inbox: no unread messages"), not as an absence or an
|
("checked the inbox: no unread messages"), not as an absence or an error, so
|
||||||
error, so the assessment does not read a healthy empty result as a failure.
|
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
|
- **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
|
real failure in `action_log` and set `new_state` back to `request.text` (see
|
||||||
the hard requirements).
|
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)
|
### Rules (hard requirements)
|
||||||
|
|
||||||
- **Perform the real action.** If the skill's purpose involves an external
|
- **Perform the real action.** If the skill's purpose involves an external
|
||||||
@@ -518,26 +572,47 @@ Rules:
|
|||||||
see how `nextcloud.create_event` caches the extracted title/description and the
|
see how `nextcloud.create_event` caches the extracted title/description and the
|
||||||
answers it collected.
|
answers it collected.
|
||||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
- **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
|
- **The function is `act` exactly.** The module is imported under its registered
|
||||||
leaf name; the entry point is a module-level `act(ctx, request)`.
|
leaf name; the entry point is a module-level `act(ctx, request)`.
|
||||||
|
|
||||||
## Bridge services
|
## Bridge services
|
||||||
|
|
||||||
Some real systems are reached through a **bridge service**: a standalone local
|
A body reaches a real service with a stdlib transport. A **plain HTTP API** is
|
||||||
process that stands up a small, token-guarded HTTP API in front of the system
|
called directly — `urllib.request` / `http.client`, endpoint and credentials read
|
||||||
and owns its native protocol and credentials. The concrete catalog of bridges —
|
from `ctx.config` — and needs no bridge. Some systems, however, are reached
|
||||||
which services exist, their base-URL config var, auth, config vars, and the
|
through a **bridge service**: a standalone local process that stands up a small,
|
||||||
exact endpoints with their request/response/error shapes — is injected into the
|
token-guarded HTTP API in front of the system and owns its native protocol,
|
||||||
prompt at authoring time (render it with
|
credentials, and connection state. Reach for a bridge only when a simple,
|
||||||
|
repeatable skill file would otherwise be inconsistent, inconvenient, or unsafe:
|
||||||
|
|
||||||
|
- **State, especially auth state.** The service needs an OAuth token, a session
|
||||||
|
cookie, a live daemon connection, a read cursor, or other state a stateless,
|
||||||
|
re-run-from-the-top `act` cannot own.
|
||||||
|
- **Sanitized connectivity.** You want one narrow, token-guarded, audited
|
||||||
|
surface instead of arbitrary bodies speaking the service's raw protocol.
|
||||||
|
- **A native or heavy protocol.** The service speaks WebSocket/DAV/OCS or needs
|
||||||
|
a third-party dependency (a browser, a mail client) a one-file stdlib body
|
||||||
|
must not carry.
|
||||||
|
|
||||||
|
When a bridge **does** front a service, the body calls the bridge and must never
|
||||||
|
reach around it to the service's native protocol — no WebSocket to
|
||||||
|
`simplex-chat`, no direct daemon access, no DAV/OCS hand-rolling. It calls the
|
||||||
|
bridge's HTTP API with the base URL from the bridge's config variable, exactly
|
||||||
|
like any other HTTP integration:
|
||||||
|
|
||||||
|
The concrete catalog of bridges — which services exist, their base-URL config
|
||||||
|
var, auth, config vars, and the exact endpoints with their request/response/error
|
||||||
|
shapes — is injected into the prompt at authoring time (render it with
|
||||||
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This
|
`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This
|
||||||
section is only the generic pattern; the catalog is the source of truth for the
|
section is only the generic pattern; the catalog is the source of truth for the
|
||||||
bridge-specific details.
|
bridge-specific details.
|
||||||
|
|
||||||
A body must never speak a service's native protocol directly — no WebSocket to
|
|
||||||
`simplex-chat`, no direct daemon access. It calls the bridge's HTTP API with the
|
|
||||||
base URL from the bridge's config variable, exactly like any other HTTP
|
|
||||||
integration:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
INTEGRATION = {
|
INTEGRATION = {
|
||||||
"service": "<the bridge's service id, from the catalog>",
|
"service": "<the bridge's service id, from the catalog>",
|
||||||
@@ -548,6 +623,9 @@ INTEGRATION = {
|
|||||||
|
|
||||||
Rules:
|
Rules:
|
||||||
|
|
||||||
|
- **A plain HTTP service needs no bridge.** If the service exposes a normal HTTP
|
||||||
|
API and needs none of the three triggers above, call it directly with a stdlib
|
||||||
|
transport; declare its endpoint in `CONTRACT` and read it from `ctx.config`.
|
||||||
- **Read every value from `ctx.config`.** The base URL, any token, and any
|
- **Read every value from `ctx.config`.** The base URL, any token, and any
|
||||||
default (recipient/contact/target) come from the config vars the catalog
|
default (recipient/contact/target) come from the config vars the catalog
|
||||||
lists. Never hardcode a host, port, or bridge address in the body.
|
lists. Never hardcode a host, port, or bridge address in the body.
|
||||||
@@ -575,6 +653,9 @@ Rules:
|
|||||||
|
|
||||||
- Single purpose, single file, single module.
|
- Single purpose, single file, single module.
|
||||||
- Avoid duplicating an existing skill in the same category.
|
- Avoid duplicating an existing skill in the same category.
|
||||||
|
- Reach a plain HTTP API directly; use a bridge only for a service that needs
|
||||||
|
state/auth, a native or heavy protocol, or one sanitized surface — and never
|
||||||
|
reach around a bridge that fronts the service.
|
||||||
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
|
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
|
||||||
sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar
|
sub-decisions, mirroring how `nextcloud.create_event` resolves which calendar
|
||||||
to write to.
|
to write to.
|
||||||
@@ -616,9 +697,14 @@ A generated skill is accepted only if:
|
|||||||
11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
|
11. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
|
||||||
and is consistent with the body's `ctx.config` reads and behavior.
|
and is consistent with the body's `ctx.config` reads and behavior.
|
||||||
12. It does no network, file, or engine work at import time.
|
12. It does no network, file, or engine work at import time.
|
||||||
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
|
13. If the service it targets is fronted by a bridge, it calls that bridge over
|
||||||
service's native protocol), resolves recipients with a SemIf sub-decision,
|
HTTP (never the service's native protocol); otherwise it may call the
|
||||||
and sends only on explicit user intent.
|
service's HTTP API directly. A messaging skill resolves recipients with a
|
||||||
|
SemIf sub-decision and sends only on explicit user intent.
|
||||||
|
14. It is small enough to be ingested whole by the fidelity decision (a body
|
||||||
|
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
|
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
|
||||||
body outright. The rest are not statically rejected: a missing or inconsistent
|
body outright. The rest are not statically rejected: a missing or inconsistent
|
||||||
|
|||||||
+468
@@ -0,0 +1,468 @@
|
|||||||
|
# PACKGEN.md — the contract for new packs
|
||||||
|
|
||||||
|
This file is the authoritative spec for what a **pack** is and how to author a
|
||||||
|
new one. It is the third sibling of the skill contracts: `CODEGEN.md` governs a
|
||||||
|
skill's runnable **body**, `TESTGEN.md` governs its **test**, and this file
|
||||||
|
governs the **pack** that bundles a concern, its skills, its bridge reference,
|
||||||
|
and its settings into one thing.
|
||||||
|
|
||||||
|
Read this before adding a pack. A pack is what makes a new
|
||||||
|
product/concern a first-class part of the agent instead of scattered edits to
|
||||||
|
`skills.py` and `config.py`.
|
||||||
|
|
||||||
|
## What a pack is
|
||||||
|
|
||||||
|
Semif-agent ships a set of starter integrations. Each is a **pack**: a folder
|
||||||
|
`packs/<name>/` holding a `pack.json` manifest plus a `skills/` store of leaves
|
||||||
|
in the exact generated-skill format. Each pack lives in its **own repository**
|
||||||
|
(`pack.<name>`, listed in the `semif-packs` pack-index repo); `scripts/bootstrap.sh`
|
||||||
|
clones them into the gitignored `packs/<name>/`. The manifest binds the pieces
|
||||||
|
that would otherwise be scattered by convention:
|
||||||
|
|
||||||
|
- the **concern** (what product/job this is) and its **title**;
|
||||||
|
- its **categories** (the tree buckets it owns, each with a scope description);
|
||||||
|
- the **bridge(s)** it talks to, referenced by name — and **ships** the bridge
|
||||||
|
code itself under `bridge/` (see "Authoring a new bridge");
|
||||||
|
- its **runtime requirements** (optional heavy deps);
|
||||||
|
- its **enable flag**; and
|
||||||
|
- its **config schema** (the defaults and validation for its settings).
|
||||||
|
|
||||||
|
A pack is loaded by `semif_agent/packs.py` (`PackRegistry` discovers packs,
|
||||||
|
`merge_packs` loads every **enabled** pack into the tree at startup) and its
|
||||||
|
`config` schema is read by `semif_agent/config.py` to generate
|
||||||
|
`config.example.json` and to validate a live config.
|
||||||
|
|
||||||
|
Three boundaries must stay crisp:
|
||||||
|
|
||||||
|
- A **skill** is one leaf action (`packs/<name>/skills/<category>/<leaf>/`),
|
||||||
|
governed by `CODEGEN.md`/`TESTGEN.md`. A pack contains skills; it is not one.
|
||||||
|
- A **bridge** is a standalone process in front of a third-party system,
|
||||||
|
warranted when the system needs state (especially auth state), a native or
|
||||||
|
heavy protocol, or one sanitized surface; a system with a plain HTTP API needs
|
||||||
|
no bridge — its skill calls the API directly. A bridge **ships with its pack**
|
||||||
|
(`packs/<name>/bridge/`); the core keeps only the shared contract
|
||||||
|
(`semif_agent/bridges/base.py`) and the discovery registry
|
||||||
|
(`semif_agent/bridges/registry.py`). The one shared, pack-less bridge is the
|
||||||
|
**LLM bridge** (a core built-in many packs call). A pack's `bridges` list names
|
||||||
|
the bridge(s) it ships; a pack never edits core bridge code.
|
||||||
|
- A pack is **declarative structure**, committed in its own repository.
|
||||||
|
Per-machine values are the split config; credentials live in `secrets.json`.
|
||||||
|
A pack repo never holds a secret.
|
||||||
|
|
||||||
|
## Folder layout
|
||||||
|
|
||||||
|
```
|
||||||
|
packs/<name>/
|
||||||
|
pack.json # the manifest (this file's subject)
|
||||||
|
requirements.txt # optional: the pack's own python deps (pip format)
|
||||||
|
skills/<category>/<leaf>/
|
||||||
|
skill.py # the body — CODEGEN.md
|
||||||
|
manifest.json # {"description": "..."} navigation text
|
||||||
|
contract.json # mirror of the body's CONTRACT — TESTGEN.md
|
||||||
|
skill.test.py # hermetic mechanics test — TESTGEN.md
|
||||||
|
bridge/ # only for a bridge-backed pack (see below)
|
||||||
|
__init__.py # the pack's bridge package
|
||||||
|
<bridge>.py # the BridgeService subclass (bridge name)
|
||||||
|
<bridge>_client.py # optional protocol client (e.g. nextcloud_client.py)
|
||||||
|
test_<bridge>_bridge.py # hermetic bridge test (loopback HTTP)
|
||||||
|
scripts/ # optional concern helpers (e.g. an auth or
|
||||||
|
# setup script), run from the checkout
|
||||||
|
```
|
||||||
|
|
||||||
|
- The `<category>` directory name is the tree bucket; the `<leaf>` directory
|
||||||
|
name is the leaf's `name`. The runner joins them as `category.name` only in
|
||||||
|
run summaries.
|
||||||
|
- Every leaf carries the four artifacts above. Their contents are governed by
|
||||||
|
`CODEGEN.md` (body + `CONTRACT` + `INTEGRATION`) and `TESTGEN.md`
|
||||||
|
(test + `contract.json` mirror); do not restate those rules here.
|
||||||
|
- `bridge/` ships the pack's bridge (one module per name in `bridges`, plus
|
||||||
|
optional sibling modules it imports relatively). It is absent for a
|
||||||
|
bridge-less pack. See "Authoring a new bridge".
|
||||||
|
- `requirements.txt` is the pack's own optional python deps (standard pip
|
||||||
|
format); it is absent for a stdlib-only pack. See "Pack python deps".
|
||||||
|
- `manifest.json` holds a single non-empty `description` — the navigation text
|
||||||
|
SemIf routes on. It is the seed analog of the registry entry a generated
|
||||||
|
skill gets from the `llm` provider.
|
||||||
|
- A root with no `pack.json` is treated as **one implicit, manifest-less pack**
|
||||||
|
whose store is the root itself (a plain skills directory still works), but a
|
||||||
|
pack repo should always have a manifest.
|
||||||
|
|
||||||
|
The shipped packs are the authoritative worked examples: `essentials` is
|
||||||
|
the minimal bridge-less pack; `nextcloud`, `simplex`, `outlook`, and `browser`
|
||||||
|
are bridge-backed packs.
|
||||||
|
|
||||||
|
## `pack.json` — the manifest
|
||||||
|
|
||||||
|
A single JSON object. Fields (from `packs._parse_pack`):
|
||||||
|
|
||||||
|
| Field | Type | Required | Meaning |
|
||||||
|
| -------------------- | --------------- | -------- | ------- |
|
||||||
|
| `name` | string | no\* | Pack id (snake_case). Defaults to the folder name. |
|
||||||
|
| `title` | string | no | Human display name. Defaults to `name`. |
|
||||||
|
| `concern` | string | **yes** | One- to two-sentence statement of the product/job the pack serves. (`description` is accepted as a legacy alias.) |
|
||||||
|
| `categories` | object | **yes** | `{category_id: scope_description}` — the tree buckets this pack owns. |
|
||||||
|
| `bridges` | array of string | no | Bridge names this pack ships and talks to. Each name is a `bridge/<name>.py` module in the pack; `simplex`/`llm`/`nextcloud`/`outlook`/`browser` are the shipped names. Empty for a bridge-less pack. |
|
||||||
|
| `requires` | array of string | no | Optional heavy deps named at a glance (e.g. `playwright`). Informational — the pinned install list is the pack's own `requirements.txt` (see "Pack python deps"), and the code's `check_requirements` is what enforces them at runtime. |
|
||||||
|
| `enabled_by_default` | bool | no | Default `true`. Whether the pack loads when nothing else decides. |
|
||||||
|
| `config` | object | no | The pack's config schema (see below). |
|
||||||
|
|
||||||
|
\* `name` is optional in the parser but should always be set explicitly.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **`concern` and `categories` are required** (`tests/test_packs.py` fails
|
||||||
|
without them). A pack with no declared concern is not a pack.
|
||||||
|
- **Category ids are the tree keys.** They are the same ids the leaf folders
|
||||||
|
live under (`skills/<category>/<leaf>/`). When `categories` is omitted, the
|
||||||
|
pack's categories are inferred from the `skills/` subdirectories — but declare
|
||||||
|
them, because the description is load-bearing.
|
||||||
|
- **A category description is navigation-critical.** It is what SemIf reads to
|
||||||
|
route a request into the bucket; a bare id with no description routes badly.
|
||||||
|
Write one to two sentences naming the concrete jobs the category does.
|
||||||
|
- **`bridges[0]` owns the config block.** For a bridge pack, the pack's `config`
|
||||||
|
schema maps onto `bridges.<bridges[0]>`; only the first bridge gets the block
|
||||||
|
(a pack normally fronts one bridge). Each name in `bridges` must have a
|
||||||
|
`bridge/<name>.py` module that defines its `BridgeService` subclass.
|
||||||
|
- Keep the manifest minimal: it binds metadata and settings, nothing executable.
|
||||||
|
|
||||||
|
## The config schema
|
||||||
|
|
||||||
|
`config` is a nested schema. A **leaf** is a dict with a `default`; a **block**
|
||||||
|
is a dict without one (recurse). Each leaf spec:
|
||||||
|
|
||||||
|
| Key | Type | Meaning |
|
||||||
|
| --------- | ------ | ------- |
|
||||||
|
| `type` | string | `bool` \| `int` \| `float` \| `str` \| `list` \| `dict`. Checked by `check-config` (`int`/`float` are interchangeable). |
|
||||||
|
| `default` | any | The value shipped in `config.example.json` and seeded by `config-init`. Required on a leaf. |
|
||||||
|
| `doc` | string | One-line plain-language description. Shown in the generated example. |
|
||||||
|
| `secret` | bool | `true` marks a credential: the example emits `"!secret <pack>_<key>"` instead of a value. |
|
||||||
|
|
||||||
|
Example (a bridge-backed pack, mirroring `packs/simplex/pack.json`):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"config": {
|
||||||
|
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
|
||||||
|
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
|
||||||
|
"port": {"type": "int", "default": 5227, "doc": "Bridge listen port."},
|
||||||
|
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
|
||||||
|
"reconnect": {
|
||||||
|
"initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."},
|
||||||
|
"max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
How the schema maps onto the live config (`config.default_config` /
|
||||||
|
`generate_example_config`):
|
||||||
|
|
||||||
|
- A **bridge pack** (`bridges` non-empty) maps its whole `config` schema onto
|
||||||
|
the `bridges.<bridges[0]>` block.
|
||||||
|
- A **bridge-less pack** maps only its `enabled` flag onto
|
||||||
|
`packs.<name>.enabled`; its other keys are not carried (a bridge-less pack is
|
||||||
|
configured through its skills' own config, not a pack block).
|
||||||
|
- Secret leaves become `"!secret <pack>_<key>"` in `config.example.json`, where
|
||||||
|
`<pack>_` is the pack name prefix (nested keys are prefixed with their path,
|
||||||
|
e.g. `simplex_reconnect_initial`). Never write a real credential into the
|
||||||
|
manifest.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- Every leaf needs a `default` and a `doc`. A key with no `default` is treated
|
||||||
|
as a nested block.
|
||||||
|
- Put **operational** settings here (endpoints, accounts, defaults, timeouts) —
|
||||||
|
the values a skill body reads from `ctx.config`. Per-request arguments never
|
||||||
|
belong in config (see `CODEGEN.md`).
|
||||||
|
- `config.json`, `config/`, and `secrets.json` are gitignored and per-machine.
|
||||||
|
The manifest is committed structure only.
|
||||||
|
|
||||||
|
After changing a schema, regenerate and validate:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m semif_agent.cli check-config --write-example config.example.json
|
||||||
|
python -m semif_agent.cli check-config
|
||||||
|
```
|
||||||
|
|
||||||
|
`config-init` seeds the split `config/` layout from the schemas (bootstrap runs
|
||||||
|
it once, only when `config.json` is absent); afterwards only a human edits it.
|
||||||
|
The generated example and the live config are never hand-edited.
|
||||||
|
|
||||||
|
## Pack python deps
|
||||||
|
|
||||||
|
A pack owns the python packages its skills and bridge need. Put them in
|
||||||
|
`packs/<name>/requirements.txt` (standard pip requirements format, pinned) —
|
||||||
|
**not** in the agent repo's `requirements/`. A pack that is stdlib-only ships no
|
||||||
|
file.
|
||||||
|
|
||||||
|
How the injection works:
|
||||||
|
|
||||||
|
- `SkillPack.requirements_file` (`semif_agent/packs.py`) resolves
|
||||||
|
`packs/<name>/requirements.txt` when it exists.
|
||||||
|
- The install plan lists those packs: `setup.build_plan` /
|
||||||
|
`setup.plan_from_config` set `pack_requirements` to the selected/enabled packs
|
||||||
|
that ship one (`scripts/bootstrap.sh` reads the plan).
|
||||||
|
- Bootstrap installs each listed pack's file into `.runtime/venv` **after**
|
||||||
|
cloning the selected packs and creating the venv, and only for packs the host
|
||||||
|
actually selected (a host that never enables the pack installs nothing). The
|
||||||
|
`--browser` flag force-adds the browser pack's deps.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Lazy-import** every heavy dep in the pack's bridge/skills so a host without
|
||||||
|
the pack still runs — the core stays stdlib-only. A missing dep is a per-call
|
||||||
|
`503` with an install hint (see "Authoring a new bridge"), never a crash.
|
||||||
|
- **Pin** the versions (this is a shipped integration, not an app you upgrade in
|
||||||
|
place). If a dep needs a non-pip step (a downloaded binary, a system package),
|
||||||
|
ship a helper under `scripts/` and document it in the pack's
|
||||||
|
`requirements.txt` header — the browser pack's Chromium download is the model.
|
||||||
|
- `requires` in the manifest is the human-readable summary of the heavy deps;
|
||||||
|
`requirements.txt` is the authoritative install list. Keep them consistent.
|
||||||
|
- Never put a credential or a per-machine value in `requirements.txt`; it is
|
||||||
|
committed structure like the rest of the pack.
|
||||||
|
|
||||||
|
## The enable switch
|
||||||
|
|
||||||
|
One switch governs the pack's skills **and** its bridge, so a host never offers
|
||||||
|
a skill whose bridge is off. `packs.pack_enabled` resolves in order:
|
||||||
|
|
||||||
|
1. an explicit `packs.<name>.enabled` in config (wins);
|
||||||
|
2. else, for a bridge pack, `bridges.<bridges[0]>.enabled` (the historical
|
||||||
|
switch);
|
||||||
|
3. else `enabled_by_default`.
|
||||||
|
|
||||||
|
Disabling a pack drops its categories entirely — including any generated body
|
||||||
|
authored into one — and stops its bridge. The switch lives in the pack's
|
||||||
|
`config/packs/<name>.json` fragment (written by `config-init`/`check-config`).
|
||||||
|
|
||||||
|
## Referencing a bridge by name
|
||||||
|
|
||||||
|
A pack whose skills talk to a third-party system lists that bridge in
|
||||||
|
`bridges`, **ships** it under `bridge/`, and carries its config block in
|
||||||
|
`config`. (A pack whose skills reach a plain HTTP API directly needs no bridge:
|
||||||
|
`bridges` stays empty and each leaf declares the endpoint in its own
|
||||||
|
`CONTRACT`.) The bridge itself is a `BridgeService` subclass in
|
||||||
|
`packs/<name>/bridge/<name>.py`; the core registry imports it by convention and
|
||||||
|
its `BridgeInfo` (name, service, description, URL config var, other config vars,
|
||||||
|
auth header, endpoints) is injected into every codegen prompt via
|
||||||
|
`describe_bridges()`, so bodies learn how to reach it without the pack restating
|
||||||
|
protocol details. The one exception is the shared, pack-less **LLM bridge**
|
||||||
|
(a core built-in).
|
||||||
|
|
||||||
|
Skill-facing config is **derived**, never duplicated: `derived_config_vars`
|
||||||
|
turns the bridge's `bridges.<name>` block (`host`/`port`/`token`) into the
|
||||||
|
`<url_config_var>` and `<auth_config_var>` values a body reads from
|
||||||
|
`ctx.config` (e.g. `simplex_bridge_url`, `simplex_bridge_token`). Bodies call
|
||||||
|
the bridge over the ordinary `http` transport; their hermetic tests are
|
||||||
|
loopback HTTP like any other HTTP body.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- The bridge block's `enabled`/`host`/`port`/`token` are the pack's config
|
||||||
|
schema; the URL/token config vars are derived and must not be declared again.
|
||||||
|
- A pack ships its own bridge and never imports or edits another pack's or the
|
||||||
|
core's. Gateway isolation is non-negotiable — read/send/address capability is
|
||||||
|
a bridge, never a gateway feature.
|
||||||
|
|
||||||
|
## Authoring a new bridge
|
||||||
|
|
||||||
|
A **bridge** is a standalone process that stands up a simple, secure localhost
|
||||||
|
HTTP layer in front of one third-party system. Author one when a skill body
|
||||||
|
cannot sanely talk to the system itself — because it holds auth/session state,
|
||||||
|
needs a native or heavy protocol, or should be reached through one sanitized
|
||||||
|
surface. A system with a plain HTTP API needs no bridge: its skill calls the API
|
||||||
|
directly. Adding a bridge means:
|
||||||
|
|
||||||
|
1. **Write the bridge class** in the pack's `bridge/<name>.py`, subclassing
|
||||||
|
`BridgeService` (`semif_agent/bridges/base.py`). Set the `name` attribute and
|
||||||
|
a module-level/class `INFO = BridgeInfo(...)`. Ship `bridge/__init__.py` (the
|
||||||
|
package marker) and any sibling modules the bridge imports relatively (e.g.
|
||||||
|
`bridge/<name>_client.py` for the protocol client):
|
||||||
|
|
||||||
|
```python
|
||||||
|
from semif_agent.bridges.base import BridgeInfo, BridgeService
|
||||||
|
|
||||||
|
class WidgetBridge(BridgeService):
|
||||||
|
name = "widget"
|
||||||
|
INFO = BridgeInfo(
|
||||||
|
name="widget",
|
||||||
|
service="widget_service",
|
||||||
|
description="The user's Widget account: widgets and their status.",
|
||||||
|
url_config_var="widget_bridge_url",
|
||||||
|
endpoints=(
|
||||||
|
"GET /widgets — list widgets",
|
||||||
|
"POST /widgets — create a widget",
|
||||||
|
),
|
||||||
|
config_vars=("widget_bridge_token",),
|
||||||
|
config_var_docs=(("widget_bridge_token", "Shared secret for the X-Semif-Token header."),),
|
||||||
|
auth_header="X-Semif-Token",
|
||||||
|
auth_config_var="widget_bridge_token",
|
||||||
|
)
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
return True, None # stdlib-only
|
||||||
|
|
||||||
|
def handle_get(self, path, query): ...
|
||||||
|
def handle_post(self, path, payload): ...
|
||||||
|
```
|
||||||
|
|
||||||
|
The base class owns the HTTP/JSON/auth plumbing (`start`/`stop`, the
|
||||||
|
`X-Semif-Token` guard); a subclass implements only its routes. Override
|
||||||
|
`start`/`stop`/`_stop_transport` only if the bridge owns a service daemon.
|
||||||
|
Anchor checkout-relative paths (e.g. a token store under `.runtime/`) with
|
||||||
|
`semif_agent.bridges.base.checkout_root()`, never from the bridge's own
|
||||||
|
`__file__` — the bridge ships in its pack, so its path is pack-relative.
|
||||||
|
|
||||||
|
2. **Declare it** in the pack's `bridges` list and ship its module at
|
||||||
|
`bridge/<name>.py`. That is what makes it discoverable, describable to
|
||||||
|
codegen, and runnable via `python -m semif_agent.cli bridge` — there is no
|
||||||
|
core `CATALOG` to edit.
|
||||||
|
|
||||||
|
3. **Carry its config block** in the pack's `config` schema
|
||||||
|
(`enabled`/`host`/`port`/`token` plus service vars). The schema is what gives
|
||||||
|
the bridge its config defaults and validation.
|
||||||
|
|
||||||
|
4. **Override `BridgeService.from_config`** only when the bridge needs more than
|
||||||
|
its own block: the scheduler's configured `llm` client (the shared LLM
|
||||||
|
bridge) or top-level fallback values (like Nextcloud's `nextcloud_*`). A
|
||||||
|
plain bridge uses the default and needs no override.
|
||||||
|
|
||||||
|
5. **Heavy/optional deps:** `check_requirements()` must **never raise** and must
|
||||||
|
return `(ok, install_hint)`. `run_bridges` aborts **all** bridges when one
|
||||||
|
reports `ok=False`, so a bridge with an optional dependency (like the
|
||||||
|
browser) must return `(True, None)` and surface a per-call `503` with an
|
||||||
|
install hint instead — a missing browser must not take down simplex/llm/
|
||||||
|
nextcloud. Lazy-import every heavy dep so the core stays stdlib-only.
|
||||||
|
|
||||||
|
6. **Report real failures:** a transport/HTTP/bad-reply failure is a `502`, a
|
||||||
|
missing connection/dep is a `503`, bad input a `400` — never a fabricated
|
||||||
|
success. The bridge owns its own state (cursors, daemons); bodies keep none.
|
||||||
|
|
||||||
|
7. **Test it hermetically:** add `bridge/test_<name>_bridge.py` driving the real
|
||||||
|
routes over a loopback `http.server` (inject a fake driver where a real
|
||||||
|
service would be needed). No external network, no real daemon. Import the
|
||||||
|
bridge through the core registry
|
||||||
|
(`load_pack_bridge_module("<pack>", "<name>")`) so the test also proves the
|
||||||
|
pack's bridge is discoverable; `tests/test_packs.py` runs it from the
|
||||||
|
checkout. `describe_bridges()` picks the new bridge up automatically.
|
||||||
|
|
||||||
|
8. **Regenerate** `config.example.json` and run `check-config` (see above), and
|
||||||
|
document the bridge in `AGENTS.md` (bridges section). Never widen the
|
||||||
|
gateway for a new capability.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
A new pack is accepted only if:
|
||||||
|
|
||||||
|
1. `packs/<name>/pack.json` parses as JSON, declares a non-empty `concern` and
|
||||||
|
a non-empty `categories` map, and every `bridges` name has a
|
||||||
|
`bridge/<name>.py` module defining its `BridgeService` subclass.
|
||||||
|
2. Every leaf under `skills/<category>/<leaf>/` is a complete skill folder
|
||||||
|
(`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`) satisfying
|
||||||
|
`CODEGEN.md` and `TESTGEN.md`: a module-level `act`, a flat `CONTRACT` whose
|
||||||
|
every key is read from `ctx.config`, an `INTEGRATION` consistent with the
|
||||||
|
code, a non-empty `manifest.json` `description`, and `contract.json` an exact
|
||||||
|
mirror of the body's `CONTRACT`.
|
||||||
|
3. The leaf's hermetic mechanics test passes
|
||||||
|
(`python skill.test.py` from the leaf folder). This proves mechanics only —
|
||||||
|
only a real run against the user's service proves the integration.
|
||||||
|
4. Each category id in the manifest is the id its leaves live under, and each
|
||||||
|
category has a navigation-grade scope description.
|
||||||
|
5. The `config` schema is well-formed (every leaf has `default` + `doc`; secrets
|
||||||
|
marked `secret`), maps onto `bridges.<bridges[0]>` (or `packs.<name>` for a
|
||||||
|
bridge-less pack), and the regenerated `config.example.json` + `check-config`
|
||||||
|
are clean.
|
||||||
|
6. A bridge-backed pack ships its bridge test (`bridge/test_<bridge>_bridge.py`)
|
||||||
|
and it passes hermetically (loopback HTTP, no external network, no daemon).
|
||||||
|
7. Nothing deployment-specific (hostname, address, username, absolute home
|
||||||
|
path, local model name) appears in any committed file —
|
||||||
|
`tests/test_no_env_leaks.py` enforces this for the agent repo; keep a pack
|
||||||
|
repo clean too. Secrets live in `secrets.json`.
|
||||||
|
8. If the pack ships a `requirements.txt`, it is pinned, lives with the pack (not
|
||||||
|
the agent repo's `requirements/`), and its deps are lazy-imported so a host
|
||||||
|
without the pack is unaffected.
|
||||||
|
|
||||||
|
`tests/test_packs.py` enforces items 1–6 and 8 mechanically for every shipped
|
||||||
|
pack (valid manifest, concern + categories, integration matches code, contract
|
||||||
|
flat and mirrored, manifest description, hermetic skill test, hermetic bridge
|
||||||
|
test, pinned pack requirements)
|
||||||
|
and keeps the shipped pack ids present.
|
||||||
|
|
||||||
|
## Worked example — a minimal bridge-less pack
|
||||||
|
|
||||||
|
The smallest complete pack needs a manifest and one leaf. `packs/essentials/`
|
||||||
|
is the committed model; a hypothetical `packs/hello/`:
|
||||||
|
|
||||||
|
```
|
||||||
|
packs/hello/
|
||||||
|
pack.json
|
||||||
|
skills/hello/greet/
|
||||||
|
skill.py
|
||||||
|
manifest.json
|
||||||
|
contract.json
|
||||||
|
skill.test.py
|
||||||
|
```
|
||||||
|
|
||||||
|
`pack.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "hello",
|
||||||
|
"title": "Hello",
|
||||||
|
"concern": "A trivial local greeting utility that needs no account, network, or bridge.",
|
||||||
|
"categories": {
|
||||||
|
"hello": "Greetings: producing a friendly greeting for the user."
|
||||||
|
},
|
||||||
|
"bridges": [],
|
||||||
|
"requires": [],
|
||||||
|
"enabled_by_default": true,
|
||||||
|
"config": {
|
||||||
|
"enabled": {"type": "bool", "default": true, "doc": "Load the hello skills."}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`skills/hello/greet/manifest.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "description": "Produce a friendly greeting." }
|
||||||
|
```
|
||||||
|
|
||||||
|
The leaf's `skill.py` (a `compute`-transport body — no external action, empty
|
||||||
|
`CONTRACT`) and `skill.test.py` follow `CODEGEN.md`/`TESTGEN.md`; the shipped
|
||||||
|
`packs/essentials/skills/time/now/` is the reference for exactly this shape.
|
||||||
|
|
||||||
|
For a bridge-backed pack, start from `packs/simplex/pack.json` (bridge
|
||||||
|
reference + `host`/`port`/`token` + service vars), `packs/simplex/bridge/` (the
|
||||||
|
bridge module, its package marker, and its hermetic test), and
|
||||||
|
`packs/simplex/skills/simplex/send_message/` (a body that calls the bridge over
|
||||||
|
HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/` (its
|
||||||
|
`bridge/nextcloud.py` overrides `from_config`).
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
1. Decide the concern and the category ids; write navigation-grade category
|
||||||
|
descriptions.
|
||||||
|
2. If a third-party system is involved and it needs state/auth, a native or
|
||||||
|
heavy protocol, or one sanitized surface, author a bridge first (see
|
||||||
|
"Authoring a new bridge") and ship it under `bridge/`. A system with a plain
|
||||||
|
HTTP API needs no bridge — the skill calls it directly.
|
||||||
|
3. Create the pack (its own repository, `pack.<name>`): `packs/<name>/pack.json`
|
||||||
|
with `name`, `title`, `concern`, `categories`, `bridges` (if any), `requires`,
|
||||||
|
`enabled_by_default`, and the `config` schema. If the pack needs python deps,
|
||||||
|
ship them pinned at `packs/<name>/requirements.txt` (see "Pack python deps").
|
||||||
|
4. Add each leaf under `skills/<category>/<leaf>/` following `CODEGEN.md` and
|
||||||
|
`TESTGEN.md` (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`),
|
||||||
|
and each bridge under `bridge/<name>.py` with its `bridge/test_<name>_bridge.py`.
|
||||||
|
5. Regenerate and validate config:
|
||||||
|
`python -m semif_agent.cli check-config --write-example config.example.json`
|
||||||
|
then `python -m semif_agent.cli check-config`.
|
||||||
|
6. Run the tests:
|
||||||
|
`python3 -m pytest tests/test_packs.py tests/test_codegen.py -q`
|
||||||
|
(it runs every pack's skill and bridge tests, including the new ones).
|
||||||
|
7. Cross-link the pack/bridge in `AGENTS.md` (and `README.md` for a shipped
|
||||||
|
pack).
|
||||||
|
8. Verify a real run against the user's actual service — the only proof the
|
||||||
|
integration works.
|
||||||
|
9. Register the pack in the `semif-packs` index repo — add an entry (name + clone
|
||||||
|
URL, plus title/description for the interview) to its `packs.json` — then push
|
||||||
|
the pack's own repository (`pack.<name>`); `scripts/bootstrap.sh` reads the
|
||||||
|
index and clones the pack into `packs/`.
|
||||||
@@ -127,11 +127,15 @@ choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
|
|||||||
- **Leaf.** The leaf softmax picks only among the existing skills (a create
|
- **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
|
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**
|
weak plurality). The picked skill then goes through the **intent guard**
|
||||||
(`confirm_skill_fit`, phase `navigate:intent`): an action comparison at
|
(`confirm_skill_fit`, phase `navigate:intent`): at `navigation.intent_tau` it
|
||||||
`navigation.intent_tau` asking whether the skill performs the same action the
|
decides what the skill does for the request, given the steps already taken
|
||||||
request asks for. Same → run it; different → author a new leaf in that
|
(the run ledger is part of its state). `same` (it performs the next action the
|
||||||
category. An empty (or single-skill) category skips the softmax and goes
|
request needs) or `part` (the request needs more than one action and this
|
||||||
straight to the guard.
|
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
|
- 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
|
cases score 0.9–1.0, so a borderline over-cover routes into a plausible
|
||||||
category and the leaf guard catches it.
|
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
|
a live candidate set) are returned on `ActionResult.decisions` and logged as
|
||||||
training rows with the run outcome.
|
training rows with the run outcome.
|
||||||
- `assess` is a **SemIf decision**, not generation:
|
- `assess` is a **SemIf decision**, not generation:
|
||||||
- `assess:outcome` — success/failure at `tau`; its state includes the resolved
|
- `assess:outcome` — is there any *additional work* to satisfy the request?
|
||||||
inputs (secrets redacted) so a wrong resolution is visible.
|
Three outcomes at threshold precedence `failed > done > continue`: `done`
|
||||||
- `assess:requeue` — on failure, `complete` vs `retry` (bounded by
|
(request satisfied), `continue` (this step worked but more work is needed →
|
||||||
`max_reentries`).
|
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):
|
- The run summary is **deterministic** (same inputs ⇒ same string):
|
||||||
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
|
`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
|
- 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
|
re-runs on resume, with `request.user_input` set), or — for a contract
|
||||||
variable the runner cannot satisfy — a **pre-act** pause collects config
|
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
|
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:
|
worker. It is **asynchronous**, so the gate stays free while either model thinks:
|
||||||
|
|
||||||
1. **Stub.** The small `llm` provider (`generate_skill`) authors a title +
|
1. **Spec.** The small `llm` provider (`generate_skill_spec`) authors a title +
|
||||||
description on its own worker. The stub is registered and hot-merged into the
|
description **and a de-identified, reusable goal** (plus the generic
|
||||||
running tree as
|
service/transport) on its own worker. The stub is registered and hot-merged
|
||||||
soon as it lands; a `skill_writing` trace event is emitted.
|
into the running tree as soon as it lands; a `skill_writing` trace event is
|
||||||
2. **Elicitation** (`generate_elicitation`, default on): implementation
|
emitted. The goal is the *only* task data codegen is ever shown.
|
||||||
questions — which service/account, how to connect, where the credential
|
2. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model
|
||||||
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
|
|
||||||
(`codegen`, your configured code-capable model) writes a single `act` against `CODEGEN.md`,
|
(`codegen`, your configured code-capable model) writes a single `act` against `CODEGEN.md`,
|
||||||
reading every operational value from `ctx.config` and declaring `INTEGRATION`
|
reading every operational value from `ctx.config` and declaring `INTEGRATION`
|
||||||
(service / transport / config_vars) plus its own flat `CONTRACT`
|
(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 +
|
4. **Fidelity gate** (`authoring:fidelity` SemIf accept/reconsider decision +
|
||||||
static `integration_findings`): is the action real, or simulated? One
|
static `integration_findings`): does the body contain a concrete,
|
||||||
corrective regen with the raw evidence bundle, then accept-with-badge
|
side-effecting operation that really performs its goal? The state carries the
|
||||||
(`unverified`) rather than hard-fail.
|
**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`
|
5. **Contract** (`parse_contract`): read from the body's own `CONTRACT`
|
||||||
constant — a flat map of snake_case variable name → semantic description, for
|
constant — a flat map of snake_case variable name → semantic description, for
|
||||||
user input and SemIf only; `contract.json` is a persisted mirror.
|
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:
|
category runs the same chain deterministically:
|
||||||
`create_category` → `create_skill` → async body → re-dispatch.
|
`create_category` → `create_skill` → async body → re-dispatch.
|
||||||
|
|
||||||
A rejected/simulated body is traced (`fidelity_review`), badged `unverified`,
|
A rejected/simulated body is traced (`fidelity_review`) and never blocks
|
||||||
and never blocks authoring. Codegen failures (including timeouts) surface as a
|
authoring. Codegen failures (including timeouts) surface as a graceful stub and
|
||||||
graceful stub and are retryable with `restart <category> <skill>`.
|
are retryable with `restart <category> <skill>`.
|
||||||
|
|
||||||
### What each model sees
|
### 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
|
what you see in the table below is the entire input. Probabilities are
|
||||||
conditional on exactly the supplied options.
|
conditional on exactly the supplied options.
|
||||||
|
|
||||||
A **generative call** (`llm` for titles/descriptions, `codegen` for bodies and
|
A **generative call** (`llm` for titles/descriptions/goals, `codegen` for bodies
|
||||||
tests) is a built OpenAI-style `messages` list. Its context is assembled from
|
and tests) is a built OpenAI-style `messages` list. The trusted local `llm`
|
||||||
the request, the tree, the elicitation answers, the runtime **bridge catalog**
|
context is assembled from the request and the tree; the **codegen** context is
|
||||||
(`describe_bridges()`), and — for bodies and tests — the contract files
|
assembled only from the de-identified spec (goal + generic service/transport),
|
||||||
(`CODEGEN.md`, `TESTGEN.md`).
|
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
|
#### 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: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: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` |
|
| `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:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
|
||||||
| `assess:requeue` | `skill.py:279` | skill label + goal + action log + `outcome: failed` | `complete` / `retry` |
|
|
||||||
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
|
| `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` |
|
| `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` |
|
| `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` |
|
| 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` |
|
| `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 |
|
| 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_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_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** | request, category, name, description, existing skills + tree summary, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:156` |
|
| `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, request, category, name, description, elicitation answers, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:474` |
|
| body retry | `codegen` | full **CODEGEN.md** | rejection reason, de-identified spec (goal + description), 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_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` |
|
||||||
| `generate_data_contract` | `codegen` | full **TESTGEN.md** | skill, request, full body code, **bridge catalog** + the contract ask | `codegen.py:833` |
|
| `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` |
|
||||||
| `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` |
|
|
||||||
|
|
||||||
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py:33`): each
|
The **bridge catalog** is `describe_bridges()` (`bridges/registry.py`): each
|
||||||
known bridge's name, service, description, base-URL config var, auth header +
|
known bridge's name, service, description, base-URL config var, auth header +
|
||||||
token var, documented config vars, and endpoints. It is the single runtime
|
token var, documented config vars, and endpoints. It is the single runtime
|
||||||
source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic
|
source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic
|
||||||
pattern — so a bridge can be added without touching either contract file.
|
pattern — so a bridge can be added without touching either contract file (a
|
||||||
|
bridge ships with its pack; the registry discovers it by convention).
|
||||||
|
|
||||||
The **raw evidence bundle** handed to a corrective regen carries the request,
|
The **evidence bundle** handed to a corrective regen is de-identified: a generic
|
||||||
description, requirements, the observed failure fields (error, action log, new
|
failure kind, the integration, the goal, and the previous body, rendered as-is
|
||||||
state, summary) and the previous body, rendered as-is with no prose diagnosis.
|
with no prose diagnosis. It carries no request text and no run output.
|
||||||
|
|
||||||
### Data contracts and tiered config
|
### 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.
|
to the closed `response` canned tree.
|
||||||
- **Real integrations by construction** — bodies must perform the real action,
|
- **Real integrations by construction** — bodies must perform the real action,
|
||||||
read data from `ctx.config`, declare `INTEGRATION`, and report real failures.
|
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.
|
auto-run, with a SemIf regeneration ladder on test failure. Gate stays free.
|
||||||
- **Tiered config + first-fire collection** — global/category/skill config with
|
- **Tiered config + first-fire collection** — global/category/skill config with
|
||||||
a `record-vs-ask` decision per answer.
|
a `record-vs-ask` decision per answer.
|
||||||
@@ -338,15 +352,21 @@ fine-tuning loop — it is not yet the fine-tune itself.
|
|||||||
with prompt hashes, tokens and timing.
|
with prompt hashes, tokens and timing.
|
||||||
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
|
- **Run lifecycle tracing** — `runs.jsonl` keyed by `run_id`, powering a
|
||||||
Redux-DevTools-style dashboard.
|
Redux-DevTools-style dashboard.
|
||||||
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM.
|
- **Messenger command gateway (SimpleX + LXMF)** — take commands and reply over DM,
|
||||||
|
including Sideband push-to-talk **voice messages** on LXMF (local transcription,
|
||||||
|
and voice replies synthesized with Piper).
|
||||||
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
|
- **Voice gateway** — a local microphone front end: wake word + speech-to-text +
|
||||||
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
|
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
|
||||||
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
|
- **Standalone bridge services** — an optional token-guarded localhost HTTP
|
||||||
of third-party systems, so generated bodies never speak native protocols.
|
layer for third-party systems that need state/auth, a native protocol, or a
|
||||||
|
sanitized surface; a plain HTTP API is called directly.
|
||||||
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
|
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
|
||||||
authoritative worked example), `nextcloud.next_event` (Nextcloud CalDAV),
|
authoritative worked example), `nextcloud.next_event` (the user's Nextcloud
|
||||||
`nextcloud.create_task` (Nextcloud task list), and
|
calendar, through the bridge), `nextcloud.create_task` (Nextcloud task list),
|
||||||
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`.
|
`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.
|
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
|
||||||
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
|
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
|
||||||
importable and testable without the heavy engine installed.
|
importable and testable without the heavy engine installed.
|
||||||
@@ -366,7 +386,7 @@ semif_agent/
|
|||||||
summary; pre-act contract collection; resolved-input state
|
summary; pre-act contract collection; resolved-input state
|
||||||
skills.py tree + registry, canned `response` tree, navigation,
|
skills.py tree + registry, canned `response` tree, navigation,
|
||||||
create gates, intent guard, tiered config resolution
|
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
|
parse/validate; CONTRACT + INTEGRATION extraction; test runner
|
||||||
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog);
|
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog);
|
||||||
SemIfEngineClient generates text from the in-process engine
|
SemIfEngineClient generates text from the in-process engine
|
||||||
@@ -385,15 +405,31 @@ semif_agent/
|
|||||||
voice_transport.py neutral voice transport: mic capture, wake word, VAD,
|
voice_transport.py neutral voice transport: mic capture, wake word, VAD,
|
||||||
speech-to-text (faster-whisper), text-to-speech (Piper)
|
speech-to-text (faster-whisper), text-to-speech (Piper)
|
||||||
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
|
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
|
||||||
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud)
|
bridges/ bridge contract + discovery (base.py, registry.py, inbox.py,
|
||||||
seeds/ committed starter skills (nextcloud, simplex)
|
llm.py); the concrete bridges ship in their packs
|
||||||
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
|
config.py layered config: index includes + !secret + schema/example
|
||||||
requirements/ staging.txt — the pinned engine deps
|
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)
|
tests/ stdlib unit tests + tests/integration (real engine + LLM)
|
||||||
CODEGEN.md the contract fed to the skill-body codegen model
|
CODEGEN.md the contract fed to the skill-body codegen model
|
||||||
TESTGEN.md the contract fed to the test/contract codegen model
|
TESTGEN.md the contract fed to the test/contract codegen model
|
||||||
|
PACKGEN.md the contract for authoring a skill pack (packs/<name>/)
|
||||||
AGENTS.md the operational guide (read this before touching code)
|
AGENTS.md the operational guide (read this before touching code)
|
||||||
config.example.json per-machine config template (seeded to config.json once)
|
config.json per-machine config INDEX ({"include": [...]}); seeded once
|
||||||
|
config/ split config fragments (core, gateway, bridges, packs/*)
|
||||||
|
secrets.json gitignored credentials, referenced as "!secret <key>"
|
||||||
|
config.example.json GENERATED per-machine config reference (from the schemas)
|
||||||
pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs
|
pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs
|
||||||
local/ gitignored: this deployment's notes (hosts, addresses, models)
|
local/ gitignored: this deployment's notes (hosts, addresses, models)
|
||||||
```
|
```
|
||||||
@@ -403,30 +439,43 @@ local/ gitignored: this deployment's notes (hosts, addresses, model
|
|||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
|
The agent runs anywhere pure-Python runs, but a *working* agent needs the SemIf
|
||||||
decision engine, a pinned GGUF, and an OpenAI-compatible endpoint for codegen.
|
decision engine (local or remote). `scripts/bootstrap.sh` provisions what this
|
||||||
`scripts/bootstrap.sh` provisions all of it inside a gitignored `.runtime/` tree
|
machine needs inside a gitignored `.runtime/` tree in the checkout — and only
|
||||||
in the checkout.
|
what it needs, based on the answers to a short first-run interview.
|
||||||
|
|
||||||
### Prerequisites: ollama models
|
### Prerequisites: the decision engine, and optional models
|
||||||
|
|
||||||
Two OpenAI-compatible endpoints (usually ollama), which may be on different
|
The **decision engine** routes every request. It runs one of three ways,
|
||||||
machines:
|
chosen in the interview:
|
||||||
|
|
||||||
|
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
|
||||||
|
default and the whole minimum path.
|
||||||
|
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
|
||||||
|
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
|
||||||
|
- **remote Ollama** — ollama's native System One `/v1/systemone` route
|
||||||
|
(`engine.provider == "ollama"`) against a pulled decision model. It probes
|
||||||
|
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
|
||||||
|
skips the local engine clone/GGUF/tokenizer too. System One models do not
|
||||||
|
generate text, so this provider cannot back `llm.provider == "semif"`.
|
||||||
|
|
||||||
|
The local engine is CPU by default; to offload it to a GPU, set
|
||||||
|
`engine.gpu_layers` in `config.json` and run
|
||||||
|
`scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because it
|
||||||
|
is slower on CPU).
|
||||||
|
|
||||||
|
**Skill authoring is opt-in** (`new_skill_creation`: `deny` by default). When it
|
||||||
|
is off, no `llm`/`codegen` endpoint is needed at all — the agent only runs the
|
||||||
|
shipped packs. When it is on, two OpenAI-compatible endpoints are required
|
||||||
|
(usually ollama, possibly on different machines):
|
||||||
|
|
||||||
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
|
|
||||||
slow and ideally on a beefier host.
|
|
||||||
- **`llm`** — a small, fast model that authors the title + description of a
|
- **`llm`** — a small, fast model that authors the title + description of a
|
||||||
newly created category/skill. Deliberately its own endpoint/model, so it can
|
newly created category/skill. Its `provider` can be `"ollama"` (default),
|
||||||
stay local even when `codegen` is remote; it uses the same provider transport
|
|
||||||
(`provider.py`) and an unreachable endpoint is graceful (the request is not
|
|
||||||
re-dispatched), never fatal. Its `provider` can be `"ollama"` (default),
|
|
||||||
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
|
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
|
||||||
decision engine model generates in-process, with no endpoint and no
|
decision engine model generates in-process, with no endpoint and no
|
||||||
`llm.model` at all (see the `llm.semif` block in `config.json`).
|
`llm.model` at all (the local SemIf or Winnow engine only; an Ollama
|
||||||
|
System One decision model does not generate text).
|
||||||
The **decision engine is separate** and runs via llama.cpp, not ollama. It is CPU
|
- **`codegen`** — a large, code-capable model that writes skill bodies. This is
|
||||||
by default; to offload it to a GPU, set `engine.gpu_layers` in `config.json` and
|
slow and ideally on a beefier host.
|
||||||
run `scripts/bootstrap.sh --gpu vulkan|rocm|cuda` (a GPU build is opt-in because
|
|
||||||
it is slower on CPU).
|
|
||||||
|
|
||||||
### Option A: one-command provisioning (`bootstrap.sh`)
|
### Option A: one-command provisioning (`bootstrap.sh`)
|
||||||
|
|
||||||
@@ -436,41 +485,63 @@ On a fresh Ubuntu machine, from a checkout of this repo:
|
|||||||
scripts/bootstrap.sh
|
scripts/bootstrap.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
With no `config.json` yet, the script seeds one from `config.example.json`; edit
|
On a fresh machine the script **asks a few questions** and writes this machine's
|
||||||
it to set `llm.model`/`codegen.model` (and the endpoints). Flags override those
|
config from the answers:
|
||||||
values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`,
|
|
||||||
`--codegen-model` — and are never written back to `config.json`.
|
|
||||||
|
|
||||||
The script is idempotent (every stage no-ops on existing state) and:
|
1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
|
||||||
|
Ollama System One decision model (URL/model/key).
|
||||||
|
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
|
||||||
|
`llm` + `codegen` endpoints and credentials.
|
||||||
|
3. **Capabilities** — the skill packs to enable, offered from the pack index
|
||||||
|
repo (`semif-packs`): SimpleX, browser, Nextcloud, Outlook, Gutendex (the
|
||||||
|
`essentials` pack is always on). Only the packs you pick are cloned.
|
||||||
|
4. **Gateways** — how you talk to the agent: SimpleX, LXMF, voice (or none —
|
||||||
|
REPL + dashboard only).
|
||||||
|
5. **Timezone** — an IANA name for timers and reported times.
|
||||||
|
|
||||||
|
It then installs **only what those answers require**. Both ends of the spectrum
|
||||||
|
are reachable by the end of a run:
|
||||||
|
|
||||||
|
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
|
||||||
|
calculator, skill listing). No account, no network, no gateway, no heavy
|
||||||
|
downloads.
|
||||||
|
- **maximum** — every pack, a remote Winnow or Ollama System One decision
|
||||||
|
engine, remote `llm`/`codegen` endpoints, and all gateways.
|
||||||
|
|
||||||
|
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
|
||||||
|
replays a saved answer set (JSON matching the `setup` fields). The script is
|
||||||
|
idempotent — on a rerun the interview is **skipped** and the existing config is
|
||||||
|
used; pass `--reconfigure` to re-run it. `--voice` / `--browser` additionally
|
||||||
|
install those optional stacks even if the plan did not pick them.
|
||||||
|
|
||||||
|
The script:
|
||||||
|
|
||||||
1. installs system prereqs + enables linger;
|
1. installs system prereqs + enables linger;
|
||||||
2. generates/uses `~/.ssh/id_ed25519` and clones + pins the SemIf engine;
|
2. clones/updates the skill packs, then runs the setup interview and writes
|
||||||
3. creates `.runtime/venv` and installs the pinned deps from
|
`config/` + `secrets.json` (first run or `--reconfigure`);
|
||||||
`requirements/staging.txt` (installing `semif-phase1` with `--no-deps`, since
|
3. generates/uses `~/.ssh/id_ed25519` and, for a local engine, clones + pins the
|
||||||
the llama.cpp path never imports torch);
|
SemIf engine;
|
||||||
4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`;
|
4. creates `.runtime/venv` and installs only the needed dep files:
|
||||||
5. pre-fetches the HF tokenizer into `.runtime/hf/`;
|
`requirements/core.txt` always, `engine.txt` for a local engine,
|
||||||
6. downloads and sha256-verifies the pinned `simplex-chat` binary;
|
`transports.txt` when a SimpleX/LXMF transport is selected (`voice.txt` for
|
||||||
7. seeds `config.json` from `config.example.json` **only if it does not already
|
the voice stack, `transcribe.txt` when `gateway.lxmf.voice` is enabled —
|
||||||
exist** — it never rewrites `config.json` (only a human edits that file);
|
plus `tts.txt` when `voice.reply_with_voice` is on, and `codec2.txt` + system
|
||||||
8. renders and enables systemd **user** units:
|
`libcodec2` best-effort for non-HQ Codec2 PTT — and each selected pack's own
|
||||||
`semif-simplex` (bot daemon), `semif-gateway` (agent gateway),
|
`packs/<name>/requirements.txt` — e.g. the browser pack's Playwright deps);
|
||||||
`semif-simplex-forward` (the bridge's own daemon), `semif-bridge`;
|
5. for a local engine, downloads/sha256-verifies the GGUF into `.runtime/models/`
|
||||||
9. prints the bot's SimpleX contact address.
|
and pre-fetches the HF tokenizer into `.runtime/hf/`;
|
||||||
|
6. downloads/sha256-verifies the pinned `simplex-chat` binary **only** when a
|
||||||
|
SimpleX gateway or the simplex pack is selected;
|
||||||
|
7. renders and enables only the systemd **user** units the answers need
|
||||||
|
(`semif-simplex` bot daemon, `semif-gateway` agent, `semif-simplex-forward`
|
||||||
|
bridge daemon, `semif-bridge`), retiring any a reconfigure dropped;
|
||||||
|
8. prints the SimpleX contact address(es) when those services are active.
|
||||||
|
|
||||||
Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`,
|
Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it
|
||||||
`--copy-data SRC`) override the values read from `config.json` for that run only.
|
pulls `llm.model` from the target host's ollama when configured, and never
|
||||||
`--voice` additionally installs the optional voice-gateway stack
|
auto-pulls `codegen`. Pinned external refs (engine commit, GGUF url+sha256, HF
|
||||||
(`requirements/voice.txt` + system PortAudio) and downloads its models (the
|
tokenizer revision, simplex-chat version/url+sha256) live in the committed
|
||||||
openWakeWord models into the venv under `.runtime/venv`, the Piper voice into
|
`pins.json`, not in `config.json`.
|
||||||
`.runtime/voice/tts`, the faster-whisper model into the `.runtime/hf` cache).
|
|
||||||
Run `scripts/bootstrap.sh -h` for the full list.
|
|
||||||
|
|
||||||
It installs **no ollama**; it expects one for `llm` and pulls `llm.model`,
|
|
||||||
warning (never auto-pulling) if the remote codegen host is missing its model.
|
|
||||||
Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision,
|
|
||||||
simplex-chat version/url+sha256) live in the committed `pins.json`, not in
|
|
||||||
`config.json`.
|
|
||||||
|
|
||||||
### Option B: core only (stdlib)
|
### Option B: core only (stdlib)
|
||||||
|
|
||||||
@@ -481,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
|
For a full install on a machine you manage, follow the same steps bootstrap
|
||||||
performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF,
|
performs (venv, `semif-phase1 --no-deps`, the `requirements/` files, GGUF,
|
||||||
tokenizer cache), then create `config.json` from the template and adjust paths:
|
tokenizer cache), then generate the split config:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp config.example.json config.json
|
python -m semif_agent.cli setup --interview # or --yes / --answers FILE
|
||||||
|
python -m semif_agent.cli config-init # schema defaults, no interview
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
|
|
||||||
`config.json` is **gitignored, per-machine, and required** — the agent refuses
|
The per-machine config is **gitignored, per-machine, and required** — the agent
|
||||||
to start without it. `scripts/bootstrap.sh` seeds it from `config.example.json`
|
refuses to start without it. `config.json` is a thin **index**
|
||||||
once; afterwards only a human edits it (nothing writes `config.json`). Pinned
|
(`{"include": ["config/core.json", "config/gateway.json", ...]}`); the fragments
|
||||||
external refs live in the committed `pins.json`, so `config.json` holds only
|
under `config/` hold the values and are deep-merged in order. Credentials live in
|
||||||
per-machine settings:
|
the gitignored `secrets.json` and are referenced from any fragment as
|
||||||
|
`"!secret <key>"` (there is no `api_key_env`). `scripts/bootstrap.sh` runs
|
||||||
|
`setup` to generate the split config from your answers; afterwards only a human
|
||||||
|
edits it (`--reconfigure` re-runs the interview).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp config.example.json config.json # if not already created by bootstrap
|
python -m semif_agent.cli setup --interview # generate config/ from answers
|
||||||
|
python -m semif_agent.cli config-init # seed schema defaults (no interview)
|
||||||
|
python -m semif_agent.cli check-config # validate against the schemas
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The committed `config.example.json` is **generated** from the core schema
|
||||||
|
(`semif_agent/config.py`) and each pack's `config` schema; regenerate it after
|
||||||
|
changing a schema:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m semif_agent.cli check-config --write-example config.example.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Pinned external refs live in the committed `pins.json`, so the config holds only
|
||||||
|
per-machine settings.
|
||||||
|
|
||||||
Key blocks:
|
Key blocks:
|
||||||
|
|
||||||
| Block | What it controls |
|
| Block | What it controls |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `engine` | per-machine engine settings: backend, context, threads, optional GGUF path override (refs come from `pins.json`) |
|
| `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 |
|
| `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` |
|
| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
|
||||||
| `tau` | decision threshold; `max_reentries` requeue bound |
|
| `tau` | decision threshold; `max_reentries` requeue bound |
|
||||||
| `queue` | `max_size` |
|
| `queue` | `max_size` |
|
||||||
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
|
| `skill_bodies` / `skill_packs` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
|
||||||
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
|
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
|
||||||
| `gateway.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.simplex` | forwarding bridge: host/port/token/ws_url |
|
||||||
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
|
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
|
||||||
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
|
| `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.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`) |
|
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
|
||||||
| `dashboard` | bind host/port |
|
| `dashboard` | bind host/port |
|
||||||
|
|
||||||
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` /
|
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>`
|
`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
|
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
|
with no block (or no port) leaves the variable unresolved and the operator is
|
||||||
asked for it.
|
asked for it.
|
||||||
|
|
||||||
`llm.model` and `codegen.model` are **required** (no default): set each to a
|
`llm.model` and `codegen.model` are **required only when authoring is enabled**
|
||||||
model its endpoint serves. A missing model fails fast at startup with a clear
|
(`new_skill_creation` is `ask`/`allow`): set each to a model its endpoint serves.
|
||||||
config error rather than sending a request to a model that isn't there.
|
An empty `codegen.model` means "no authoring path" — the minimum config leaves it
|
||||||
|
empty and the agent simply runs the shipped packs. With authoring on, a missing
|
||||||
|
model fails fast at startup with a clear config error rather than sending a
|
||||||
|
request to a model that isn't there.
|
||||||
|
|
||||||
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
|
Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
|
||||||
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
|
`data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too.
|
||||||
@@ -545,6 +639,7 @@ Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`,
|
|||||||
All subcommands go through the CLI:
|
All subcommands go through the CLI:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
python -m semif_agent.cli setup --interview # generate config/ from answers
|
||||||
python -m semif_agent.cli run # interactive REPL
|
python -m semif_agent.cli run # interactive REPL
|
||||||
python -m semif_agent.cli run --script inputs.jsonl
|
python -m semif_agent.cli run --script inputs.jsonl
|
||||||
python -m semif_agent.cli dream # cost report
|
python -m semif_agent.cli dream # cost report
|
||||||
@@ -627,7 +722,7 @@ without it). `allowed_users` entries match a numeric contactId or a display
|
|||||||
name. The daemon must run in **bot mode** (`simplex-chat -p PORT
|
name. The daemon must run in **bot mode** (`simplex-chat -p PORT
|
||||||
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
|
--create-bot-display-name NAME`), not `--headless`/`--relay` — in v7 those mean
|
||||||
"chat relay" and yield a relay address, not a user contact address. Add the
|
"chat relay" and yield a relay address, not a user contact address. Add the
|
||||||
bot's contact link to reach it: `scripts/simplex-address.py` shows/creates it
|
bot's contact link to reach it: `packs/simplex/scripts/simplex-address.py` shows/creates it
|
||||||
(bootstrap prints it), and the gateway prints it once on connect.
|
(bootstrap prints it), and the gateway prints it once on connect.
|
||||||
|
|
||||||
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
|
**LXMF (Reticulum).** Runs **in-process — there is no external daemon**;
|
||||||
@@ -641,6 +736,32 @@ matches the peer's LXMF address (32 hex) or a best-effort display name.
|
|||||||
and an optional `propagation_node` enables store-and-forward. Add the printed
|
and an optional `propagation_node` enables store-and-forward. Add the printed
|
||||||
address as a contact in your LXMF client and DM it.
|
address as a contact in your LXMF client and DM it.
|
||||||
|
|
||||||
|
**Voice commands (Sideband push-to-talk).** Set
|
||||||
|
`gateway.lxmf.voice.enabled: true` and a Sideband PTT voice message is
|
||||||
|
transcribed into a command, just like typed text. HQ PTT (Opus/OGG) is decoded
|
||||||
|
and transcribed by faster-whisper, which needs only `requirements/transcribe.txt`
|
||||||
|
(installed by the install plan — no microphone, no voice stack). Non-HQ Codec2
|
||||||
|
PTT is decoded by the optional `pycodec2` bindings (`requirements/codec2.txt`,
|
||||||
|
installed best-effort alongside the system `libcodec2`); without it a Codec2
|
||||||
|
message is reported back rather than dropped. The audio is transient and never
|
||||||
|
leaves the machine. The model is `gateway.lxmf.voice.stt.model` (default
|
||||||
|
`base.en`).
|
||||||
|
|
||||||
|
**Voice replies.** With `gateway.lxmf.voice.reply_with_voice: true` (the
|
||||||
|
default), a chat that last messaged by voice is answered with a synthesized
|
||||||
|
voice message: the reply text is spoken with Piper and sent back as a Sideband
|
||||||
|
HQ push-to-talk message, with the text also carried as the message content so a
|
||||||
|
text-only client still sees it. A later text message from that chat reverts it to
|
||||||
|
text replies. This needs only `piper-tts` + PyAV (`requirements/tts.txt`,
|
||||||
|
installed by the install plan — still no microphone); a missing stack or a
|
||||||
|
synthesis failure falls back to a text reply rather than dropping it. The voice
|
||||||
|
is `gateway.lxmf.voice.tts.voice` (default `en_US-lessac-medium`).
|
||||||
|
|
||||||
|
**Result-only replies.** The LXMF gateway sends only the skill's result line:
|
||||||
|
the scheduler's queue/urgency bookkeeping is dropped and the `<skill>: ok —`
|
||||||
|
wrapper is stripped, so a DM is the answer, not the internals. Override with
|
||||||
|
`gateway.lxmf.result_only: false` for the full scheduler output.
|
||||||
|
|
||||||
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
|
> **Gateway isolation is non-negotiable.** The gateway takes commands and sends
|
||||||
> replies — nothing else. It never reads history, shows or creates invite links,
|
> replies — nothing else. It never reads history, shows or creates invite links,
|
||||||
> or composes messages. That is messaging UX and lives in the bridges.
|
> or composes messages. That is messaging UX and lives in the bridges.
|
||||||
@@ -681,13 +802,16 @@ python -m semif_agent.cli gateway --platform voice
|
|||||||
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
|
run lower than the official models, the seeded `wake.threshold` is `0.2` (the
|
||||||
official models score ~0.99 and use `0.5`).
|
official models score ~0.99 and use `0.5`).
|
||||||
- **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so
|
- **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 agent never transcribes itself (no barge-in yet). The wake word is required
|
||||||
the wake word fires (`gateway.voice.cue`), so you know you're being heard; set
|
before every command and is held while the scheduler is still running the
|
||||||
`cue.submit_frequency > 0` for a second beep once the utterance is
|
current request, so a second command cannot start until the first reaches a
|
||||||
transcribed. After a reply, the next
|
result. A short beep plays when
|
||||||
utterance is accepted **without** the wake word for `follow_up_window_s`, so
|
the wake word fires (`gateway.voice.cue`), so you know you're being heard; a
|
||||||
answering a question is conversational. After the wake word, capture waits
|
short multi-note "bling" (`cue.submit_notes`, each entry
|
||||||
`listen_timeout_s` for the command to begin, so a pause before speaking
|
`[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`
|
(e.g. while the cue beep plays) does not truncate it. `max_speak_chars`
|
||||||
truncates long
|
truncates long
|
||||||
replies before speaking. `result_only` (default true for voice) speaks only the
|
replies before speaking. `result_only` (default true for voice) speaks only the
|
||||||
@@ -704,11 +828,13 @@ python -m semif_agent.cli gateway --platform voice
|
|||||||
|
|
||||||
`cli bridge` runs standalone bridges: each is a process that stands up a small,
|
`cli bridge` runs standalone bridges: each is a process that stands up a small,
|
||||||
token-guarded localhost HTTP API in front of one third-party system (and, where
|
token-guarded localhost HTTP API in front of one third-party system (and, where
|
||||||
the system needs one, owns its own daemon/profile). Generated skill bodies call
|
the system needs one, owns its own daemon/profile). A bridge is a deliberate
|
||||||
them like any HTTP service (base URL from a config var), so they never speak a
|
choice for a system that needs state (especially auth state), a native or heavy
|
||||||
native protocol directly.
|
protocol, or one sanitized surface — a skill may call a plain HTTP API directly.
|
||||||
|
When a bridge fronts a service, generated skill bodies call it like any HTTP
|
||||||
|
service (base URL from a config var) and never speak the native protocol.
|
||||||
|
|
||||||
The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own
|
The first bridge is **SimpleX** (`packs/simplex/bridge/simplex.py`), with its own
|
||||||
simplex-chat daemon separate from the gateway's. Its HTTP surface:
|
simplex-chat daemon separate from the gateway's. Its HTTP surface:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -730,10 +856,11 @@ acking is a client-side read receipt, not an API call.
|
|||||||
Skills call the forwarding bridge at the address derived from `bridges.simplex`
|
Skills call the forwarding bridge at the address derived from `bridges.simplex`
|
||||||
(`simplex_bridge_url`); the bridge catalog
|
(`simplex_bridge_url`); the bridge catalog
|
||||||
is injected into every codegen prompt via `describe_bridges()`, so it is the
|
is injected into every codegen prompt via `describe_bridges()`, so it is the
|
||||||
single source of bridge specifics. Adding a bridge = a class + a config block +
|
single source of bridge specifics. Adding a bridge = a pack that ships its
|
||||||
a `CATALOG` entry.
|
`bridge/<name>.py` + a config block; the core registry discovers it by convention.
|
||||||
|
|
||||||
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic
|
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the shared, pack-less one: a
|
||||||
|
generic
|
||||||
|
|
||||||
```
|
```
|
||||||
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
|
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
|
||||||
@@ -749,17 +876,18 @@ carries just the local listener. Skills call it at the address derived from
|
|||||||
it returns `502`, never a fabricated reply. It starts in the same
|
it returns `502`, never a fabricated reply. It starts in the same
|
||||||
`semif-bridge.service` process as the other enabled bridges.
|
`semif-bridge.service` process as the other enabled bridges.
|
||||||
|
|
||||||
The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it
|
The **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py`) is the third: it
|
||||||
wraps the account's native protocols — WebDAV files, CalDAV calendar events and
|
wraps the account's native protocols — WebDAV files, CalDAV calendar events and
|
||||||
tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a
|
tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a
|
||||||
body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is
|
body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is
|
||||||
plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
|
plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
|
||||||
in the same `semif-bridge` process. The connection (base URL, username, app
|
in the same `semif-bridge` process. The connection (base URL, username, app
|
||||||
password) is configured in `bridges.nextcloud` and falls back to the top-level
|
password) is configured in `bridges.nextcloud`; `NextcloudBridge.from_config`
|
||||||
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` /
|
also accepts the top-level `nextcloud_url` / `nextcloud_username` /
|
||||||
`nextcloud_default_calendar` the nextcloud seeds use, so the account is
|
`nextcloud_app_password` / `nextcloud_default_calendar` as a fallback for a
|
||||||
configured once. Skills call it at the address derived from `bridges.nextcloud`
|
hand-edited config, with a block value winning. Skills call it at the address
|
||||||
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface:
|
derived from `bridges.nextcloud` (`nextcloud_bridge_url`, + optional
|
||||||
|
`nextcloud_bridge_token`). Its HTTP surface:
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /health
|
GET /health
|
||||||
@@ -771,8 +899,8 @@ GET /files/read?path=<path> # text, or base64 for binary
|
|||||||
GET /files/search?query=<text>&path=<dir>
|
GET /files/search?query=<text>&path=<dir>
|
||||||
POST /files/write {"path","content","encoding"?,"overwrite"?}
|
POST /files/write {"path","content","encoding"?,"overwrite"?}
|
||||||
POST /files/mkdir | /files/delete | /files/move | /files/copy
|
POST /files/mkdir | /files/delete | /files/move | /files/copy
|
||||||
GET /calendars
|
GET /calendars # includes "default" (configured default name)
|
||||||
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT
|
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT; recurrences expand with a window
|
||||||
POST /calendars/events | /calendars/events/update | /calendars/events/delete
|
POST /calendars/events | /calendars/events/update | /calendars/events/delete
|
||||||
GET /tasks?calendar=<name> # CalDAV VTODO
|
GET /tasks?calendar=<name> # CalDAV VTODO
|
||||||
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
|
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
|
||||||
@@ -788,13 +916,13 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo
|
|||||||
defaults resolve from `bridges.nextcloud` when a request names none and the
|
defaults resolve from `bridges.nextcloud` when a request names none and the
|
||||||
account has several.
|
account has several.
|
||||||
|
|
||||||
The **Outlook bridge** (`semif_agent/bridges/outlook.py`) wraps the user's
|
The **Outlook bridge** (`packs/outlook/bridge/outlook.py`) wraps the user's
|
||||||
Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail,
|
Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail,
|
||||||
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
|
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
|
||||||
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
|
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
|
||||||
so it starts instantly in the same `semif-bridge` process. Authorization is the
|
so it starts instantly in the same `semif-bridge` process. Authorization is the
|
||||||
OAuth2 **device code flow**: register an Entra ID public-client app, put its
|
OAuth2 **device code flow**: register an Entra ID public-client app, put its
|
||||||
`client_id` in `bridges.outlook`, and run `scripts/outlook-auth.py` once — the
|
`client_id` in `bridges.outlook`, and run `packs/outlook/scripts/outlook-auth.py` once — the
|
||||||
tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and
|
tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and
|
||||||
refreshed automatically. The bridge starts without a token; an unauthenticated
|
refreshed automatically. The bridge starts without a token; an unauthenticated
|
||||||
route returns `503` telling the operator to run that helper. Skills call it at the
|
route returns `503` telling the operator to run that helper. Skills call it at the
|
||||||
@@ -823,11 +951,55 @@ POST /files/write {"path","content","encoding"?,"overwrite"?}
|
|||||||
|
|
||||||
A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure
|
A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure
|
||||||
(transport, HTTP error, or a bad reply) is `502` — never a fabricated success.
|
(transport, HTTP error, or a bad reply) is `502` — never a fabricated success.
|
||||||
Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`,
|
Seven `packs/outlook/skills/outlook/*` skills ship (`next_message`, `send_message`,
|
||||||
`next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`);
|
`next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`);
|
||||||
`send_message` composes the message through the LLM bridge and asks for
|
`send_message` composes the message through the LLM bridge and asks for
|
||||||
confirmation before it sends.
|
confirmation before it sends.
|
||||||
|
|
||||||
|
The **browser bridge** (`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
|
### Dream report
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -863,20 +1035,24 @@ bodies, no external network, no `mock_data.json`. Passing it proves the code
|
|||||||
runs, not that the live integration works. That is what the real run and the
|
runs, not that the live integration works. That is what the real run and the
|
||||||
repair loop are for.
|
repair loop are for.
|
||||||
|
|
||||||
**Seeds** (`seeds/`) ship real starter integrations in the exact generated
|
**Packs** ship real starter integrations in the exact generated folder format,
|
||||||
folder format, plus a `manifest.json`. `merge_seed_store` loads them into every
|
plus a `manifest.json` and a `pack.json` manifest binding the concern to its
|
||||||
tree at startup; recorded config is written to the runtime store, so the
|
categories, bridge, and config schema. Each pack lives in its **own repository**
|
||||||
committed seed never holds secrets.
|
(`pack.<name>`, listed in the `semif-packs` index repo); `scripts/bootstrap.sh` clones them into
|
||||||
|
the gitignored `packs/<name>/`, and `merge_packs` loads every enabled pack into
|
||||||
|
the tree at startup. Recorded config is written to the runtime store, so a pack
|
||||||
|
repo never holds secrets. `PACKGEN.md` is the authoritative contract for
|
||||||
|
authoring a new pack (and a new bridge to back one).
|
||||||
|
|
||||||
- `nextcloud.create_event` — create an event on Nextcloud CalDAV (the
|
- `nextcloud.create_event` — create an event on the user's Nextcloud calendar
|
||||||
authoritative worked example); resolves the target calendar with a SemIf
|
through the Nextcloud bridge (`GET /calendars`, `POST /calendars/events`);
|
||||||
choice over the owned calendars (strong winner, else the configured default);
|
resolves the target calendar with a SemIf choice over the owned calendars
|
||||||
config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`,
|
(strong winner, else the configured default); config vars
|
||||||
`nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`,
|
`nextcloud_bridge_url`, `nextcloud_bridge_token`, plus the LLM bridge
|
||||||
`llm_bridge_token`).
|
(`llm_bridge_url`, `llm_bridge_token`).
|
||||||
- `nextcloud.next_event` — next upcoming event from Nextcloud CalDAV (recurring
|
- `nextcloud.next_event` — next upcoming event through the Nextcloud bridge
|
||||||
events expanded server-side); config vars `nextcloud_url`,
|
(`GET /calendars`, `GET /calendars/events`; recurring events expanded
|
||||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`.
|
server-side); config vars `nextcloud_bridge_url`, `nextcloud_bridge_token`.
|
||||||
- `nextcloud.create_task` — add a task to a Nextcloud task list through the
|
- `nextcloud.create_task` — add a task to a Nextcloud task list through the
|
||||||
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
|
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
|
||||||
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
|
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
|
||||||
@@ -890,6 +1066,18 @@ committed seed never holds secrets.
|
|||||||
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
|
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
|
||||||
`llm_bridge_token`) to write the text when the request states none.
|
`llm_bridge_token`) to write the text when the request states none.
|
||||||
- `simplex.connect_link` — show/create the forwarding bot's contact link.
|
- `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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -919,11 +1107,11 @@ works.
|
|||||||
|
|
||||||
**Done.** Core loop, FIFO queue, skill tree, real SemIf assessment, decision
|
**Done.** Core loop, FIFO queue, skill tree, real SemIf assessment, decision
|
||||||
logging, `dream` cost pass, REPL + JSONL CLI; live `create_category` /
|
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
|
contract → test → auto-run → re-dispatch); tiered config + first-fire
|
||||||
collection; runtime repair loop; the closed `response` canned tree; real
|
collection; runtime repair loop; the closed `response` canned tree; real
|
||||||
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
|
integrations with `INTEGRATION` declarations; the SimpleX command gateway and the
|
||||||
standalone SimpleX bridge + seeds (contact-list refresh, daemon-backed message
|
standalone SimpleX bridge + pack skills (contact-list refresh, daemon-backed message
|
||||||
history / true unread); the LXMF gateway; and the voice gateway (wake word +
|
history / true unread); the LXMF gateway; and the voice gateway (wake word +
|
||||||
speech-to-text + text-to-speech).
|
speech-to-text + text-to-speech).
|
||||||
|
|
||||||
|
|||||||
+16
-6
@@ -6,6 +6,9 @@ test artifact. The runnable body contract lives in `CODEGEN.md`; this file is
|
|||||||
deliberately separate so the body writer never embeds test data and the test is
|
deliberately separate so the body writer never embeds test data and the test is
|
||||||
generated from the finished body rather than the other way around.
|
generated from the finished body rather than the other way around.
|
||||||
|
|
||||||
|
The pack that ships a skill as a committed starter — its manifest, categories,
|
||||||
|
bridge reference, and config schema — is the separate contract `PACKGEN.md`.
|
||||||
|
|
||||||
A finished skill leaf is a folder
|
A finished skill leaf is a folder
|
||||||
`data/skills/<category>/<name>/` containing (among others) two artifacts:
|
`data/skills/<category>/<name>/` containing (among others) two artifacts:
|
||||||
|
|
||||||
@@ -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
|
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.
|
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
|
## contract.json
|
||||||
|
|
||||||
A **single JSON object**. Each key is the name of a variable the skill needs;
|
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,
|
Assert the server actually received the expected request (method, path,
|
||||||
headers, body) where practical. The loopback address exists only in the test;
|
headers, body) where practical. The loopback address exists only in the test;
|
||||||
the body must read its endpoint from config.
|
the body must read its endpoint from config.
|
||||||
- For a messaging skill (a body that talks to a bridge service), stand up a
|
- For a body that talks to a bridge service (or any fixed HTTP API), stand up a
|
||||||
loopback server implementing the bridge endpoints the body uses (the bridge
|
loopback server implementing the endpoints the body uses (the bridge catalog
|
||||||
catalog injected into this prompt lists them) and assert the body built the
|
injected into this prompt lists a bridge's; for a direct HTTP API, mirror the
|
||||||
real requests. If the catalog names an auth header, set the fixture token in
|
routes the body calls) and assert the body built the real requests. If the
|
||||||
the fixture config and assert the body sent that header. Never connect to a
|
catalog names an auth header, set the fixture token in the fixture config and
|
||||||
real service daemon or a live bridge.
|
assert the body sent that header. Never connect to a real service daemon or a
|
||||||
|
live bridge.
|
||||||
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
|
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
|
||||||
resolution, argument construction, and error paths (missing or misconfigured
|
resolution, argument construction, and error paths (missing or misconfigured
|
||||||
values) without performing the real I/O.
|
values) without performing the real I/O.
|
||||||
|
|||||||
+170
-96
@@ -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,
|
"tau": 0.6,
|
||||||
"max_reentries": 3,
|
"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": "",
|
"timezone": "",
|
||||||
"navigation": {
|
"navigation": {
|
||||||
"_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then 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,
|
"intent_tau": 0.6,
|
||||||
"category_tau": 0.75,
|
"category_tau": 0.75,
|
||||||
"action_tau": 0.5,
|
"action_tau": 0.5,
|
||||||
"softmax_bypass_tau": 0.5
|
"softmax_bypass_tau": 0.5
|
||||||
},
|
},
|
||||||
"queue": {"max_size": 100},
|
"queue": {
|
||||||
|
"max_size": 100
|
||||||
|
},
|
||||||
"engine": {
|
"engine": {
|
||||||
"_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.",
|
|
||||||
"_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).",
|
|
||||||
"_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.",
|
|
||||||
"provider": "semif",
|
"provider": "semif",
|
||||||
"backend": "llamacpp",
|
"backend": "llamacpp",
|
||||||
"context_tokens": 4096,
|
"context_tokens": 4096,
|
||||||
@@ -24,24 +30,33 @@
|
|||||||
"gpu_device": null,
|
"gpu_device": null,
|
||||||
"gpu_split": 0,
|
"gpu_split": 0,
|
||||||
"winnow": {
|
"winnow": {
|
||||||
"_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.",
|
|
||||||
"base_url": "http://127.0.0.1:8091",
|
"base_url": "http://127.0.0.1:8091",
|
||||||
"model": "",
|
"model": "",
|
||||||
"api_key": "",
|
"context_tokens": 32768,
|
||||||
"api_key_env": "",
|
"api_key": "!secret engine_winnow_api_key",
|
||||||
"timeout": 120,
|
"timeout": 120,
|
||||||
"retries": 0,
|
"retries": 0,
|
||||||
"user_agent": "semif-agent",
|
"user_agent": "semif-agent",
|
||||||
"extra_headers": {}
|
"extra_headers": {}
|
||||||
}
|
},
|
||||||
|
"ollama": {
|
||||||
|
"base_url": "http://127.0.0.1:11434",
|
||||||
|
"model": "",
|
||||||
|
"context_tokens": 16384,
|
||||||
|
"api_key": "!secret engine_ollama_api_key",
|
||||||
|
"timeout": 120,
|
||||||
|
"retries": 0,
|
||||||
|
"keep_alive": "",
|
||||||
|
"user_agent": "semif-agent",
|
||||||
|
"extra_headers": {}
|
||||||
|
},
|
||||||
|
"gguf": ""
|
||||||
},
|
},
|
||||||
"llm": {
|
"llm": {
|
||||||
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
|
|
||||||
"provider": "ollama",
|
"provider": "ollama",
|
||||||
"base_url": "http://localhost:11434/v1",
|
"base_url": "http://localhost:11434/v1",
|
||||||
"model": "",
|
"model": "",
|
||||||
"api_key": "",
|
"api_key": "!secret llm_api_key",
|
||||||
"api_key_env": "",
|
|
||||||
"user_agent": "",
|
"user_agent": "",
|
||||||
"timeout": 600,
|
"timeout": 600,
|
||||||
"stream": false,
|
"stream": false,
|
||||||
@@ -54,18 +69,15 @@
|
|||||||
"frequency_penalty": 0.0,
|
"frequency_penalty": 0.0,
|
||||||
"disable_thinking": true,
|
"disable_thinking": true,
|
||||||
"semif": {
|
"semif": {
|
||||||
"_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.",
|
|
||||||
"temperature": 0.0,
|
"temperature": 0.0,
|
||||||
"max_tokens": 256
|
"max_tokens": 256
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"codegen": {
|
"codegen": {
|
||||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. 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",
|
"provider": "ollama",
|
||||||
"base_url": "http://localhost:11434/v1",
|
"base_url": "http://localhost:11434/v1",
|
||||||
"model": "",
|
"model": "",
|
||||||
"api_key": "",
|
"api_key": "!secret codegen_api_key",
|
||||||
"api_key_env": "",
|
|
||||||
"user_agent": "",
|
"user_agent": "",
|
||||||
"timeout": 3600,
|
"timeout": 3600,
|
||||||
"stream": true,
|
"stream": true,
|
||||||
@@ -83,31 +95,27 @@
|
|||||||
"presence_penalty": 0,
|
"presence_penalty": 0,
|
||||||
"frequency_penalty": 1,
|
"frequency_penalty": 1,
|
||||||
"max_attempts": 3,
|
"max_attempts": 3,
|
||||||
"elicitation": {
|
"approval": {
|
||||||
"_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,
|
|
||||||
"wait_timeout": 900
|
"wait_timeout": 900
|
||||||
},
|
},
|
||||||
"fidelity": {
|
"fidelity": {
|
||||||
"_comment": "After the body lands, an authoring:fidelity SemIf decision (accept/reconsider, P(reconsider) >= tau or any static finding) checks whether it really performs the action vs simulates it (canned result, fabricated data, draft-by-default). 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,
|
"enabled": true,
|
||||||
"max_attempts": 1
|
"max_attempts": 1,
|
||||||
|
"tau": 0.6
|
||||||
},
|
},
|
||||||
"repair": {
|
"repair": {
|
||||||
"_comment": "A failed real run triggers a logged SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in the REPL and dashboard. Executing a repair is user-confirmed (a codegen write is slow); body repairs are bounded by max_attempts per skill and carry the observed failure into the regeneration.",
|
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"max_attempts": 1
|
"max_attempts": 1
|
||||||
},
|
},
|
||||||
"test_timeout": 30,
|
"test_timeout": 30,
|
||||||
"test_max_attempts": 3,
|
"test_max_attempts": 3,
|
||||||
|
"max_body_tokens": 0,
|
||||||
|
"max_test_tokens": 0,
|
||||||
|
"decision_reserve_tokens": 1024,
|
||||||
"contract_search": {
|
"contract_search": {
|
||||||
"_comment": "After the data contract lands, run a SemIf choice per variable to auto-populate the skill config.json from the global config and the category config (data/skills/<category>/config.json). Logged as phase config:search.",
|
|
||||||
"enabled": true
|
"enabled": true
|
||||||
},
|
},
|
||||||
"degeneration": {
|
"degeneration": {
|
||||||
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
|
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"threshold": 0.9,
|
"threshold": 0.9,
|
||||||
"interval": 8000,
|
"interval": 8000,
|
||||||
@@ -116,80 +124,23 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"skill_bodies": "data/skills",
|
"skill_bodies": "data/skills",
|
||||||
"skill_seeds": "seeds",
|
|
||||||
"log": "data/decisions.jsonl",
|
"log": "data/decisions.jsonl",
|
||||||
"trace": "data/runs.jsonl",
|
"trace": "data/runs.jsonl",
|
||||||
"category_registry": "data/categories.json",
|
"category_registry": "data/categories.json",
|
||||||
"simplex_chat": {
|
"simplex_chat": {
|
||||||
"_comment": "Per-machine simplex-chat daemon settings. The pinned binary (version/bin_url/sha256) lives in the committed pins.json, not here. The command gateway talks to the daemon on `port` (profile .runtime/simplex/, unit semif-simplex.service). The SimpleX forwarding bridge owns its OWN daemon/profile on `forward_port` (profile .runtime/simplex-forward/, unit semif-simplex-forward.service) so messaging UX never shares the command bot's identity. bootstrap.sh renders both units from these values. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
|
|
||||||
"port": 5226,
|
"port": 5226,
|
||||||
"display_name": "semif",
|
"display_name": "semif",
|
||||||
"forward_port": 5228,
|
"forward_port": 5228,
|
||||||
"forward_display_name": "semif-forward"
|
"forward_display_name": "semif-forward"
|
||||||
},
|
},
|
||||||
"bridges": {
|
|
||||||
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
|
|
||||||
"simplex": {
|
|
||||||
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
|
||||||
"enabled": true,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5227,
|
|
||||||
"token": "",
|
|
||||||
"max_inbox": 100,
|
|
||||||
"ws_url": "ws://127.0.0.1:5228",
|
|
||||||
"user_id": 1,
|
|
||||||
"auto_accept": true,
|
|
||||||
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
|
|
||||||
},
|
|
||||||
"llm": {
|
|
||||||
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
|
|
||||||
"enabled": true,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5229,
|
|
||||||
"token": ""
|
|
||||||
},
|
|
||||||
"nextcloud": {
|
|
||||||
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the nextcloud seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
|
||||||
"enabled": true,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5230,
|
|
||||||
"token": "",
|
|
||||||
"url": "",
|
|
||||||
"username": "",
|
|
||||||
"app_password": "",
|
|
||||||
"default_calendar": "",
|
|
||||||
"default_task_calendar": "",
|
|
||||||
"default_addressbook": "",
|
|
||||||
"verify_tls": true,
|
|
||||||
"timeout": 30
|
|
||||||
},
|
|
||||||
"outlook": {
|
|
||||||
"_comment": "Outlook bridge: the user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — over one uniform local JSON API, so skill bodies never speak Graph or OAuth. No service daemon and no extra dependency (Graph is plain HTTPS); it runs inside the same `semif-bridge` process as the other enabled bridges. Authorization is the OAuth2 device code flow: register an Entra ID public-client app, put its `client_id` here, run `scripts/outlook-auth.py` once, and the tokens are stored (0600) under `.runtime/outlook/token.json` (override with `token_path`). `tenant` is usually `common` (personal + work accounts). `default_calendar`/`default_task_list`/`default_mail_folder` are used when a request names none; `default_timezone` (IANA name) labels created events/tasks whose start has no offset. `verify_tls` false skips certificate verification. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Disabled by default because it needs a client id + an authorization run first.",
|
|
||||||
"enabled": false,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5231,
|
|
||||||
"token": "",
|
|
||||||
"client_id": "",
|
|
||||||
"tenant": "common",
|
|
||||||
"default_calendar": "",
|
|
||||||
"default_task_list": "",
|
|
||||||
"default_mail_folder": "inbox",
|
|
||||||
"default_timezone": "UTC",
|
|
||||||
"verify_tls": true,
|
|
||||||
"timeout": 30
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"gateway": {
|
"gateway": {
|
||||||
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.",
|
|
||||||
"humanize": {
|
"humanize": {
|
||||||
"_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `<skill>: <ok|failed> — <detail>` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.",
|
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"timeout": 20.0,
|
"timeout": 20.0,
|
||||||
"max_tokens": 200,
|
"max_tokens": 200,
|
||||||
"max_chars": 600
|
"max_chars": 600
|
||||||
},
|
},
|
||||||
"simplex": {
|
"simplex": {
|
||||||
"_comment": "SimpleX command adapter. Connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. Groups/attachments are not supported.",
|
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"ws_url": "ws://127.0.0.1:5226",
|
"ws_url": "ws://127.0.0.1:5226",
|
||||||
"allowed_users": [],
|
"allowed_users": [],
|
||||||
@@ -198,10 +149,13 @@
|
|||||||
"home_channel": "",
|
"home_channel": "",
|
||||||
"reply_prefix": "",
|
"reply_prefix": "",
|
||||||
"text_batch_delay": 0.8,
|
"text_batch_delay": 0.8,
|
||||||
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
|
"reconnect": {
|
||||||
|
"initial": 1.0,
|
||||||
|
"max": 60.0,
|
||||||
|
"jitter": 0.2
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"lxmf": {
|
"lxmf": {
|
||||||
"_comment": "LXMF (Reticulum) command adapter. Runs IN-PROCESS — there is no external daemon; `pip install lxmf` provides the transport (optional, lazy-imported; the gateway refuses to start with an install hint). The bot's reachable address is its LXMF delivery destination hash (32 hex chars), printed on connect. config_dir/storage_path hold Reticulum's config and the persisted identity under .runtime/lxmf/ so the address is stable across restarts (empty = the .runtime/lxmf defaults). allowed_users entries match the peer's LXMF address (32 hex chars) or a best-effort display name; default is deny-all unless allow_all_users is set. desired_method is 'direct' (reliable link) or 'opportunistic' (single packet). propagation_node is an optional LXMF propagation-node address (hex) for store-and-forward.",
|
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"allowed_users": [],
|
"allowed_users": [],
|
||||||
"allow_all_users": false,
|
"allow_all_users": false,
|
||||||
@@ -214,10 +168,33 @@
|
|||||||
"storage_path": "",
|
"storage_path": "",
|
||||||
"home_channel": "",
|
"home_channel": "",
|
||||||
"reply_prefix": "",
|
"reply_prefix": "",
|
||||||
"text_batch_delay": 0.8
|
"text_batch_delay": 0.8,
|
||||||
|
"result_only": true,
|
||||||
|
"voice": {
|
||||||
|
"enabled": false,
|
||||||
|
"reply_with_voice": true,
|
||||||
|
"max_speak_chars": 600,
|
||||||
|
"reply_bitrate": 24000,
|
||||||
|
"read": {
|
||||||
|
"enabled": true,
|
||||||
|
"chunk_chars": 300
|
||||||
|
},
|
||||||
|
"stt": {
|
||||||
|
"model": "base.en",
|
||||||
|
"device": "cpu",
|
||||||
|
"compute_type": "int8",
|
||||||
|
"language": "en"
|
||||||
|
},
|
||||||
|
"tts": {
|
||||||
|
"voice": "en_US-lessac-medium",
|
||||||
|
"voice_dir": "",
|
||||||
|
"speaker_id": 0,
|
||||||
|
"length_scale": 1.0,
|
||||||
|
"volume": 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"voice": {
|
"voice": {
|
||||||
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.",
|
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"chat_id": "voice",
|
"chat_id": "voice",
|
||||||
"display_name": "voice",
|
"display_name": "voice",
|
||||||
@@ -225,19 +202,31 @@
|
|||||||
"reply_prefix": "",
|
"reply_prefix": "",
|
||||||
"result_only": true,
|
"result_only": true,
|
||||||
"max_speak_chars": 600,
|
"max_speak_chars": 600,
|
||||||
"follow_up_window_s": 5.0,
|
"read": {
|
||||||
|
"enabled": true,
|
||||||
|
"chunk_chars": 300
|
||||||
|
},
|
||||||
"listen_timeout_s": 3.0,
|
"listen_timeout_s": 3.0,
|
||||||
"cue": {
|
"cue": {
|
||||||
"_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.",
|
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"frequency": 880,
|
"frequency": 880,
|
||||||
"duration_ms": 120,
|
"duration_ms": 120,
|
||||||
"volume": 0.9,
|
"volume": 0.9,
|
||||||
"submit_frequency": 0,
|
"submit_frequency": 0,
|
||||||
"submit_duration_ms": 100
|
"submit_duration_ms": 100,
|
||||||
|
"submit_notes": [
|
||||||
|
[
|
||||||
|
1046.5,
|
||||||
|
70
|
||||||
|
],
|
||||||
|
[
|
||||||
|
1568.0,
|
||||||
|
90
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"note_gap_ms": 20
|
||||||
},
|
},
|
||||||
"wake": {
|
"wake": {
|
||||||
"_comment": "model is an openWakeWord name/path. The default 'hey_computer' is a pinned community model whose scores run lower than the official models (measured ~0.26-0.82 on the phrase, <0.02 on negatives), so threshold 0.2 is tuned for it; the official models (e.g. hey_mycroft) score ~0.99 and are fine at 0.5.",
|
|
||||||
"model": "hey_computer",
|
"model": "hey_computer",
|
||||||
"threshold": 0.2,
|
"threshold": 0.2,
|
||||||
"inference_framework": "onnx",
|
"inference_framework": "onnx",
|
||||||
@@ -257,7 +246,6 @@
|
|||||||
"volume": 1.0
|
"volume": 1.0
|
||||||
},
|
},
|
||||||
"audio": {
|
"audio": {
|
||||||
"_comment": "Capture-stream watchdog: read_timeout_s is how long a frame read waits before it counts as a stall; when the stream stalls continuously for stall_timeout_s (a wedged PortAudio/ALSA callback stops delivering frames) the input is closed and reopened so the voice front end recovers instead of hanging forever. 0 for either restores the old blocking read with no recovery.",
|
|
||||||
"input_device": "",
|
"input_device": "",
|
||||||
"output_device": "",
|
"output_device": "",
|
||||||
"sample_rate": 16000,
|
"sample_rate": 16000,
|
||||||
@@ -269,7 +257,6 @@
|
|||||||
"stall_timeout_s": 5.0
|
"stall_timeout_s": 5.0
|
||||||
},
|
},
|
||||||
"vad": {
|
"vad": {
|
||||||
"_comment": "Endpointing. silence_ms is the trailing-silence endpoint once a command is underway. The wake detector can fire inside the wake phrase (and the cue beep follows), so the first speech captured is the phrase's tail, not the command: until min_command_ms of speech is in hand the endpoint uses initial_silence_ms instead, so a natural pause before the command does not end the capture. min_speech_ms rejects a blip; max_utterance_s caps a runaway.",
|
|
||||||
"silence_ms": 500,
|
"silence_ms": 500,
|
||||||
"min_speech_ms": 120,
|
"min_speech_ms": 120,
|
||||||
"max_utterance_s": 30,
|
"max_utterance_s": 30,
|
||||||
@@ -277,8 +264,95 @@
|
|||||||
"initial_silence_ms": 1500,
|
"initial_silence_ms": 1500,
|
||||||
"aggressiveness": 2,
|
"aggressiveness": 2,
|
||||||
"energy_threshold": 200.0
|
"energy_threshold": 200.0
|
||||||
|
},
|
||||||
|
"follow_up_window_s": 0.0,
|
||||||
|
"barge_in": {
|
||||||
|
"enabled": true,
|
||||||
|
"wait_s": 2.0,
|
||||||
|
"threshold": 0.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dashboard": {"port": 8765, "host": "127.0.0.1"}
|
"dashboard": {
|
||||||
|
"port": 8765,
|
||||||
|
"host": "127.0.0.1"
|
||||||
|
},
|
||||||
|
"skill_packs": "packs",
|
||||||
|
"secrets_file": "secrets.json",
|
||||||
|
"_comment": "GENERATED from the core schema (semif_agent/config.py) and each pack's pack.json `config` schema \u2014 do not hand-edit; edit a pack's schema or the core schema. This is the reference example; the live per-machine config is split under config/ (see config.json's include list) and secrets live in the gitignored secrets.json, referenced as '!secret <key>'.",
|
||||||
|
"bridges": {
|
||||||
|
"llm": {
|
||||||
|
"enabled": true,
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 5229,
|
||||||
|
"token": "!secret llm_token"
|
||||||
|
},
|
||||||
|
"browser": {
|
||||||
|
"enabled": false,
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 5232,
|
||||||
|
"token": "!secret browser_token",
|
||||||
|
"engine": "chromium",
|
||||||
|
"headless": true,
|
||||||
|
"channel": "",
|
||||||
|
"executable_path": "",
|
||||||
|
"profile_dir": "",
|
||||||
|
"browsers_path": "",
|
||||||
|
"screenshot_dir": "",
|
||||||
|
"default_timeout": 30.0,
|
||||||
|
"max_text_chars": 20000
|
||||||
|
},
|
||||||
|
"nextcloud": {
|
||||||
|
"enabled": true,
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 5230,
|
||||||
|
"token": "!secret nextcloud_token",
|
||||||
|
"url": "",
|
||||||
|
"username": "",
|
||||||
|
"app_password": "!secret nextcloud_app_password",
|
||||||
|
"default_calendar": "",
|
||||||
|
"default_task_calendar": "",
|
||||||
|
"default_addressbook": "",
|
||||||
|
"verify_tls": true,
|
||||||
|
"timeout": 30
|
||||||
|
},
|
||||||
|
"outlook": {
|
||||||
|
"enabled": false,
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 5231,
|
||||||
|
"token": "!secret outlook_token",
|
||||||
|
"client_id": "",
|
||||||
|
"tenant": "common",
|
||||||
|
"token_path": ".runtime/outlook/token.json",
|
||||||
|
"default_calendar": "",
|
||||||
|
"default_task_list": "",
|
||||||
|
"default_mail_folder": "inbox",
|
||||||
|
"default_timezone": "UTC",
|
||||||
|
"verify_tls": true,
|
||||||
|
"timeout": 30
|
||||||
|
},
|
||||||
|
"simplex": {
|
||||||
|
"enabled": true,
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 5227,
|
||||||
|
"token": "!secret simplex_token",
|
||||||
|
"max_inbox": 100,
|
||||||
|
"ws_url": "ws://127.0.0.1:5228",
|
||||||
|
"user_id": 1,
|
||||||
|
"auto_accept": true,
|
||||||
|
"reconnect": {
|
||||||
|
"initial": 1.0,
|
||||||
|
"max": 60.0,
|
||||||
|
"jitter": 0.2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"packs": {
|
||||||
|
"essentials": {
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
|
"gutendex": {
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -175,6 +175,15 @@ Then on the gateway host set:
|
|||||||
"gateway": { "voice": { "tts": { "voice": "<name>" } } }
|
"gateway": { "voice": { "tts": { "voice": "<name>" } } }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The LXMF gateway's voice replies resolve a Piper voice the same way from
|
||||||
|
`.runtime/voice/tts/` (`cli._build_gateway_adapter` anchors
|
||||||
|
`gateway.lxmf.voice.tts.voice_dir` there too), so the same trained voice can back
|
||||||
|
both the microphone gateway and Sideband push-to-talk replies:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"gateway": { "lxmf": { "voice": { "tts": { "voice": "<name>" } } } }
|
||||||
|
```
|
||||||
|
|
||||||
Restart the gateway and speak a reply. **Only a real spoken reply proves the
|
Restart the gateway and speak a reply. **Only a real spoken reply proves the
|
||||||
integration** — a generated test passing proves mechanics, not that the voice
|
integration** — a generated test passing proves mechanics, not that the voice
|
||||||
loads and sounds right.
|
loads and sounds right.
|
||||||
|
|||||||
@@ -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 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:
|
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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") 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
|
||||||
@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
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
How one input travels through the agent. Every diamond marked **SemIf** is a
|
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
|
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
|
handle/ignore gate — every input is dispatched, and an explicit housekeeping
|
||||||
command is routed deterministically before navigation.
|
command is routed deterministically before navigation.
|
||||||
|
|
||||||
@@ -64,8 +64,8 @@ flowchart TD
|
|||||||
%% ---------- reuse vs create ----------
|
%% ---------- reuse vs create ----------
|
||||||
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
|
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
|
||||||
HARD -- "yes" --> RUN
|
HARD -- "yes" --> RUN
|
||||||
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>P same >= intent_tau?"]
|
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>same / part / different?<br/>P same+part >= intent_tau"]
|
||||||
INTENT -- "same" --> RUN
|
INTENT -- "same / part" --> RUN
|
||||||
INTENT -- "different" --> CREATESKILL
|
INTENT -- "different" --> CREATESKILL
|
||||||
|
|
||||||
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
|
CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
|
||||||
@@ -94,12 +94,11 @@ flowchart TD
|
|||||||
ACTNI -- "no" --> ASSESS
|
ACTNI -- "no" --> ASSESS
|
||||||
|
|
||||||
%% ---------- assessment ----------
|
%% ---------- assessment ----------
|
||||||
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>P success >= tau?<br/>a definitive empty result counts as success"] --> OK{"success?"}
|
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>additional work to do?<br/>a definitive empty result counts as done"] --> OK{"outcome?"}
|
||||||
OK -- "yes" --> SUMMARY
|
OK -- "done" --> SUMMARY
|
||||||
OK -- "no" --> REQ["SemIf choice<br/>phase 'assess:requeue'<br/>complete vs retry"]
|
OK -- "continue" --> CHAIN["route the logical next step<br/>re-dispatch with the run ledger<br/>bounded by max_reentries + monotonic guard"]
|
||||||
REQ -- "retry" --> REQUEUE["requeue original request<br/>bounded by max_reentries"]
|
CHAIN -.-> PUSH
|
||||||
REQUEUE -.-> PUSH
|
OK -- "failed" --> REPAIR
|
||||||
REQ -- "complete" --> 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"]
|
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 semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
|
||||||
classDef output fill:#fce8e6,stroke:#d93025;
|
classDef output fill:#fce8e6,stroke:#d93025;
|
||||||
classDef author fill:#e6f4ea,stroke:#34a853;
|
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||||
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill;
|
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REPAIR,RECORD semfill;
|
||||||
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT output;
|
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT,CHAIN output;
|
||||||
class CREATECAT,CREATESKILL,AUTHORING author;
|
class CREATECAT,CREATESKILL,AUTHORING author;
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -134,26 +133,26 @@ flowchart TD
|
|||||||
|
|
||||||
DRAFT --> GEN{"category or skill?"}
|
DRAFT --> GEN{"category or skill?"}
|
||||||
GEN -- "category" --> GC["generate_category()<br/>title + description"]
|
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
|
GC --> APPROVE
|
||||||
GS --> APPROVE
|
GS --> APPROVE
|
||||||
|
|
||||||
APPROVE{"creation_approval<br/>on? (default off)"}
|
APPROVE{"new-skill mode<br/>allow / deny / ask<br/>(global default, per-category override)"}
|
||||||
APPROVE -- "no / already approved" --> REGISTER
|
APPROVE -- "allow" --> REGISTER
|
||||||
APPROVE -- "yes" --> PROMPT["Output: approval prompt<br/>REPL / dashboard / gateway<br/>deny or timeout aborts"]
|
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 -- "approved" --> REGISTER
|
||||||
PROMPT -- "denied / timeout / no front end" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
|
PROMPT -- "denied / timeout / no front end" --> ABORT["Output: creation aborted<br/>nothing registered, not re-dispatched"]
|
||||||
|
|
||||||
REGISTER["register stub in registry + tree<br/>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"]
|
REGISTER -- "category" --> CHAIN["chain into skill job<br/>approved=true"]
|
||||||
CHAIN --> DRAFT
|
CHAIN --> DRAFT
|
||||||
REGISTER -- "skill" --> WRITE["single-slot codegen worker<br/>SkillWrite queue<br/>leaf.writing = true, trace 'skill_writing'"]
|
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"]
|
WRITE --> BODY
|
||||||
ELICIT --> QS["Output: questions<br/>posted one at a time<br/>answer_timeout per question"]
|
|
||||||
QS -- "answers / timeout" --> 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 -- "reconsider (once)" --> BODY
|
||||||
FID -- "accept" --> CONTRACT["parse_contract()<br/>read body's CONTRACT constant"]
|
FID -- "accept" --> CONTRACT["parse_contract()<br/>read body's CONTRACT constant"]
|
||||||
|
|
||||||
@@ -176,7 +175,7 @@ flowchart TD
|
|||||||
classDef output fill:#fce8e6,stroke:#d93025;
|
classDef output fill:#fce8e6,stroke:#d93025;
|
||||||
classDef author fill:#e6f4ea,stroke:#34a853;
|
classDef author fill:#e6f4ea,stroke:#34a853;
|
||||||
class FID,CFG,REGEN semfill;
|
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;
|
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) |
|
| Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) |
|
||||||
| Canned | which reply | `navigate:response` | canned line |
|
| Canned | which reply | `navigate:response` | canned line |
|
||||||
| Leaf | which skill | `navigate:leaf` | skill |
|
| 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 |
|
| Config record | record or ask? | `config:record` | persisted / per-fire |
|
||||||
| Outcome | did it succeed? | `assess:outcome` | ok / failed |
|
| Outcome | additional work? | `assess:outcome` | done / continue / failed |
|
||||||
| Requeue | complete or retry? | `assess:requeue` | done / requeue |
|
|
||||||
| Repair | how to recover? | `repair:choice` | offer |
|
| Repair | how to recover? | `repair:choice` | offer |
|
||||||
| Fidelity | real action? | `authoring:fidelity` | accept / rewrite |
|
| Fidelity | real action? | `authoring:fidelity` | accept / rewrite |
|
||||||
| Config search | where is the value? | `config:search` | auto-populate |
|
| 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
|
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,
|
has no create option, so a confident winner is only the closest existing skill,
|
||||||
never a match) — it always runs and can reject into create.
|
never a match) — it always runs and can reject into create.
|
||||||
New-skill creation is also gated deterministically by the per-category
|
New-skill creation is gated deterministically by the tri-state
|
||||||
`locks.new_skill` (the `housekeeping` and `response` categories are hard-locked
|
`new_skill_creation` mode — global default `deny` (opt in with `allow`, or
|
||||||
in code).
|
`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.
|
||||||
@@ -9,10 +9,19 @@
|
|||||||
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
|
"revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
|
||||||
},
|
},
|
||||||
"simplex_chat": {
|
"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",
|
"version": "v7.0.3",
|
||||||
|
"assets": {
|
||||||
|
"x86_64": {
|
||||||
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
|
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
|
||||||
"sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0"
|
"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": {
|
"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.",
|
"_comment": "Piper TTS voice-training refs used by scripts/voice-train.sh (optional, off-bootstrap): the piper1-gpl training toolchain commit and the medium base checkpoint it fine-tunes from. See docs/VOICE-TRAIN.md.",
|
||||||
"piper_train_repo": "https://github.com/OHF-Voice/piper1-gpl.git",
|
"piper_train_repo": "https://github.com/OHF-Voice/piper1-gpl.git",
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Codec2 voice-message decoding (optional).
|
||||||
|
#
|
||||||
|
# Sideband's non-HQ push-to-talk messages carry raw Codec2 frames
|
||||||
|
# (`LXMF.AM_CODEC2_*`); decoding them needs the `pycodec2` bindings, which
|
||||||
|
# compile against the system `libcodec2` (Debian/Ubuntu: `libcodec2-dev`). Only
|
||||||
|
# needed for `gateway.lxmf.voice` when the sender uses non-HQ PTT — HQ Opus
|
||||||
|
# works with `requirements/transcribe.txt` alone. Lazy-imported by
|
||||||
|
# semif_agent/voice_transport.py, so the core stays stdlib-only; a missing
|
||||||
|
# decoder is reported per-message, never a crash.
|
||||||
|
#
|
||||||
|
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the plan
|
||||||
|
# installs it best-effort), or manually:
|
||||||
|
# apt-get install -y libcodec2-dev
|
||||||
|
# .runtime/venv/bin/pip install -r requirements/codec2.txt
|
||||||
|
pycodec2==4.1.1
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Core agent deps (the agent itself is stdlib-only; this is the test runner).
|
||||||
|
#
|
||||||
|
# Every host installs this. The decision engine and messaging transports are
|
||||||
|
# separate, optional files (engine.txt, transports.txt) so a host installs only
|
||||||
|
# what its answers require. The voice stack (voice.txt) is hardware-dependent,
|
||||||
|
# and the browser stack ships WITH its pack (packs/browser/requirements.txt) —
|
||||||
|
# bootstrap installs each selected pack's own requirements.txt.
|
||||||
|
# `staging.txt` includes the repo-level files for a full provision.
|
||||||
|
pytest
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Local decision-engine deps (SemIf / llama.cpp, CPU path).
|
||||||
|
#
|
||||||
|
# Only needed on a host whose `engine.provider` is the local SemIf GGUF. A host
|
||||||
|
# pointed at a remote Winnow decision server (engine.provider == "winnow")
|
||||||
|
# installs neither this file nor the SemIf engine clone / GGUF / tokenizer.
|
||||||
|
#
|
||||||
|
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
|
||||||
|
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
|
||||||
|
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
|
||||||
|
# cp314 wheel (source build fails). So semif-phase1 is installed with
|
||||||
|
# `--no-deps` and exactly this set is brought in instead. The pins match the
|
||||||
|
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
|
||||||
|
# declared version) so the pip resolver stays quiet about it.
|
||||||
|
numpy==2.3.5
|
||||||
|
transformers==5.17.0
|
||||||
|
tokenizers==0.23.2
|
||||||
|
huggingface-hub==1.31.0
|
||||||
|
llama-cpp-python==0.3.35
|
||||||
+16
-22
@@ -1,23 +1,17 @@
|
|||||||
# Staging-machine engine deps (CPU llama.cpp path).
|
# Full provision: every repo-level dependency this checkout can need, for a host
|
||||||
|
# that runs the local decision engine and all messaging transports. This is the
|
||||||
|
# union of the per-concern files below; a `scripts/bootstrap.sh` run installs
|
||||||
|
# only the subset its answers require, so prefer those files (engine.txt,
|
||||||
|
# transports.txt) when provisioning by hand.
|
||||||
#
|
#
|
||||||
# semIF (semif-phase1) hard-pins torch/accelerate/safetensors/sentencepiece/
|
# Voice (voice.txt) and browser (packs/browser/requirements.txt) stacks are
|
||||||
# protobuf/numpy==2.2.6 in its BASE dependencies, but the llamacpp backend
|
# hardware/optional. Voice is a repo file installed with
|
||||||
# never imports torch (it's lazy inside direct.score), and numpy 2.2.6 has no
|
# `scripts/bootstrap.sh --voice`; the browser deps live WITH their pack and are
|
||||||
# cp314 wheel (source build fails). So semif-phase1 is installed with
|
# installed by bootstrap when that pack is selected. transcribe.txt
|
||||||
# `--no-deps` and exactly this set is brought in instead. The pins match the
|
# (faster-whisper only, for LXMF Sideband voice messages), tts.txt (piper-tts +
|
||||||
# proven staging venv; huggingface-hub is pinned to 1.31.0 (semif-phase1's
|
# PyAV, for LXMF voice replies) and codec2.txt (pycodec2, for non-HQ Codec2 PTT)
|
||||||
# declared version) so the pip resolver stays quiet about it.
|
# are likewise optional and installed by bootstrap when `gateway.lxmf.voice` is
|
||||||
numpy==2.3.5
|
# enabled.
|
||||||
transformers==5.17.0
|
-r core.txt
|
||||||
tokenizers==0.23.2
|
-r engine.txt
|
||||||
huggingface-hub==1.31.0
|
-r transports.txt
|
||||||
llama-cpp-python==0.3.35
|
|
||||||
pytest
|
|
||||||
# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the
|
|
||||||
# gateway refuses to start without it. Not needed by the decision engine.
|
|
||||||
websockets==15.0.1
|
|
||||||
# LXMF (Reticulum) gateway transport. Optional: lazy-imported, the gateway
|
|
||||||
# refuses to start without it. Runs in-process — there is no daemon binary.
|
|
||||||
# rns pulls cryptography + pyserial transitively (resolved by pip).
|
|
||||||
lxmf==1.2.0
|
|
||||||
rns==1.5.7
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Voice-message transcription deps (optional).
|
||||||
|
#
|
||||||
|
# Only needed on a host whose LXMF gateway transcribes Sideband push-to-talk
|
||||||
|
# voice messages (`gateway.lxmf.voice.enabled`) but that does NOT run the voice
|
||||||
|
# gateway — `requirements/voice.txt` is hardware-dependent (PortAudio mic +
|
||||||
|
# speaker, wake word, TTS) and none of that is required here. faster-whisper
|
||||||
|
# decodes the Opus/OGG container itself (its bundled PyAV/ffmpeg) and
|
||||||
|
# transcribes, and is lazy-imported by semif_agent/voice_transport.py, so the
|
||||||
|
# core stays stdlib-only on every other host.
|
||||||
|
#
|
||||||
|
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
|
||||||
|
# install plan picks it up on the next run), or manually:
|
||||||
|
# .runtime/venv/bin/pip install -r requirements/transcribe.txt
|
||||||
|
faster-whisper==1.2.1
|
||||||
|
# PyAV 19.0.0 (2026-09-29) REMOVED the `metadata_errors` argument to av.open(),
|
||||||
|
# which faster-whisper 1.2.1 (the latest release) still passes — so any voice
|
||||||
|
# message fails to decode with `TypeError: open() got an unexpected keyword
|
||||||
|
# argument 'metadata_errors'`. faster-whisper's git master handles both, but it
|
||||||
|
# is unreleased; pin PyAV below 19 until a release ships the fix.
|
||||||
|
av<19
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Messaging transport deps (SimpleX + LXMF gateways/bridges).
|
||||||
|
#
|
||||||
|
# Only needed on a host that enables the SimpleX gateway or bridge (which uses
|
||||||
|
# `websockets` against its simplex-chat daemon) or the LXMF gateway (in-process
|
||||||
|
# `lxmf`/`rns`). Both are lazy-imported, so a host without them still runs every
|
||||||
|
# other front end; the gateway refuses to start with an install hint.
|
||||||
|
#
|
||||||
|
# `websockets` is shared by the command gateway and the forwarding bridge (the
|
||||||
|
# neutral `semif_agent/simplex_ws.py`). `lxmf` pulls `rns` (Reticulum) and
|
||||||
|
# cryptography transitively; both are pinned so the resolver stays quiet.
|
||||||
|
websockets==15.0.1
|
||||||
|
lxmf==1.2.0
|
||||||
|
rns==1.5.7
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Voice-reply (text-to-speech) deps for the LXMF gateway (optional).
|
||||||
|
#
|
||||||
|
# When the LXMF gateway handles Sideband push-to-talk voice messages
|
||||||
|
# (`gateway.lxmf.voice.enabled`) and is configured to reply with voice
|
||||||
|
# (`gateway.lxmf.voice.reply_with_voice`, the default), it synthesizes the reply
|
||||||
|
# with Piper and encodes it to the Opus/OGG container Sideband's HQ push-to-talk
|
||||||
|
# uses (`LXMF.AM_OPUS_OGG`). That needs piper-tts (text-to-speech) and PyAV
|
||||||
|
# (libopus encoding) — NOT the hardware voice stack in `requirements/voice.txt`
|
||||||
|
# (no microphone, wake word, or speaker) and NOT transcription
|
||||||
|
# (`requirements/transcribe.txt`, which already pulls PyAV for decoding).
|
||||||
|
# Lazy-imported by semif_agent/voice_transport.py, so the core stays stdlib-only;
|
||||||
|
# a missing stack makes the reply fall back to text, never a crash.
|
||||||
|
#
|
||||||
|
# Install with scripts/bootstrap.sh after enabling gateway.lxmf.voice (the
|
||||||
|
# install plan picks it up on the next run), or manually:
|
||||||
|
# .runtime/venv/bin/pip install -r requirements/tts.txt
|
||||||
|
piper-tts==1.8.0
|
||||||
|
onnxruntime==1.30.0
|
||||||
|
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
|
||||||
|
# still passes to av.open() (see requirements/transcribe.txt); pin below 19 here
|
||||||
|
# too so the shared PyAV is the one both paths expect.
|
||||||
|
av<19
|
||||||
@@ -26,6 +26,10 @@
|
|||||||
sounddevice==0.5.6
|
sounddevice==0.5.6
|
||||||
onnxruntime==1.30.0
|
onnxruntime==1.30.0
|
||||||
faster-whisper==1.2.1
|
faster-whisper==1.2.1
|
||||||
|
# PyAV 19.0.0 removed the `metadata_errors` argument that faster-whisper 1.2.1
|
||||||
|
# still passes to av.open(), breaking every transcription; see
|
||||||
|
# requirements/transcribe.txt for the full note.
|
||||||
|
av<19
|
||||||
piper-tts==1.8.0
|
piper-tts==1.8.0
|
||||||
webrtcvad-wheels==2.0.14.post1
|
webrtcvad-wheels==2.0.14.post1
|
||||||
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
|
# openwakeword runtime deps (installed here because openwakeword is --no-deps).
|
||||||
|
|||||||
+655
-147
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Print the merged config.json as JSON, following its `include` list.
|
||||||
|
|
||||||
|
Stdlib-only on purpose: bootstrap.sh reads per-machine values from the config
|
||||||
|
before the venv exists, so it cannot import `semif_agent.config`. This is the
|
||||||
|
same include/deep-merge semantics (`semif_agent/config.py`), reduced to the
|
||||||
|
minimum bootstrap needs (secrets are not resolved — bootstrap only reads
|
||||||
|
non-secret values like ports and endpoints).
|
||||||
|
|
||||||
|
Usage: python3 scripts/config_merge.py [config.json]
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def _deep_merge(base: dict, extra: dict) -> dict:
|
||||||
|
for key, value in extra.items():
|
||||||
|
if isinstance(value, dict) and isinstance(base.get(key), dict):
|
||||||
|
_deep_merge(base[key], value)
|
||||||
|
else:
|
||||||
|
base[key] = value
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def merge(path: Path, seen: set[Path] | None = None) -> dict:
|
||||||
|
seen = seen if seen is not None else set()
|
||||||
|
resolved = path.resolve()
|
||||||
|
if resolved in seen:
|
||||||
|
raise SystemExit(f"config include cycle at {path}")
|
||||||
|
seen.add(resolved)
|
||||||
|
data = json.loads(path.read_text())
|
||||||
|
includes = data.pop("include", None)
|
||||||
|
merged: dict = {}
|
||||||
|
if includes:
|
||||||
|
for entry in includes:
|
||||||
|
inc = Path(entry)
|
||||||
|
if not inc.is_absolute():
|
||||||
|
inc = path.parent / inc
|
||||||
|
_deep_merge(merged, merge(inc, seen))
|
||||||
|
return _deep_merge(merged, data)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
source = Path(sys.argv[1] if len(sys.argv) > 1 else "config.json")
|
||||||
|
print(json.dumps(merge(source)))
|
||||||
@@ -1,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())
|
|
||||||
@@ -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())
|
|
||||||
@@ -11,7 +11,7 @@ Environment=PYTHONUNBUFFERED=1
|
|||||||
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
|
# Dump every thread's stack on a fatal signal so a wedged front end (e.g. the
|
||||||
# voice mic loop) leaves a trace in the journal instead of hanging silently.
|
# voice mic loop) leaves a trace in the journal instead of hanging silently.
|
||||||
Environment=PYTHONFAULTHANDLER=1
|
Environment=PYTHONFAULTHANDLER=1
|
||||||
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform all
|
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli gateway --platform @PLATFORMS@
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
StandardOutput=journal
|
StandardOutput=journal
|
||||||
|
|||||||
@@ -12,8 +12,11 @@ probability.
|
|||||||
description plus `create_category`; `confirm_category_fit` confirms the
|
description plus `create_category`; `confirm_category_fit` confirms the
|
||||||
winner's scope. `navigation.category_tau` is that guard's P(covers) floor.
|
winner's scope. `navigation.category_tau` is that guard's P(covers) floor.
|
||||||
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
|
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
|
||||||
compares the winner's action to the request. `navigation.intent_tau` is that
|
decides what the winner does for the request (`same` / `part` / `different`).
|
||||||
guard's P(same) floor.
|
`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
|
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
|
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
|
||||||
.runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6
|
.runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6
|
||||||
|
|
||||||
The tree is whatever the host currently has loaded (committed seeds + the runtime
|
The tree is whatever the host currently has loaded (shipped packs + the runtime
|
||||||
`data/skills/`), so an expectation naming a skill that is not present is
|
`data/skills/`), so an expectation naming a skill that is not present is
|
||||||
reported as N/A rather than counted wrong. Labels are hand-written ground truth;
|
reported as N/A rather than counted wrong. Labels are hand-written ground truth;
|
||||||
self-labeled decision rows are not evidence. Nothing is written to the runtime
|
self-labeled decision rows are not evidence. Nothing is written to the runtime
|
||||||
@@ -63,6 +66,8 @@ LEAF_EVAL: list[tuple[str, str]] = [
|
|||||||
("what is my simplex connection link?", "simplex.connect_link"),
|
("what is my simplex connection link?", "simplex.connect_link"),
|
||||||
("give me my simplex contact link", "simplex.connect_link"),
|
("give me my simplex contact link", "simplex.connect_link"),
|
||||||
("tell me the next event in my nextcloud calendar", "nextcloud.next_event"),
|
("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"),
|
("translate my last simplex message to French", "create"),
|
||||||
("delete my next simplex message", "create"),
|
("delete my next simplex message", "create"),
|
||||||
("book a flight to japan", "create"),
|
("book a flight to japan", "create"),
|
||||||
@@ -74,6 +79,8 @@ CATEGORY_EVAL: list[tuple[str, str]] = [
|
|||||||
("send a simplex message to pepper saying hi", "simplex"),
|
("send a simplex message to pepper saying hi", "simplex"),
|
||||||
("what is my simplex connection link?", "simplex"),
|
("what is my simplex connection link?", "simplex"),
|
||||||
("tell me the next event in my nextcloud calendar", "nextcloud"),
|
("tell me the next event in my nextcloud calendar", "nextcloud"),
|
||||||
|
("what is 15% of 80?", "calculator"),
|
||||||
|
("square root of 144", "calculator"),
|
||||||
("hello there", "response"),
|
("hello there", "response"),
|
||||||
("thanks!", "response"),
|
("thanks!", "response"),
|
||||||
("what", "response"),
|
("what", "response"),
|
||||||
@@ -118,7 +125,10 @@ def measure(
|
|||||||
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
|
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
|
||||||
events = trace.read()[before:]
|
events = trace.read()[before:]
|
||||||
guard = next((e for e in events if e["kind"] == "intent_guard"), None)
|
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:
|
def verdict(measured: dict, tau: float) -> str:
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
|
||||||
"nextcloud_username": "The Nextcloud username whose calendars are used.",
|
|
||||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
|
||||||
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
|
|
||||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
|
|
||||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Create a calendar event from a request such as \"add Ashley's dance recital for 5pm Tuesday\"."
|
|
||||||
}
|
|
||||||
@@ -1,628 +0,0 @@
|
|||||||
"""Create a calendar event on the user's Nextcloud calendar from a request.
|
|
||||||
|
|
||||||
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
|
||||||
details and the default calendar come from `ctx.config` (`nextcloud_url`,
|
|
||||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
|
|
||||||
|
|
||||||
`act` reads `request.text` and derives the event's per-request arguments. The
|
|
||||||
title and description are extracted by the local LLM bridge (`llm_bridge_url`,
|
|
||||||
`llm_bridge_token`) with one generic chat call, cached in `request.meta` so a
|
|
||||||
`needs_input` resume does not re-call it; the start date/time and duration are
|
|
||||||
parsed deterministically. Missing arguments are asked one at a time and the
|
|
||||||
answer is stashed in `request.meta`; because `act` is single-phase and re-runs
|
|
||||||
from the top after a `needs_input` pause, the body never re-asks a question it
|
|
||||||
already has an answer for. Calendars are discovered over PROPFIND and the target
|
|
||||||
is resolved by a single SemIf choice over every owned calendar (state = the user
|
|
||||||
query), asking which one the request refers to; a strong winner (probability >=
|
|
||||||
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is
|
|
||||||
used. The event is created with a real CalDAV PUT (iCalendar, UTC timestamps,
|
|
||||||
`If-None-Match: *`) and the real outcome is reported.
|
|
||||||
|
|
||||||
The date/time parse is deliberately bounded; the title/description come from the
|
|
||||||
model. When the model bridge is unavailable the body reports the real failure
|
|
||||||
rather than guessing.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
from datetime import datetime, time, timedelta, timezone
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, Option
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
from semif_agent.timers import local_now
|
|
||||||
|
|
||||||
INTEGRATION = {
|
|
||||||
"service": "nextcloud_calendar",
|
|
||||||
"transport": "caldav",
|
|
||||||
"config_vars": [
|
|
||||||
"nextcloud_url",
|
|
||||||
"nextcloud_username",
|
|
||||||
"nextcloud_app_password",
|
|
||||||
"nextcloud_default_calendar",
|
|
||||||
"llm_bridge_url",
|
|
||||||
"llm_bridge_token",
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
CONTRACT = {
|
|
||||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
|
||||||
"nextcloud_username": "The Nextcloud username whose calendars are used.",
|
|
||||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
|
||||||
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
|
|
||||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
|
|
||||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
}
|
|
||||||
|
|
||||||
DAV = "DAV:"
|
|
||||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
|
||||||
TIMEOUT_SECONDS = 30
|
|
||||||
DEFAULT_DURATION_MINUTES = 60
|
|
||||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
|
||||||
# target calendar; below it the configured default calendar is used instead.
|
|
||||||
CALENDAR_WINNER_TAU = 0.6
|
|
||||||
|
|
||||||
PROPFIND_BODY = (
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
|
|
||||||
"</d:propfind>"
|
|
||||||
).encode("utf-8")
|
|
||||||
|
|
||||||
_WEEKDAYS = {
|
|
||||||
"monday": 0,
|
|
||||||
"mon": 0,
|
|
||||||
"tuesday": 1,
|
|
||||||
"tue": 1,
|
|
||||||
"tues": 1,
|
|
||||||
"wednesday": 2,
|
|
||||||
"wed": 2,
|
|
||||||
"thursday": 3,
|
|
||||||
"thu": 3,
|
|
||||||
"thur": 3,
|
|
||||||
"thurs": 3,
|
|
||||||
"friday": 4,
|
|
||||||
"fri": 4,
|
|
||||||
"saturday": 5,
|
|
||||||
"sat": 5,
|
|
||||||
"sunday": 6,
|
|
||||||
"sun": 6,
|
|
||||||
}
|
|
||||||
_WEEKDAY_RE = re.compile(
|
|
||||||
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
|
|
||||||
)
|
|
||||||
|
|
||||||
_MONTHS = {
|
|
||||||
"jan": 1,
|
|
||||||
"feb": 2,
|
|
||||||
"mar": 3,
|
|
||||||
"apr": 4,
|
|
||||||
"may": 5,
|
|
||||||
"jun": 6,
|
|
||||||
"jul": 7,
|
|
||||||
"aug": 8,
|
|
||||||
"sep": 9,
|
|
||||||
"oct": 10,
|
|
||||||
"nov": 11,
|
|
||||||
"dec": 12,
|
|
||||||
}
|
|
||||||
_MONTH_ALT = (
|
|
||||||
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
|
|
||||||
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
|
|
||||||
)
|
|
||||||
|
|
||||||
class CalDavError(Exception):
|
|
||||||
"""A real failure talking to the calendar service."""
|
|
||||||
|
|
||||||
|
|
||||||
class BridgeError(Exception):
|
|
||||||
"""A real failure talking to the local LLM bridge."""
|
|
||||||
|
|
||||||
|
|
||||||
def _now(ctx):
|
|
||||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
|
||||||
config value when set, else host local. A test seam; never freezes time."""
|
|
||||||
return local_now(ctx.config)
|
|
||||||
|
|
||||||
|
|
||||||
# ---- transport ----
|
|
||||||
|
|
||||||
|
|
||||||
def _request(ctx, method, path, body=None, depth="0", content_type="application/xml; charset=utf-8", extra_headers=None):
|
|
||||||
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
password = str(ctx.config.get("nextcloud_app_password", "") or "")
|
|
||||||
if not url:
|
|
||||||
raise CalDavError("nextcloud_url is not configured")
|
|
||||||
if not username or not password:
|
|
||||||
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
|
|
||||||
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
|
||||||
headers = {"Authorization": f"Basic {token}", "Depth": depth}
|
|
||||||
if body is not None:
|
|
||||||
headers["Content-Type"] = content_type
|
|
||||||
if extra_headers:
|
|
||||||
headers.update(extra_headers)
|
|
||||||
request = urllib.request.Request(
|
|
||||||
url + path, data=body, method=method, headers=headers
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
return response.status, response.read()
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, OSError) as exc:
|
|
||||||
raise CalDavError(f"{method} {path}: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
# ---- CalDAV discovery ----
|
|
||||||
|
|
||||||
|
|
||||||
def _multistatus(body):
|
|
||||||
try:
|
|
||||||
root = ET.fromstring(body)
|
|
||||||
except ET.ParseError as exc:
|
|
||||||
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
|
|
||||||
if root.tag != f"{{{DAV}}}multistatus":
|
|
||||||
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
|
|
||||||
return root
|
|
||||||
|
|
||||||
|
|
||||||
def _response_prop(response):
|
|
||||||
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
|
|
||||||
|
|
||||||
|
|
||||||
def _discover_calendars(ctx):
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
if not username:
|
|
||||||
raise CalDavError("nextcloud_username is not configured")
|
|
||||||
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
|
|
||||||
_status, body = _request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")
|
|
||||||
calendars = []
|
|
||||||
for response in _multistatus(body).findall(f"{{{DAV}}}response"):
|
|
||||||
prop = _response_prop(response)
|
|
||||||
if prop is None:
|
|
||||||
continue
|
|
||||||
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
|
|
||||||
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
|
|
||||||
continue
|
|
||||||
href = response.find(f"{{{DAV}}}href")
|
|
||||||
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
|
|
||||||
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
|
|
||||||
if not name:
|
|
||||||
continue
|
|
||||||
display = prop.find(f"{{{DAV}}}displayname")
|
|
||||||
label = (display.text or "").strip() if display is not None else ""
|
|
||||||
calendars.append({"name": name, "label": label or name})
|
|
||||||
return calendars
|
|
||||||
|
|
||||||
|
|
||||||
def _calendar_path(ctx, calendar):
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
return (
|
|
||||||
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
|
|
||||||
f"{urllib.parse.quote(calendar)}/"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---- LLM field extraction ----
|
|
||||||
|
|
||||||
|
|
||||||
def _extract_fields(ctx, request):
|
|
||||||
"""Ask the LLM bridge for the event title and description.
|
|
||||||
|
|
||||||
One generic `POST /chat` call to the local LLM bridge; the reply is the JSON
|
|
||||||
object the prompt asks for. Raises `BridgeError` when the bridge is
|
|
||||||
unreachable or the reply carries no usable object.
|
|
||||||
"""
|
|
||||||
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
|
||||||
if not base:
|
|
||||||
raise BridgeError("llm_bridge_url is not configured")
|
|
||||||
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
|
|
||||||
messages = [
|
|
||||||
{
|
|
||||||
"role": "system",
|
|
||||||
"content": (
|
|
||||||
"Extract the calendar event from the user's request. Reply with "
|
|
||||||
'ONLY a JSON object: {"title": "<short event title>", '
|
|
||||||
'"description": "<one short sentence, or empty>"}. The title must '
|
|
||||||
"not contain the date, the time, or words like add/schedule/create."
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{"role": "user", "content": request.text},
|
|
||||||
]
|
|
||||||
payload = json.dumps({"messages": messages}).encode("utf-8")
|
|
||||||
headers = {"Content-Type": "application/json"}
|
|
||||||
if token:
|
|
||||||
headers["X-Semif-Token"] = token
|
|
||||||
http_request = urllib.request.Request(
|
|
||||||
base + "/chat", data=payload, method="POST", headers=headers
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
data = json.loads(response.read().decode("utf-8"))
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise BridgeError(f"llm bridge /chat: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
||||||
raise BridgeError(f"llm bridge /chat: {exc}") from exc
|
|
||||||
return _parse_fields(str(data.get("text") or ""))
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_fields(text):
|
|
||||||
"""Pull the `{"title","description"}` object out of the model's reply."""
|
|
||||||
start, end = text.find("{"), text.rfind("}")
|
|
||||||
if start == -1 or end < start:
|
|
||||||
raise BridgeError("llm bridge returned no JSON object")
|
|
||||||
try:
|
|
||||||
data = json.loads(text[start : end + 1])
|
|
||||||
except ValueError as exc:
|
|
||||||
raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
raise BridgeError("llm bridge returned JSON that is not an object")
|
|
||||||
return {
|
|
||||||
"title": str(data.get("title") or "").strip(),
|
|
||||||
"description": str(data.get("description") or "").strip(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _month_number(token):
|
|
||||||
return _MONTHS.get(token.lower()[:3])
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_month_day(month, day, year, now):
|
|
||||||
if not (month and 1 <= day <= 31):
|
|
||||||
return None
|
|
||||||
given_year = year is not None
|
|
||||||
year = year or now.year
|
|
||||||
try:
|
|
||||||
candidate = datetime(year, month, day).date()
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
if not given_year and candidate < now.date():
|
|
||||||
try:
|
|
||||||
candidate = datetime(year + 1, month, day).date()
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_when(text, now):
|
|
||||||
"""Best-effort extraction of date/time/duration from free text.
|
|
||||||
|
|
||||||
Returns a dict with `date` (datetime.date | None), `time` (datetime.time |
|
|
||||||
None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday`
|
|
||||||
(bool). The title and description come from the LLM bridge, so no matched
|
|
||||||
spans are tracked here.
|
|
||||||
"""
|
|
||||||
text = text or ""
|
|
||||||
result = {
|
|
||||||
"date": None,
|
|
||||||
"time": None,
|
|
||||||
"all_day": False,
|
|
||||||
"duration_minutes": None,
|
|
||||||
"from_weekday": False,
|
|
||||||
}
|
|
||||||
|
|
||||||
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
result["all_day"] = True
|
|
||||||
|
|
||||||
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
|
|
||||||
else:
|
|
||||||
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
result["duration_minutes"] = int(match.group(1))
|
|
||||||
else:
|
|
||||||
for phrase, minutes in (
|
|
||||||
(r"\bfor\s+half\s+an?\s+hour\b", 30),
|
|
||||||
(r"\bfor\s+an?\s+hour\b", 60),
|
|
||||||
(r"\bfor\s+a\s+couple\s+of\s+hours\b", 120),
|
|
||||||
):
|
|
||||||
match = re.search(phrase, text, re.I)
|
|
||||||
if match:
|
|
||||||
result["duration_minutes"] = minutes
|
|
||||||
break
|
|
||||||
|
|
||||||
date = None
|
|
||||||
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
|
|
||||||
if match:
|
|
||||||
try:
|
|
||||||
date = datetime(
|
|
||||||
int(match.group(1)), int(match.group(2)), int(match.group(3))
|
|
||||||
).date()
|
|
||||||
except ValueError:
|
|
||||||
date = None
|
|
||||||
|
|
||||||
if date is None:
|
|
||||||
match = re.search(
|
|
||||||
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b",
|
|
||||||
text,
|
|
||||||
re.I,
|
|
||||||
)
|
|
||||||
if match:
|
|
||||||
month = _month_number(match.group(1))
|
|
||||||
year = int(match.group(3)) if match.group(3) else None
|
|
||||||
date = _resolve_month_day(month, int(match.group(2)), year, now)
|
|
||||||
|
|
||||||
if date is None:
|
|
||||||
match = re.search(
|
|
||||||
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
|
|
||||||
text,
|
|
||||||
re.I,
|
|
||||||
)
|
|
||||||
if match:
|
|
||||||
month = _month_number(match.group(2))
|
|
||||||
year = int(match.group(3)) if match.group(3) else None
|
|
||||||
date = _resolve_month_day(month, int(match.group(1)), year, now)
|
|
||||||
|
|
||||||
if date is None:
|
|
||||||
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text)
|
|
||||||
if match:
|
|
||||||
first, second = int(match.group(1)), int(match.group(2))
|
|
||||||
month, day = (first, second) if first <= 12 else (second, first)
|
|
||||||
year = int(match.group(3)) if match.group(3) else None
|
|
||||||
if year is not None and year < 100:
|
|
||||||
year += 2000
|
|
||||||
date = _resolve_month_day(month, day, year, now)
|
|
||||||
|
|
||||||
if date is None:
|
|
||||||
match = re.search(
|
|
||||||
r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I
|
|
||||||
)
|
|
||||||
if match:
|
|
||||||
word = re.sub(r"\s+", " ", match.group(1).lower())
|
|
||||||
if word in ("today", "tonight"):
|
|
||||||
date = now.date()
|
|
||||||
elif word in ("tomorrow", "tmrw", "tomorow"):
|
|
||||||
date = now.date() + timedelta(days=1)
|
|
||||||
else:
|
|
||||||
date = now.date() + timedelta(days=7)
|
|
||||||
|
|
||||||
if date is None:
|
|
||||||
match = _WEEKDAY_RE.search(text)
|
|
||||||
if match:
|
|
||||||
target = _WEEKDAYS[match.group(1).lower()]
|
|
||||||
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
|
|
||||||
prefix = text[max(0, match.start() - 6):match.start()]
|
|
||||||
if re.search(r"\bnext\s*$", prefix, re.I):
|
|
||||||
date += timedelta(days=7)
|
|
||||||
result["from_weekday"] = True
|
|
||||||
|
|
||||||
parsed_time = None
|
|
||||||
match = re.search(r"\bnoon\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
parsed_time = time(12, 0)
|
|
||||||
elif re.search(r"\bmidnight\b", text, re.I):
|
|
||||||
parsed_time = time(0, 0)
|
|
||||||
else:
|
|
||||||
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
hour = int(match.group(1)) % 12
|
|
||||||
minute = int(match.group(2) or 0)
|
|
||||||
if match.group(3).lower() == "p":
|
|
||||||
hour += 12
|
|
||||||
if hour < 24 and minute < 60:
|
|
||||||
parsed_time = time(hour, minute)
|
|
||||||
else:
|
|
||||||
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
|
|
||||||
if match:
|
|
||||||
hour, minute = int(match.group(1)), int(match.group(2))
|
|
||||||
if hour < 24 and minute < 60:
|
|
||||||
parsed_time = time(hour, minute)
|
|
||||||
else:
|
|
||||||
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
|
|
||||||
if match and 13 <= int(match.group(1)) < 24:
|
|
||||||
parsed_time = time(int(match.group(1)), 0)
|
|
||||||
|
|
||||||
result["date"] = date
|
|
||||||
result["time"] = parsed_time
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
# ---- calendar resolution ----
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
|
||||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
|
||||||
default = None
|
|
||||||
for calendar in calendars:
|
|
||||||
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
|
|
||||||
default = calendar
|
|
||||||
break
|
|
||||||
|
|
||||||
if len(calendars) == 1:
|
|
||||||
return calendars[0]["name"]
|
|
||||||
|
|
||||||
decision = DecisionRequest(
|
|
||||||
state=request.text,
|
|
||||||
question="Which calendar is referred to in the user query?",
|
|
||||||
options=[Option(c["name"], c["label"]) for c in calendars],
|
|
||||||
)
|
|
||||||
result = ctx.engine.call(decision)
|
|
||||||
decisions.append((decision, result))
|
|
||||||
winner = result.selected
|
|
||||||
if result.prob(winner) >= CALENDAR_WINNER_TAU:
|
|
||||||
return winner
|
|
||||||
if default is not None:
|
|
||||||
return default["name"]
|
|
||||||
return winner
|
|
||||||
|
|
||||||
|
|
||||||
# ---- iCalendar ----
|
|
||||||
|
|
||||||
|
|
||||||
def _escape_ics(value):
|
|
||||||
return (
|
|
||||||
str(value)
|
|
||||||
.replace("\\", "\\\\")
|
|
||||||
.replace(";", "\\;")
|
|
||||||
.replace(",", "\\,")
|
|
||||||
.replace("\r\n", "\\n")
|
|
||||||
.replace("\n", "\\n")
|
|
||||||
.replace("\r", "\\n")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _utc_stamp(moment):
|
|
||||||
return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
||||||
|
|
||||||
|
|
||||||
def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
|
|
||||||
lines = [
|
|
||||||
"BEGIN:VCALENDAR",
|
|
||||||
"VERSION:2.0",
|
|
||||||
"PRODID:-//semif-agent//nextcloud.create_event//EN",
|
|
||||||
"CALSCALE:GREGORIAN",
|
|
||||||
"BEGIN:VEVENT",
|
|
||||||
f"UID:{uid}",
|
|
||||||
f"DTSTAMP:{stamp}",
|
|
||||||
]
|
|
||||||
if all_day:
|
|
||||||
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
|
|
||||||
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
|
|
||||||
else:
|
|
||||||
lines.append(f"DTSTART:{_utc_stamp(start)}")
|
|
||||||
lines.append(f"DTEND:{_utc_stamp(end)}")
|
|
||||||
lines.append(f"SUMMARY:{_escape_ics(summary)}")
|
|
||||||
if description:
|
|
||||||
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
|
|
||||||
lines += ["END:VEVENT", "END:VCALENDAR", ""]
|
|
||||||
return "\r\n".join(lines).encode("utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
# ---- skill phases ----
|
|
||||||
|
|
||||||
|
|
||||||
def _ask(request, field, question):
|
|
||||||
request.meta["create_event_awaiting"] = field
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"waiting for {field}",
|
|
||||||
new_state=request.text,
|
|
||||||
needs_input=question,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
answers = request.meta.setdefault("create_event_answers", {})
|
|
||||||
awaiting = request.meta.get("create_event_awaiting")
|
|
||||||
if request.user_input is not None and awaiting:
|
|
||||||
if answers.get(awaiting) != request.user_input.strip():
|
|
||||||
answers[awaiting] = request.user_input.strip()
|
|
||||||
request.meta.pop("create_event_awaiting", None)
|
|
||||||
|
|
||||||
fields = request.meta.get("create_event_fields")
|
|
||||||
if fields is None:
|
|
||||||
try:
|
|
||||||
fields = _extract_fields(ctx, request)
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=str(exc),
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
request.meta["create_event_fields"] = fields
|
|
||||||
title = fields["title"]
|
|
||||||
description = fields["description"]
|
|
||||||
|
|
||||||
now = _now(ctx)
|
|
||||||
parsed = _parse_when(request.text, now)
|
|
||||||
|
|
||||||
if answers.get("title"):
|
|
||||||
title = answers["title"].strip()
|
|
||||||
for key in ("date", "time"):
|
|
||||||
if answers.get(key):
|
|
||||||
extra = _parse_when(answers[key], now)
|
|
||||||
if extra["date"] is not None:
|
|
||||||
parsed["date"] = extra["date"]
|
|
||||||
parsed["from_weekday"] = extra["from_weekday"]
|
|
||||||
if extra["time"] is not None:
|
|
||||||
parsed["time"] = extra["time"]
|
|
||||||
if extra["all_day"]:
|
|
||||||
parsed["all_day"] = True
|
|
||||||
if extra["duration_minutes"]:
|
|
||||||
parsed["duration_minutes"] = extra["duration_minutes"]
|
|
||||||
|
|
||||||
if not title:
|
|
||||||
return _ask(request, "title", "What should I call the event?")
|
|
||||||
if parsed["date"] is None:
|
|
||||||
return _ask(request, "date", f"What day should I schedule {title!r}?")
|
|
||||||
if not parsed["all_day"] and parsed["time"] is None:
|
|
||||||
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
|
|
||||||
|
|
||||||
local_tz = now.tzinfo or timezone.utc
|
|
||||||
all_day = bool(parsed["all_day"])
|
|
||||||
if all_day:
|
|
||||||
start_date = parsed["date"]
|
|
||||||
end_date = start_date + timedelta(days=1)
|
|
||||||
start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz)
|
|
||||||
end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz)
|
|
||||||
else:
|
|
||||||
start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz)
|
|
||||||
if start <= now and parsed.get("from_weekday"):
|
|
||||||
start += timedelta(days=7)
|
|
||||||
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
|
|
||||||
end = start + duration
|
|
||||||
|
|
||||||
try:
|
|
||||||
calendars = _discover_calendars(ctx)
|
|
||||||
except CalDavError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"calendar discovery failed: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
if not calendars:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="no calendars found on the account",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
|
|
||||||
decisions = []
|
|
||||||
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
|
||||||
|
|
||||||
uid = f"{uuid.uuid4().hex}@semif-agent"
|
|
||||||
body = _build_ics(
|
|
||||||
uid, title, start, end, all_day, _utc_stamp(now), description=description
|
|
||||||
)
|
|
||||||
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
|
|
||||||
try:
|
|
||||||
_request(
|
|
||||||
ctx,
|
|
||||||
"PUT",
|
|
||||||
path,
|
|
||||||
body=body,
|
|
||||||
depth="0",
|
|
||||||
content_type="text/calendar; charset=utf-8",
|
|
||||||
extra_headers={"If-None-Match": "*"},
|
|
||||||
)
|
|
||||||
except CalDavError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"could not create {title!r} on "
|
|
||||||
f"{calendar!r}: {exc}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
if all_day:
|
|
||||||
when_text = f"{start_date.isoformat()} (all day)"
|
|
||||||
else:
|
|
||||||
when_text = (
|
|
||||||
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
|
|
||||||
f"{end.strftime('%H:%M %Z')}"
|
|
||||||
)
|
|
||||||
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
|
|
||||||
return ActionResult(
|
|
||||||
action_log=report,
|
|
||||||
new_state=report,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
@@ -1,451 +0,0 @@
|
|||||||
"""Hermetic mechanics test for nextcloud.create_event.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
|
||||||
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
|
|
||||||
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
|
|
||||||
and description through the LLM bridge (caching the call across a `needs_input`
|
|
||||||
resume), parses the date/time from the request, asks for a missing field and
|
|
||||||
resumes, resolves the target calendar with a SemIf choice over the owned
|
|
||||||
calendars (a strong winner is used, otherwise the configured default), writes a
|
|
||||||
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
|
|
||||||
It does NOT prove the live integration — only a real run against the user's
|
|
||||||
Nextcloud does.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import urllib.parse
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionResult, Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
|
|
||||||
skill._now = lambda ctx: FIXED_NOW
|
|
||||||
|
|
||||||
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
|
|
||||||
|
|
||||||
|
|
||||||
def next_weekday(now, weekday):
|
|
||||||
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
|
|
||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
|
||||||
"""Test-only engine.
|
|
||||||
|
|
||||||
By default it picks the requested option id (else the first) with full
|
|
||||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
|
||||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, pick=None, probs=None):
|
|
||||||
self.pick = pick
|
|
||||||
self.probs = probs
|
|
||||||
self.decisions = []
|
|
||||||
|
|
||||||
def call(self, decision):
|
|
||||||
self.decisions.append(decision)
|
|
||||||
option_ids = [option.id for option in decision.options]
|
|
||||||
if self.probs is not None:
|
|
||||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
|
||||||
else:
|
|
||||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
|
||||||
probabilities = [
|
|
||||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
|
||||||
]
|
|
||||||
return DecisionResult(
|
|
||||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CalDavHandler(BaseHTTPRequestHandler):
|
|
||||||
calendars = []
|
|
||||||
put_status = 201
|
|
||||||
requests = []
|
|
||||||
puts = []
|
|
||||||
llm_reply = DEFAULT_LLM_REPLY
|
|
||||||
llm_status = 200
|
|
||||||
llm_requests = []
|
|
||||||
|
|
||||||
def _read_body(self):
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
return self.rfile.read(length) if length else b""
|
|
||||||
|
|
||||||
def _send(self, payload, status, content_type):
|
|
||||||
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
|
|
||||||
self.send_response(status)
|
|
||||||
self.send_header("Content-Type", content_type)
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def do_PROPFIND(self):
|
|
||||||
self._read_body()
|
|
||||||
self.requests.append(("PROPFIND", self.path))
|
|
||||||
responses = []
|
|
||||||
for calendar in self.calendars:
|
|
||||||
responses.append(
|
|
||||||
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
|
|
||||||
f'{calendar["name"]}/</d:href>'
|
|
||||||
f"<d:propstat><d:prop>"
|
|
||||||
f'<d:displayname>{calendar["label"]}</d:displayname>'
|
|
||||||
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
|
|
||||||
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
|
|
||||||
f"</d:response>"
|
|
||||||
)
|
|
||||||
body = (
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
+ "".join(responses)
|
|
||||||
+ "</d:multistatus>"
|
|
||||||
)
|
|
||||||
self._send(body, 207, "application/xml; charset=utf-8")
|
|
||||||
|
|
||||||
def do_PUT(self):
|
|
||||||
body = self._read_body()
|
|
||||||
self.puts.append(
|
|
||||||
{"path": self.path, "body": body, "headers": dict(self.headers)}
|
|
||||||
)
|
|
||||||
self._send(b"", self.put_status, "text/plain")
|
|
||||||
|
|
||||||
def do_POST(self):
|
|
||||||
body = self._read_body()
|
|
||||||
if self.path != "/chat":
|
|
||||||
self._send(json.dumps({"error": "not found"}), 404, "application/json")
|
|
||||||
return
|
|
||||||
self.llm_requests.append(body)
|
|
||||||
if self.llm_status != 200:
|
|
||||||
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
|
|
||||||
return
|
|
||||||
self._send(
|
|
||||||
json.dumps({"text": json.dumps(self.llm_reply)}),
|
|
||||||
200,
|
|
||||||
"application/json",
|
|
||||||
)
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
|
|
||||||
handler = type(
|
|
||||||
"Handler",
|
|
||||||
(CalDavHandler,),
|
|
||||||
{
|
|
||||||
"calendars": calendars
|
|
||||||
if calendars is not None
|
|
||||||
else [
|
|
||||||
{"name": "personal", "label": "Personal"},
|
|
||||||
{"name": "work", "label": "Work"},
|
|
||||||
],
|
|
||||||
"put_status": put_status,
|
|
||||||
"requests": [],
|
|
||||||
"puts": [],
|
|
||||||
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
|
|
||||||
"llm_status": llm_status,
|
|
||||||
"llm_requests": [],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
|
||||||
|
|
||||||
|
|
||||||
def config(url, default="personal", llm_url=None):
|
|
||||||
return {
|
|
||||||
"nextcloud_url": url,
|
|
||||||
"nextcloud_username": "alice",
|
|
||||||
"nextcloud_app_password": "secret",
|
|
||||||
"nextcloud_default_calendar": default,
|
|
||||||
"llm_bridge_url": url if llm_url is None else llm_url,
|
|
||||||
"llm_bridge_token": "",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def run(handler, url, text, default="personal", engine=None, llm_url=None):
|
|
||||||
engine = engine or FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
|
|
||||||
request = Request(text)
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
return action, request, engine
|
|
||||||
|
|
||||||
|
|
||||||
def test_example_creates_event_on_default_calendar():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
llm_reply={
|
|
||||||
"title": "Ashley's dance recital",
|
|
||||||
"description": "Dance recital at 5pm.",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
# The query names no calendar, so the SemIf choice is a near-tie and the
|
|
||||||
# configured default ("personal") wins.
|
|
||||||
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
|
|
||||||
action, _request, engine = run(
|
|
||||||
handler,
|
|
||||||
url,
|
|
||||||
"add Ashley's dance recital to the calendar for 5pm Tuesday",
|
|
||||||
engine=engine,
|
|
||||||
)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
|
|
||||||
assert engine.decisions[0].state == (
|
|
||||||
"add Ashley's dance recital to the calendar for 5pm Tuesday"
|
|
||||||
), engine.decisions[0]
|
|
||||||
assert "referred to in the user query" in engine.decisions[0].question
|
|
||||||
assert len(handler.puts) == 1, handler.puts
|
|
||||||
put = handler.puts[0]
|
|
||||||
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
|
|
||||||
assert put["path"].endswith(".ics"), put
|
|
||||||
assert put["headers"].get("If-None-Match") == "*"
|
|
||||||
body = put["body"].decode("utf-8")
|
|
||||||
assert "SUMMARY:Ashley's dance recital" in body, body
|
|
||||||
assert "DESCRIPTION:Dance recital at 5pm." in body, body
|
|
||||||
tuesday = next_weekday(FIXED_NOW, 1)
|
|
||||||
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
|
|
||||||
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
|
|
||||||
assert "Ashley's dance recital" in action.action_log, action.action_log
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_time_asks_then_creates():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
llm_reply={"title": "dentist appointment", "description": ""}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
action, request, engine = run(
|
|
||||||
handler, url, "add dentist appointment on 2026-11-10"
|
|
||||||
)
|
|
||||||
assert action.needs_input, "a missing start time must be asked"
|
|
||||||
assert "time" in action.needs_input.lower(), action.needs_input
|
|
||||||
assert handler.puts == []
|
|
||||||
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
|
|
||||||
request.user_input = "2pm"
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(handler.puts) == 1, handler.puts
|
|
||||||
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
|
|
||||||
body = handler.puts[0]["body"].decode("utf-8")
|
|
||||||
assert "SUMMARY:dentist appointment" in body, body
|
|
||||||
assert "DTSTART:20261110T140000Z" in body, body
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_day_asks_then_creates():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
llm_reply={"title": "dentist appointment", "description": ""}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
|
|
||||||
assert action.needs_input, "a missing day must be asked"
|
|
||||||
assert "day" in action.needs_input.lower(), action.needs_input
|
|
||||||
request.user_input = "2026-11-10"
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
body = handler.puts[0]["body"].decode("utf-8")
|
|
||||||
assert "DTSTART:20261110T140000Z" in body, body
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_title_asks():
|
|
||||||
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
|
|
||||||
try:
|
|
||||||
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
|
|
||||||
assert action.needs_input, "a missing title must be asked"
|
|
||||||
assert "call the event" in action.needs_input.lower(), action.needs_input
|
|
||||||
assert handler.puts == []
|
|
||||||
print(action.needs_input)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_named_calendar_is_used():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
llm_reply={"title": "team sync", "description": ""}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(pick="work")
|
|
||||||
action, _request, engine = run(
|
|
||||||
handler,
|
|
||||||
url,
|
|
||||||
"add team sync to my work calendar on 2026-11-10 at 9am",
|
|
||||||
engine=engine,
|
|
||||||
)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(engine.decisions) == 1, engine.decisions
|
|
||||||
assert [option.id for option in engine.decisions[0].options] == [
|
|
||||||
"personal",
|
|
||||||
"work",
|
|
||||||
], engine.decisions[0].options
|
|
||||||
assert handler.puts[0]["path"].startswith(
|
|
||||||
"/remote.php/dav/calendars/alice/work/"
|
|
||||||
), handler.puts[0]
|
|
||||||
body = handler.puts[0]["body"].decode("utf-8")
|
|
||||||
assert "SUMMARY:team sync" in body, body
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_weak_winner_falls_back_to_default():
|
|
||||||
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
|
|
||||||
try:
|
|
||||||
# Work edges out personal but stays below the strong-winner threshold, so
|
|
||||||
# the configured default ("personal") is used instead.
|
|
||||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
|
||||||
action, _request, engine = run(
|
|
||||||
handler,
|
|
||||||
url,
|
|
||||||
"add standup on 2026-11-10 at 9am",
|
|
||||||
engine=engine,
|
|
||||||
)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(engine.decisions) == 1, engine.decisions
|
|
||||||
assert handler.puts[0]["path"].startswith(
|
|
||||||
"/remote.php/dav/calendars/alice/personal/"
|
|
||||||
), handler.puts[0]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_default_uses_semif_decision():
|
|
||||||
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
|
|
||||||
try:
|
|
||||||
# The configured default is not among the account's calendars and the
|
|
||||||
# SemIf winner is weak: the winner is used anyway (never blocks).
|
|
||||||
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
|
|
||||||
action, _request, engine = run(
|
|
||||||
handler,
|
|
||||||
url,
|
|
||||||
"add standup on 2026-11-10 at 9am",
|
|
||||||
default="missing",
|
|
||||||
engine=engine,
|
|
||||||
)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(engine.decisions) == 1, engine.decisions
|
|
||||||
assert action.decisions and len(action.decisions) == 1, action.decisions
|
|
||||||
assert handler.puts[0]["path"].startswith(
|
|
||||||
"/remote.php/dav/calendars/alice/work/"
|
|
||||||
), handler.puts[0]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_all_day_event():
|
|
||||||
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
|
|
||||||
try:
|
|
||||||
action, _request, _engine = run(
|
|
||||||
handler, url, "add conference all day on 2026-11-10"
|
|
||||||
)
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
body = handler.puts[0]["body"].decode("utf-8")
|
|
||||||
assert "DTSTART;VALUE=DATE:20261110" in body, body
|
|
||||||
assert "DTEND;VALUE=DATE:20261111" in body, body
|
|
||||||
assert "SUMMARY:conference" in body, body
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_llm_bridge_failure_is_reported_honestly():
|
|
||||||
server, handler, url = start_server()
|
|
||||||
try:
|
|
||||||
action, request, _engine = run(
|
|
||||||
handler,
|
|
||||||
url,
|
|
||||||
"add standup on 2026-11-10 at 9am",
|
|
||||||
llm_url="http://127.0.0.1:1",
|
|
||||||
)
|
|
||||||
assert "llm bridge" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text, "a failed extraction must not fake a result"
|
|
||||||
assert handler.puts == [], "no event is created when the LLM bridge is down"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_llm_bridge_error_status_is_reported_honestly():
|
|
||||||
server, handler, url = start_server(llm_status=502)
|
|
||||||
try:
|
|
||||||
action, request, _engine = run(
|
|
||||||
handler, url, "add standup on 2026-11-10 at 9am"
|
|
||||||
)
|
|
||||||
assert "HTTP 502" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text
|
|
||||||
assert handler.puts == []
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_server_error_is_reported_honestly():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
put_status=500, llm_reply={"title": "standup", "description": ""}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
action, request, _engine = run(
|
|
||||||
handler, url, "add standup on 2026-11-10 at 9am"
|
|
||||||
)
|
|
||||||
assert "500" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text, "a failed create must not fake a result"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unreachable_server_fails_honestly():
|
|
||||||
action, request, _engine = run(
|
|
||||||
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
|
|
||||||
)
|
|
||||||
assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
test_example_creates_event_on_default_calendar()
|
|
||||||
test_missing_time_asks_then_creates()
|
|
||||||
test_missing_day_asks_then_creates()
|
|
||||||
test_missing_title_asks()
|
|
||||||
test_named_calendar_is_used()
|
|
||||||
test_weak_winner_falls_back_to_default()
|
|
||||||
test_unknown_default_uses_semif_decision()
|
|
||||||
test_all_day_event()
|
|
||||||
test_llm_bridge_failure_is_reported_honestly()
|
|
||||||
test_llm_bridge_error_status_is_reported_honestly()
|
|
||||||
test_server_error_is_reported_honestly()
|
|
||||||
test_unreachable_server_fails_honestly()
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list task lists and create the task.",
|
|
||||||
"nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to phrase the task title and description.",
|
|
||||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Add a single task to a Nextcloud task list from a request such as \"add a task to eat more hot dogs\"."
|
|
||||||
}
|
|
||||||
@@ -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 nextcloud.create_task.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
|
||||||
http.server plays the Nextcloud bridge (`GET /tasklists`, `POST /tasks`) and the
|
|
||||||
LLM bridge's `POST /chat`. This proves the body phrases the task through the LLM
|
|
||||||
bridge, picks a task list (the sole one, or a SemIf choice when there are
|
|
||||||
several), creates the task through the bridge, and fails honestly when the LLM
|
|
||||||
bridge or the Nextcloud bridge errors. It does NOT prove the live integration —
|
|
||||||
only a real run against the user's Nextcloud does.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import socket
|
|
||||||
import threading
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
def make_handler(routes, seen):
|
|
||||||
"""Build a request handler that records every request and replays `routes`."""
|
|
||||||
|
|
||||||
class Handler(BaseHTTPRequestHandler):
|
|
||||||
def _respond(self):
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
raw = self.rfile.read(length) if length else b""
|
|
||||||
try:
|
|
||||||
body = json.loads(raw.decode("utf-8")) if raw else None
|
|
||||||
except ValueError:
|
|
||||||
body = raw.decode("utf-8", "replace")
|
|
||||||
seen.append(
|
|
||||||
{
|
|
||||||
"method": self.command,
|
|
||||||
"path": self.path,
|
|
||||||
"headers": {k.lower(): v for k, v in self.headers.items()},
|
|
||||||
"body": body,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
key = (self.command, self.path.split("?")[0])
|
|
||||||
status, payload = routes.get(key, (404, {"error": "no route"}))
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
self.send_response(status)
|
|
||||||
self.send_header("Content-Type", "application/json")
|
|
||||||
self.send_header("Content-Length", str(len(data)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(data)
|
|
||||||
|
|
||||||
do_GET = _respond
|
|
||||||
do_POST = _respond
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
return Handler
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(routes):
|
|
||||||
seen = []
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(routes, seen))
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
url = "http://127.0.0.1:%d" % server.server_address[1]
|
|
||||||
return server, seen, url
|
|
||||||
|
|
||||||
|
|
||||||
def stop(server):
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def closed_port_url():
|
|
||||||
sock = socket.socket()
|
|
||||||
sock.bind(("127.0.0.1", 0))
|
|
||||||
port = sock.getsockname()[1]
|
|
||||||
sock.close()
|
|
||||||
return "http://127.0.0.1:%d" % port
|
|
||||||
|
|
||||||
|
|
||||||
class FakeResult:
|
|
||||||
"""Minimal stand-in for a DecisionResult: the body only reads `.selected`."""
|
|
||||||
|
|
||||||
def __init__(self, selected):
|
|
||||||
self.selected = selected
|
|
||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
|
||||||
"""Test-only decision engine; records the requests the body asked for."""
|
|
||||||
|
|
||||||
def __init__(self, choice=None):
|
|
||||||
self.choice = choice
|
|
||||||
self.calls = []
|
|
||||||
|
|
||||||
def call(self, decision):
|
|
||||||
self.calls.append(decision)
|
|
||||||
return FakeResult(self.choice)
|
|
||||||
|
|
||||||
|
|
||||||
def test_happy_path_single_task_list():
|
|
||||||
llm_routes = {
|
|
||||||
("POST", "/chat"): (
|
|
||||||
200,
|
|
||||||
{
|
|
||||||
"text": '{"summary": "Eat hot dogs", '
|
|
||||||
'"description": "Buy and eat hot dogs"}'
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
nc_routes = {
|
|
||||||
("GET", "/tasklists"): (
|
|
||||||
200,
|
|
||||||
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
|
|
||||||
),
|
|
||||||
("POST", "/tasks"): (
|
|
||||||
200,
|
|
||||||
{"ok": True, "uid": "uid-1", "calendar": "tasks"},
|
|
||||||
),
|
|
||||||
}
|
|
||||||
llm_server, llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=engine,
|
|
||||||
config={
|
|
||||||
"nextcloud_bridge_url": nc_url,
|
|
||||||
"nextcloud_bridge_token": "nc-secret",
|
|
||||||
"llm_bridge_url": llm_url,
|
|
||||||
"llm_bridge_token": "llm-secret",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
request = Request("Add a task in next cloud for eating hot dogs.")
|
|
||||||
result = skill.act(ctx, request)
|
|
||||||
|
|
||||||
assert not engine.calls, "a single task list must not need a decision"
|
|
||||||
assert "Eat hot dogs" in result.action_log, result.action_log
|
|
||||||
assert "Tasks" in result.action_log, result.action_log
|
|
||||||
assert "uid-1" in result.action_log, result.action_log
|
|
||||||
|
|
||||||
assert len(llm_seen) == 1, llm_seen
|
|
||||||
chat = llm_seen[0]
|
|
||||||
assert chat["method"] == "POST", chat
|
|
||||||
assert chat["path"] == "/chat", chat
|
|
||||||
assert chat["headers"].get("x-semif-token") == "llm-secret", chat["headers"]
|
|
||||||
assert chat["body"]["messages"][1]["content"] == request.text, chat["body"]
|
|
||||||
assert "summary" in chat["body"]["messages"][0]["content"], chat["body"]
|
|
||||||
|
|
||||||
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
|
|
||||||
listing = nc_seen[0]
|
|
||||||
assert listing["method"] == "GET", listing
|
|
||||||
assert listing["headers"].get("x-semif-token") == "nc-secret", listing["headers"]
|
|
||||||
create = nc_seen[1]
|
|
||||||
assert create["method"] == "POST", create
|
|
||||||
assert create["headers"].get("x-semif-token") == "nc-secret", create["headers"]
|
|
||||||
assert create["body"] == {
|
|
||||||
"calendar": "tasks",
|
|
||||||
"summary": "Eat hot dogs",
|
|
||||||
"description": "Buy and eat hot dogs",
|
|
||||||
}, create["body"]
|
|
||||||
print("happy path:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_task_lists_asks_and_omits_token_header():
|
|
||||||
llm_routes = {
|
|
||||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
|
||||||
}
|
|
||||||
nc_routes = {
|
|
||||||
("GET", "/tasklists"): (
|
|
||||||
200,
|
|
||||||
{
|
|
||||||
"tasklists": [
|
|
||||||
{"name": "tasks", "label": "Tasks"},
|
|
||||||
{"name": "work", "label": "Work"},
|
|
||||||
]
|
|
||||||
},
|
|
||||||
),
|
|
||||||
("POST", "/tasks"): (200, {"ok": True, "uid": "uid-2", "calendar": "work"}),
|
|
||||||
}
|
|
||||||
llm_server, llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(choice="work")
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=engine,
|
|
||||||
config={
|
|
||||||
"nextcloud_bridge_url": nc_url,
|
|
||||||
"nextcloud_bridge_token": "",
|
|
||||||
"llm_bridge_url": llm_url,
|
|
||||||
"llm_bridge_token": "",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, Request("Add a task in next cloud for eating hot dogs.")
|
|
||||||
)
|
|
||||||
|
|
||||||
assert len(engine.calls) == 1, "two task lists must trigger one decision"
|
|
||||||
decision = engine.calls[0]
|
|
||||||
assert [o.id for o in decision.options] == ["tasks", "work"], decision.options
|
|
||||||
assert result.decisions, "the decision must be recorded on the result"
|
|
||||||
|
|
||||||
assert "x-semif-token" not in llm_seen[0]["headers"], llm_seen[0]["headers"]
|
|
||||||
create = nc_seen[-1]
|
|
||||||
assert create["path"] == "/tasks", create
|
|
||||||
assert create["body"]["calendar"] == "work", create["body"]
|
|
||||||
assert create["body"]["description"] == "", create["body"]
|
|
||||||
assert "x-semif-token" not in create["headers"], create["headers"]
|
|
||||||
assert "Work" in result.action_log, result.action_log
|
|
||||||
print("decision path:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_llm_bridge_failure_leaves_nextcloud_untouched():
|
|
||||||
llm_routes = {("POST", "/chat"): (502, {"error": "model down"})}
|
|
||||||
nc_routes = {
|
|
||||||
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
|
|
||||||
}
|
|
||||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={
|
|
||||||
"nextcloud_bridge_url": nc_url,
|
|
||||||
"llm_bridge_url": llm_url,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
|
||||||
assert "could not phrase the task" in result.action_log, result.action_log
|
|
||||||
assert "model down" in result.action_log, result.action_log
|
|
||||||
assert nc_seen == [], "Nextcloud must not be touched when phrasing fails"
|
|
||||||
print("llm failure:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_llm_reply_without_task_text():
|
|
||||||
llm_routes = {("POST", "/chat"): (200, {"text": "I cannot help with that."})}
|
|
||||||
nc_routes = {
|
|
||||||
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
|
|
||||||
}
|
|
||||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, Request("do something vague"))
|
|
||||||
assert "no usable task text" in result.action_log, result.action_log
|
|
||||||
assert nc_seen == [], "Nextcloud must not be touched without a task title"
|
|
||||||
print("unusable llm reply:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_task_lists_available():
|
|
||||||
llm_routes = {
|
|
||||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
|
||||||
}
|
|
||||||
nc_routes = {("GET", "/tasklists"): (200, {"tasklists": []})}
|
|
||||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
|
||||||
assert "no Nextcloud task lists" in result.action_log, result.action_log
|
|
||||||
assert [r["path"] for r in nc_seen] == ["/tasklists"], nc_seen
|
|
||||||
print("no task lists:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_unreachable_nextcloud_bridge():
|
|
||||||
llm_routes = {
|
|
||||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
|
||||||
}
|
|
||||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={
|
|
||||||
"nextcloud_bridge_url": closed_port_url(),
|
|
||||||
"llm_bridge_url": llm_url,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
|
||||||
assert "could not list Nextcloud task lists" in result.action_log, result.action_log
|
|
||||||
print("unreachable nextcloud:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
|
|
||||||
|
|
||||||
def test_task_creation_failure_is_reported():
|
|
||||||
llm_routes = {
|
|
||||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
|
||||||
}
|
|
||||||
nc_routes = {
|
|
||||||
("GET", "/tasklists"): (
|
|
||||||
200,
|
|
||||||
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
|
|
||||||
),
|
|
||||||
("POST", "/tasks"): (502, {"error": "CalDAV rejected the VTODO"}),
|
|
||||||
}
|
|
||||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
|
||||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
|
||||||
assert "failed to add task" in result.action_log, result.action_log
|
|
||||||
assert "CalDAV rejected the VTODO" in result.action_log, result.action_log
|
|
||||||
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
|
|
||||||
print("creation failure:", result.action_log)
|
|
||||||
finally:
|
|
||||||
stop(llm_server)
|
|
||||||
stop(nc_server)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
test_happy_path_single_task_list()
|
|
||||||
test_multiple_task_lists_asks_and_omits_token_header()
|
|
||||||
test_llm_bridge_failure_leaves_nextcloud_untouched()
|
|
||||||
test_llm_reply_without_task_text()
|
|
||||||
test_no_task_lists_available()
|
|
||||||
test_unreachable_nextcloud_bridge()
|
|
||||||
test_task_creation_failure_is_reported()
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
|
||||||
"nextcloud_username": "The Nextcloud username whose calendars are read.",
|
|
||||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
|
||||||
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Report the next upcoming event on the user's Nextcloud calendar."
|
|
||||||
}
|
|
||||||
@@ -1,416 +0,0 @@
|
|||||||
"""Report the next upcoming event on the user's Nextcloud calendar.
|
|
||||||
|
|
||||||
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
|
||||||
details and the default calendar come from `ctx.config` (`nextcloud_url`,
|
|
||||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
|
|
||||||
|
|
||||||
`act` discovers the user's calendars over PROPFIND and resolves which one the
|
|
||||||
request means with a single SemIf choice over every owned calendar (state = the
|
|
||||||
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
|
|
||||||
otherwise the configured default calendar is used; with no configured default
|
|
||||||
the weak winner stands. It then issues a `calendar-query` REPORT with
|
|
||||||
server-side recurrence expansion and reports the earliest instance that has not
|
|
||||||
ended yet.
|
|
||||||
|
|
||||||
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
|
|
||||||
lives here; a server that ignores expansion is reported honestly rather than
|
|
||||||
guessed at.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import re
|
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from zoneinfo import ZoneInfo
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, Option
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
from semif_agent.timers import local_now
|
|
||||||
|
|
||||||
INTEGRATION = {
|
|
||||||
"service": "nextcloud_calendar",
|
|
||||||
"transport": "caldav",
|
|
||||||
"config_vars": [
|
|
||||||
"nextcloud_url",
|
|
||||||
"nextcloud_username",
|
|
||||||
"nextcloud_app_password",
|
|
||||||
"nextcloud_default_calendar",
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
CONTRACT = {
|
|
||||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
|
||||||
"nextcloud_username": "The Nextcloud username whose calendars are read.",
|
|
||||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
|
||||||
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
|
|
||||||
}
|
|
||||||
|
|
||||||
DAV = "DAV:"
|
|
||||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
|
||||||
LOOKAHEAD_DAYS = 60
|
|
||||||
TIMEOUT_SECONDS = 30
|
|
||||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
|
||||||
# target calendar; below it the configured default calendar is used instead.
|
|
||||||
CALENDAR_WINNER_TAU = 0.6
|
|
||||||
|
|
||||||
PROPFIND_BODY = (
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
|
|
||||||
"</d:propfind>"
|
|
||||||
).encode("utf-8")
|
|
||||||
|
|
||||||
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
|
|
||||||
DURATION_RE = re.compile(
|
|
||||||
r"^(?P<sign>[+-])?P"
|
|
||||||
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
|
|
||||||
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CalDavError(Exception):
|
|
||||||
"""A real failure talking to the calendar service."""
|
|
||||||
|
|
||||||
|
|
||||||
def _now(ctx):
|
|
||||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
|
||||||
config value when set, else host local. A test seam; never freezes time."""
|
|
||||||
return local_now(ctx.config)
|
|
||||||
|
|
||||||
|
|
||||||
# ---- transport ----
|
|
||||||
|
|
||||||
|
|
||||||
def _request(ctx, method, path, body=None, depth="0"):
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
password = str(ctx.config.get("nextcloud_app_password", "") or "")
|
|
||||||
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
|
|
||||||
if not url:
|
|
||||||
raise CalDavError("nextcloud_url is not configured")
|
|
||||||
if not username or not password:
|
|
||||||
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
|
|
||||||
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
|
||||||
request = urllib.request.Request(
|
|
||||||
url + path,
|
|
||||||
data=body,
|
|
||||||
method=method,
|
|
||||||
headers={
|
|
||||||
"Authorization": f"Basic {token}",
|
|
||||||
"Depth": depth,
|
|
||||||
"Content-Type": "application/xml; charset=utf-8",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
return response.read()
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, OSError) as exc:
|
|
||||||
raise CalDavError(f"{method} {path}: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
# ---- CalDAV discovery + query ----
|
|
||||||
|
|
||||||
|
|
||||||
def _multistatus(body):
|
|
||||||
try:
|
|
||||||
root = ET.fromstring(body)
|
|
||||||
except ET.ParseError as exc:
|
|
||||||
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
|
|
||||||
if root.tag != f"{{{DAV}}}multistatus":
|
|
||||||
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
|
|
||||||
return root
|
|
||||||
|
|
||||||
|
|
||||||
def _response_prop(response):
|
|
||||||
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
|
|
||||||
|
|
||||||
|
|
||||||
def _discover_calendars(ctx):
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
if not username:
|
|
||||||
raise CalDavError("nextcloud_username is not configured")
|
|
||||||
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
|
|
||||||
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
|
|
||||||
calendars = []
|
|
||||||
for response in root.findall(f"{{{DAV}}}response"):
|
|
||||||
prop = _response_prop(response)
|
|
||||||
if prop is None:
|
|
||||||
continue
|
|
||||||
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
|
|
||||||
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
|
|
||||||
continue
|
|
||||||
href = response.find(f"{{{DAV}}}href")
|
|
||||||
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
|
|
||||||
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
|
|
||||||
if not name:
|
|
||||||
continue
|
|
||||||
display = prop.find(f"{{{DAV}}}displayname")
|
|
||||||
label = (display.text or "").strip() if display is not None else ""
|
|
||||||
calendars.append({"name": name, "label": label or name})
|
|
||||||
return calendars
|
|
||||||
|
|
||||||
|
|
||||||
def _calendar_path(ctx, calendar):
|
|
||||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
|
||||||
return (
|
|
||||||
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
|
|
||||||
f"{urllib.parse.quote(calendar)}/"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _report_body(start, end):
|
|
||||||
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
||||||
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
||||||
return (
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
"<d:prop>"
|
|
||||||
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
|
|
||||||
"</c:calendar-data>"
|
|
||||||
"</d:prop>"
|
|
||||||
"<c:filter>"
|
|
||||||
'<c:comp-filter name="VCALENDAR">'
|
|
||||||
'<c:comp-filter name="VEVENT">'
|
|
||||||
f'<c:time-range start="{start_text}" end="{end_text}"/>'
|
|
||||||
"</c:comp-filter>"
|
|
||||||
"</c:comp-filter>"
|
|
||||||
"</c:filter>"
|
|
||||||
"</c:calendar-query>"
|
|
||||||
).encode("utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
def _calendar_payloads(body):
|
|
||||||
root = _multistatus(body)
|
|
||||||
payloads = []
|
|
||||||
for response in root.findall(f"{{{DAV}}}response"):
|
|
||||||
prop = _response_prop(response)
|
|
||||||
if prop is None:
|
|
||||||
continue
|
|
||||||
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
|
|
||||||
if data.text:
|
|
||||||
payloads.append(data.text)
|
|
||||||
return payloads
|
|
||||||
|
|
||||||
|
|
||||||
# ---- calendar resolution ----
|
|
||||||
|
|
||||||
|
|
||||||
def _default_calendar(ctx, calendars):
|
|
||||||
"""The configured default calendar, if it is one of the account's."""
|
|
||||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
|
||||||
for calendar in calendars:
|
|
||||||
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
|
|
||||||
return calendar
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
|
||||||
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
|
|
||||||
|
|
||||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
|
||||||
default calendar, and with no configured default the weak winner stands.
|
|
||||||
"""
|
|
||||||
default = _default_calendar(ctx, calendars)
|
|
||||||
if len(calendars) == 1:
|
|
||||||
return calendars[0]["name"]
|
|
||||||
|
|
||||||
decision = DecisionRequest(
|
|
||||||
state=request.text,
|
|
||||||
question="Which calendar is referred to in the user query?",
|
|
||||||
options=[Option(c["name"], c["label"]) for c in calendars],
|
|
||||||
)
|
|
||||||
result = ctx.engine.call(decision)
|
|
||||||
decisions.append((decision, result))
|
|
||||||
winner = result.selected
|
|
||||||
if result.prob(winner) >= CALENDAR_WINNER_TAU:
|
|
||||||
return winner
|
|
||||||
if default is not None:
|
|
||||||
return default["name"]
|
|
||||||
return winner
|
|
||||||
|
|
||||||
|
|
||||||
# ---- iCalendar parsing ----
|
|
||||||
|
|
||||||
|
|
||||||
def _unfold(text):
|
|
||||||
lines = []
|
|
||||||
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
|
|
||||||
if raw[:1] in (" ", "\t") and lines:
|
|
||||||
lines[-1] += raw[1:]
|
|
||||||
else:
|
|
||||||
lines.append(raw)
|
|
||||||
return lines
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_property(line):
|
|
||||||
match = PROPERTY_RE.match(line)
|
|
||||||
if match is None:
|
|
||||||
return "", {}, ""
|
|
||||||
name = match.group("name").upper()
|
|
||||||
params = {}
|
|
||||||
for chunk in match.group("params").strip(";").split(";"):
|
|
||||||
key, _, value = chunk.partition("=")
|
|
||||||
if key:
|
|
||||||
params[key.strip().upper()] = value.strip().strip('"')
|
|
||||||
return name, params, match.group("value")
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_datetime(value, params, default_tz):
|
|
||||||
value = value.strip()
|
|
||||||
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
|
|
||||||
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
|
|
||||||
tz = default_tz
|
|
||||||
if value.endswith("Z"):
|
|
||||||
tz = timezone.utc
|
|
||||||
value = value[:-1]
|
|
||||||
elif params.get("TZID"):
|
|
||||||
try:
|
|
||||||
tz = ZoneInfo(params["TZID"])
|
|
||||||
except Exception:
|
|
||||||
tz = default_tz
|
|
||||||
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_duration(value):
|
|
||||||
match = DURATION_RE.match(value.strip().upper())
|
|
||||||
if match is None:
|
|
||||||
return None
|
|
||||||
total = timedelta(
|
|
||||||
weeks=int(match.group("weeks") or 0),
|
|
||||||
days=int(match.group("days") or 0),
|
|
||||||
hours=int(match.group("hours") or 0),
|
|
||||||
minutes=int(match.group("minutes") or 0),
|
|
||||||
seconds=int(match.group("seconds") or 0),
|
|
||||||
)
|
|
||||||
return -total if match.group("sign") == "-" else total
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_events(payloads, default_tz):
|
|
||||||
events = []
|
|
||||||
for payload in payloads:
|
|
||||||
current = None
|
|
||||||
for line in _unfold(payload):
|
|
||||||
name, params, value = _parse_property(line)
|
|
||||||
if name == "BEGIN" and value.strip().upper() == "VEVENT":
|
|
||||||
current = {}
|
|
||||||
continue
|
|
||||||
if name == "END" and value.strip().upper() == "VEVENT":
|
|
||||||
if current is not None:
|
|
||||||
events.append(current)
|
|
||||||
current = None
|
|
||||||
continue
|
|
||||||
if current is None:
|
|
||||||
continue
|
|
||||||
if name == "DTSTART":
|
|
||||||
current["start"], current["all_day"] = _parse_datetime(
|
|
||||||
value, params, default_tz
|
|
||||||
)
|
|
||||||
elif name == "DTEND":
|
|
||||||
current["end"] = _parse_datetime(value, params, default_tz)[0]
|
|
||||||
elif name == "DURATION":
|
|
||||||
current["duration"] = _parse_duration(value)
|
|
||||||
elif name == "SUMMARY":
|
|
||||||
current["summary"] = value.strip()
|
|
||||||
elif name == "LOCATION":
|
|
||||||
current["location"] = value.strip()
|
|
||||||
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
|
|
||||||
current["cancelled"] = True
|
|
||||||
if current is not None:
|
|
||||||
events.append(current)
|
|
||||||
return [
|
|
||||||
event for event in events if "start" in event and not event.get("cancelled")
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _event_end(event):
|
|
||||||
if event.get("end") is not None:
|
|
||||||
return event["end"]
|
|
||||||
duration = event.get("duration")
|
|
||||||
if duration is not None:
|
|
||||||
return event["start"] + duration
|
|
||||||
if event.get("all_day"):
|
|
||||||
return event["start"] + timedelta(days=1)
|
|
||||||
return event["start"]
|
|
||||||
|
|
||||||
|
|
||||||
def _pick_next(events, now):
|
|
||||||
current_or_future = [event for event in events if _event_end(event) >= now]
|
|
||||||
if not current_or_future:
|
|
||||||
return None
|
|
||||||
return min(current_or_future, key=lambda event: event["start"])
|
|
||||||
|
|
||||||
|
|
||||||
def _format_when(event):
|
|
||||||
start = event["start"]
|
|
||||||
if event.get("all_day"):
|
|
||||||
return start.strftime("%Y-%m-%d (all day)")
|
|
||||||
return start.strftime("%Y-%m-%d %H:%M %Z")
|
|
||||||
|
|
||||||
|
|
||||||
# ---- skill phases ----
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
try:
|
|
||||||
calendars = _discover_calendars(ctx)
|
|
||||||
except CalDavError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"calendar discovery failed: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
if not calendars:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="calendar discovery failed: no calendars found",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
|
|
||||||
decisions = []
|
|
||||||
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
|
||||||
if not calendar:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="aborted: no calendar resolved.",
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
now = _now(ctx)
|
|
||||||
local_tz = now.tzinfo or timezone.utc
|
|
||||||
window_start = now - timedelta(days=1)
|
|
||||||
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
|
|
||||||
try:
|
|
||||||
body = _request(
|
|
||||||
ctx,
|
|
||||||
"REPORT",
|
|
||||||
_calendar_path(ctx, calendar),
|
|
||||||
_report_body(window_start, window_end),
|
|
||||||
depth="1",
|
|
||||||
)
|
|
||||||
events = _parse_events(_calendar_payloads(body), local_tz)
|
|
||||||
except CalDavError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"failed on {calendar!r}: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
next_event = _pick_next(events, now)
|
|
||||||
if next_event is None:
|
|
||||||
message = (
|
|
||||||
f"No events on calendar {calendar!r} through "
|
|
||||||
f"{window_end.strftime('%Y-%m-%d')}."
|
|
||||||
)
|
|
||||||
return ActionResult(action_log=message, new_state=message, decisions=decisions)
|
|
||||||
|
|
||||||
summary = next_event.get("summary") or "(no title)"
|
|
||||||
when = _format_when(next_event)
|
|
||||||
message = f"Next event on {calendar!r}: {summary} — {when}"
|
|
||||||
if next_event.get("location"):
|
|
||||||
message += f" at {next_event['location']}"
|
|
||||||
return ActionResult(action_log=message, new_state=message, decisions=decisions)
|
|
||||||
@@ -1,259 +0,0 @@
|
|||||||
"""Hermetic mechanics test for nextcloud.next_event.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
|
||||||
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
|
|
||||||
real CalDAV requests, discovers calendars, resolves the calendar through a
|
|
||||||
SemIf sub-decision (a strong winner is used, otherwise the configured default,
|
|
||||||
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
|
|
||||||
when the service errors. It does NOT prove the live integration — only a real
|
|
||||||
run against the user's Nextcloud does.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionResult, Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
CALENDARS = [("personal", "Personal"), ("work", "Work")]
|
|
||||||
ICS = ""
|
|
||||||
|
|
||||||
|
|
||||||
def build_ics():
|
|
||||||
"""Fixture events relative to now, so the test never rots."""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
past = now - timedelta(days=2)
|
|
||||||
soon = now + timedelta(hours=2)
|
|
||||||
all_day = (now + timedelta(days=2)).date()
|
|
||||||
|
|
||||||
def stamp(value):
|
|
||||||
return value.strftime("%Y%m%dT%H%M%SZ")
|
|
||||||
|
|
||||||
return (
|
|
||||||
"BEGIN:VCALENDAR\nVERSION:2.0\n"
|
|
||||||
"BEGIN:VEVENT\nUID:past@example\n"
|
|
||||||
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
|
|
||||||
"SUMMARY:Already happened\nEND:VEVENT\n"
|
|
||||||
"BEGIN:VEVENT\nUID:soon@example\n"
|
|
||||||
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
|
|
||||||
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n"
|
|
||||||
"BEGIN:VEVENT\nUID:allday@example\n"
|
|
||||||
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n"
|
|
||||||
"SUMMARY:Offsite\nEND:VEVENT\n"
|
|
||||||
"END:VCALENDAR"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
|
||||||
"""Test-only engine.
|
|
||||||
|
|
||||||
By default it picks the requested option id (else the first) with full
|
|
||||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
|
||||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, pick=None, probs=None):
|
|
||||||
self.pick = pick
|
|
||||||
self.probs = probs
|
|
||||||
self.decisions = []
|
|
||||||
|
|
||||||
def call(self, decision):
|
|
||||||
self.decisions.append(decision)
|
|
||||||
option_ids = [option.id for option in decision.options]
|
|
||||||
if self.probs is not None:
|
|
||||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
|
||||||
else:
|
|
||||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
|
||||||
probabilities = [
|
|
||||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
|
||||||
]
|
|
||||||
return DecisionResult(
|
|
||||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CalDavHandler(BaseHTTPRequestHandler):
|
|
||||||
requests = []
|
|
||||||
calendar_count = 2
|
|
||||||
report_status = 207
|
|
||||||
|
|
||||||
def _record(self):
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
body = self.rfile.read(length) if length else b""
|
|
||||||
self.requests.append(
|
|
||||||
{
|
|
||||||
"command": self.command,
|
|
||||||
"path": self.path,
|
|
||||||
"depth": self.headers.get("Depth"),
|
|
||||||
"authorization": self.headers.get("Authorization"),
|
|
||||||
"body": body.decode("utf-8", "replace"),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
def _multistatus(self, payload):
|
|
||||||
body = payload.encode("utf-8")
|
|
||||||
self.send_response(207)
|
|
||||||
self.send_header("Content-Type", "application/xml; charset=utf-8")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def do_PROPFIND(self):
|
|
||||||
self._record()
|
|
||||||
responses = "".join(
|
|
||||||
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
|
|
||||||
"<d:propstat><d:prop>"
|
|
||||||
f"<d:displayname>{label}</d:displayname>"
|
|
||||||
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
|
|
||||||
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
|
|
||||||
for name, label in CALENDARS[: self.calendar_count]
|
|
||||||
)
|
|
||||||
self._multistatus(
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
f"{responses}</d:multistatus>"
|
|
||||||
)
|
|
||||||
|
|
||||||
def do_REPORT(self):
|
|
||||||
self._record()
|
|
||||||
if self.report_status != 207:
|
|
||||||
self.send_response(self.report_status)
|
|
||||||
self.end_headers()
|
|
||||||
return
|
|
||||||
self._multistatus(
|
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
|
||||||
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
|
||||||
"<d:response>"
|
|
||||||
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
|
|
||||||
"<d:propstat><d:prop>"
|
|
||||||
f"<c:calendar-data>{ICS}</c:calendar-data>"
|
|
||||||
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
|
|
||||||
"</d:response></d:multistatus>"
|
|
||||||
)
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(**overrides):
|
|
||||||
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides})
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
|
||||||
|
|
||||||
|
|
||||||
def fixture_config(url, default="personal"):
|
|
||||||
return {
|
|
||||||
"nextcloud_url": url,
|
|
||||||
"nextcloud_username": "testuser",
|
|
||||||
"nextcloud_app_password": "app-pw",
|
|
||||||
"nextcloud_default_calendar": default,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
global ICS
|
|
||||||
ICS = build_ics()
|
|
||||||
|
|
||||||
# A strong winner is used even though a default is configured.
|
|
||||||
server, handler, url = start_server()
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(pick="work")
|
|
||||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
|
||||||
request = Request("what is the next event on my work calendar?")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(action.decisions) == 1, "act must log the calendar choice"
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert [option.id for option in engine.decisions[0].options] == [
|
|
||||||
"personal",
|
|
||||||
"work",
|
|
||||||
], engine.decisions[0].options
|
|
||||||
assert "Team sync" in action.action_log, action.action_log
|
|
||||||
assert action.new_state, "act must set a new state"
|
|
||||||
|
|
||||||
commands = [entry["command"] for entry in handler.requests]
|
|
||||||
assert commands == ["PROPFIND", "REPORT"], commands
|
|
||||||
report = handler.requests[1]
|
|
||||||
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
|
|
||||||
assert report["depth"] == "1", report["depth"]
|
|
||||||
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
|
|
||||||
assert report["authorization"] == expected_auth, report["authorization"]
|
|
||||||
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
|
|
||||||
assert "c:time-range" in report["body"], "the query must bound a time range"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
# A weak winner falls back to the configured default calendar.
|
|
||||||
server, handler, url = start_server()
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
|
||||||
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
|
|
||||||
request = Request("what is the next event on my calendar?")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
|
|
||||||
assert "Team sync" in action.action_log, action.action_log
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
# A weak winner with no configured default stands.
|
|
||||||
server, handler, url = start_server()
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
|
||||||
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
|
|
||||||
request = Request("what is the next event on my calendar?")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
# A single calendar needs no SemIf decision.
|
|
||||||
server, handler, url = start_server(calendar_count=1)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
|
||||||
request = Request("what is the next event on my calendar?")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert engine.decisions == [], "a single calendar needs no SemIf decision"
|
|
||||||
assert "Team sync" in action.action_log, action.action_log
|
|
||||||
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
# A failing REPORT is reported honestly.
|
|
||||||
server, handler, url = start_server(report_status=500)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(pick="personal")
|
|
||||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
|
||||||
request = Request("what is the next event on my calendar?")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "failed" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text, "a failed query must not fake a result"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -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": "Create an Outlook calendar event from a request such as \"add dentist appointment on 2026-11-10 at 2pm\"."
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -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": "Add a task to the user's Microsoft To Do list, e.g. \"remind me to call the dentist tomorrow\"."
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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."
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -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": "List the user's OneDrive files, optionally in a named folder."
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -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": "Read the user's upcoming Outlook calendar events."
|
|
||||||
}
|
|
||||||
@@ -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]}"
|
|
||||||
@@ -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)
|
|
||||||
@@ -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": "Read the latest messages from the user's Outlook inbox."
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -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."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Compose and send an Outlook email, after confirming the message."
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
@@ -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,4 +0,0 @@
|
|||||||
{
|
|
||||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
|
||||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
"""Show the SimpleX contact link others use to connect to this agent.
|
|
||||||
|
|
||||||
Real integration: the standalone SimpleX forwarding bridge
|
|
||||||
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
|
|
||||||
the `simplex-chat` daemon is the only thing that can read (or create) the
|
|
||||||
forwarding bot's *user contact address*; this body asks the bridge for it and
|
|
||||||
reports the link honestly. It never opens a WebSocket to the daemon and never
|
|
||||||
invents a link: if the bridge is not running or has no address, it says so.
|
|
||||||
|
|
||||||
`act` health-checks the bridge, then `GET /address` shows the existing link and
|
|
||||||
creates one on first call, returning `{short_link, full_link, created}`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
|
|
||||||
INTEGRATION = {
|
|
||||||
"service": "simplex",
|
|
||||||
"transport": "http",
|
|
||||||
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
|
|
||||||
}
|
|
||||||
|
|
||||||
CONTRACT = {
|
|
||||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
|
||||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
}
|
|
||||||
|
|
||||||
TIMEOUT_SECONDS = 30
|
|
||||||
|
|
||||||
|
|
||||||
class BridgeError(Exception):
|
|
||||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
|
||||||
|
|
||||||
|
|
||||||
# ---- transport ----
|
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
|
||||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
|
||||||
if not url:
|
|
||||||
raise BridgeError("simplex_bridge_url is not configured")
|
|
||||||
return url
|
|
||||||
|
|
||||||
|
|
||||||
def _headers(ctx):
|
|
||||||
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
|
|
||||||
return {"X-Semif-Token": token} if token else {}
|
|
||||||
|
|
||||||
|
|
||||||
def _get(ctx, path):
|
|
||||||
request = urllib.request.Request(
|
|
||||||
_base(ctx) + path, headers=_headers(ctx)
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
return json.loads(response.read().decode("utf-8"))
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
||||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
# ---- skill phases ----
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
try:
|
|
||||||
payload = _get(ctx, "/health")
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
|
||||||
if not payload.get("ok"):
|
|
||||||
return ActionResult(
|
|
||||||
action_log="simplex forwarding bridge is not healthy",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
payload = _get(ctx, "/address")
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"reading the contact link failed: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
short = str(payload.get("short_link") or "").strip()
|
|
||||||
full = str(payload.get("full_link") or "").strip()
|
|
||||||
if not (short or full):
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
"the bridge returned no SimpleX "
|
|
||||||
"contact link; the bot has no address yet."
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
verb = "created" if payload.get("created") else "current"
|
|
||||||
lines = [f"SimpleX contact link ({verb}): {short or full}"]
|
|
||||||
if short and full:
|
|
||||||
lines.append(f"Full link: {full}")
|
|
||||||
lines.append(
|
|
||||||
"Share this link with someone so they can add the agent and message it."
|
|
||||||
)
|
|
||||||
report = "\n".join(lines)
|
|
||||||
return ActionResult(action_log=report, new_state=report)
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
"""Hermetic mechanics test for simplex.connect_link.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
|
||||||
http.server plays the standalone SimpleX forwarding bridge. This proves the body health-
|
|
||||||
checks the bridge, fetches the contact link, reports a freshly created link, and
|
|
||||||
fails honestly when the bridge has no provider or is unreachable. It does NOT
|
|
||||||
prove the live integration — only a real run against the bridge and a real
|
|
||||||
simplex-chat daemon does.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import urllib.parse
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
class BridgeHandler(BaseHTTPRequestHandler):
|
|
||||||
address = {}
|
|
||||||
address_status = 200
|
|
||||||
requests = []
|
|
||||||
tokens = []
|
|
||||||
|
|
||||||
def _send(self, payload, status=200):
|
|
||||||
body = json.dumps(payload).encode("utf-8")
|
|
||||||
self.send_response(status)
|
|
||||||
self.send_header("Content-Type", "application/json")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def do_GET(self):
|
|
||||||
self.requests.append(self.path)
|
|
||||||
self.tokens.append(self.headers.get("X-Semif-Token"))
|
|
||||||
url = urllib.parse.urlparse(self.path)
|
|
||||||
if url.path == "/health":
|
|
||||||
self._send({"ok": True, "platform": "simplex"})
|
|
||||||
elif url.path == "/address":
|
|
||||||
self._send(self.address, self.address_status)
|
|
||||||
else:
|
|
||||||
self._send({"error": "not found"}, 404)
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(address=None, address_status=200):
|
|
||||||
handler = type(
|
|
||||||
"Handler",
|
|
||||||
(BridgeHandler,),
|
|
||||||
{
|
|
||||||
"address": address or {},
|
|
||||||
"address_status": address_status,
|
|
||||||
"requests": [],
|
|
||||||
"tokens": [],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
|
||||||
|
|
||||||
|
|
||||||
def config(url, token=""):
|
|
||||||
return {"simplex_bridge_url": url, "simplex_bridge_token": token}
|
|
||||||
|
|
||||||
|
|
||||||
def test_reports_existing_link():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
{"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=None, config=config(url))
|
|
||||||
request = Request("give me your simplex link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "simplex:/contact#abc" in action.action_log, action.action_log
|
|
||||||
assert "https://smp/short" in action.action_log, action.action_log
|
|
||||||
assert "current" in action.action_log, action.action_log
|
|
||||||
assert handler.requests == ["/health", "/address"], handler.requests
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_reports_freshly_created_link():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
{"short_link": "simplex:/contact#new", "full_link": "", "created": True}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=None, config=config(url))
|
|
||||||
request = Request("create a simplex invitation link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "simplex:/contact#new" in action.action_log, action.action_log
|
|
||||||
assert "created" in action.action_log, action.action_log
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_provider_is_reported_honestly():
|
|
||||||
server, handler, url = start_server({"error": "address lookup is not available"}, 503)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=None, config=config(url))
|
|
||||||
request = Request("give me your simplex link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "503" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text, "a failed lookup must not fake a result"
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_empty_link_is_reported_honestly():
|
|
||||||
server, handler, url = start_server({"short_link": "", "full_link": "", "created": False})
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=None, config=config(url))
|
|
||||||
request = Request("give me your simplex link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "no SimpleX" in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unreachable_bridge_fails_honestly():
|
|
||||||
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
|
|
||||||
request = Request("give me your simplex link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.action_log and "simplex.connect_link" not in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
|
|
||||||
def test_auth_token_is_sent_when_configured():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
{"short_link": "simplex:/contact#abc", "full_link": "", "created": False}
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
|
|
||||||
request = Request("give me your simplex link")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "simplex:/contact#abc" in action.action_log, action.action_log
|
|
||||||
assert set(handler.tokens) == {"sekret"}, handler.tokens
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
test_reports_existing_link()
|
|
||||||
test_reports_freshly_created_link()
|
|
||||||
test_no_provider_is_reported_honestly()
|
|
||||||
test_empty_link_is_reported_honestly()
|
|
||||||
test_unreachable_bridge_fails_honestly()
|
|
||||||
test_auth_token_is_sent_when_configured()
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
|
||||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Read the next unread SimpleX message."
|
|
||||||
}
|
|
||||||
@@ -1,303 +0,0 @@
|
|||||||
"""Read the next unread SimpleX message through the forwarding bridge.
|
|
||||||
|
|
||||||
Real integration: the standalone SimpleX forwarding bridge
|
|
||||||
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
|
||||||
`act` peeks that inbox, finds which conversations have unread messages, and
|
|
||||||
resolves which one to read with a SemIf choice over them (state = the user
|
|
||||||
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
|
|
||||||
the configured default contact is used; with no configured default (or a default
|
|
||||||
with no unread message) the weak winner stands. It then pops and reports the
|
|
||||||
oldest unread message for that conversation.
|
|
||||||
|
|
||||||
When the live buffer is empty it falls back to the daemon's persistent unread
|
|
||||||
(`/unread` + `/history`), so a message that arrived before the bridge started is
|
|
||||||
still reported. After reporting a message, that single item is marked read on
|
|
||||||
the daemon through the bridge (`POST /read`), so the next call advances to the
|
|
||||||
next unread message instead of re-reporting the same one.
|
|
||||||
|
|
||||||
The bridge owns the read cursor, so this skill keeps no state of its own. It
|
|
||||||
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
|
|
||||||
messaging surface it uses.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import urllib.error
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, Option
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
|
|
||||||
INTEGRATION = {
|
|
||||||
"service": "simplex",
|
|
||||||
"transport": "http",
|
|
||||||
"config_vars": [
|
|
||||||
"simplex_bridge_url",
|
|
||||||
"simplex_bridge_token",
|
|
||||||
"simplex_default_contact",
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
CONTRACT = {
|
|
||||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
|
||||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
|
|
||||||
}
|
|
||||||
|
|
||||||
TIMEOUT_SECONDS = 20
|
|
||||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
|
||||||
# conversation; below it the configured default contact is used instead.
|
|
||||||
CONTACT_WINNER_TAU = 0.6
|
|
||||||
|
|
||||||
|
|
||||||
class BridgeError(Exception):
|
|
||||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
|
||||||
|
|
||||||
|
|
||||||
# ---- transport ----
|
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
|
||||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
|
||||||
if not url:
|
|
||||||
raise BridgeError("simplex_bridge_url is not configured")
|
|
||||||
return url
|
|
||||||
|
|
||||||
|
|
||||||
def _headers(ctx):
|
|
||||||
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
|
|
||||||
return {"X-Semif-Token": token} if token else {}
|
|
||||||
|
|
||||||
|
|
||||||
def _get(ctx, path):
|
|
||||||
request = urllib.request.Request(
|
|
||||||
_base(ctx) + path, headers=_headers(ctx)
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
return json.loads(response.read().decode("utf-8"))
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
||||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
def _post(ctx, path, payload):
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
headers = {**_headers(ctx), "Content-Type": "application/json"}
|
|
||||||
request = urllib.request.Request(
|
|
||||||
_base(ctx) + path, data=data, headers=headers, method="POST"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
|
||||||
return json.loads(response.read().decode("utf-8"))
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
|
||||||
raise BridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
|
|
||||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
||||||
raise BridgeError(f"POST {path}: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
def _mark_read(ctx, contact, item_id):
|
|
||||||
"""Mark one just-reported item read via the bridge.
|
|
||||||
|
|
||||||
Returns None on success, or a short honest reason string on failure. The
|
|
||||||
message was still reported, so a failed consume is surfaced as a note rather
|
|
||||||
than fabricated into a read failure.
|
|
||||||
"""
|
|
||||||
item = str(item_id or "").strip()
|
|
||||||
if not item:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
|
|
||||||
except BridgeError as exc:
|
|
||||||
return str(exc)
|
|
||||||
if not payload.get("ok"):
|
|
||||||
return payload.get("error") or "the bridge did not mark it read"
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
# ---- conversation resolution ----
|
|
||||||
|
|
||||||
|
|
||||||
def _senders(messages):
|
|
||||||
"""Distinct conversations with buffered messages, in arrival order."""
|
|
||||||
senders = []
|
|
||||||
seen = set()
|
|
||||||
for message in messages:
|
|
||||||
contact = str(message.get("contact_id") or "")
|
|
||||||
if not contact or contact in seen:
|
|
||||||
continue
|
|
||||||
seen.add(contact)
|
|
||||||
senders.append(
|
|
||||||
{"id": contact, "display_name": message.get("display_name") or contact}
|
|
||||||
)
|
|
||||||
return senders
|
|
||||||
|
|
||||||
|
|
||||||
def _is_healthy(sender):
|
|
||||||
"""A conversation is healthy when its connection is not known-bad.
|
|
||||||
|
|
||||||
`connected` is absent when the source did not report it (treat as unknown);
|
|
||||||
`auth_errors` counts failed sends on the connection and marks a stale peer.
|
|
||||||
"""
|
|
||||||
if sender.get("connected") is False:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return int(sender.get("auth_errors") or 0) == 0
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _default_sender(ctx, senders):
|
|
||||||
"""The configured default contact, if it has unread messages."""
|
|
||||||
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
|
||||||
if not default:
|
|
||||||
return None
|
|
||||||
for sender in senders:
|
|
||||||
if sender["id"] == default or sender["display_name"] == default:
|
|
||||||
return sender
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve_contact(ctx, request, senders, decisions):
|
|
||||||
"""Resolve which conversation to read, mirroring nextcloud.create_event.
|
|
||||||
|
|
||||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
|
||||||
default contact, and with no configured default the weak winner stands.
|
|
||||||
"""
|
|
||||||
default = _default_sender(ctx, senders)
|
|
||||||
if len(senders) == 1:
|
|
||||||
return senders[0]["id"]
|
|
||||||
|
|
||||||
decision = DecisionRequest(
|
|
||||||
state=request.text,
|
|
||||||
question="Which conversation should I read the next SimpleX message from?",
|
|
||||||
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
|
|
||||||
)
|
|
||||||
result = ctx.engine.call(decision)
|
|
||||||
decisions.append((decision, result))
|
|
||||||
winner = result.selected
|
|
||||||
if result.prob(winner) >= CONTACT_WINNER_TAU:
|
|
||||||
return winner
|
|
||||||
if default is not None:
|
|
||||||
return default["id"]
|
|
||||||
return winner
|
|
||||||
|
|
||||||
|
|
||||||
# ---- skill phases ----
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
try:
|
|
||||||
payload = _get(ctx, "/inbox")
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
|
||||||
senders = _senders(payload.get("messages") or [])
|
|
||||||
if senders:
|
|
||||||
return _read_live(ctx, request, senders)
|
|
||||||
# The live buffer only holds messages that arrived while the bridge was
|
|
||||||
# connected; fall back to the daemon's persistent unread so a message that
|
|
||||||
# landed before the bridge started is not silently missed.
|
|
||||||
return _read_persistent(ctx, request)
|
|
||||||
|
|
||||||
|
|
||||||
def _read_live(ctx, request, senders):
|
|
||||||
decisions = []
|
|
||||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
|
||||||
try:
|
|
||||||
payload = _get(
|
|
||||||
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
|
|
||||||
)
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"failed reading {contact!r}: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
message = payload.get("message")
|
|
||||||
if not message:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"no unread message from {contact!r}.",
|
|
||||||
new_state="no unread SimpleX messages",
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
read_note = _mark_read(ctx, contact, message.get("item_id"))
|
|
||||||
return _report(
|
|
||||||
message.get("display_name") or contact,
|
|
||||||
message.get("text"),
|
|
||||||
decisions,
|
|
||||||
read_note,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _read_persistent(ctx, request):
|
|
||||||
try:
|
|
||||||
payload = _get(ctx, "/unread")
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"no unread SimpleX messages ({exc}).",
|
|
||||||
new_state="no unread SimpleX messages",
|
|
||||||
)
|
|
||||||
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
|
|
||||||
if not chats:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="no unread SimpleX messages.",
|
|
||||||
new_state="no unread SimpleX messages",
|
|
||||||
)
|
|
||||||
senders = [
|
|
||||||
{
|
|
||||||
"id": str(chat.get("contact_id") or ""),
|
|
||||||
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
|
|
||||||
"connected": chat.get("connected"),
|
|
||||||
"auth_errors": chat.get("auth_errors"),
|
|
||||||
}
|
|
||||||
for chat in chats
|
|
||||||
if chat.get("contact_id")
|
|
||||||
]
|
|
||||||
decisions = []
|
|
||||||
healthy = [s for s in senders if _is_healthy(s)]
|
|
||||||
if len(healthy) == 1:
|
|
||||||
# Exactly one conversation is on a healthy connection (the rest are
|
|
||||||
# stale duplicates): read it without a coin-flip decision.
|
|
||||||
contact = healthy[0]["id"]
|
|
||||||
else:
|
|
||||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
|
||||||
try:
|
|
||||||
history = _get(
|
|
||||||
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
|
|
||||||
)
|
|
||||||
except BridgeError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"failed reading {contact!r}: {exc}",
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
|
|
||||||
if not messages:
|
|
||||||
# Fall back to the previewed unread messages from /unread.
|
|
||||||
chat = next(
|
|
||||||
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
|
|
||||||
)
|
|
||||||
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
|
|
||||||
if not messages:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=f"no unread message from {contact!r}.",
|
|
||||||
new_state="no unread SimpleX messages",
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
sender = next(
|
|
||||||
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
|
|
||||||
)
|
|
||||||
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
|
|
||||||
return _report(sender, messages[0].get("text"), decisions, read_note)
|
|
||||||
|
|
||||||
|
|
||||||
def _report(sender, body, decisions, read_note=None):
|
|
||||||
report = f"SimpleX message from {sender}: {str(body or '')}"
|
|
||||||
if read_note:
|
|
||||||
report += f" (could not mark it read: {read_note})"
|
|
||||||
return ActionResult(action_log=report, new_state=report, decisions=decisions)
|
|
||||||
@@ -1,425 +0,0 @@
|
|||||||
"""Hermetic mechanics test for simplex.next_message.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
|
||||||
http.server plays the standalone SimpleX forwarding bridge. This proves the body
|
|
||||||
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
|
|
||||||
strong winner is used, otherwise the configured default, otherwise the weak
|
|
||||||
winner), pops the real `next` message, and fails honestly when the bridge is
|
|
||||||
unreachable. It does NOT prove the live integration — only a real run against
|
|
||||||
the bridge and a real contact does.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import urllib.parse
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionResult, Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
|
||||||
"""Test-only engine.
|
|
||||||
|
|
||||||
By default it picks the requested option id (else the first) with full
|
|
||||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
|
||||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, pick=None, probs=None):
|
|
||||||
self.pick = pick
|
|
||||||
self.probs = probs
|
|
||||||
self.decisions = []
|
|
||||||
|
|
||||||
def call(self, decision):
|
|
||||||
self.decisions.append(decision)
|
|
||||||
option_ids = [option.id for option in decision.options]
|
|
||||||
if self.probs is not None:
|
|
||||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
|
||||||
else:
|
|
||||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
|
||||||
probabilities = [
|
|
||||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
|
||||||
]
|
|
||||||
return DecisionResult(
|
|
||||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class BridgeHandler(BaseHTTPRequestHandler):
|
|
||||||
messages = []
|
|
||||||
unread_chats = []
|
|
||||||
history = {}
|
|
||||||
requests = []
|
|
||||||
tokens = []
|
|
||||||
read_calls = []
|
|
||||||
read_ok = True
|
|
||||||
|
|
||||||
def _send(self, payload, status=200):
|
|
||||||
body = json.dumps(payload).encode("utf-8")
|
|
||||||
self.send_response(status)
|
|
||||||
self.send_header("Content-Type", "application/json")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def do_GET(self):
|
|
||||||
self.requests.append(self.path)
|
|
||||||
self.tokens.append(self.headers.get("X-Semif-Token"))
|
|
||||||
url = urllib.parse.urlparse(self.path)
|
|
||||||
if url.path == "/inbox":
|
|
||||||
self._send({"messages": list(self.messages)})
|
|
||||||
elif url.path == "/inbox/next":
|
|
||||||
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
|
|
||||||
found = None
|
|
||||||
for index, message in enumerate(self.messages):
|
|
||||||
if contact is None or message["contact_id"] == str(contact):
|
|
||||||
found = self.messages.pop(index)
|
|
||||||
break
|
|
||||||
self._send({"message": found})
|
|
||||||
elif url.path == "/unread":
|
|
||||||
self._send({"chats": list(self.unread_chats)})
|
|
||||||
elif url.path == "/history":
|
|
||||||
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
|
|
||||||
self._send(
|
|
||||||
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
self._send({"error": "not found"}, 404)
|
|
||||||
|
|
||||||
def do_POST(self):
|
|
||||||
url = urllib.parse.urlparse(self.path)
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
|
|
||||||
if url.path != "/read":
|
|
||||||
self._send({"error": "not found"}, 404)
|
|
||||||
return
|
|
||||||
self.read_calls.append(payload)
|
|
||||||
if self.read_ok:
|
|
||||||
self._send(
|
|
||||||
{
|
|
||||||
"ok": True,
|
|
||||||
"contact_id": payload.get("contact"),
|
|
||||||
"item_ids": payload.get("item_ids"),
|
|
||||||
"status": "read",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
self._send({"ok": False, "error": "the daemon rejected the read"})
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(messages, unread_chats=None, history=None, read_ok=True):
|
|
||||||
handler = type(
|
|
||||||
"Handler",
|
|
||||||
(BridgeHandler,),
|
|
||||||
{
|
|
||||||
"messages": list(messages),
|
|
||||||
"unread_chats": list(unread_chats or []),
|
|
||||||
"history": dict(history or {}),
|
|
||||||
"requests": [],
|
|
||||||
"tokens": [],
|
|
||||||
"read_calls": [],
|
|
||||||
"read_ok": read_ok,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
|
||||||
|
|
||||||
|
|
||||||
def message(identifier, contact, name, text):
|
|
||||||
return {
|
|
||||||
"id": identifier,
|
|
||||||
"item_id": str(identifier),
|
|
||||||
"contact_id": contact,
|
|
||||||
"display_name": name,
|
|
||||||
"text": text,
|
|
||||||
"received_at": 1.0,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def config(url, default="", token=""):
|
|
||||||
return {
|
|
||||||
"simplex_bridge_url": url,
|
|
||||||
"simplex_default_contact": default,
|
|
||||||
"simplex_bridge_token": token,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_senders_uses_semif_decision():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[
|
|
||||||
message("m1", "4", "Alice", "hello there"),
|
|
||||||
message("m2", "7", "Bob", "shipment arrived"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(pick="7")
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(action.decisions) == 1, "act must log the conversation choice"
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert "Bob" in action.action_log, action.action_log
|
|
||||||
assert "shipment arrived" in action.action_log, action.action_log
|
|
||||||
assert action.new_state, "act must set a new state"
|
|
||||||
|
|
||||||
assert handler.requests[0] == "/inbox", handler.requests
|
|
||||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
|
||||||
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
|
|
||||||
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
|
|
||||||
"the reported item must be marked read, and only it"
|
|
||||||
)
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_strong_winner_overrides_default_contact():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[
|
|
||||||
message("m1", "4", "Alice", "hello there"),
|
|
||||||
message("m2", "7", "Bob", "shipment arrived"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
|
||||||
request = Request("read my next simplex message from Bob")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
|
|
||||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_weak_winner_falls_back_to_default_contact():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[
|
|
||||||
message("m1", "4", "Alice", "hello there"),
|
|
||||||
message("m2", "7", "Bob", "shipment arrived"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
# Bob edges out Alice but stays below the strong-winner threshold, so the
|
|
||||||
# configured default ("Alice") is used instead.
|
|
||||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
|
|
||||||
assert "hello there" in action.action_log, action.action_log
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_weak_winner_without_default_stands():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[
|
|
||||||
message("m1", "4", "Alice", "hello there"),
|
|
||||||
message("m2", "7", "Bob", "shipment arrived"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert len(engine.decisions) == 1
|
|
||||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_single_sender_needs_no_decision():
|
|
||||||
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert engine.decisions == []
|
|
||||||
assert "hi" in action.action_log, action.action_log
|
|
||||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_empty_inbox_is_reported_honestly():
|
|
||||||
server, handler, url = start_server([])
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "no unread" in action.action_log, action.action_log
|
|
||||||
# An empty live buffer falls back to the daemon's persistent unread.
|
|
||||||
assert handler.requests == ["/inbox", "/unread"], handler.requests
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_empty_live_inbox_falls_back_to_persistent_unread():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[],
|
|
||||||
unread_chats=[
|
|
||||||
{
|
|
||||||
"contact_id": "3",
|
|
||||||
"display_name": "pepper",
|
|
||||||
"unread_count": 2,
|
|
||||||
"min_unread_item_id": "8",
|
|
||||||
"unread": True,
|
|
||||||
"messages": [],
|
|
||||||
}
|
|
||||||
],
|
|
||||||
history={
|
|
||||||
"3": [
|
|
||||||
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
|
|
||||||
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
|
|
||||||
]
|
|
||||||
},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert engine.decisions == [], "a single unread chat needs no decision"
|
|
||||||
assert "hello" in action.action_log, action.action_log
|
|
||||||
assert "pepper" in action.action_log, action.action_log
|
|
||||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
|
|
||||||
handler.requests
|
|
||||||
)
|
|
||||||
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_persistent_unread_prefers_a_healthy_conversation():
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[],
|
|
||||||
unread_chats=[
|
|
||||||
{
|
|
||||||
"contact_id": "3",
|
|
||||||
"display_name": "pepper",
|
|
||||||
"unread_count": 1,
|
|
||||||
"unread": True,
|
|
||||||
"connected": True,
|
|
||||||
"auth_errors": 2,
|
|
||||||
"messages": [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"contact_id": "4",
|
|
||||||
"display_name": "pepper",
|
|
||||||
"unread_count": 1,
|
|
||||||
"unread": True,
|
|
||||||
"connected": True,
|
|
||||||
"auth_errors": 0,
|
|
||||||
"messages": [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
history={
|
|
||||||
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
|
|
||||||
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url))
|
|
||||||
action = skill.act(ctx, Request("read my next simplex message"))
|
|
||||||
assert engine.decisions == [], "one healthy chat must win without a decision"
|
|
||||||
assert "fresh hello" in action.action_log, action.action_log
|
|
||||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
|
|
||||||
handler.requests
|
|
||||||
)
|
|
||||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unreachable_bridge_fails_honestly():
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
|
|
||||||
assert action.new_state == request.text, "a failed read must not fake a result"
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
|
|
||||||
def test_auth_token_is_sent_when_configured():
|
|
||||||
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
|
|
||||||
try:
|
|
||||||
engine = FakeEngine()
|
|
||||||
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
|
|
||||||
request = Request("read my next simplex message")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert "hi" in action.action_log, action.action_log
|
|
||||||
assert set(handler.tokens) == {"sekret"}, handler.tokens
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_failed_read_marking_is_surfaced_honestly():
|
|
||||||
"""A message is still reported when consuming it fails, with an honest note
|
|
||||||
instead of a fabricated failure of the read."""
|
|
||||||
server, handler, url = start_server(
|
|
||||||
[message("m1", "4", "Alice", "hi")], read_ok=False
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
|
||||||
action = skill.act(ctx, Request("read my next simplex message"))
|
|
||||||
assert "hi" in action.action_log, action.action_log
|
|
||||||
assert "could not mark it read" in action.action_log, action.action_log
|
|
||||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
|
|
||||||
print(action.action_log)
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
test_multiple_senders_uses_semif_decision()
|
|
||||||
test_strong_winner_overrides_default_contact()
|
|
||||||
test_weak_winner_falls_back_to_default_contact()
|
|
||||||
test_weak_winner_without_default_stands()
|
|
||||||
test_single_sender_needs_no_decision()
|
|
||||||
test_empty_inbox_is_reported_honestly()
|
|
||||||
test_empty_live_inbox_falls_back_to_persistent_unread()
|
|
||||||
test_persistent_unread_prefers_a_healthy_conversation()
|
|
||||||
test_unreachable_bridge_fails_honestly()
|
|
||||||
test_auth_token_is_sent_when_configured()
|
|
||||||
test_failed_read_marking_is_surfaced_honestly()
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"simplex_bridge_url": "Base URL of the local SimpleX forwarding bridge that fronts the user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
|
||||||
"simplex_bridge_token": "Shared secret for the SimpleX bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
|
||||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not clearly name a recipient; leave blank to always use the strongest candidate.",
|
|
||||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to write the message text when the request does not state it.",
|
|
||||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Send a SimpleX message to a contact through the forwarding bridge."
|
|
||||||
}
|
|
||||||
@@ -1,477 +0,0 @@
|
|||||||
"""Send a text message to a SimpleX contact through the local SimpleX bridge.
|
|
||||||
|
|
||||||
Real integration: the simplex bridge over HTTP. The bridge owns the SimpleX
|
|
||||||
daemon connection and its credentials; this body only calls the bridge's HTTP
|
|
||||||
API with the base URL and token resolved from `ctx.config`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, Option
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
|
|
||||||
INTEGRATION = {
|
|
||||||
"service": "simplex",
|
|
||||||
"transport": "http",
|
|
||||||
"config_vars": [
|
|
||||||
"simplex_bridge_url",
|
|
||||||
"simplex_bridge_token",
|
|
||||||
"simplex_default_contact",
|
|
||||||
"llm_bridge_url",
|
|
||||||
"llm_bridge_token",
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
CONTRACT = {
|
|
||||||
"simplex_bridge_url": (
|
|
||||||
"Base URL of the local SimpleX forwarding bridge that fronts the "
|
|
||||||
"user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash "
|
|
||||||
"needed)."
|
|
||||||
),
|
|
||||||
"simplex_bridge_token": (
|
|
||||||
"Shared secret for the SimpleX bridge, if one is configured; sent as "
|
|
||||||
"the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
),
|
|
||||||
"simplex_default_contact": (
|
|
||||||
"Default SimpleX contact (contact id or display name) used when the "
|
|
||||||
"request does not clearly name a recipient; leave blank to always use "
|
|
||||||
"the strongest candidate."
|
|
||||||
),
|
|
||||||
"llm_bridge_url": (
|
|
||||||
"Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no "
|
|
||||||
"trailing slash needed); used to write the message text when the "
|
|
||||||
"request does not state it."
|
|
||||||
),
|
|
||||||
"llm_bridge_token": (
|
|
||||||
"Shared secret for the LLM bridge, if one is configured; sent as the "
|
|
||||||
"X-Semif-Token header. Leave blank when the bridge requires no auth."
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
# A contact sub-decision winner is used only when its conditional probability
|
|
||||||
# clears this bar; otherwise the configured default contact wins.
|
|
||||||
CONFIDENCE_THRESHOLD = 0.5
|
|
||||||
|
|
||||||
_HTTP_TIMEOUT = 20
|
|
||||||
|
|
||||||
# Ordered: the literal message text the user dictated wins over anything else.
|
|
||||||
_MESSAGE_PATTERNS = (
|
|
||||||
r"\b(?:saying|say|that says|which says|that reads|reads)\b\s*[:\-]?\s*(.+)$",
|
|
||||||
r'["\u201c](.+?)["\u201d]',
|
|
||||||
r"\b(?:message|text)\s*(?:is|:)\s*(.+)$",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# bridge transport
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _headers(token: str, has_body: bool) -> dict:
|
|
||||||
headers = {"Accept": "application/json"}
|
|
||||||
if has_body:
|
|
||||||
headers["Content-Type"] = "application/json"
|
|
||||||
if token:
|
|
||||||
headers["X-Semif-Token"] = token
|
|
||||||
return headers
|
|
||||||
|
|
||||||
|
|
||||||
def _http_json(url: str, token: str, payload=None):
|
|
||||||
"""GET the url, or POST the payload as JSON, and decode the JSON reply."""
|
|
||||||
data = None
|
|
||||||
if payload is not None:
|
|
||||||
data = json.dumps(payload).encode("utf-8")
|
|
||||||
request = urllib.request.Request(
|
|
||||||
url,
|
|
||||||
data=data,
|
|
||||||
headers=_headers(token, data is not None),
|
|
||||||
method="POST" if data is not None else "GET",
|
|
||||||
)
|
|
||||||
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT) as response:
|
|
||||||
raw = response.read().decode("utf-8")
|
|
||||||
if not raw.strip():
|
|
||||||
return {}
|
|
||||||
return json.loads(raw)
|
|
||||||
|
|
||||||
|
|
||||||
def _error_detail(exc) -> str:
|
|
||||||
"""Best-effort human-readable detail from an HTTP error response."""
|
|
||||||
try:
|
|
||||||
raw = exc.read().decode("utf-8", "replace")
|
|
||||||
except Exception:
|
|
||||||
raw = ""
|
|
||||||
if raw:
|
|
||||||
try:
|
|
||||||
parsed = json.loads(raw)
|
|
||||||
except ValueError:
|
|
||||||
parsed = None
|
|
||||||
if isinstance(parsed, dict) and parsed.get("error"):
|
|
||||||
return str(parsed["error"])
|
|
||||||
return raw.strip()
|
|
||||||
return str(getattr(exc, "reason", "") or exc)
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# contacts
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _contact_id(contact) -> str:
|
|
||||||
return str(contact.get("id") or contact.get("display_name") or "").strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _display(contact) -> str:
|
|
||||||
return str(contact.get("display_name") or contact.get("id") or "").strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _label(contact) -> str:
|
|
||||||
"""The unique name for a contact: the daemon's local name when known.
|
|
||||||
|
|
||||||
Two peers can share a profile display name; the local name is unique, so it
|
|
||||||
is the right label for a SemIf option and the right thing to match on.
|
|
||||||
"""
|
|
||||||
return str(
|
|
||||||
contact.get("local_name") or _display(contact) or contact.get("id") or ""
|
|
||||||
).strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _is_healthy(contact) -> bool:
|
|
||||||
"""A contact is healthy when its connection is not known-bad.
|
|
||||||
|
|
||||||
`connected` is absent when the source did not report it (treat as unknown,
|
|
||||||
i.e. not disqualifying); `auth_errors` counts failed sends on the connection
|
|
||||||
and marks a stale/duplicate peer.
|
|
||||||
"""
|
|
||||||
if contact.get("connected") is False:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return int(contact.get("auth_errors") or 0) == 0
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _mentions(query: str, name: str) -> bool:
|
|
||||||
if not name:
|
|
||||||
return False
|
|
||||||
pattern = r"(?<!\w)" + re.escape(name.lower()) + r"(?!\w)"
|
|
||||||
return re.search(pattern, query.lower()) is not None
|
|
||||||
|
|
||||||
|
|
||||||
def _match_contact(contacts, ref: str):
|
|
||||||
"""Resolve an id or display name against the bridge's contact list."""
|
|
||||||
ref = (ref or "").strip()
|
|
||||||
if not ref:
|
|
||||||
return None
|
|
||||||
lowered = ref.lower()
|
|
||||||
for contact in contacts:
|
|
||||||
if _contact_id(contact).lower() == lowered:
|
|
||||||
return contact
|
|
||||||
exact = [
|
|
||||||
c
|
|
||||||
for c in contacts
|
|
||||||
if _label(c).lower() == lowered or _display(c).lower() == lowered
|
|
||||||
]
|
|
||||||
if exact:
|
|
||||||
return _preferred(exact)
|
|
||||||
matches = [
|
|
||||||
c
|
|
||||||
for c in contacts
|
|
||||||
if lowered in _display(c).lower() or lowered in _label(c).lower()
|
|
||||||
]
|
|
||||||
if len(matches) == 1:
|
|
||||||
return matches[0]
|
|
||||||
if matches:
|
|
||||||
return _preferred(matches)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _preferred(candidates):
|
|
||||||
"""Prefer a healthy candidate (the others are likely stale duplicates)."""
|
|
||||||
healthy = [c for c in candidates if _is_healthy(c)]
|
|
||||||
return (healthy or candidates)[0]
|
|
||||||
|
|
||||||
|
|
||||||
def _find_by_id(contacts, contact_id):
|
|
||||||
wanted = str(contact_id or "")
|
|
||||||
for contact in contacts:
|
|
||||||
if _contact_id(contact) == wanted:
|
|
||||||
return contact
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _confidence(result, option_id) -> float:
|
|
||||||
prob = getattr(result, "prob", None)
|
|
||||||
if callable(prob):
|
|
||||||
try:
|
|
||||||
return float(prob(option_id))
|
|
||||||
except Exception:
|
|
||||||
return 0.0
|
|
||||||
probs = getattr(result, "probs", None)
|
|
||||||
if isinstance(probs, dict):
|
|
||||||
try:
|
|
||||||
return float(probs.get(option_id, 0.0))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return 0.0
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# message text
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _message_from_query(query: str) -> str:
|
|
||||||
"""Pull the literal message text out of the user's request, if stated."""
|
|
||||||
for pattern in _MESSAGE_PATTERNS:
|
|
||||||
match = re.search(pattern, query, flags=re.IGNORECASE | re.DOTALL)
|
|
||||||
if match:
|
|
||||||
text = match.group(1).strip().strip("\"'\u201c\u201d").strip()
|
|
||||||
if text:
|
|
||||||
return text
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def _llm_message_text(ctx, query: str):
|
|
||||||
"""Ask the LLM bridge to write the message body. Returns (text, reason)."""
|
|
||||||
base_url = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
|
||||||
if not base_url:
|
|
||||||
return None, "no llm bridge is configured"
|
|
||||||
token = str(ctx.config.get("llm_bridge_token", "") or "")
|
|
||||||
payload = {
|
|
||||||
"messages": [
|
|
||||||
{
|
|
||||||
"role": "system",
|
|
||||||
"content": (
|
|
||||||
"You write the exact text of a chat message a user wants to "
|
|
||||||
"send. Reply with the message text only: no quotes, no "
|
|
||||||
"preamble, no explanation."
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{"role": "user", "content": query},
|
|
||||||
],
|
|
||||||
"max_tokens": 256,
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
reply = _http_json(f"{base_url}/chat", token, payload)
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
return None, f"the llm bridge returned HTTP {exc.code} {_error_detail(exc)}"
|
|
||||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
|
||||||
return None, f"could not reach the llm bridge: {exc}"
|
|
||||||
if not isinstance(reply, dict):
|
|
||||||
return None, "the llm bridge returned an unexpected reply"
|
|
||||||
text = str(reply.get("text", "")).strip().strip('"').strip()
|
|
||||||
if not text:
|
|
||||||
return None, "the llm bridge returned no text"
|
|
||||||
return text, ""
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
# action
|
|
||||||
# --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request) -> ActionResult:
|
|
||||||
"""Send the requested message to the requested SimpleX contact."""
|
|
||||||
base_url = str(ctx.config["simplex_bridge_url"]).strip().rstrip("/")
|
|
||||||
token = str(ctx.config.get("simplex_bridge_token", "") or "")
|
|
||||||
default_ref = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
|
||||||
|
|
||||||
query = (request.text or "").strip()
|
|
||||||
user_input = str(getattr(request, "user_input", "") or "").strip()
|
|
||||||
decisions = []
|
|
||||||
|
|
||||||
# --- the bridge's real contact list ------------------------------------
|
|
||||||
try:
|
|
||||||
payload = _http_json(f"{base_url}/contacts", token)
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"the simplex bridge at {base_url} returned HTTP {exc.code} "
|
|
||||||
f"while listing contacts: {_error_detail(exc)}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"could not reach the simplex bridge at {base_url} to list "
|
|
||||||
f"contacts: {exc}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
|
|
||||||
raw_contacts = payload.get("contacts") if isinstance(payload, dict) else None
|
|
||||||
contacts = (
|
|
||||||
[c for c in raw_contacts if isinstance(c, dict)]
|
|
||||||
if isinstance(raw_contacts, list)
|
|
||||||
else []
|
|
||||||
)
|
|
||||||
|
|
||||||
# --- resolve the recipient --------------------------------------------
|
|
||||||
default_contact = _match_contact(contacts, default_ref)
|
|
||||||
named = [
|
|
||||||
c
|
|
||||||
for c in contacts
|
|
||||||
if _mentions(query, _display(c)) or _mentions(query, _label(c))
|
|
||||||
]
|
|
||||||
|
|
||||||
chosen = None
|
|
||||||
used_input_for_contact = False
|
|
||||||
|
|
||||||
if named or default_contact is not None:
|
|
||||||
candidates = list(named)
|
|
||||||
if default_contact is not None and all(
|
|
||||||
_contact_id(c) != _contact_id(default_contact) for c in candidates
|
|
||||||
):
|
|
||||||
candidates.append(default_contact)
|
|
||||||
|
|
||||||
healthy = [c for c in candidates if _is_healthy(c)]
|
|
||||||
if len(candidates) == 1:
|
|
||||||
chosen = candidates[0]
|
|
||||||
elif len(healthy) == 1:
|
|
||||||
# Exactly one candidate's connection is healthy (the rest are stale
|
|
||||||
# duplicates): pick it deterministically rather than coin-flipping.
|
|
||||||
chosen = healthy[0]
|
|
||||||
else:
|
|
||||||
decision = DecisionRequest(
|
|
||||||
state=query,
|
|
||||||
question="Which SimpleX contact should the message be sent to?",
|
|
||||||
options=[
|
|
||||||
Option(_contact_id(c), _label(c) or _contact_id(c))
|
|
||||||
for c in candidates
|
|
||||||
],
|
|
||||||
)
|
|
||||||
result = ctx.engine.call(decision)
|
|
||||||
decisions.append((decision, result))
|
|
||||||
selected_id = getattr(result, "selected", None)
|
|
||||||
selected = _find_by_id(candidates, selected_id)
|
|
||||||
if (
|
|
||||||
selected is not None
|
|
||||||
and _confidence(result, selected_id) >= CONFIDENCE_THRESHOLD
|
|
||||||
):
|
|
||||||
chosen = selected
|
|
||||||
elif default_contact is not None:
|
|
||||||
chosen = default_contact
|
|
||||||
else:
|
|
||||||
chosen = selected if selected is not None else candidates[0]
|
|
||||||
elif user_input:
|
|
||||||
# The human answered the question asked on the previous pass.
|
|
||||||
chosen = _match_contact(contacts, user_input) or {
|
|
||||||
"id": user_input,
|
|
||||||
"display_name": user_input,
|
|
||||||
}
|
|
||||||
used_input_for_contact = True
|
|
||||||
|
|
||||||
if chosen is None:
|
|
||||||
known = ", ".join(_display(c) for c in contacts if _display(c)) or "none"
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
"the request does not identify a SimpleX contact to message; "
|
|
||||||
f"the bridge knows these contacts: {known}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
needs_input="Which SimpleX contact should I message?",
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
recipient = _contact_id(chosen) or _display(chosen)
|
|
||||||
display_name = _display(chosen) or recipient
|
|
||||||
|
|
||||||
# --- resolve the message text -----------------------------------------
|
|
||||||
message_text = _message_from_query(query)
|
|
||||||
if not message_text and user_input and not used_input_for_contact:
|
|
||||||
message_text = user_input
|
|
||||||
if not message_text:
|
|
||||||
written, reason = _llm_message_text(ctx, query)
|
|
||||||
if written:
|
|
||||||
message_text = written
|
|
||||||
else:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"the request does not state what the message to "
|
|
||||||
f"{display_name} should say and no message text could be "
|
|
||||||
f"written ({reason})"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
needs_input=f"What should the message to {display_name} say?",
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
# --- send it through the bridge ---------------------------------------
|
|
||||||
try:
|
|
||||||
response = _http_json(
|
|
||||||
f"{base_url}/send", token, {"recipient": recipient, "text": message_text}
|
|
||||||
)
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"the simplex bridge refused to send to {display_name}: "
|
|
||||||
f"HTTP {exc.code} {_error_detail(exc)}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"could not reach the simplex bridge at {base_url} to send the "
|
|
||||||
f"message to {display_name}: {exc}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not isinstance(response, dict):
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"the simplex bridge returned an unexpected reply while sending "
|
|
||||||
f"to {display_name}"
|
|
||||||
),
|
|
||||||
new_state=request.text,
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
contact_id = str(response.get("contact_id") or recipient)
|
|
||||||
status = str(response.get("status") or "")
|
|
||||||
if not response.get("ok"):
|
|
||||||
detail = str(response.get("error") or "").strip() or json.dumps(response)
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"the message to {display_name} (contact {contact_id}) did not "
|
|
||||||
f"send (status {status or 'unknown'}: {detail})"
|
|
||||||
),
|
|
||||||
new_state=json.dumps(
|
|
||||||
{
|
|
||||||
"sent": False,
|
|
||||||
"contact_id": contact_id,
|
|
||||||
"display_name": display_name,
|
|
||||||
"status": status,
|
|
||||||
"error": detail,
|
|
||||||
"text": message_text,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
|
|
||||||
return ActionResult(
|
|
||||||
action_log=(
|
|
||||||
f"sent the message {message_text!r} to {display_name} "
|
|
||||||
f"(contact {contact_id}, status {status or 'ok'}) through the "
|
|
||||||
f"simplex bridge"
|
|
||||||
),
|
|
||||||
new_state=json.dumps(
|
|
||||||
{
|
|
||||||
"sent": True,
|
|
||||||
"contact_id": contact_id,
|
|
||||||
"display_name": display_name,
|
|
||||||
"status": status,
|
|
||||||
"text": message_text,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
decisions=decisions,
|
|
||||||
)
|
|
||||||
@@ -1,371 +0,0 @@
|
|||||||
"""Hermetic mechanics test for simplex.send_message.
|
|
||||||
|
|
||||||
Stands up loopback HTTP servers that imitate the simplex and llm bridges,
|
|
||||||
points the fixture config at them, and drives the body's real `act` so the
|
|
||||||
request construction, recipient/message resolution and error paths are
|
|
||||||
exercised without leaving the machine.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import threading
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
|
|
||||||
import skill
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# inline fixtures
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
CONTACTS = [
|
|
||||||
{"id": "c-pepper", "display_name": "pepper"},
|
|
||||||
{"id": "c-salt", "display_name": "salt"},
|
|
||||||
]
|
|
||||||
|
|
||||||
SIMPLEX_TOKEN = "s3cret-simplex-token"
|
|
||||||
LLM_TOKEN = "s3cret-llm-token"
|
|
||||||
LLM_REPLY = "a friendly hello"
|
|
||||||
|
|
||||||
|
|
||||||
class FakeRequest:
|
|
||||||
"""Minimal stand-in for the agent's Request object (test-only)."""
|
|
||||||
|
|
||||||
def __init__(self, text, user_input=""):
|
|
||||||
self.text = text
|
|
||||||
self.user_input = user_input
|
|
||||||
|
|
||||||
|
|
||||||
class FakeResult:
|
|
||||||
"""Stand-in for a decision result: exposes `selected` and `prob(id)`."""
|
|
||||||
|
|
||||||
def __init__(self, selected, confidence):
|
|
||||||
self.selected = selected
|
|
||||||
self._confidence = confidence
|
|
||||||
|
|
||||||
def prob(self, option_id):
|
|
||||||
return float(self._confidence) if option_id == self.selected else 0.0
|
|
||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
|
||||||
"""Test-only decision engine."""
|
|
||||||
|
|
||||||
def __init__(self, selected=None, confidence=1.0):
|
|
||||||
self.selected = selected
|
|
||||||
self.confidence = confidence
|
|
||||||
self.calls = []
|
|
||||||
|
|
||||||
def call(self, decision):
|
|
||||||
self.calls.append(decision)
|
|
||||||
selected = self.selected
|
|
||||||
if selected is None:
|
|
||||||
options = list(decision.options)
|
|
||||||
selected = options[0].id if options else None
|
|
||||||
return FakeResult(selected, self.confidence)
|
|
||||||
|
|
||||||
|
|
||||||
class _BaseHandler(BaseHTTPRequestHandler):
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _send_json(self, code, obj):
|
|
||||||
body = json.dumps(obj).encode("utf-8")
|
|
||||||
self.send_response(code)
|
|
||||||
self.send_header("Content-Type", "application/json")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def _read_body(self):
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
raw = self.rfile.read(length) if length else b""
|
|
||||||
if not raw:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
return json.loads(raw.decode("utf-8"))
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
class SimplexHandler(_BaseHandler):
|
|
||||||
contacts = []
|
|
||||||
send_error = False
|
|
||||||
seen = []
|
|
||||||
|
|
||||||
def do_GET(self):
|
|
||||||
SimplexHandler.seen.append(
|
|
||||||
{
|
|
||||||
"method": "GET",
|
|
||||||
"path": self.path,
|
|
||||||
"token": self.headers.get("X-Semif-Token"),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if self.path == "/contacts":
|
|
||||||
self._send_json(200, {"contacts": SimplexHandler.contacts})
|
|
||||||
else:
|
|
||||||
self._send_json(404, {"error": "not found"})
|
|
||||||
|
|
||||||
def do_POST(self):
|
|
||||||
body = self._read_body()
|
|
||||||
SimplexHandler.seen.append(
|
|
||||||
{
|
|
||||||
"method": "POST",
|
|
||||||
"path": self.path,
|
|
||||||
"token": self.headers.get("X-Semif-Token"),
|
|
||||||
"body": body,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if self.path != "/send":
|
|
||||||
self._send_json(404, {"error": "not found"})
|
|
||||||
return
|
|
||||||
if SimplexHandler.send_error:
|
|
||||||
self._send_json(400, {"error": "unknown recipient"})
|
|
||||||
return
|
|
||||||
recipient = (body or {}).get("recipient", "")
|
|
||||||
self._send_json(200, {"ok": True, "contact_id": recipient})
|
|
||||||
|
|
||||||
|
|
||||||
class LlmHandler(_BaseHandler):
|
|
||||||
reply = LLM_REPLY
|
|
||||||
seen = []
|
|
||||||
|
|
||||||
def do_POST(self):
|
|
||||||
body = self._read_body()
|
|
||||||
LlmHandler.seen.append(
|
|
||||||
{
|
|
||||||
"path": self.path,
|
|
||||||
"token": self.headers.get("X-Semif-Token"),
|
|
||||||
"body": body,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if self.path == "/chat":
|
|
||||||
self._send_json(200, {"text": LlmHandler.reply})
|
|
||||||
else:
|
|
||||||
self._send_json(404, {"error": "not found"})
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# helpers
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def start_server(handler):
|
|
||||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
return server
|
|
||||||
|
|
||||||
|
|
||||||
def base_url(server):
|
|
||||||
return f"http://127.0.0.1:{server.server_address[1]}"
|
|
||||||
|
|
||||||
|
|
||||||
def reset(contacts=None, send_error=False):
|
|
||||||
SimplexHandler.contacts = [dict(c) for c in (contacts if contacts is not None else CONTACTS)]
|
|
||||||
SimplexHandler.send_error = send_error
|
|
||||||
SimplexHandler.seen = []
|
|
||||||
LlmHandler.seen = []
|
|
||||||
LlmHandler.reply = LLM_REPLY
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# tests
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def test_happy_path():
|
|
||||||
"""A named contact plus an explicit message: GET /contacts then POST /send."""
|
|
||||||
reset()
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={
|
|
||||||
"simplex_bridge_url": base_url(server),
|
|
||||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
|
||||||
)
|
|
||||||
|
|
||||||
assert result.action_log, "act must log what it did"
|
|
||||||
assert not result.needs_input, result.action_log
|
|
||||||
assert "sent" in result.action_log.lower(), result.action_log
|
|
||||||
|
|
||||||
gets = [r for r in SimplexHandler.seen if r["method"] == "GET"]
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert any(r["path"] == "/contacts" for r in gets), SimplexHandler.seen
|
|
||||||
assert len(posts) == 1, SimplexHandler.seen
|
|
||||||
assert posts[0]["path"] == "/send", SimplexHandler.seen
|
|
||||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": "hey"}, posts[0]
|
|
||||||
|
|
||||||
for seen in SimplexHandler.seen:
|
|
||||||
assert seen["token"] == SIMPLEX_TOKEN, seen
|
|
||||||
|
|
||||||
state = json.loads(result.new_state)
|
|
||||||
assert state["sent"] is True, state
|
|
||||||
assert state["contact_id"] == "c-pepper", state
|
|
||||||
assert state["text"] == "hey", state
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_ambiguous_contact_uses_engine():
|
|
||||||
"""Two named contacts: the body must ask the engine and honour the pick."""
|
|
||||||
reset()
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
try:
|
|
||||||
engine = FakeEngine(selected="c-salt", confidence=0.9)
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=engine,
|
|
||||||
config={"simplex_bridge_url": base_url(server)},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, FakeRequest("send a message to pepper and salt saying hi")
|
|
||||||
)
|
|
||||||
|
|
||||||
assert not result.needs_input, result.action_log
|
|
||||||
assert len(engine.calls) == 1, engine.calls
|
|
||||||
option_ids = [o.id for o in engine.calls[0].options]
|
|
||||||
assert set(option_ids) == {"c-pepper", "c-salt"}, option_ids
|
|
||||||
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert len(posts) == 1, SimplexHandler.seen
|
|
||||||
assert posts[0]["body"] == {"recipient": "c-salt", "text": "hi"}, posts[0]
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_message_written_by_llm_bridge():
|
|
||||||
"""No literal text: the body must ask the llm bridge, then send its reply."""
|
|
||||||
reset()
|
|
||||||
simplex = start_server(SimplexHandler)
|
|
||||||
llm = start_server(LlmHandler)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={
|
|
||||||
"simplex_bridge_url": base_url(simplex),
|
|
||||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
|
||||||
"llm_bridge_url": base_url(llm),
|
|
||||||
"llm_bridge_token": LLM_TOKEN,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
|
||||||
|
|
||||||
assert not result.needs_input, result.action_log
|
|
||||||
assert len(LlmHandler.seen) == 1, LlmHandler.seen
|
|
||||||
chat = LlmHandler.seen[0]
|
|
||||||
assert chat["path"] == "/chat", chat
|
|
||||||
assert chat["token"] == LLM_TOKEN, chat
|
|
||||||
assert chat["body"]["messages"], chat
|
|
||||||
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert len(posts) == 1, SimplexHandler.seen
|
|
||||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": LLM_REPLY}, posts[0]
|
|
||||||
finally:
|
|
||||||
simplex.shutdown()
|
|
||||||
simplex.server_close()
|
|
||||||
llm.shutdown()
|
|
||||||
llm.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_text_without_llm_asks():
|
|
||||||
"""A clear recipient but no message text and no llm bridge: ask the user."""
|
|
||||||
reset()
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"simplex_bridge_url": base_url(server)},
|
|
||||||
)
|
|
||||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
|
||||||
|
|
||||||
assert result.needs_input, result.action_log
|
|
||||||
assert "say" in result.needs_input.lower(), result.needs_input
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert posts == [], SimplexHandler.seen
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_contact_asks():
|
|
||||||
"""No matching contact in the bridge list: ask which contact to message."""
|
|
||||||
reset(contacts=[])
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"simplex_bridge_url": base_url(server)},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
|
||||||
)
|
|
||||||
|
|
||||||
assert result.needs_input, result.action_log
|
|
||||||
assert "contact" in result.needs_input.lower(), result.needs_input
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert posts == [], SimplexHandler.seen
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_send_refused_is_reported():
|
|
||||||
"""A 400 from POST /send must be surfaced, not silently swallowed."""
|
|
||||||
reset(send_error=True)
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
try:
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"simplex_bridge_url": base_url(server)},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
|
||||||
)
|
|
||||||
|
|
||||||
assert not result.needs_input, result.action_log
|
|
||||||
assert "refused" in result.action_log.lower(), result.action_log
|
|
||||||
assert "400" in result.action_log, result.action_log
|
|
||||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
|
||||||
assert len(posts) == 1, SimplexHandler.seen
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unreachable_bridge_is_reported():
|
|
||||||
"""A dead bridge must produce a plain failure log, not an exception."""
|
|
||||||
reset()
|
|
||||||
server = start_server(SimplexHandler)
|
|
||||||
url = base_url(server)
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
|
|
||||||
ctx = ActionContext(
|
|
||||||
engine=FakeEngine(),
|
|
||||||
config={"simplex_bridge_url": url},
|
|
||||||
)
|
|
||||||
result = skill.act(
|
|
||||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
|
||||||
)
|
|
||||||
assert not result.needs_input, result.action_log
|
|
||||||
assert "could not reach" in result.action_log.lower(), result.action_log
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
test_happy_path()
|
|
||||||
test_ambiguous_contact_uses_engine()
|
|
||||||
test_message_written_by_llm_bridge()
|
|
||||||
test_missing_text_without_llm_asks()
|
|
||||||
test_unknown_contact_asks()
|
|
||||||
test_send_refused_is_reported()
|
|
||||||
test_unreachable_bridge_is_reported()
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Report today's date."
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
"""Report today's date.
|
|
||||||
|
|
||||||
Real local compute: reads the host clock and formats the calendar date in the
|
|
||||||
user's timezone — the top-level `timezone` config value (an IANA name) when set,
|
|
||||||
otherwise the host's local timezone. No external service.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
from semif_agent.timers import local_now
|
|
||||||
|
|
||||||
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
|
|
||||||
|
|
||||||
CONTRACT = {}
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
today = local_now(ctx.config).date()
|
|
||||||
message = f"Today is {today.strftime('%A, %B')} {today.day}, {today.year}."
|
|
||||||
return ActionResult(action_log=message, new_state=message)
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
"""Hermetic mechanics test for time.date.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network, no config.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ctx = ActionContext(engine=None, config={})
|
|
||||||
action = skill.act(ctx, Request("what is today's date?"))
|
|
||||||
assert action.new_state, "act must report the date"
|
|
||||||
assert "Today is" in action.action_log, action.action_log
|
|
||||||
assert action.needs_input is None
|
|
||||||
print(action.action_log)
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Report the current local time of day."
|
|
||||||
}
|
|
||||||
@@ -1,23 +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 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):
|
|
||||||
now = local_now(ctx.config)
|
|
||||||
message = f"It is {now.strftime('%I:%M %p').lstrip('0')}."
|
|
||||||
return ActionResult(action_log=message, new_state=message)
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
"""Hermetic mechanics test for time.now.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network, no config.
|
|
||||||
This proves the body reads the host clock and reports a real local time; it
|
|
||||||
does NOT prove anything about the host's timezone correctness.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ctx = ActionContext(engine=None, config={})
|
|
||||||
action = skill.act(ctx, Request("what time is it?"))
|
|
||||||
assert action.new_state, "act must report the time"
|
|
||||||
assert "It is" in action.action_log, action.action_log
|
|
||||||
assert action.needs_input is None
|
|
||||||
print(action.action_log)
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Set an alarm for a specific time of day that notifies when it goes off."
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
"""Set an alarm for a specific time of day that notifies when it goes off.
|
|
||||||
|
|
||||||
Real local compute: parses a wall-clock time out of the request and schedules it
|
|
||||||
on the in-process timer service (`ctx.timers`). The wall-clock time is read in
|
|
||||||
the user's timezone — the top-level `timezone` config value when set, otherwise
|
|
||||||
the host's local timezone. A time already past rolls to the next day. When it
|
|
||||||
fires, the front end that set it notifies the user.
|
|
||||||
|
|
||||||
If no time can be parsed the body pauses and asks for one, stashing the answer
|
|
||||||
in `request.meta` so the single-phase `act` re-run does not ask again.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import re
|
|
||||||
from datetime import datetime, time, timedelta
|
|
||||||
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
from semif_agent.timers import local_now
|
|
||||||
|
|
||||||
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
|
|
||||||
|
|
||||||
CONTRACT = {}
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_time(text, now):
|
|
||||||
"""The next datetime matching a wall-clock time in `text`, or None."""
|
|
||||||
text = text or ""
|
|
||||||
parsed = None
|
|
||||||
if re.search(r"\bnoon\b", text, re.I):
|
|
||||||
parsed = time(12, 0)
|
|
||||||
elif re.search(r"\bmidnight\b", text, re.I):
|
|
||||||
parsed = time(0, 0)
|
|
||||||
else:
|
|
||||||
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
|
|
||||||
if match:
|
|
||||||
hour = int(match.group(1)) % 12
|
|
||||||
minute = int(match.group(2) or 0)
|
|
||||||
if match.group(3).lower() == "p":
|
|
||||||
hour += 12
|
|
||||||
if hour < 24 and minute < 60:
|
|
||||||
parsed = time(hour, minute)
|
|
||||||
else:
|
|
||||||
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
|
|
||||||
if match:
|
|
||||||
hour, minute = int(match.group(1)), int(match.group(2))
|
|
||||||
if hour < 24 and minute < 60:
|
|
||||||
parsed = time(hour, minute)
|
|
||||||
else:
|
|
||||||
# A bare hour is only accepted when unambiguous (24-hour).
|
|
||||||
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
|
|
||||||
if match and 13 <= int(match.group(1)) < 24:
|
|
||||||
parsed = time(int(match.group(1)), 0)
|
|
||||||
if parsed is None:
|
|
||||||
return None
|
|
||||||
candidate = datetime.combine(now.date(), parsed, tzinfo=now.tzinfo)
|
|
||||||
if candidate <= now:
|
|
||||||
candidate += timedelta(days=1)
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
if request.user_input is not None and request.meta.get("alarm_awaiting"):
|
|
||||||
if request.user_input.strip():
|
|
||||||
request.meta["alarm_time_text"] = request.user_input.strip()
|
|
||||||
request.meta.pop("alarm_awaiting", None)
|
|
||||||
|
|
||||||
text = request.meta.get("alarm_time_text") or request.text
|
|
||||||
now = local_now(ctx.config)
|
|
||||||
when = _parse_time(text, now)
|
|
||||||
if when is None:
|
|
||||||
request.meta["alarm_awaiting"] = True
|
|
||||||
return ActionResult(
|
|
||||||
action_log="waiting for a time",
|
|
||||||
new_state=request.text,
|
|
||||||
needs_input="What time should the alarm go off? (e.g. '5pm')",
|
|
||||||
)
|
|
||||||
if ctx.timers is None:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="no timer service is available in this front end",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
|
|
||||||
label = when.strftime("%H:%M")
|
|
||||||
ctx.timers.set_alarm(when, label, run_id=request.id, source=request.source)
|
|
||||||
message = f"Alarm set for {when.strftime('%H:%M')} on {when.strftime('%A')}."
|
|
||||||
return ActionResult(action_log=message, new_state=message)
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"""Hermetic mechanics test for time.set_alarm.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network, no real
|
|
||||||
sleeping: a fake timer service records what the body schedules. This proves the
|
|
||||||
body parses wall-clock times (am/pm, 24-hour, noon/midnight), rolls a past time
|
|
||||||
to the next day, and pauses for input when no time is present.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
class FakeTimers:
|
|
||||||
def __init__(self):
|
|
||||||
self.alarms = []
|
|
||||||
|
|
||||||
def set_alarm(self, at, label, run_id="", source=""):
|
|
||||||
self.alarms.append((at, label))
|
|
||||||
return SimpleNamespace(id="a1", due_at=at.timestamp())
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_with_timers():
|
|
||||||
timers = FakeTimers()
|
|
||||||
return ActionContext(engine=None, config={}, timers=timers), timers
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
now = datetime.now().astimezone()
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
action = skill.act(ctx, Request("set an alarm for 5pm"))
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert len(timers.alarms) == 1, timers.alarms
|
|
||||||
at, label = timers.alarms[0]
|
|
||||||
assert (at.hour, at.minute) == (17, 0), at
|
|
||||||
assert label == "17:00"
|
|
||||||
assert at > now, "an alarm must be in the future"
|
|
||||||
assert at <= now + timedelta(days=1)
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
skill.act(ctx, Request("set an alarm for 17:30"))
|
|
||||||
assert timers.alarms[0][0].strftime("%H:%M") == "17:30", timers.alarms
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
skill.act(ctx, Request("wake me at noon"))
|
|
||||||
assert timers.alarms[0][0].strftime("%H:%M") == "12:00", timers.alarms
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
skill.act(ctx, Request("alarm at midnight"))
|
|
||||||
assert timers.alarms[0][0].strftime("%H:%M") == "00:00", timers.alarms
|
|
||||||
|
|
||||||
# An unparseable request pauses, then the answer is used on the re-run.
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
request = Request("set an alarm")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input, "an alarm with no time must ask for one"
|
|
||||||
assert timers.alarms == []
|
|
||||||
request.user_input = "6:15am"
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input is None
|
|
||||||
assert timers.alarms[0][0].strftime("%H:%M") == "06:15", timers.alarms
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
# No timer service fails honestly.
|
|
||||||
ctx = ActionContext(engine=None, config={}, timers=None)
|
|
||||||
action = skill.act(ctx, Request("set an alarm for 5pm"))
|
|
||||||
assert "no timer service" in action.action_log, action.action_log
|
|
||||||
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"description": "Set a countdown timer that notifies when it finishes."
|
|
||||||
}
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
"""Set a countdown timer that notifies the user when it finishes.
|
|
||||||
|
|
||||||
Real local compute: parses a duration out of the request (digits or words) and
|
|
||||||
schedules it on the in-process timer service (`ctx.timers`). When it fires, the
|
|
||||||
front end that set it notifies the user — the REPL prints it, the gateway sends
|
|
||||||
it back to the originating chat, the dashboard shows it. The due time is shown
|
|
||||||
in the user's timezone (the top-level `timezone` config value, else host local).
|
|
||||||
A timer lives in the process that set it and does not survive a restart.
|
|
||||||
|
|
||||||
If no duration can be parsed the body pauses and asks for one, stashing the
|
|
||||||
answer in `request.meta` so the single-phase `act` re-run does not ask again.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from semif_agent.skills import ActionResult
|
|
||||||
from semif_agent.timers import format_duration
|
|
||||||
|
|
||||||
INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []}
|
|
||||||
|
|
||||||
CONTRACT = {}
|
|
||||||
|
|
||||||
_DURATION_WORDS = {
|
|
||||||
"a": 1,
|
|
||||||
"an": 1,
|
|
||||||
"one": 1,
|
|
||||||
"two": 2,
|
|
||||||
"three": 3,
|
|
||||||
"four": 4,
|
|
||||||
"five": 5,
|
|
||||||
"six": 6,
|
|
||||||
"seven": 7,
|
|
||||||
"eight": 8,
|
|
||||||
"nine": 9,
|
|
||||||
"ten": 10,
|
|
||||||
"eleven": 11,
|
|
||||||
"twelve": 12,
|
|
||||||
"fifteen": 15,
|
|
||||||
"twenty": 20,
|
|
||||||
"thirty": 30,
|
|
||||||
"forty": 40,
|
|
||||||
"fortyfive": 45,
|
|
||||||
"sixty": 60,
|
|
||||||
"ninety": 90,
|
|
||||||
}
|
|
||||||
|
|
||||||
_UNIT_SECONDS = {
|
|
||||||
"second": 1,
|
|
||||||
"seconds": 1,
|
|
||||||
"sec": 1,
|
|
||||||
"secs": 1,
|
|
||||||
"s": 1,
|
|
||||||
"minute": 60,
|
|
||||||
"minutes": 60,
|
|
||||||
"min": 60,
|
|
||||||
"mins": 60,
|
|
||||||
"m": 60,
|
|
||||||
"hour": 3600,
|
|
||||||
"hours": 3600,
|
|
||||||
"hr": 3600,
|
|
||||||
"hrs": 3600,
|
|
||||||
"h": 3600,
|
|
||||||
}
|
|
||||||
|
|
||||||
_DIGIT_DURATION = re.compile(
|
|
||||||
r"\b(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b",
|
|
||||||
re.I,
|
|
||||||
)
|
|
||||||
_WORD_DURATION = re.compile(
|
|
||||||
r"\b(" + "|".join(sorted(_DURATION_WORDS, key=len, reverse=True)) + r")\s+"
|
|
||||||
r"(seconds?|secs?|minutes?|mins?|hours?|hrs?)\b",
|
|
||||||
re.I,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_duration(text):
|
|
||||||
"""Seconds for a duration phrase, or None when none is present."""
|
|
||||||
text = text or ""
|
|
||||||
if re.search(r"\bhalf\s+an?\s+hour\b", text, re.I):
|
|
||||||
return 1800
|
|
||||||
if re.search(r"\bquarter\s+(?:of\s+)?an?\s+hour\b", text, re.I):
|
|
||||||
return 900
|
|
||||||
if re.search(r"\ba\s+couple\s+of\s+(?:minutes?|mins?)\b", text, re.I):
|
|
||||||
return 120
|
|
||||||
if re.search(r"\ba\s+few\s+(?:minutes?|mins?)\b", text, re.I):
|
|
||||||
return 180
|
|
||||||
match = _DIGIT_DURATION.search(text)
|
|
||||||
if match:
|
|
||||||
unit = _UNIT_SECONDS.get(match.group(2).lower())
|
|
||||||
if unit:
|
|
||||||
return int(round(float(match.group(1)) * unit))
|
|
||||||
match = _WORD_DURATION.search(text)
|
|
||||||
if match:
|
|
||||||
value = _DURATION_WORDS.get(match.group(1).lower())
|
|
||||||
unit = _UNIT_SECONDS.get(match.group(2).lower())
|
|
||||||
if value and unit:
|
|
||||||
return value * unit
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
|
||||||
if request.user_input is not None and request.meta.get("timer_awaiting"):
|
|
||||||
if request.user_input.strip():
|
|
||||||
request.meta["timer_duration_text"] = request.user_input.strip()
|
|
||||||
request.meta.pop("timer_awaiting", None)
|
|
||||||
|
|
||||||
text = request.meta.get("timer_duration_text") or request.text
|
|
||||||
seconds = _parse_duration(text)
|
|
||||||
if seconds is None:
|
|
||||||
request.meta["timer_awaiting"] = True
|
|
||||||
return ActionResult(
|
|
||||||
action_log="waiting for a duration",
|
|
||||||
new_state=request.text,
|
|
||||||
needs_input="How long should the timer run? (e.g. '5 minutes')",
|
|
||||||
)
|
|
||||||
if ctx.timers is None:
|
|
||||||
return ActionResult(
|
|
||||||
action_log="no timer service is available in this front end",
|
|
||||||
new_state=request.text,
|
|
||||||
)
|
|
||||||
|
|
||||||
label = format_duration(seconds)
|
|
||||||
timer = ctx.timers.set_timer(seconds, label, run_id=request.id, source=request.source)
|
|
||||||
due = timer.due_datetime().strftime("%H:%M")
|
|
||||||
message = f"Timer set for {label}; it will fire at {due}."
|
|
||||||
return ActionResult(action_log=message, new_state=message)
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
"""Hermetic mechanics test for time.set_timer.
|
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network, no real
|
|
||||||
sleeping: a fake timer service records what the body schedules. This proves the
|
|
||||||
body parses durations (digits and words) and schedules the right number of
|
|
||||||
seconds, and that an unparseable request pauses for input; it does NOT prove
|
|
||||||
the in-process timer actually fires (tests/test_timers.py covers the service).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from datetime import datetime
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
|
||||||
from semif_agent.skills import ActionContext
|
|
||||||
|
|
||||||
import skill
|
|
||||||
|
|
||||||
|
|
||||||
class FakeTimer:
|
|
||||||
def __init__(self, seconds):
|
|
||||||
self.due_at = time.time() + seconds
|
|
||||||
|
|
||||||
def due_datetime(self):
|
|
||||||
return datetime.fromtimestamp(self.due_at).astimezone()
|
|
||||||
|
|
||||||
|
|
||||||
class FakeTimers:
|
|
||||||
def __init__(self):
|
|
||||||
self.timers = []
|
|
||||||
|
|
||||||
def set_timer(self, seconds, label, run_id="", source=""):
|
|
||||||
self.timers.append((seconds, label))
|
|
||||||
return FakeTimer(seconds)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_with_timers():
|
|
||||||
timers = FakeTimers()
|
|
||||||
return ActionContext(engine=None, config={}, timers=timers), timers
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
action = skill.act(ctx, Request("please set a timer for five minutes"))
|
|
||||||
assert action.needs_input is None, action.needs_input
|
|
||||||
assert timers.timers == [(300, "5 minutes")], timers.timers
|
|
||||||
assert "300" not in action.action_log and "5 minutes" in action.action_log
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
action = skill.act(ctx, Request("set a timer for 90 seconds"))
|
|
||||||
assert timers.timers == [(90, "1 minute 30 seconds")], timers.timers
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
skill.act(ctx, Request("timer for 1.5 hours"))
|
|
||||||
assert timers.timers == [(5400, "1 hour 30 minutes")], timers.timers
|
|
||||||
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
skill.act(ctx, Request("set a timer for half an hour"))
|
|
||||||
assert timers.timers == [(1800, "30 minutes")], timers.timers
|
|
||||||
|
|
||||||
# An unparseable request pauses, then the answer is used on the re-run.
|
|
||||||
ctx, timers = ctx_with_timers()
|
|
||||||
request = Request("set a timer")
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input, "a timer with no duration must ask for one"
|
|
||||||
assert timers.timers == []
|
|
||||||
request.user_input = "ten minutes"
|
|
||||||
action = skill.act(ctx, request)
|
|
||||||
assert action.needs_input is None
|
|
||||||
assert timers.timers == [(600, "10 minutes")], timers.timers
|
|
||||||
print(action.action_log)
|
|
||||||
|
|
||||||
# No timer service (e.g. a front end without one) fails honestly.
|
|
||||||
ctx = ActionContext(engine=None, config={}, timers=None)
|
|
||||||
action = skill.act(ctx, Request("set a timer for 5 minutes"))
|
|
||||||
assert action.needs_input is None
|
|
||||||
assert "no timer service" in action.action_log, action.action_log
|
|
||||||
|
|
||||||
print("ok")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except AssertionError as exc:
|
|
||||||
print(f"FAILED: {exc}")
|
|
||||||
sys.exit(1)
|
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
"""Third-party API bridges: a secure local layer between skills and services.
|
"""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
|
A **bridge service** is a standalone process that exposes one third-party system
|
||||||
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to
|
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook, a real
|
||||||
codegen-authored skill bodies
|
web browser via Playwright) to codegen-authored skill bodies over a local,
|
||||||
over a local, token-guarded HTTP API. It exists so a generated body never speaks
|
token-guarded HTTP API. A skill body can call a plain HTTP API directly; a
|
||||||
a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
|
bridge is a deliberate choice for a system that needs state (especially auth
|
||||||
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
|
state), a native or heavy protocol, or one sanitized surface. When a bridge
|
||||||
surface instead, and the bridge owns the messy integration details and
|
fronts a service, a generated body never speaks that system's native protocol
|
||||||
credentials.
|
(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:
|
Two boundaries matter:
|
||||||
|
|
||||||
@@ -16,21 +24,26 @@ Two boundaries matter:
|
|||||||
own processes (`python -m semif_agent.cli bridge`) against their own service
|
own processes (`python -m semif_agent.cli bridge`) against their own service
|
||||||
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
|
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
|
||||||
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
|
- **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
|
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,
|
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
|
config-var docs, and its endpoints with request/response/error shapes. CODEGEN.md
|
||||||
and TESTGEN.md carry only the generic pattern.
|
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 .inbox import MessagingInbox
|
||||||
from .registry import (
|
from .registry import (
|
||||||
build_bridge,
|
build_bridge,
|
||||||
derived_config_vars,
|
derived_config_vars,
|
||||||
describe_bridges,
|
describe_bridges,
|
||||||
|
discover_bridge_classes,
|
||||||
known_infos,
|
known_infos,
|
||||||
|
load_pack_bridge_class,
|
||||||
|
load_pack_bridge_module,
|
||||||
|
load_pack_bridge_package,
|
||||||
run_bridges,
|
run_bridges,
|
||||||
|
set_bridge_packs,
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -38,8 +51,14 @@ __all__ = [
|
|||||||
"BridgeService",
|
"BridgeService",
|
||||||
"MessagingInbox",
|
"MessagingInbox",
|
||||||
"build_bridge",
|
"build_bridge",
|
||||||
|
"checkout_root",
|
||||||
"derived_config_vars",
|
"derived_config_vars",
|
||||||
"describe_bridges",
|
"describe_bridges",
|
||||||
|
"discover_bridge_classes",
|
||||||
"known_infos",
|
"known_infos",
|
||||||
|
"load_pack_bridge_class",
|
||||||
|
"load_pack_bridge_module",
|
||||||
|
"load_pack_bridge_package",
|
||||||
"run_bridges",
|
"run_bridges",
|
||||||
|
"set_bridge_packs",
|
||||||
]
|
]
|
||||||
@@ -14,9 +14,20 @@ import threading
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
from urllib.parse import parse_qs, urlparse
|
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)
|
@dataclass(frozen=True)
|
||||||
class BridgeInfo:
|
class BridgeInfo:
|
||||||
"""Static, prompt-safe metadata about a bridge.
|
"""Static, prompt-safe metadata about a bridge.
|
||||||
@@ -60,6 +71,25 @@ class BridgeService(ABC):
|
|||||||
self._server: ThreadingHTTPServer | None = None
|
self._server: ThreadingHTTPServer | None = None
|
||||||
self._thread: threading.Thread | 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 ----
|
# ---- lifecycle ----
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
|
|||||||
@@ -60,6 +60,12 @@ class LLMBridge(BridgeService):
|
|||||||
#: the bridge is built without one; calls then report 502, never a guess.
|
#: the bridge is built without one; calls then report 502, never a guess.
|
||||||
self.client = client
|
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 ----
|
# ---- lifecycle ----
|
||||||
|
|
||||||
def check_requirements(self) -> tuple[bool, str | None]:
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
|||||||
@@ -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 nextcloud 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
@@ -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 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user