@benjilabs/beaconfire-mcp 0.1.2 → 0.3.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/index.js CHANGED
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { loadBuild } from "./build.js";
5
+ import { Cards } from "./cards.js";
4
6
  import { loadConfig, parseSessionName, readSecretKey } from "./config.js";
5
7
  import { log, makeRedactor } from "./redact.js";
6
8
  import { RealRelayPool } from "./relay.js";
7
9
  import { Roster } from "./roster.js";
10
+ import { REPUBLISH_MS, republish } from "./serve.js";
8
11
  import { runSetup, SetupError } from "./setup.js";
9
12
  import { Signer } from "./signer.js";
10
13
  import { State, stateDirFor } from "./state.js";
11
14
  import { makeTools, registerTools } from "./tools.js";
15
+ import { Trust } from "./trust.js";
12
16
  if (process.argv[2] === "setup") {
13
17
  runSetup(process.argv.slice(3)).catch((e) => {
14
18
  const msg = e instanceof SetupError
@@ -36,19 +40,28 @@ async function main() {
36
40
  const signer = new Signer(readSecretKey(config.keyFile));
37
41
  const redact = makeRedactor(signer.secretForms());
38
42
  const pool = new RealRelayPool(config.relays, signer);
43
+ const roster = new Roster(pool, config.orchestrator);
39
44
  const deps = {
40
45
  signer,
41
46
  pool,
42
- roster: new Roster(pool, config.orchestrator),
47
+ roster,
48
+ trust: new Trust(pool, signer, roster),
43
49
  state: new State(stateDirFor(config.stateDir, session)),
50
+ cards: new Cards(stateDirFor(config.stateDir, session), config.stateDir, signer.pubkey),
44
51
  session,
45
52
  orchestrator: config.orchestrator,
46
53
  enroll: config.siteUrl === null ? undefined : { siteUrl: config.siteUrl, config },
47
54
  publicRoom: config.publicRoom,
55
+ sent: new Map(),
56
+ waitCeilingS: config.waitCeilingS,
48
57
  now: () => Math.floor(Date.now() / 1000),
49
58
  };
50
- const server = new McpServer({ name: "beaconfire", version: "0.1.0" });
51
- registerTools(server, makeTools(deps), redact, config.orchestrator !== null);
59
+ const build = loadBuild();
60
+ const server = new McpServer({ name: "beaconfire", version: build.version });
61
+ registerTools(server, makeTools(deps, build), redact, config.orchestrator !== null);
52
62
  await server.connect(new StdioServerTransport());
53
63
  log(`ready as ${signer.pubkey}`);
64
+ // Sealed cards this agent serves are wrapped again at start and daily (AB-55); a failure is logged only.
65
+ void republish(deps);
66
+ setInterval(() => void republish(deps), REPUBLISH_MS).unref();
54
67
  }
package/dist/relay.js CHANGED
@@ -160,6 +160,69 @@ class Conn {
160
160
  });
161
161
  });
162
162
  }
163
+ /**
164
+ * One live subscription per filter. A CLOSED with auth-required runs AUTH and re-sends once. Resolves
165
+ * when every subscription has answered EOSE; `onend` runs once if any of them is closed afterwards.
166
+ */
167
+ async follow(filters, onevent, onend) {
168
+ const relay = await this.relay();
169
+ const subs = [];
170
+ let closing = false;
171
+ const close = () => {
172
+ closing = true;
173
+ for (const s of subs)
174
+ s.close();
175
+ };
176
+ const ended = (_reason) => {
177
+ if (closing)
178
+ return;
179
+ close();
180
+ onend();
181
+ };
182
+ try {
183
+ for (const filter of filters) {
184
+ let r = await this.#open(relay, filter, onevent, ended);
185
+ if (r.closed !== undefined && r.closed.includes("auth-required")) {
186
+ await this.#authenticate(relay);
187
+ r = await this.#open(relay, filter, onevent, ended);
188
+ }
189
+ if (r.sub === undefined) {
190
+ throw new Error(`relay ${this.cfg.url}: ${r.closed?.includes("auth-required") ? "auth failed" : `REQ closed: ${r.closed}`}`);
191
+ }
192
+ subs.push(r.sub);
193
+ }
194
+ }
195
+ catch (e) {
196
+ close();
197
+ throw e;
198
+ }
199
+ return { close };
200
+ }
201
+ /** Send a live-only REQ; resolves at its EOSE, or with the CLOSED reason if it was closed first. */
202
+ #open(relay, filter, onevent, onend) {
203
+ return new Promise((resolve, reject) => {
204
+ let ready = false;
205
+ const timer = setTimeout(() => {
206
+ sub.close();
207
+ reject(new Error(`relay ${this.cfg.url}: EOSE timed out`));
208
+ }, TIMEOUT.eose);
209
+ const sub = relay.subscribe([{ ...filter, limit: 0 }], {
210
+ onevent,
211
+ oneose: () => {
212
+ ready = true;
213
+ clearTimeout(timer);
214
+ resolve({ sub });
215
+ },
216
+ onclose: (reason) => {
217
+ clearTimeout(timer);
218
+ if (ready)
219
+ onend(reason);
220
+ else
221
+ resolve({ closed: reason });
222
+ },
223
+ });
224
+ });
225
+ }
163
226
  close() {
164
227
  this.#relay?.close();
165
228
  }
@@ -197,6 +260,39 @@ export class RealRelayPool {
197
260
  const settled = await Promise.allSettled(this.#conns.map((c) => pagedFetch((f) => c.page(f), filter, maxLimit)));
198
261
  return mergeSettled(settled, opts.strict === true);
199
262
  }
263
+ async follow(filters, onevent) {
264
+ let started = -1;
265
+ let ended = 0;
266
+ let done;
267
+ const closed = new Promise((res) => {
268
+ done = res;
269
+ });
270
+ const check = () => {
271
+ if (started >= 0 && ended >= started)
272
+ done();
273
+ };
274
+ const settled = await Promise.allSettled(this.#conns.map((c) => c.follow(filters, onevent, () => {
275
+ ended++;
276
+ check();
277
+ })));
278
+ const ok = settled.filter((s) => s.status === "fulfilled");
279
+ const failed = settled.filter((s) => s.status === "rejected");
280
+ for (const f of failed)
281
+ log(String(f.reason.message));
282
+ if (ok[0] === undefined)
283
+ throw failed[0].reason;
284
+ started = ok.length;
285
+ check();
286
+ return {
287
+ closed,
288
+ close: () => {
289
+ for (const s of ok)
290
+ s.value.close();
291
+ ended = started;
292
+ check();
293
+ },
294
+ };
295
+ }
200
296
  publish(event) {
201
297
  return Promise.all(this.#conns.map((c) => c.publish(event)));
202
298
  }
package/dist/roster.js CHANGED
@@ -1,15 +1,12 @@
1
1
  import { verifyEvent } from "nostr-tools/pure";
2
2
  import { pubkeyToHex } from "./config.js";
3
3
  const FRESH_MS = 5 * 60 * 1000;
4
- const HEX64 = /^[0-9a-f]{64}$/;
5
4
  /**
6
5
  * The orchestrator's kind 30000 `d=agents` event: `["p", <hex>, "", <name>]` per agent
7
6
  * (NIP-02 petname position, element 3). Only an event signed by the orchestrator counts.
8
7
  */
9
8
  export class Roster {
10
9
  entries = [];
11
- /** Group name to member pubkeys, from the orchestrator's `d=group:<name>` sets (NIP-51 follow sets). */
12
- groups = new Map();
13
10
  fetchedAt = null;
14
11
  #lastOk = false;
15
12
  pool;
@@ -25,9 +22,8 @@ export class Roster {
25
22
  return this.#lastOk && nowMs - this.fetchedAt < FRESH_MS ? "fresh" : "stale";
26
23
  }
27
24
  /**
28
- * Refetch the orchestrator's kind 30000 sets: `d=agents` (the roster) and every `d=group:<name>`.
29
- * On failure the previous entries and groups stay and status becomes stale/missing. A fetch that
30
- * succeeds is the whole truth about groups: a set that is absent or empty removes the group.
25
+ * Refetch the orchestrator's kind 30000 sets and read `d=agents` (the roster); its `d=group:*` sets are
26
+ * not read (AB-60). On failure the previous entries stay and status becomes stale/missing.
31
27
  */
32
28
  async refresh(nowMs = Date.now(), strict = false) {
33
29
  if (this.orchestrator === null)
@@ -49,12 +45,6 @@ export class Roster {
49
45
  sets.set(d, e);
50
46
  }
51
47
  }
52
- this.groups = new Map();
53
- for (const [d, e] of sets) {
54
- if (!d.startsWith("group:"))
55
- continue;
56
- this.groups.set(d.slice("group:".length), new Set(e.tags.filter((t) => t[0] === "p" && HEX64.test(t[1] ?? "")).map((t) => t[1])));
57
- }
58
48
  const newest = sets.get("agents");
59
49
  if (newest) {
60
50
  this.entries = newest.tags
@@ -87,13 +77,6 @@ export class Roster {
87
77
  has(pubkey) {
88
78
  return this.entries.some((e) => e.pubkey === pubkey);
89
79
  }
90
- /** The groups whose set lists `pubkey`. */
91
- groupsOf(pubkey) {
92
- return [...this.groups].filter(([, m]) => m.has(pubkey)).map(([g]) => g);
93
- }
94
- inGroup(group, pubkey) {
95
- return this.groups.get(group)?.has(pubkey) ?? false;
96
- }
97
80
  nameOf(pubkey) {
98
81
  return this.entries.find((e) => e.pubkey === pubkey)?.name ?? null;
99
82
  }
package/dist/send.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SESSION_PATTERN } from "./config.js";
2
2
  import { ToolError } from "./deps.js";
3
3
  import { buildEnvelope } from "./envelope.js";
4
+ import { plainGroupRefusal, readOwnGroups } from "./groups.js";
4
5
  import { makeWrap } from "./signer.js";
5
6
  /** NIP-17 line 106: "more than 10 participants" need another scheme. Participants include the sender. */
6
7
  const MAX_SEALED_PARTICIPANTS = 10;
@@ -9,40 +10,41 @@ function overCap(participants) {
9
10
  }
10
11
  /**
11
12
  * Largest body, as UTF-8 bytes of its JSON, that `send` accepts. Set by the reader, not the relay:
12
- * the Hermes adapter peeks ten messages and Hermes truncates an MCP result over about 64 KB, and ten
13
- * messages at this size come to about 48 KB. The relay limit (`maxEventSize` 65536) never binds here:
13
+ * one message at this size must fit a `beacon_inbox` result (`RESULT_BUDGET` in `inbox.ts`, which cuts
14
+ * a result by size, AB-64). The relay limit (`maxEventSize` 65536) never binds here:
14
15
  * the worst-case sealed wrap of a body this size is about 19.3 KB.
15
16
  */
16
17
  export const MAX_BODY_BYTES = 4096;
17
- function unknownRecipient(deps, input) {
18
+ function unknownRecipient(deps, input, hint = "") {
18
19
  const names = deps.roster.names();
19
- return new ToolError(`unknown recipient "${input}"; roster names: ${names.length ? names.join(", ") : "(none)"}`);
20
+ return new ToolError(`unknown recipient "${input}"; roster names: ${names.length ? names.join(", ") : "(none)"}${hint}`);
20
21
  }
21
22
  /**
22
- * The members other than me of group `name`, for a sealed send. Every refusal is before any wrap is made:
23
- * the reader drops an author who is not in the group, and the relay refuses a wrap to an unrostered key.
23
+ * The members other than me of group `name`, for a sealed send, from the agent's own set read strictly
24
+ * from the relay now (AB-57): a removed member must not receive. Every refusal is before any wrap is made.
24
25
  */
25
- function sealedGroupMembers(deps, name) {
26
+ async function sealedGroupMembers(deps, name) {
26
27
  const me = deps.signer.pubkey;
27
- const set = deps.roster.groups.get(name);
28
- if (!set || set.size === 0) {
29
- const names = [...deps.roster.groups.keys()];
30
- throw new ToolError(`unknown group "${name}"; groups: ${names.length ? names.join(", ") : "(none)"}`);
28
+ const own = await readOwnGroups(deps, true);
29
+ const set = own.get(name);
30
+ if (set?.members === null) {
31
+ throw new ToolError(`group "${name}" is unreadable (a set exists that this key cannot decrypt); nothing was sent`);
31
32
  }
32
- if (!set.has(me))
33
- throw new ToolError(`you are not a member of group "${name}"`);
34
- const offRoster = [...set].filter((p) => !deps.roster.has(p));
35
- if (offRoster.length > 0) {
36
- throw new ToolError(`group "${name}" has members who are not on the roster: ${offRoster.join(", ")}`);
33
+ const others = (set?.members ?? []).filter((p) => p !== me);
34
+ if (others.length === 0) {
35
+ const names = [...own].filter(([, g]) => (g.members ?? []).length > 0).map(([n]) => n);
36
+ throw new ToolError(`group "${name}" is unknown or has no members, so nothing was sent. Create it with beacon_group {action: "create", name: "${name}", members: [...]}; your groups: ${names.length ? names.join(", ") : "(none)"}`);
37
+ }
38
+ if (others.length + 1 > MAX_SEALED_PARTICIPANTS)
39
+ throw overCap(others.length + 1);
40
+ // A set written by another client may hold a key NIP-44 cannot use; refuse before the first wrap.
41
+ const bad = others.filter((p) => !deps.signer.canSealTo(p));
42
+ if (bad.length > 0) {
43
+ throw new ToolError(`group "${name}" holds keys that cannot be sealed to: ${bad.join(", ")}; nothing was sent`);
37
44
  }
38
- const others = [...set].filter((p) => p !== me);
39
- if (others.length === 0)
40
- throw new ToolError(`group "${name}" has no other members`);
41
- if (set.size > MAX_SEALED_PARTICIPANTS)
42
- throw overCap(set.size);
43
45
  return others;
44
46
  }
45
- export function resolveTarget(deps, to, sealed) {
47
+ export async function resolveTarget(deps, to, sealed) {
46
48
  if (deps.roster.status() === "missing") {
47
49
  throw new ToolError("roster not available: no roster event from the orchestrator was found");
48
50
  }
@@ -60,15 +62,24 @@ export function resolveTarget(deps, to, sealed) {
60
62
  const name = to.slice("group:".length);
61
63
  if (!name)
62
64
  throw new ToolError("group name is empty");
63
- return { kind: "group", name, pubkeys: sealed ? sealedGroupMembers(deps, name) : [] };
65
+ if (!sealed)
66
+ throw new ToolError(plainGroupRefusal(name));
67
+ return { kind: "group", name, pubkeys: await sealedGroupMembers(deps, name) };
64
68
  }
65
69
  const pk = deps.roster.resolve(to);
66
70
  if (pk === null)
67
- throw unknownRecipient(deps, to);
71
+ throw unknownRecipient(deps, to, "; or a 64-hex pubkey");
68
72
  if (pk === me)
69
73
  throw new ToolError("cannot send to yourself");
70
- if (!deps.roster.has(pk))
71
- throw unknownRecipient(deps, to);
74
+ if (!deps.roster.has(pk)) {
75
+ // Off the account roster (AB-54). The relay checks the recipient of a kind 1059 only (allowlist.mjs rules 4
76
+ // and 6); it admits any plain kind 7400 from a roster author, so the client is the only gate on a plain send.
77
+ if (!sealed) {
78
+ throw new ToolError("a plain send cannot leave your account: the relay does not check the recipient; send sealed");
79
+ }
80
+ if (!deps.signer.canSealTo(pk))
81
+ throw new ToolError("to is not a valid public key");
82
+ }
72
83
  return { kind: "direct", pubkeys: [pk] };
73
84
  }
74
85
  function recipientsOf(deps, pubkeys) {
@@ -104,7 +115,7 @@ function byRelay(perEvent) {
104
115
  return [...rows.values()];
105
116
  }
106
117
  /** Publish `events`; throws if one reached no relay. */
107
- async function publishAll(deps, events) {
118
+ export async function publishAll(deps, events) {
108
119
  const perEvent = await publishEach(deps, events);
109
120
  const unreached = perEvent.filter((results) => !results.some((r) => r.ok)).length;
110
121
  const published = byRelay(perEvent);
@@ -115,7 +126,7 @@ async function publishAll(deps, events) {
115
126
  return published;
116
127
  }
117
128
  /** `session` names the addressee's session; `from_session` is this server's own, on every send. */
118
- function sessionTags(deps, session) {
129
+ export function sessionTags(deps, session) {
119
130
  const tags = [];
120
131
  if (session !== null)
121
132
  tags.push(["session", session]);
@@ -142,12 +153,41 @@ function addresseeSession(deps, a, target) {
142
153
  return known.fromSession;
143
154
  return null;
144
155
  }
156
+ /** A sealed send that did not reach every wrap's relay. `delivered` holds the recipients (not me) whose wrap a relay took. */
157
+ export class PartialDelivery extends ToolError {
158
+ delivered;
159
+ constructor(message, delivered) {
160
+ super(message);
161
+ this.delivered = delivered;
162
+ }
163
+ }
164
+ /**
165
+ * Seal `rumor` and wrap it to each of `recipients` plus a copy to self (NIP-17 / NIP-59), then publish.
166
+ * Throws `PartialDelivery` (a `ToolError` with the same text a sealed send always gave) when a wrap reached no relay.
167
+ */
168
+ export async function wrapAndPublish(deps, rumor, recipients, expiration, now) {
169
+ const addressed = [...recipients, deps.signer.pubkey];
170
+ const wraps = addressed.map((r) => makeWrap(deps.signer.seal(rumor, r), r, expiration, now));
171
+ const perWrap = await publishEach(deps, wraps);
172
+ const failed = addressed.flatMap((r, i) => perWrap[i]?.some((x) => x.ok) ? [] : [{ pubkey: r, results: perWrap[i] ?? [] }]);
173
+ if (failed.length > 0) {
174
+ const label = (p) => p === deps.signer.pubkey ? "self copy" : (deps.roster.nameOf(p) ?? p);
175
+ const why = (rs) => rs.map((x) => `${x.relay}: ${x.error ?? "failed"}`).join("; ");
176
+ const deliveredKeys = addressed.filter((r) => !failed.some((f) => f.pubkey === r));
177
+ const delivered = deliveredKeys.map(label);
178
+ const state = delivered.length ? "partly delivered" : "not delivered";
179
+ const notDelivered = failed.map((f) => `${label(f.pubkey)} (${why(f.results)})`).join(", ");
180
+ throw new PartialDelivery(`sealed send ${state}: delivered to ${delivered.length ? delivered.join(", ") : "nobody"}; NOT delivered to ${notDelivered}; id ${rumor.id}`, deliveredKeys.filter((r) => r !== deps.signer.pubkey));
181
+ }
182
+ return byRelay(perWrap);
183
+ }
145
184
  /** One rumor, then seal and wrap per recipient plus a copy to self (NIP-17 / NIP-59). */
146
185
  export async function sendSealed(deps, recipients, envelope, session = null, group) {
147
186
  const now = deps.now();
148
187
  const tags = recipients.map((r) => ["p", r]);
188
+ // `h` for a server not yet upgraded; `subject` is the label of record (NIP-17, `17.md` line 19).
149
189
  if (group !== undefined)
150
- tags.push(["h", group]);
190
+ tags.push(["h", group], ["subject", group]);
151
191
  tags.push(...sessionTags(deps, session));
152
192
  if (envelope.re)
153
193
  tags.push(["e", envelope.re, "", "reply"]);
@@ -158,24 +198,13 @@ export async function sendSealed(deps, recipients, envelope, session = null, gro
158
198
  tags,
159
199
  });
160
200
  const expiration = envelope.ttl === undefined ? undefined : now + envelope.ttl;
161
- const addressed = [...recipients, deps.signer.pubkey];
162
- const wraps = addressed.map((r) => makeWrap(deps.signer.seal(rumor, r), r, expiration, now));
163
- const perWrap = await publishEach(deps, wraps);
164
- const failed = addressed.flatMap((r, i) => perWrap[i]?.some((x) => x.ok) ? [] : [{ pubkey: r, results: perWrap[i] ?? [] }]);
165
- if (failed.length > 0) {
166
- const label = (p) => p === deps.signer.pubkey ? "self copy" : (deps.roster.nameOf(p) ?? p);
167
- const why = (rs) => rs.map((x) => `${x.relay}: ${x.error ?? "failed"}`).join("; ");
168
- const delivered = addressed.filter((r) => !failed.some((f) => f.pubkey === r)).map(label);
169
- const state = delivered.length ? "partly delivered" : "not delivered";
170
- const notDelivered = failed.map((f) => `${label(f.pubkey)} (${why(f.results)})`).join(", ");
171
- throw new ToolError(`sealed send ${state}: delivered to ${delivered.length ? delivered.join(", ") : "nobody"}; NOT delivered to ${notDelivered}; id ${rumor.id}`);
172
- }
201
+ const published = await wrapAndPublish(deps, rumor, recipients, expiration, now);
173
202
  return {
174
203
  id: rumor.id,
175
204
  kind: 14,
176
205
  recipients: recipientsOf(deps, recipients),
177
206
  ...(group !== undefined ? { group } : {}),
178
- published: byRelay(perWrap),
207
+ published,
179
208
  };
180
209
  }
181
210
  export async function sendPlain(deps, target, envelope, session = null) {
@@ -184,8 +213,6 @@ export async function sendPlain(deps, target, envelope, session = null) {
184
213
  if (target.kind === "direct")
185
214
  tags.push(["p", target.pubkeys[0]]);
186
215
  tags.push(...sessionTags(deps, session));
187
- if (target.kind === "group")
188
- tags.push(["h", target.name]);
189
216
  if (envelope.re)
190
217
  tags.push(["e", envelope.re, "", "reply"]);
191
218
  if (envelope.ttl !== undefined)
@@ -197,12 +224,10 @@ export async function sendPlain(deps, target, envelope, session = null) {
197
224
  content: JSON.stringify(envelope),
198
225
  });
199
226
  const published = await publishAll(deps, [ev]);
200
- const pubkeys = target.kind === "group" ? [] : target.pubkeys;
201
227
  return {
202
228
  id: ev.id,
203
229
  kind: 7400,
204
- recipients: recipientsOf(deps, pubkeys),
205
- ...(target.kind === "group" ? { group: target.name } : {}),
230
+ recipients: recipientsOf(deps, target.pubkeys),
206
231
  published,
207
232
  };
208
233
  }
@@ -245,6 +270,8 @@ async function sendPublic(deps, a) {
245
270
  return { id: ev.id, kind: 7400, recipients: [], group: PUBLIC_ROOM, published };
246
271
  }
247
272
  export async function send(deps, a) {
273
+ if (isHelpAnswer(deps, a))
274
+ return sendHelpAnswer(deps, a);
248
275
  if (a.to === PUBLIC_ROOM)
249
276
  return sendPublic(deps, a);
250
277
  if (a.to === `group:${PUBLIC_ROOM}`) {
@@ -253,18 +280,40 @@ export async function send(deps, a) {
253
280
  if (deps.orchestrator === null) {
254
281
  throw new ToolError("this server has no orchestrator configured; it can only send to `public`");
255
282
  }
283
+ // Groups are sealed only (AB-57): refused before any relay read.
284
+ if (a.to.startsWith("group:") && !a.sealed) {
285
+ throw new ToolError(plainGroupRefusal(a.to.slice("group:".length)));
286
+ }
256
287
  await deps.roster.ensureFresh();
257
- const target = resolveTarget(deps, a.to, a.sealed);
288
+ const target = await resolveTarget(deps, a.to, a.sealed);
258
289
  const session = addresseeSession(deps, a, target);
259
290
  const size = Buffer.byteLength(JSON.stringify(a.body));
260
291
  if (size > MAX_BODY_BYTES) {
261
- throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes (beacon_inbox must return ten messages in under 64 KB); send less, or send a link to the data`);
292
+ throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes; send less, or send a link to the data`);
262
293
  }
263
294
  const envelope = buildEnvelope(a);
264
- if (a.sealed) {
265
- return sendSealed(deps, target.pubkeys, envelope, session, target.kind === "group" ? target.name : undefined);
295
+ const sentAt = deps.now();
296
+ const result = a.sealed
297
+ ? await sendSealed(deps, target.pubkeys, envelope, session, target.kind === "group" ? target.name : undefined)
298
+ : await sendPlain(deps, target, envelope, session);
299
+ // Only a send that reached every recipient is recorded; one that threw is not (its id is in the error text only).
300
+ if (a.type === "request") {
301
+ const known = a.sealed || target.kind === "direct";
302
+ recordAsk(deps, result.id, { at: sentAt, to: known ? target.pubkeys : null });
266
303
  }
267
- return sendPlain(deps, target, envelope, session);
304
+ return result;
305
+ }
306
+ const SENT_MAX = 1000;
307
+ const SENT_MAX_AGE = 7 * 24 * 60 * 60;
308
+ /** Remember a sent request for `beacon_wait`; drops entries older than seven days, then the oldest beyond 1000. */
309
+ export function recordAsk(deps, id, ask) {
310
+ const { sent } = deps;
311
+ for (const [k, v] of sent)
312
+ if (v.at < ask.at - SENT_MAX_AGE)
313
+ sent.delete(k);
314
+ sent.set(id, ask);
315
+ while (sent.size > SENT_MAX)
316
+ sent.delete(sent.keys().next().value);
268
317
  }
269
318
  /** Sealed `type: ack` to the sender of message `id`, as recorded when it was read. */
270
319
  export async function ack(deps, id) {
@@ -285,3 +334,65 @@ export async function ack(deps, id) {
285
334
  const r = await sendSealed(deps, [known.from], envelope, known.fromSession ?? null);
286
335
  return { ...r, re: id };
287
336
  }
337
+ /** `re` names a kind 5050 ask this session read, and the message is an answer or progress (AB-56). */
338
+ function isHelpAnswer(deps, a) {
339
+ if (a.re === undefined || (a.type !== "response" && a.type !== "event"))
340
+ return false;
341
+ return deps.state.known.get(a.re)?.help === 5050;
342
+ }
343
+ const HELP_STATUSES = ["processing", "partial", "error", "success"];
344
+ /**
345
+ * An answer to a kind 5050 ask (AB-56): a kind 6050 result or a kind 7000 status, a rumor in a NIP-59 wrap to the
346
+ * asker plus a copy to self. Always sealed (decision 0064 item 1); the asker's `beacon_wait` matches it by `e`.
347
+ */
348
+ async function sendHelpAnswer(deps, a) {
349
+ const re = a.re;
350
+ const asker = deps.state.known.get(re)?.from;
351
+ if (deps.orchestrator === null) {
352
+ throw new ToolError("this server has no orchestrator configured; it can only send to `public`");
353
+ }
354
+ await deps.roster.ensureFresh();
355
+ const notAsker = new ToolError(`re names a request from ${asker}; an answer goes to the asker`);
356
+ if (a.to === "all" || a.to === PUBLIC_ROOM || a.to.startsWith("group:"))
357
+ throw notAsker;
358
+ const target = await resolveTarget(deps, a.to, true);
359
+ if (target.kind !== "direct" || target.pubkeys[0] !== asker)
360
+ throw notAsker;
361
+ if (!a.sealed)
362
+ throw new ToolError("an answer to a help request is always sealed");
363
+ if (a.thread !== undefined) {
364
+ throw new ToolError("a help answer cannot carry thread; NIP-90 has no such field");
365
+ }
366
+ const size = Buffer.byteLength(JSON.stringify(a.body));
367
+ if (size > MAX_BODY_BYTES) {
368
+ throw new ToolError(`body is ${size} bytes of JSON; the cap is ${MAX_BODY_BYTES} bytes`);
369
+ }
370
+ const session = addresseeSession(deps, a, target);
371
+ let kind;
372
+ let content;
373
+ const tags = [];
374
+ if (a.type === "response") {
375
+ kind = 6050;
376
+ content = typeof a.body === "string" ? a.body : JSON.stringify(a.body);
377
+ }
378
+ else {
379
+ kind = 7000;
380
+ content = "";
381
+ const b = a.body;
382
+ const status = b !== null && typeof b === "object" ? b.status : undefined;
383
+ if (typeof status !== "string" || !HELP_STATUSES.includes(status)) {
384
+ throw new ToolError(`a status update needs body {status, note?} with status one of ${HELP_STATUSES.join(", ")}`);
385
+ }
386
+ const note = b?.note;
387
+ if (note !== undefined && typeof note !== "string") {
388
+ throw new ToolError("note must be a string");
389
+ }
390
+ tags.push(note === undefined ? ["status", status] : ["status", status, note]);
391
+ }
392
+ tags.push(["e", re], ["p", asker], ...sessionTags(deps, session));
393
+ const now = deps.now();
394
+ const rumor = deps.signer.rumor({ kind, created_at: now, content, tags });
395
+ const expiration = a.ttl === undefined ? undefined : now + a.ttl;
396
+ const published = await wrapAndPublish(deps, rumor, [asker], expiration, now);
397
+ return { id: rumor.id, kind, recipients: recipientsOf(deps, [asker]), published };
398
+ }