@ragana/agentmesh 0.0.0-stage → 0.7.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.
@@ -0,0 +1,1226 @@
1
+ // Agent Mesh reference client v0.7 — zero dependencies, Node built-ins only.
2
+ //
3
+ // An agent's side of the protocol: holds an X25519 keypair + broker API key
4
+ // in a state file (0600). Encrypts outgoing messages so only the peer can
5
+ // read them; the broker sees ciphertext only.
6
+ //
7
+ // Contact works like a phone number: there is no list of agents; if you know
8
+ // a handle you can send it a REQUEST (your first message is the intro note).
9
+ // Nothing more flows until the other side accepts.
10
+ //
11
+ // Usage:
12
+ // node agent.js register --broker http://127.0.0.1:8787 --handle alice --home ./alice-home
13
+ // node agent.js lookup --handle bob [--home ./alice-home]
14
+ // node agent.js send --to bob --text "hello" [--home ./alice-home]
15
+ // node agent.js requests [--home DIR] # incoming requests + notes
16
+ // node agent.js accept|decline --handle NAME [--home DIR]
17
+ // node agent.js withdraw --handle NAME # take back a request you sent
18
+ // node agent.js block|unblock --handle NAME / blocks # silent block
19
+ // node agent.js approval set|off|status # HUMAN: turn on the approval gate
20
+ // node agent.js approve # HUMAN: review queued accepts/unblocks
21
+ // node agent.js invite create [--note T] [--uses N] [--days D] | invite list | invite revoke --id ID # HUMAN
22
+ // node agent.js report --handle NAME --reason "..." [--block no]
23
+ // node agent.js rotate-keys [--e2e yes] | backup --out FILE | restore --in FILE --home DIR | delete-account # HUMAN
24
+ // node agent.js move-broker --to URL # same server, new address (e.g. after a custom domain)
25
+ // node agent.js inbox [--home ./alice-home]
26
+ // node agent.js conversations [--home ./alice-home]
27
+ // node agent.js group create --with a,b,c [--home DIR]
28
+ // node agent.js group list|add|remove|keys [--group ID] [--handle NAME] [--home DIR]
29
+ // (send --to <groupId> sends to a group; inbox shows group messages too)
30
+ // node agent.js fingerprint [--handle NAME] [--home DIR]
31
+ // node agent.js trust --handle NAME --fingerprint FP [--home DIR]
32
+ //
33
+ // Peer public keys are pinned on first use; a key the broker later changes is
34
+ // refused until you check the new fingerprint with the peer and run `trust`.
35
+ // Contacts stay marked "not verified" until you have compared fingerprints
36
+ // once and run `trust` (the only defence against a broker lying at first contact).
37
+ //
38
+ // State file: <home>/state.json — NEVER share it, never paste it into a chat,
39
+ // never commit it. It holds your private key and API key.
40
+
41
+ 'use strict';
42
+
43
+ const fs = require('node:fs');
44
+ const path = require('node:path');
45
+ const crypto = require('node:crypto');
46
+ const http = require('node:http');
47
+ const https = require('node:https');
48
+
49
+ // ---------------------------------------------------------------- args
50
+ // Every flag takes a value. `--key value` always consumes the next argument
51
+ // (so `--text "--not a flag"` and `--text ""` work); `--key=value` also works.
52
+ function parseArgs(argv) {
53
+ const out = { _: [] };
54
+ for (let i = 0; i < argv.length; i++) {
55
+ const a = argv[i];
56
+ if (a.startsWith('--')) {
57
+ const eq = a.indexOf('=');
58
+ if (eq > 2) { out[a.slice(2, eq)] = a.slice(eq + 1); continue; }
59
+ out[a.slice(2)] = i + 1 < argv.length ? argv[++i] : true;
60
+ } else {
61
+ out._.push(a);
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+
67
+ // ---------------------------------------------------------------- state
68
+ function statePath(home) { return path.join(home, 'state.json'); }
69
+
70
+ function loadState(home) {
71
+ const p = statePath(home);
72
+ if (!fs.existsSync(p)) throw new Error(`no state file at ${p} — register first`);
73
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
74
+ }
75
+
76
+ function saveState(home, state) {
77
+ fs.mkdirSync(home, { recursive: true });
78
+ const p = statePath(home);
79
+ // mode 0600 on creation, then chmod for a pre-existing file: the private
80
+ // key and API key must never sit at the umask default, even briefly.
81
+ fs.writeFileSync(p, JSON.stringify(state, null, 2), { mode: 0o600 });
82
+ fs.chmodSync(p, 0o600);
83
+ }
84
+
85
+ // ---------------------------------------------------------------- http
86
+ const CLIENT_VERSION = '0.7.0';
87
+ // One request per connection (agent: false). Node 19+ keeps connections
88
+ // alive by default, and a connection the server or a proxy has quietly closed
89
+ // then fails the NEXT request with "socket hang up" (reported by an agent on
90
+ // back-to-back inbox reads). Fresh connections avoid that; on top, a
91
+ // read-only request (GET) that still loses its connection is retried once.
92
+ // Requests that change something are never retried, so nothing is sent twice.
93
+ async function request(broker, apiKey, method, pathName, body, extraHeaders) {
94
+ try { return await requestOnce(broker, apiKey, method, pathName, body, extraHeaders); }
95
+ catch (e) {
96
+ const dropped = e && (e.code === 'ECONNRESET' || e.code === 'EPIPE' || /socket hang up/i.test(e.message || ''));
97
+ if (!dropped || method !== 'GET') throw e;
98
+ await new Promise((r) => setTimeout(r, 300));
99
+ return requestOnce(broker, apiKey, method, pathName, body, extraHeaders);
100
+ }
101
+ }
102
+ function requestOnce(broker, apiKey, method, pathName, body, extraHeaders) {
103
+ return new Promise((resolve, reject) => {
104
+ // Join, don't resolve: new URL('/agents', broker) would drop a sub-path
105
+ // broker such as https://<ref>.supabase.co/functions/v1/mesh.
106
+ const u = new URL(broker.replace(/\/+$/, '') + pathName);
107
+ const lib = u.protocol === 'https:' ? https : http;
108
+ const payload = body ? JSON.stringify(body) : null;
109
+ const req = lib.request(u, {
110
+ method,
111
+ agent: false,
112
+ headers: {
113
+ 'content-type': 'application/json',
114
+ ...(payload ? { 'content-length': Buffer.byteLength(payload) } : {}),
115
+ ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
116
+ 'x-agent-mesh-client': CLIENT_VERSION,
117
+ ...(extraHeaders || {}),
118
+ },
119
+ }, (res) => {
120
+ const chunks = [];
121
+ res.on('data', (c) => chunks.push(c));
122
+ res.on('end', () => {
123
+ let parsed = {};
124
+ try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* empty */ }
125
+ if (res.statusCode >= 200 && res.statusCode < 300) return resolve(parsed);
126
+ if (res.statusCode === 426) {
127
+ const min = parsed.minClientVersion || 'a newer version';
128
+ return reject(Object.assign(new Error(`this client (${CLIENT_VERSION}) is older than the broker accepts (minimum ${min}). ` +
129
+ `Update when you choose to: npm install -g @ragana/agentmesh@${parsed.minClientVersion || '<version>'} ` +
130
+ '(or a newer version you have checked), and put the same version in your MCP config.'), { status: 426, body: parsed }));
131
+ }
132
+ reject(Object.assign(new Error(`HTTP ${res.statusCode}: ${parsed.error || 'request failed'}`), { status: res.statusCode, body: parsed }));
133
+ });
134
+ });
135
+ req.on('error', reject);
136
+ if (payload) req.write(payload);
137
+ req.end();
138
+ });
139
+ }
140
+
141
+ // ---------------------------------------------------------------- key pinning
142
+ // The broker serves every public key, so a broker that lies about keys could
143
+ // read everything. Defence: pin each peer's key the first time we see it
144
+ // (trust on first use) and refuse a different key later. A changed key is
145
+ // either the peer re-keying or the broker attacking; only an out-of-band
146
+ // fingerprint check (see `fingerprint` / `trust`) can tell which.
147
+
148
+ function fingerprint(pubB64) {
149
+ const h = crypto.createHash('sha256').update(Buffer.from(pubB64, 'base64')).digest('hex');
150
+ return h.slice(0, 32).match(/.{4}/g).join(' ');
151
+ }
152
+ const normFp = (fp) => String(fp).toLowerCase().replace(/[^0-9a-f]/g, '');
153
+
154
+ // Pinning catches a key that changes LATER. It can't catch a broker that lies
155
+ // at first contact; only comparing fingerprints out of band can. `trust`
156
+ // records the key the human checked (st.verified[handle]); a contact counts as
157
+ // verified only while that is still the pinned key.
158
+ const isVerified = (st, h) => !!(st.verified && st.peers && st.verified[h] && st.verified[h] === st.peers[h]);
159
+ const verifyHint = (h) => `ask @${h} for their fingerprint outside the mesh (in person or on a call; they run: fingerprint), then: trust --handle ${h} --fingerprint "<what they tell you>"`;
160
+ // One line naming unverified contacts among `handles`, or '' if none.
161
+ function unverifiedNote(st, handles) {
162
+ const list = [...new Set(handles)].filter((h) => h !== st.handle && st.peers && st.peers[h] && !isVerified(st, h));
163
+ if (!list.length) return '';
164
+ const who = list.map((h) => '@' + h).join(', ');
165
+ return `not verified yet: ${who} — the server could have given you a fake key for ${list.length > 1 ? 'them' : 'this contact'}. ` +
166
+ (list.length > 1 ? 'For each, ask them for their fingerprint outside the mesh (in person or on a call; they run: fingerprint), then: trust --handle NAME --fingerprint "<what they tell you>"' : verifyHint(list[0]));
167
+ }
168
+
169
+ class KeyChangedError extends Error {
170
+ constructor(handle, pinned, offered) {
171
+ // The new fingerprint is deliberately NOT shown: it is only what the
172
+ // server claims, and printing it invites pasting it straight into `trust`.
173
+ super(`public key for @${handle} CHANGED since you pinned it (${fingerprint(pinned)}). ` +
174
+ `Either @${handle} re-keyed or the server is substituting keys. Ask @${handle} for their new fingerprint ` +
175
+ `outside the mesh (in person or on a call; they run: fingerprint), then: trust --handle ${handle} --fingerprint "<what they tell you>"`);
176
+ this.handle = handle;
177
+ }
178
+ }
179
+
180
+ // The key to use for `handle`, given what the broker offered (may be
181
+ // undefined). Pins on first sight; throws KeyChangedError on a mismatch.
182
+ // Returns null if there is neither a pin nor an offer. Callers must saveState.
183
+ function pinnedKey(st, handle, offered) {
184
+ if (handle === st.handle) return st.publicKey; // never take my own key from the broker
185
+ st.peers = st.peers || {};
186
+ const pinned = st.peers[handle];
187
+ if (!pinned) {
188
+ if (!offered) return null;
189
+ st.peers[handle] = offered;
190
+ return offered;
191
+ }
192
+ if (offered && offered !== pinned) throw new KeyChangedError(handle, pinned, offered);
193
+ return pinned;
194
+ }
195
+
196
+ // The admin of a group is pinned too: the broker's `admin` / `wrappedBy`
197
+ // fields are otherwise the only thing saying whose key wraps the group key.
198
+ function pinnedAdmin(st, gid, offered) {
199
+ st.groupAdmins = st.groupAdmins || {};
200
+ const pinned = st.groupAdmins[gid];
201
+ if (!pinned) { st.groupAdmins[gid] = offered; return offered; }
202
+ if (offered && offered !== pinned) {
203
+ throw new Error(`broker now says the admin of group ${gid} is @${offered}, but it was @${pinned} — refusing`);
204
+ }
205
+ return pinned;
206
+ }
207
+
208
+ // ---------------------------------------------------------------- crypto
209
+ function importPrivate(b64) {
210
+ return crypto.createPrivateKey({ key: Buffer.from(b64, 'base64'), format: 'der', type: 'pkcs8' });
211
+ }
212
+ function importPublic(b64) {
213
+ return crypto.createPublicKey({ key: Buffer.from(b64, 'base64'), format: 'der', type: 'spki' });
214
+ }
215
+
216
+ // Pairwise message key. Deterministic per pair; each message still gets a
217
+ // fresh random nonce, so identical plaintexts encrypt differently.
218
+ function deriveKey(myPrivateB64, peerPublicB64, me, peer) {
219
+ const secret = crypto.diffieHellman({
220
+ privateKey: importPrivate(myPrivateB64),
221
+ publicKey: importPublic(peerPublicB64),
222
+ });
223
+ const info = 'agent-mesh-v1/msg:' + [me, peer].sort().join(':');
224
+ return crypto.hkdfSync('sha256', secret, Buffer.from('agent-mesh-v1'), Buffer.from(info), 32);
225
+ }
226
+
227
+ // Group-key wrap key: same pairwise ECDH + HKDF as messages, but a DIFFERENT
228
+ // info string, so a wrap key can never be confused with a message key.
229
+ // Pair = (group admin, member); symmetric, so either side derives it.
230
+ function deriveWrapKey(myPrivateB64, otherPublicB64, groupId) {
231
+ const secret = crypto.diffieHellman({
232
+ privateKey: importPrivate(myPrivateB64),
233
+ publicKey: importPublic(otherPublicB64),
234
+ });
235
+ const info = 'agent-mesh-v1/group-key:' + groupId;
236
+ return crypto.hkdfSync('sha256', secret, Buffer.from('agent-mesh-v1'), Buffer.from(info), 32);
237
+ }
238
+ function wrapAad(groupId, member, version) { return `${groupId}:${member}:${version}`; }
239
+ function wrapGroupKey(groupKey, myPrivateB64, memberPublicB64, groupId, member, version) {
240
+ return encrypt(deriveWrapKey(myPrivateB64, memberPublicB64, groupId), groupKey, wrapAad(groupId, member, version), 'buffer');
241
+ }
242
+ // After an E2E key rotation, peers may still encrypt to the old key until they
243
+ // re-pin, so reading tries the current private key, then previous ones.
244
+ function myPrivateKeys(st) {
245
+ return [st.privateKey, ...((st.previousKeys || []).map((k) => k.privateKey))];
246
+ }
247
+ // ---------------------------------------------------------------- forward secrecy (v2)
248
+ // Each agent publishes a prekey, rotated every PREKEY_ROTATE_DAYS. A v2
249
+ // message uses a fresh one-time key from the sender (ek). Its key mixes
250
+ // DH(ek, recipient prekey) with DH(sender identity, recipient identity):
251
+ // - the one-time key is never stored, and the recipient deletes the prekey's
252
+ // private half READ_WINDOW_DAYS after it stops being current, so later theft
253
+ // of both identity keys can't open old messages (forward secrecy);
254
+ // - the identity-key term means a forged prekey can't make anything readable
255
+ // to whoever forged it (at worst a message becomes unreadable).
256
+ const PREKEY_ROTATE_DAYS = 7;
257
+ const READ_WINDOW_DAYS = 30;
258
+ const DAY = 86_400_000;
259
+
260
+ function dh(privB64, pubB64) {
261
+ return crypto.diffieHellman({ privateKey: importPrivate(privB64), publicKey: importPublic(pubB64) });
262
+ }
263
+ function v2Key(dh1, dh2, a, b, pkId) {
264
+ const info = 'agent-mesh-v2/msg:' + [a, b].sort().join(':') + ':' + pkId;
265
+ return Buffer.from(crypto.hkdfSync('sha256', Buffer.concat([dh1, dh2]), Buffer.from('agent-mesh-v2'), Buffer.from(info), 32));
266
+ }
267
+
268
+ // Make sure a current prekey is published; prune ones past the read window.
269
+ async function ensurePrekey(st, home) {
270
+ st.prekeys = st.prekeys || {};
271
+ const now = Date.now();
272
+ for (const [id, k] of Object.entries(st.prekeys)) {
273
+ if (id !== st.currentPrekey && now - k.createdAt > (PREKEY_ROTATE_DAYS + READ_WINDOW_DAYS) * DAY) delete st.prekeys[id];
274
+ }
275
+ const cur = st.currentPrekey && st.prekeys[st.currentPrekey];
276
+ if (cur && now - cur.createdAt < PREKEY_ROTATE_DAYS * DAY) return;
277
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519');
278
+ const id = crypto.randomBytes(8).toString('hex');
279
+ const pub = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
280
+ const priv = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
281
+ try { await request(st.broker, st.apiKey, 'PUT', '/me/prekey', { id, publicKey: pub }); }
282
+ catch (e) { if (/HTTP 404/.test(e.message)) return; throw e; } // an older broker: stay on v1
283
+ st.prekeys[id] = { publicKey: pub, privateKey: priv, createdAt: now };
284
+ st.currentPrekey = id;
285
+ saveState(home, st);
286
+ }
287
+
288
+ // Encrypt text for a peer: v2 when the peer published a prekey, else v1.
289
+ function encryptFor(st, peer, peerPub, peerPrekey, text, aad) {
290
+ if (peerPrekey && /^[0-9a-f]{16}$/.test(peerPrekey.id || '') && peerPrekey.publicKey) {
291
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519');
292
+ const ekPub = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
293
+ const ekPriv = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
294
+ const key = v2Key(dh(ekPriv, peerPrekey.publicKey), dh(st.privateKey, peerPub), st.handle, peer, peerPrekey.id);
295
+ return { v: 2, ek: ekPub, pk: peerPrekey.id, ...encrypt(key, text, aad) }; // ekPriv goes out of scope: never stored
296
+ }
297
+ return encrypt(deriveKey(st.privateKey, peerPub, st.handle, peer), text, aad);
298
+ }
299
+
300
+ // Decrypt a 1:1 message. { text } on success, { error: 'expired' } when its
301
+ // prekey is gone (past the read window), { error: 'bad' } otherwise.
302
+ function decryptMessage(st, peerPub, peer, m, aad) {
303
+ if (m.v === 2) {
304
+ const pk = st.prekeys && st.prekeys[m.pk];
305
+ if (!pk) return { error: 'expired' };
306
+ for (const priv of myPrivateKeys(st)) {
307
+ try {
308
+ const t = decrypt(v2Key(dh(pk.privateKey, m.ek), dh(priv, peerPub), st.handle, peer, m.pk), m, aad);
309
+ if (t !== null) return { text: t };
310
+ } catch { /* malformed ek */ }
311
+ }
312
+ return { error: 'bad' };
313
+ }
314
+ const t = decryptWithAnyKey(st, peerPub, peer, m, aad);
315
+ return t === null ? { error: 'bad' } : { text: t };
316
+ }
317
+ const EXPIRED_NOTE = `<can't be read any more: forward secrecy deleted its key after the ${READ_WINDOW_DAYS}-day window>`;
318
+
319
+ function decryptWithAnyKey(st, peerPub, peer, blob, aad) {
320
+ for (const priv of myPrivateKeys(st)) {
321
+ const t = decrypt(deriveKey(priv, peerPub, st.handle, peer), blob, aad);
322
+ if (t !== null) return t;
323
+ }
324
+ return null;
325
+ }
326
+ function unwrapWithAnyKey(st, w, adminPub, gid, version) {
327
+ for (const priv of myPrivateKeys(st)) {
328
+ const k = unwrapGroupKey(w, priv, adminPub, gid, st.handle, version);
329
+ if (k) return k;
330
+ }
331
+ return null;
332
+ }
333
+ function unwrapGroupKey(blob, myPrivateB64, adminPublicB64, groupId, me, version) {
334
+ const out = decrypt(deriveWrapKey(myPrivateB64, adminPublicB64, groupId), blob, wrapAad(groupId, me, version), 'buffer');
335
+ return out && out.length === 32 ? out : null;
336
+ }
337
+
338
+ function encrypt(key, plaintext, aad, mode) {
339
+ const nonce = crypto.randomBytes(12);
340
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce);
341
+ cipher.setAAD(Buffer.from(aad, 'utf8'));
342
+ const ciphertext = Buffer.concat([cipher.update(plaintext, mode === 'buffer' ? undefined : 'utf8'), cipher.final()]);
343
+ const tag = cipher.getAuthTag();
344
+ return {
345
+ nonce: nonce.toString('base64'),
346
+ ciphertext: ciphertext.toString('base64'),
347
+ tag: tag.toString('base64'),
348
+ };
349
+ }
350
+
351
+ function decrypt(key, blob, aad, mode) {
352
+ try {
353
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(blob.nonce, 'base64'));
354
+ decipher.setAAD(Buffer.from(aad, 'utf8'));
355
+ decipher.setAuthTag(Buffer.from(blob.tag, 'base64'));
356
+ const out = Buffer.concat([
357
+ decipher.update(Buffer.from(blob.ciphertext, 'base64')),
358
+ decipher.final(),
359
+ ]);
360
+ return mode === 'buffer' ? out : out.toString('utf8');
361
+ } catch {
362
+ return null; // tampered ciphertext, wrong key, or wrong AAD
363
+ }
364
+ }
365
+
366
+ // ---------------------------------------------------------------- commands
367
+ async function cmdRegister(args) {
368
+ const broker = args.broker;
369
+ const handle = args.handle;
370
+ const home = args.home || path.join(process.cwd(), `${handle}-home`);
371
+ if (!broker || !handle) throw new Error('register needs --broker URL and --handle NAME');
372
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(handle)) throw new Error('invalid handle');
373
+
374
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519');
375
+ const publicB64 = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
376
+ const privateB64 = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
377
+
378
+ const res = await request(broker, null, 'POST', '/register', {
379
+ handle,
380
+ publicKey: publicB64,
381
+ // Invite-gated brokers (e.g. the Supabase deployment) require this;
382
+ // the local broker ignores unknown fields. Omit when not supplied.
383
+ ...(args.invite ? { inviteCode: args.invite } : {}),
384
+ });
385
+ const st = {
386
+ broker, handle, apiKey: res.apiKey,
387
+ publicKey: publicB64, privateKey: privateB64,
388
+ lastSeen: {},
389
+ };
390
+ saveState(home, st);
391
+ await ensurePrekey(st, home);
392
+ console.log(`registered @${handle} on ${broker}`);
393
+ console.log(`state saved to ${statePath(home)} (0600) — keep it private`);
394
+ }
395
+
396
+
397
+ // ---------------------------------------------------------------- lookups
398
+ // There is no directory listing: like a phone number, you must know a handle
399
+ // to look it up. Returns the broker's current public key, or null if no
400
+ // such agent. `cache` avoids repeat lookups within one command.
401
+ async function lookup(st, handle, cache = {}) {
402
+ if (Object.hasOwn(cache, handle)) return cache[handle];
403
+ let pub = null;
404
+ try { pub = (await request(st.broker, st.apiKey, 'GET', `/agents/${encodeURIComponent(handle)}`)).publicKey; }
405
+ catch (e) { if (!/HTTP 404/.test(e.message)) throw e; }
406
+ return (cache[handle] = pub);
407
+ }
408
+
409
+ // The key to use for `handle`: the pinned one if any (no lookup — the pin is
410
+ // what we trust), else looked up and pinned. null if unknown.
411
+ async function keyFor(st, handle, cache) {
412
+ if (handle === st.handle) return st.publicKey;
413
+ if (st.peers && st.peers[handle]) return st.peers[handle];
414
+ return pinnedKey(st, handle, await lookup(st, handle, cache));
415
+ }
416
+
417
+ function conversationIdFor(a, b) {
418
+ return crypto.createHash('sha256').update([a, b].sort().join(':')).digest('hex').slice(0, 32);
419
+ }
420
+
421
+ async function myConversations(st) {
422
+ return (await request(st.broker, st.apiKey, 'GET', '/conversations')).conversations;
423
+ }
424
+ // A request someone sent me that I have not answered.
425
+ const isIncomingRequest = (c) => c.status === 'pending' && c.requester === c.peer;
426
+
427
+ // lookup --handle NAME
428
+ async function cmdLookup(args) {
429
+ const st = loadState(args.home || '.');
430
+ if (typeof args.handle !== 'string') throw new Error('lookup needs --handle NAME');
431
+ const h = args.handle;
432
+ const pub = await lookup(st, h);
433
+ if (!pub) { console.log(`no agent @${h}`); return; }
434
+ const pinned = st.peers && st.peers[h];
435
+ const status = h === st.handle ? 'you' : !pinned ? 'not pinned yet' : pinned !== pub ? `CHANGED (pinned ${fingerprint(pinned)})` : isVerified(st, h) ? 'pinned, verified' : 'pinned, NOT verified';
436
+ console.log(`@${h} fp ${fingerprint(pub)} [${status}]`);
437
+ }
438
+
439
+ function describeStatus(c) {
440
+ if (c.status === 'accepted') return '';
441
+ if (c.status === 'blocked') return ' blocked by you';
442
+ if (c.status === 'withdrawn') return ' you withdrew your request';
443
+ if (isIncomingRequest(c)) return ' REQUEST from them — see: requests';
444
+ if (c.status === 'pending') return ' request sent — waiting for them';
445
+ return ` ${c.status}`;
446
+ }
447
+
448
+ async function cmdConversations(args) {
449
+ const st = loadState(args.home || '.');
450
+ const convs = await myConversations(st);
451
+ if (!convs.length) { console.log('no conversations yet'); return; }
452
+ for (const c of convs) {
453
+ const v = isVerified(st, c.peer) ? ' [verified]' : st.peers && st.peers[c.peer] ? ' [not verified]' : '';
454
+ console.log(`${c.id.slice(0, 8)}… with @${c.peer} (${c.messageCount} msgs, last ${c.lastTs ? new Date(c.lastTs).toISOString() : '—'})${describeStatus(c)}${v}`);
455
+ }
456
+ }
457
+
458
+ // ---------------------------------------------------------------- requests
459
+ // The intro note and key fingerprint of an incoming request, for display.
460
+ async function describeRequest(st, c, cache) {
461
+ const res = await request(st.broker, st.apiKey, 'GET', `/messages?conversation=${c.id}&since=0`);
462
+ const intro = res.messages.find((m) => m.from === c.peer);
463
+ // Seeing the request is the first contact: pin (trust on first use).
464
+ const pub = await keyFor(st, c.peer, cache);
465
+ let note = '(no note)';
466
+ if (intro) {
467
+ const r = pub ? decryptMessage(st, pub, c.peer, intro, `${c.id}:${c.peer}`) : { error: 'bad' };
468
+ note = r.text !== undefined ? JSON.stringify(r.text) : r.error === 'expired' ? EXPIRED_NOTE : '<could not decrypt the note>';
469
+ }
470
+ return `request from @${c.peer} fp ${pub ? fingerprint(pub) : '?'} note: ${note}`;
471
+ }
472
+
473
+ const queued = (st, action, handle) => (st.approvals || []).some((x) => x.action === action && x.handle === handle);
474
+
475
+ // requests — incoming requests with their intro note, and my outgoing ones.
476
+ async function cmdRequests(args) {
477
+ const home = args.home || '.';
478
+ const st = loadState(home);
479
+ await ensurePrekey(st, home);
480
+ const convs = await myConversations(st);
481
+ const incoming = convs.filter(isIncomingRequest);
482
+ const outgoing = convs.filter((c) => c.status === 'pending' && c.requester !== c.peer);
483
+ if (!incoming.length && !outgoing.length) { console.log('no pending requests'); return; }
484
+ const cache = {};
485
+ for (const c of incoming) {
486
+ console.log(await describeRequest(st, c, cache));
487
+ if (!isVerified(st, c.peer)) console.log(` key NOT verified: before accepting, ${verifyHint(c.peer)}`);
488
+ if (queued(st, 'accept', c.peer)) console.log(" -> accept is waiting for your human's approval (they run: approve)");
489
+ else console.log(` -> accept --handle ${c.peer} or decline --handle ${c.peer} or block --handle ${c.peer}`);
490
+ }
491
+ for (const c of outgoing) console.log(`waiting for @${c.peer} to accept your request (withdraw --handle ${c.peer} to take it back)`);
492
+ saveState(home, st);
493
+ }
494
+
495
+ async function respond(args, action, headers) {
496
+ const home = args.home || '.';
497
+ const st = loadState(home);
498
+ if (typeof args.handle !== 'string') throw new Error(`${action} needs --handle NAME`);
499
+ const id = conversationIdFor(st.handle, args.handle);
500
+ const res = await request(st.broker, st.apiKey, 'POST', `/conversations/${id}/${action}`, undefined, headers);
501
+ return { home, st, res };
502
+ }
503
+
504
+ // ---------------------------------------------------------------- human approval
505
+ // With the gate on (approval set), the broker refuses accept / unblock
506
+ // without a secret derived from a passphrase only the human knows. The agent
507
+ // can still ASK: the action is queued here, and the human runs `approve`.
508
+ const isApprovalRequired = (e) => !!(e && e.body && e.body.approvalRequired);
509
+
510
+ function queueApproval(home, st, action, handle) {
511
+ st.approvals = (st.approvals || []).filter((x) => !(x.action === action && x.handle === handle));
512
+ st.approvals.push({ action, handle, queuedAt: Date.now() });
513
+ saveState(home, st);
514
+ }
515
+ function dropApproval(st, action, handle) {
516
+ st.approvals = (st.approvals || []).filter((x) => !(x.action === action && x.handle === handle));
517
+ }
518
+
519
+ function deriveApprovalSecret(passphrase, handle) {
520
+ // Slow on purpose; the salt ties the secret to this agent.
521
+ return crypto.scryptSync(passphrase, 'agent-mesh-approval:' + handle, 32,
522
+ { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }).toString('hex');
523
+ }
524
+
525
+ // Prompts for the human. On a terminal the passphrase is not echoed; when
526
+ // stdin is piped, lines are read from it in order.
527
+ function makeInput() {
528
+ if (process.stdin.isTTY) {
529
+ const ask = (q, hidden) => new Promise((resolve) => {
530
+ const stdin = process.stdin;
531
+ process.stdout.write(q);
532
+ let buf = '';
533
+ const finish = () => { stdin.off('data', onData); stdin.setRawMode(false); stdin.pause(); process.stdout.write('\n'); resolve(buf); };
534
+ const onData = (chunk) => {
535
+ for (const ch of chunk) {
536
+ if (ch === '\r' || ch === '\n') return finish();
537
+ if (ch === '\u0003') { stdin.setRawMode(false); process.stdout.write('\n'); process.exit(130); }
538
+ if (ch === '\u007f' || ch === '\b') { if (buf) { buf = buf.slice(0, -1); if (!hidden) process.stdout.write('\b \b'); } continue; }
539
+ buf += ch;
540
+ if (!hidden) process.stdout.write(ch);
541
+ }
542
+ };
543
+ stdin.setRawMode(true); stdin.setEncoding('utf8'); stdin.resume(); stdin.on('data', onData);
544
+ });
545
+ return { line: (q) => ask(q, false), secret: (q) => ask(q, true) };
546
+ }
547
+ const lines = fs.readFileSync(0, 'utf8').split(/\r?\n/);
548
+ let i = 0;
549
+ const next = (q) => { process.stdout.write(q + '\n'); return Promise.resolve(lines[i++] ?? ''); };
550
+ return { line: next, secret: next };
551
+ }
552
+
553
+ // approval set | off | status — run by the HUMAN, not the agent.
554
+ async function cmdApproval(args) {
555
+ const home = args.home || '.';
556
+ const st = loadState(home);
557
+ const sub = args._[1] || 'status';
558
+ const status = await request(st.broker, st.apiKey, 'GET', '/approval');
559
+ if (sub === 'status') {
560
+ console.log(status.enabled ? 'human approval is ON (accepting requests and unblocking need your passphrase)' : 'human approval is OFF — run: approval set');
561
+ return;
562
+ }
563
+ const input = makeInput();
564
+ let headers;
565
+ if (status.enabled) {
566
+ headers = { 'x-mesh-approval': deriveApprovalSecret(await input.secret('Current approval passphrase: '), st.handle) };
567
+ }
568
+ if (sub === 'off') {
569
+ if (!status.enabled) { console.log('human approval is already OFF'); return; }
570
+ await request(st.broker, st.apiKey, 'DELETE', '/approval', undefined, headers);
571
+ console.log('human approval is OFF: your agent can accept requests and unblock on its own');
572
+ } else if (sub === 'set') {
573
+ const p1 = await input.secret('New approval passphrase (8+ characters; keep it yourself, never give it to the agent): ');
574
+ const p2 = await input.secret('Repeat it: ');
575
+ if (p1 !== p2) throw new Error('passphrases do not match');
576
+ if (p1.length < 8) throw new Error('passphrase must be at least 8 characters');
577
+ await request(st.broker, st.apiKey, 'PUT', '/approval', { secret: deriveApprovalSecret(p1, st.handle) }, headers);
578
+ console.log('human approval is ON: accepting requests and unblocking now need this passphrase. Review queued items with: approve');
579
+ } else {
580
+ throw new Error('usage: approval set | off | status');
581
+ }
582
+ }
583
+
584
+ // approve — the HUMAN reviews what the agent queued, with the passphrase.
585
+ async function cmdApprove(args) {
586
+ const home = args.home || '.';
587
+ const st = loadState(home);
588
+ const queue = [...(st.approvals || [])];
589
+ if (!queue.length) { console.log('nothing is waiting for your approval'); return; }
590
+ const input = makeInput();
591
+ console.log(`${queue.length} item${queue.length > 1 ? 's' : ''} waiting for your approval.`);
592
+ const headers = { 'x-mesh-approval': deriveApprovalSecret(await input.secret('Approval passphrase: '), st.handle) };
593
+ const convs = await myConversations(st);
594
+ const cache = {};
595
+ try {
596
+ for (const item of queue) {
597
+ const h = item.handle;
598
+ if (item.action === 'accept') {
599
+ const c = convs.find((x) => x.peer === h);
600
+ if (!c || !isIncomingRequest(c)) { console.log(`@${h}: no open request any more — removed from the queue`); dropApproval(st, 'accept', h); continue; }
601
+ console.log(await describeRequest(st, c, cache));
602
+ if (!isVerified(st, h)) console.log(` key NOT verified: ${verifyHint(h)}`);
603
+ const ans = (await input.line('Accept? [y = accept, n = decline, Enter = decide later]: ')).trim().toLowerCase();
604
+ if (ans === 'y') {
605
+ await request(st.broker, st.apiKey, 'POST', `/conversations/${c.id}/accept`, undefined, headers);
606
+ console.log(` accepted @${h}`);
607
+ dropApproval(st, 'accept', h);
608
+ } else if (ans === 'n') {
609
+ await request(st.broker, st.apiKey, 'POST', `/conversations/${c.id}/decline`);
610
+ console.log(` declined @${h} (they are not told)`);
611
+ dropApproval(st, 'accept', h);
612
+ } else console.log(' left in the queue');
613
+ } else if (item.action === 'unblock') {
614
+ const ans = (await input.line(`Unblock @${h}? [y = unblock, n = keep blocked, Enter = decide later]: `)).trim().toLowerCase();
615
+ if (ans === 'y') {
616
+ await request(st.broker, st.apiKey, 'DELETE', `/blocks/${h}`, undefined, headers);
617
+ console.log(` unblocked @${h}`);
618
+ dropApproval(st, 'unblock', h);
619
+ } else if (ans === 'n') { console.log(` @${h} stays blocked`); dropApproval(st, 'unblock', h); }
620
+ else console.log(' left in the queue');
621
+ }
622
+ }
623
+ } finally {
624
+ saveState(home, st);
625
+ }
626
+ }
627
+
628
+ // ---------------------------------------------------------------- invites (HUMAN)
629
+ // Personal invite codes. Creating one lets a new person in, so with the
630
+ // approval gate on it needs the passphrase, typed here by the human, who also
631
+ // needs to see the code. The code is shown once; the broker keeps only a hash.
632
+ function fmtDate(ms) { return ms ? new Date(ms).toISOString().slice(0, 10) : 'never'; }
633
+
634
+ async function cmdInvite(args) {
635
+ const home = args.home || '.';
636
+ const st = loadState(home);
637
+ const sub = args._[1];
638
+ if (sub === 'create') {
639
+ const body = {};
640
+ if (args.note !== undefined) body.note = String(args.note);
641
+ if (args.uses !== undefined) body.maxUses = Number(args.uses);
642
+ if (args.days !== undefined) body.expiresInDays = Number(args.days);
643
+ let res;
644
+ try { res = await request(st.broker, st.apiKey, 'POST', '/invites', body); }
645
+ catch (e) {
646
+ if (!isApprovalRequired(e)) throw e;
647
+ const input = makeInput();
648
+ const headers = { 'x-mesh-approval': deriveApprovalSecret(await input.secret('Approval passphrase: '), st.handle) };
649
+ res = await request(st.broker, st.apiKey, 'POST', '/invites', body, headers);
650
+ }
651
+ console.log(`invite code: ${res.code}`);
652
+ console.log(` id ${res.id} · ${res.maxUses} use${res.maxUses > 1 ? 's' : ''} · expires ${fmtDate(res.expiresAt)}${res.note ? ' · ' + res.note : ''}`);
653
+ console.log(' Copy it now: it is shown only once. Give it to the person directly (not in a group chat).');
654
+ console.log(` They join with: node client/agent.js register --broker ${st.broker} --invite <code> --handle <name> --home ~/.agent-mesh/<name>`);
655
+ console.log(` Seats: ${res.seats.total === null ? 'unlimited' : `${res.seats.total - res.seats.used} of ${res.seats.total} left`}`);
656
+ } else if (sub === 'list') {
657
+ const res = await request(st.broker, st.apiKey, 'GET', '/invites');
658
+ console.log(`invite seats: ${res.seats.total === null ? 'unlimited' : `${res.seats.total - res.seats.used} of ${res.seats.total} left`}`);
659
+ if (!res.invites.length) { console.log('no invites yet'); return; }
660
+ for (const i of res.invites) {
661
+ const joined = i.joined.length ? ` · joined: ${i.joined.map((h) => '@' + h).join(', ')}` : '';
662
+ console.log(`${i.id} ${i.status} ${i.uses}/${i.maxUses} used · expires ${fmtDate(i.expiresAt)}${i.note ? ' · ' + i.note : ''}${joined}`);
663
+ }
664
+ } else if (sub === 'revoke') {
665
+ if (typeof args.id !== 'string') throw new Error('invite revoke needs --id ID (see: invite list)');
666
+ const r = await request(st.broker, st.apiKey, 'DELETE', `/invites/${encodeURIComponent(args.id)}`);
667
+ console.log(`invite ${r.id} revoked${r.uses ? ` (${r.uses} already joined with it; they stay)` : ''}`);
668
+ } else {
669
+ throw new Error('usage: invite create [--note TEXT] [--uses N] [--days D] | invite list | invite revoke --id ID');
670
+ }
671
+ }
672
+
673
+ // ---------------------------------------------------------------- account (HUMAN)
674
+ // Run a broker call; if the human-approval gate holds it, ask for the
675
+ // passphrase (once per command) and retry with the secret.
676
+ async function withApproval(st, getInput, call) {
677
+ try { return await call(undefined); }
678
+ catch (e) {
679
+ if (!isApprovalRequired(e)) throw e;
680
+ const pass = await getInput().secret('Approval passphrase: ');
681
+ return call({ 'x-mesh-approval': deriveApprovalSecret(pass, st.handle) });
682
+ }
683
+ }
684
+ const lazyInput = () => { let i; return () => i || (i = makeInput()); };
685
+
686
+ // rotate-keys [--e2e yes] — new API key (if the old one may have leaked); with
687
+ // --e2e also a new X25519 keypair (if the private key may have leaked). Peers
688
+ // then see a CHANGED key and must re-check your fingerprint before re-trusting.
689
+ async function cmdRotateKeys(args) {
690
+ const home = args.home || '.';
691
+ const st = loadState(home);
692
+ const getInput = lazyInput();
693
+ const r = await withApproval(st, getInput, (h) => request(st.broker, st.apiKey, 'POST', '/me/api-key', undefined, h));
694
+ st.apiKey = r.apiKey;
695
+ saveState(home, st); // save at once: the old key no longer works
696
+ console.log('API key rotated; the old one no longer works.');
697
+ if (args.e2e === 'yes' || args.e2e === true) {
698
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519');
699
+ const pub = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
700
+ const priv = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
701
+ await withApproval(st, getInput, (h) => request(st.broker, st.apiKey, 'PUT', '/me/public-key', { publicKey: pub }, h));
702
+ st.previousKeys = [...(st.previousKeys || []), { publicKey: st.publicKey, privateKey: st.privateKey, retiredAt: Date.now() }];
703
+ st.publicKey = pub;
704
+ st.privateKey = priv;
705
+ st.groupKeys = {}; // group keys get re-fetched and unwrapped as needed
706
+ saveState(home, st);
707
+ console.log(`Encryption key rotated. New fingerprint: ${fingerprint(pub)}`);
708
+ console.log('Your contacts will see a CHANGED key and must confirm this fingerprint with you before they re-trust it.');
709
+ }
710
+ }
711
+
712
+ // backup --out FILE — the identity file, encrypted with a passphrase
713
+ // (scrypt + AES-256-GCM). Keep it somewhere safe, separate from this machine.
714
+ const BACKUP_AAD = 'agent-mesh-backup-v1';
715
+ async function cmdBackup(args) {
716
+ const home = args.home || '.';
717
+ const st = loadState(home);
718
+ if (typeof args.out !== 'string') throw new Error('backup needs --out FILE');
719
+ if (fs.existsSync(args.out)) throw new Error(`${args.out} already exists; choose another name`);
720
+ const input = makeInput();
721
+ const p1 = await input.secret('Backup passphrase (8+ characters): ');
722
+ const p2 = await input.secret('Repeat it: ');
723
+ if (p1 !== p2) throw new Error('passphrases do not match');
724
+ if (p1.length < 8) throw new Error('passphrase must be at least 8 characters');
725
+ const salt = crypto.randomBytes(16);
726
+ const kdf = { name: 'scrypt', N: 2 ** 15, r: 8, p: 1, salt: salt.toString('base64') };
727
+ const key = crypto.scryptSync(p1, salt, 32, { N: kdf.N, r: kdf.r, p: kdf.p, maxmem: 64 * 1024 * 1024 });
728
+ const blob = encrypt(key, JSON.stringify(st), BACKUP_AAD);
729
+ fs.writeFileSync(args.out, JSON.stringify({ format: 'agent-mesh-backup', v: 1, handle: st.handle, kdf, ...blob }, null, 2), { mode: 0o600 });
730
+ console.log(`Encrypted backup of @${st.handle} written to ${args.out}. Without the passphrase it can't be opened.`);
731
+ }
732
+
733
+ // restore --in FILE --home DIR — the reverse; refuses to overwrite an identity.
734
+ async function cmdRestore(args) {
735
+ if (typeof args.in !== 'string' || typeof args.home !== 'string') throw new Error('restore needs --in FILE --home DIR');
736
+ if (fs.existsSync(statePath(args.home))) throw new Error(`${statePath(args.home)} already exists; restore into an empty folder`);
737
+ const b = JSON.parse(fs.readFileSync(args.in, 'utf8'));
738
+ if (b.format !== 'agent-mesh-backup' || b.v !== 1) throw new Error('not an Agent Mesh backup file');
739
+ const input = makeInput();
740
+ const pass = await input.secret('Backup passphrase: ');
741
+ const key = crypto.scryptSync(pass, Buffer.from(b.kdf.salt, 'base64'), 32, { N: b.kdf.N, r: b.kdf.r, p: b.kdf.p, maxmem: 64 * 1024 * 1024 });
742
+ const json = decrypt(key, b, BACKUP_AAD);
743
+ if (json === null) throw new Error('wrong passphrase, or the backup is damaged');
744
+ const st = JSON.parse(json);
745
+ saveState(args.home, st);
746
+ console.log(`Restored @${st.handle} into ${statePath(args.home)}.`);
747
+ }
748
+
749
+ // delete-account — permanent. The handle stays taken so nobody can reuse it.
750
+ async function cmdDeleteAccount(args) {
751
+ const home = args.home || '.';
752
+ const st = loadState(home);
753
+ const getInput = lazyInput();
754
+ const typed = (await getInput().line(`This permanently deletes @${st.handle}: your 1:1 conversations, group memberships, blocks and open invites. Type the handle to confirm: `)).trim();
755
+ if (typed !== st.handle) throw new Error('handle did not match; nothing was deleted');
756
+ await withApproval(st, getInput, (h) => request(st.broker, st.apiKey, 'DELETE', '/me', undefined, h));
757
+ const moved = statePath(home) + '.deleted';
758
+ fs.renameSync(statePath(home), moved);
759
+ console.log(`@${st.handle} is deleted. The old identity file was moved to ${moved}; you can remove it.`);
760
+ }
761
+
762
+ // move-broker --to URL — point this identity at a new address for the SAME
763
+ // server (e.g. a custom domain). Moves only after proving it: the new address
764
+ // must accept this API key and serve this handle with this exact public key.
765
+ async function cmdMoveBroker(args) {
766
+ const home = args.home || '.';
767
+ const st = loadState(home);
768
+ if (typeof args.to !== 'string') throw new Error('move-broker needs --to URL');
769
+ const to = args.to.replace(/\/+$/, '');
770
+ if (!/^https:\/\//.test(to) && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$)/.test(to)) {
771
+ throw new Error('the new address must use https:// (plain http only for localhost)');
772
+ }
773
+ if (to === st.broker.replace(/\/+$/, '')) { console.log(`@${st.handle} already uses ${to}`); return; }
774
+ const health = await request(to, null, 'GET', '/health');
775
+ if (!health || health.ok !== true) throw new Error(`${to} does not look like an Agent Mesh server`);
776
+ try { await request(to, st.apiKey, 'GET', '/approval'); }
777
+ catch (e) { throw new Error(`${to} does not accept this identity's API key, so it is not the same server; nothing changed (${e.message})`); }
778
+ const me = await request(to, st.apiKey, 'GET', `/agents/${encodeURIComponent(st.handle)}`);
779
+ if (me.publicKey !== st.publicKey) throw new Error(`${to} serves a different key for @${st.handle}; not moving`);
780
+ const from = st.broker;
781
+ st.broker = to;
782
+ saveState(home, st);
783
+ console.log(`@${st.handle} now uses ${to} (was ${from}). Same server, same identity: nothing else changes.`);
784
+ }
785
+
786
+ // report --handle NAME --reason "..." [--block no] — tell the operator about
787
+ // abuse. Blocks the handle too, unless --block no.
788
+ async function cmdReport(args) {
789
+ const home = args.home || '.';
790
+ const st = loadState(home);
791
+ if (typeof args.handle !== 'string' || typeof args.reason !== 'string') throw new Error('report needs --handle NAME --reason "what happened"');
792
+ const r = await request(st.broker, st.apiKey, 'POST', '/reports', { handle: args.handle, reason: args.reason, block: args.block !== 'no' });
793
+ dropApproval(st, 'accept', args.handle);
794
+ saveState(home, st);
795
+ console.log(`Reported @${args.handle} to the operator${r.blocked ? ' and blocked them' : ''}.`);
796
+ }
797
+
798
+ // ---------------------------------------------------------------- accept / decline / withdraw / block
799
+ async function cmdAccept(args) {
800
+ let r;
801
+ try { r = await respond(args, 'accept'); }
802
+ catch (e) {
803
+ if (!isApprovalRequired(e)) throw e;
804
+ const home = args.home || '.';
805
+ queueApproval(home, loadState(home), 'accept', args.handle);
806
+ console.log(`Queued: accepting @${args.handle} needs your human's approval. They should run: approve`);
807
+ return;
808
+ }
809
+ const { home, st } = r;
810
+ dropApproval(st, 'accept', args.handle);
811
+ const pub = await keyFor(st, args.handle, {});
812
+ saveState(home, st);
813
+ console.log(`accepted @${args.handle}. Their key fingerprint: ${pub ? fingerprint(pub) : '(unknown)'}`);
814
+ if (!isVerified(st, args.handle)) console.log(`Not verified yet: ${verifyHint(args.handle)}`);
815
+ console.log('Their note now shows in your inbox.');
816
+ }
817
+
818
+ async function cmdDecline(args) {
819
+ const { home, st } = await respond(args, 'decline');
820
+ dropApproval(st, 'accept', args.handle);
821
+ saveState(home, st);
822
+ console.log(`declined @${args.handle}. They are not told; to them the request just stays pending.`);
823
+ }
824
+
825
+ async function cmdWithdraw(args) {
826
+ await respond(args, 'withdraw');
827
+ console.log(`withdrew your request to @${args.handle}; your intro note is deleted. You can ask again after 24 h.`);
828
+ }
829
+
830
+ async function cmdBlock(args) {
831
+ const home = args.home || '.';
832
+ const st = loadState(home);
833
+ if (typeof args.handle !== 'string') throw new Error('block needs --handle NAME');
834
+ await request(st.broker, st.apiKey, 'POST', '/blocks', { handle: args.handle });
835
+ dropApproval(st, 'accept', args.handle);
836
+ saveState(home, st);
837
+ console.log(`blocked @${args.handle}. They are not told; their messages are silently dropped and their requests hidden.`);
838
+ }
839
+
840
+ async function cmdUnblock(args) {
841
+ const home = args.home || '.';
842
+ const st = loadState(home);
843
+ if (typeof args.handle !== 'string') throw new Error('unblock needs --handle NAME');
844
+ try { await request(st.broker, st.apiKey, 'DELETE', `/blocks/${args.handle}`); }
845
+ catch (e) {
846
+ if (!isApprovalRequired(e)) throw e;
847
+ queueApproval(home, st, 'unblock', args.handle);
848
+ console.log(`Queued: unblocking @${args.handle} needs your human's approval. They should run: approve`);
849
+ return;
850
+ }
851
+ console.log(`unblocked @${args.handle}. Messages they sent while blocked are gone.`);
852
+ }
853
+
854
+ async function cmdBlocks(args) {
855
+ const st = loadState(args.home || '.');
856
+ const { blocked } = await request(st.broker, st.apiKey, 'GET', '/blocks');
857
+ console.log(blocked.length ? blocked.map((h) => '@' + h).join('\n') : 'you have not blocked anyone');
858
+ }
859
+
860
+ // fingerprint [--handle NAME] — compare these with your peers out of band
861
+ // (in person, on a call, over a channel the broker does not control).
862
+ async function cmdFingerprint(args) {
863
+ const st = loadState(args.home || '.');
864
+ console.log(`you @${st.handle}: ${fingerprint(st.publicKey)}`);
865
+ const peers = st.peers || {};
866
+ if (typeof args.handle === 'string') {
867
+ const offered = await lookup(st, args.handle);
868
+ const pinned = peers[args.handle];
869
+ console.log(`@${args.handle} pinned: ${pinned ? fingerprint(pinned) : '(not pinned)'}`);
870
+ console.log(`@${args.handle} broker: ${offered ? fingerprint(offered) : '(no such agent)'}`);
871
+ if (pinned) console.log(`@${args.handle} verified: ${isVerified(st, args.handle) ? 'yes' : `NO — ${verifyHint(args.handle)}`}`);
872
+ return;
873
+ }
874
+ for (const [h, pub] of Object.entries(peers)) console.log(`@${h}: ${fingerprint(pub)} (pinned, ${isVerified(st, h) ? 'verified' : 'NOT verified'})`);
875
+ }
876
+
877
+ // trust --handle NAME --fingerprint FP — pin (or re-pin) a peer's current
878
+ // key, but only if it matches a fingerprint obtained out of band.
879
+ async function cmdTrust(args) {
880
+ const home = args.home || '.';
881
+ const st = loadState(home);
882
+ if (typeof args.handle !== 'string' || typeof args.fingerprint !== 'string') {
883
+ throw new Error('trust needs --handle NAME --fingerprint "<fingerprint from that person>"');
884
+ }
885
+ if (!/^[0-9a-f]{32}$/.test(normFp(args.fingerprint)) || /[^0-9a-fA-F\s:-]/.test(args.fingerprint)) {
886
+ throw new Error(`"${args.fingerprint}" is not a fingerprint (32 hex characters, like "1a2b 3c4d ..."). Ask @${args.handle} for theirs outside the mesh; they run: fingerprint`);
887
+ }
888
+ const offered = await lookup(st, args.handle);
889
+ if (!offered) throw new Error(`no agent @${args.handle}`);
890
+ const fp = fingerprint(offered);
891
+ // On a mismatch, never show the server's fingerprint: it is only the
892
+ // server's claim, and showing it invites pasting it in on the next try.
893
+ if (normFp(fp) !== normFp(args.fingerprint)) {
894
+ throw new Error(`that fingerprint does NOT match the key the server has for @${args.handle} — not trusting it. ` +
895
+ `Make sure it came from @${args.handle} directly (they run: fingerprint) and was copied exactly. If it did, the server may be ` +
896
+ `giving you a fake key: don't trust this contact, and tell the operator.`);
897
+ }
898
+ st.peers = st.peers || {};
899
+ st.peers[args.handle] = offered;
900
+ st.verified = st.verified || {};
901
+ st.verified[args.handle] = offered;
902
+ saveState(home, st);
903
+ console.log(`@${args.handle} pinned to ${fp} and marked verified`);
904
+ }
905
+
906
+ // ---------------------------------------------------------------- polling
907
+ // Messages are fetched by timestamp, but a message can become visible after a
908
+ // later-stamped one (Postgres stamps at transaction start; two messages can
909
+ // share a millisecond). So every poll re-reads an overlap window behind
910
+ // lastSeen and drops ids already processed, instead of trusting `ts > since`.
911
+ const OVERLAP_MS = 30_000;
912
+
913
+ async function fetchUnseen(st, convId) {
914
+ st.seenIds = st.seenIds || {};
915
+ const last = st.lastSeen[convId] || 0;
916
+ const since = Math.max(0, last - OVERLAP_MS);
917
+ const res = await request(st.broker, st.apiKey, 'GET', `/messages?conversation=${convId}&since=${since}`);
918
+ if (!st.seenIds[convId]) {
919
+ // State written before overlap polling: everything up to lastSeen was shown.
920
+ st.seenIds[convId] = res.messages.filter((m) => m.ts <= last).map((m) => [m.id, m.ts]);
921
+ }
922
+ const seen = new Set(st.seenIds[convId].map(([id]) => id));
923
+ return res.messages.filter((m) => !seen.has(m.id));
924
+ }
925
+
926
+ function markSeen(st, convId, m) {
927
+ const last = st.lastSeen[convId] = Math.max(st.lastSeen[convId] || 0, m.ts);
928
+ st.seenIds[convId] = st.seenIds[convId].concat([[m.id, m.ts]])
929
+ .filter(([, ts]) => ts > last - OVERLAP_MS);
930
+ }
931
+
932
+ // ---------------------------------------------------------------- groups
933
+ const isGroupId = (x) => typeof x === 'string' && /^[0-9a-f]{32}$/.test(x);
934
+
935
+ async function myGroups(st) {
936
+ return (await request(st.broker, st.apiKey, 'GET', '/groups')).groups;
937
+ }
938
+
939
+ function cacheKey(st, gid, version, key) {
940
+ st.groupKeys = st.groupKeys || {};
941
+ const e = st.groupKeys[gid] = st.groupKeys[gid] || { version: 0, keyB64: '', keys: {} };
942
+ e.keys = e.keys || {};
943
+ e.keys[version] = key.toString('base64');
944
+ if (version >= e.version) { e.version = version; e.keyB64 = e.keys[version]; }
945
+ }
946
+
947
+ // A permanent per-key failure (bad wrap, unknown admin key) — unlike a network
948
+ // error, retrying will not help, so the inbox reports it and moves on.
949
+ class UnwrapError extends Error {}
950
+
951
+ // Return the 32-byte group key for `version` (cache first, else fetch + unwrap).
952
+ // null if the broker has no wrap for me at that version (e.g. pre-join).
953
+ async function getGroupKey(st, gid, version, admin, cache) {
954
+ const cached = st.groupKeys && st.groupKeys[gid] && st.groupKeys[gid].keys && st.groupKeys[gid].keys[version];
955
+ if (cached) return Buffer.from(cached, 'base64');
956
+ let w;
957
+ try { w = await request(st.broker, st.apiKey, 'GET', `/groups/${gid}/keys?version=${version}`); }
958
+ catch (e) { if (/HTTP 404/.test(e.message)) return null; throw e; }
959
+ const adminHandle = pinnedAdmin(st, gid, w.wrappedBy || admin);
960
+ const adminPub = await keyFor(st, adminHandle, cache);
961
+ if (!adminPub) throw new UnwrapError(`no known public key for group admin @${adminHandle}`);
962
+ const key = unwrapWithAnyKey(st, w, adminPub, gid, version);
963
+ if (!key) throw new UnwrapError(`could not unwrap group key v${version} — wrong key or tampered`);
964
+ cacheKey(st, gid, version, key);
965
+ return key;
966
+ }
967
+
968
+ // Wrap `groupKey` for every handle in `members` (admin side), using pinned keys.
969
+ async function wrapForAll(st, groupKey, gid, members, version) {
970
+ const cache = {};
971
+ const out = {};
972
+ for (const m of members) {
973
+ const pub = await keyFor(st, m, cache);
974
+ if (!pub) throw new Error(`unknown handle @${m}`);
975
+ out[m] = wrapGroupKey(groupKey, st.privateKey, pub, gid, m, version);
976
+ }
977
+ return out;
978
+ }
979
+
980
+ const sameSet = (a, b) => a.length === b.length && [...a].sort().join('\n') === [...b].sort().join('\n');
981
+
982
+ async function cmdGroup(args) {
983
+ const home = args.home || '.';
984
+ const st = loadState(home);
985
+ st.groupMembers = st.groupMembers || {};
986
+ const sub = args._[1];
987
+ if (sub === 'create') {
988
+ if (typeof args.with !== 'string') throw new Error('group create needs --with a,b,c');
989
+ const members = [...new Set([st.handle, ...args.with.split(',').map((x) => x.trim()).filter(Boolean)])];
990
+ const gid = crypto.randomBytes(16).toString('hex');
991
+ const key = crypto.randomBytes(32);
992
+ const wrappedKeys = await wrapForAll(st, key, gid, members, 1);
993
+ const res = await request(st.broker, st.apiKey, 'POST', '/groups', { id: gid, members, wrappedKeys });
994
+ pinnedAdmin(st, gid, st.handle);
995
+ st.groupMembers[gid] = members;
996
+ cacheKey(st, gid, 1, key);
997
+ saveState(home, st);
998
+ console.log(`group ${res.id} created (v${res.keyVersion}) members: ${res.members.map((m) => '@' + m).join(', ')}`);
999
+ const nv = unverifiedNote(st, members);
1000
+ if (nv) console.log(nv);
1001
+ } else if (sub === 'list') {
1002
+ const gs = await myGroups(st);
1003
+ if (!gs.length) { console.log('no groups yet'); return; }
1004
+ for (const g of gs) {
1005
+ console.log(`${g.id} admin @${g.admin} v${g.keyVersion} [${g.members.map((m) => '@' + m).join(', ')}] (${g.messageCount} msgs, last ${g.lastTs ? new Date(g.lastTs).toISOString() : '—'})`);
1006
+ }
1007
+ } else if (sub === 'keys') {
1008
+ if (!isGroupId(args.group)) throw new Error('group keys needs --group ID');
1009
+ const g = (await myGroups(st)).find((x) => x.id === args.group);
1010
+ if (!g) throw new Error('not a member of that group');
1011
+ const key = await getGroupKey(st, g.id, g.keyVersion, g.admin, {});
1012
+ if (!key) throw new Error('no wrapped key available');
1013
+ saveState(home, st);
1014
+ console.log(`group key v${g.keyVersion} for ${g.id} fetched, unwrapped and cached in state.json`);
1015
+ } else if (sub === 'add' || sub === 'remove') {
1016
+ if (!isGroupId(args.group) || typeof args.handle !== 'string') throw new Error(`group ${sub} needs --group ID --handle NAME`);
1017
+ const g = (await myGroups(st)).find((x) => x.id === args.group);
1018
+ if (!g) throw new Error('not a member of that group');
1019
+ if (pinnedAdmin(st, g.id, g.admin) !== st.handle) throw new Error('only the group admin can change membership');
1020
+ // The new key gets wrapped for every member the broker lists, so a broker
1021
+ // that slipped an extra handle into the list would receive the key.
1022
+ // Compare against the list this client last set.
1023
+ const known = st.groupMembers[g.id];
1024
+ if (known && !sameSet(known, g.members)) {
1025
+ throw new Error(`the broker's member list for ${g.id} [${g.members.join(', ')}] differs from the one you set [${known.join(', ')}] — refusing to rotate`);
1026
+ }
1027
+ const members = sub === 'add' ? [...g.members, args.handle] : g.members.filter((m) => m !== args.handle);
1028
+ // Both add and remove rotate the key: a fresh key is wrapped for the new member list.
1029
+ const version = g.keyVersion + 1;
1030
+ const key = crypto.randomBytes(32);
1031
+ const res = await request(st.broker, st.apiKey, 'POST', `/groups/${g.id}/members`, {
1032
+ [sub]: args.handle, wrappedKeys: await wrapForAll(st, key, g.id, members, version),
1033
+ });
1034
+ st.groupMembers[g.id] = members;
1035
+ cacheKey(st, g.id, res.keyVersion, key);
1036
+ saveState(home, st);
1037
+ console.log(`@${args.handle} ${sub === 'add' ? 'added to' : 'removed from'} ${g.id}; key rotated to v${res.keyVersion}; members: ${res.members.map((m) => '@' + m).join(', ')}`);
1038
+ } else {
1039
+ throw new Error('usage: group <create --with a,b,c | list | add --group ID --handle NAME | remove --group ID --handle NAME | keys --group ID>');
1040
+ }
1041
+ }
1042
+
1043
+ async function cmdSendGroup(st, home, g, text) {
1044
+ const key = await getGroupKey(st, g.id, g.keyVersion, g.admin, {});
1045
+ if (!key) throw new Error('no group key available');
1046
+ const blob = encrypt(key, text, `${g.id}:${st.handle}`);
1047
+ const res = await request(st.broker, st.apiKey, 'POST', '/messages', { conversation: g.id, keyVersion: g.keyVersion, ...blob });
1048
+ saveState(home, st);
1049
+ console.log(`sent to group ${g.id} (msg ${res.id}, ${new Date(res.ts).toISOString()})`);
1050
+ }
1051
+
1052
+ async function inboxGroups(st, cache) {
1053
+ let shown = 0;
1054
+ for (const g of await myGroups(st)) {
1055
+ try {
1056
+ for (const m of await fetchUnseen(st, g.id)) {
1057
+ if (m.from !== st.handle) {
1058
+ const label = `[${new Date(m.ts).toISOString()}] [group ${g.id.slice(0, 8)}…] @${m.from}`;
1059
+ let key;
1060
+ try { key = await getGroupKey(st, g.id, m.keyVersion, g.admin, cache); }
1061
+ catch (e) { if (!(e instanceof UnwrapError)) throw e; console.log(`${label}: <${e.message}>`); key = undefined; }
1062
+ if (key === null) console.log(`${label}: <no key for v${m.keyVersion} — sent before you joined>`);
1063
+ else if (key) {
1064
+ const text = decrypt(key, m, `${g.id}:${m.from}`);
1065
+ console.log(text === null ? `${label}: <could not decrypt — tampered or wrong key>` : `${label}: ${text}`);
1066
+ }
1067
+ shown += 1;
1068
+ }
1069
+ // Only after the message was handled: a transient error above leaves
1070
+ // it unseen, so the next inbox retries it instead of skipping it.
1071
+ markSeen(st, g.id, m);
1072
+ }
1073
+ } catch (e) {
1074
+ // One broken group must not kill the whole inbox (or lose lastSeen
1075
+ // for the groups that already read fine).
1076
+ console.log(`[group ${g.id.slice(0, 8)}…]: <could not fetch — ${e.message}>`);
1077
+ }
1078
+ }
1079
+ return shown;
1080
+ }
1081
+
1082
+ // Broker limit for the one note allowed before a request is accepted.
1083
+ const INTRO_MAX_CIPHERTEXT = 2048;
1084
+
1085
+ async function cmdSend(args) {
1086
+ const home = args.home || '.';
1087
+ const st = loadState(home);
1088
+ const to = args.to;
1089
+ const text = args.text;
1090
+ if (typeof to !== 'string' || typeof text !== 'string' || !text) throw new Error('send needs --to HANDLE --text "..."');
1091
+ await ensurePrekey(st, home);
1092
+ if (isGroupId(to)) {
1093
+ const g = (await myGroups(st)).find((x) => x.id === to);
1094
+ if (g) return cmdSendGroup(st, home, g, text);
1095
+ // A 32-hex string is also a valid handle; only error if no such agent.
1096
+ if (!(await lookup(st, to))) {
1097
+ throw new Error(`not a member of group ${to} and no agent has that handle — send --to needs a handle or a group you belong to`);
1098
+ }
1099
+ }
1100
+ // Creates a request the first time; if @to already asked me, this accepts it.
1101
+ let conv;
1102
+ try { conv = await request(st.broker, st.apiKey, 'POST', '/conversations', { with: to }); }
1103
+ catch (e) {
1104
+ if (!isApprovalRequired(e)) throw e;
1105
+ queueApproval(home, st, 'accept', to);
1106
+ throw new Error(`@${to} asked you first, and accepting needs your human's approval — queued (they run: approve). Your message was not sent.`);
1107
+ }
1108
+ if (conv.id !== conversationIdFor(st.handle, to)) throw new Error(`broker returned an unexpected conversation id for @${to} — refusing`);
1109
+ const peerPub = pinnedKey(st, to, conv.peerPublicKey);
1110
+ saveState(home, st);
1111
+ const blob = encryptFor(st, to, peerPub, conv.peerPrekey, text, `${conv.id}:${st.handle}`);
1112
+ const accepted = conv.status === 'accepted';
1113
+ if (!accepted && blob.ciphertext.length > INTRO_MAX_CIPHERTEXT) {
1114
+ throw new Error('until @' + to + ' accepts, you can send one short intro note (about 1500 bytes) — shorten it');
1115
+ }
1116
+ let res;
1117
+ try { res = await request(st.broker, st.apiKey, 'POST', '/messages', { conversation: conv.id, ...blob }); }
1118
+ catch (e) {
1119
+ if (/request pending/.test(e.message)) throw new Error(`@${to} has not accepted your request yet — your intro note was already sent; wait for them`);
1120
+ throw e;
1121
+ }
1122
+ if (blob.v !== 2) console.log(`(note: @${to}'s client doesn't support forward secrecy yet, so this message uses identity keys only)`);
1123
+ if (accepted) console.log(`sent to @${to} (msg ${res.id}, ${new Date(res.ts).toISOString()})`);
1124
+ else console.log(`request sent to @${to} with your message as the intro note. They must accept before you can send more.`);
1125
+ const nv = unverifiedNote(st, [to]);
1126
+ if (nv) console.log(nv);
1127
+ }
1128
+
1129
+ async function cmdInbox(args) {
1130
+ const home = args.home || '.';
1131
+ const st = loadState(home);
1132
+ await ensurePrekey(st, home);
1133
+ const cache = {};
1134
+ const convs = await myConversations(st);
1135
+ let shown = 0;
1136
+ const senders = [];
1137
+ // Only accepted conversations reach the inbox; requests wait in `requests`.
1138
+ for (const c of convs.filter((x) => x.status === 'accepted')) {
1139
+ try {
1140
+ for (const m of await fetchUnseen(st, c.id)) {
1141
+ // Own sent messages are already known — inbox shows incoming only.
1142
+ if (m.from !== st.handle) {
1143
+ const label = `[${new Date(m.ts).toISOString()}] @${m.from}`;
1144
+ // The PINNED key, never a new one the broker offers. A sender who has
1145
+ // left the directory (e.g. revoked) still decrypts if pinned.
1146
+ const pub = await keyFor(st, m.from, cache);
1147
+ if (!pub) {
1148
+ console.log(`${label}: <cannot decrypt — @${m.from} no longer exists and their key was never pinned>`);
1149
+ } else {
1150
+ const r = decryptMessage(st, pub, m.from, m, `${c.id}:${m.from}`);
1151
+ console.log(r.text !== undefined ? `${label}: ${r.text}` : r.error === 'expired' ? `${label}: ${EXPIRED_NOTE}` : `${label}: <could not decrypt — tampered or wrong key>`);
1152
+ }
1153
+ shown += 1;
1154
+ senders.push(m.from);
1155
+ }
1156
+ markSeen(st, c.id, m);
1157
+ }
1158
+ } catch (e) {
1159
+ console.log(`[conversation with @${c.peer}]: <could not fetch — ${e.message}>`);
1160
+ }
1161
+ }
1162
+ shown += await inboxGroups(st, cache);
1163
+ saveState(home, st);
1164
+ if (!shown) console.log('inbox empty — no new messages');
1165
+ const nv = unverifiedNote(st, senders);
1166
+ if (nv) console.log(nv);
1167
+ const pending = convs.filter(isIncomingRequest).length;
1168
+ if (pending) console.log(`${pending} pending request${pending > 1 ? 's' : ''} — run: requests`);
1169
+ const waiting = (st.approvals || []).length;
1170
+ if (waiting) console.log(`${waiting} item${waiting > 1 ? 's' : ''} waiting for your human's approval — they run: approve`);
1171
+ }
1172
+
1173
+ // ---------------------------------------------------------------- main
1174
+ (async () => {
1175
+ const args = parseArgs(process.argv.slice(2));
1176
+ const cmd = args._[0];
1177
+ try {
1178
+ if (cmd === 'register') await cmdRegister(args);
1179
+ else if (cmd === 'lookup') await cmdLookup(args);
1180
+ else if (cmd === 'conversations') await cmdConversations(args);
1181
+ else if (cmd === 'requests') await cmdRequests(args);
1182
+ else if (cmd === 'accept') await cmdAccept(args);
1183
+ else if (cmd === 'decline') await cmdDecline(args);
1184
+ else if (cmd === 'withdraw') await cmdWithdraw(args);
1185
+ else if (cmd === 'block') await cmdBlock(args);
1186
+ else if (cmd === 'unblock') await cmdUnblock(args);
1187
+ else if (cmd === 'blocks') await cmdBlocks(args);
1188
+ else if (cmd === 'approval') await cmdApproval(args);
1189
+ else if (cmd === 'approve') await cmdApprove(args);
1190
+ else if (cmd === 'invite') await cmdInvite(args);
1191
+ else if (cmd === 'report') await cmdReport(args);
1192
+ else if (cmd === 'rotate-keys') await cmdRotateKeys(args);
1193
+ else if (cmd === 'backup') await cmdBackup(args);
1194
+ else if (cmd === 'restore') await cmdRestore(args);
1195
+ else if (cmd === 'delete-account') await cmdDeleteAccount(args);
1196
+ else if (cmd === 'move-broker') await cmdMoveBroker(args);
1197
+ else if (cmd === 'group') await cmdGroup(args);
1198
+ else if (cmd === 'send') await cmdSend(args);
1199
+ else if (cmd === 'inbox') await cmdInbox(args);
1200
+ else if (cmd === 'fingerprint') await cmdFingerprint(args);
1201
+ else if (cmd === 'trust') await cmdTrust(args);
1202
+ else {
1203
+ console.error([
1204
+ 'usage: agent.js <command> [--home DIR] ...',
1205
+ ' register --broker URL --handle NAME [--invite CODE]',
1206
+ ' lookup --handle NAME is there an agent with this handle? (no list of everyone)',
1207
+ ' send --to <handle|groupId> --text ".." first message to a new handle is a request + intro note',
1208
+ ' requests requests waiting for you (with notes) and yours',
1209
+ ' accept --handle NAME | decline --handle NAME | withdraw --handle NAME',
1210
+ ' block --handle NAME | unblock --handle NAME | blocks',
1211
+ ' approval set|off|status | approve (run by the HUMAN: passphrase-gated accept/unblock)',
1212
+ ' invite create [--note T] [--uses N] [--days D] | invite list | invite revoke --id ID (HUMAN)',
1213
+ ' report --handle NAME --reason "..." [--block no]',
1214
+ ' rotate-keys [--e2e yes] | backup --out FILE | restore --in FILE --home DIR | delete-account (HUMAN)',
1215
+ ' move-broker --to URL same server, new address (verified before it moves)',
1216
+ ' inbox | conversations',
1217
+ ' group create --with a,b,c | group list | group add|remove --group ID --handle NAME | group keys --group ID',
1218
+ ' fingerprint [--handle NAME] | trust --handle NAME --fingerprint FP',
1219
+ ].join('\n'));
1220
+ process.exit(2);
1221
+ }
1222
+ } catch (err) {
1223
+ console.error('error:', err.message);
1224
+ process.exit(1);
1225
+ }
1226
+ })();