axmbly-openclaw 0.0.0-stage → 2.0.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +128 -2
  2. package/TESTED.json +15 -0
  3. package/dist/src/cli.js +222 -0
  4. package/dist/src/config.js +62 -0
  5. package/dist/src/consent/quiet.js +57 -0
  6. package/dist/src/consent/standing-book.js +127 -0
  7. package/dist/src/consent/standings.js +198 -0
  8. package/dist/src/constants.js +186 -0
  9. package/dist/src/crypto/ids.js +83 -0
  10. package/dist/src/crypto/keys.js +77 -0
  11. package/dist/src/crypto/seal.js +106 -0
  12. package/dist/src/crypto/vectors.js +133 -0
  13. package/dist/src/enrol.js +75 -0
  14. package/dist/src/errands/manager.js +1473 -0
  15. package/dist/src/errands/prompt.js +84 -0
  16. package/dist/src/errands/surface.js +176 -0
  17. package/dist/src/errands/types.js +1 -0
  18. package/dist/src/gateway/link.js +148 -0
  19. package/dist/src/gateway/socket.js +62 -0
  20. package/dist/src/generated/release.js +3 -0
  21. package/dist/src/index.js +144 -0
  22. package/dist/src/log.js +31 -0
  23. package/dist/src/mirror/agent-state.js +125 -0
  24. package/dist/src/mirror/compose.js +22 -0
  25. package/dist/src/mirror/history.js +278 -0
  26. package/dist/src/mirror/media.js +178 -0
  27. package/dist/src/mirror/mirror.js +1215 -0
  28. package/dist/src/protocol/devicelist.js +113 -0
  29. package/dist/src/protocol/kinds.js +62 -0
  30. package/dist/src/protocol/outbound.js +174 -0
  31. package/dist/src/protocol/payload.js +27 -0
  32. package/dist/src/protocol/verify.js +187 -0
  33. package/dist/src/relay/client.js +447 -0
  34. package/dist/src/relay/frames.js +58 -0
  35. package/dist/src/relay/socket.js +38 -0
  36. package/dist/src/selfcheck.js +256 -0
  37. package/dist/src/service.js +618 -0
  38. package/dist/src/state/adapter-state.js +305 -0
  39. package/dist/src/state/signals.js +160 -0
  40. package/dist/src/state/store.js +105 -0
  41. package/dist/src/util/bytes.js +47 -0
  42. package/dist/src/util/timing.js +67 -0
  43. package/dist/src/util/uuid.js +29 -0
  44. package/dist/src/version.js +19 -0
  45. package/docs/SURFACE.md +26 -0
  46. package/openclaw.plugin.json +63 -0
  47. package/package.json +45 -4
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # axmbly-openclaw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Axmbly adapter for OpenClaw: an in-process OpenClaw plugin (id `axmbly`) that makes a gateway an Axmbly participant (Axmbly v2 spec, Gateway adapter; `docs/PROTOCOL-AXMBLY.md` section 11; discovery verdict `docs/discovery/DISCOVERY-A.md`, D-049).
4
+
5
+ Private. Specification and shared protocol documents live in the `assembly` repository (`SPEC.md`, `docs/PROTOCOL-AXMBLY.md`, `docs/RELAY.md`, `docs/PROTOCOL.md`); this repository links to them and holds only its own code. Working title Axmbly (formerly Assembly), D-046.
6
+
7
+ ## What it does (Phase A)
8
+
9
+ - Holds the gateway's device keys (Ed25519 sign, X25519 seal) in the plugin's own keyed store (`api.runtime.state.openKeyedStore`); nothing is written under the gateway's identity location.
10
+ - `openclaw axmbly enrol` prints the enrolment code (`axmbly-enrol:1:` + base64url JSON `{v, sign, seal, nonce, relay}`) as a QR and as paste text, rotating the nonce every 60 s; every printed nonce stays valid for 5 minutes. `openclaw axmbly reset` retires the identity on the relay with the stored tombstone, then points to `start-over`.
11
+ - Dials the relay outbound (`wss://<relayHost>/v1`), authenticates by signature, syncs and acks, pings every 25 s, and follows the connection schedule (5 s open timeout; fixed 2 s retry after a hung or server-closed attempt; backoff 1-2-4-8-16-30 s only when the host is unreachable; `DEVICE_UNKNOWN` every 3 s for 5 minutes). Two relay close rules (F-A26): close `4001` (superseded: another copy of this gateway device took over) stops the client until the gateway restarts or the next enrolment, and close `1013` or an `auth.prove` answered `RATE_LIMITED` retries after the relay's `retryAfterMs` (at most 60 s), else the fixed 2 s, without advancing the backoff.
12
+ - Opens a loopback `GatewayClient` (`openclaw/plugin-sdk/gateway-runtime`) to its own gateway as `gateway-client` / `backend` with the shared token, scopes `operator.read|write|approvals` (and `operator.admin` from Phase B, for errand sessions), `caps: ["tool-events"]`, and subscribes to every agent's `agent:<id>:main` with `includeApprovals`. The connect carries the plugin's own Ed25519 device identity (kept in the plugin's keyed store, separate from the Axmbly sign key; id = SHA-256 of the raw public key as OpenClaw derives it): the gateway grants approval review (`sessions.messages.subscribe` with `includeApprovals`, `exec.approval.resolve`) only to a connect that carries a device id, and a local backend client with a signed identity is admitted on loopback without a pairing record (F-A27).
13
+ - Mirrors each main session to the owner's phone as sealed envelopes: `text` and `attachment` (with `agentId` when an agent wrote it), run errors as one `text` with `style: status` (the gateway's persisted `custom` row when there is one, else the live error text; F-A16), `agentState` per the adapter-side table plus the 30 s heartbeat, `approval` with status updates, `roster` (D-021 name chain), history backfill (newest 100 per agent, UUIDv5 ids over `sessionKey|source|rawSeq|rowIndex` from each row's `__openclaw.transcriptPosition`, F-A36: `sessions.reset` keeps the `sessionId` and restarts `seq`, but the transcript position keeps counting; a row from a gateway without one falls back to `sessionKey|sessionId|seq|rowIndex`, F-A28, with one warning per session key; sibling rows of one record carry `sentAt = record timestamp + rowIndex` ms, F-A14). Live mirroring reads `chat.history` in pages until a record at or below the last mirrored `rawSeq` is seen (F-A5); the mark is kept per session key as `{seq, rawSeq, source, sessionId}`, a changed `source` or `sessionId` restarts from a fresh baseline (F-A36, F-A18), and a mark written before F-A36 is upgraded to the page's newest position without mirroring anything in that pass. `historyRequest` pages are anchored on the oldest mirrored transcript position, so live rows landing meanwhile never cause a re-send (F-A15, F-A36). A second enrolment on the pinned identity (a reinstalled or replaced phone, or a new relay; recognised by an attestation nonce history was not yet sent for, on a list the adapter accepted as current) sends the roster and the newest page per agent again, once (F-A40); backfill passes, the reset and Load older run one at a time (F-A41); in history, a row the owner typed on the phone goes out under the phone's original `msgId`, so a fresh install gets it back and a phone that still holds it drops the repeat (F-A42).
14
+ - Applies the phone's `text`/`attachment` (`chat.send` with the `msgId` as `idempotencyKey`), `approvalReply` (`exec.approval.resolve`), `historyRequest`, `contactSet`, `tombstone`. A box that fails permanently (blob gone from the relay, hash mismatch, over 18 MiB, `chat.send` or `exec.approval.resolve` rejected with a non-transient code) is acked after one grey status line to the principal; only transient failures (gateway detached, relay unreachable, `UNAVAILABLE`, timeouts) leave the box for redelivery (F-A4).
15
+ - Media: agent artifacts via `artifacts.download`, encrypted as blobs (`nonce || ct || tag`, ChaCha20-Poly1305) and uploaded in 512 KiB chunks; the gateway's bearer URL is a logged fallback for documents only, and a block's `url` is used only when it resolves to the gateway's own origin under `/api/chat/media/outgoing/` with redirects refused; anything else is dropped with one log line and one status line (F-A3). Phone uploads are decrypted and passed to `chat.send` as base64 attachments (18 MiB cap).
16
+ - `gateway_stop` (5 s budget): `agentState: unavailable` for every agent before the process exits ([r5] with `reason: stopped`, below).
17
+
18
+ ## What it adds (Phase B, D-070)
19
+
20
+ - **Standings.** `standing.get` at relay attach, every 10 minutes, before every friend-facing send and after every handshake-family message sealed to this gateway; both signatures of each row are verified against pinned identities (the principal and the `contactSet` contacts), and a grant counts only when the recipient's own signature says `granted` (a principal-signed widening never widens). A verified `revoke` envelope revokes at once. The gateway never calls `standing.put`.
21
+ - **Errands.** `start-errand {recipient, goal}` is offered to each agent's main session only; it opens a delegate errand to the friend's phone, or an agent-to-agent errand when the friend's agent also holds the principal's grant (narrower tier and disclosure). The first inbound from a standing agent's gateway under mutual standing opens a responder errand. One durable record per errand in the keyed store; the outbound counter is written before the frame is handed to the outbox and never re-credited. Caps 1/2/8, the 24 h nudge wait, the recipient's quiet hours, "stop", `errandControl {stop|continue}`, 7-day idle, revoke, `reportBack`, `errandClosed`, `tierRestated` and `errandState` as in `docs/PROTOCOL-AXMBLY.md` 9.11.
22
+ - **Sessions.** One gateway session per errand, `agent:<agentId>:axmbly:<errandId>`, created and driven over the loopback client (scopes now include `operator.admin`): `chat.send` with `suppressCommandInterpretation: true` and `deliver: false`, the run's end from the session's `chat`/`agent` events, 120 s per turn with one retry, `sessions.delete` at close. The model's plain text goes nowhere; only `send-message` and `propose-times` reach anyone.
23
+ - **Hooks and tools.** One tool factory (six tools, non-optional, `catalogMode: "direct-only"`); `before_prompt_build` replaces an errand session's whole system prompt with the friend-facing floor and narrows the tools by `toolsAllow`; `before_agent_run` blocks any errand run whose system prompt is not the adapter's; `before_tool_call` refuses an errand tool outside an errand, `start-errand` outside a main session, and any tool outside the errand's tier/disclosure list. The two conversation hooks need `plugins.entries.axmbly.hooks.allowConversationAccess: true`; without it the adapter mirrors as before, logs one warning, and errands refuse to open ("Errands need the hook permission").
24
+ - **F-A44.** A `RATE_LIMITED` answer to a `backfill` frame sets history aside until `retryAfterMs`; live frames go first.
25
+
26
+ Headless runs: `dev/phone-sim.mjs` (a scripted phone, and optionally a scripted friend's gateway, on the **local** relay only) with the container gateways in `dev/container`; see `dev/README.md`.
27
+
28
+ ## What it adds (r5, 2.0.0-beta.11, the update slice)
29
+
30
+ The adapter is the only piece of Axmbly that speaks OpenClaw, so it is the only piece an OpenClaw update can break. From 2.0.0-beta.11 it knows what it depends on, says so when any of it fails, and is packaged for a registry (PROTOCOL-AXMBLY sections 13 and 14; D-163, D-166...D-171).
31
+
32
+ - **The surface list.** `docs/SURFACE.md` names every OpenClaw API, hook, gateway method, event and SDK import the code uses, S1...S14. `tools/surface-guard.mjs` runs in every build (`npm run build`, `npm run build:r5`) and fails it, naming the name, when the code uses one the file does not list or the file lists one the code no longer uses.
33
+ - **The self-check at load.** The relay connection starts first, with the keyed store (S12) and the adapter's own code only. When the local gateway answers, every probe in the table runs before the normal attach (presence in the gateway's own hello-ok feature list, a read of `agents.list` and `server.version`, and a throwaway session created and deleted; nothing is ever sent to an agent). All pass: as before. Any fail: the adapter still attaches, sends `roster`, sends once for every agent `agentState {state: unavailable, reason: incompatible, failed: ["S6 per-session tool restriction", ...]}`, heartbeats every 30 s with `reason` and `failed` at the heartbeat's top level and every agent `unavailable`, holds back per-agent live states, logs one line with the failed ids, and re-probes every five minutes; a re-probe that passes sends each agent's live state and the next heartbeat carries live states again, with no restart. No hello-ok within two minutes of start reports S2 alone.
34
+ - **`openclaw axmbly check`** prints the same table with pass or fail per row and the three versions (`Axmbly plugin <version> on OpenClaw <version>, minimum app build 12`), using the local gateway socket only; exit code 1 when a row fails.
35
+ - **`roster.adapter`** on every `roster`: `{version, openclaw, testedAgainst, minBuild}`. `version` is this package's version; `openclaw` is the gateway's hello-ok `server.version` (S11; cached in the keyed store for a roster sent before an attach); `testedAgainst` is the list baked at release from TESTED.json (empty in a development build, which logs one line saying so); `minBuild` is 12 from 2.0.0-beta.12 (11 at 2.0.0-beta.11).
36
+ - **`reason: stopped`.** `gateway_stop` (and the gateway's own `shutdown` event) sends `agentState {unavailable, reason: stopped}` for every agent; the host's `gateway_stop` reason string is logged verbatim and mapped to nothing. A crash still sends nothing.
37
+ - **`notify: true`** on the `msg.send` of every `approval` and of nothing else, so the relay can push an approval to a closed phone.
38
+
39
+ ## What it adds (2.0.0-beta.12, D-187)
40
+
41
+ Two changes to what the adapter puts in front of the model and on the wire. **A quoted reply reaches the agent:** a `text` from the owner's phone may carry `replyText` (the selected text, or the quoted message's text when nothing was selected, 280 characters at most; `replyTo`/`replyRange` are still carried for the phones and not interpreted here), and the adapter composes the one `chat.send` message as a Markdown blockquote of it (every line prefixed `> `, a blank line inside it as `>`), one blank line, then the typed text, so the gateway's own transcript shows what the agent read; an attachment's caption is composed the same way; a `replyText` that is not a string is dropped as `bad_payload` like a malformed `replyTo`. **The agent's words before its tools ran are marked:** an assistant transcript record whose words were followed by tool calls goes out as `text` with `style: working`, live and in backfill alike (every mirroring path projects through `projectPage`), keeping its `agentId`, `msgId` and `sentAt`; a record with text only carries no style, and the run-error `custom` row stays `status`. Three signs, any one counts: a tool-call block in the record's `content` beside the text (`{type: "toolCall", id, name, arguments}`), a `stopReason` naming tool use, or, on the page, a later row of the same `__openclaw.runId` that is a `toolResult` or carries a tool-call block. The page sign is what OpenClaw 2026.10.4 needs: its store keeps text, `toolCall` block and `stopReason: "toolUse"` in one record, but `chat.history` shows that record as two rows (the text without its `stopReason`, then the `toolCall` block), and a call to a tool the session lacks leaves only the `toolResult` row that follows. `minBuild` becomes 12: a beta.11 phone decodes `style` strictly and would drop every `working` text as `bad_payload`, so it is told to update; a beta.12 phone reads an unknown style as absent.
42
+
43
+ ## Versions
44
+
45
+ The package version is in lockstep with the app tag from 2.0.0-beta.11 (D-170): `2.0.0-beta.11`, then 2.0.0 and every later app tag, whether or not the adapter changed. Compatibility is carried by `minBuild` (the lowest app build number the adapter expects, a constant in `src/constants.ts`), not by the version. `package.json` `openclaw.compat` declares the supported OpenClaw range; whether OpenClaw enforces it at install is not confirmed, and the self-check is the guard either way.
46
+
47
+ ## Release
48
+
49
+ Publishing is the principal's hand; nothing in this repository publishes.
50
+
51
+ 1. **TESTED.json** must list at least one OpenClaw version on which the nightly ran green. It is written by the nightly (`docs/NIGHTLY.md`), never by hand.
52
+ 2. **Build the package:** `npm run release` (`node tools/release.mjs`). It refuses with one line while TESTED.json is empty; otherwise it runs the surface guard, compiles `src/` (never `dist/`), stages `dist-release/<version>/package/` (package.json without `private`, scripts and devDependencies and with `axmbly: {testedAgainst, minBuild}`; openclaw.plugin.json; README; docs/SURFACE.md; TESTED.json; `dist/src/**` with `generated/release.js` baked from TESTED.json) and runs `npm pack` there: `dist-release/<version>/axmbly-openclaw-<version>.tgz`, recorded with its integrity in `release.json`.
53
+ 3. **Check the install shape** on a clean container (never on a live gateway): `openclaw plugins install npm-pack:<tgz> --force --accept-capabilities`, then `openclaw axmbly check` and `openclaw plugins list` (the Version column shows the released version).
54
+ 4. **`openclaw plugins pack`** (`--root <package> --out <file.tgz> --json`) bundles a built plugin into "an exact artifact for activation approval" and prints its path, SHA-256 and the activation request; it is not a registry publish, and neither a ClawHub nor an npm install needs it. Tried on 2026.10.4 in a container against the 2.0.0-beta.11 package: it loads the plugin from `--root` (so the package's dependencies must be installed there first) and then refuses, "plugin entry does not expose tool or feature authoring metadata": it is for plugins built with OpenClaw's authoring metadata (`openclaw plugins build`), which this plugin does not use. The release therefore does not depend on it; `node tools/release.mjs --openclaw-pack openclaw` remains as an option for the day it applies (run it inside a container).
55
+ 5. **Publish (the principal's hand, from CI with provenance, one organisation account with two-factor authentication).** ClawHub is the target, because `openclaw plugins install` takes a ClawHub package with no `--force`:
56
+ ```bash
57
+ npm i -g clawhub
58
+ clawhub login
59
+ cd dist-release/<version>/package
60
+ clawhub package publish <org>/axmbly --dry-run
61
+ clawhub package publish <org>/axmbly
62
+ ```
63
+ The install command is then `openclaw plugins install clawhub:<org>/axmbly`, and the Set up screen's open field (`setup.installCommand`) is set to the form that resolves. Fallback if ClawHub cannot carry it, npm with provenance from GitHub Actions (OIDC), the package name to be chosen (the repository's `axmbly-openclaw`, or `axmbly`), the license field to be settled (it is `UNLICENSED` today):
64
+ ```bash
65
+ cd dist-release/<version>/package
66
+ npm publish --provenance --access public
67
+ ```
68
+ and the command shown carries `--force` as OpenClaw requires for a non-ClawHub source: `openclaw plugins install <npm name> --force`.
69
+
70
+ **Done 2026-11-16 (D-183 in the app repository): the package is on npm as `axmbly-openclaw`**, published by the principal's hand from `dist-release/2.0.0-beta.11/package` with `npm publish --access public --tag beta` (npm refuses a pre-release without a dist-tag). OpenClaw refuses a pre-release through the plain name, so the install command while the version is a pre-release is `openclaw plugins install axmbly-openclaw@beta --force` (add `--accept-capabilities` for a non-interactive install), and `openclaw plugins install axmbly-openclaw --force` from 2.0.0. Proven on a clean 2026.10.4 container: installed under the manifest id `axmbly`, listed at 2.0.0-beta.11, `openclaw axmbly check` S1…S15 pass.
71
+ 6. **Updates.** Whether `openclaw update` refreshes a published plugin is not confirmed; `openclaw plugins update axmbly` (or `--all`, `--dry-run` to preview) is the manual form.
72
+
73
+ `--link` installs (`openclaw plugins install -l <path>`) are for development only.
74
+
75
+ ## The nightly
76
+
77
+ `sh dev/nightly/nightly.sh` installs the release candidate into a fresh container of the newest OpenClaw beta, runs the unit suite, `openclaw axmbly check` and a gateway-side smoke, and appends a green night to TESTED.json or writes a red or no-run file under `dev/nightly/out/`. Seven consecutive green nights, with at least one OpenClaw beta change among them, gate the 2.0.0 upload. Full description, outcomes and the launchd template: `docs/NIGHTLY.md`.
78
+
79
+ ## Install for the fix pass
80
+
81
+ The live install is the principal's step (lanes never install, enable or change gateway config).
82
+
83
+ ```bash
84
+ cd axmbly-openclaw
85
+ npm install
86
+ npm run build # compiles to dist/ (the plugin entry is dist/src/index.js)
87
+ openclaw plugins install --link /Users/agent-discovery/Local_Documents/activeprojects/axmbly-openclaw
88
+ ```
89
+
90
+ `--link` keeps the plugin at this path (so `node_modules/ws` resolves); a copy install needs `npm install --omit=dev` in the managed copy. A noninteractive install of a local path needs `--force` after review (the install docs call it an arbitrary source).
91
+
92
+ Configuration (`openclaw config set` or the config file), under `plugins.entries.axmbly`:
93
+
94
+ | Key | Meaning | Default |
95
+ | --- | --- | --- |
96
+ | `config.relayHost` | relay host, `hostname[:port]`; a loopback host (`localhost:8787`, the local image) is dialled over `ws://`, anything else over `wss://` | `relay.axmbly.com` |
97
+ | `config.gatewayToken` | fallback only (F-A6, see below): the gateway's shared token, used only on the loopback socket to the gateway itself; never logged | unset |
98
+ | `hooks.allowConversationAccess` | **Phase B**: lets the plugin's `before_prompt_build` and `before_agent_run` hooks assemble and guard the friend-facing context; without it errands refuse to open (mirroring is unaffected). Setting it hot-replaces the plugin (F-A38): only together with an approved restart | unset |
99
+
100
+ The gateway port is read from the gateway config (`gateway.port`, default 18789).
101
+
102
+ **Gateway token (F-A6).** The adapter reads the gateway's own token first, from `gateway.auth.token` in the gateway config as the plugin SDK exposes it (`api.config.gateway.auth.token`; typing `OpenClawPluginApi.config: OpenClawConfig` → `gateway?: GatewayConfig` → `auth?: GatewayAuthConfig` → `token?: SecretInput`, OpenClaw 2026.10.4 `dist/channel-core-Dw23qZdV.d.ts:21323`, `dist/agent-scope-Dajnzfj6.d.ts:13014, :11853-11854, :11821-11823, :4266`). When that value is a plain string nothing else is needed: the principal types no token anywhere. When it is absent or a structured secret ref (`{source, provider, id}`, which this plugin does not resolve), the adapter falls back to `plugins.entries.axmbly.config.gatewayToken`; set that key by editing the config file in an editor, never on a command line (shell history) and never through tooling that would echo it. The log says which source was used (`gateway token read from …`); neither value is ever logged.
103
+
104
+ Then:
105
+
106
+ ```bash
107
+ openclaw axmbly enrol # scan with the Axmbly app, or Paste code; Ctrl-C when enrolled
108
+ openclaw plugins inspect axmbly --runtime --json
109
+ openclaw axmbly reset # only if the phone is lost: retires the identity with the stored tombstone
110
+ openclaw axmbly recover # slice ID: prints the recovery QR and text for a new phone (needs the owner's recovery code; no network)
111
+ openclaw axmbly start-over # slice ID: clears Axmbly state and rotates the device keys; refuses while attached unless --force
112
+ ```
113
+
114
+ **Identity lifecycle (slice ID, PROTOCOL-AXMBLY `[r3]`).** The owner's phone sends a `recoveryCopy` (its identity key sealed under a recovery code the gateway never sees); the adapter keeps the newest `codeVersion` beside its device keys, never opens it, and answers with a `receipt`. `recover` prints `axmbly-recover:1:` + base64url JSON `{v, identityPub, handle, codeVersion, nonce, ct, relay}` from that copy; it works after `reset` too. A `restoreRequest` from the owner's phone (a recovered or reinstalled phone) is answered with a full `contactSet`, a `roster` and the newest 100 rows per agent under the same ids as at enrolment; the log says `restore: contacts, roster and history sent (n agents, m rows)` (and `enrolment: …` after a pin). The owner's list is refetched before sealing when the held copy is older than 10 minutes, so a phone dropped at recovery stops receiving. Close `4002` (this gateway was replaced on the owner's list) or `4003` (identity retired) stops the relay client at once until a restart or the next enrolment. An `errandClosed` with reason `error` from a thread member (the replaced gateway owner's phone) closes the errand with its `reportBack` and no second `errandClosed`; an ordinary restart closes nothing. `start-over` reads the liveness mark the heartbeat writes (attached = younger than 90 s); a running service notices a forced wipe at its next 30 s tick, logs that it is not enrolled and waits for the next `enrol` code.
115
+
116
+ Gateway logs are prefixed `axmbly:`. Drop lines are `axmbly: drop reason=<token> thread=<8 hex> msg=<8 hex>` with the token from the closed list of 17 (`bad_payload` for a malformed `P` or undecodable fields, `kind_not_permitted` for an unknown kind; BG-7); `replay` is at debug level, and a seq-bearing envelope not above the held seq is not a drop but `ignored stale_seq` at debug level. No key material, token, handle or message content is ever logged.
117
+
118
+ ## Development
119
+
120
+ ```bash
121
+ npm test # build, then node:test against dist/ (mock relay on ws, mock gateway behind the socket seam)
122
+ npm run test:r5 # the same into dist-r5/: use it whenever a live gateway loads the plugin from this repository's dist/
123
+ npm run build
124
+ npm run vectors # regenerates ../assembly/docs/vectors/seal-v1.json from fixed seeds (pass a path to write elsewhere)
125
+ ```
126
+
127
+ Runtime dependency: `ws` only (RULE-03 expected). The OpenClaw plugin SDK is a peer resolved by the gateway's loader; `src/sdk-types.d.ts` declares the subset this plugin uses, cited to the shipped typings, and the SDK-facing files were type-checked against the real typings of OpenClaw 2026.10.4.
128
+
129
+ Layout: `src/crypto` (sealed box, ids, keys, vector generator), `src/protocol` (kinds, payload, device lists, verification on receive, outbound), `src/relay` (client, frames, socket), `src/gateway` (loopback link and SDK socket), `src/mirror` (agent state, history projection, media, the mirror), `src/state` (keyed stores), `src/enrol.ts`, `src/cli.ts`, `src/service.ts`, `src/index.ts`.
package/TESTED.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "about": "OpenClaw versions on which the nightly ran green (docs/NIGHTLY.md). Appended by dev/nightly/nightly.sh, never by hand (D-170). tools/release.mjs refuses to produce a package while this list is empty and bakes it into the package as roster.adapter.testedAgainst.",
3
+ "tested": [
4
+ {
5
+ "openclaw": "2026.10.4",
6
+ "date": "2026-11-16",
7
+ "commit": "9079293abaffdede45695bad7402c5f76df9a147"
8
+ },
9
+ {
10
+ "openclaw": "2026.11.5-beta.3",
11
+ "date": "2026-11-16",
12
+ "commit": "9079293abaffdede45695bad7402c5f76df9a147"
13
+ }
14
+ ]
15
+ }
@@ -0,0 +1,222 @@
1
+ import { DEFAULT_RELAY_HOST, HEARTBEAT_INTERVAL_MS, MIN_APP_BUILD, OPEN_TIMEOUT_MS, QR_RECOVER_PREFIX } from "./constants.js";
2
+ import { checkLines, helloVersion, runProbes } from "./selfcheck.js";
3
+ import { uuidv4 } from "./util/uuid.js";
4
+ import { FileSignals } from "./state/signals.js";
5
+ import { packageVersion } from "./version.js";
6
+ import { EnrolSession } from "./enrol.js";
7
+ import { oneShotRelayRequest } from "./relay/client.js";
8
+ import { RelayError } from "./relay/frames.js";
9
+ import { b64u, utf8 } from "./util/bytes.js";
10
+ /** `renderQrTerminal` from the public SDK subpath `openclaw/plugin-sdk/media-runtime` (dist/plugin-sdk/media-runtime.d.ts:153). */
11
+ export const sdkQrRenderer = async (text) => {
12
+ try {
13
+ const mod = await import("openclaw/plugin-sdk/media-runtime");
14
+ return await mod.renderQrTerminal(text, { small: true });
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ };
20
+ export function registerAxmblyCli(program, deps) {
21
+ const root = program.command("axmbly").description("Enrol this gateway with your Axmbly phone, recover, start over, or retire the identity");
22
+ root
23
+ .command("enrol")
24
+ .description("Print the enrolment code (QR and paste text); a fresh code every 60 s until you stop it")
25
+ .option("--once", "print one code and exit")
26
+ .action(async (opts) => {
27
+ await runEnrol(deps, opts.once === true);
28
+ });
29
+ root
30
+ .command("reset")
31
+ .description("Retire the identity on the relay with the stored tombstone (if the phone is lost)")
32
+ .action(async () => {
33
+ await runReset(deps);
34
+ });
35
+ root
36
+ .command("recover")
37
+ .description("Print the recovery code (QR and paste text) for a new phone; it needs your recovery code to open")
38
+ .action(async () => {
39
+ await runRecover(deps);
40
+ });
41
+ root
42
+ .command("check")
43
+ .description("Check this OpenClaw against every surface the Axmbly plugin depends on (docs/SURFACE.md) and print the versions")
44
+ .action(async () => {
45
+ await runCheck(deps);
46
+ });
47
+ root
48
+ .command("start-over")
49
+ .description("Clear this gateway's Axmbly state and device keys, to enrol it under another identity")
50
+ .option("--force", "clear even while the adapter is attached to the relay")
51
+ .action(async (opts) => {
52
+ await runStartOver(deps, opts.force === true);
53
+ });
54
+ }
55
+ /**
56
+ * [r5] `openclaw axmbly check`: opens the local gateway socket (no other network), runs the self-check table and prints
57
+ * it with the three versions (`cli.check.header`, `cli.check.row`). Exit code 1 when a blocking row fails.
58
+ */
59
+ export async function runCheck(deps) {
60
+ const c = deps.check;
61
+ let hello;
62
+ let attached = false;
63
+ let sock;
64
+ if (c?.gatewaySocketFactory) {
65
+ const factory = c.gatewaySocketFactory;
66
+ await new Promise((resolve) => {
67
+ const timer = setTimeout(resolve, c.helloTimeoutMs ?? 10_000);
68
+ timer.unref?.();
69
+ sock = factory({
70
+ onHelloOk: (h) => {
71
+ hello = h;
72
+ attached = true;
73
+ clearTimeout(timer);
74
+ resolve();
75
+ },
76
+ onEvent: () => { },
77
+ onClose: () => {
78
+ attached = false;
79
+ clearTimeout(timer);
80
+ resolve();
81
+ },
82
+ onConnectError: (e) => deps.log.debug(`check: gateway connect error: ${e.message}`),
83
+ });
84
+ });
85
+ }
86
+ else {
87
+ deps.out("No gateway token is readable from gateway.auth.token or plugins.entries.axmbly.config.gatewayToken; the gateway rows cannot be checked.");
88
+ }
89
+ const s = sock;
90
+ try {
91
+ const results = await runProbes({
92
+ host: c?.host ?? { registered: { service: false, gatewayStop: false, tools: false }, hooks: { before_prompt_build: false, before_agent_run: false, before_tool_call: false }, conversationAccess: false },
93
+ storeReadable: async () => (await deps.state.deviceKeys()) !== undefined,
94
+ hello: () => hello,
95
+ gateway: {
96
+ request: (m, p) => (s && attached ? s.request(m, p) : Promise.reject(new Error("gateway not attached"))),
97
+ get isAttached() {
98
+ return attached;
99
+ },
100
+ },
101
+ forced: c?.forced ?? (() => []),
102
+ ...(deps.state.signals instanceof FileSignals ? { stateDirProbe: () => deps.state.signals.probe() } : {}),
103
+ qrAvailable: c?.qrAvailable ?? (async () => false),
104
+ newId: () => uuidv4(),
105
+ });
106
+ for (const line of checkLines(results, { plugin: packageVersion(), openclaw: helloVersion(hello) ?? "unknown", minBuild: MIN_APP_BUILD }))
107
+ deps.out(line);
108
+ if (results.some((r) => r.blocking && !r.ok))
109
+ c?.setExitCode?.(1);
110
+ return results;
111
+ }
112
+ finally {
113
+ s?.close();
114
+ }
115
+ }
116
+ /** [r3] The line `reset` prints after retiring, and `start-over` prints when done (SPEC "openclaw axmbly start-over"). */
117
+ export const START_OVER_DONE_LINE = "Axmbly state cleared; run openclaw axmbly enrol.";
118
+ /** [r5 fix pass] Printed after the done line only when `--force` cleared the state while the adapter was attached. */
119
+ export const START_OVER_FORCED_LINE = "The running gateway may still hold the old keys until it restarts; restart it before `openclaw axmbly enrol`.";
120
+ export const START_OVER_HINT_LINE = "To enrol this gateway under another identity, run openclaw axmbly start-over.";
121
+ export const RECOVER_REFUSAL_LINE = "No recovery copy is stored on this gateway: your phone sends it when enrolment completes and on every new recovery code. Nothing was printed.";
122
+ /** "Attached": a liveness mark younger than three heartbeat intervals (DISCOVERY-ID D2; adapter-id-1). */
123
+ export const ATTACHED_WINDOW_MS = 3 * HEARTBEAT_INTERVAL_MS;
124
+ /** [r3] `axmbly-recover:1:` + base64url(JSON `{v: 1, identityPub, handle, codeVersion, nonce, ct, relay}`) (section 3). */
125
+ export function buildRecoverQr(copy, relayHost) {
126
+ const payload = { v: 1, identityPub: copy.identityPub, handle: copy.handle ?? "", codeVersion: copy.codeVersion, nonce: copy.nonce, ct: copy.ct, relay: relayHost };
127
+ return `${QR_RECOVER_PREFIX}${b64u(utf8(JSON.stringify(payload)))}`;
128
+ }
129
+ /**
130
+ * [r3] `openclaw axmbly recover`: prints the stored sealed copy and public facts as a QR and as text. No network, no
131
+ * derivation: the gateway never opens the copy, never derives the key, never sees the code ([review] line). It works
132
+ * after `reset` too, so a retired identity's phone can learn its cell (the copy names its identity; adapter-id-8).
133
+ */
134
+ export async function runRecover(deps) {
135
+ const copy = await deps.state.recoveryCopy();
136
+ if (!copy) {
137
+ deps.out(RECOVER_REFUSAL_LINE);
138
+ return;
139
+ }
140
+ const relay = deps.relayHost || DEFAULT_RELAY_HOST;
141
+ const code = buildRecoverQr(copy, relay);
142
+ const qr = deps.qr ? await deps.qr(code) : undefined;
143
+ deps.out("");
144
+ deps.out(qr ?? "(QR rendering unavailable in this process; use the text below)");
145
+ deps.out("");
146
+ deps.out("On the new phone choose Recover an existing account, then scan this code or paste the text, and enter your recovery code:");
147
+ deps.out(code);
148
+ deps.out("");
149
+ deps.out(`Recovery copy codeVersion ${copy.codeVersion}. Relay: ${relay}. It does not expire and is useless without your recovery code.`);
150
+ }
151
+ /**
152
+ * [r3] `openclaw axmbly start-over`: refuses while the adapter is attached (a fresh liveness mark) unless `--force`;
153
+ * otherwise clears the pin and all Axmbly state, rotates the device keys (new deviceId) and prints the cleared line.
154
+ * Never touches the relay, never touches OpenClaw sessions.
155
+ */
156
+ export async function runStartOver(deps, force) {
157
+ const now = deps.timing.now();
158
+ const mark = await deps.state.liveness();
159
+ const age = mark ? now - mark.at : undefined;
160
+ if (!force && age !== undefined && age >= 0 && age < ATTACHED_WINDOW_MS) {
161
+ deps.out(`The Axmbly adapter is attached to the relay (heartbeat ${Math.round(age / 1000)} s ago); stop the gateway first, or run openclaw axmbly start-over --force.`);
162
+ return;
163
+ }
164
+ const before = await deps.state.deviceKeys();
165
+ const keys = await deps.state.wipeForStartOver(now);
166
+ // [r5 fix pass] The running service learns of it from this file, not from the keyed store (beta.3 finding).
167
+ await deps.state.signals.markStartOver({ at: now, devicePrefix: keys.deviceId.slice(0, 8) });
168
+ deps.log.info(`start-over: Axmbly state cleared; device ${before ? before.deviceId.slice(0, 8) : "-"} -> ${keys.deviceId.slice(0, 8)}${force && age !== undefined && age < ATTACHED_WINDOW_MS ? " (forced while attached)" : ""}`);
169
+ deps.out(START_OVER_DONE_LINE);
170
+ if (force && age !== undefined && age >= 0 && age < ATTACHED_WINDOW_MS)
171
+ deps.out(START_OVER_FORCED_LINE);
172
+ }
173
+ export async function runEnrol(deps, once) {
174
+ const keys = await deps.state.ensureDeviceKeys(deps.timing.now());
175
+ const principal = await deps.state.principal();
176
+ if (principal)
177
+ deps.out("This gateway is already enrolled; scanning a new code re-enrols it on the same identity.");
178
+ const session = new EnrolSession(deps.state, keys, deps.relayHost || DEFAULT_RELAY_HOST, deps.timing, async (code) => {
179
+ const qr = deps.qr ? await deps.qr(code) : undefined;
180
+ deps.out("");
181
+ deps.out(qr ?? "(QR rendering unavailable in this process; use Paste code)");
182
+ deps.out("");
183
+ deps.out("Scan with the Axmbly app, or Paste code:");
184
+ deps.out(code);
185
+ deps.out("");
186
+ deps.out(`This code rotates every 60 s and stays valid for 5 minutes. Relay: ${deps.relayHost || DEFAULT_RELAY_HOST}. Device ${keys.deviceId.slice(0, 8)}.`);
187
+ });
188
+ if (once) {
189
+ await session.printOnce();
190
+ return;
191
+ }
192
+ await session.start();
193
+ deps.out("Waiting for the scan; press Ctrl-C to stop. The gateway service completes the enrolment when your phone publishes its device list.");
194
+ await new Promise((resolve) => {
195
+ const onSignal = () => {
196
+ session.stop();
197
+ resolve();
198
+ };
199
+ process.once("SIGINT", onSignal);
200
+ process.once("SIGTERM", onSignal);
201
+ });
202
+ }
203
+ export async function runReset(deps) {
204
+ const tombstone = await deps.state.tombstone();
205
+ if (!tombstone) {
206
+ deps.out("No tombstone is stored on this gateway: the phone delivers it after enrolment completes. Nothing was sent to the relay.");
207
+ return;
208
+ }
209
+ try {
210
+ const res = await oneShotRelayRequest(deps.relayHost || DEFAULT_RELAY_HOST, "identity.retire", { identityPub: tombstone.identityPub, signature: tombstone.signature }, deps.timing, deps.relaySocketFactory, OPEN_TIMEOUT_MS);
211
+ await deps.state.clearPrincipal();
212
+ deps.out(`Identity retired on the relay at ${String(res.retiredAt)}. Contacts will see it as Retired at their next refetch.`);
213
+ deps.out(START_OVER_HINT_LINE);
214
+ }
215
+ catch (e) {
216
+ if (e instanceof RelayError)
217
+ deps.out(`The relay refused the retirement: ${e.code}. ${e.message}`);
218
+ else
219
+ deps.out(`Could not reach the relay: ${e.message}`);
220
+ throw e;
221
+ }
222
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Plugin configuration as the entry reads it from the host `api` (F-A6).
3
+ *
4
+ * The gateway token comes first from the gateway's own config, `api.config.gateway.auth.token`, so the
5
+ * principal types nothing on a command line; the plugin key `plugins.entries.axmbly.config.gatewayToken`
6
+ * is the fallback. Typing, OpenClaw 2026.10.4: `OpenClawPluginApi.config: OpenClawConfig`
7
+ * (dist/channel-core-Dw23qZdV.d.ts:21323); `OpenClawConfig.gateway?: GatewayConfig`
8
+ * (dist/agent-scope-Dajnzfj6.d.ts:12926, :13014); `GatewayConfig.auth?: GatewayAuthConfig` (:11853-11854);
9
+ * `GatewayAuthConfig.token?: SecretInput` (:11821-11823) where `SecretInput = string | SecretRef` (:4266) and
10
+ * `SecretRef = { source, provider, id }` (:4260-4264). The gateway reads the same path itself
11
+ * (dist/auth-config-utils-G_ogHVLj.mjs:11, :43). Only a plain string is used here: a SecretRef is left to the
12
+ * host to resolve, and the plugin key is used instead. Neither value is ever logged; `tokenSource` is.
13
+ */
14
+ import { DEFAULT_GATEWAY_PORT, DEFAULT_RELAY_HOST } from "./constants.js";
15
+ const isRec = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+ export const CLOCK_OFFSET_ENV = "AXMBLY_CLOCK_OFFSET_MS";
17
+ /**
18
+ * Slice COHORT (HARNESS.md section 5): `AXMBLY_CLOCK_OFFSET_MS`, an optional integer number of milliseconds (may be
19
+ * negative) added to every clock read that decides behaviour. Unset or empty means 0. Anything else that is not a safe
20
+ * integer in plain decimal is refused.
21
+ */
22
+ export function readClockOffset(env) {
23
+ const raw = env[CLOCK_OFFSET_ENV];
24
+ if (raw === undefined || raw.trim() === "")
25
+ return { offsetMs: 0 };
26
+ const s = raw.trim();
27
+ const n = Number(s);
28
+ if (!/^[+-]?\d+$/.test(s) || !Number.isSafeInteger(n)) {
29
+ return { error: `${CLOCK_OFFSET_ENV} must be an integer number of milliseconds (got ${JSON.stringify(raw.slice(0, 40))}); refusing to start` };
30
+ }
31
+ return { offsetMs: n === 0 ? 0 : n }; // never -0
32
+ }
33
+ /** As a bad config would: one stderr line and exit. `exit` and `write` are injectable for the tests. */
34
+ export function clockOffsetOrExit(env, exit = (c) => process.exit(c), write = (l) => process.stderr.write(l)) {
35
+ const r = readClockOffset(env);
36
+ if ("error" in r) {
37
+ write(`[axmbly] ${r.error}\n`);
38
+ return exit(78);
39
+ }
40
+ return r.offsetMs;
41
+ }
42
+ export function readAdapterConfig(api) {
43
+ const cfg = isRec(api.config) ? api.config : {};
44
+ const plugin = isRec(api.pluginConfig) ? api.pluginConfig : {};
45
+ const gateway = isRec(cfg.gateway) ? cfg.gateway : {};
46
+ const auth = isRec(gateway.auth) ? gateway.auth : {};
47
+ const relayHost = typeof plugin.relayHost === "string" && plugin.relayHost.trim() ? plugin.relayHost.trim() : DEFAULT_RELAY_HOST;
48
+ const gatewayPort = typeof gateway.port === "number" ? gateway.port : DEFAULT_GATEWAY_PORT;
49
+ const own = auth.token;
50
+ const ownTokenShape = typeof own === "string" && own.length > 0 ? "string" : isRec(own) ? "ref" : "absent";
51
+ if (ownTokenShape === "string") {
52
+ return { relayHost, gatewayPort, gatewayToken: own, tokenSource: "gateway.auth.token", ownTokenShape };
53
+ }
54
+ const fallback = typeof plugin.gatewayToken === "string" && plugin.gatewayToken.length > 0 ? plugin.gatewayToken : undefined;
55
+ return {
56
+ relayHost,
57
+ gatewayPort,
58
+ gatewayToken: fallback,
59
+ tokenSource: fallback !== undefined ? "plugins.entries.axmbly.config.gatewayToken" : undefined,
60
+ ownTokenShape,
61
+ };
62
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Recipient quiet hours (PROTOCOL-AXMBLY.md section 9.4): `{timezone, window: {start, end}}`, `HH:MM` 24-hour, default
3
+ * 21:00 to 09:00. A nudge due inside the window is deferred to the window's end. Local time comes from the built-in
4
+ * `Intl` time zone database; no dependency. A window may wrap midnight (start > end) or not (start < end); start ==
5
+ * end is an empty window.
6
+ */
7
+ import { QUIET_HOURS_DEFAULT } from "../constants.js";
8
+ const HHMM = /^([01][0-9]|2[0-3]):([0-5][0-9])$/;
9
+ function minutesOf(hhmm) {
10
+ const m = HHMM.exec(hhmm);
11
+ return m ? Number(m[1]) * 60 + Number(m[2]) : undefined;
12
+ }
13
+ /** A well-formed value or undefined; the timezone must be one `Intl` knows. */
14
+ export function parseQuietHours(v) {
15
+ if (typeof v !== "object" || v === null)
16
+ return undefined;
17
+ const o = v;
18
+ const w = o.window;
19
+ if (typeof o.timezone !== "string" || typeof w !== "object" || w === null)
20
+ return undefined;
21
+ if (typeof w.start !== "string" || typeof w.end !== "string" || minutesOf(w.start) === undefined || minutesOf(w.end) === undefined)
22
+ return undefined;
23
+ try {
24
+ new Intl.DateTimeFormat("en-GB", { timeZone: o.timezone });
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ return { timezone: o.timezone, window: { start: w.start, end: w.end } };
30
+ }
31
+ /** Minutes past local midnight at `now` in `timezone`. */
32
+ export function localMinutes(now, timezone) {
33
+ const parts = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(now));
34
+ const h = Number(parts.find((p) => p.type === "hour")?.value ?? "0");
35
+ const m = Number(parts.find((p) => p.type === "minute")?.value ?? "0");
36
+ return (h % 24) * 60 + m;
37
+ }
38
+ export function inQuietHours(now, qh = QUIET_HOURS_DEFAULT) {
39
+ const start = minutesOf(qh.window.start);
40
+ const end = minutesOf(qh.window.end);
41
+ if (start === end)
42
+ return false;
43
+ const m = localMinutes(now, qh.timezone);
44
+ return start < end ? m >= start && m < end : m >= start || m < end;
45
+ }
46
+ /**
47
+ * The earliest time at or after `at` that is outside the quiet window: `at` itself when outside, else the window's
48
+ * end (to the minute).
49
+ */
50
+ export function deferPastQuiet(at, qh = QUIET_HOURS_DEFAULT) {
51
+ if (!inQuietHours(at, qh))
52
+ return at;
53
+ const end = minutesOf(qh.window.end);
54
+ const m = localMinutes(at, qh.timezone);
55
+ const delta = (end - m + 1440) % 1440 || 1440;
56
+ return Math.floor(at / 60_000) * 60_000 + delta * 60_000;
57
+ }
@@ -0,0 +1,127 @@
1
+ import { short } from "../log.js";
2
+ import { verifyStandingRow } from "./standings.js";
3
+ export class StandingBook {
4
+ state;
5
+ log;
6
+ cache = new Map();
7
+ loaded = false;
8
+ constructor(state, log) {
9
+ this.state = state;
10
+ this.log = log;
11
+ }
12
+ /** [r3] Forget the in-memory copy (start-over wiped the store); the next load reads the store again. */
13
+ forget() {
14
+ this.cache.clear();
15
+ this.loaded = false;
16
+ }
17
+ async load() {
18
+ if (this.loaded)
19
+ return;
20
+ for (const { key, value } of await this.state.standings.entries())
21
+ this.cache.set(key, value);
22
+ this.loaded = true;
23
+ }
24
+ effective(s) {
25
+ const v = s.verified;
26
+ if (!v)
27
+ return undefined;
28
+ const locallyRevoked = s.revokedAtVersion !== undefined && s.revokedAtVersion >= v.version;
29
+ return { ...v, effectiveGranted: v.granted && !locallyRevoked, effectiveRevoked: v.revoked || locallyRevoked };
30
+ }
31
+ all() {
32
+ return [...this.cache.values()].map((s) => this.effective(s)).filter((s) => s !== undefined);
33
+ }
34
+ get(standingId) {
35
+ const s = this.cache.get(standingId);
36
+ return s ? this.effective(s) : undefined;
37
+ }
38
+ /** True when the standing was revoked (by the relay row or a verified revoke envelope). */
39
+ isRevoked(standingId) {
40
+ const s = this.cache.get(standingId);
41
+ if (!s)
42
+ return false;
43
+ if (s.verified?.revoked)
44
+ return true;
45
+ return s.revokedAtVersion !== undefined && (s.verified === undefined || s.revokedAtVersion >= s.verified.version);
46
+ }
47
+ /** Our principal's agent `agentId` granted by `recipient` (initiator side). */
48
+ grantFor(principal, agentId, recipient) {
49
+ return this.all().find((s) => s.principal === principal && s.agentId === agentId && s.recipient === recipient && s.effectiveGranted);
50
+ }
51
+ /** Any standing (any status) for that triple, newest version first. */
52
+ latestFor(principal, agentId, recipient) {
53
+ return this.all()
54
+ .filter((s) => s.principal === principal && s.agentId === agentId && s.recipient === recipient)
55
+ .sort((a, b) => b.version - a.version)[0];
56
+ }
57
+ /** The friend's agent granted by our principal (the other half of a mutual standing). */
58
+ grantsFrom(friend, toRecipient) {
59
+ return this.all().filter((s) => s.principal === friend && s.recipient === toRecipient && s.effectiveGranted);
60
+ }
61
+ /** The handshake-family version held for a standing (section 9.7: a message not above it is ignored). */
62
+ heldVersion(standingId) {
63
+ const s = this.cache.get(standingId);
64
+ if (!s)
65
+ return undefined;
66
+ const vs = [s.verified?.version, s.heldVersion, s.revokedAtVersion].filter((x) => typeof x === "number");
67
+ return vs.length > 0 ? Math.max(...vs) : undefined;
68
+ }
69
+ async put(standingId, s) {
70
+ this.cache.set(standingId, s);
71
+ await this.state.standings.set(standingId, s);
72
+ }
73
+ /** True when `identity` is the principal or the recipient of the held, verified standing (F-B7). */
74
+ isParty(standingId, identity) {
75
+ const v = this.cache.get(standingId)?.verified;
76
+ return v !== undefined && (v.principal === identity || v.recipient === identity);
77
+ }
78
+ partyOnly(what, standingId, sender) {
79
+ if (this.isParty(standingId, sender))
80
+ return true;
81
+ // F-B11: a standing not held and verified yet has no known parties; say so instead of calling the sender a stranger.
82
+ const reason = this.cache.get(standingId)?.verified === undefined ? "not_held_yet" : "not_a_party";
83
+ this.log.warn(`${what} for standing ${short(standingId)} ignored reason=${reason} sender=${short(sender)}`);
84
+ return false;
85
+ }
86
+ /** Record the version of a handshake-family envelope that passed verification; only a party of the standing moves it. */
87
+ async noteVersion(standingId, version, senderIdentity) {
88
+ if (!this.partyOnly("version", standingId, senderIdentity))
89
+ return;
90
+ const s = this.cache.get(standingId) ?? {};
91
+ if ((s.heldVersion ?? 0) >= version)
92
+ return;
93
+ await this.put(standingId, { ...s, heldVersion: version });
94
+ }
95
+ /** A verified `revoke` envelope (signed by a party's phone): revoked from this version on. Returns whether it applied. */
96
+ async revokeFromEnvelope(standingId, version, senderIdentity) {
97
+ if (!this.partyOnly("revoke", standingId, senderIdentity))
98
+ return false;
99
+ const s = this.cache.get(standingId) ?? {};
100
+ await this.put(standingId, { ...s, revokedAtVersion: Math.max(version, s.revokedAtVersion ?? 0), heldVersion: Math.max(version, s.heldVersion ?? 0) });
101
+ return true;
102
+ }
103
+ /**
104
+ * Replace the held set from one `standing.get` answer. Rows that fail verification are logged and skipped (a
105
+ * standing the gateway cannot verify grants nothing). Returns the standingIds that are revoked now and were not.
106
+ */
107
+ async applyRows(rows, isPinned, now) {
108
+ const newlyRevoked = [];
109
+ for (const row of rows) {
110
+ const res = verifyStandingRow(row, isPinned);
111
+ const id = typeof row === "object" && row !== null ? row.record?.standingId : undefined;
112
+ if (!res.ok) {
113
+ this.log.warn(`standing ${short(typeof id === "string" ? id : undefined)} refused: ${res.reason}`);
114
+ continue;
115
+ }
116
+ const v = res.standing;
117
+ const before = this.cache.get(v.standingId);
118
+ const wasRevoked = this.isRevoked(v.standingId);
119
+ if (before?.verified && before.verified.version > v.version)
120
+ continue; // never step back to an older row
121
+ await this.put(v.standingId, { ...before, verified: v, fetchedAt: now });
122
+ if (!wasRevoked && this.isRevoked(v.standingId))
123
+ newlyRevoked.push(v.standingId);
124
+ }
125
+ return newlyRevoked;
126
+ }
127
+ }