@benjilabs/beaconfire-mcp 0.1.1 → 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/serve.js ADDED
@@ -0,0 +1,318 @@
1
+ import { verifyEvent } from "nostr-tools/pure";
2
+ import { CARD_LIMITS } from "./cards.js";
3
+ import { ToolError } from "./deps.js";
4
+ import { log } from "./redact.js";
5
+ import { makeWrap } from "./signer.js";
6
+ const DAY = 24 * 60 * 60;
7
+ /** A sealed card's wrap expires after the inbox window, so an unrefreshed card leaves the relay (invented, AB-55). */
8
+ export const CARD_WRAP_EXPIRY = 7 * DAY;
9
+ /** The republish cadence (invented, AB-55): at start and then this often. */
10
+ export const REPUBLISH_MS = DAY * 1000;
11
+ /** NIP-17 line 106: ten participants, the sender counted; a card has no self copy, so nine recipients (spec 9 item 10). */
12
+ export const MAX_CARD_RECIPIENTS = 9;
13
+ /** The warning every `public: true` result carries (spec section 9 item 7). */
14
+ export const PUBLIC_WARNING = "This card is public. On the production relay anyone on the internet who knows its address can read it: its kind, topics and text. It does not let strangers reach you; your trust list still decides whom you answer. Withdraw it with beacon_serve {d, withdraw: true}.";
15
+ const reason = (e) => (e instanceof Error ? e.message : String(e));
16
+ function checkText(label, v, max) {
17
+ if (v !== undefined && v.length > max)
18
+ throw new ToolError(`${label} is over ${max} characters`);
19
+ }
20
+ /** The recipients of a sealed card: `to` (names, 64-hex, npub), else the trust list, never me; at most 9. */
21
+ async function audience(deps, to) {
22
+ const { signer, roster, trust } = deps;
23
+ const me = signer.pubkey;
24
+ let keys;
25
+ if (to && to.length > 0) {
26
+ keys = to.map((x) => {
27
+ const pk = roster.resolve(x);
28
+ if (pk === null)
29
+ throw new ToolError(`unknown recipient "${x}"; use a roster name or a 64-hex pubkey`);
30
+ if (!signer.canSealTo(pk))
31
+ throw new ToolError("to is not a valid public key");
32
+ return pk;
33
+ });
34
+ }
35
+ else {
36
+ await trust.refresh(true);
37
+ if (trust.source === "unreadable") {
38
+ throw new ToolError("your trust list exists but cannot be read, so the default audience is unknown; name keys in to");
39
+ }
40
+ keys = trust.source === "own" ? [...(trust.own ?? [])] : roster.entries.map((e) => e.pubkey);
41
+ }
42
+ keys = [...new Set(keys)].filter((p) => p !== me);
43
+ if (keys.length === 0) {
44
+ throw new ToolError("no one to send the card to: trust list and roster are empty; name keys in to");
45
+ }
46
+ if (keys.length > MAX_CARD_RECIPIENTS) {
47
+ throw new ToolError(`sealed card to ${keys.length} recipients; the cap is ${MAX_CARD_RECIPIENTS} (NIP-17 allows ten participants, the sender counted); name at most ${MAX_CARD_RECIPIENTS} keys in to`);
48
+ }
49
+ return keys;
50
+ }
51
+ function cardTags(d, k, t) {
52
+ return [["d", d], ...(k === null ? [] : [["k", k]]), ...t.map((x) => ["t", x])];
53
+ }
54
+ /** One kind 31990 rumor, sealed and wrapped (with an expiration) to each of `recipients`; no copy to self. */
55
+ async function publishSealed(deps, recipients, tags, content, createdAt) {
56
+ const now = deps.now();
57
+ const rumor = deps.signer.rumor({ kind: 31990, created_at: createdAt, content, tags });
58
+ const expiration = now + CARD_WRAP_EXPIRY;
59
+ const results = await Promise.all(recipients.map(async (r) => ({
60
+ r,
61
+ res: await deps.pool.publish(makeWrap(deps.signer.seal(rumor, r), r, expiration, now)),
62
+ })));
63
+ const ok = (x) => x.res.some((p) => p.ok);
64
+ return {
65
+ id: rumor.id,
66
+ delivered: results.filter(ok).map((x) => ({ name: deps.roster.nameOf(x.r), pubkey: x.r })),
67
+ refused: results
68
+ .filter((x) => !ok(x))
69
+ .map((x) => ({
70
+ pubkey: x.r,
71
+ error: x.res.map((p) => `${p.relay}: ${p.error ?? "failed"}`).join("; "),
72
+ })),
73
+ };
74
+ }
75
+ function sealedFailure(s) {
76
+ return new ToolError(`card not delivered: ${s.refused.map((f) => `${f.pubkey} (${f.error})`).join(", ")}`);
77
+ }
78
+ async function publishPlain(deps, tags, content, createdAt) {
79
+ const ev = deps.signer.sign({ kind: 31990, created_at: createdAt, tags, content });
80
+ const published = await deps.pool.publish(ev);
81
+ if (!published.some((p) => p.ok)) {
82
+ throw new ToolError(`card not published: ${published.map((p) => `${p.relay}: ${p.error ?? "rejected"}`).join("; ")}`);
83
+ }
84
+ return { id: ev.id, published };
85
+ }
86
+ /** This agent's own plain cards named `d`, as the relay holds them: a strict read, so a silent relay refuses the call. */
87
+ async function readOwnPlain(deps, d) {
88
+ const me = deps.signer.pubkey;
89
+ let evs;
90
+ try {
91
+ evs = await deps.pool.fetch({ kinds: [31990], authors: [me], "#d": [d] }, { strict: true });
92
+ }
93
+ catch (e) {
94
+ throw new ToolError(`your own card could not be read from the relay (${reason(e)}); nothing was changed`);
95
+ }
96
+ let best = null;
97
+ for (const e of evs) {
98
+ if (e.pubkey !== me || !verifyEvent(e) || !e.tags.some((t) => t[0] === "d" && t[1] === d))
99
+ continue;
100
+ if (!best ||
101
+ e.created_at > best.created_at ||
102
+ (e.created_at === best.created_at && e.id < best.id)) {
103
+ best = e;
104
+ }
105
+ }
106
+ return best;
107
+ }
108
+ const isLive = (e) => e?.tags.some((t) => t[0] === "k") === true;
109
+ /**
110
+ * `beacon_serve`: publish a card (sealed to a chosen set, or plain with `public: true`), or withdraw one.
111
+ * The relay, not `served.json`, says whether a plain card of this agent is out: every call reads it first, and a
112
+ * narrowing (public to sealed) or a withdrawal replaces it. Every new version of (me, `d`) is stamped one second
113
+ * past the newest this agent has published, so a withdrawal and the next card never tie.
114
+ */
115
+ export async function serve(deps, a) {
116
+ const { cards } = deps;
117
+ if (deps.orchestrator === null) {
118
+ throw new ToolError("this server has no orchestrator configured; beacon_serve needs a roster");
119
+ }
120
+ if (a.public === true && a.to !== undefined) {
121
+ throw new ToolError("a public card has no audience: omit to");
122
+ }
123
+ if (a.withdraw === true ? a.k !== undefined : a.k === undefined) {
124
+ throw new ToolError(a.withdraw === true ? "a withdrawal names d, not k" : "`k` is needed");
125
+ }
126
+ if (a.k !== undefined && !/^[0-9]{1,5}$/.test(a.k)) {
127
+ throw new ToolError("k must be a kind number: one to five digits");
128
+ }
129
+ const d = a.d ?? a.k;
130
+ if (d === undefined || d.length < 1)
131
+ throw new ToolError("`d` is needed to withdraw");
132
+ checkText("d", d, CARD_LIMITS.dChars);
133
+ const t = a.t ?? [];
134
+ if (t.length > CARD_LIMITS.maxT)
135
+ throw new ToolError(`t has more than ${CARD_LIMITS.maxT} topics`);
136
+ for (const x of t) {
137
+ if (x.length < 1)
138
+ throw new ToolError("a topic is empty");
139
+ checkText("a topic", x, CARD_LIMITS.tChars);
140
+ }
141
+ checkText("content.name", a.content?.name, CARD_LIMITS.nameChars);
142
+ checkText("content.about", a.content?.about, CARD_LIMITS.aboutChars);
143
+ const content = a.content
144
+ ? {
145
+ ...(a.content.name ? { name: a.content.name } : {}),
146
+ ...(a.content.about ? { about: a.content.about } : {}),
147
+ }
148
+ : {};
149
+ const contentText = Object.keys(content).length > 0 ? JSON.stringify(content) : "";
150
+ await deps.roster.ensureFresh();
151
+ const now = deps.now();
152
+ const file = cards.readServed(now);
153
+ const entry = file.entries.find((e) => e.d === d);
154
+ const tomb = file.tombstones.find((x) => x.d === d);
155
+ const own = await readOwnPlain(deps, d);
156
+ let floor = Math.max(own?.created_at ?? 0, entry?.lastCreatedAt ?? 0, tomb?.lastCreatedAt ?? 0);
157
+ const stamp = () => (floor = Math.max(now, floor + 1));
158
+ const warnings = [];
159
+ const save = (change) => {
160
+ if (!cards.updateServed(now, change))
161
+ warnings.push("state not saved; the card will not be republished after a restart");
162
+ };
163
+ const done = (r) => ({
164
+ ...r,
165
+ ...(warnings.length > 0
166
+ ? { warning: [r.warning, ...warnings].filter(Boolean).join("; ") }
167
+ : {}),
168
+ });
169
+ /** The plain card on the relay is replaced by a withdrawal and the relay is read again: it must be gone. */
170
+ const withdrawPlain = async () => {
171
+ await publishPlain(deps, cardTags(d, null, []), "", stamp());
172
+ if (isLive(await readOwnPlain(deps, d))) {
173
+ throw new ToolError("plain card still on the relay: the withdrawal did not replace it");
174
+ }
175
+ };
176
+ if (a.withdraw === true) {
177
+ const sealedPart = entry?.form === "sealed" || (!entry && a.public !== true && !isLive(own));
178
+ const to = sealedPart ? await audience(deps, a.to ?? entry?.to ?? null) : [];
179
+ let plain = "none";
180
+ if (isLive(own)) {
181
+ await withdrawPlain();
182
+ plain = "withdrawn";
183
+ }
184
+ let sealed;
185
+ if (sealedPart) {
186
+ sealed = await publishSealed(deps, to, cardTags(d, null, []), "", stamp());
187
+ }
188
+ // A withdrawal the agent asked for stops republishing whatever its delivery: the entry goes either way.
189
+ save((f) => {
190
+ f.entries = f.entries.filter((e) => e.d !== d);
191
+ f.tombstones = [
192
+ ...f.tombstones.filter((x) => x.d !== d),
193
+ { d, lastCreatedAt: floor, withdrawnAt: now },
194
+ ];
195
+ });
196
+ if (sealed && sealed.delivered.length === 0) {
197
+ throw new ToolError(`the withdrawal did not reach the audience (${sealed.refused.map((f) => `${f.pubkey}: ${f.error}`).join("; ")}); the card is no longer republished and ages out in about a week`);
198
+ }
199
+ return done({
200
+ d,
201
+ form: sealedPart ? "sealed" : "plain",
202
+ withdrawn: true,
203
+ plain,
204
+ ...(sealed ? { delivered: sealed.delivered, refused: sealed.refused } : {}),
205
+ ...(!entry
206
+ ? { note: `no served card named ${d}; withdrawal sent to ${to.length} keys` }
207
+ : {}),
208
+ });
209
+ }
210
+ const k = a.k;
211
+ const upsert = (form, to, at) => save((f) => {
212
+ f.entries = [
213
+ ...f.entries.filter((e) => e.d !== d),
214
+ { d, k, t, content, form, to, lastPublished: now, lastCreatedAt: at },
215
+ ];
216
+ f.tombstones = f.tombstones.filter((x) => x.d !== d);
217
+ });
218
+ if (a.public === true) {
219
+ // The sealed withdrawal gets the lower stamp, so the reader's newest-wins merge keeps the new plain card.
220
+ const old = entry?.form === "sealed"
221
+ ? await audience(deps, entry.to).then((r) => r, () => [])
222
+ : [];
223
+ const withdrawStamp = old.length > 0 ? stamp() : 0;
224
+ const at = stamp();
225
+ const { id, published } = await publishPlain(deps, cardTags(d, k, t), contentText, at);
226
+ let note;
227
+ if (entry?.form === "sealed") {
228
+ const gone = old.length > 0
229
+ ? await publishSealed(deps, old, cardTags(d, null, []), "", withdrawStamp).catch((e) => {
230
+ log(`sealed withdrawal failed: ${reason(e)}`);
231
+ return null;
232
+ })
233
+ : null;
234
+ note = !gone
235
+ ? "the earlier sealed card could not be withdrawn from its audience (audience unknown or unreachable); it ages out in about a week"
236
+ : gone.delivered.length === 0
237
+ ? `the earlier sealed card was not withdrawn: the relay refused all ${gone.refused.length} keys; it ages out in about a week`
238
+ : `the earlier sealed card was withdrawn from ${gone.delivered.length} keys${gone.refused.length > 0 ? `, refused for ${gone.refused.length}; those copies age out in about a week` : ""}`;
239
+ }
240
+ upsert("plain", null, at);
241
+ return done({
242
+ d,
243
+ form: "plain",
244
+ k,
245
+ id,
246
+ published,
247
+ warning: PUBLIC_WARNING,
248
+ ...(note ? { note } : {}),
249
+ });
250
+ }
251
+ const explicit = a.to && a.to.length > 0 ? await audience(deps, a.to) : null;
252
+ const recipients = explicit ?? (await audience(deps, null));
253
+ let plain;
254
+ if (isLive(own)) {
255
+ await withdrawPlain();
256
+ plain = "withdrawn";
257
+ }
258
+ const at = stamp();
259
+ const sealed = await publishSealed(deps, recipients, cardTags(d, k, t), contentText, at);
260
+ if (sealed.delivered.length === 0)
261
+ throw sealedFailure(sealed);
262
+ upsert("sealed", explicit, at);
263
+ return done({
264
+ d,
265
+ form: "sealed",
266
+ k,
267
+ id: sealed.id,
268
+ delivered: sealed.delivered,
269
+ refused: sealed.refused,
270
+ expiresAt: now + CARD_WRAP_EXPIRY,
271
+ ...(plain ? { plain } : {}),
272
+ });
273
+ }
274
+ /**
275
+ * Wrap every served sealed card again with a new rumor, so the readers' seven-day window still holds it and a
276
+ * reader that upgraded since the last publish gets it (AB-55; the cadence is invented). Never throws. The file is
277
+ * read again right before each publish, so a card another session withdrew meanwhile is skipped; a withdrawal
278
+ * landing during the few seconds of the publish itself can still be undone (design, Not verified).
279
+ */
280
+ export async function republish(deps) {
281
+ try {
282
+ if (deps.orchestrator === null)
283
+ return;
284
+ const sealed = deps.cards.readServed(deps.now()).entries.filter((e) => e.form === "sealed");
285
+ if (sealed.length === 0)
286
+ return;
287
+ await deps.roster.ensureFresh();
288
+ for (const e of sealed) {
289
+ try {
290
+ // The entry as it is on disk now: another session may have served the card again or withdrawn it.
291
+ const now = deps.now();
292
+ const cur = deps.cards
293
+ .readServed(now)
294
+ .entries.find((x) => x.d === e.d && x.form === "sealed");
295
+ if (!cur)
296
+ continue;
297
+ const to = await audience(deps, cur.to);
298
+ const at = Math.max(now, cur.lastCreatedAt + 1);
299
+ const r = await publishSealed(deps, to, cardTags(cur.d, cur.k, cur.t), Object.keys(cur.content).length > 0 ? JSON.stringify(cur.content) : "", at);
300
+ if (r.delivered.length > 0) {
301
+ deps.cards.updateServed(now, (f) => {
302
+ const x = f.entries.find((y) => y.d === e.d && y.form === "sealed");
303
+ if (x) {
304
+ x.lastPublished = now;
305
+ x.lastCreatedAt = at;
306
+ }
307
+ });
308
+ }
309
+ }
310
+ catch (err) {
311
+ log(`card ${e.d} not republished: ${reason(err)}`);
312
+ }
313
+ }
314
+ }
315
+ catch (err) {
316
+ log(`republish failed: ${reason(err)}`);
317
+ }
318
+ }
package/dist/setup.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join, resolve } from "node:path";
4
+ import { createInterface } from "node:readline";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { parseArgs } from "node:util";
6
7
  import { generateSecretKey, getPublicKey } from "nostr-tools/pure";
@@ -17,12 +18,57 @@ export class SetupError extends Error {
17
18
  this.name = "SetupError";
18
19
  }
19
20
  }
21
+ function promptToken() {
22
+ return new Promise((resolve) => {
23
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
24
+ process.stdout.write("Enrollment token: ");
25
+ rl._writeToOutput = () => { };
26
+ rl.question("", (answer) => {
27
+ process.stdout.write("\n");
28
+ rl.close();
29
+ resolve(answer.trim());
30
+ });
31
+ });
32
+ }
20
33
  function die(msg) {
21
34
  throw new SetupError(msg);
22
35
  }
23
36
  function validName(name) {
24
37
  return NAME_PATTERN.test(name) && !RESERVED.has(name);
25
38
  }
39
+ function tomlEntry(serverPath, configPath) {
40
+ return [
41
+ "[mcp_servers.beaconfire]",
42
+ `command = "node"`,
43
+ `args = ${JSON.stringify([serverPath])}`,
44
+ `env = { BEACONFIRE_CONFIG = ${JSON.stringify(configPath)} }`,
45
+ `default_tools_approval_mode = "approve"`,
46
+ "",
47
+ ].join("\n");
48
+ }
49
+ /**
50
+ * Merge a beaconfire TOML entry into existing TOML text. Returns the merged string, or null if the
51
+ * beaconfire section already exists and force is false.
52
+ */
53
+ export function mergeToml(existing, entry, force) {
54
+ const lines = existing.split("\n");
55
+ const start = lines.findIndex((l) => l.trim() === "[mcp_servers.beaconfire]");
56
+ if (start === -1) {
57
+ const trimmed = existing.trimEnd();
58
+ return (trimmed ? trimmed + "\n\n" : "") + entry;
59
+ }
60
+ if (!force)
61
+ return null;
62
+ let end = lines.length;
63
+ for (let i = start + 1; i < lines.length; i++) {
64
+ const l = (lines[i] ?? "").trim();
65
+ if (l.startsWith("[") && !l.startsWith("[mcp_servers.beaconfire")) {
66
+ end = i;
67
+ break;
68
+ }
69
+ }
70
+ return [...lines.slice(0, start), entry.trimEnd(), "", ...lines.slice(end)].join("\n");
71
+ }
26
72
  /**
27
73
  * Runs `beaconfire-mcp setup`. Throws `SetupError` on invalid input; other throws are unexpected.
28
74
  *
@@ -43,6 +89,7 @@ export async function runSetup(argv, opts) {
43
89
  "state-dir": { type: "string" },
44
90
  project: { type: "string" },
45
91
  session: { type: "string" },
92
+ codex: { type: "boolean", default: false },
46
93
  force: { type: "boolean", default: false },
47
94
  },
48
95
  });
@@ -55,17 +102,23 @@ export async function runSetup(argv, opts) {
55
102
  const hasRelay = values.relay !== undefined;
56
103
  // --token wins over the env var; both are checked before anything is written.
57
104
  // Empty string from either source is treated as unset.
58
- const token = (values.token || undefined) ?? (process.env.BEACONFIRE_TOKEN || undefined);
105
+ let token = (values.token || undefined) ?? (process.env.BEACONFIRE_TOKEN || undefined);
59
106
  const hasToken = token !== undefined;
60
107
  if (hasSite && hasRelay) {
61
108
  die("--site and --relay cannot both be given; use --site + --token for private, --relay for public-only");
62
109
  }
63
- if (hasSite && !hasToken)
64
- die("a non-empty token is required; use --token or BEACONFIRE_TOKEN");
65
- if (values.token !== undefined && !hasSite)
66
- die("--token requires --site");
110
+ if (hasToken && !hasSite)
111
+ die("a token was given but --site is missing; use --site for private mode");
67
112
  if (!hasSite && !hasRelay)
68
113
  die("one of --site + --token (private) or --relay (public-only) is required");
114
+ if (hasSite && !hasToken) {
115
+ const canPrompt = opts?.readTokenImpl != null || !!process.stdin.isTTY;
116
+ if (!canPrompt)
117
+ die("a non-empty token is required; use --token or BEACONFIRE_TOKEN");
118
+ token = await (opts?.readTokenImpl ?? promptToken)();
119
+ if (!token)
120
+ die("enrollment token is required");
121
+ }
69
122
  const isPrivate = hasSite;
70
123
  let siteOrigin;
71
124
  if (isPrivate) {
@@ -102,35 +155,47 @@ export async function runSetup(argv, opts) {
102
155
  die(`config ${configPath} already exists; use --force to overwrite`);
103
156
  }
104
157
  let mcpExisting = {};
158
+ let tomlExisting = "";
105
159
  if (values.project !== undefined) {
106
160
  const projectDir = resolve(values.project);
107
161
  if (!existsSync(projectDir) || !statSync(projectDir).isDirectory()) {
108
162
  die(`--project: directory ${projectDir} does not exist`);
109
163
  }
110
- const mcpPath = join(projectDir, ".mcp.json");
111
- if (existsSync(mcpPath)) {
112
- let parsed;
113
- try {
114
- parsed = JSON.parse(readFileSync(mcpPath, "utf8"));
115
- }
116
- catch {
117
- die(`${mcpPath} is not valid JSON`);
164
+ if (values.codex) {
165
+ const tomlPath = join(projectDir, ".codex", "config.toml");
166
+ if (existsSync(tomlPath)) {
167
+ tomlExisting = readFileSync(tomlPath, "utf8");
168
+ if (tomlExisting.includes("[mcp_servers.beaconfire]") && !values.force) {
169
+ die(`${tomlPath} already has a beaconfire entry; use --force to replace it`);
170
+ }
118
171
  }
119
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
120
- die(`${mcpPath} is not a JSON object`);
121
- }
122
- const obj = parsed;
123
- if (obj.mcpServers !== undefined &&
124
- (typeof obj.mcpServers !== "object" ||
125
- obj.mcpServers === null ||
126
- Array.isArray(obj.mcpServers))) {
127
- die(`${mcpPath}: mcpServers is not an object`);
128
- }
129
- const servers = obj.mcpServers;
130
- if (servers?.beaconfire !== undefined && !values.force) {
131
- die(`${mcpPath} already has a beaconfire entry; use --force to replace it`);
172
+ }
173
+ else {
174
+ const mcpPath = join(projectDir, ".mcp.json");
175
+ if (existsSync(mcpPath)) {
176
+ let parsed;
177
+ try {
178
+ parsed = JSON.parse(readFileSync(mcpPath, "utf8"));
179
+ }
180
+ catch {
181
+ die(`${mcpPath} is not valid JSON`);
182
+ }
183
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
184
+ die(`${mcpPath} is not a JSON object`);
185
+ }
186
+ const obj = parsed;
187
+ if (obj.mcpServers !== undefined &&
188
+ (typeof obj.mcpServers !== "object" ||
189
+ obj.mcpServers === null ||
190
+ Array.isArray(obj.mcpServers))) {
191
+ die(`${mcpPath}: mcpServers is not an object`);
192
+ }
193
+ const servers = obj.mcpServers;
194
+ if (servers?.beaconfire !== undefined && !values.force) {
195
+ die(`${mcpPath} already has a beaconfire entry; use --force to replace it`);
196
+ }
197
+ mcpExisting = obj;
132
198
  }
133
- mcpExisting = obj;
134
199
  }
135
200
  }
136
201
  // ── set up directories ───────────────────────────────────────────────────────
@@ -186,27 +251,46 @@ export async function runSetup(argv, opts) {
186
251
  // validate the config we just wrote
187
252
  loadConfig(configPath);
188
253
  const serverPath = opts?.serverPath ?? join(dirname(fileURLToPath(import.meta.url)), "index.js");
189
- const mcpEntry = {
190
- command: "node",
191
- args: [serverPath],
192
- env: { BEACONFIRE_CONFIG: configPath },
193
- };
194
- if (values.project !== undefined) {
195
- const projectDir = resolve(values.project);
196
- const mcpPath = join(projectDir, ".mcp.json");
197
- const updated = {
198
- ...mcpExisting,
199
- mcpServers: {
200
- ...mcpExisting.mcpServers,
201
- beaconfire: mcpEntry,
202
- },
203
- };
204
- writeFileSync(mcpPath, `${JSON.stringify(updated, null, 2)}\n`);
205
- console.log(`wrote ${mcpPath}`);
254
+ if (values.codex) {
255
+ const entry = tomlEntry(serverPath, configPath);
256
+ if (values.project !== undefined) {
257
+ const projectDir = resolve(values.project);
258
+ const tomlPath = join(projectDir, ".codex", "config.toml");
259
+ mkdirSync(dirname(tomlPath), { recursive: true });
260
+ const merged = mergeToml(tomlExisting, entry, values.force ?? false);
261
+ if (merged === null)
262
+ die(`${tomlPath} already has a beaconfire entry; use --force to replace it`);
263
+ writeFileSync(tomlPath, merged.trimEnd() + "\n");
264
+ console.log(`wrote ${tomlPath}`);
265
+ }
266
+ else {
267
+ console.log("\nAdd to your project's .codex/config.toml:");
268
+ console.log(entry);
269
+ }
206
270
  }
207
271
  else {
208
- console.log("\nAdd to your project's .mcp.json:");
209
- console.log(JSON.stringify({ mcpServers: { beaconfire: mcpEntry } }, null, 2));
272
+ const mcpEntry = {
273
+ command: "node",
274
+ args: [serverPath],
275
+ env: { BEACONFIRE_CONFIG: configPath },
276
+ };
277
+ if (values.project !== undefined) {
278
+ const projectDir = resolve(values.project);
279
+ const mcpPath = join(projectDir, ".mcp.json");
280
+ const updated = {
281
+ ...mcpExisting,
282
+ mcpServers: {
283
+ ...mcpExisting.mcpServers,
284
+ beaconfire: mcpEntry,
285
+ },
286
+ };
287
+ writeFileSync(mcpPath, `${JSON.stringify(updated, null, 2)}\n`);
288
+ console.log(`wrote ${mcpPath}`);
289
+ }
290
+ else {
291
+ console.log("\nAdd to your project's .mcp.json:");
292
+ console.log(JSON.stringify({ mcpServers: { beaconfire: mcpEntry } }, null, 2));
293
+ }
210
294
  }
211
295
  if (isPrivate) {
212
296
  console.log(`\nDone. Send messages to this agent with to: "${name}"`);
package/dist/signer.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { nip19 } from "nostr-tools";
2
2
  import { minePow } from "nostr-tools/nip13";
3
- import { encrypt, getConversationKey } from "nostr-tools/nip44";
3
+ import { decrypt, encrypt, getConversationKey } from "nostr-tools/nip44";
4
4
  import { createRumor, createSeal, unwrapEvent } from "nostr-tools/nip59";
5
5
  import { finalizeEvent, generateSecretKey, getPublicKey, } from "nostr-tools/pure";
6
6
  const TWO_DAYS = 2 * 24 * 60 * 60;
@@ -40,6 +40,24 @@ export class Signer {
40
40
  seal(rumor, recipient) {
41
41
  return createSeal(rumor, this.#sk, recipient);
42
42
  }
43
+ /** True when `recipient` is a valid public key to seal to (the NIP-44 key derivation `seal` and `makeWrap` use succeeds). */
44
+ canSealTo(recipient) {
45
+ try {
46
+ getConversationKey(this.#sk, recipient);
47
+ return true;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ /** NIP-44 to this key's own public key (NIP-51 private items: the shared key is derived from the author's own pair). */
54
+ encryptToSelf(plaintext) {
55
+ return encrypt(plaintext, getConversationKey(this.#sk, this.pubkey));
56
+ }
57
+ /** Throws unless `ciphertext` was made by `encryptToSelf` under this key. */
58
+ decryptFromSelf(ciphertext) {
59
+ return decrypt(ciphertext, getConversationKey(this.#sk, this.pubkey));
60
+ }
43
61
  /** Throws unless wrap, seal signature and `rumor.pubkey == seal.pubkey` all hold (nip59). */
44
62
  unwrap(wrap) {
45
63
  return unwrapEvent(wrap, this.#sk);
package/dist/state.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  const SEVEN_DAYS = 7 * 24 * 60 * 60;
4
+ /** Most held-back markers kept (invented, AB-48): bounds `seen.json` against a flood of strangers. */
5
+ export const MAX_HELD = 200;
4
6
  /** A session keeps its cursor and seen set in `<stateDir>/sessions/<name>`; a session-less server in `stateDir`. */
5
7
  export function stateDirFor(stateDir, session) {
6
8
  return session === null ? stateDir : join(stateDir, "sessions", session);