@benjilabs/beaconfire-mcp 0.1.2 → 0.2.0

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.
package/dist/trust.js ADDED
@@ -0,0 +1,218 @@
1
+ import { verifyEvent } from "nostr-tools/pure";
2
+ import { pubkeyToHex } from "./config.js";
3
+ import { ToolError } from "./deps.js";
4
+ /** Most keys on the own list (invented, AB-48): 500 items fit strfry's 65536-byte event size (RUN); 800 do not. */
5
+ export const MAX_TRUST = 500;
6
+ const HEX64 = /^[0-9a-f]{64}$/;
7
+ const reason = (e) => (e instanceof Error ? e.message : String(e));
8
+ /**
9
+ * The agent's own trust list: a kind 30000 set, `d=trust`, signed by the agent, with the `p` items NIP-44
10
+ * encrypted to its own key in `content` (NIP-51, `51.md` line 11). Nothing of it is kept on disk; every
11
+ * consuming call refetches it. A failed read never falls back to the roster: a key the agent removed
12
+ * would be trusted again.
13
+ */
14
+ export class Trust {
15
+ source = "roster";
16
+ /** The own list; null unless `source` is `own`. */
17
+ own = null;
18
+ /** `created_at` of the event read; null when none. */
19
+ createdAt = null;
20
+ /** A state was read earlier in this process: a view may reuse it when a lenient read fails. */
21
+ loaded = false;
22
+ #pool;
23
+ #signer;
24
+ #roster;
25
+ constructor(pool, signer, roster) {
26
+ this.#pool = pool;
27
+ this.#signer = signer;
28
+ this.#roster = roster;
29
+ }
30
+ /**
31
+ * A copy of the state as it is now. A call judges against the copy taken right after its own read, so a
32
+ * lenient read by another call (a view, `beacon_trust list`) cannot swap the state under a strict call
33
+ * that is still judging, such as a `beacon_wait` of up to 1740 s.
34
+ */
35
+ snapshot() {
36
+ const t = new Trust(this.#pool, this.#signer, this.#roster);
37
+ t.source = this.source;
38
+ t.own = this.own === null ? null : new Set(this.own);
39
+ t.createdAt = this.createdAt;
40
+ t.loaded = this.loaded;
41
+ return t;
42
+ }
43
+ async #read(strict) {
44
+ const me = this.#signer.pubkey;
45
+ const evs = await this.#pool.fetch({ kinds: [30000], authors: [me], "#d": ["trust"] }, { strict });
46
+ let best = null;
47
+ for (const e of evs) {
48
+ if (e.pubkey !== me || !verifyEvent(e))
49
+ continue;
50
+ // NIP-01: greater created_at wins, lower id on a tie (as roster.ts).
51
+ if (!best ||
52
+ e.created_at > best.created_at ||
53
+ (e.created_at === best.created_at && e.id < best.id)) {
54
+ best = e;
55
+ }
56
+ }
57
+ return best;
58
+ }
59
+ /**
60
+ * Read the list. Throws `ToolError` ("trust list not read: ...") and leaves the state alone when a relay
61
+ * fails on a `strict` read. A lenient read that finds no event proves nothing (the silent relay may hold
62
+ * it), so it is repeated strict; only a complete read may say "no list".
63
+ */
64
+ async refresh(strict) {
65
+ if (this.#roster.orchestrator === null)
66
+ return;
67
+ let ev;
68
+ try {
69
+ ev = await this.#read(strict);
70
+ if (ev === null && !strict)
71
+ ev = await this.#read(true);
72
+ }
73
+ catch (e) {
74
+ throw new ToolError(`trust list not read: ${reason(e)}`);
75
+ }
76
+ this.loaded = true;
77
+ if (ev === null) {
78
+ this.source = "roster";
79
+ this.own = null;
80
+ this.createdAt = null;
81
+ return;
82
+ }
83
+ this.createdAt = ev.created_at;
84
+ try {
85
+ const items = JSON.parse(this.#signer.decryptFromSelf(ev.content));
86
+ if (!Array.isArray(items))
87
+ throw new Error("not an array");
88
+ this.own = new Set(items.flatMap((it) => Array.isArray(it) && it[0] === "p" && typeof it[1] === "string" && HEX64.test(it[1])
89
+ ? [it[1]]
90
+ : []));
91
+ this.source = "own";
92
+ }
93
+ catch {
94
+ this.own = null;
95
+ this.source = "unreadable";
96
+ }
97
+ }
98
+ isTrusted(pubkey) {
99
+ if (this.source === "own")
100
+ return this.own?.has(pubkey) ?? false;
101
+ if (this.source === "unreadable")
102
+ return false;
103
+ return this.#roster.has(pubkey);
104
+ }
105
+ /** The authors of the plain all-hands filter: the own list and the roster, or the roster alone; never me. */
106
+ authors(me) {
107
+ const set = new Set(this.#roster.entries.map((e) => e.pubkey));
108
+ if (this.source === "own")
109
+ for (const p of this.own ?? [])
110
+ set.add(p);
111
+ set.delete(me);
112
+ return [...set];
113
+ }
114
+ }
115
+ function listResult(deps) {
116
+ const { trust, roster, signer } = deps;
117
+ const keys = trust.source === "own"
118
+ ? [...(trust.own ?? [])]
119
+ : trust.source === "roster"
120
+ ? roster.entries.map((e) => e.pubkey).filter((p) => p !== signer.pubkey)
121
+ : [];
122
+ return {
123
+ source: trust.source,
124
+ published: trust.source !== "roster",
125
+ trusted: keys.map((pubkey) => ({ pubkey, name: roster.nameOf(pubkey) })),
126
+ updatedAt: trust.createdAt,
127
+ };
128
+ }
129
+ /** `beacon_trust`: list, add or remove a key on the agent's own trust list. */
130
+ export async function trustTool(deps, args) {
131
+ const { trust, roster, signer, pool } = deps;
132
+ if (roster.orchestrator === null) {
133
+ throw new ToolError("this server has no orchestrator configured; beacon_trust needs a roster");
134
+ }
135
+ if (args.action === "list") {
136
+ try {
137
+ await roster.refresh(deps.now() * 1000, false);
138
+ }
139
+ catch (e) {
140
+ if (roster.fetchedAt === null)
141
+ throw e;
142
+ }
143
+ try {
144
+ await trust.refresh(false);
145
+ }
146
+ catch (e) {
147
+ if (!trust.loaded)
148
+ throw e;
149
+ }
150
+ return listResult(deps);
151
+ }
152
+ if (args.pubkey === undefined)
153
+ throw new ToolError(`\`pubkey\` is needed to ${args.action}`);
154
+ let pk;
155
+ try {
156
+ pk = pubkeyToHex(args.pubkey);
157
+ }
158
+ catch (e) {
159
+ throw new ToolError(reason(e));
160
+ }
161
+ const add = args.action === "add";
162
+ // The write is a read-modify-write: every relay must answer, or an `add` over a failed read
163
+ // would publish a list of one and wipe the rest.
164
+ try {
165
+ await roster.refresh(deps.now() * 1000, true);
166
+ }
167
+ catch (e) {
168
+ throw new ToolError(`trust list not read: ${reason(e)}`);
169
+ }
170
+ await trust.refresh(true);
171
+ if (trust.source === "unreadable") {
172
+ throw new ToolError("trust list unreadable: publish a fresh set by hand (kind 30000, d=trust); nothing was changed");
173
+ }
174
+ const seeding = trust.own === null;
175
+ const effective = trust.own ?? new Set(roster.entries.map((e) => e.pubkey).filter((p) => p !== signer.pubkey));
176
+ if (add ? effective.has(pk) : !effective.has(pk))
177
+ return { ...listResult(deps), changed: false };
178
+ const next = new Set(effective);
179
+ if (add)
180
+ next.add(pk);
181
+ else
182
+ next.delete(pk);
183
+ if (next.size > MAX_TRUST) {
184
+ throw new ToolError(`trust list is over ${MAX_TRUST} keys (this change makes ${next.size})`);
185
+ }
186
+ const event = signer.sign({
187
+ kind: 30000,
188
+ // Beats the previous event under NIP-01 even inside one second.
189
+ created_at: Math.max(deps.now(), (trust.createdAt ?? 0) + 1),
190
+ tags: [["d", "trust"]],
191
+ content: signer.encryptToSelf(JSON.stringify([...next].map((p) => ["p", p]))),
192
+ });
193
+ const { maxBytes } = await pool.limits();
194
+ if (maxBytes !== undefined && JSON.stringify(event).length > maxBytes) {
195
+ throw new ToolError(`trust list of ${next.size} keys is over this relay's ${maxBytes}-byte event limit`);
196
+ }
197
+ const results = await pool.publish(event);
198
+ if (!results.some((r) => r.ok)) {
199
+ throw new ToolError(`trust list not published: ${results.map((r) => `${r.relay}: ${r.error ?? "rejected"}`).join("; ")}`);
200
+ }
201
+ const refused = results.filter((r) => !r.ok).map((r) => r.relay);
202
+ // Two sessions writing in one second: the lower id wins and the other's key is gone. Read back.
203
+ try {
204
+ await trust.refresh(true);
205
+ }
206
+ catch (e) {
207
+ throw new ToolError(`${reason(e)}; the new list was published and may be in force: call list to see it`);
208
+ }
209
+ if (trust.source !== "own" || trust.own?.has(pk) !== add) {
210
+ throw new ToolError("another session changed the list at the same moment; call again");
211
+ }
212
+ return {
213
+ ...listResult(deps),
214
+ changed: true,
215
+ ...(seeding ? { seeded: effective.size } : {}),
216
+ ...(refused.length > 0 ? { refused } : {}),
217
+ };
218
+ }
package/dist/wait.js ADDED
@@ -0,0 +1,260 @@
1
+ import { DEFAULT_WAIT_S } from "./config.js";
2
+ import { ToolError } from "./deps.js";
3
+ import { judgePlain, judgeWrap, renderMessage, } from "./inbox.js";
4
+ import { log } from "./redact.js";
5
+ import { PUBLIC_ROOM } from "./send.js";
6
+ const TWO_DAYS = 2 * 24 * 60 * 60;
7
+ const SEVEN_DAYS = 7 * 24 * 60 * 60;
8
+ /** Allowance on the sealed `since` for a replier whose clock runs behind (the relay accepts 900 s ahead). */
9
+ const SKEW = 900;
10
+ /**
11
+ * Hold one call open until a `response` whose envelope `re` is `args.re` reaches this session, or `timeout_s`
12
+ * ends (AB-47). It returns only what `beacon_inbox` would return: `judgeWrap` and `judgePlain` are the inbox's own
13
+ * rules (unwrap with seal pubkey = rumor pubkey, session filter, group membership, expiry). On top: the author is
14
+ * on the trust list (`Candidate.trusted`, read strict at the start, AB-48), so a wrap from a key off it never
15
+ * matches, on or off the roster (AB-54); type `response`, and when the ask went to known
16
+ * recipients the author is one of them. Public-room events never match.
17
+ *
18
+ * Help asks (AB-56, kind 5050): a 6050 result is a `response` for `re`. A trusted 7000 for `re` is collected as
19
+ * `feedback`; an `error` ends the wait only when every helper in `ask.to` has sent one (never for a room ask).
20
+ * A plain kind 7400 answer never satisfies a wait for a help ask (decision 0064 item 1). The ask is known to be one
21
+ * from `deps.sent`, or, with no entry (a restart, another process), from the asker's own copy on the relay: the
22
+ * self copy in the sealed fetch, or the signed room ask fetched by id (decision 0065). Without an entry a plain
23
+ * candidate is held until the stored part is read, and the stored fetches are strict.
24
+ *
25
+ * Non-consuming: no `ret`, no cursor, no `save`, no `pending`. The one write is in memory: the returned message
26
+ * is registered in `state.known` (as a view does) so `beacon_mark_seen` and `beacon_ack` accept its id.
27
+ *
28
+ * The stored part is read with the paged `fetch` from the ask's send time minus two days (a wrap's `created_at`
29
+ * is back-dated up to two days, NIP-17 line 59), never from the wait's start; the live part is a held-open
30
+ * follow opened first so nothing falls between the two.
31
+ */
32
+ export async function wait(deps, args, signal) {
33
+ if (deps.orchestrator === null) {
34
+ throw new ToolError("this server has no orchestrator configured; beacon_wait needs a roster");
35
+ }
36
+ const timeoutS = args.timeout_s ?? DEFAULT_WAIT_S;
37
+ if (timeoutS > deps.waitCeilingS) {
38
+ throw new ToolError(`timeout_s ${timeoutS} is over this server's ceiling of ${deps.waitCeilingS} seconds (config key waitCeilingSeconds); wait again instead`);
39
+ }
40
+ const { signer, pool, roster, state } = deps;
41
+ const me = signer.pubkey;
42
+ const re = args.re;
43
+ const startedMs = Date.now();
44
+ return new Promise((resolve, reject) => {
45
+ let done = false;
46
+ let follow = null;
47
+ const myAcks = new Set();
48
+ /** Trusted 7000 feedback for `re`, by id. */
49
+ const feedback = new Map();
50
+ const feedbackOut = (except) => {
51
+ const rest = [...feedback.values()]
52
+ .filter((c) => c.id !== except)
53
+ .sort((a, b) => a.createdAt - b.createdAt)
54
+ .map((c) => {
55
+ register(c);
56
+ return renderMessage(deps, c, myAcks.has(c.id));
57
+ });
58
+ return rest.length > 0 ? { feedback: rest } : {};
59
+ };
60
+ const end = (how, fn) => {
61
+ if (done)
62
+ return;
63
+ done = true;
64
+ clearTimeout(timer);
65
+ signal?.removeEventListener("abort", onAbort);
66
+ follow?.close();
67
+ log(`wait done: ${how} in ${Date.now() - startedMs} ms`);
68
+ fn();
69
+ };
70
+ const timer = setTimeout(() => end("timeout", () => resolve({ status: "timeout", ...feedbackOut() })), timeoutS * 1000);
71
+ const onAbort = () => end("aborted", () => resolve({ status: "timeout", ...feedbackOut() }));
72
+ signal?.addEventListener("abort", onAbort);
73
+ if (signal?.aborted)
74
+ onAbort();
75
+ let ctx = { myGroups: [] };
76
+ let ask = { at: null, to: null };
77
+ let trustView = deps.trust;
78
+ /** `re` is known to be a help ask: from `deps.sent`, or found as my own 5050 (decision 0065). */
79
+ let marked = false;
80
+ /** No `deps.sent` entry: plain candidates are held until the stored part is read. */
81
+ let noEntry = false;
82
+ let storedDone = false;
83
+ /** Plain candidates that arrived live while the stored part was being read. */
84
+ const held = [];
85
+ /** Distinct helpers whose 7000 `error` was seen, and the latest of them. */
86
+ const errored = new Map();
87
+ const permitted = (c) => c.trusted && (ask.to === null || ask.to.includes(c.from));
88
+ /** The candidate if it is the reply this wait is for. */
89
+ const wanted = (c) => {
90
+ if (c.env.type !== "response" || c.env.re !== re)
91
+ return null;
92
+ // On my trust list (a key I removed is not heard); a trusted key off the roster counts (AB-54, decision 0062 item 4).
93
+ if (!c.trusted)
94
+ return null;
95
+ if (ask.to !== null && !ask.to.includes(c.from))
96
+ return null;
97
+ return c;
98
+ };
99
+ /** A trusted 7000 for `re` from a permitted author. */
100
+ const isFeedback = (c) => c.env.type === "event" && c.help?.kind === 7000 && c.env.re === re && permitted(c);
101
+ /** Judge one event; acks are collected, a candidate for this wait (reply or feedback) is returned. */
102
+ const judge = (e) => {
103
+ const now = deps.now();
104
+ const j = e.kind === 1059
105
+ ? judgeWrap(deps, e, {
106
+ now,
107
+ trust: trustView,
108
+ onOwnAsk: (id) => {
109
+ if (id === re)
110
+ marked = true;
111
+ },
112
+ })
113
+ : judgePlain(deps, e, {
114
+ myGroups: ctx.myGroups,
115
+ now,
116
+ trust: trustView,
117
+ mode: e.tags.some((t) => t[0] === "h") ? "group" : "direct",
118
+ });
119
+ if (j.kind === "ack")
120
+ myAcks.add(j.re);
121
+ if (j.kind !== "candidate")
122
+ return null;
123
+ return wanted(j.c) ?? (isFeedback(j.c) ? j.c : null);
124
+ };
125
+ const register = (c) => {
126
+ const prior = state.known.get(c.id);
127
+ state.known.set(c.id, {
128
+ from: c.from,
129
+ t: deps.now(),
130
+ type: c.env.type,
131
+ ret: prior?.ret ?? false,
132
+ ...(c.fromSession ? { fromSession: c.fromSession } : {}),
133
+ });
134
+ };
135
+ const finish = (c) => {
136
+ register(c);
137
+ const message = renderMessage(deps, c, myAcks.has(c.id));
138
+ end("matched", () => resolve({ status: "response", message, ...feedbackOut(c.id) }));
139
+ };
140
+ /** Every helper addressed has sent an `error`: nobody is left to answer. Never for a room ask or no helper. */
141
+ const allErrored = () => {
142
+ if (ask.to === null || ask.to.length === 0)
143
+ return null;
144
+ if (!ask.to.every((h) => errored.has(h)))
145
+ return null;
146
+ return [...errored.values()].sort((a, b) => b.createdAt - a.createdAt)[0] ?? null;
147
+ };
148
+ const finishError = (c) => {
149
+ register(c);
150
+ const message = renderMessage(deps, c, myAcks.has(c.id));
151
+ end("error", () => resolve({ status: "error", message, ...feedbackOut(c.id) }));
152
+ };
153
+ /** Take a feedback candidate in; true when it was one. */
154
+ const collect = (c) => {
155
+ if (!isFeedback(c))
156
+ return false;
157
+ feedback.set(c.id, c);
158
+ const status = c.env.body.status;
159
+ if (status === "error")
160
+ errored.set(c.from, c);
161
+ return true;
162
+ };
163
+ /** A plain 7400 answer to a help ask is dropped; without an entry it waits for the stored part. */
164
+ const isPlain = (c) => !c.sealed;
165
+ const run = async () => {
166
+ const nowS = deps.now();
167
+ try {
168
+ await roster.refresh(nowS * 1000, false);
169
+ }
170
+ catch (e) {
171
+ if (roster.fetchedAt === null)
172
+ throw e;
173
+ }
174
+ // Strict, and no fallback: a wait that cannot read the trust list must not hear a key the agent removed.
175
+ await deps.trust.refresh(true);
176
+ // Judged against this strict read for the whole wait, whatever a view reads meanwhile.
177
+ trustView = deps.trust.snapshot();
178
+ if (done)
179
+ return;
180
+ ctx = { myGroups: roster.groupsOf(me).filter((g) => g !== PUBLIC_ROOM) };
181
+ const sent = deps.sent.get(re);
182
+ ask = { at: sent?.at ?? null, to: sent?.to ?? null };
183
+ marked = sent?.help === true;
184
+ noEntry = sent === undefined;
185
+ const since = Math.max(0, (sent?.at ?? nowS - SEVEN_DAYS) - TWO_DAYS - SKEW);
186
+ const sealed = { kinds: [1059], "#p": [me], since };
187
+ const plain = { kinds: [7400], "#e": [re] };
188
+ // Live first, so nothing published while the stored part is read is missed.
189
+ const f = await pool.follow([sealed, plain], (e) => {
190
+ if (done)
191
+ return;
192
+ const c = judge(e);
193
+ if (!c)
194
+ return;
195
+ if (collect(c)) {
196
+ // Judged after the stored part: until then the pass below decides.
197
+ if (storedDone) {
198
+ const all = allErrored();
199
+ if (all)
200
+ finishError(all);
201
+ }
202
+ return;
203
+ }
204
+ if (isPlain(c)) {
205
+ if (marked)
206
+ return;
207
+ if (noEntry && !storedDone) {
208
+ held.push(c);
209
+ return;
210
+ }
211
+ }
212
+ finish(c);
213
+ });
214
+ if (done) {
215
+ f.close();
216
+ return;
217
+ }
218
+ follow = f;
219
+ void f.closed.then(() => end("connection lost", () => reject(new ToolError("relay connection lost; call beacon_wait again"))));
220
+ // With no entry the ask is looked up on the relay, and a relay that fails stops the wait: a self copy held
221
+ // only by the silent relay must not release a plain answer (decision 0065).
222
+ const opts = noEntry ? { strict: true } : {};
223
+ const [wraps, plains, own] = await Promise.all([
224
+ pool.fetch(sealed, opts),
225
+ pool.fetch(plain, opts),
226
+ noEntry ? pool.fetch({ kinds: [5050], ids: [re] }, opts) : Promise.resolve([]),
227
+ ]);
228
+ if (done)
229
+ return;
230
+ // Pass 1: judge everything stored, so every mark is known before any candidate is chosen.
231
+ for (const e of own)
232
+ if (e.kind === 5050 && e.pubkey === me && e.id === re)
233
+ marked = true;
234
+ const stored = [];
235
+ for (const e of [...wraps, ...plains]) {
236
+ const c = judge(e);
237
+ if (c && !collect(c))
238
+ stored.push(c);
239
+ }
240
+ storedDone = true;
241
+ // Pass 2: a plain answer to a help ask is dropped, whatever order it was found in.
242
+ let first = null;
243
+ for (const c of [...stored, ...held]) {
244
+ if (isPlain(c) && marked)
245
+ continue;
246
+ if (first === null || c.createdAt < first.createdAt)
247
+ first = c;
248
+ }
249
+ held.length = 0;
250
+ if (first) {
251
+ finish(first);
252
+ return;
253
+ }
254
+ const all = allErrored();
255
+ if (all)
256
+ finishError(all);
257
+ };
258
+ run().catch((e) => end("error", () => reject(e)));
259
+ });
260
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@benjilabs/beaconfire-mcp",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "engines": { "node": ">=22.18" },
6
6
  "main": "dist/index.js",