bridges: standalone third-party API bridges; isolate the command gateway
Split messaging UX (invite links, read, send) out of the command gateway into a
new `semif_agent.bridges` layer. Each bridge is its own process (`cli bridge`)
against its own service daemon/profile; the SimpleX bridge owns a second
simplex-chat daemon and buffers every inbound DM, so a message sent to the
connect-link address shows up in `simplex.next_message`.
- new: bridges/{base,inbox,registry,simplex}.py + neutral semif_agent/simplex_ws.py
- gateway: delete bridge.py; drop address/observer/pull-mode from the command path
- codegen: inject the bridge catalog (describe_bridges) into body + elicitation prompts
- seeds: repoint simplex.next_message/connect_link to top-level `simplex_bridge_url`
- config/bootstrap: new top-level `bridges` block + `simplex_bridge_url`; render
semif-simplex-forward + semif-bridge units; gateway config loses bridge/inbox
- docs: AGENTS.md gateway isolation is non-negotiable
This commit is contained in:
1 parent
d46fbdca19
commit
ddc5cb66c8
31 files changed
+1702
-1088
No files matched your search
@@ -47,11 +47,20 @@ The design spec is `IDEA.md`. The key point: **semantic ifs, not text
|
|||||||
generation, do the routing.** SemIf returns probabilities conditional on the
|
generation, do the routing.** SemIf returns probabilities conditional on the
|
||||||
supplied options; an LLM is used only for generation and self-assessment.
|
supplied options; an LLM is used only for generation and self-assessment.
|
||||||
|
|
||||||
|
**Gateway isolation is non-negotiable.** The command gateway (`gateway/`) exists
|
||||||
|
only to take commands and send replies. Everything that is messaging *UX* —
|
||||||
|
invite links, reading a contact's messages, composing/sending on the user's
|
||||||
|
behalf — belongs to the standalone bridge services (`semif_agent.bridges`),
|
||||||
|
which run as their own processes against their own service daemons/profiles.
|
||||||
|
Never widen the gateway's surface for convenience: a new read/send/address
|
||||||
|
capability is a new bridge, not a gateway feature.
|
||||||
|
|
||||||
## Architecture map
|
## Architecture map
|
||||||
|
|
||||||
```
|
```
|
||||||
cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
||||||
dashboard
|
dashboard, gateway (command intake), bridge (standalone
|
||||||
|
third-party API bridges)
|
||||||
scheduler.py gate (handle/ignore; state carries the user's expectation +
|
scheduler.py gate (handle/ignore; state carries the user's expectation +
|
||||||
the available skills, so lookups are not read as small talk)
|
the available skills, so lookups are not read as small talk)
|
||||||
-> choice(tau) -> score -> queue; preempt + requeue;
|
-> choice(tau) -> score -> queue; preempt + requeue;
|
||||||
@@ -96,7 +105,9 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
|
|||||||
data from the runner via ctx.config, never embedded; bodies
|
data from the runner via ctx.config, never embedded; bodies
|
||||||
declare INTEGRATION service/transport/config_vars);
|
declare INTEGRATION service/transport/config_vars);
|
||||||
parse/validate (compile + predict/act) + parse_integration /
|
parse/validate (compile + predict/act) + parse_integration /
|
||||||
infer_integration / integration_findings; elicitation questions
|
infer_integration / integration_findings; the bridge catalog
|
||||||
|
(describe_bridges()) is injected into the body + elicitation
|
||||||
|
prompts; elicitation questions
|
||||||
+ integration hint; TESTGEN.md drives two shared-context calls
|
+ integration hint; TESTGEN.md drives two shared-context calls
|
||||||
producing contract.json then skill.test.py (hermetic mechanics
|
producing contract.json then skill.test.py (hermetic mechanics
|
||||||
test: inline fixtures, loopback http.server for HTTP bodies, no
|
test: inline fixtures, loopback http.server for HTTP bodies, no
|
||||||
@@ -114,22 +125,32 @@ decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult,
|
|||||||
dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/
|
dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/
|
||||||
questions/repairs + POST submit/answer/questions/repair/restart/
|
questions/repairs + POST submit/answer/questions/repair/restart/
|
||||||
relabel); static/ frontend served at /
|
relabel); static/ frontend served at /
|
||||||
gateway/ messenger intake/reply. base.py: GatewayAdapter contract +
|
gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
|
||||||
Inbound/OutboundMessage. service.py: GatewayService maps chats
|
GatewayAdapter contract + Inbound/OutboundMessage. service.py:
|
||||||
onto the single-slot scheduler (submit_request, owner maps,
|
GatewayService maps chats onto the single-slot scheduler
|
||||||
pending-run ownership, queue drain, authoring questions/repairs
|
(submit_request, owner maps, pending-run ownership, queue
|
||||||
routed back to the origin chat). simplex.py: SimplexAdapter —
|
drain, authoring questions/repairs routed back to the origin
|
||||||
local simplex-chat daemon over its JSON WebSocket API
|
chat). simplex.py: SimplexAdapter — command simplex-chat daemon
|
||||||
(lazy `websockets`, allowlist, batching, structured `/_send`,
|
over its JSON WebSocket API (lazy `websockets`, allowlist,
|
||||||
corrId→Future request path for `/_show_address`/`/_address`).
|
batching, structured `/_send`). Run with `python -m
|
||||||
bridge.py: MessagingBridge — a localhost stdlib HTTP API the
|
|
||||||
gateway serves so skills can send/read SimpleX messages without
|
|
||||||
touching the daemon (`/health`, `/contacts`, `/inbox`,
|
|
||||||
`/inbox/next`, `/address`, `/send`); owns the read cursor
|
|
||||||
(bounded inbox), reuses the adapter's outbound queue, and takes
|
|
||||||
an injected `address_provider` for the connect link. Run with `python -m
|
|
||||||
semif_agent.cli gateway [--dashboard]`; config under
|
semif_agent.cli gateway [--dashboard]`; config under
|
||||||
`gateway.simplex` in config.json
|
`gateway.simplex`. The gateway MUST NOT read history, show/create
|
||||||
|
invite links, or compose messages — see "gateway isolation"
|
||||||
|
below.
|
||||||
|
bridges/ standalone third-party API bridges (SimpleX first). base.py:
|
||||||
|
BridgeInfo + BridgeService (shared localhost JSON HTTP layer,
|
||||||
|
`X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO +
|
||||||
|
contacts, bridge-owned read cursor). simplex.py: SimplexBridge —
|
||||||
|
owns its OWN simplex-chat daemon/profile (separate from the
|
||||||
|
gateway's), buffers every inbound DM, serves invite-link/read/
|
||||||
|
send. registry.py: CATALOG, describe_bridges() (catalog injected
|
||||||
|
into the codegen prompts), run_bridges(). Run with `python -m
|
||||||
|
semif_agent.cli bridge [--name NAME]`; config under `bridges`.
|
||||||
|
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
|
||||||
|
adapter and the bridge (parse direct text across v7 shapes,
|
||||||
|
structured `/_send`, corrId→Future round-trips, contact-address
|
||||||
|
`/_show_address`/`/_address`, contact-request accept). Knows
|
||||||
|
nothing about the scheduler or either front end.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Run / verify
|
## Run / verify
|
||||||
@@ -168,6 +189,19 @@ Machine split (Sep 2026): **guppy** hosts the remote **codegen** model (the
|
|||||||
SemIf engine + deps) and runs its **own local ollama** serving the small
|
SemIf engine + deps) and runs its **own local ollama** serving the small
|
||||||
self-assessment model (`qwen3.5:4b`). Only codegen traffic travels to guppy.
|
self-assessment model (`qwen3.5:4b`). Only codegen traffic travels to guppy.
|
||||||
Provision jarvis with `scripts/bootstrap.sh` (see "### jarvis (staging)").
|
Provision jarvis with `scripts/bootstrap.sh` (see "### jarvis (staging)").
|
||||||
|
|
||||||
|
**Connecting to jarvis (`ssh jarvis@192.168.8.130`)**: this is a plain `ssh`
|
||||||
|
call. The key `~/.ssh/id_ed25519` is passphrase-protected and Linux Mint pops an
|
||||||
|
askpass dialog for it; the flatpak overlay
|
||||||
|
(`SSH_AUTH_SOCK=/run/flatpak/ssh-auth`) blocks the user's password locker, so
|
||||||
|
they cannot paste from it and must type the passphrase by hand. **Warn the user
|
||||||
|
right before running the command** ("about to ssh to jarvis — be ready to type
|
||||||
|
your passphrase") so they can enter it, then just run `ssh`. Do **not** burn
|
||||||
|
tokens on ssh-agent/askpass/fixed-socket workarounds — once the user types the
|
||||||
|
passphrase at the prompt, plain `ssh` works for the session. The `agent refused
|
||||||
|
operation` error from the flatpak socket is exactly this prompt, not a broken
|
||||||
|
key.
|
||||||
|
|
||||||
Guppy key facts:
|
Guppy key facts:
|
||||||
|
|
||||||
- ssh key `~/.ssh/id_ed25519` is passphrase-protected. Load it into an agent at
|
- ssh key `~/.ssh/id_ed25519` is passphrase-protected. Load it into an agent at
|
||||||
@@ -287,6 +321,14 @@ unit tests (24) + box integration tests (2).
|
|||||||
rapid-message batching, structured `/_send`). DMs only for the first cut;
|
rapid-message batching, structured `/_send`). DMs only for the first cut;
|
||||||
groups/attachments/reactions are future work. See "### gateway (messenger
|
groups/attachments/reactions are future work. See "### gateway (messenger
|
||||||
intake)".
|
intake)".
|
||||||
|
- **Bridge services (SimpleX first)** (Sep 2026): messaging *UX* — invite links,
|
||||||
|
reading incoming messages, composing sends — is decoupled from the command
|
||||||
|
gateway. `semif_agent.bridges` is a folder of standalone third-party API
|
||||||
|
bridges, each its own process (`cli bridge`) against its own service daemon.
|
||||||
|
`SimplexBridge` owns a second simplex-chat profile and serves a token-guarded
|
||||||
|
localhost HTTP API; `registry.describe_bridges()` injects the catalog into the
|
||||||
|
codegen prompts. Gateway isolation is non-negotiable: the gateway must never
|
||||||
|
grow read/send/address surface. See "### bridges (third-party API services)".
|
||||||
|
|
||||||
### Later / open questions
|
### Later / open questions
|
||||||
- Safety/authority: which inputs may interrupt high-stakes processes; is
|
- Safety/authority: which inputs may interrupt high-stakes processes; is
|
||||||
@@ -398,15 +440,20 @@ unit tests (24) + box integration tests (2).
|
|||||||
`--copy-data SRC` rsyncs guppy's `data/` for continuity; `--public-dashboard`
|
`--copy-data SRC` rsyncs guppy's `data/` for continuity; `--public-dashboard`
|
||||||
binds the dashboard to `0.0.0.0`.
|
binds the dashboard to `0.0.0.0`.
|
||||||
It also enables the SimpleX gateway (`gateway.simplex.enabled = true`,
|
It also enables the SimpleX gateway (`gateway.simplex.enabled = true`,
|
||||||
`ws_url` from `simplex_chat.port`) and renders/enables the two user services
|
`ws_url` from `simplex_chat.port`) and the standalone forwarding bridge
|
||||||
`semif-simplex.service` (the pinned `simplex-chat` bot daemon,
|
(`bridges.simplex.enabled = true`, `ws_url` from `simplex_chat.forward_port`,
|
||||||
`--create-bot-display-name` on `simplex_chat.port`) and `semif-gateway.service`
|
top-level `simplex_bridge_url`), rendering/enabling four user services:
|
||||||
(`.runtime/venv/bin/python -m semif_agent.cli gateway`). `--simplex-allowed-users
|
`semif-simplex.service` (the command `simplex-chat` bot daemon,
|
||||||
|
`--create-bot-display-name` on `simplex_chat.port`), `semif-gateway.service`
|
||||||
|
(`.runtime/venv/bin/python -m semif_agent.cli gateway`),
|
||||||
|
`semif-simplex-forward.service` (the bridge's **own** daemon/profile on
|
||||||
|
`simplex_chat.forward_port`) and `semif-bridge.service`
|
||||||
|
(`.runtime/venv/bin/python -m semif_agent.cli bridge`). `--simplex-allowed-users
|
||||||
CSV` / `--simplex-home-channel ID` / `--simplex-display-name NAME` populate
|
CSV` / `--simplex-home-channel ID` / `--simplex-display-name NAME` populate
|
||||||
the allowlist/fallback/identity; with an empty allowlist the gateway denies
|
the gateway allowlist/fallback/identity; with an empty allowlist the gateway
|
||||||
everyone (the safe default until the human adds their contact id). Bootstrap
|
denies everyone (the safe default until the human adds their contact id).
|
||||||
then runs `scripts/simplex-address.py` to create/print the bot's contact
|
Bootstrap then runs `scripts/simplex-address.py` to create/print the command
|
||||||
address.
|
bot's contact address (and the forwarding bot's, via `--ws-url`).
|
||||||
- Run / verify on jarvis:
|
- Run / verify on jarvis:
|
||||||
```sh
|
```sh
|
||||||
REPO=~/repos/semif-agent && cd "$REPO" && export HF_HOME="$REPO/.runtime/hf"
|
REPO=~/repos/semif-agent && cd "$REPO" && export HF_HOME="$REPO/.runtime/hf"
|
||||||
@@ -414,7 +461,7 @@ unit tests (24) + box integration tests (2).
|
|||||||
"$REPO/.runtime/venv/bin/python" -m semif_agent.cli dream # cost report
|
"$REPO/.runtime/venv/bin/python" -m semif_agent.cli dream # cost report
|
||||||
"$REPO/.runtime/venv/bin/python" -m pytest tests/integration -q -s # ~100s, background+poll
|
"$REPO/.runtime/venv/bin/python" -m pytest tests/integration -q -s # ~100s, background+poll
|
||||||
"$REPO/.runtime/venv/bin/python" -m semif_agent.cli dashboard --port 8765
|
"$REPO/.runtime/venv/bin/python" -m semif_agent.cli dashboard --port 8765
|
||||||
systemctl --user status semif-simplex semif-gateway # gateway stack
|
systemctl --user status semif-simplex semif-gateway semif-simplex-forward semif-bridge # gateway + bridge stack
|
||||||
```
|
```
|
||||||
- First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source
|
- First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source
|
||||||
(~10 min on 6 cores); reruns are fast no-ops.
|
(~10 min on 6 cores); reruns are fast no-ops.
|
||||||
@@ -455,9 +502,9 @@ unit tests (24) + box integration tests (2).
|
|||||||
seed never holds secrets, and a generated body with the same name replaces the
|
seed never holds secrets, and a generated body with the same name replaces the
|
||||||
seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded
|
seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded
|
||||||
server-side) is the reference seed; `simplex.next_message` (read via the
|
server-side) is the reference seed; `simplex.next_message` (read via the
|
||||||
messaging bridge) and `simplex.connect_link` (show/create the bot's contact
|
forwarding bridge) and `simplex.connect_link` (show/create the forwarding
|
||||||
link) are the messenger seeds; `tests/test_seed_skills.py` keeps them
|
bot's contact link) are the messenger seeds; `tests/test_seed_skills.py` keeps
|
||||||
honest.
|
them honest.
|
||||||
- **Contract provenance.** Each authored body records the SKILL.md revision it
|
- **Contract provenance.** Each authored body records the SKILL.md revision it
|
||||||
was written against. `skill_contract_ref()` (`codegen.py`) returns
|
was written against. `skill_contract_ref()` (`codegen.py`) returns
|
||||||
`{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read
|
`{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read
|
||||||
@@ -659,7 +706,9 @@ unit tests (24) + box integration tests (2).
|
|||||||
flushed after `text_batch_delay`. Outbound uses the **structured** command
|
flushed after `text_batch_delay`. Outbound uses the **structured** command
|
||||||
`/_send @<contactId> json [{"msgContent":{"type":"text","text":...}}]` — the
|
`/_send @<contactId> json [{"msgContent":{"type":"text","text":...}}]` — the
|
||||||
`@<id> <text>` shortcut is silently rejected over WebSocket. Groups,
|
`@<id> <text>` shortcut is silently rejected over WebSocket. Groups,
|
||||||
attachments, reactions, and typing are out of scope for this cut.
|
attachments, reactions, and typing are out of scope for this cut. The wire
|
||||||
|
protocol itself lives in the neutral `semif_agent/simplex_ws.py`
|
||||||
|
(`SimplexDaemon`); this adapter adds only the allowlist and batching on top.
|
||||||
- **Scheduler glue** (`gateway/service.py`): inbound text →
|
- **Scheduler glue** (`gateway/service.py`): inbound text →
|
||||||
`Scheduler.submit_request(text, source=f"simplex:<chat_id>")`; the returned
|
`Scheduler.submit_request(text, source=f"simplex:<chat_id>")`; the returned
|
||||||
request id maps to the chat (`owners`), and `Scheduler.on_request_requeued`
|
request id maps to the chat (`owners`), and `Scheduler.on_request_requeued`
|
||||||
@@ -674,63 +723,82 @@ unit tests (24) + box integration tests (2).
|
|||||||
= True`; the service routes them by `run_id` → origin, falling back to
|
= True`; the service routes them by `run_id` → origin, falling back to
|
||||||
`home_channel`); a chat's plain reply answers the question or picks the
|
`home_channel`); a chat's plain reply answers the question or picks the
|
||||||
repair action (`retry`/`repair`/`ask`/`no`).
|
repair action (`retry`/`repair`/`ask`/`no`).
|
||||||
- **Messaging bridge (skills send/read SimpleX)** (`gateway/bridge.py`,
|
- **Gateway isolation (non-negotiable).** The gateway exists only to take
|
||||||
Sep 2026): the gateway serves a **localhost stdlib HTTP API** so a skill body
|
commands and send replies. It MUST NOT read a contact's history, show/create
|
||||||
never opens a WebSocket to the daemon. `run_gateway` starts a `MessagingBridge`
|
invite links, or compose messages on the user's behalf: no `observer`, no
|
||||||
(`gateway.simplex.bridge`: `enabled` default true, `host`/`port` default
|
inbound buffering/pull mode, no `/address`, no `/inbox`, no `/send`. Those are
|
||||||
`127.0.0.1:5227`, optional `token` checked as `X-Semif-Token`, `max_inbox`)
|
messaging-UX concerns and live in the standalone bridges
|
||||||
and wires `service.observer = bridge.record_inbound` plus
|
(`semif_agent.bridges`) against their own daemons/profiles. Letting them bleed
|
||||||
`bridge.address_provider = adapter.request_address`. Endpoints: `GET
|
into the always-connected command bot enlarges its attack surface for nothing.
|
||||||
/health`, `GET /contacts`, `GET /inbox` (peek), `GET /inbox/next?contact=<id>`
|
If you are tempted to add read/send/address functionality to `gateway/`, add a
|
||||||
(pop oldest unread — the bridge owns the cursor), `GET /address` (show or
|
bridge instead.
|
||||||
create the bot's user contact link; `{short_link, full_link, created}`, or
|
- **Neutral SimpleX transport** (`semif_agent/simplex_ws.py`): the wire protocol
|
||||||
503 when no provider is wired and 502 when the daemon lookup fails), `POST
|
both front ends share — parsing a direct text item across the v7 wire shapes,
|
||||||
/send` `{"recipient": "<id|display_name>", "text"}` (resolves a numeric id or
|
the structured `/_send`, `/_accept`, and the corrId→Future round-trip used by
|
||||||
a known display name and enqueues on the adapter's existing outbound queue).
|
`/_show_address` / `/_address` (`SimplexDaemon.request_address`, thread-safe
|
||||||
The adapter gained a reusable **corrId→Future request path**
|
via `run_coroutine_threadsafe`). It carries no policy: no allowlist, no
|
||||||
(`SimplexAdapter._roundtrip` / `request_address`, with `user_id` config,
|
scheduler, no HTTP.
|
||||||
default 1): `_consume` resolves a pending future for any frame whose `corrId`
|
- **Tests.** `tests/test_gateway.py` (stdlib, dev box): adapter allowlist/auth,
|
||||||
is registered, so `/_show_address` / `/_address` can be called from the bridge
|
structured send command, batching (real `asyncio`), and `GatewayService`
|
||||||
thread via `run_coroutine_threadsafe` without touching the event loop. The
|
routing against a real `Scheduler` (lazy engine, unreachable LLM).
|
||||||
top-level `messaging_bridge_url` config is the skill-facing address (the data
|
`tests/test_simplex_ws.py` covers the neutral protocol layer (parse shapes,
|
||||||
contract's config search auto-populates it); bootstrap keeps it in sync with
|
accept ids, corrId round-trips, address show/create). `tests/test_bridges.py`
|
||||||
the bridge port. `gateway.simplex.inbox.dispatch` (default true) preserves the
|
exercises `SimplexBridge` over a real loopback server (peek/pop, recipient
|
||||||
current push behavior while buffering every authorized inbound for reads; set
|
resolution, outbound routing, token/body validation, `/address` success/503/502,
|
||||||
false for pull-only mode (buffer without scheduling). Skills reach the bridge
|
daemon close on stop, catalog/`describe_bridges()`).
|
||||||
with the ordinary `http` transport, so their hermetic tests are loopback HTTP
|
`tests/test_seed_skills.py` hermetically tests every
|
||||||
like any other HTTP body. Recipient resolution is a SemIf sub-decision; no
|
`seeds/<category>/<name>/` package, including `simplex.next_message` and
|
||||||
mark-read command exists in the v7 API and contact-list refresh from the
|
`simplex.connect_link`. The live `websockets` transport against a real daemon
|
||||||
daemon (`/_contacts`) is a follow-up (the corrId request path it needs now
|
is a jarvis integration concern.
|
||||||
exists).
|
|
||||||
- **Tests.** `tests/test_gateway.py` (stdlib, dev box): allowlist/auth,
|
|
||||||
`newChatItems` parsing + echo/group/non-text filtering, structured send
|
|
||||||
command, batching (real `asyncio`), corrId→Future round-trips and address
|
|
||||||
normalization, `GatewayService` routing against a real `Scheduler` (lazy
|
|
||||||
engine, unreachable LLM), the observer hook, and pull mode.
|
|
||||||
`tests/test_gateway_bridge.py` exercises the bridge over a real loopback
|
|
||||||
server (peek/pop, recipient resolution, outbound routing, token/body
|
|
||||||
validation, `/address` success/503/502). `tests/test_seed_skills.py`
|
|
||||||
hermetically tests every `seeds/<category>/<name>/` package, including
|
|
||||||
`simplex.next_message` and `simplex.connect_link`. The live `websockets`
|
|
||||||
transport against a real daemon is a jarvis integration concern.
|
|
||||||
- **Deps.** `websockets` is pinned in `requirements/staging.txt` (staging
|
- **Deps.** `websockets` is pinned in `requirements/staging.txt` (staging
|
||||||
only); the dev box core stays stdlib-only.
|
only); the dev box core stays stdlib-only.
|
||||||
|
|
||||||
## Gateway messaging backlog (one session per item)
|
### bridges (third-party API services)
|
||||||
|
|
||||||
The `MessagingBridge` + `simplex.next_message` / `simplex.connect_link` seeds
|
- **What they are.** A bridge service is a standalone process that stands up a
|
||||||
cover the read path, outbound sends onto the adapter's queue, and the bot's
|
simple, secure localhost HTTP layer in front of one third-party system so a
|
||||||
contact-link lookup. Deferred follow-ups:
|
codegen-authored skill body never speaks that system's native protocol.
|
||||||
|
SimpleX is the first; adding a service means adding a class to
|
||||||
|
`bridges/registry.py` `CATALOG` and a `config.example.json` block. The catalog
|
||||||
|
(`BridgeInfo`: name, description, URL config var, endpoints) is injected into
|
||||||
|
the codegen prompts via `describe_bridges()`, so the model knows what it can
|
||||||
|
build against and how.
|
||||||
|
- **Run mode.** `python -m semif_agent.cli bridge [--name simplex]` builds the
|
||||||
|
scheduler (engine lazy, used only for trace) and runs the selected + enabled
|
||||||
|
bridges until interrupted. Each bridge owns its service daemon: `SimplexBridge`
|
||||||
|
connects to a **second** simplex-chat daemon/profile (`bridges.simplex.ws_url`,
|
||||||
|
default port 5228, pinning `simplex_chat.forward_port`), separate from the
|
||||||
|
command gateway's. On a bootstrap-provisioned box, `scripts/bootstrap.sh`
|
||||||
|
renders and enables `semif-simplex-forward.service` (the second daemon) and
|
||||||
|
`semif-bridge.service` (`cli bridge`) alongside the gateway units.
|
||||||
|
- **HTTP surface** (`bridges/base.py` + `bridges/simplex.py`): JSON in/out,
|
||||||
|
localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge`
|
||||||
|
buffers **every** inbound DM (no allowlist — the user wants to see who reached
|
||||||
|
the bot through its invite link) in a bounded `MessagingInbox` that owns the
|
||||||
|
read cursor, and serves `GET /health`, `GET /contacts`, `GET /inbox` (peek),
|
||||||
|
`GET /inbox/next?contact=<id>` (pop oldest), `GET /address` (show/create the
|
||||||
|
forwarding bot's contact link; 503 when the daemon is not connected, 502 when
|
||||||
|
the lookup fails), and `POST /send` `{"recipient","text"}` (resolves a numeric
|
||||||
|
id or a known display name and enqueues on the bridge's own daemon).
|
||||||
|
- **Skill-facing config.** The top-level `simplex_bridge_url` is the address a
|
||||||
|
body calls (the data-contract config search auto-populates it); bootstrap keeps
|
||||||
|
it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
|
||||||
|
transport, so their hermetic tests are loopback HTTP like any other HTTP body.
|
||||||
|
`simplex.next_message` and `simplex.connect_link` are the seeds.
|
||||||
|
|
||||||
- [ ] **1. Contact-list refresh from the daemon** (`gateway/bridge.py`,
|
## Bridge backlog (one session per item)
|
||||||
`gateway/simplex.py`). The bridge learns contacts only from observed inbound
|
|
||||||
|
The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||||
|
(`simplex.connect_link`) are covered. Deferred follow-ups:
|
||||||
|
|
||||||
|
- [ ] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`,
|
||||||
|
`simplex_ws.py`). The bridge learns contacts only from observed inbound
|
||||||
senders, so `/send` cannot address a contact it has never received from.
|
senders, so `/send` cannot address a contact it has never received from.
|
||||||
Query `/_contacts <userId>` (active user from `/user` →
|
Query `/_contacts <userId>` (active user from `/user` →
|
||||||
`activeUser.userId`) at startup and on demand, caching `contactId` +
|
`activeUser.userId`) at startup and on demand, caching `contactId` +
|
||||||
`profile.displayName`. The adapter now has the reusable corrId→Future path
|
`profile.displayName`. Reuse the daemon's corrId→Future path
|
||||||
this needs (`_roundtrip` / `request_address`, used by `GET /address`), so
|
(`SimplexDaemon._roundtrip`) rather than opening a second WebSocket client.
|
||||||
reuse it rather than opening a second WebSocket client.
|
- [ ] **2. Message history + true unread** (`bridges/simplex.py`). The in-memory
|
||||||
- [ ] **2. Message history + true unread** (`gateway/bridge.py`). The in-memory
|
|
||||||
inbox is a receive buffer, not the daemon's read state. Use `/_get chats
|
inbox is a receive buffer, not the daemon's read state. Use `/_get chats
|
||||||
<userId> count=<n> <json(PaginationByTime)>` with a `ChatListQuery` unread
|
<userId> count=<n> <json(PaginationByTime)>` with a `ChatListQuery` unread
|
||||||
filter and `AChat.chatStats{unreadCount, minUnreadItemId}` +
|
filter and `AChat.chatStats{unreadCount, minUnreadItemId}` +
|
||||||
@@ -741,10 +809,9 @@ contact-link lookup. Deferred follow-ups:
|
|||||||
outbound counterpart to `simplex.next_message`: resolve the recipient with a
|
outbound counterpart to `simplex.next_message`: resolve the recipient with a
|
||||||
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
||||||
report the bridge's `contact_id` / errors honestly.
|
report the bridge's `contact_id` / errors honestly.
|
||||||
- [ ] **4. Pull (queue-only) mode as a first-class option.**
|
- [ ] **4. More bridges.** Each new third-party API gets its own `bridges/<name>.py`
|
||||||
`gateway.simplex.inbox.dispatch=false` already buffers without dispatching;
|
+ config block + `CATALOG` entry; the codegen prompts pick it up automatically
|
||||||
document it as a supported mode and give senders an ack/UX story (today their
|
through `describe_bridges()`.
|
||||||
message is buffered silently).
|
|
||||||
|
|
||||||
### Code principles
|
### Code principles
|
||||||
- **Contain installation artifacts in the repo.** Everything a machine installs
|
- **Contain installation artifacts in the repo.** Everything a machine installs
|
||||||
|
|||||||
@@ -150,23 +150,29 @@ talk to. Declaring a transport the body does not use is a broken skill.
|
|||||||
- **Names match the manifest.** The module is imported as its manifest name;
|
- **Names match the manifest.** The module is imported as its manifest name;
|
||||||
the functions are `predict` and `act` exactly.
|
the functions are `predict` and `act` exactly.
|
||||||
|
|
||||||
## Messaging through the gateway bridge
|
## Bridge services
|
||||||
|
|
||||||
The agent can read and send SimpleX messages on the user's behalf. A skill
|
Some real systems are reached through a **bridge service**: a standalone local
|
||||||
never opens a WebSocket to the `simplex-chat` daemon: the running messenger
|
process that stands up a small, token-guarded HTTP API in front of the system
|
||||||
gateway exposes a local HTTP bridge, and that is the only messaging surface a
|
and owns its native protocol and credentials. The concrete catalog of bridges
|
||||||
body touches. Declare it like any other HTTP integration:
|
available to you is injected into the prompt at authoring time (render it with
|
||||||
|
`semif_agent.bridges.describe_bridges()`); read it rather than guessing.
|
||||||
|
|
||||||
|
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": "simplex",
|
"service": "simplex",
|
||||||
"transport": "http",
|
"transport": "http",
|
||||||
"config_vars": ["messaging_bridge_url", "simplex_default_contact"],
|
"config_vars": ["simplex_bridge_url", "simplex_default_contact"],
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`messaging_bridge_url` is the bridge base URL (e.g. `http://127.0.0.1:5227`),
|
For example, the `simplex` bridge (SimpleX messaging) exposes, at the base URL
|
||||||
supplied by the runner through `ctx.config`. Call it with `urllib.request`:
|
in `simplex_bridge_url`:
|
||||||
|
|
||||||
| Request | Purpose |
|
| Request | Purpose |
|
||||||
| -------------------------------------- | ------------------------------------------------------------------ |
|
| -------------------------------------- | ------------------------------------------------------------------ |
|
||||||
@@ -174,11 +180,13 @@ supplied by the runner through `ctx.config`. Call it with `urllib.request`:
|
|||||||
| `GET <base>/contacts` | `{"contacts": [{"id", "display_name"}]}` — known contacts. |
|
| `GET <base>/contacts` | `{"contacts": [{"id", "display_name"}]}` — known contacts. |
|
||||||
| `GET <base>/inbox` | Peek buffered inbound messages; does not consume. |
|
| `GET <base>/inbox` | Peek buffered inbound messages; does not consume. |
|
||||||
| `GET <base>/inbox/next?contact=<id>` | Pop the oldest unread message (optionally from one contact). |
|
| `GET <base>/inbox/next?contact=<id>` | Pop the oldest unread message (optionally from one contact). |
|
||||||
|
| `GET <base>/address` | The agent's contact link; creates it on first call. |
|
||||||
| `POST <base>/send` | `{"recipient": "<id\|display_name>", "text": "..."}` — send. |
|
| `POST <base>/send` | `{"recipient": "<id\|display_name>", "text": "..."}` — send. |
|
||||||
|
|
||||||
`GET /inbox` returns `{"messages": [{"id", "contact_id", "display_name", "text",
|
`GET /inbox` returns `{"messages": [{"id", "contact_id", "display_name", "text",
|
||||||
"received_at"}]}`; `GET /inbox/next` returns `{"message": {...} | null}`, where
|
"received_at"}]}`; `GET /inbox/next` returns `{"message": {...} | null}`, where
|
||||||
`null` means nothing is buffered. `POST /send` returns
|
`null` means nothing is buffered. `GET /address` returns
|
||||||
|
`{"short_link", "full_link", "created"}`. `POST /send` returns
|
||||||
`{"ok": true, "contact_id": "<id>"}`. The bridge owns the read cursor, so a
|
`{"ok": true, "contact_id": "<id>"}`. The bridge owns the read cursor, so a
|
||||||
read skill needs no state of its own.
|
read skill needs no state of its own.
|
||||||
|
|
||||||
@@ -232,9 +240,9 @@ A generated skill is accepted only if:
|
|||||||
and reports real failures honestly.
|
and reports real failures honestly.
|
||||||
8. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
|
8. `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.
|
||||||
9. If it is a messaging skill, it uses the gateway bridge over HTTP (never the
|
9. If it is a messaging skill, it uses a bridge service over HTTP (never a
|
||||||
daemon WebSocket), resolves recipients with a SemIf sub-decision, and sends
|
service's native protocol), resolves recipients with a SemIf sub-decision,
|
||||||
only on explicit user intent.
|
and sends only on explicit user intent.
|
||||||
|
|
||||||
## Worked example
|
## Worked example
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -74,10 +74,11 @@ 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 the gateway bridge), stand up a
|
- For a messaging skill (a body that talks to a bridge service), stand up a
|
||||||
loopback server implementing the bridge endpoints the body uses (`GET /inbox`,
|
loopback server implementing the bridge endpoints the body uses (`GET /inbox`,
|
||||||
`GET /inbox/next?contact=`, `POST /send`) and assert the body built the real
|
`GET /inbox/next?contact=`, `GET /address`, `POST /send`) and assert the body
|
||||||
requests. Never connect to a real `simplex-chat` daemon or the live bridge.
|
built the real requests. Never connect to a real `simplex-chat` 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.
|
||||||
|
|||||||
+22
-19
@@ -73,44 +73,47 @@
|
|||||||
},
|
},
|
||||||
"skill_bodies": "data/skills",
|
"skill_bodies": "data/skills",
|
||||||
"skill_seeds": "seeds",
|
"skill_seeds": "seeds",
|
||||||
"messaging_bridge_url": "http://127.0.0.1:5227",
|
"simplex_bridge_url": "http://127.0.0.1:5227",
|
||||||
"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": "Pinned simplex-chat daemon that the messenger gateway talks to. bootstrap.sh downloads this exact binary (sha256 verified) into .runtime/bin/, runs it headless on `port` with its profile in .runtime/simplex/, and renders the semif-simplex.service unit from it. Bump version/bin_url/sha256 together. The gateway's ws_url (gateway.simplex.ws_url) must match `port`.",
|
"_comment": "Pinned simplex-chat daemon(s). 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 downloads this exact binary (sha256 verified) into .runtime/bin/ and renders both units. Bump version/bin_url/sha256 together. gateway.simplex.ws_url must match `port`; bridges.simplex.ws_url must match `forward_port`.",
|
||||||
"version": "v7.0.3",
|
"version": "v7.0.3",
|
||||||
"bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64",
|
"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",
|
||||||
"port": 5226,
|
"port": 5226,
|
||||||
"display_name": "semif"
|
"display_name": "semif",
|
||||||
|
"forward_port": 5228,
|
||||||
|
"forward_display_name": "semif-forward"
|
||||||
|
},
|
||||||
|
"bridges": {
|
||||||
|
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
|
||||||
|
"simplex": {
|
||||||
|
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills use the top-level `simplex_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||||
|
"enabled": false,
|
||||||
|
"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}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"gateway": {
|
"gateway": {
|
||||||
"_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (see `simplex_chat` above) over its JSON WebSocket API and 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. 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. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. `user_id` is the daemon user whose contact address the connect-link lookup shows/creates (default 1). Groups/attachments are not supported in this first cut.",
|
"_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` connects to the command simplex-chat daemon (`simplex_chat.port`) over its JSON WebSocket API and 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`). 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. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.",
|
||||||
"simplex": {
|
"simplex": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"ws_url": "ws://127.0.0.1:5226",
|
"ws_url": "ws://127.0.0.1:5226",
|
||||||
"allowed_users": [],
|
"allowed_users": [],
|
||||||
"allow_all_users": false,
|
"allow_all_users": false,
|
||||||
"auto_accept": true,
|
"auto_accept": true,
|
||||||
"user_id": 1,
|
|
||||||
"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}
|
||||||
"inbox": {
|
|
||||||
"_comment": "Buffer every authorized inbound DM so a read skill can pull it (see `messaging_bridge_url`). dispatch=true keeps the current behavior (also submit the message as a scheduler request); set dispatch=false for pull-only mode, where inbound messages are buffered and only acted on when the user asks.",
|
|
||||||
"dispatch": true,
|
|
||||||
"max_size": 100
|
|
||||||
},
|
|
||||||
"bridge": {
|
|
||||||
"_comment": "Local HTTP API the gateway serves to skills (send/read SimpleX messages). Skills call it over `http` with the top-level `messaging_bridge_url`; keep that URL in sync with host/port. GET /address shows/creates the bot's contact link (wired to the adapter); /health, /contacts, /inbox, /inbox/next and POST /send are the rest. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Set enabled=false to run the gateway without the bridge.",
|
|
||||||
"enabled": true,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5227,
|
|
||||||
"token": "",
|
|
||||||
"max_inbox": 100
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dashboard": {"port": 8765, "host": "0.0.0.0"}
|
"dashboard": {"port": 8765, "host": "0.0.0.0"}
|
||||||
|
|||||||
+64
-19
@@ -95,7 +95,8 @@ fi
|
|||||||
|
|
||||||
# --- read pins from config.example.json ------------------------------------
|
# --- read pins from config.example.json ------------------------------------
|
||||||
read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \
|
read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \
|
||||||
SIMPLEX_BIN_URL SIMPLEX_SHA256 SIMPLEX_PORT SIMPLEX_DISPLAY LLM_MODEL < <(
|
SIMPLEX_BIN_URL SIMPLEX_SHA256 SIMPLEX_PORT SIMPLEX_DISPLAY \
|
||||||
|
SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY LLM_MODEL < <(
|
||||||
python3 - "$EXAMPLE" <<'PY'
|
python3 - "$EXAMPLE" <<'PY'
|
||||||
import json, sys
|
import json, sys
|
||||||
cfg = json.load(open(sys.argv[1]))
|
cfg = json.load(open(sys.argv[1]))
|
||||||
@@ -114,6 +115,8 @@ print(
|
|||||||
str(s.get("sha256", "")),
|
str(s.get("sha256", "")),
|
||||||
str(s.get("port", "")),
|
str(s.get("port", "")),
|
||||||
str(s.get("display_name", "")),
|
str(s.get("display_name", "")),
|
||||||
|
str(s.get("forward_port", "")),
|
||||||
|
str(s.get("forward_display_name", "")),
|
||||||
str(cfg.get("llm", {}).get("model", "")),
|
str(cfg.get("llm", {}).get("model", "")),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -145,7 +148,7 @@ echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex
|
|||||||
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
|
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
|
||||||
echo "== runtime tree: $RUNTIME"
|
echo "== runtime tree: $RUNTIME"
|
||||||
|
|
||||||
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$UNITS" "$USER_UNITS"
|
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$UNITS" "$USER_UNITS"
|
||||||
|
|
||||||
# --- stage 0: system prereqs + linger ----------------------------------------
|
# --- stage 0: system prereqs + linger ----------------------------------------
|
||||||
PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake util-linux)
|
PKGS=(ca-certificates curl git rsync build-essential python3-dev python3-venv pkg-config cmake util-linux)
|
||||||
@@ -280,12 +283,16 @@ simplex["enabled"] = True
|
|||||||
simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}"
|
simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}"
|
||||||
simplex["allowed_users"] = allowed
|
simplex["allowed_users"] = allowed
|
||||||
simplex["home_channel"] = home_channel
|
simplex["home_channel"] = home_channel
|
||||||
# The gateway serves a localhost HTTP bridge that skills use to send/read
|
# The standalone SimpleX forwarding bridge owns its own daemon/profile
|
||||||
# SimpleX messages; expose its address as the top-level `messaging_bridge_url`
|
# (simplex_chat.forward_port), separate from the command gateway, and serves the
|
||||||
# so the data-contract config search auto-populates it.
|
# invite-link / read / send HTTP API skills use. Expose its URL as the top-level
|
||||||
bridge_port = int(simplex.get("bridge", {}).get("port", 5227))
|
# `simplex_bridge_url` so the data-contract config search auto-populates it.
|
||||||
simplex.setdefault("bridge", {})["enabled"] = True
|
bridge = cfg.setdefault("bridges", {}).setdefault("simplex", {})
|
||||||
cfg["messaging_bridge_url"] = f"http://127.0.0.1:{bridge_port}"
|
bridge_port = int(bridge.get("port", 5227))
|
||||||
|
bridge["enabled"] = True
|
||||||
|
bridge["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('forward_port', 5228)}"
|
||||||
|
cfg["simplex_bridge_url"] = f"http://127.0.0.1:{bridge_port}"
|
||||||
|
simplex.pop("bridge", None) # legacy key; forwarding is a separate service now
|
||||||
json.dump(cfg, open(out, "w"), indent=2)
|
json.dump(cfg, open(out, "w"), indent=2)
|
||||||
PY
|
PY
|
||||||
|
|
||||||
@@ -294,12 +301,14 @@ render_unit() {
|
|||||||
local src="$1" dst="$2"
|
local src="$1" dst="$2"
|
||||||
sed -e "s|@REPO@|$REPO_ROOT|g" \
|
sed -e "s|@REPO@|$REPO_ROOT|g" \
|
||||||
-e "s|@PORT@|$SIMPLEX_PORT|g" \
|
-e "s|@PORT@|$SIMPLEX_PORT|g" \
|
||||||
-e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" "$src" > "$dst"
|
-e "s|@DISPLAY_NAME@|$SIMPLEX_DISPLAY|g" \
|
||||||
|
-e "s|@FORWARD_PORT@|$SIMPLEX_FORWARD_PORT|g" \
|
||||||
|
-e "s|@FORWARD_DISPLAY@|$SIMPLEX_FORWARD_DISPLAY|g" "$src" > "$dst"
|
||||||
}
|
}
|
||||||
echo "== rendering systemd user units into $UNITS"
|
echo "== rendering systemd user units into $UNITS"
|
||||||
UNIT_CHANGED=0
|
UNIT_CHANGED=0
|
||||||
ACTIVE_BEFORE=""
|
ACTIVE_BEFORE=""
|
||||||
for unit in semif-simplex.service semif-gateway.service; do
|
for unit in semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service; do
|
||||||
tmp="$UNITS/$unit.new"
|
tmp="$UNITS/$unit.new"
|
||||||
render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$tmp"
|
render_unit "$REPO_ROOT/scripts/systemd/$unit.in" "$tmp"
|
||||||
if [[ ! -f "$UNITS/$unit" ]] || ! cmp -s "$tmp" "$UNITS/$unit"; then
|
if [[ ! -f "$UNITS/$unit" ]] || ! cmp -s "$tmp" "$UNITS/$unit"; then
|
||||||
@@ -318,9 +327,9 @@ done
|
|||||||
if command -v systemctl >/dev/null 2>&1; then
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
||||||
if systemctl --user daemon-reload 2>/dev/null; then
|
if systemctl --user daemon-reload 2>/dev/null; then
|
||||||
systemctl --user enable --now semif-simplex.service semif-gateway.service 2>/dev/null \
|
systemctl --user enable --now semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service 2>/dev/null \
|
||||||
&& echo "== enabled semif-simplex.service semif-gateway.service" \
|
&& echo "== enabled semif-simplex.service semif-simplex-forward.service semif-gateway.service semif-bridge.service" \
|
||||||
|| echo "WARN: could not enable user services (run: systemctl --user enable --now semif-simplex semif-gateway)" >&2
|
|| echo "WARN: could not enable user services (run: systemctl --user enable --now semif-simplex semif-simplex-forward semif-gateway semif-bridge)" >&2
|
||||||
# Apply a changed unit to services that were already running (enable --now
|
# Apply a changed unit to services that were already running (enable --now
|
||||||
# leaves active units untouched). A daemon restart is safe: the simplex
|
# leaves active units untouched). A daemon restart is safe: the simplex
|
||||||
# profile persists and the gateway reconnects.
|
# profile persists and the gateway reconnects.
|
||||||
@@ -355,6 +364,32 @@ if command -v systemctl >/dev/null 2>&1; then
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# --- stage 8c: forwarding bridge contact address --------------------------------------
|
||||||
|
# The forwarding bridge owns a second daemon/profile; its own contact link is the
|
||||||
|
# one `simplex.connect_link` shows. Print it too so the user can share it.
|
||||||
|
BRIDGE_FORWARD_WS="$("$PYTHON" - "$REPO_ROOT/config.json" <<'PY' 2>/dev/null || true
|
||||||
|
import json, sys
|
||||||
|
try:
|
||||||
|
cfg = json.load(open(sys.argv[1]))
|
||||||
|
except Exception:
|
||||||
|
raise SystemExit(0)
|
||||||
|
print(cfg.get("bridges", {}).get("simplex", {}).get("ws_url", "") or "")
|
||||||
|
PY
|
||||||
|
)"
|
||||||
|
if [[ -n "$BRIDGE_FORWARD_WS" ]] && command -v systemctl >/dev/null 2>&1; then
|
||||||
|
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
||||||
|
if systemctl --user is-active --quiet semif-simplex-forward.service 2>/dev/null; then
|
||||||
|
echo "== ensuring the forwarding bridge contact address exists"
|
||||||
|
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||||
|
if FORWARD_ADDRESS="$("$PYTHON" "$REPO_ROOT/scripts/simplex-address.py" --ws-url "$BRIDGE_FORWARD_WS" 2>/dev/null)"; then
|
||||||
|
printf '%s\n' "$FORWARD_ADDRESS" | sed 's/^/ /'
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# --- stage 9: optional data copy -----------------------------------------------------
|
# --- stage 9: optional data copy -----------------------------------------------------
|
||||||
if [[ -n "$COPY_DATA" ]]; then
|
if [[ -n "$COPY_DATA" ]]; then
|
||||||
echo "== rsync data from $COPY_DATA"
|
echo "== rsync data from $COPY_DATA"
|
||||||
@@ -408,9 +443,11 @@ else
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
if command -v systemctl >/dev/null 2>&1; then
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
echo "== gateway services"
|
echo "== gateway + bridge services"
|
||||||
systemctl --user is-active semif-simplex.service 2>/dev/null | sed 's/^/ semif-simplex: /' || true
|
systemctl --user is-active semif-simplex.service 2>/dev/null | sed 's/^/ semif-simplex: /' || true
|
||||||
systemctl --user is-active semif-gateway.service 2>/dev/null | sed 's/^/ semif-gateway: /' || true
|
systemctl --user is-active semif-gateway.service 2>/dev/null | sed 's/^/ semif-gateway: /' || true
|
||||||
|
systemctl --user is-active semif-simplex-forward.service 2>/dev/null | sed 's/^/ semif-simplex-forward: /' || true
|
||||||
|
systemctl --user is-active semif-bridge.service 2>/dev/null | sed 's/^/ semif-bridge: /' || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
@@ -421,8 +458,8 @@ Done. Next steps:
|
|||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m pytest tests/integration -q -s (needs real engine+LLM)
|
HF_HOME="$HF_CACHE" "$PYTHON" -m pytest tests/integration -q -s (needs real engine+LLM)
|
||||||
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli dashboard --port 8765
|
HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli dashboard --port 8765
|
||||||
|
|
||||||
SimpleX gateway:
|
SimpleX command gateway (commands only):
|
||||||
- The bot runs as systemd user services 'semif-simplex' (bot daemon, port $SIMPLEX_PORT) and
|
- Runs as systemd user services 'semif-simplex' (bot daemon, port $SIMPLEX_PORT) and
|
||||||
'semif-gateway' (agent). Check them with:
|
'semif-gateway' (agent). Check them with:
|
||||||
systemctl --user status semif-simplex semif-gateway
|
systemctl --user status semif-simplex semif-gateway
|
||||||
journalctl --user -u semif-gateway -f
|
journalctl --user -u semif-gateway -f
|
||||||
@@ -433,7 +470,15 @@ SimpleX gateway:
|
|||||||
gateway.simplex.allowed_users (discover the id from a 'gateway_denied' trace
|
gateway.simplex.allowed_users (discover the id from a 'gateway_denied' trace
|
||||||
event or the daemon's /contacts) and reply. With an empty allowlist the
|
event or the daemon's /contacts) and reply. With an empty allowlist the
|
||||||
gateway rejects everyone — that is the safe default.
|
gateway rejects everyone — that is the safe default.
|
||||||
- Skills send/read SimpleX messages through the gateway's local HTTP bridge
|
- The gateway takes commands and replies. It never reads history, shows invite
|
||||||
(config.json top-level messaging_bridge_url, default
|
links, or composes messages: that is the forwarding bridge's job.
|
||||||
http://127.0.0.1:5227); nothing else is needed while the gateway runs.
|
|
||||||
|
SimpleX forwarding bridge (messaging UX for skills):
|
||||||
|
- Runs as 'semif-simplex-forward' (a second bot daemon/profile, port $SIMPLEX_FORWARD_PORT)
|
||||||
|
and 'semif-bridge' (the standalone bridge API). Its contact address is printed
|
||||||
|
above; re-print with:
|
||||||
|
"$PYTHON" scripts/simplex-address.py --ws-url ws://127.0.0.1:$SIMPLEX_FORWARD_PORT
|
||||||
|
- Skills reach it over HTTP via the top-level simplex_bridge_url
|
||||||
|
(default http://127.0.0.1:5227); simplex.connect_link shows its address and
|
||||||
|
simplex.next_message reads messages sent to it.
|
||||||
EOF
|
EOF
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent third-party API bridges (SimpleX forwarding)
|
||||||
|
After=network-online.target semif-simplex-forward.service
|
||||||
|
Wants=network-online.target semif-simplex-forward.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=@REPO@
|
||||||
|
Environment=HF_HOME=@REPO@/.runtime/hf
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
ExecStart=@REPO@/.runtime/venv/bin/python -m semif_agent.cli bridge
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-bridge
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=SemIf agent SimpleX forwarding bridge daemon
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# The forwarding bridge owns its OWN simplex-chat profile (separate from the
|
||||||
|
# command gateway's bot), so messaging UX never shares the command identity.
|
||||||
|
# Bot mode + a PTY are required for the same reason as semif-simplex.service:
|
||||||
|
# --headless means "chat relay" in v7, and the CLI only pumps WebSocket events
|
||||||
|
# with a controlling terminal.
|
||||||
|
ExecStart=/usr/bin/script -q -e -c "@REPO@/.runtime/bin/simplex-chat -p @FORWARD_PORT@ -d @REPO@/.runtime/simplex-forward/simplex_v1 -k '' --create-bot-display-name '@FORWARD_DISPLAY@'" /dev/null
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=semif-simplex-forward
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"messaging_bridge_url": "Base URL of the messenger gateway's local HTTP bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed)."
|
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed)."
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
"""Show the SimpleX contact link others use to connect to this agent.
|
"""Show the SimpleX contact link others use to connect to this agent.
|
||||||
|
|
||||||
Real integration: the running messenger gateway serves a local HTTP bridge
|
Real integration: the standalone SimpleX forwarding bridge
|
||||||
(`messaging_bridge_url`). The gateway's own connection to the `simplex-chat`
|
(`simplex_bridge_url`). The bridge's own connection to the `simplex-chat`
|
||||||
daemon is the only thing that can read (or create) the bot's *user contact
|
daemon is the only thing that can read (or create) the forwarding bot's *user
|
||||||
address*; this body asks the bridge for it and reports the link honestly. It
|
contact address*; this body asks the bridge for it and reports the link
|
||||||
never opens a WebSocket to the daemon and never invents a link: if the gateway
|
honestly. It never opens a WebSocket to the daemon and never invents a link: if
|
||||||
is not running or has no address, it says so.
|
the bridge is not running or has no address, it says so.
|
||||||
|
|
||||||
`GET /address` shows the existing link and creates one on first call, returning
|
`GET /address` shows the existing link and creates one on first call, returning
|
||||||
`{short_link, full_link, created}`.
|
`{short_link, full_link, created}`.
|
||||||
@@ -22,20 +22,20 @@ from semif_agent.skills import ActionResult, Prediction
|
|||||||
INTEGRATION = {
|
INTEGRATION = {
|
||||||
"service": "simplex",
|
"service": "simplex",
|
||||||
"transport": "http",
|
"transport": "http",
|
||||||
"config_vars": ["messaging_bridge_url"],
|
"config_vars": ["simplex_bridge_url"],
|
||||||
}
|
}
|
||||||
|
|
||||||
TIMEOUT_SECONDS = 30
|
TIMEOUT_SECONDS = 30
|
||||||
|
|
||||||
|
|
||||||
class BridgeError(Exception):
|
class BridgeError(Exception):
|
||||||
"""The local messaging bridge is unreachable or returned an error."""
|
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
def _base(ctx):
|
||||||
url = str(ctx.config.get("messaging_bridge_url", "") or "").strip().rstrip("/")
|
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||||
if not url:
|
if not url:
|
||||||
raise BridgeError("messaging_bridge_url is not configured")
|
raise BridgeError("simplex_bridge_url is not configured")
|
||||||
return url
|
return url
|
||||||
|
|
||||||
|
|
||||||
@@ -57,8 +57,8 @@ def predict(ctx, request):
|
|||||||
except BridgeError as exc:
|
except BridgeError as exc:
|
||||||
return Prediction(text=f"bridge error: {exc}")
|
return Prediction(text=f"bridge error: {exc}")
|
||||||
if not payload.get("ok"):
|
if not payload.get("ok"):
|
||||||
return Prediction(text="bridge error: gateway bridge is not healthy")
|
return Prediction(text="bridge error: simplex forwarding bridge is not healthy")
|
||||||
return Prediction(text="ready: messenger bridge reachable")
|
return Prediction(text="ready: simplex forwarding bridge reachable")
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request, prediction):
|
def act(ctx, request, prediction):
|
||||||
@@ -77,7 +77,7 @@ def act(ctx, request, prediction):
|
|||||||
if not (short or full):
|
if not (short or full):
|
||||||
return ActionResult(
|
return ActionResult(
|
||||||
action_log=(
|
action_log=(
|
||||||
"simplex.connect_link: the gateway returned no SimpleX "
|
"simplex.connect_link: the bridge returned no SimpleX "
|
||||||
"contact link; the bot has no address yet."
|
"contact link; the bot has no address yet."
|
||||||
),
|
),
|
||||||
new_state=request.text,
|
new_state=request.text,
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
"""Hermetic mechanics test for simplex.connect_link.
|
"""Hermetic mechanics test for simplex.connect_link.
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||||
http.server plays the messenger gateway's bridge. This proves the body health-
|
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
|
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
|
fails honestly when the bridge has no provider or is unreachable. It does NOT
|
||||||
prove the live integration — only a real run against the gateway and a real
|
prove the live integration — only a real run against the bridge and a real
|
||||||
simplex-chat daemon does.
|
simplex-chat daemon does.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -59,7 +59,7 @@ def start_server(address=None, address_status=200):
|
|||||||
|
|
||||||
|
|
||||||
def config(url):
|
def config(url):
|
||||||
return {"messaging_bridge_url": url}
|
return {"simplex_bridge_url": url}
|
||||||
|
|
||||||
|
|
||||||
def test_reports_existing_link():
|
def test_reports_existing_link():
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"messaging_bridge_url": "Base URL of the messenger gateway's local HTTP bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||||
"simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages."
|
"simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages."
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"description": "Read the next unread SimpleX message through the messenger gateway."
|
"description": "Read the next unread SimpleX message through the forwarding bridge."
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
"""Read the next unread SimpleX message through the messenger gateway.
|
"""Read the next unread SimpleX message through the forwarding bridge.
|
||||||
|
|
||||||
Real integration: the running messenger gateway serves a local HTTP bridge
|
Real integration: the standalone SimpleX forwarding bridge
|
||||||
(`messaging_bridge_url`) that buffers every inbound DM and forwards outbound
|
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
||||||
sends. `predict` peeks that inbox, finds which conversations have unread
|
`predict` peeks that inbox, finds which conversations have unread messages, and
|
||||||
messages, and resolves which one to read with a SemIf sub-decision when more
|
resolves which one to read with a SemIf sub-decision when more than one does
|
||||||
than one does (honoring a configured default contact); `act` pops and reports
|
(honoring a configured default contact); `act` pops and reports the oldest
|
||||||
the oldest unread message for that conversation.
|
unread message for that conversation.
|
||||||
|
|
||||||
The bridge owns the read cursor, so this skill keeps no state of its own. It
|
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
|
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
|
||||||
@@ -25,20 +25,20 @@ from semif_agent.skills import ActionResult, Prediction
|
|||||||
INTEGRATION = {
|
INTEGRATION = {
|
||||||
"service": "simplex",
|
"service": "simplex",
|
||||||
"transport": "http",
|
"transport": "http",
|
||||||
"config_vars": ["messaging_bridge_url", "simplex_default_contact"],
|
"config_vars": ["simplex_bridge_url", "simplex_default_contact"],
|
||||||
}
|
}
|
||||||
|
|
||||||
TIMEOUT_SECONDS = 20
|
TIMEOUT_SECONDS = 20
|
||||||
|
|
||||||
|
|
||||||
class BridgeError(Exception):
|
class BridgeError(Exception):
|
||||||
"""The local messaging bridge is unreachable or returned an error."""
|
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
def _base(ctx):
|
||||||
url = str(ctx.config.get("messaging_bridge_url", "") or "").strip().rstrip("/")
|
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||||
if not url:
|
if not url:
|
||||||
raise BridgeError("messaging_bridge_url is not configured")
|
raise BridgeError("simplex_bridge_url is not configured")
|
||||||
return url
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
"""Hermetic mechanics test for simplex.next_message.
|
"""Hermetic mechanics test for simplex.next_message.
|
||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||||
http.server plays the messenger gateway's bridge. This proves the body peeks the
|
http.server plays the standalone SimpleX forwarding bridge. This proves the body peeks the
|
||||||
inbox, resolves the conversation through a SemIf sub-decision (or a configured
|
inbox, resolves the conversation through a SemIf sub-decision (or a configured
|
||||||
default), pops the real `next` message, and fails honestly when the bridge is
|
default), 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
|
unreachable. It does NOT prove the live integration — only a real run against
|
||||||
the gateway and a real contact does.
|
the bridge and a real contact does.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -89,7 +89,7 @@ def message(identifier, contact, name, text):
|
|||||||
|
|
||||||
|
|
||||||
def config(url, default=""):
|
def config(url, default=""):
|
||||||
return {"messaging_bridge_url": url, "simplex_default_contact": default}
|
return {"simplex_bridge_url": url, "simplex_default_contact": default}
|
||||||
|
|
||||||
|
|
||||||
def test_multiple_senders_uses_semif_decision():
|
def test_multiple_senders_uses_semif_decision():
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Third-party API bridges: a secure local layer between skills and services.
|
||||||
|
|
||||||
|
A **bridge service** is a standalone process that exposes one third-party system
|
||||||
|
(SimpleX first, more later) to codegen-authored skill bodies over a local,
|
||||||
|
token-guarded HTTP API. It exists so a generated body never speaks a system's
|
||||||
|
native protocol (WebSocket, SMTP, CalDAV, 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.
|
||||||
|
|
||||||
|
Two boundaries matter:
|
||||||
|
|
||||||
|
- **Bridges are not the gateway.** The command gateway only takes commands and
|
||||||
|
replies; it must never grow read/send/invite endpoints. Bridges run as their
|
||||||
|
own processes (`python -m semif_agent.cli bridge`) against their own service
|
||||||
|
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
|
||||||
|
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
|
||||||
|
the code-generation prompts so the model knows which real services it may
|
||||||
|
build against and how to reach them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .base import BridgeInfo, BridgeService
|
||||||
|
from .inbox import MessagingInbox
|
||||||
|
from .registry import (
|
||||||
|
build_bridge,
|
||||||
|
describe_bridges,
|
||||||
|
known_infos,
|
||||||
|
run_bridges,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"BridgeInfo",
|
||||||
|
"BridgeService",
|
||||||
|
"MessagingInbox",
|
||||||
|
"build_bridge",
|
||||||
|
"describe_bridges",
|
||||||
|
"known_infos",
|
||||||
|
"run_bridges",
|
||||||
|
]
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
"""Bridge service contract + the shared secure HTTP layer.
|
||||||
|
|
||||||
|
Every bridge stands up the same thin HTTP surface: JSON in, JSON out, bound to
|
||||||
|
localhost, optionally guarded by a shared-secret header. A subclass only
|
||||||
|
implements its routes (`handle_get` / `handle_post`) and, if it needs a service
|
||||||
|
daemon, starts it in `start()`. The HTTP/JSON/auth plumbing lives here once so
|
||||||
|
each new bridge is small and hard to get wrong.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BridgeInfo:
|
||||||
|
"""Static, prompt-safe metadata about a bridge.
|
||||||
|
|
||||||
|
Fed to the code-generation model so it knows what it can build against,
|
||||||
|
and used to describe the service in docs. Holds no secrets and needs no
|
||||||
|
running process.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
service: str
|
||||||
|
description: str
|
||||||
|
url_config_var: str
|
||||||
|
#: Human-readable `METHOD /path` -> purpose lines.
|
||||||
|
endpoints: tuple[str, ...] = ()
|
||||||
|
#: Other `ctx.config` keys a body built on this bridge may read.
|
||||||
|
config_vars: tuple[str, ...] = field(default=())
|
||||||
|
|
||||||
|
|
||||||
|
class BridgeService(ABC):
|
||||||
|
"""Base class for a standalone third-party API bridge."""
|
||||||
|
|
||||||
|
#: short snake_case id (`simplex`)
|
||||||
|
name: str = "bridge"
|
||||||
|
#: static catalog entry
|
||||||
|
info: BridgeInfo
|
||||||
|
|
||||||
|
def __init__(self, config: dict | None = None, trace=None):
|
||||||
|
cfg = config or {}
|
||||||
|
self.host = str(cfg.get("host", "127.0.0.1"))
|
||||||
|
self.port = int(cfg.get("port", 0))
|
||||||
|
self.token = str(cfg.get("token", "") or "")
|
||||||
|
self.trace = trace
|
||||||
|
self._server: ThreadingHTTPServer | None = None
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
|
||||||
|
|
||||||
|
def start(self) -> int:
|
||||||
|
"""Start serving HTTP; returns the bound port (`port=0` is ephemeral)."""
|
||||||
|
server = ThreadingHTTPServer((self.host, self.port), _BridgeHTTPHandler)
|
||||||
|
server.bridge = self # type: ignore[attr-defined]
|
||||||
|
self._server = server
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=server.serve_forever,
|
||||||
|
name=f"bridge-{self.name}",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
return int(server.server_address[1])
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop_transport()
|
||||||
|
server, self._server = self._server, None
|
||||||
|
if server is not None:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
thread, self._thread = self._thread, None
|
||||||
|
if thread is not None:
|
||||||
|
thread.join(timeout=2.0)
|
||||||
|
|
||||||
|
def _stop_transport(self) -> None:
|
||||||
|
"""Hook for subclasses that own a background transport (daemon)."""
|
||||||
|
|
||||||
|
# ---- routes ----
|
||||||
|
|
||||||
|
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
# ---- helpers ----
|
||||||
|
|
||||||
|
def _event(self, kind: str, **fields) -> None:
|
||||||
|
if self.trace is not None:
|
||||||
|
self.trace.append(kind, "?", **fields)
|
||||||
|
|
||||||
|
|
||||||
|
class _BridgeHTTPHandler(BaseHTTPRequestHandler):
|
||||||
|
"""JSON request handler; the owning bridge is on `self.server.bridge`."""
|
||||||
|
|
||||||
|
def log_message(self, *args) -> None: # silence the default stderr spam
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _bridge(self) -> BridgeService:
|
||||||
|
return self.server.bridge # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
def _authorized(self) -> bool:
|
||||||
|
token = self._bridge().token
|
||||||
|
if not token:
|
||||||
|
return True
|
||||||
|
return self.headers.get("X-Semif-Token") == token
|
||||||
|
|
||||||
|
def _json(self, status: int, payload: dict) -> None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _require_auth(self) -> bool:
|
||||||
|
if self._authorized():
|
||||||
|
return True
|
||||||
|
self._json(401, {"error": "unauthorized"})
|
||||||
|
return False
|
||||||
|
|
||||||
|
def do_GET(self) -> None:
|
||||||
|
if not self._require_auth():
|
||||||
|
return
|
||||||
|
url = urlparse(self.path)
|
||||||
|
status, payload = self._bridge().handle_get(url.path, parse_qs(url.query))
|
||||||
|
self._json(status, payload)
|
||||||
|
|
||||||
|
def do_POST(self) -> None:
|
||||||
|
if not self._require_auth():
|
||||||
|
return
|
||||||
|
url = urlparse(self.path)
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length) if length else b""
|
||||||
|
try:
|
||||||
|
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||||
|
except ValueError:
|
||||||
|
self._json(400, {"error": "invalid JSON body"})
|
||||||
|
return
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
self._json(400, {"error": "body must be a JSON object"})
|
||||||
|
return
|
||||||
|
status, response = self._bridge().handle_post(url.path, payload)
|
||||||
|
self._json(status, response)
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""A bounded, thread-safe FIFO of buffered inbound messages + known contacts.
|
||||||
|
|
||||||
|
The bridge owns the read cursor so a read skill stays stateless. Generic over
|
||||||
|
transports: entries are normalized message dicts (`contact_id`, `display_name`,
|
||||||
|
`text`), which is exactly what `semif_agent.simplex_ws` yields.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
|
||||||
|
class MessagingInbox:
|
||||||
|
def __init__(self, max_size: int = 100):
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._items: deque[dict] = deque()
|
||||||
|
self._max = max(1, int(max_size))
|
||||||
|
self._contacts: dict[str, str] = {}
|
||||||
|
|
||||||
|
def record(self, message: dict) -> dict:
|
||||||
|
contact_id = str(message.get("contact_id") or "")
|
||||||
|
display_name = message.get("display_name") or ""
|
||||||
|
entry = {
|
||||||
|
"id": uuid.uuid4().hex[:12],
|
||||||
|
"contact_id": contact_id,
|
||||||
|
"display_name": display_name,
|
||||||
|
"text": message.get("text") or "",
|
||||||
|
"received_at": time.time(),
|
||||||
|
}
|
||||||
|
with self._lock:
|
||||||
|
if display_name:
|
||||||
|
self._contacts[contact_id] = display_name
|
||||||
|
else:
|
||||||
|
self._contacts.setdefault(contact_id, "")
|
||||||
|
self._items.append(entry)
|
||||||
|
while len(self._items) > self._max:
|
||||||
|
self._items.popleft()
|
||||||
|
return entry
|
||||||
|
|
||||||
|
def peek(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
return list(self._items)
|
||||||
|
|
||||||
|
def pop(self, contact_id: str | None = None) -> dict | None:
|
||||||
|
with self._lock:
|
||||||
|
if contact_id is None:
|
||||||
|
return self._items.popleft() if self._items else None
|
||||||
|
target = str(contact_id)
|
||||||
|
for index, entry in enumerate(self._items):
|
||||||
|
if entry["contact_id"] == target:
|
||||||
|
del self._items[index]
|
||||||
|
return entry
|
||||||
|
return None
|
||||||
|
|
||||||
|
def contacts(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
return [
|
||||||
|
{"id": contact_id, "display_name": name}
|
||||||
|
for contact_id, name in self._contacts.items()
|
||||||
|
]
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""The bridge catalog: discovery, prompt description, and standalone runner.
|
||||||
|
|
||||||
|
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
|
||||||
|
static metadata, `describe_bridges()` renders the catalog block injected into
|
||||||
|
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
|
||||||
|
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
|
||||||
|
adding its class here and a `config.example.json` block; the gateway is never
|
||||||
|
touched.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from .base import BridgeInfo, BridgeService
|
||||||
|
from .simplex import SimplexBridge
|
||||||
|
|
||||||
|
#: Known bridge services. Order is presentation order.
|
||||||
|
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge,)
|
||||||
|
|
||||||
|
|
||||||
|
def _class_for(name: str) -> type[BridgeService] | None:
|
||||||
|
for bridge_class in CATALOG:
|
||||||
|
if bridge_class.INFO.name == name:
|
||||||
|
return bridge_class
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def known_infos() -> list[BridgeInfo]:
|
||||||
|
return [bridge_class.INFO for bridge_class in CATALOG]
|
||||||
|
|
||||||
|
|
||||||
|
def describe_bridges() -> str:
|
||||||
|
"""A prompt block describing every available bridge service.
|
||||||
|
|
||||||
|
Injected into the skill-body and elicitation prompts so codegen knows which
|
||||||
|
real services it may build a skill against, how to reach each one, and which
|
||||||
|
`ctx.config` variable carries its URL. Static — no bridge needs to be
|
||||||
|
running or enabled.
|
||||||
|
"""
|
||||||
|
lines = [
|
||||||
|
"Available bridge services (call these over HTTP with urllib.request; "
|
||||||
|
"never speak a service's native protocol directly):",
|
||||||
|
]
|
||||||
|
for info in known_infos():
|
||||||
|
lines.append(f"- {info.name}: {info.description}")
|
||||||
|
lines.append(f" config var: {info.url_config_var}")
|
||||||
|
if info.config_vars:
|
||||||
|
other = [v for v in info.config_vars if v != info.url_config_var]
|
||||||
|
if other:
|
||||||
|
lines.append(f" other config vars: {', '.join(other)}")
|
||||||
|
for endpoint in info.endpoints:
|
||||||
|
lines.append(f" {endpoint}")
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def build_bridge(config: dict, name: str, trace=None) -> BridgeService:
|
||||||
|
"""Instantiate one bridge from the top-level `bridges.<name>` config block."""
|
||||||
|
bridge_class = _class_for(name)
|
||||||
|
if bridge_class is None:
|
||||||
|
raise KeyError(f"unknown bridge: {name!r}")
|
||||||
|
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
|
||||||
|
return bridge_class(block, trace=trace)
|
||||||
|
|
||||||
|
|
||||||
|
def run_bridges(
|
||||||
|
config: dict,
|
||||||
|
names: list[str] | None = None,
|
||||||
|
trace=None,
|
||||||
|
) -> int:
|
||||||
|
"""Run the selected (+ enabled) bridges until interrupted.
|
||||||
|
|
||||||
|
With explicit `names`, a bridge runs even if disabled is not set; with no
|
||||||
|
names, only `enabled` bridges run. Returns a process exit code.
|
||||||
|
"""
|
||||||
|
blocks = config.get("bridges", {}) or {}
|
||||||
|
selected: list[BridgeService] = []
|
||||||
|
for bridge_class in CATALOG:
|
||||||
|
name = bridge_class.INFO.name
|
||||||
|
if names and name not in names:
|
||||||
|
continue
|
||||||
|
block = blocks.get(name, {}) or {}
|
||||||
|
if not names and not block.get("enabled", False):
|
||||||
|
continue
|
||||||
|
bridge = bridge_class(block, trace=trace)
|
||||||
|
ok, hint = bridge.check_requirements()
|
||||||
|
if not ok:
|
||||||
|
print(f"bridge {name} unavailable: {hint}")
|
||||||
|
for running in selected:
|
||||||
|
running.stop()
|
||||||
|
return 1
|
||||||
|
port = bridge.start()
|
||||||
|
selected.append(bridge)
|
||||||
|
print(
|
||||||
|
f"bridge {name} listening on http://{bridge.host}:{port} "
|
||||||
|
f"(skills use the {bridge_class.INFO.url_config_var} config var)"
|
||||||
|
)
|
||||||
|
if not selected:
|
||||||
|
print("no bridge services enabled (set bridges.<name>.enabled)")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
stop = threading.Event()
|
||||||
|
try:
|
||||||
|
while not stop.wait(0.5):
|
||||||
|
pass
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for bridge in selected:
|
||||||
|
bridge.stop()
|
||||||
|
return 0
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
|
||||||
|
|
||||||
|
The first third-party API bridge. It stands up a small HTTP API that a skill
|
||||||
|
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
|
||||||
|
SimpleX daemon/profile — separate from the command gateway's. That separation is
|
||||||
|
the point: the gateway takes commands; this bridge forwards the user's messaging
|
||||||
|
UX (show/create the contact link, read the next message, compose a send).
|
||||||
|
|
||||||
|
It buffers every inbound direct message (no allowlist — the user wants to see
|
||||||
|
who reached the bot through its invite link), and it never runs inside the
|
||||||
|
gateway process.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from semif_agent.simplex_ws import SimplexDaemon
|
||||||
|
|
||||||
|
from .base import BridgeInfo, BridgeService
|
||||||
|
from .inbox import MessagingInbox
|
||||||
|
|
||||||
|
|
||||||
|
class SimplexBridge(BridgeService):
|
||||||
|
name = "simplex"
|
||||||
|
INFO = BridgeInfo(
|
||||||
|
name="simplex",
|
||||||
|
service="simplex",
|
||||||
|
description=(
|
||||||
|
"Read and send SimpleX messages on the user's behalf, and show or "
|
||||||
|
"create the contact link others use to reach this agent."
|
||||||
|
),
|
||||||
|
url_config_var="simplex_bridge_url",
|
||||||
|
endpoints=(
|
||||||
|
"GET /health -> {\"ok\": true} — the bridge is up",
|
||||||
|
"GET /contacts -> {\"contacts\": [{\"id\", \"display_name\"}]}",
|
||||||
|
"GET /inbox -> peek buffered inbound messages (does not consume)",
|
||||||
|
"GET /inbox/next?contact=<id> -> pop the oldest unread message for a "
|
||||||
|
"contact (or any contact) -> {\"message\": {...}|null}",
|
||||||
|
"GET /address -> the agent's SimpleX contact link "
|
||||||
|
"(creates it on first call) -> {\"short_link\", \"full_link\", "
|
||||||
|
"\"created\"}",
|
||||||
|
"POST /send {\"recipient\": \"<id|display_name>\", \"text\": \"...\"} "
|
||||||
|
"-> {\"ok\", \"contact_id\"}",
|
||||||
|
),
|
||||||
|
config_vars=("simplex_bridge_url", "simplex_default_contact"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, config: dict | None = None, trace=None, daemon=None):
|
||||||
|
super().__init__(config, trace)
|
||||||
|
cfg = config or {}
|
||||||
|
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
|
||||||
|
self.daemon = daemon or SimplexDaemon(
|
||||||
|
cfg.get("ws_url", "ws://127.0.0.1:5228"),
|
||||||
|
user_id=int(cfg.get("user_id", 1)),
|
||||||
|
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||||
|
reconnect=cfg.get("reconnect", {}) or {},
|
||||||
|
trace=trace,
|
||||||
|
name=self.name,
|
||||||
|
)
|
||||||
|
self._daemon_thread: threading.Thread | None = None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
return self.daemon.check_requirements()
|
||||||
|
|
||||||
|
def start(self) -> int:
|
||||||
|
port = super().start()
|
||||||
|
self._daemon_thread = threading.Thread(
|
||||||
|
target=self.daemon.run,
|
||||||
|
args=(self._on_message,),
|
||||||
|
name="bridge-simplex-daemon",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
self._daemon_thread.start()
|
||||||
|
return port
|
||||||
|
|
||||||
|
def _stop_transport(self) -> None:
|
||||||
|
self.daemon.close()
|
||||||
|
|
||||||
|
def _on_message(self, message: dict) -> None:
|
||||||
|
self.inbox.record(message)
|
||||||
|
|
||||||
|
# ---- routes ----
|
||||||
|
|
||||||
|
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||||
|
if path == "/health":
|
||||||
|
return 200, {"ok": True, "platform": self.name}
|
||||||
|
if path == "/contacts":
|
||||||
|
return 200, {"contacts": self.inbox.contacts()}
|
||||||
|
if path == "/inbox":
|
||||||
|
return 200, {"messages": self.inbox.peek()}
|
||||||
|
if path == "/inbox/next":
|
||||||
|
contact = (query.get("contact") or [None])[0]
|
||||||
|
return 200, {"message": self.inbox.pop(contact)}
|
||||||
|
if path == "/address":
|
||||||
|
return self._address()
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
|
||||||
|
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||||
|
if path != "/send":
|
||||||
|
return 404, {"error": "not found"}
|
||||||
|
recipient = payload.get("recipient")
|
||||||
|
text = payload.get("text")
|
||||||
|
if not isinstance(recipient, str) or not recipient.strip():
|
||||||
|
return 400, {"error": "recipient is required"}
|
||||||
|
if not isinstance(text, str) or not text.strip():
|
||||||
|
return 400, {"error": "text is required"}
|
||||||
|
try:
|
||||||
|
contact_id = self.send(recipient, text)
|
||||||
|
except ValueError as exc:
|
||||||
|
return 400, {"error": str(exc)}
|
||||||
|
return 200, {"ok": True, "contact_id": contact_id}
|
||||||
|
|
||||||
|
# ---- actions ----
|
||||||
|
|
||||||
|
def _address(self) -> tuple[int, dict]:
|
||||||
|
try:
|
||||||
|
link = self.daemon.request_address()
|
||||||
|
except RuntimeError as exc:
|
||||||
|
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
|
||||||
|
except Exception as exc: # TimeoutError, daemon error
|
||||||
|
return 502, {"error": f"address lookup failed: {exc}"[:300]}
|
||||||
|
if not isinstance(link, dict):
|
||||||
|
return 502, {"error": "address lookup returned no link"}
|
||||||
|
return 200, link
|
||||||
|
|
||||||
|
def send(self, recipient: str, text: str) -> str:
|
||||||
|
"""Resolve a recipient and enqueue the message. Returns the contact id."""
|
||||||
|
contact_id = self.resolve(recipient)
|
||||||
|
if contact_id is None:
|
||||||
|
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
||||||
|
self.daemon.enqueue(contact_id, text)
|
||||||
|
return contact_id
|
||||||
|
|
||||||
|
def resolve(self, recipient: str) -> str | None:
|
||||||
|
"""A numeric id (with or without `@`) or a known display name."""
|
||||||
|
recipient = str(recipient or "").strip()
|
||||||
|
if not recipient:
|
||||||
|
return None
|
||||||
|
bare = recipient.lstrip("@")
|
||||||
|
if bare.isdigit():
|
||||||
|
return bare
|
||||||
|
for contact in self.inbox.contacts():
|
||||||
|
if contact["display_name"] == recipient or contact["id"] == recipient:
|
||||||
|
return contact["id"]
|
||||||
|
return None
|
||||||
+24
-19
@@ -345,23 +345,6 @@ def run_gateway(
|
|||||||
scheduler.on_request_requeued = service.on_request_requeued
|
scheduler.on_request_requeued = service.on_request_requeued
|
||||||
service.start()
|
service.start()
|
||||||
|
|
||||||
from .gateway.bridge import MessagingBridge
|
|
||||||
|
|
||||||
bridge_cfg = cfg.get("bridge", {}) or {}
|
|
||||||
bridge = None
|
|
||||||
if bridge_cfg.get("enabled", True):
|
|
||||||
bridge = MessagingBridge(
|
|
||||||
service.outbound,
|
|
||||||
config=bridge_cfg,
|
|
||||||
address_provider=adapter.request_address,
|
|
||||||
)
|
|
||||||
service.observer = bridge.record_inbound
|
|
||||||
port = bridge.start()
|
|
||||||
print(
|
|
||||||
f"messaging bridge listening on http://{bridge.host}:{port} "
|
|
||||||
"(skills use messaging_bridge_url)"
|
|
||||||
)
|
|
||||||
|
|
||||||
if serve_dashboard:
|
if serve_dashboard:
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
@@ -386,11 +369,22 @@ def run_gateway(
|
|||||||
finally:
|
finally:
|
||||||
service.stop()
|
service.stop()
|
||||||
adapter.close()
|
adapter.close()
|
||||||
if bridge is not None:
|
|
||||||
bridge.stop()
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def run_bridge(scheduler: Scheduler, config: dict, name: str | None = None) -> int:
|
||||||
|
"""Run standalone third-party API bridges (SimpleX first).
|
||||||
|
|
||||||
|
Bridges are their own processes so generated skills never touch a system's
|
||||||
|
native protocol and the command gateway never grows read/send surface. See
|
||||||
|
`semif_agent.bridges`.
|
||||||
|
"""
|
||||||
|
from .bridges.registry import run_bridges
|
||||||
|
|
||||||
|
names = [name] if name else None
|
||||||
|
return run_bridges(config, names=names, trace=scheduler.trace)
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
argv = list(argv) if argv is not None else list(sys.argv[1:])
|
argv = list(argv) if argv is not None else list(sys.argv[1:])
|
||||||
config = load_config(_extract_config_path(argv))
|
config = load_config(_extract_config_path(argv))
|
||||||
@@ -430,6 +424,15 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
help="also serve the browser dashboard from the same process",
|
help="also serve the browser dashboard from the same process",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
bridge_p = sub.add_parser(
|
||||||
|
"bridge", help="run standalone third-party API bridges (SimpleX first)"
|
||||||
|
)
|
||||||
|
bridge_p.add_argument(
|
||||||
|
"--name",
|
||||||
|
default=None,
|
||||||
|
help="bridge service to run (default: all enabled)",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
scheduler, config = build_scheduler(config)
|
scheduler, config = build_scheduler(config)
|
||||||
|
|
||||||
@@ -461,6 +464,8 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
platform=args.platform,
|
platform=args.platform,
|
||||||
serve_dashboard=args.dashboard,
|
serve_dashboard=args.dashboard,
|
||||||
)
|
)
|
||||||
|
elif args.command == "bridge":
|
||||||
|
return run_bridge(scheduler, config, name=args.name)
|
||||||
else:
|
else:
|
||||||
parser.print_help()
|
parser.print_help()
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
+11
-7
@@ -24,6 +24,7 @@ from typing import Callable, NamedTuple
|
|||||||
|
|
||||||
from .decisions import Request
|
from .decisions import Request
|
||||||
from .skills import SkillDraft, tree_summary
|
from .skills import SkillDraft, tree_summary
|
||||||
|
from .bridges.registry import describe_bridges
|
||||||
|
|
||||||
DEFAULT_CONTRACT = Path(__file__).resolve().parent.parent / "SKILL.md"
|
DEFAULT_CONTRACT = Path(__file__).resolve().parent.parent / "SKILL.md"
|
||||||
DEFAULT_CONTEXT_WINDOW = 100000
|
DEFAULT_CONTEXT_WINDOW = 100000
|
||||||
@@ -633,12 +634,12 @@ BODY_DIRECTIVES = (
|
|||||||
"body.\n"
|
"body.\n"
|
||||||
"Declare the integration as a module-level `INTEGRATION` dict exactly as "
|
"Declare the integration as a module-level `INTEGRATION` dict exactly as "
|
||||||
"SKILL.md specifies: service, transport, config_vars.\n"
|
"SKILL.md specifies: service, transport, config_vars.\n"
|
||||||
"If this skill sends or reads SimpleX messages, call the messenger "
|
"If this skill interacts with one of the available bridge services listed "
|
||||||
"gateway's local HTTP bridge (the `messaging_bridge_url` value from "
|
"below, call that bridge over HTTP with the URL from its config variable — "
|
||||||
"`ctx.config`; endpoints: GET /inbox, GET /inbox/next?contact=, POST "
|
"never speak the service's native protocol directly (no WebSocket to "
|
||||||
"/send) — never open a WebSocket to the simplex-chat daemon. Resolve which "
|
"simplex-chat, no direct daemon access). Resolve which contact or "
|
||||||
"contact/conversation with a `ctx.engine` sub-decision, and send only when "
|
"conversation with a `ctx.engine` sub-decision, and send only when the "
|
||||||
"the request or requirements ask for it.\n"
|
"request or requirements ask for it.\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -682,6 +683,7 @@ def build_skill_body_prompt(
|
|||||||
f"Existing skills in this category: {existing}\n"
|
f"Existing skills in this category: {existing}\n"
|
||||||
f"Existing categories:\n{tree_summary(tree)}\n"
|
f"Existing categories:\n{tree_summary(tree)}\n"
|
||||||
f"{req_block}"
|
f"{req_block}"
|
||||||
|
f"{describe_bridges()}\n"
|
||||||
f"{BODY_DIRECTIVES}"
|
f"{BODY_DIRECTIVES}"
|
||||||
"Write the Python module body now. Reply with ONLY valid Python code "
|
"Write the Python module body now. Reply with ONLY valid Python code "
|
||||||
"defining `predict` and `act`. No prose, no markdown fences, no JSON."
|
"defining `predict` and `act`. No prose, no markdown fences, no JSON."
|
||||||
@@ -995,6 +997,7 @@ def _retry_prompt(
|
|||||||
f"Skill name: {draft.name}\n"
|
f"Skill name: {draft.name}\n"
|
||||||
f"Skill description: {draft.description}\n"
|
f"Skill description: {draft.description}\n"
|
||||||
f"{_requirements_block(requirements)}"
|
f"{_requirements_block(requirements)}"
|
||||||
|
f"{describe_bridges()}\n"
|
||||||
f"{BODY_DIRECTIVES}"
|
f"{BODY_DIRECTIVES}"
|
||||||
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||||
"no markdown fences, no JSON."
|
"no markdown fences, no JSON."
|
||||||
@@ -1067,7 +1070,7 @@ ELICITATION_EXAMPLES = [
|
|||||||
"How does it authenticate with the service, and should that credential come from the app's config?",
|
"How does it authenticate with the service, and should that credential come from the app's config?",
|
||||||
"What does a successful run look like — what should it report back to you?",
|
"What does a successful run look like — what should it report back to you?",
|
||||||
"If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?",
|
"If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?",
|
||||||
"Should this skill send or read SimpleX messages through the messaging gateway, and if so which conversation (resolved by contact name)?",
|
"Should this skill send or read SimpleX messages through the simplex bridge, and if so which conversation (resolved by contact name)?",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -1122,6 +1125,7 @@ def build_elicitation_prompt(
|
|||||||
f"Skill description: {draft.description}\n"
|
f"Skill description: {draft.description}\n"
|
||||||
f"Existing skills in this category: {existing}\n"
|
f"Existing skills in this category: {existing}\n"
|
||||||
f"Existing categories:\n{tree_summary(tree)}\n"
|
f"Existing categories:\n{tree_summary(tree)}\n"
|
||||||
|
f"{describe_bridges()}\n"
|
||||||
)
|
)
|
||||||
return [
|
return [
|
||||||
{"role": "system", "content": system},
|
{"role": "system", "content": system},
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
"""Messaging gateway: external messenger intake/reply for the SemIf agent.
|
"""Messaging gateway: external messenger intake/reply for the SemIf agent.
|
||||||
|
|
||||||
A `GatewayAdapter` owns a transport (SimpleX first), and `GatewayService`
|
The gateway is the agent's **command** surface and nothing else. A
|
||||||
maps inbound text onto the scheduler's existing gate/score/queue/dispatch
|
`GatewayAdapter` owns a transport (SimpleX first), and `GatewayService` maps
|
||||||
pipeline and routes results, questions, and repairs back to the originating
|
inbound text onto the scheduler's existing gate/score/queue/dispatch pipeline
|
||||||
chat. See `base.py` for the contract.
|
and routes results, questions, and repairs back to the originating chat.
|
||||||
|
|
||||||
|
Messaging *UX* — invite links, reading a contact's messages, composing sends —
|
||||||
|
does not live here; it belongs to the standalone bridge services in
|
||||||
|
`semif_agent.bridges`. Keeping the command surface free of that functionality
|
||||||
|
is a hard boundary (see AGENTS.md "gateway isolation").
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||||
from .bridge import MessagingBridge, MessagingInbox, start_bridge
|
|
||||||
from .service import GatewayService
|
from .service import GatewayService
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -15,8 +19,5 @@ __all__ = [
|
|||||||
"InboundMessage",
|
"InboundMessage",
|
||||||
"OutboundMessage",
|
"OutboundMessage",
|
||||||
"GatewayService",
|
"GatewayService",
|
||||||
"MessagingBridge",
|
|
||||||
"MessagingInbox",
|
|
||||||
"start_bridge",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
+11
-10
@@ -1,15 +1,16 @@
|
|||||||
"""The messaging-gateway adapter contract.
|
"""The messenger command-gateway adapter contract.
|
||||||
|
|
||||||
An adapter owns one transport (SimpleX WebSocket, and later Telegram, Signal,
|
An adapter owns one command transport (SimpleX WebSocket, and later Telegram,
|
||||||
...). It delivers inbound text as `InboundMessage` and drains outbound replies
|
Signal, ...). It delivers inbound text as `InboundMessage` and drains outbound
|
||||||
from a stdlib queue. Everything about the SemIf scheduler — gating, scoring,
|
replies from a stdlib queue. Everything about the SemIf scheduler — gating,
|
||||||
queueing, run ownership, questions, repairs — lives in `GatewayService`; an
|
scoring, queueing, run ownership, questions, repairs — lives in `GatewayService`;
|
||||||
adapter must not know it exists.
|
an adapter must not know it exists. Neither knows anything about messaging UX
|
||||||
|
(invite links, reading, composing): that is the bridge services' job.
|
||||||
|
|
||||||
The transport is intentionally a plain `queue.Queue` bridge: the adapter's
|
The transport is intentionally a plain `queue.Queue`: the adapter's event loop
|
||||||
event loop puts an outbound message into the queue, the service puts replies
|
puts an outbound message into the queue, the service puts replies into it. This
|
||||||
into it. This keeps scheduler work (which is synchronous and can block on the
|
keeps scheduler work (which is synchronous and can block on the decision engine)
|
||||||
decision engine) off the adapter's event loop.
|
off the adapter's event loop.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -1,276 +0,0 @@
|
|||||||
"""Local HTTP bridge that exposes the messenger gateway to skill bodies.
|
|
||||||
|
|
||||||
A skill never opens a WebSocket to the `simplex-chat` daemon itself. Instead
|
|
||||||
the running gateway serves this small stdlib HTTP API on localhost:
|
|
||||||
|
|
||||||
GET /health {"ok": true, "platform": "simplex"}
|
|
||||||
GET /contacts {"contacts": [{"id", "display_name"}]}
|
|
||||||
GET /inbox peek buffered inbound messages
|
|
||||||
GET /inbox/next?contact=<id> pop the oldest unread message (optionally
|
|
||||||
for one contact) -> {"message": {...}|null}
|
|
||||||
GET /address the bot's user contact link, creating it if
|
|
||||||
needed -> {"short_link", "full_link", "created"}
|
|
||||||
POST /send {"recipient": "<id|name>", "text": "..."}
|
|
||||||
|
|
||||||
The bridge owns the read cursor (a bounded FIFO of authorized inbound DMs), so
|
|
||||||
a read skill stays stateless. Outbound sends reuse the gateway's existing
|
|
||||||
`OutboundMessage` queue, i.e. the same transport that already replies to chats.
|
|
||||||
The bridge is deliberately the only messaging surface a generated body touches,
|
|
||||||
which keeps bodies stdlib-only and their hermetic tests ordinary loopback HTTP.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import queue
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
from collections import deque
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
||||||
from urllib.parse import parse_qs, urlparse
|
|
||||||
|
|
||||||
from .base import InboundMessage, OutboundMessage
|
|
||||||
|
|
||||||
|
|
||||||
class MessagingInbox:
|
|
||||||
"""Thread-safe, bounded FIFO of buffered inbound messages + contacts."""
|
|
||||||
|
|
||||||
def __init__(self, max_size: int = 100):
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self._items: deque[dict] = deque()
|
|
||||||
self._max = max(1, int(max_size))
|
|
||||||
self._contacts: dict[str, str] = {}
|
|
||||||
|
|
||||||
def record(self, msg: InboundMessage) -> dict:
|
|
||||||
contact_id = str(msg.contact_id or msg.chat_id)
|
|
||||||
entry = {
|
|
||||||
"id": uuid.uuid4().hex[:12],
|
|
||||||
"contact_id": contact_id,
|
|
||||||
"display_name": msg.display_name or "",
|
|
||||||
"text": msg.text,
|
|
||||||
"received_at": time.time(),
|
|
||||||
}
|
|
||||||
with self._lock:
|
|
||||||
if msg.display_name:
|
|
||||||
self._contacts[contact_id] = msg.display_name
|
|
||||||
else:
|
|
||||||
self._contacts.setdefault(contact_id, "")
|
|
||||||
self._items.append(entry)
|
|
||||||
while len(self._items) > self._max:
|
|
||||||
self._items.popleft()
|
|
||||||
return entry
|
|
||||||
|
|
||||||
def peek(self) -> list[dict]:
|
|
||||||
with self._lock:
|
|
||||||
return list(self._items)
|
|
||||||
|
|
||||||
def pop(self, contact_id: str | None = None) -> dict | None:
|
|
||||||
with self._lock:
|
|
||||||
if contact_id is None:
|
|
||||||
return self._items.popleft() if self._items else None
|
|
||||||
target = str(contact_id)
|
|
||||||
for index, entry in enumerate(self._items):
|
|
||||||
if entry["contact_id"] == target:
|
|
||||||
del self._items[index]
|
|
||||||
return entry
|
|
||||||
return None
|
|
||||||
|
|
||||||
def contacts(self) -> list[dict]:
|
|
||||||
with self._lock:
|
|
||||||
return [
|
|
||||||
{"id": contact_id, "display_name": name}
|
|
||||||
for contact_id, name in self._contacts.items()
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
class MessagingBridge:
|
|
||||||
"""The gateway's localhost messaging API for skills.
|
|
||||||
|
|
||||||
Serves the endpoints above in a background thread. `outbound` is the
|
|
||||||
adapter's send queue (the gateway drains it); posting an `OutboundMessage`
|
|
||||||
onto it is exactly how replies are sent. `config` is the
|
|
||||||
`gateway.<platform>.bridge` block: `host` (default 127.0.0.1), `port`
|
|
||||||
(default 5227, `0` picks an ephemeral port), `token` (optional shared
|
|
||||||
secret checked against the `X-Semif-Token` header), `max_inbox`.
|
|
||||||
|
|
||||||
`address_provider` is an optional zero-arg callable returning
|
|
||||||
`{short_link, full_link, created}` — the gateway wires it to the adapter's
|
|
||||||
contact-address lookup. When absent, `GET /address` answers 503 so a skill
|
|
||||||
reports that the link is unavailable rather than inventing one.
|
|
||||||
"""
|
|
||||||
|
|
||||||
name = "simplex"
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
outbound: "queue.Queue[OutboundMessage | None]",
|
|
||||||
config: dict | None = None,
|
|
||||||
address_provider=None,
|
|
||||||
):
|
|
||||||
cfg = config or {}
|
|
||||||
self.host = str(cfg.get("host", "127.0.0.1"))
|
|
||||||
self.port = int(cfg.get("port", 5227))
|
|
||||||
self.token = str(cfg.get("token", "") or "")
|
|
||||||
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
|
|
||||||
self.outbound = outbound
|
|
||||||
self.address_provider = address_provider
|
|
||||||
self._server: ThreadingHTTPServer | None = None
|
|
||||||
self._thread: threading.Thread | None = None
|
|
||||||
|
|
||||||
# ---- lifecycle ----
|
|
||||||
|
|
||||||
def start(self) -> int:
|
|
||||||
"""Start serving; returns the bound port (useful when `port` is 0)."""
|
|
||||||
handler = type("BridgeHandler", (_BridgeHandler,), {})
|
|
||||||
server = ThreadingHTTPServer((self.host, self.port), handler)
|
|
||||||
server.bridge = self # type: ignore[attr-defined]
|
|
||||||
self._server = server
|
|
||||||
self._thread = threading.Thread(
|
|
||||||
target=server.serve_forever, name="messaging-bridge", daemon=True
|
|
||||||
)
|
|
||||||
self._thread.start()
|
|
||||||
return int(server.server_address[1])
|
|
||||||
|
|
||||||
def stop(self) -> None:
|
|
||||||
server, self._server = self._server, None
|
|
||||||
if server is not None:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
thread, self._thread = self._thread, None
|
|
||||||
if thread is not None:
|
|
||||||
thread.join(timeout=2.0)
|
|
||||||
|
|
||||||
# ---- used by the gateway service ----
|
|
||||||
|
|
||||||
def record_inbound(self, msg: InboundMessage) -> None:
|
|
||||||
"""Observer callback: buffer an authorized inbound message for reads."""
|
|
||||||
self.inbox.record(msg)
|
|
||||||
|
|
||||||
def send(self, recipient: str, text: str) -> str:
|
|
||||||
"""Resolve a recipient and enqueue the message. Returns the contact id."""
|
|
||||||
contact_id = self.resolve(recipient)
|
|
||||||
if contact_id is None:
|
|
||||||
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
|
||||||
self.outbound.put(OutboundMessage(chat_id=contact_id, text=text))
|
|
||||||
return contact_id
|
|
||||||
|
|
||||||
def resolve(self, recipient: str) -> str | None:
|
|
||||||
"""A numeric id (with or without `@`) or a known display name."""
|
|
||||||
recipient = str(recipient or "").strip()
|
|
||||||
if not recipient:
|
|
||||||
return None
|
|
||||||
bare = recipient.lstrip("@")
|
|
||||||
if bare.isdigit():
|
|
||||||
return bare
|
|
||||||
for contact in self.inbox.contacts():
|
|
||||||
if contact["display_name"] == recipient or contact["id"] == recipient:
|
|
||||||
return contact["id"]
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
class _BridgeHandler(BaseHTTPRequestHandler):
|
|
||||||
"""Request handler; the owning bridge is on `self.server.bridge`."""
|
|
||||||
|
|
||||||
def log_message(self, *args) -> None: # silence the default stderr spam
|
|
||||||
pass
|
|
||||||
|
|
||||||
# ---- helpers ----
|
|
||||||
|
|
||||||
def _bridge(self) -> MessagingBridge:
|
|
||||||
return self.server.bridge # type: ignore[attr-defined]
|
|
||||||
|
|
||||||
def _authorized(self) -> bool:
|
|
||||||
token = self._bridge().token
|
|
||||||
if not token:
|
|
||||||
return True
|
|
||||||
return self.headers.get("X-Semif-Token") == token
|
|
||||||
|
|
||||||
def _json(self, status: int, payload: dict) -> None:
|
|
||||||
body = json.dumps(payload).encode("utf-8")
|
|
||||||
self.send_response(status)
|
|
||||||
self.send_header("Content-Type", "application/json")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body)
|
|
||||||
|
|
||||||
def _require_auth(self) -> bool:
|
|
||||||
if self._authorized():
|
|
||||||
return True
|
|
||||||
self._json(401, {"error": "unauthorized"})
|
|
||||||
return False
|
|
||||||
|
|
||||||
# ---- routes ----
|
|
||||||
|
|
||||||
def do_GET(self) -> None:
|
|
||||||
if not self._require_auth():
|
|
||||||
return
|
|
||||||
url = urlparse(self.path)
|
|
||||||
bridge = self._bridge()
|
|
||||||
if url.path == "/health":
|
|
||||||
self._json(200, {"ok": True, "platform": bridge.name})
|
|
||||||
elif url.path == "/contacts":
|
|
||||||
self._json(200, {"contacts": bridge.inbox.contacts()})
|
|
||||||
elif url.path == "/inbox":
|
|
||||||
self._json(200, {"messages": bridge.inbox.peek()})
|
|
||||||
elif url.path == "/inbox/next":
|
|
||||||
contact = (parse_qs(url.query).get("contact") or [None])[0]
|
|
||||||
self._json(200, {"message": bridge.inbox.pop(contact)})
|
|
||||||
elif url.path == "/address":
|
|
||||||
provider = bridge.address_provider
|
|
||||||
if provider is None:
|
|
||||||
self._json(503, {"error": "address lookup is not available"})
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
link = provider()
|
|
||||||
except Exception as exc:
|
|
||||||
self._json(502, {"error": f"address lookup failed: {exc}"[:300]})
|
|
||||||
return
|
|
||||||
if not isinstance(link, dict):
|
|
||||||
self._json(502, {"error": "address lookup returned no link"})
|
|
||||||
return
|
|
||||||
self._json(200, link)
|
|
||||||
else:
|
|
||||||
self._json(404, {"error": "not found"})
|
|
||||||
|
|
||||||
def do_POST(self) -> None:
|
|
||||||
if not self._require_auth():
|
|
||||||
return
|
|
||||||
url = urlparse(self.path)
|
|
||||||
if url.path != "/send":
|
|
||||||
self._json(404, {"error": "not found"})
|
|
||||||
return
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
raw = self.rfile.read(length) if length else b""
|
|
||||||
try:
|
|
||||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
|
||||||
except ValueError:
|
|
||||||
self._json(400, {"error": "invalid JSON body"})
|
|
||||||
return
|
|
||||||
if not isinstance(payload, dict):
|
|
||||||
self._json(400, {"error": "body must be a JSON object"})
|
|
||||||
return
|
|
||||||
recipient = payload.get("recipient")
|
|
||||||
text = payload.get("text")
|
|
||||||
if not isinstance(recipient, str) or not recipient.strip():
|
|
||||||
self._json(400, {"error": "recipient is required"})
|
|
||||||
return
|
|
||||||
if not isinstance(text, str) or not text.strip():
|
|
||||||
self._json(400, {"error": "text is required"})
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
contact_id = self._bridge().send(recipient, text)
|
|
||||||
except ValueError as exc:
|
|
||||||
self._json(400, {"error": str(exc)})
|
|
||||||
return
|
|
||||||
self._json(200, {"ok": True, "contact_id": contact_id})
|
|
||||||
|
|
||||||
|
|
||||||
def start_bridge(
|
|
||||||
outbound: "queue.Queue[OutboundMessage | None]",
|
|
||||||
config: dict | None = None,
|
|
||||||
address_provider=None,
|
|
||||||
) -> tuple[MessagingBridge, int]:
|
|
||||||
bridge = MessagingBridge(outbound, config=config, address_provider=address_provider)
|
|
||||||
port = bridge.start()
|
|
||||||
return bridge, port
|
|
||||||
@@ -59,13 +59,6 @@ class GatewayService:
|
|||||||
self.home_channel = str(cfg.get("home_channel", "") or "")
|
self.home_channel = str(cfg.get("home_channel", "") or "")
|
||||||
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
|
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
|
||||||
self.poll_interval = float(poll_interval)
|
self.poll_interval = float(poll_interval)
|
||||||
inbox_cfg = cfg.get("inbox", {}) or {}
|
|
||||||
#: When false the gateway only buffers inbound messages (for a read
|
|
||||||
#: skill to pull) instead of dispatching them as scheduler requests.
|
|
||||||
self.inbox_dispatch = bool(inbox_cfg.get("dispatch", True))
|
|
||||||
#: Optional callback invoked for every authorized inbound message,
|
|
||||||
#: before routing. The bridge uses it to fill its inbox.
|
|
||||||
self.observer = None
|
|
||||||
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue()
|
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue()
|
||||||
self._owners: dict[str, str] = {}
|
self._owners: dict[str, str] = {}
|
||||||
self._parents: dict[str, str] = {}
|
self._parents: dict[str, str] = {}
|
||||||
@@ -111,15 +104,8 @@ class GatewayService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def handle_inbound(self, msg: InboundMessage) -> None:
|
def handle_inbound(self, msg: InboundMessage) -> None:
|
||||||
"""Handle one authorized inbound message. Called by the adapter."""
|
"""Handle one authorized inbound command. Called by the adapter."""
|
||||||
with self._route_lock:
|
with self._route_lock:
|
||||||
if self.observer is not None:
|
|
||||||
self.observer(msg)
|
|
||||||
if not self.inbox_dispatch:
|
|
||||||
# Pull mode: buffer only (the observer recorded it); a read
|
|
||||||
# skill will consume it later. No scheduler request, no reply.
|
|
||||||
self.drain()
|
|
||||||
return
|
|
||||||
reply_to = msg.chat_id
|
reply_to = msg.chat_id
|
||||||
pending = self.scheduler.pending
|
pending = self.scheduler.pending
|
||||||
if pending is not None and self._pending_owner is None:
|
if pending is not None and self._pending_owner is None:
|
||||||
|
|||||||
+52
-273
@@ -1,84 +1,54 @@
|
|||||||
"""SimpleX Chat gateway adapter.
|
"""SimpleX command-gateway adapter.
|
||||||
|
|
||||||
Connects to the local `simplex-chat` daemon (`simplex-chat -p 5225`) over its
|
The gateway is the agent's **command** surface: allowlisted contacts DM the bot
|
||||||
JSON WebSocket API, receives DM text from allowlisted contacts, and sends
|
and their text is fed to the scheduler, whose reply is sent back. All the
|
||||||
replies with the structured `/_send` command. Groups, attachments, reactions,
|
messaging *UX* surface (invite links, reading a contact's messages, composing on
|
||||||
and typing are deliberately out of scope for the first cut.
|
the user's behalf) lives in separate bridge services, never here — see
|
||||||
|
AGENTS.md "gateway isolation".
|
||||||
|
|
||||||
`websockets` is imported lazily inside the functions that need it so this
|
This adapter is the policy layer over the neutral `SimplexDaemon` transport in
|
||||||
module (and the gateway package) stays importable on a machine without the
|
`semif_agent.simplex_ws`: it applies the allowlist, batches rapid messages, and
|
||||||
dependency; `check_requirements()` gates the gateway off with an install hint.
|
hands authorized text to the scheduler. It must not grow address/inbox/send
|
||||||
|
endpoints; those belong to a bridge.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import concurrent.futures
|
|
||||||
import json
|
|
||||||
import queue
|
import queue
|
||||||
import random
|
|
||||||
import threading
|
import threading
|
||||||
from typing import Any
|
|
||||||
|
from semif_agent.simplex_ws import SimplexDaemon, send_text_command
|
||||||
|
|
||||||
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
from .base import GatewayAdapter, InboundMessage, OutboundMessage
|
||||||
|
|
||||||
|
|
||||||
def contact_link(resp: dict) -> dict:
|
|
||||||
"""Pull `{connShortLink, connFullLink}` out of a daemon address response.
|
|
||||||
|
|
||||||
`/_show_address` nests it as `contactLink.connLinkContact`; `/_address`
|
|
||||||
returns it directly as `connLinkContact`. Tolerate both (and a flat
|
|
||||||
`contactLink`) so the adapter reads the real daemon shape rather than
|
|
||||||
calling `/_address` again on an existing link and reporting nothing.
|
|
||||||
"""
|
|
||||||
for candidate in (
|
|
||||||
(resp.get("contactLink") or {}).get("connLinkContact"),
|
|
||||||
resp.get("connLinkContact"),
|
|
||||||
resp.get("contactLink"),
|
|
||||||
resp,
|
|
||||||
):
|
|
||||||
if isinstance(candidate, dict) and (
|
|
||||||
candidate.get("connShortLink") or candidate.get("connFullLink")
|
|
||||||
):
|
|
||||||
return candidate
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
class SimplexAdapter(GatewayAdapter):
|
class SimplexAdapter(GatewayAdapter):
|
||||||
name = "simplex"
|
name = "simplex"
|
||||||
|
|
||||||
def __init__(self, cfg: dict | None = None, trace=None):
|
def __init__(self, cfg: dict | None = None, trace=None):
|
||||||
cfg = cfg or {}
|
cfg = cfg or {}
|
||||||
self.ws_url = str(cfg.get("ws_url", "ws://127.0.0.1:5225"))
|
|
||||||
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
|
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
|
||||||
self.allow_all_users = bool(cfg.get("allow_all_users", False))
|
self.allow_all_users = bool(cfg.get("allow_all_users", False))
|
||||||
self.auto_accept = bool(cfg.get("auto_accept", True))
|
|
||||||
self.batch_delay = float(cfg.get("text_batch_delay", 0.8))
|
self.batch_delay = float(cfg.get("text_batch_delay", 0.8))
|
||||||
self.user_id = int(cfg.get("user_id", 1))
|
self.daemon = SimplexDaemon(
|
||||||
reconnect = cfg.get("reconnect", {}) or {}
|
cfg.get("ws_url", "ws://127.0.0.1:5225"),
|
||||||
self.reconnect_initial = float(reconnect.get("initial", 1.0))
|
user_id=int(cfg.get("user_id", 1)),
|
||||||
self.reconnect_max = float(reconnect.get("max", 60.0))
|
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||||
self.reconnect_jitter = float(reconnect.get("jitter", 0.2))
|
reconnect=cfg.get("reconnect", {}) or {},
|
||||||
self.trace = trace
|
trace=trace,
|
||||||
self._corr = 0
|
name=self.name,
|
||||||
self._pending: dict[str, asyncio.Future] = {}
|
)
|
||||||
self._loop: asyncio.AbstractEventLoop | None = None
|
self.ws_url = self.daemon.ws_url
|
||||||
self._ws = None
|
|
||||||
self._buffers: dict[str, str] = {}
|
self._buffers: dict[str, str] = {}
|
||||||
self._buffered: dict[str, InboundMessage] = {}
|
self._buffered: dict[str, InboundMessage] = {}
|
||||||
self._flush_tasks: dict[str, asyncio.Task] = {}
|
self._flush_tasks: dict[str, asyncio.Task] = {}
|
||||||
self._stop = threading.Event()
|
self._on_inbound = None
|
||||||
|
|
||||||
# ---- requirements ----
|
# ---- requirements ----
|
||||||
|
|
||||||
def check_requirements(self) -> tuple[bool, str | None]:
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
if not self.ws_url:
|
return self.daemon.check_requirements()
|
||||||
return False, "gateway.simplex.ws_url is required"
|
|
||||||
try:
|
|
||||||
import websockets # noqa: F401
|
|
||||||
except ImportError:
|
|
||||||
return False, "pip install websockets"
|
|
||||||
return True, None
|
|
||||||
|
|
||||||
# ---- authorization ----
|
# ---- authorization ----
|
||||||
|
|
||||||
@@ -99,232 +69,47 @@ class SimplexAdapter(GatewayAdapter):
|
|||||||
on_inbound,
|
on_inbound,
|
||||||
outbound: "queue.Queue[OutboundMessage | None]",
|
outbound: "queue.Queue[OutboundMessage | None]",
|
||||||
) -> None:
|
) -> None:
|
||||||
asyncio.run(self._serve(on_inbound, outbound))
|
self._on_inbound = on_inbound
|
||||||
|
|
||||||
|
def _pump() -> None:
|
||||||
|
# Translate the service's OutboundMessage queue onto the daemon's
|
||||||
|
# (chat_id, text) queue without letting scheduler work touch the
|
||||||
|
# daemon's event loop.
|
||||||
|
while True:
|
||||||
|
message = outbound.get()
|
||||||
|
if message is None:
|
||||||
|
self.daemon.enqueue(None)
|
||||||
|
return
|
||||||
|
self.daemon.enqueue(message.chat_id, message.text)
|
||||||
|
|
||||||
|
threading.Thread(target=_pump, name="simplex-outbound-pump", daemon=True).start()
|
||||||
|
self.daemon.run(self._on_item)
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._stop.set()
|
self.daemon.close()
|
||||||
|
|
||||||
async def _serve(self, on_inbound, outbound: "queue.Queue") -> None:
|
|
||||||
import websockets
|
|
||||||
|
|
||||||
self._loop = asyncio.get_running_loop()
|
|
||||||
backoff = self.reconnect_initial
|
|
||||||
while not self._stop.is_set():
|
|
||||||
try:
|
|
||||||
async with websockets.connect(self.ws_url, max_size=None) as ws:
|
|
||||||
self._ws = ws
|
|
||||||
backoff = self.reconnect_initial
|
|
||||||
self._event("gateway_connected", url=self.ws_url)
|
|
||||||
sender = asyncio.create_task(self._outbound_loop(ws, outbound))
|
|
||||||
try:
|
|
||||||
async for raw in ws:
|
|
||||||
await self._consume(raw, on_inbound, ws)
|
|
||||||
finally:
|
|
||||||
sender.cancel()
|
|
||||||
except Exception as exc: # reconnect on any transport failure
|
|
||||||
self._event("gateway_error", message=str(exc)[:300])
|
|
||||||
finally:
|
|
||||||
self._ws = None
|
|
||||||
self._fail_pending("simplex gateway disconnected")
|
|
||||||
delay = min(backoff, self.reconnect_max)
|
|
||||||
delay *= 1 + random.random() * self.reconnect_jitter
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(self._stop_wait(), timeout=delay)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass
|
|
||||||
backoff = min(max(delay, self.reconnect_initial), self.reconnect_max)
|
|
||||||
|
|
||||||
async def _stop_wait(self) -> None:
|
|
||||||
while not self._stop.is_set():
|
|
||||||
await asyncio.sleep(0.2)
|
|
||||||
|
|
||||||
async def _outbound_loop(self, ws, outbound: "queue.Queue") -> None:
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
while True:
|
|
||||||
message = await loop.run_in_executor(None, outbound.get)
|
|
||||||
if message is None:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
await self._send(ws, message)
|
|
||||||
except Exception as exc:
|
|
||||||
self._event("gateway_error", phase="send", message=str(exc)[:300])
|
|
||||||
|
|
||||||
async def _send(self, ws, message: OutboundMessage) -> None:
|
|
||||||
command = self.send_command(message.chat_id, message.text)
|
|
||||||
self._corr += 1
|
|
||||||
await ws.send(json.dumps({"corrId": f"sf-{self._corr}", "cmd": command}))
|
|
||||||
self._event("gateway_sent", chat_id=message.chat_id, chars=len(message.text))
|
|
||||||
|
|
||||||
def send_command(self, chat_id: str, text: str) -> str:
|
def send_command(self, chat_id: str, text: str) -> str:
|
||||||
"""Structured APISendMessages command for a direct contact.
|
return send_text_command(chat_id, text)
|
||||||
|
|
||||||
The CLI shortcut `@<id> <text>` is silently rejected over WebSocket
|
|
||||||
(it resolves the ref as a display name), so always use the JSON form.
|
|
||||||
"""
|
|
||||||
composed = [{"msgContent": {"type": "text", "text": text}}]
|
|
||||||
return f"/_send @{chat_id} json {json.dumps(composed)}"
|
|
||||||
|
|
||||||
# ---- request/response + address ----
|
|
||||||
|
|
||||||
async def _roundtrip(self, command: str, timeout: float) -> dict:
|
|
||||||
"""Send a command and await its correlated `resp` from the event loop."""
|
|
||||||
ws = self._ws
|
|
||||||
if ws is None or self._loop is None:
|
|
||||||
raise RuntimeError("simplex gateway is not connected")
|
|
||||||
self._corr += 1
|
|
||||||
corr = f"req-{self._corr}"
|
|
||||||
future = self._loop.create_future()
|
|
||||||
self._pending[corr] = future
|
|
||||||
await ws.send(json.dumps({"corrId": corr, "cmd": command}))
|
|
||||||
try:
|
|
||||||
return await asyncio.wait_for(future, timeout)
|
|
||||||
finally:
|
|
||||||
self._pending.pop(corr, None)
|
|
||||||
|
|
||||||
def _fail_pending(self, reason: str) -> None:
|
|
||||||
pending, self._pending = self._pending, {}
|
|
||||||
for future in pending.values():
|
|
||||||
if not future.done():
|
|
||||||
future.set_exception(RuntimeError(reason))
|
|
||||||
|
|
||||||
async def address(self, timeout: float = 20.0) -> dict:
|
|
||||||
"""Show the bot's user contact address, creating it on first call.
|
|
||||||
|
|
||||||
Mirrors `scripts/simplex-address.py`: `/_show_address <userId>` returns an
|
|
||||||
existing link; when there is none, `/_address <userId>` creates one.
|
|
||||||
Returns `{short_link, full_link, created}`.
|
|
||||||
"""
|
|
||||||
resp = await self._roundtrip(f"/_show_address {self.user_id}", timeout)
|
|
||||||
link: dict = {}
|
|
||||||
created = False
|
|
||||||
if resp.get("type") == "userContactLink":
|
|
||||||
link = contact_link(resp)
|
|
||||||
if not (link.get("connShortLink") or link.get("connFullLink")):
|
|
||||||
resp = await self._roundtrip(f"/_address {self.user_id}", timeout)
|
|
||||||
link = contact_link(resp)
|
|
||||||
created = True
|
|
||||||
return {
|
|
||||||
"short_link": link.get("connShortLink") or "",
|
|
||||||
"full_link": link.get("connFullLink") or "",
|
|
||||||
"created": created,
|
|
||||||
}
|
|
||||||
|
|
||||||
def request_address(self, timeout: float = 20.0) -> dict:
|
|
||||||
"""Thread-safe address lookup for callers off the event loop (the bridge).
|
|
||||||
|
|
||||||
Raises `RuntimeError` when no live connection exists and `TimeoutError`
|
|
||||||
when the daemon does not answer in time — never a fabricated link.
|
|
||||||
"""
|
|
||||||
loop = self._loop
|
|
||||||
if loop is None or not loop.is_running():
|
|
||||||
raise RuntimeError("simplex gateway is not connected")
|
|
||||||
future = asyncio.run_coroutine_threadsafe(self.address(timeout=timeout), loop)
|
|
||||||
try:
|
|
||||||
return future.result(timeout=timeout + 5.0)
|
|
||||||
except concurrent.futures.TimeoutError as exc:
|
|
||||||
future.cancel()
|
|
||||||
raise TimeoutError("simplex address request timed out") from exc
|
|
||||||
|
|
||||||
# ---- inbound ----
|
# ---- inbound ----
|
||||||
|
|
||||||
async def _consume(self, raw: Any, on_inbound, ws) -> None:
|
def _on_item(self, message: dict) -> None:
|
||||||
try:
|
contact_id = str(message.get("contact_id") or "")
|
||||||
data = json.loads(raw)
|
display_name = message.get("display_name")
|
||||||
except (TypeError, ValueError):
|
|
||||||
return
|
|
||||||
corr_id = data.get("corrId")
|
|
||||||
if corr_id is not None:
|
|
||||||
# A correlated command response (round-trip): resolve the waiting
|
|
||||||
# requester. Fire-and-forget commands (`_send`, `_accept`) never
|
|
||||||
# register a future, so their responses are dropped here as before.
|
|
||||||
future = self._pending.pop(corr_id, None)
|
|
||||||
if future is not None and not future.done():
|
|
||||||
future.set_result(data.get("resp") or {})
|
|
||||||
return
|
|
||||||
resp = data.get("resp") or {}
|
|
||||||
kind = resp.get("type")
|
|
||||||
if kind == "receivedContactRequest":
|
|
||||||
await self._maybe_accept(ws, resp)
|
|
||||||
return
|
|
||||||
if kind != "newChatItems":
|
|
||||||
return
|
|
||||||
for item in resp.get("chatItems", []) or []:
|
|
||||||
message = self._parse_chat_item(item)
|
|
||||||
if message is not None:
|
|
||||||
self._schedule_flush(message, on_inbound)
|
|
||||||
|
|
||||||
def _parse_chat_item(self, item: dict) -> InboundMessage | None:
|
|
||||||
chat_info = item.get("chatInfo") or {}
|
|
||||||
if chat_info.get("type") != "direct":
|
|
||||||
return None
|
|
||||||
chat_item = item.get("chatItem") or {}
|
|
||||||
direction = (chat_item.get("chatDir") or {}).get("type", "")
|
|
||||||
if direction and "Snd" in direction:
|
|
||||||
return None # own echo
|
|
||||||
content = chat_item.get("content") or {}
|
|
||||||
# simplex-chat v7 tags the content union by constructor: a received text
|
|
||||||
# message is {"type": "rcvMsgContent", "msgContent": {"type": "text",
|
|
||||||
# "text": ...}}. The daemon's DB/Aeson encoding nests under the
|
|
||||||
# constructor key instead ({"rcvMsgContent": {"msgContent": ...}}), so
|
|
||||||
# accept both shapes.
|
|
||||||
if content.get("type") == "rcvMsgContent":
|
|
||||||
msg_content = content.get("msgContent") or {}
|
|
||||||
elif isinstance(content.get("rcvMsgContent"), dict):
|
|
||||||
msg_content = content["rcvMsgContent"].get("msgContent") or {}
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
if msg_content.get("type") != "text":
|
|
||||||
return None
|
|
||||||
text = str(msg_content.get("text", "")).strip()
|
|
||||||
if not text:
|
|
||||||
return None
|
|
||||||
contact = chat_info.get("contact") or {}
|
|
||||||
contact_id = str(contact.get("contactId") or chat_info.get("chatId") or "")
|
|
||||||
profile = contact.get("profile") or {}
|
|
||||||
# v7's Contact has `displayName: null`; the real peer name lives in
|
|
||||||
# `profile.displayName`, and `localDisplayName` is auto-suffixed on
|
|
||||||
# collisions (e.g. a second contact becomes `pepper_1`).
|
|
||||||
display_name = (
|
|
||||||
profile.get("displayName")
|
|
||||||
or contact.get("displayName")
|
|
||||||
or contact.get("localDisplayName")
|
|
||||||
)
|
|
||||||
if not contact_id:
|
|
||||||
return None
|
|
||||||
if not self.is_authorized(contact_id, display_name):
|
if not self.is_authorized(contact_id, display_name):
|
||||||
self._event("gateway_denied", contact_id=contact_id, display_name=display_name)
|
self.daemon._event(
|
||||||
return None
|
"gateway_denied", contact_id=contact_id, display_name=display_name
|
||||||
return InboundMessage(
|
)
|
||||||
text=text,
|
return
|
||||||
|
inbound = InboundMessage(
|
||||||
|
text=message.get("text") or "",
|
||||||
chat_id=contact_id,
|
chat_id=contact_id,
|
||||||
chat_type="dm",
|
chat_type="dm",
|
||||||
contact_id=contact_id,
|
contact_id=contact_id,
|
||||||
display_name=display_name,
|
display_name=display_name,
|
||||||
raw=item,
|
raw=message.get("raw") or {},
|
||||||
)
|
|
||||||
|
|
||||||
async def _maybe_accept(self, ws, resp: dict) -> None:
|
|
||||||
if not self.auto_accept:
|
|
||||||
return
|
|
||||||
req = resp.get("contactRequest") or {}
|
|
||||||
# v7 names the field contactRequestId_ (the trailing underscore is the
|
|
||||||
# generated-API optional marker) and /_accept takes the *request* id;
|
|
||||||
# older events exposed contactId. Fall back so both shapes work.
|
|
||||||
req_id = req.get("contactRequestId")
|
|
||||||
if req_id is None:
|
|
||||||
req_id = req.get("contactId_") or req.get("contactId")
|
|
||||||
if req_id is None:
|
|
||||||
return
|
|
||||||
self._corr += 1
|
|
||||||
await ws.send(
|
|
||||||
json.dumps({"corrId": f"sf-{self._corr}", "cmd": f"/_accept {req_id}"})
|
|
||||||
)
|
|
||||||
contact_id = req.get("contactId_") or req.get("contactId")
|
|
||||||
self._event(
|
|
||||||
"gateway_accepted",
|
|
||||||
contact_request_id=str(req_id),
|
|
||||||
contact_id=str(contact_id) if contact_id is not None else "",
|
|
||||||
)
|
)
|
||||||
|
self._schedule_flush(inbound, self._on_inbound)
|
||||||
|
|
||||||
def _schedule_flush(self, message: InboundMessage, on_inbound) -> None:
|
def _schedule_flush(self, message: InboundMessage, on_inbound) -> None:
|
||||||
chat = message.chat_id
|
chat = message.chat_id
|
||||||
@@ -347,16 +132,10 @@ class SimplexAdapter(GatewayAdapter):
|
|||||||
if message is None or not text:
|
if message is None or not text:
|
||||||
return
|
return
|
||||||
message.text = text
|
message.text = text
|
||||||
self._event(
|
self.daemon._event(
|
||||||
"gateway_message",
|
"gateway_message",
|
||||||
contact_id=message.contact_id,
|
contact_id=message.contact_id,
|
||||||
display_name=message.display_name,
|
display_name=message.display_name,
|
||||||
chars=len(text),
|
chars=len(text),
|
||||||
)
|
)
|
||||||
await asyncio.to_thread(on_inbound, message)
|
await asyncio.to_thread(on_inbound, message)
|
||||||
|
|
||||||
# ---- tracing ----
|
|
||||||
|
|
||||||
def _event(self, kind: str, **fields) -> None:
|
|
||||||
if self.trace is not None:
|
|
||||||
self.trace.append(kind, "?", **fields)
|
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
"""Low-level SimpleX Chat daemon WebSocket protocol (neutral transport).
|
||||||
|
|
||||||
|
This module owns the wire protocol only: connecting to a local `simplex-chat`
|
||||||
|
daemon, parsing received events into plain message dicts, running correlated
|
||||||
|
request/response round-trips (e.g. the contact-address lookup), accepting
|
||||||
|
contact requests, and draining an outbound send queue. It knows nothing about
|
||||||
|
the SemIf scheduler, the command gateway, or the forwarding bridge — both
|
||||||
|
front ends build on top of it.
|
||||||
|
|
||||||
|
Keeping this layer neutral is deliberate (see AGENTS.md "gateway isolation"):
|
||||||
|
the command gateway and the third-party bridge services have different jobs,
|
||||||
|
and neither inherits the other's surface by sharing this module.
|
||||||
|
|
||||||
|
`websockets` is imported lazily inside the functions that need it so importing
|
||||||
|
this module stays stdlib-only on a websocket-free machine.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import concurrent.futures
|
||||||
|
import json
|
||||||
|
import queue
|
||||||
|
import random
|
||||||
|
import threading
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
#: One received direct text message, normalized across the v7 wire shapes.
|
||||||
|
InboundDict = dict[str, Any]
|
||||||
|
#: Callback invoked in the event loop for each received direct text message.
|
||||||
|
MessageHandler = Callable[[InboundDict], None]
|
||||||
|
|
||||||
|
|
||||||
|
def contact_link(resp: dict) -> dict:
|
||||||
|
"""Pull `{connShortLink, connFullLink}` out of a daemon address response.
|
||||||
|
|
||||||
|
`/_show_address` nests it as `contactLink.connLinkContact`; `/_address`
|
||||||
|
returns it directly as `connLinkContact`. Tolerate both (and a flat
|
||||||
|
`contactLink`) so callers read the real daemon shape rather than calling
|
||||||
|
`/_address` again on an existing link and reporting nothing.
|
||||||
|
"""
|
||||||
|
for candidate in (
|
||||||
|
(resp.get("contactLink") or {}).get("connLinkContact"),
|
||||||
|
resp.get("connLinkContact"),
|
||||||
|
resp.get("contactLink"),
|
||||||
|
resp,
|
||||||
|
):
|
||||||
|
if isinstance(candidate, dict) and (
|
||||||
|
candidate.get("connShortLink") or candidate.get("connFullLink")
|
||||||
|
):
|
||||||
|
return candidate
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_direct_text_item(item: dict) -> InboundDict | None:
|
||||||
|
"""Normalize one `newChatItems` entry into a message dict, or None.
|
||||||
|
|
||||||
|
Returns `{text, contact_id, display_name, raw}` for a received direct text
|
||||||
|
message. Drops group chats, own echoes, non-text content, and items with no
|
||||||
|
resolvable contact id. Authorization is the caller's job — this layer is
|
||||||
|
deliberately policy-free.
|
||||||
|
"""
|
||||||
|
chat_info = item.get("chatInfo") or {}
|
||||||
|
if chat_info.get("type") != "direct":
|
||||||
|
return None
|
||||||
|
chat_item = item.get("chatItem") or {}
|
||||||
|
direction = (chat_item.get("chatDir") or {}).get("type", "")
|
||||||
|
if direction and "Snd" in direction:
|
||||||
|
return None # own echo
|
||||||
|
content = chat_item.get("content") or {}
|
||||||
|
# simplex-chat v7 tags the content union by constructor: a received text
|
||||||
|
# message is {"type": "rcvMsgContent", "msgContent": {"type": "text",
|
||||||
|
# "text": ...}}. The daemon's DB/Aeson encoding nests under the
|
||||||
|
# constructor key instead ({"rcvMsgContent": {"msgContent": ...}}), so
|
||||||
|
# accept both shapes.
|
||||||
|
if content.get("type") == "rcvMsgContent":
|
||||||
|
msg_content = content.get("msgContent") or {}
|
||||||
|
elif isinstance(content.get("rcvMsgContent"), dict):
|
||||||
|
msg_content = content["rcvMsgContent"].get("msgContent") or {}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if msg_content.get("type") != "text":
|
||||||
|
return None
|
||||||
|
text = str(msg_content.get("text", "")).strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
contact = chat_info.get("contact") or {}
|
||||||
|
contact_id = str(contact.get("contactId") or chat_info.get("chatId") or "")
|
||||||
|
if not contact_id:
|
||||||
|
return None
|
||||||
|
profile = contact.get("profile") or {}
|
||||||
|
# v7's Contact has `displayName: null`; the real peer name lives in
|
||||||
|
# `profile.displayName`, and `localDisplayName` is auto-suffixed on
|
||||||
|
# collisions (e.g. a second contact becomes `pepper_1`).
|
||||||
|
display_name = (
|
||||||
|
profile.get("displayName")
|
||||||
|
or contact.get("displayName")
|
||||||
|
or contact.get("localDisplayName")
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"text": text,
|
||||||
|
"contact_id": contact_id,
|
||||||
|
"display_name": display_name,
|
||||||
|
"raw": item,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_text_command(chat_id: str, text: str) -> str:
|
||||||
|
"""Structured APISendMessages command for a direct contact.
|
||||||
|
|
||||||
|
The CLI shortcut `@<id> <text>` is silently rejected over WebSocket (it
|
||||||
|
resolves the ref as a display name), so always use the JSON form.
|
||||||
|
"""
|
||||||
|
composed = [{"msgContent": {"type": "text", "text": text}}]
|
||||||
|
return f"/_send @{chat_id} json {json.dumps(composed)}"
|
||||||
|
|
||||||
|
|
||||||
|
def accept_command(resp: dict) -> str | None:
|
||||||
|
"""The `/_accept` command for a `receivedContactRequest`, or None.
|
||||||
|
|
||||||
|
v7 names the field contactRequestId_ (the trailing underscore is the
|
||||||
|
generated-API optional marker) and /_accept takes the *request* id; older
|
||||||
|
events exposed contactId. Fall back so both shapes work.
|
||||||
|
"""
|
||||||
|
req = resp.get("contactRequest") or {}
|
||||||
|
req_id = req.get("contactRequestId")
|
||||||
|
if req_id is None:
|
||||||
|
req_id = req.get("contactId_") or req.get("contactId")
|
||||||
|
if req_id is None:
|
||||||
|
return None
|
||||||
|
return f"/_accept {req_id}"
|
||||||
|
|
||||||
|
|
||||||
|
class SimplexDaemon:
|
||||||
|
"""One WebSocket connection to a `simplex-chat` daemon.
|
||||||
|
|
||||||
|
`run(on_message)` blocks, reconnecting on transport failure, delivering each
|
||||||
|
received direct text message to `on_message` in the event loop and draining
|
||||||
|
`enqueue()`d sends from an internal queue. `request_address()` is safe to
|
||||||
|
call from another thread (the bridge's HTTP handler). Beware: the same
|
||||||
|
daemon/profile must not be shared by two processes — each front end points
|
||||||
|
at its own daemon.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
ws_url: str,
|
||||||
|
*,
|
||||||
|
user_id: int = 1,
|
||||||
|
auto_accept: bool = True,
|
||||||
|
reconnect: dict | None = None,
|
||||||
|
trace=None,
|
||||||
|
name: str = "simplex",
|
||||||
|
):
|
||||||
|
self.ws_url = str(ws_url)
|
||||||
|
self.user_id = int(user_id)
|
||||||
|
self.auto_accept = bool(auto_accept)
|
||||||
|
settings = reconnect or {}
|
||||||
|
self.reconnect_initial = float(settings.get("initial", 1.0))
|
||||||
|
self.reconnect_max = float(settings.get("max", 60.0))
|
||||||
|
self.reconnect_jitter = float(settings.get("jitter", 0.2))
|
||||||
|
self.trace = trace
|
||||||
|
self.name = name
|
||||||
|
self._corr = 0
|
||||||
|
self._pending: dict[str, asyncio.Future] = {}
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self._ws = None
|
||||||
|
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._on_message: MessageHandler | None = None
|
||||||
|
|
||||||
|
# ---- requirements ----
|
||||||
|
|
||||||
|
def check_requirements(self) -> tuple[bool, str | None]:
|
||||||
|
if not self.ws_url:
|
||||||
|
return False, "simplex ws_url is required"
|
||||||
|
try:
|
||||||
|
import websockets # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
return False, "pip install websockets"
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
# ---- lifecycle ----
|
||||||
|
|
||||||
|
def run(self, on_message: MessageHandler) -> None:
|
||||||
|
asyncio.run(self._serve(on_message))
|
||||||
|
|
||||||
|
def enqueue(self, chat_id: str | None, text: str = "") -> None:
|
||||||
|
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
|
||||||
|
if chat_id is None:
|
||||||
|
self._outbound.put(None)
|
||||||
|
else:
|
||||||
|
self._outbound.put((str(chat_id), text))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
self._outbound.put(None)
|
||||||
|
|
||||||
|
async def _serve(self, on_message: MessageHandler) -> None:
|
||||||
|
import websockets
|
||||||
|
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self._on_message = on_message
|
||||||
|
backoff = self.reconnect_initial
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
async with websockets.connect(self.ws_url, max_size=None) as ws:
|
||||||
|
self._ws = ws
|
||||||
|
backoff = self.reconnect_initial
|
||||||
|
self._event("gateway_connected", url=self.ws_url)
|
||||||
|
sender = asyncio.create_task(self._outbound_loop(ws))
|
||||||
|
try:
|
||||||
|
async for raw in ws:
|
||||||
|
await self._consume(raw)
|
||||||
|
finally:
|
||||||
|
sender.cancel()
|
||||||
|
except Exception as exc: # reconnect on any transport failure
|
||||||
|
self._event("gateway_error", message=str(exc)[:300])
|
||||||
|
finally:
|
||||||
|
self._ws = None
|
||||||
|
self._fail_pending("simplex gateway disconnected")
|
||||||
|
delay = min(backoff, self.reconnect_max)
|
||||||
|
delay *= 1 + random.random() * self.reconnect_jitter
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._stop_wait(), timeout=delay)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
pass
|
||||||
|
backoff = min(max(delay, self.reconnect_initial), self.reconnect_max)
|
||||||
|
|
||||||
|
async def _stop_wait(self) -> None:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
async def _outbound_loop(self, ws) -> None:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
while True:
|
||||||
|
item = await loop.run_in_executor(None, self._outbound.get)
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
chat_id, text = item
|
||||||
|
try:
|
||||||
|
self._corr += 1
|
||||||
|
await ws.send(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"corrId": f"sf-{self._corr}",
|
||||||
|
"cmd": send_text_command(chat_id, text),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._event("gateway_sent", chat_id=chat_id, chars=len(text))
|
||||||
|
except Exception as exc:
|
||||||
|
self._event("gateway_error", phase="send", message=str(exc)[:300])
|
||||||
|
|
||||||
|
# ---- request/response + address ----
|
||||||
|
|
||||||
|
async def _roundtrip(self, command: str, timeout: float) -> dict:
|
||||||
|
"""Send a command and await its correlated `resp` from the event loop."""
|
||||||
|
ws = self._ws
|
||||||
|
if ws is None or self._loop is None:
|
||||||
|
raise RuntimeError("simplex gateway is not connected")
|
||||||
|
self._corr += 1
|
||||||
|
corr = f"req-{self._corr}"
|
||||||
|
future = self._loop.create_future()
|
||||||
|
self._pending[corr] = future
|
||||||
|
await ws.send(json.dumps({"corrId": corr, "cmd": command}))
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(future, timeout)
|
||||||
|
finally:
|
||||||
|
self._pending.pop(corr, None)
|
||||||
|
|
||||||
|
def _fail_pending(self, reason: str) -> None:
|
||||||
|
pending, self._pending = self._pending, {}
|
||||||
|
for future in pending.values():
|
||||||
|
if not future.done():
|
||||||
|
future.set_exception(RuntimeError(reason))
|
||||||
|
|
||||||
|
async def address(self, timeout: float = 20.0) -> dict:
|
||||||
|
"""Show the daemon user's contact address, creating it on first call.
|
||||||
|
|
||||||
|
`/_show_address <userId>` returns an existing link; when there is none,
|
||||||
|
`/_address <userId>` creates one. Returns
|
||||||
|
`{short_link, full_link, created}`.
|
||||||
|
"""
|
||||||
|
resp = await self._roundtrip(f"/_show_address {self.user_id}", timeout)
|
||||||
|
link: dict = {}
|
||||||
|
created = False
|
||||||
|
if resp.get("type") == "userContactLink":
|
||||||
|
link = contact_link(resp)
|
||||||
|
if not (link.get("connShortLink") or link.get("connFullLink")):
|
||||||
|
resp = await self._roundtrip(f"/_address {self.user_id}", timeout)
|
||||||
|
link = contact_link(resp)
|
||||||
|
created = True
|
||||||
|
return {
|
||||||
|
"short_link": link.get("connShortLink") or "",
|
||||||
|
"full_link": link.get("connFullLink") or "",
|
||||||
|
"created": created,
|
||||||
|
}
|
||||||
|
|
||||||
|
def request_address(self, timeout: float = 20.0) -> dict:
|
||||||
|
"""Thread-safe address lookup for callers off the event loop.
|
||||||
|
|
||||||
|
Raises `RuntimeError` when no live connection exists and `TimeoutError`
|
||||||
|
when the daemon does not answer in time — never a fabricated link.
|
||||||
|
"""
|
||||||
|
loop = self._loop
|
||||||
|
if loop is None or not loop.is_running():
|
||||||
|
raise RuntimeError("simplex gateway is not connected")
|
||||||
|
future = asyncio.run_coroutine_threadsafe(self.address(timeout=timeout), loop)
|
||||||
|
try:
|
||||||
|
return future.result(timeout=timeout + 5.0)
|
||||||
|
except concurrent.futures.TimeoutError as exc:
|
||||||
|
future.cancel()
|
||||||
|
raise TimeoutError("simplex address request timed out") from exc
|
||||||
|
|
||||||
|
# ---- inbound ----
|
||||||
|
|
||||||
|
async def _consume(self, raw: Any) -> None:
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
corr_id = data.get("corrId")
|
||||||
|
if corr_id is not None:
|
||||||
|
# A correlated command response (round-trip): resolve the waiting
|
||||||
|
# requester. Fire-and-forget commands (`_send`, `_accept`) never
|
||||||
|
# register a future, so their responses are dropped here.
|
||||||
|
future = self._pending.pop(corr_id, None)
|
||||||
|
if future is not None and not future.done():
|
||||||
|
future.set_result(data.get("resp") or {})
|
||||||
|
return
|
||||||
|
resp = data.get("resp") or {}
|
||||||
|
kind = resp.get("type")
|
||||||
|
if kind == "receivedContactRequest":
|
||||||
|
await self._maybe_accept(resp)
|
||||||
|
return
|
||||||
|
if kind != "newChatItems":
|
||||||
|
return
|
||||||
|
for item in resp.get("chatItems", []) or []:
|
||||||
|
message = parse_direct_text_item(item)
|
||||||
|
if message is not None and self._on_message is not None:
|
||||||
|
self._on_message(message)
|
||||||
|
|
||||||
|
async def _maybe_accept(self, resp: dict) -> None:
|
||||||
|
if not self.auto_accept:
|
||||||
|
return
|
||||||
|
command = accept_command(resp)
|
||||||
|
if command is None:
|
||||||
|
return
|
||||||
|
self._corr += 1
|
||||||
|
await self._ws.send(json.dumps({"corrId": f"sf-{self._corr}", "cmd": command}))
|
||||||
|
req = resp.get("contactRequest") or {}
|
||||||
|
contact_id = req.get("contactId_") or req.get("contactId")
|
||||||
|
self._event(
|
||||||
|
"gateway_accepted",
|
||||||
|
contact_request_id=command.split()[-1],
|
||||||
|
contact_id=str(contact_id) if contact_id is not None else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- tracing ----
|
||||||
|
|
||||||
|
def _event(self, kind: str, **fields) -> None:
|
||||||
|
if self.trace is not None:
|
||||||
|
self.trace.append(kind, "?", **fields)
|
||||||
@@ -1,35 +1,60 @@
|
|||||||
"""Pure-stdlib tests for the gateway's local messaging bridge.
|
"""Pure-stdlib tests for the standalone bridge services.
|
||||||
|
|
||||||
The bridge is exercised over a real loopback HTTP server (no mocking of its
|
The SimpleX bridge is exercised over a real loopback HTTP server (no mocking of
|
||||||
transport); the decision engine and LLM are never involved. These prove the
|
its HTTP transport) with a fake daemon standing in for the `simplex-chat`
|
||||||
|
connection — the decision engine and LLM are never involved. These prove the
|
||||||
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
|
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
|
||||||
resolution, outbound routing onto the adapter queue, and token/body validation.
|
resolution, outbound routing, address lookup, and token/body validation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import queue
|
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from semif_agent.gateway.base import InboundMessage, OutboundMessage
|
from semif_agent.bridges.registry import describe_bridges, known_infos
|
||||||
from semif_agent.gateway.bridge import MessagingBridge
|
from semif_agent.bridges.simplex import SimplexBridge
|
||||||
|
|
||||||
|
|
||||||
def start_bridge(address_provider=None, **config):
|
class FakeDaemon:
|
||||||
outbound = queue.Queue()
|
"""Stands in for the bridge's own simplex-chat connection."""
|
||||||
bridge = MessagingBridge(
|
|
||||||
outbound, config=config, address_provider=address_provider
|
def __init__(self, link=None, error=None):
|
||||||
)
|
self.link = link
|
||||||
|
self.error = error
|
||||||
|
self.sent = []
|
||||||
|
self.closed = False
|
||||||
|
self.on_message = None
|
||||||
|
|
||||||
|
def check_requirements(self):
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
def run(self, on_message):
|
||||||
|
self.on_message = on_message
|
||||||
|
|
||||||
|
def enqueue(self, chat_id, text=""):
|
||||||
|
if chat_id is not None:
|
||||||
|
self.sent.append((chat_id, text))
|
||||||
|
|
||||||
|
def request_address(self, timeout=20.0):
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.link
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def start_bridge(daemon=None, **config):
|
||||||
|
daemon = daemon or FakeDaemon()
|
||||||
|
bridge = SimplexBridge(config, daemon=daemon)
|
||||||
port = bridge.start()
|
port = bridge.start()
|
||||||
return bridge, outbound, f"http://127.0.0.1:{port}"
|
return bridge, daemon, f"http://127.0.0.1:{port}"
|
||||||
|
|
||||||
|
|
||||||
def inbound(text, contact_id="4", display_name="Alice"):
|
def inbound(text, contact_id="4", display_name="Alice"):
|
||||||
return InboundMessage(
|
return {"text": text, "contact_id": contact_id, "display_name": display_name}
|
||||||
text=text, chat_id=contact_id, contact_id=contact_id, display_name=display_name
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get(url, token=None):
|
def get(url, token=None):
|
||||||
@@ -53,7 +78,7 @@ def test_health_and_contacts():
|
|||||||
bridge, _, base = start_bridge()
|
bridge, _, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
|
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
|
||||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||||
assert get(f"{base}/contacts") == {
|
assert get(f"{base}/contacts") == {
|
||||||
"contacts": [{"id": "4", "display_name": "Alice"}]
|
"contacts": [{"id": "4", "display_name": "Alice"}]
|
||||||
}
|
}
|
||||||
@@ -64,8 +89,8 @@ def test_health_and_contacts():
|
|||||||
def test_inbox_peek_then_pop_consumes_oldest():
|
def test_inbox_peek_then_pop_consumes_oldest():
|
||||||
bridge, _, base = start_bridge()
|
bridge, _, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
|
||||||
peeked = get(f"{base}/inbox")["messages"]
|
peeked = get(f"{base}/inbox")["messages"]
|
||||||
assert [m["text"] for m in peeked] == ["first", "second"]
|
assert [m["text"] for m in peeked] == ["first", "second"]
|
||||||
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
|
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
|
||||||
@@ -82,8 +107,8 @@ def test_inbox_peek_then_pop_consumes_oldest():
|
|||||||
def test_inbox_next_filters_by_contact():
|
def test_inbox_next_filters_by_contact():
|
||||||
bridge, _, base = start_bridge()
|
bridge, _, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
bridge._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
bridge._on_message(inbound("second", contact_id="7", display_name="Bob"))
|
||||||
popped = get(f"{base}/inbox/next?contact=7")["message"]
|
popped = get(f"{base}/inbox/next?contact=7")["message"]
|
||||||
assert popped["text"] == "second"
|
assert popped["text"] == "second"
|
||||||
assert get(f"{base}/inbox/next?contact=7")["message"] is None
|
assert get(f"{base}/inbox/next?contact=7")["message"] is None
|
||||||
@@ -92,60 +117,69 @@ def test_inbox_next_filters_by_contact():
|
|||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_inbox_buffers_any_sender():
|
||||||
|
# No allowlist: a brand-new contact who reached the bot via its invite link
|
||||||
|
# must be visible, which is the whole point of the forwarding bridge.
|
||||||
|
bridge, _, base = start_bridge()
|
||||||
|
try:
|
||||||
|
bridge._on_message(inbound("who are you?", contact_id="99", display_name="stranger"))
|
||||||
|
messages = get(f"{base}/inbox")["messages"]
|
||||||
|
assert [m["text"] for m in messages] == ["who are you?"]
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_inbox_is_bounded():
|
def test_inbox_is_bounded():
|
||||||
bridge, _, base = start_bridge(max_inbox=2)
|
bridge, _, base = start_bridge(max_inbox=2)
|
||||||
try:
|
try:
|
||||||
for text in ("one", "two", "three"):
|
for text in ("one", "two", "three"):
|
||||||
bridge.record_inbound(inbound(text))
|
bridge._on_message(inbound(text))
|
||||||
messages = get(f"{base}/inbox")["messages"]
|
messages = get(f"{base}/inbox")["messages"]
|
||||||
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
|
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_send_routes_to_outbound_queue():
|
def test_send_routes_to_daemon():
|
||||||
bridge, outbound, base = start_bridge()
|
bridge, daemon, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
|
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
|
||||||
assert result == {"ok": True, "contact_id": "7"}
|
assert result == {"ok": True, "contact_id": "7"}
|
||||||
message = outbound.get_nowait()
|
assert daemon.sent == [("7", "on my way")]
|
||||||
assert isinstance(message, OutboundMessage)
|
|
||||||
assert message.chat_id == "7"
|
|
||||||
assert message.text == "on my way"
|
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_send_resolves_known_display_name():
|
def test_send_resolves_known_display_name():
|
||||||
bridge, outbound, base = start_bridge()
|
bridge, daemon, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||||
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
|
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
|
||||||
assert result["contact_id"] == "4"
|
assert result["contact_id"] == "4"
|
||||||
assert outbound.get_nowait().chat_id == "4"
|
assert daemon.sent == [("4", "hello")]
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_send_rejects_unknown_recipient():
|
def test_send_rejects_unknown_recipient():
|
||||||
bridge, outbound, base = start_bridge()
|
bridge, daemon, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
|
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
|
||||||
assert exc.value.code == 400
|
assert exc.value.code == 400
|
||||||
assert outbound.empty(), "a rejected send must not enqueue anything"
|
assert daemon.sent == [], "a rejected send must not enqueue anything"
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_send_validates_body():
|
def test_send_validates_body():
|
||||||
bridge, outbound, base = start_bridge()
|
bridge, daemon, base = start_bridge()
|
||||||
try:
|
try:
|
||||||
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
|
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
|
||||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
post(f"{base}/send", payload)
|
post(f"{base}/send", payload)
|
||||||
assert exc.value.code == 400
|
assert exc.value.code == 400
|
||||||
assert outbound.empty()
|
assert daemon.sent == []
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
@@ -164,17 +198,19 @@ def test_token_is_required_when_configured():
|
|||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_address_uses_provider():
|
def test_address_returns_daemon_link():
|
||||||
link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False}
|
link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False}
|
||||||
bridge, _, base = start_bridge(address_provider=lambda: link)
|
bridge, _, base = start_bridge(daemon=FakeDaemon(link=link))
|
||||||
try:
|
try:
|
||||||
assert get(f"{base}/address") == link
|
assert get(f"{base}/address") == link
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_address_without_provider_is_unavailable():
|
def test_address_without_connection_is_unavailable():
|
||||||
bridge, _, base = start_bridge()
|
bridge, _, base = start_bridge(
|
||||||
|
daemon=FakeDaemon(error=RuntimeError("not connected"))
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
get(f"{base}/address")
|
get(f"{base}/address")
|
||||||
@@ -183,14 +219,33 @@ def test_address_without_provider_is_unavailable():
|
|||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
def test_address_provider_failure_is_reported():
|
def test_address_lookup_failure_is_reported():
|
||||||
def boom():
|
bridge, _, base = start_bridge(daemon=FakeDaemon(error=TimeoutError("slow")))
|
||||||
raise RuntimeError("not connected")
|
|
||||||
|
|
||||||
bridge, _, base = start_bridge(address_provider=boom)
|
|
||||||
try:
|
try:
|
||||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||||
get(f"{base}/address")
|
get(f"{base}/address")
|
||||||
assert exc.value.code == 502
|
assert exc.value.code == 502
|
||||||
finally:
|
finally:
|
||||||
bridge.stop()
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_stop_closes_the_daemon():
|
||||||
|
bridge, daemon, _ = start_bridge()
|
||||||
|
bridge.stop()
|
||||||
|
assert daemon.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- catalog / codegen surface ----
|
||||||
|
|
||||||
|
def test_known_infos_include_simplex():
|
||||||
|
infos = {info.name: info for info in known_infos()}
|
||||||
|
assert "simplex" in infos
|
||||||
|
assert infos["simplex"].url_config_var == "simplex_bridge_url"
|
||||||
|
|
||||||
|
|
||||||
|
def test_describe_bridges_names_the_service_and_config_var():
|
||||||
|
text = describe_bridges()
|
||||||
|
assert "simplex" in text
|
||||||
|
assert "simplex_bridge_url" in text
|
||||||
|
assert "/inbox/next" in text
|
||||||
|
assert "never speak" in text
|
||||||
@@ -1680,17 +1680,17 @@ def test_skill_contract_lists_all_transports():
|
|||||||
assert transport in text
|
assert transport in text
|
||||||
|
|
||||||
|
|
||||||
def test_skill_contract_documents_messaging_bridge():
|
def test_skill_contract_documents_bridge_services():
|
||||||
text = read_skill_contract()
|
text = read_skill_contract()
|
||||||
assert "messaging_bridge_url" in text
|
assert "simplex_bridge_url" in text
|
||||||
assert "/inbox/next" in text
|
assert "/inbox/next" in text
|
||||||
assert "/send" in text
|
assert "/send" in text
|
||||||
assert "never opens a WebSocket" in text
|
assert "never speak a service's native protocol" in text
|
||||||
|
|
||||||
|
|
||||||
def test_body_directives_expose_messaging_bridge():
|
def test_body_directives_expose_bridge_services():
|
||||||
assert "messaging_bridge_url" in BODY_DIRECTIVES
|
assert "bridge services" in BODY_DIRECTIVES
|
||||||
assert "never open a WebSocket" in BODY_DIRECTIVES
|
assert "never speak the service's native protocol" in BODY_DIRECTIVES
|
||||||
|
|
||||||
|
|
||||||
def test_body_prompts_require_real_action_and_integration():
|
def test_body_prompts_require_real_action_and_integration():
|
||||||
|
|||||||
+7
-261
@@ -1,16 +1,17 @@
|
|||||||
"""Pure-stdlib tests for the messenger gateway (SimpleX adapter + router).
|
"""Pure-stdlib tests for the messenger gateway (SimpleX command adapter + router).
|
||||||
|
|
||||||
The decision engine is never loaded and the LLM endpoint is unreachable, so
|
The gateway is the agent's command surface only. These tests exercise its own
|
||||||
scheduler calls degrade to errors — which is fine: these tests exercise the
|
routing, authorization, and batching; parsing/accept/address live in
|
||||||
gateway's own routing, authorization, parsing, and batching. The real
|
`tests/test_simplex_ws.py`. The decision engine is never loaded and the LLM
|
||||||
`websockets` transport against a live `simplex-chat` daemon is a jarvis
|
endpoint is unreachable, so scheduler calls degrade to errors — which is fine.
|
||||||
|
The real `websockets` transport against a live `simplex-chat` daemon is a jarvis
|
||||||
integration concern, not a dev-box unit test.
|
integration concern, not a dev-box unit test.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request
|
from semif_agent.decisions import Request
|
||||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||||
from semif_agent.gateway.base import InboundMessage
|
from semif_agent.gateway.base import InboundMessage
|
||||||
from semif_agent.gateway.service import GatewayService
|
from semif_agent.gateway.service import GatewayService
|
||||||
@@ -63,105 +64,6 @@ def test_check_requirements_needs_url():
|
|||||||
assert "ws_url" in hint
|
assert "ws_url" in hint
|
||||||
|
|
||||||
|
|
||||||
# ---- adapter: parsing ----
|
|
||||||
|
|
||||||
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
|
|
||||||
# v7 wire shape: the Contact's `displayName` is null and the peer name lives
|
|
||||||
# in `profile.displayName`; `localDisplayName` is auto-suffixed on collision.
|
|
||||||
# Received text is tagged `rcvMsgContent` with the message under `msgContent`.
|
|
||||||
return {
|
|
||||||
"chatInfo": {
|
|
||||||
"type": "direct",
|
|
||||||
"chatId": contact_id,
|
|
||||||
"contact": {
|
|
||||||
"contactId": contact_id,
|
|
||||||
"localDisplayName": display,
|
|
||||||
"displayName": None,
|
|
||||||
"profile": {"displayName": display},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"chatItem": {
|
|
||||||
"chatDir": {"type": direction},
|
|
||||||
"content": {
|
|
||||||
"type": "rcvMsgContent",
|
|
||||||
"msgContent": {"type": kind, "text": text},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_authorized_direct_text():
|
|
||||||
adapter = SimplexAdapter({"allowed_users": ["4"]})
|
|
||||||
message = adapter._parse_chat_item(direct_item())
|
|
||||||
assert message is not None
|
|
||||||
assert message.text == "hello"
|
|
||||||
assert message.chat_id == "4"
|
|
||||||
assert message.contact_id == "4"
|
|
||||||
assert message.display_name == "alice"
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_filters_echo_group_and_non_text():
|
|
||||||
adapter = SimplexAdapter({"allow_all_users": True})
|
|
||||||
assert adapter._parse_chat_item(direct_item(direction="directSnd")) is None
|
|
||||||
assert adapter._parse_chat_item(direct_item(kind="image")) is None
|
|
||||||
group = direct_item()
|
|
||||||
group["chatInfo"]["type"] = "group"
|
|
||||||
assert adapter._parse_chat_item(group) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_filters_unauthorized_contact():
|
|
||||||
adapter = SimplexAdapter({"allowed_users": ["9"]})
|
|
||||||
assert adapter._parse_chat_item(direct_item(contact_id="4", display="alice")) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_real_v7_payload_with_suffixed_local_name():
|
|
||||||
# Captured live from simplex-chat v7 (`/_get chat @3`): the text is nested
|
|
||||||
# under content.msgContent; Contact.displayName is null, the peer name is in
|
|
||||||
# profile.displayName, and a collision-suffixed localDisplayName must not
|
|
||||||
# defeat the allowlist.
|
|
||||||
adapter = SimplexAdapter({"allowed_users": ["pepper"]})
|
|
||||||
item = {
|
|
||||||
"chatInfo": {
|
|
||||||
"type": "direct",
|
|
||||||
"chatId": 6,
|
|
||||||
"contact": {
|
|
||||||
"contactId": 6,
|
|
||||||
"localDisplayName": "pepper_1",
|
|
||||||
"displayName": None,
|
|
||||||
"profile": {"displayName": "pepper"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"chatItem": {
|
|
||||||
"chatDir": {"type": "directRcv"},
|
|
||||||
"content": {
|
|
||||||
"type": "rcvMsgContent",
|
|
||||||
"msgContent": {
|
|
||||||
"type": "text",
|
|
||||||
"text": "what is the next thing on my calendar?",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
message = adapter._parse_chat_item(item)
|
|
||||||
assert message is not None
|
|
||||||
assert message.text == "what is the next thing on my calendar?"
|
|
||||||
assert message.contact_id == "6"
|
|
||||||
assert message.display_name == "pepper"
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_accepts_aeson_nested_content_shape():
|
|
||||||
# The daemon's DB/Aeson encoding nests under the constructor key instead of
|
|
||||||
# tagging with `type`; the parser tolerates both.
|
|
||||||
adapter = SimplexAdapter({"allow_all_users": True})
|
|
||||||
item = direct_item()
|
|
||||||
item["chatItem"]["content"] = {
|
|
||||||
"rcvMsgContent": {"msgContent": {"type": "text", "text": "hi"}}
|
|
||||||
}
|
|
||||||
message = adapter._parse_chat_item(item)
|
|
||||||
assert message is not None
|
|
||||||
assert message.text == "hi"
|
|
||||||
|
|
||||||
|
|
||||||
# ---- adapter: send command ----
|
# ---- adapter: send command ----
|
||||||
|
|
||||||
def test_send_command_is_structured_not_shortcut():
|
def test_send_command_is_structured_not_shortcut():
|
||||||
@@ -174,44 +76,6 @@ def test_send_command_is_structured_not_shortcut():
|
|||||||
assert command != "/_send @4 hello"
|
assert command != "/_send @4 hello"
|
||||||
|
|
||||||
|
|
||||||
# ---- adapter: contact request acceptance ----
|
|
||||||
|
|
||||||
class _FakeWS:
|
|
||||||
def __init__(self):
|
|
||||||
self.sent = []
|
|
||||||
|
|
||||||
async def send(self, data):
|
|
||||||
self.sent.append(json.loads(data)["cmd"])
|
|
||||||
|
|
||||||
|
|
||||||
def _contact_request_event(req):
|
|
||||||
return json.dumps(
|
|
||||||
{"resp": {"type": "receivedContactRequest", "contactRequest": req}}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_accept_uses_v7_contact_request_id():
|
|
||||||
# v7 exposes contactRequestId (and contactId_); /_accept takes the request id.
|
|
||||||
adapter = SimplexAdapter({"auto_accept": True})
|
|
||||||
ws = _FakeWS()
|
|
||||||
asyncio.run(adapter._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9}), lambda m: None, ws))
|
|
||||||
assert ws.sent == ["/_accept 7"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_accept_falls_back_to_contact_id_for_legacy_events():
|
|
||||||
adapter = SimplexAdapter({"auto_accept": True})
|
|
||||||
ws = _FakeWS()
|
|
||||||
asyncio.run(adapter._consume(_contact_request_event({"contactId": 4}), lambda m: None, ws))
|
|
||||||
assert ws.sent == ["/_accept 4"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_accept_disabled_sends_nothing():
|
|
||||||
adapter = SimplexAdapter({"auto_accept": False})
|
|
||||||
ws = _FakeWS()
|
|
||||||
asyncio.run(adapter._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9}), lambda m: None, ws))
|
|
||||||
assert ws.sent == []
|
|
||||||
|
|
||||||
|
|
||||||
# ---- adapter: batching ----
|
# ---- adapter: batching ----
|
||||||
|
|
||||||
def test_batching_concatenates_rapid_messages():
|
def test_batching_concatenates_rapid_messages():
|
||||||
@@ -340,121 +204,3 @@ def test_service_answered_question_routes_back(tmp_path):
|
|||||||
|
|
||||||
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
|
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
|
||||||
assert not scheduler.pending_questions()
|
assert not scheduler.pending_questions()
|
||||||
|
|
||||||
|
|
||||||
def test_service_observer_sees_authorized_inbound(tmp_path):
|
|
||||||
scheduler = build_scheduler(tmp_path)
|
|
||||||
service = build_service(scheduler)
|
|
||||||
seen = []
|
|
||||||
service.observer = seen.append
|
|
||||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
|
||||||
assert [m.text for m in seen] == ["hi"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_service_pull_mode_buffers_without_dispatch(tmp_path):
|
|
||||||
scheduler = build_scheduler(tmp_path)
|
|
||||||
service = GatewayService(scheduler, FakeAdapter(), config={"inbox": {"dispatch": False}})
|
|
||||||
seen = []
|
|
||||||
service.observer = seen.append
|
|
||||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
|
||||||
assert [m.text for m in seen] == ["hi"], "pull mode must still buffer for a read skill"
|
|
||||||
assert drain_outbound(service) == [], "pull mode must not reply or dispatch"
|
|
||||||
assert scheduler.current is None
|
|
||||||
assert scheduler.pending is None
|
|
||||||
|
|
||||||
|
|
||||||
# ---- adapter: correlated request/response + contact address ----
|
|
||||||
|
|
||||||
|
|
||||||
class FakeWS:
|
|
||||||
"""A fake simplex-chat socket that answers correlated commands."""
|
|
||||||
|
|
||||||
def __init__(self, adapter, responses):
|
|
||||||
self.adapter = adapter
|
|
||||||
self.responses = list(responses)
|
|
||||||
self.sent = []
|
|
||||||
|
|
||||||
async def send(self, raw):
|
|
||||||
message = json.loads(raw)
|
|
||||||
self.sent.append(message)
|
|
||||||
response = self.responses.pop(0)
|
|
||||||
await self.adapter._consume(
|
|
||||||
json.dumps({"corrId": message["corrId"], "resp": response}), None, self
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_correlated_response_resolves_pending_future():
|
|
||||||
adapter = SimplexAdapter({})
|
|
||||||
|
|
||||||
async def scenario():
|
|
||||||
adapter._loop = asyncio.get_running_loop()
|
|
||||||
adapter._ws = FakeWS(adapter, [])
|
|
||||||
future = adapter._loop.create_future()
|
|
||||||
adapter._pending["req-9"] = future
|
|
||||||
await adapter._consume(
|
|
||||||
json.dumps({"corrId": "req-9", "resp": {"type": "ok", "value": 1}}), None, adapter._ws
|
|
||||||
)
|
|
||||||
assert "req-9" not in adapter._pending, "a resolved request must be dropped"
|
|
||||||
return future.result()
|
|
||||||
|
|
||||||
assert asyncio.run(scenario()) == {"type": "ok", "value": 1}
|
|
||||||
|
|
||||||
|
|
||||||
def test_address_returns_existing_link():
|
|
||||||
adapter = SimplexAdapter({"user_id": 3})
|
|
||||||
|
|
||||||
async def scenario():
|
|
||||||
adapter._loop = asyncio.get_running_loop()
|
|
||||||
ws = FakeWS(
|
|
||||||
adapter,
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"type": "userContactLink",
|
|
||||||
"user": {"userId": 3},
|
|
||||||
"contactLink": {
|
|
||||||
"userContactLinkId": 1,
|
|
||||||
"connLinkContact": {
|
|
||||||
"connShortLink": "simplex:/a",
|
|
||||||
"connFullLink": "https://a",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
],
|
|
||||||
)
|
|
||||||
adapter._ws = ws
|
|
||||||
return await adapter.address(timeout=5), ws
|
|
||||||
|
|
||||||
result, ws = asyncio.run(scenario())
|
|
||||||
assert result == {"short_link": "simplex:/a", "full_link": "https://a", "created": False}
|
|
||||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 3"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_address_creates_when_missing():
|
|
||||||
adapter = SimplexAdapter({"user_id": 1})
|
|
||||||
|
|
||||||
async def scenario():
|
|
||||||
adapter._loop = asyncio.get_running_loop()
|
|
||||||
ws = FakeWS(
|
|
||||||
adapter,
|
|
||||||
[
|
|
||||||
{"type": "userContactLink", "contactLink": None},
|
|
||||||
{
|
|
||||||
"type": "userContactLinkCreated",
|
|
||||||
"connLinkContact": {"connShortLink": "simplex:/new", "connFullLink": ""},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
)
|
|
||||||
adapter._ws = ws
|
|
||||||
return await adapter.address(timeout=5), ws
|
|
||||||
|
|
||||||
result, ws = asyncio.run(scenario())
|
|
||||||
assert result == {"short_link": "simplex:/new", "full_link": "", "created": True}
|
|
||||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1", "/_address 1"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_request_address_without_connection_raises():
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
adapter = SimplexAdapter({})
|
|
||||||
with pytest.raises(RuntimeError):
|
|
||||||
adapter.request_address(timeout=1)
|
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
"""Pure-stdlib tests for the neutral SimpleX daemon protocol layer.
|
||||||
|
|
||||||
|
`semif_agent.simplex_ws` is shared by the command gateway and the forwarding
|
||||||
|
bridge, so its parsing/accept/address behavior is tested here, independent of
|
||||||
|
either front end. The real `websockets` transport against a live daemon is a
|
||||||
|
jarvis integration concern.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from semif_agent.simplex_ws import (
|
||||||
|
SimplexDaemon,
|
||||||
|
accept_command,
|
||||||
|
contact_link,
|
||||||
|
parse_direct_text_item,
|
||||||
|
send_text_command,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- parsing ----
|
||||||
|
|
||||||
|
def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"):
|
||||||
|
# v7 wire shape: the Contact's `displayName` is null and the peer name lives
|
||||||
|
# in `profile.displayName`; `localDisplayName` is auto-suffixed on collision.
|
||||||
|
# Received text is tagged `rcvMsgContent` with the message under `msgContent`.
|
||||||
|
return {
|
||||||
|
"chatInfo": {
|
||||||
|
"type": "direct",
|
||||||
|
"chatId": contact_id,
|
||||||
|
"contact": {
|
||||||
|
"contactId": contact_id,
|
||||||
|
"localDisplayName": display,
|
||||||
|
"displayName": None,
|
||||||
|
"profile": {"displayName": display},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"chatItem": {
|
||||||
|
"chatDir": {"type": direction},
|
||||||
|
"content": {
|
||||||
|
"type": "rcvMsgContent",
|
||||||
|
"msgContent": {"type": kind, "text": text},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_direct_text():
|
||||||
|
message = parse_direct_text_item(direct_item())
|
||||||
|
assert message is not None
|
||||||
|
assert message["text"] == "hello"
|
||||||
|
assert message["contact_id"] == "4"
|
||||||
|
assert message["display_name"] == "alice"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_filters_echo_group_and_non_text():
|
||||||
|
assert parse_direct_text_item(direct_item(direction="directSnd")) is None
|
||||||
|
assert parse_direct_text_item(direct_item(kind="image")) is None
|
||||||
|
group = direct_item()
|
||||||
|
group["chatInfo"]["type"] = "group"
|
||||||
|
assert parse_direct_text_item(group) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_is_policy_free():
|
||||||
|
# No allowlist lives here: the bridge buffers everyone; the gateway filters.
|
||||||
|
assert parse_direct_text_item(direct_item(contact_id="999", display="ghost")) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_real_v7_payload_with_suffixed_local_name():
|
||||||
|
item = {
|
||||||
|
"chatInfo": {
|
||||||
|
"type": "direct",
|
||||||
|
"chatId": 6,
|
||||||
|
"contact": {
|
||||||
|
"contactId": 6,
|
||||||
|
"localDisplayName": "pepper_1",
|
||||||
|
"displayName": None,
|
||||||
|
"profile": {"displayName": "pepper"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"chatItem": {
|
||||||
|
"chatDir": {"type": "directRcv"},
|
||||||
|
"content": {
|
||||||
|
"type": "rcvMsgContent",
|
||||||
|
"msgContent": {
|
||||||
|
"type": "text",
|
||||||
|
"text": "what is the next thing on my calendar?",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
message = parse_direct_text_item(item)
|
||||||
|
assert message is not None
|
||||||
|
assert message["text"] == "what is the next thing on my calendar?"
|
||||||
|
assert message["contact_id"] == "6"
|
||||||
|
assert message["display_name"] == "pepper"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_accepts_aeson_nested_content_shape():
|
||||||
|
item = direct_item()
|
||||||
|
item["chatItem"]["content"] = {
|
||||||
|
"rcvMsgContent": {"msgContent": {"type": "text", "text": "hi"}}
|
||||||
|
}
|
||||||
|
message = parse_direct_text_item(item)
|
||||||
|
assert message is not None
|
||||||
|
assert message["text"] == "hi"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- send / accept commands ----
|
||||||
|
|
||||||
|
def test_send_command_is_structured_not_shortcut():
|
||||||
|
command = send_text_command("4", "hello")
|
||||||
|
assert command.startswith("/_send @4 json ")
|
||||||
|
payload = json.loads(command.split(" json ", 1)[1])
|
||||||
|
assert payload[0]["msgContent"]["type"] == "text"
|
||||||
|
assert payload[0]["msgContent"]["text"] == "hello"
|
||||||
|
assert command != "/_send @4 hello"
|
||||||
|
|
||||||
|
|
||||||
|
def test_accept_command_uses_v7_request_id():
|
||||||
|
assert accept_command({"contactRequest": {"contactRequestId": 7, "contactId_": 9}}) == "/_accept 7"
|
||||||
|
assert accept_command({"contactRequest": {"contactId": 4}}) == "/_accept 4"
|
||||||
|
assert accept_command({}) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_contact_link_reads_both_shapes():
|
||||||
|
nested = {"contactLink": {"connLinkContact": {"connShortLink": "simplex:/a"}}}
|
||||||
|
flat = {"connLinkContact": {"connFullLink": "https://a"}}
|
||||||
|
direct = {"connShortLink": "simplex:/b"}
|
||||||
|
assert contact_link(nested)["connShortLink"] == "simplex:/a"
|
||||||
|
assert contact_link(flat)["connFullLink"] == "https://a"
|
||||||
|
assert contact_link(direct)["connShortLink"] == "simplex:/b"
|
||||||
|
assert contact_link({}) == {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---- daemon: accept + round-trips ----
|
||||||
|
|
||||||
|
class FakeWS:
|
||||||
|
"""A fake simplex-chat socket that answers correlated commands."""
|
||||||
|
|
||||||
|
def __init__(self, daemon, responses):
|
||||||
|
self.daemon = daemon
|
||||||
|
self.responses = list(responses)
|
||||||
|
self.sent = []
|
||||||
|
|
||||||
|
async def send(self, raw):
|
||||||
|
message = json.loads(raw)
|
||||||
|
self.sent.append(message)
|
||||||
|
if self.responses:
|
||||||
|
response = self.responses.pop(0)
|
||||||
|
await self.daemon._consume(
|
||||||
|
json.dumps({"corrId": message["corrId"], "resp": response})
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _contact_request_event(req):
|
||||||
|
return json.dumps(
|
||||||
|
{"resp": {"type": "receivedContactRequest", "contactRequest": req}}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_accept_uses_v7_contact_request_id():
|
||||||
|
daemon = SimplexDaemon("ws://x", auto_accept=True)
|
||||||
|
ws = FakeWS(daemon, [])
|
||||||
|
daemon._ws = ws
|
||||||
|
asyncio.run(daemon._consume(_contact_request_event({"contactRequestId": 7, "contactId_": 9})))
|
||||||
|
assert [m["cmd"] for m in ws.sent] == ["/_accept 7"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_accept_falls_back_to_contact_id_for_legacy_events():
|
||||||
|
daemon = SimplexDaemon("ws://x", auto_accept=True)
|
||||||
|
ws = FakeWS(daemon, [])
|
||||||
|
daemon._ws = ws
|
||||||
|
asyncio.run(daemon._consume(_contact_request_event({"contactId": 4})))
|
||||||
|
assert [m["cmd"] for m in ws.sent] == ["/_accept 4"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_accept_disabled_sends_nothing():
|
||||||
|
daemon = SimplexDaemon("ws://x", auto_accept=False)
|
||||||
|
ws = FakeWS(daemon, [])
|
||||||
|
daemon._ws = ws
|
||||||
|
asyncio.run(daemon._consume(_contact_request_event({"contactRequestId": 7})))
|
||||||
|
assert ws.sent == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_chat_items_reach_the_handler():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
seen = []
|
||||||
|
daemon._on_message = seen.append
|
||||||
|
event = json.dumps(
|
||||||
|
{"resp": {"type": "newChatItems", "chatItems": [direct_item(text="hi")]}}
|
||||||
|
)
|
||||||
|
asyncio.run(daemon._consume(event))
|
||||||
|
assert [m["text"] for m in seen] == ["hi"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_correlated_response_resolves_pending_future():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
daemon._ws = FakeWS(daemon, [])
|
||||||
|
future = daemon._loop.create_future()
|
||||||
|
daemon._pending["req-9"] = future
|
||||||
|
await daemon._consume(
|
||||||
|
json.dumps({"corrId": "req-9", "resp": {"type": "ok", "value": 1}})
|
||||||
|
)
|
||||||
|
assert "req-9" not in daemon._pending, "a resolved request must be dropped"
|
||||||
|
return future.result()
|
||||||
|
|
||||||
|
assert asyncio.run(scenario()) == {"type": "ok", "value": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_address_returns_existing_link():
|
||||||
|
daemon = SimplexDaemon("ws://x", user_id=3)
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
ws = FakeWS(
|
||||||
|
daemon,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "userContactLink",
|
||||||
|
"user": {"userId": 3},
|
||||||
|
"contactLink": {
|
||||||
|
"userContactLinkId": 1,
|
||||||
|
"connLinkContact": {
|
||||||
|
"connShortLink": "simplex:/a",
|
||||||
|
"connFullLink": "https://a",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
daemon._ws = ws
|
||||||
|
return await daemon.address(timeout=5), ws
|
||||||
|
|
||||||
|
result, ws = asyncio.run(scenario())
|
||||||
|
assert result == {"short_link": "simplex:/a", "full_link": "https://a", "created": False}
|
||||||
|
assert [m["cmd"] for m in ws.sent] == ["/_show_address 3"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_address_creates_when_missing():
|
||||||
|
daemon = SimplexDaemon("ws://x", user_id=1)
|
||||||
|
|
||||||
|
async def scenario():
|
||||||
|
daemon._loop = asyncio.get_running_loop()
|
||||||
|
ws = FakeWS(
|
||||||
|
daemon,
|
||||||
|
[
|
||||||
|
{"type": "userContactLink", "contactLink": None},
|
||||||
|
{
|
||||||
|
"type": "userContactLinkCreated",
|
||||||
|
"connLinkContact": {"connShortLink": "simplex:/new", "connFullLink": ""},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
daemon._ws = ws
|
||||||
|
return await daemon.address(timeout=5), ws
|
||||||
|
|
||||||
|
result, ws = asyncio.run(scenario())
|
||||||
|
assert result == {"short_link": "simplex:/new", "full_link": "", "created": True}
|
||||||
|
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1", "/_address 1"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_address_without_connection_raises():
|
||||||
|
daemon = SimplexDaemon("ws://x")
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
daemon.request_address(timeout=1)
|
||||||
Reference in new issue
Block a user