openmsg 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -3,12 +3,24 @@
3
3
  import { allAgents, findAgent, self } from "./registry.mjs";
4
4
  import { createMessage, address, MAX_HOPS } from "./envelope.mjs";
5
5
  import * as mailbox from "./mailbox.mjs";
6
- import * as claude from "./adapters/claude.mjs";
7
- import * as opencode from "./adapters/opencode.mjs";
8
- import * as codex from "./adapters/codex.mjs";
9
6
  import { runHook } from "./hook.mjs";
10
7
  import { installHooks, uninstallHooks } from "./hookinstall.mjs";
11
8
  import { installGlobal, installProject, uninstall, GLOBAL_TARGETS, PROJECT_FILES } from "./install.mjs";
9
+ import * as identity from "./identity.mjs";
10
+ import * as directory from "./directory.mjs";
11
+ import * as invite from "./invite.mjs";
12
+ import * as gateway from "./gateway.mjs";
13
+ import * as published from "./published.mjs";
14
+ import * as permissions from "./permissions.mjs";
15
+ import * as inbound from "./inbound.mjs";
16
+ import * as remote from "./remote.mjs";
17
+ import { deliverLocal } from "./deliver.mjs";
18
+ import * as relay from "./relay.mjs";
19
+ import * as relaylink from "./relaylink.mjs";
20
+ import * as outbox from "./outbox.mjs";
21
+ import * as limits from "./limits.mjs";
22
+ import * as device from "./device.mjs";
23
+ import * as dirsync from "./dirsync.mjs";
12
24
  import { fileURLToPath } from "node:url";
13
25
  import fs from "node:fs";
14
26
  import path from "node:path";
@@ -26,6 +38,43 @@ const USAGE = `openmsg — messages between AI coding agents
26
38
  openmsg install --project [dir] the same, for one project only
27
39
  openmsg uninstall [--project] remove what install wrote
28
40
 
41
+ For the agents of another person, on another machine:
42
+
43
+ openmsg id create [--label <n>] make the signing key and the sealing key
44
+ openmsg id show [--json] show the owner id and the fingerprint
45
+ openmsg invite create make a token that invites one person
46
+ [--project <label>] [--project-id <id>] [--hours <n>]
47
+ openmsg invite show <token> read a token, and write nothing
48
+ openmsg invite accept <token> --fingerprint "<value>"
49
+ openmsg dir list [--json] the members of each project
50
+ openmsg dir endpoint <owner> <url> where the gateway of that owner answers
51
+ openmsg dir revoke <project-id> <owner-id> [--reason <text>]
52
+ openmsg gateway start [--port <n>] [--host <h>]
53
+ openmsg publish <agent> let the project reach this session
54
+ openmsg unpublish <alias> take a session back
55
+ openmsg permit <owner> <accept|hold|refuse>
56
+ openmsg held [<id>] [--text] the messages that wait for you
57
+ openmsg held --all every message from another person, and its state
58
+ openmsg accept <id> [--always] give a held message to the agent
59
+ openmsg ack <id> say that you read a message
60
+ openmsg limits the limits that this machine holds
61
+ openmsg device create [--label <n>] give this machine its own keys
62
+ openmsg device request ask the machine that holds the owner key
63
+ openmsg device grant <token> answer a request, on the owner machine
64
+ [--days <n>] [--project <id>]
65
+ openmsg device accept <token> keep the answer, on the new machine
66
+ openmsg device show the machine, and what it may sign
67
+ openmsg dir revoke-device <project-id> <device-id>
68
+ openmsg dir sync send and read the directory of each project
69
+ openmsg dir pending the owners that wait for you to accept them
70
+ openmsg dir accept <owner> --fingerprint "<value>"
71
+ openmsg device revoke <id> tell the team that a machine of yours is gone
72
+ openmsg relay start [--port <n>] [--cert <file>] [--key <file>]
73
+ openmsg relay use <url> [--ca <file>] send through that relay
74
+ openmsg outbox [--all] the messages that wait for a receipt
75
+
76
+ A message to another person goes to "claude:api-worker@alice".
77
+
29
78
  Addresses look like "claude:api-worker" or "opencode:ses_123".
30
79
  `;
31
80
 
@@ -43,8 +92,11 @@ async function cmdList() {
43
92
  }
44
93
  }
45
94
 
46
- async function cmdSend(target, text, replyTo = null) {
95
+ async function cmdSend(target, text, replyTo = null, args = []) {
47
96
  if (!target || !text) throw new Error('usage: openmsg send <agent> "<text>" [--reply-to <message-id>]');
97
+ // An alias with an owner, such as "claude:api-worker@alice", belongs to
98
+ // another person. That message goes through the two gateways.
99
+ if (target.includes("@")) return cmdSendRemote(target, text, replyTo, args);
48
100
  const from = await self();
49
101
  // A reply keeps the conversation of the message that it answers, and it adds
50
102
  // this agent to the chain of hops.
@@ -86,21 +138,7 @@ async function cmdSend(target, text, replyTo = null) {
86
138
  );
87
139
  }
88
140
 
89
- let result;
90
- if (to.vendor === "claude") {
91
- const token = to.transport.path === process.env.CLAUDE_CODE_MESSAGING_SOCKET
92
- ? process.env.CLAUDE_CODE_MESSAGING_TOKEN
93
- : undefined;
94
- result = await claude.deliver(to, message, { token });
95
- } else if (to.vendor === "opencode") {
96
- result = await opencode.deliver(to, message);
97
- } else if (to.vendor === "codex") {
98
- result = await codex.deliver(to, message);
99
- } else {
100
- // An agent with no push entry point, such as Gemini CLI or Cursor CLI,
101
- // reads its mailbox at the end of a turn. The message waits there.
102
- result = { delivered: false, transport: "mailbox" };
103
- }
141
+ const result = await deliverLocal(to, message);
104
142
 
105
143
  // "delivered" means an adapter pushed the message into the live session.
106
144
  // "queued" means it waits in the mailbox for an agent that reads it at the
@@ -145,6 +183,635 @@ async function cmdInbox(args) {
145
183
  mailbox.markRead(me, rows.map((r) => r.messageId));
146
184
  }
147
185
 
186
+ // --- version 0.2: identity, invitations, and the directory ----------------
187
+
188
+ // A project id, from the flag or from the directory. One project needs no
189
+ // flag, and more than one project needs the name.
190
+ function projectId(args) {
191
+ const named = flag(args, "project");
192
+ if (named) {
193
+ const known = directory.project(named) ?? directory.projects().find((p) => p.label === named);
194
+ if (!known) throw new Error(`no project "${named}" in the directory`);
195
+ return known.id;
196
+ }
197
+ const all = directory.projects();
198
+ if (all.length === 1) return all[0].id;
199
+ if (all.length === 0) throw new Error("no project in the directory. Run: openmsg invite create");
200
+ throw new Error(`${all.length} projects: ${all.map((p) => `${p.id} (${p.label})`).join(", ")}. Add --project <id>`);
201
+ }
202
+
203
+ // An owner, by the owner id, by the first characters of it, or by the label.
204
+ function memberOf(project, query) {
205
+ const rows = directory.members(project);
206
+ const matches = rows.filter((m) => m.ownerId === query || m.ownerId.startsWith(query) || m.label === query);
207
+ if (matches.length === 0) throw new Error(`no member "${query}" in ${project}. Run: openmsg dir list`);
208
+ if (matches.length > 1) throw new Error(`"${query}" names ${matches.length} members. Use the owner id.`);
209
+ return matches[0];
210
+ }
211
+
212
+ async function cmdSendRemote(target, text, replyTo, args) {
213
+ const [alias, ownerName] = [target.slice(0, target.lastIndexOf("@")), target.slice(target.lastIndexOf("@") + 1)];
214
+ const project = projectId(args);
215
+ const member = memberOf(project, ownerName);
216
+ const me = identity.load();
217
+
218
+ // A reply keeps the conversation of the message that it answers. That
219
+ // message is in the store of messages that arrived from other people.
220
+ const answered = replyTo ? inbound.findByPrefix(replyTo) : null;
221
+ if (replyTo && !answered) throw new Error(`no message ${replyTo} arrived from another person`);
222
+
223
+ // A member with a direct address takes the message over HTTP. A member with
224
+ // no address takes it through the relay of the team.
225
+ const relayUrl = gateway.settings().relay;
226
+ const direct = Boolean(member.endpoint);
227
+ if (!direct && !relayUrl) {
228
+ throw new Error(
229
+ `no way to reach ${member.label}: no endpoint, and no relay. ` +
230
+ "Run: openmsg relay use <url>, or: openmsg dir endpoint <owner> <url>",
231
+ );
232
+ }
233
+ const receipts = [];
234
+ const link = direct ? null : await relaylink.open(relayUrl, { onReceipt: (frame) => receipts.push(frame) });
235
+
236
+ let rows;
237
+ let label = member.label;
238
+ try {
239
+ const answer = direct
240
+ ? await gateway.routingOf(member, project)
241
+ : await gateway.routingOverRelay(link, member, project);
242
+ rows = answer.routing;
243
+ label = answer.label ?? label;
244
+ } catch (e) {
245
+ // The gateway of the other person is offline. The routing data that this
246
+ // machine read before still names the session and the epoch, and a
247
+ // session that moved refuses the message by the epoch.
248
+ const cached = directory.routingOf(project, member.ownerId);
249
+ if (!cached) {
250
+ link?.close();
251
+ throw new Error(`${e.message}. This machine holds no routing data for ${member.label} either.`);
252
+ }
253
+ console.error(`openmsg: ${e.message}`);
254
+ console.error(`openmsg: using the routing data of ${cached.at}`);
255
+ rows = cached.rows;
256
+ }
257
+
258
+ const row = rows.find((r) => r.alias === alias || r.name === alias || r.session === alias);
259
+ if (!row) {
260
+ link?.close();
261
+ const names = rows.map((r) => `${r.alias}@${label}`).join(", ") || "nothing";
262
+ throw new Error(`${member.label} does not publish "${alias}" in this project. Published: ${names}`);
263
+ }
264
+ if (row.live === false) console.error(`openmsg: the session ${row.alias}@${label} does not run now`);
265
+ // The message is sealed for the machine that holds that session, and the
266
+ // routing data of that machine gave this key.
267
+ const sealTo = row.sealTo ?? null;
268
+
269
+ const mine = await self();
270
+ const message = remote.createRemote({
271
+ from: { owner: me.ownerId, vendor: mine.vendor, id: mine.id, name: mine.name ?? mine.id },
272
+ to: { owner: member.ownerId, vendor: row.vendor, id: row.session, name: row.name },
273
+ project: { id: project, label: directory.project(project)?.label ?? null },
274
+ target: { owner: member.ownerId, project, session: row.session, epoch: row.epoch },
275
+ text,
276
+ contextId: answered?.message?.contextId ?? null,
277
+ replyTo: answered?.messageId ?? null,
278
+ hops: answered?.message?.openmsg?.hops ?? [],
279
+ workspace: remote.workspaceOf(),
280
+ });
281
+ const wire = remote.pack(message, { recipient: member, sealTo });
282
+ const how = {
283
+ "adapter-accepted": `reached the agent of ${member.label}`,
284
+ held: `waits for ${member.label} to accept you`,
285
+ queued: `waits in the mailbox of ${member.label}`,
286
+ "relay-holds": `the relay holds it for ${member.label}, who is offline now`,
287
+ };
288
+ let out;
289
+ if (direct) {
290
+ out = await gateway.send(member, wire);
291
+ } else {
292
+ // The sender keeps its copy until a receipt arrives. The relay keeps its
293
+ // own copy at the same time.
294
+ outbox.put({ messageId: message.messageId, to: member.ownerId, project, alias: `${alias}@${label}`, wire, state: "sending" });
295
+ const answer = await link.send(wire);
296
+ if (answer.type !== "stored") {
297
+ outbox.setState(message.messageId, "refused", { reason: answer.reason });
298
+ link.close();
299
+ console.log(`refused by the relay: ${answer.reason} (${message.messageId})`);
300
+ process.exitCode = 1;
301
+ return;
302
+ }
303
+ outbox.setState(message.messageId, "queued");
304
+ // A receipt says what happened at the other end. It can arrive in a
305
+ // moment, or days later, and then the gateway of this owner takes it.
306
+ const receipt = await waitForReceipt(receipts, message.messageId, 3000);
307
+ link.close();
308
+ if (receipt) {
309
+ outbox.setState(message.messageId, receipt.status, { reason: receipt.reason ?? null });
310
+ out = { status: receipt.status, reason: receipt.reason };
311
+ } else {
312
+ out = { status: "relay-holds" };
313
+ }
314
+ }
315
+ console.log(`${how[out.status] ?? `${out.status}${out.reason ? `: ${out.reason}` : ""}`} (${message.messageId})`);
316
+ if (out.status === "refused") process.exitCode = 1;
317
+
318
+ // An answer is the proof that the agent read the message. No hook and no
319
+ // transport gives that proof.
320
+ if (answered && out.status !== "refused") {
321
+ inbound.setStatus(answered.messageId, "replied");
322
+ const told = await gateway.reportState(answered, "replied").catch((e) => ({ sent: false, why: e.message }));
323
+ if (!told.sent) console.error(`openmsg: ${answered.from.label} does not know yet: ${told.why}`);
324
+ }
325
+ }
326
+
327
+ function waitForReceipt(receipts, messageId, ms) {
328
+ return new Promise((resolve) => {
329
+ const started = Date.now();
330
+ const look = () => {
331
+ const found = receipts.find((r) => r.messageId === messageId);
332
+ if (found) return resolve(found);
333
+ if (Date.now() - started > ms) return resolve(null);
334
+ setTimeout(look, 50);
335
+ };
336
+ look();
337
+ });
338
+ }
339
+
340
+ // The keys of one machine, and the record that the owner signs for them.
341
+ async function cmdDevice(args) {
342
+ const [sub, ...rest] = args;
343
+ if (sub === "create") {
344
+ const record = device.create({ label: flag(rest, "label"), force: rest.includes("--force") });
345
+ console.log(`machine ${record.deviceId} (${record.label})`);
346
+ console.log(`keys in ${device.paths().dir}`);
347
+ if (identity.exists() && identity.hasPrivateKeys()) {
348
+ // This machine holds the owner key, so it answers its own request.
349
+ const { record: given } = device.grant(device.readRequest(device.request()), {
350
+ days: Number(flag(rest, "days") ?? device.DEFAULT_DAYS),
351
+ projects: flag(rest, "project") ? [flag(rest, "project")] : "all",
352
+ });
353
+ device.saveDelegation(given);
354
+ console.log(`the owner key signed it until ${given.expiresAt}`);
355
+ console.log("From now on this machine signs with its own key.");
356
+ } else {
357
+ console.log("This machine holds no owner key. Run: openmsg device request");
358
+ }
359
+ return;
360
+ }
361
+ if (sub === "request") {
362
+ console.log(device.request());
363
+ console.log("");
364
+ console.log("Give this text to the machine that holds your owner key, and run there:");
365
+ console.log(" openmsg device grant <token>");
366
+ return;
367
+ }
368
+ if (sub === "grant") {
369
+ const [token] = positional(rest, ["days", "project"]);
370
+ const ask = device.readRequest(token);
371
+ const { record, token: answer } = device.grant(ask, {
372
+ days: Number(flag(rest, "days") ?? device.DEFAULT_DAYS),
373
+ projects: flag(rest, "project") ? [flag(rest, "project")] : "all",
374
+ });
375
+ console.log(`machine ${record.device} (${record.label})`);
376
+ console.log(`projects ${record.projects === "all" ? "all" : record.projects.join(", ")}`);
377
+ console.log(`until ${record.expiresAt}`);
378
+ console.log("");
379
+ console.log(answer);
380
+ console.log("");
381
+ console.log("Give this text back to that machine, and run there: openmsg device accept <token>");
382
+ return;
383
+ }
384
+ if (sub === "accept") {
385
+ const [token] = positional(rest);
386
+ const record = device.saveDelegation(device.readGrant(token));
387
+ console.log(`this machine signs for ${record.owner} until ${record.expiresAt}`);
388
+ return;
389
+ }
390
+ if (sub === "show" || sub === undefined) {
391
+ const record = device.load();
392
+ console.log(`machine ${record.deviceId} (${record.label})`);
393
+ console.log(`created ${record.createdAt}`);
394
+ const held = record.delegation;
395
+ if (!held) {
396
+ console.log("It has no delegation, so the owner key signs each message. Run: openmsg device request");
397
+ return;
398
+ }
399
+ console.log(`owner ${held.owner}`);
400
+ console.log(`projects ${held.projects === "all" ? "all" : held.projects.join(", ")}`);
401
+ console.log(`until ${held.expiresAt}`);
402
+ return;
403
+ }
404
+ if (sub === "revoke") {
405
+ const [which] = positional(rest, ["reason"]);
406
+ if (!which) throw new Error("usage: openmsg device revoke <device-id> [--reason <text>]");
407
+ const me = identity.load();
408
+ const reason = flag(rest, "reason");
409
+ const records = [];
410
+ for (const entry of directory.projects()) {
411
+ if (!directory.member(entry.id, me.ownerId)) continue;
412
+ directory.revokeDevice(entry.id, which, reason, { owner: me.ownerId });
413
+ records.push(dirsync.revokeDeviceRecord(entry.id, which, reason));
414
+ console.log(`revoked ${which} in ${entry.id}`);
415
+ }
416
+ const url = gateway.settings().relay;
417
+ if (!url || records.length === 0) {
418
+ console.log("Run: openmsg dir sync, on a machine with a relay, so the team learns it.");
419
+ return;
420
+ }
421
+ return relaylink.open(url).then(async (link) => {
422
+ for (const record of records) await link.publishRecord(record);
423
+ link.close();
424
+ console.log(`the team learns it through ${url}`);
425
+ });
426
+ }
427
+ throw new Error("usage: openmsg device create | request | grant <token> | accept <token> | revoke <id> | show");
428
+ }
429
+
430
+ async function cmdRelay(args) {
431
+ const [sub, ...rest] = args;
432
+ if (sub === "start") {
433
+ const host = flag(rest, "host") ?? "127.0.0.1";
434
+ const port = Number(flag(rest, "port") ?? 7800);
435
+ const running = await relay.serve({
436
+ port,
437
+ host,
438
+ cert: flag(rest, "cert"),
439
+ key: flag(rest, "key"),
440
+ insecure: rest.includes("--insecure"),
441
+ log: (line) => console.log(`${new Date().toISOString()} ${line}`),
442
+ });
443
+ console.log(`relay listens on ${running.url}, store in ${relay.home()}`);
444
+ console.log("It carries sealed bytes. It cannot read a message.");
445
+ console.log("It learns who writes to whom, when, and in which project.");
446
+ const stop = () => running.close().then(() => process.exit(0));
447
+ process.on("SIGINT", stop);
448
+ process.on("SIGTERM", stop);
449
+ return;
450
+ }
451
+ if (sub === "use") {
452
+ const [url] = positional(rest, ["ca"]);
453
+ if (!url) throw new Error("usage: openmsg relay use <url> [--ca <file>] [--insecure]");
454
+ const ca = flag(rest, "ca");
455
+ const insecure = rest.includes("--insecure");
456
+ gateway.saveSettings({ relay: url, relayCa: ca ?? null, relayInsecure: insecure });
457
+ console.log(`this owner sends through ${url}`);
458
+ if (ca) console.log(`and it trusts the certificate in ${ca}`);
459
+ if (new URL(url).protocol === "ws:" && !relay.isLoopback(new URL(url).hostname)) {
460
+ console.log(
461
+ insecure
462
+ ? "WARNING: no TLS. The messages stay sealed, and the addresses travel in the open."
463
+ : "That address has no TLS. Add --insecure if you accept that, or use a wss:// address.",
464
+ );
465
+ }
466
+ return;
467
+ }
468
+ if (sub === undefined || sub === "show") {
469
+ const url = gateway.settings().relay;
470
+ console.log(url ? `relay ${url}` : "no relay. Run: openmsg relay use <url>");
471
+ return;
472
+ }
473
+ throw new Error("usage: openmsg relay start [--cert <f> --key <f>] | relay use <url> [--ca <f>] | relay show");
474
+ }
475
+
476
+ function cmdOutbox(args) {
477
+ const rows = args.includes("--all") ? outbox.list() : outbox.waiting();
478
+ if (rows.length === 0) {
479
+ console.log(args.includes("--all") ? "the outbox is empty" : "no message waits for a receipt");
480
+ return;
481
+ }
482
+ for (const r of rows) {
483
+ console.log(`${r.messageId.slice(0, 8)} ${String(r.state).padEnd(16)} to ${r.alias ?? r.to} ${r.at}`);
484
+ }
485
+ }
486
+
487
+ async function cmdGateway(args) {
488
+ const [sub = "start", ...rest] = args;
489
+ if (sub !== "start") throw new Error("usage: openmsg gateway start [--port <n>] [--host <h>] [--relay <url>]");
490
+ const me = identity.load();
491
+ const host = flag(rest, "host") ?? "127.0.0.1";
492
+ const port = Number(flag(rest, "port") ?? 7801);
493
+ const stamp = (line) => console.log(`${new Date().toISOString()} ${line}`);
494
+ const running = await gateway.serve({ port, host, log: stamp });
495
+ gateway.saveSettings({ host, port: running.port, endpoint: running.url });
496
+ const relayUrl = flag(rest, "relay") ?? gateway.settings().relay ?? null;
497
+ if (relayUrl) {
498
+ gateway.saveSettings({ relay: relayUrl });
499
+ await gateway.joinRelay(relayUrl, { log: stamp });
500
+ }
501
+ console.log(`gateway of ${me.label} (${me.ownerId}) listens on ${running.url}`);
502
+ const rows = published.list();
503
+ if (rows.length === 0) console.log("nothing is published. Run: openmsg publish <agent>");
504
+ for (const r of rows) console.log(`published ${r.alias} · project ${r.project} · epoch ${r.epoch}`);
505
+ const stop = () => {
506
+ console.log("gateway stopped");
507
+ running.close().then(() => process.exit(0));
508
+ };
509
+ process.on("SIGINT", stop);
510
+ process.on("SIGTERM", stop);
511
+ }
512
+
513
+ async function cmdPublish(args) {
514
+ const [query] = positional(args, ["project"]);
515
+ if (!query) {
516
+ const rows = published.list();
517
+ if (rows.length === 0) console.log("nothing is published");
518
+ for (const r of rows) console.log(`${r.alias.padEnd(28)} ${r.project} epoch ${r.epoch} session ${r.session}`);
519
+ return;
520
+ }
521
+ const agent = await findAgent(query);
522
+ const row = published.publish(projectId(args), agent);
523
+ console.log(`published ${row.alias} in ${row.project ?? projectId(args)}, epoch ${row.epoch}`);
524
+ console.log("Only this session, and only this project, can be reached. Nothing else is published.");
525
+ }
526
+
527
+ function cmdUnpublish(args) {
528
+ const project = projectId(args);
529
+ const [alias] = positional(args, ["project"]);
530
+ const gone = published.unpublish(project, alias);
531
+ console.log(gone ? `${alias} is not published any more` : `${alias} was not published in ${project}`);
532
+ }
533
+
534
+ function cmdPermit(args) {
535
+ const [who, value] = positional(args, ["project"]);
536
+ if (!who || who === "list") {
537
+ const rows = permissions.list();
538
+ if (rows.length === 0) console.log(`no standing permission. The default is "${permissions.DEFAULT}".`);
539
+ for (const r of rows) console.log(`${r.owner} ${r.value.padEnd(7)} ${r.project} ${r.at}`);
540
+ return;
541
+ }
542
+ const project = projectId(args);
543
+ const member = memberOf(project, who);
544
+ const record = permissions.set(project, member.ownerId, value);
545
+ console.log(`${member.label} (${member.ownerId}) is now "${record.value}" in ${project}`);
546
+ }
547
+
548
+ function cmdHeld(args) {
549
+ const [id] = positional(args);
550
+ if (args.includes("--all") && !id) {
551
+ const all = inbound.list().sort((a, b) => (a.at < b.at ? -1 : 1));
552
+ if (all.length === 0) console.log("no message from another person");
553
+ for (const r of all) {
554
+ const why = r.reason ? ` · ${r.reason}` : "";
555
+ console.log(`${r.messageId.slice(0, 8)} ${String(r.status).padEnd(18)} from ${r.from?.label ?? "unknown"}${why} ${r.at}`);
556
+ }
557
+ // A state that holds a doubt says so here. No protocol removes that doubt.
558
+ for (const state of [...new Set(all.map((r) => r.status))]) {
559
+ if (inbound.EXPLAIN[state]) console.log(`${state}: ${inbound.EXPLAIN[state]}`);
560
+ }
561
+ return;
562
+ }
563
+ const rows = inbound.list({ status: "held" });
564
+ if (id) {
565
+ const row = inbound.findByPrefix(id);
566
+ if (!row) throw new Error(`no message ${id}`);
567
+ console.log(`from ${row.from.label} (${row.from.owner})`);
568
+ console.log(`project ${row.project}`);
569
+ console.log(`arrived ${row.at}`);
570
+ console.log(`state ${row.status} — ${inbound.EXPLAIN[row.status] ?? "unknown"}`);
571
+ if (!args.includes("--text")) {
572
+ console.log("Add --text to read it. The text is for you, and not for the agent.");
573
+ return;
574
+ }
575
+ console.log("--- the text of the message, as it arrived ---");
576
+ console.log(row.message.parts.map((p) => p.text).join("\n"));
577
+ console.log("--- end of the text ---");
578
+ console.log("This text is a message from another person. Reading it approves nothing.");
579
+ console.log(`To give it to the agent: openmsg accept ${row.messageId.slice(0, 8)}`);
580
+ return;
581
+ }
582
+ if (rows.length === 0) {
583
+ console.log("no message waits");
584
+ return;
585
+ }
586
+ for (const r of rows) {
587
+ console.log(`${r.messageId.slice(0, 8)} from ${r.from.label} (${r.from.owner}) · ${r.project} · ${r.at}`);
588
+ }
589
+ console.log(`Read one: openmsg held <id> --text. Give one to the agent: openmsg accept <id>.`);
590
+ }
591
+
592
+ // The agent says that it read the message. Only this event gives the state
593
+ // "agent-acknowledged". A write to a socket never proves that a model read.
594
+ async function cmdAck(args) {
595
+ const [id] = positional(args);
596
+ const row = inbound.findByPrefix(id ?? "");
597
+ if (!row) throw new Error(`no message ${id}. Run: openmsg held --all`);
598
+ if (!["adapter-accepted", "agent-acknowledged", "replied"].includes(row.status)) {
599
+ throw new Error(`message ${id} is "${row.status}", and an acknowledgement belongs to a message that reached the agent`);
600
+ }
601
+ if (row.status === "adapter-accepted") inbound.setStatus(row.messageId, "agent-acknowledged");
602
+ const told = await gateway.reportState(row, "agent-acknowledged").catch((e) => ({ sent: false, why: e.message }));
603
+ console.log(
604
+ `acknowledged ${row.messageId}` +
605
+ (told.sent ? `, and ${row.from.label} knows over ${told.how}` : `. ${row.from.label} does not know yet: ${told.why}`),
606
+ );
607
+ }
608
+
609
+ function cmdLimits() {
610
+ const values = limits.values();
611
+ const rows = inbound.list();
612
+ console.log(`${values.senderPerWindow} messages from one sender in ${Math.round(values.senderWindowMs / 60_000)} minutes`);
613
+ console.log(`${values.turnsPerSession} turns from remote messages in one session in ${Math.round(values.turnWindowMs / 60_000)} minutes`);
614
+ console.log(`${values.heldMax} messages that wait for the owner (${rows.filter((r) => r.status === "held").length} now)`);
615
+ console.log(`Change a value in ${identity.home()}/limits.json`);
616
+ }
617
+
618
+ async function cmdAccept(args) {
619
+ const [id] = positional(args);
620
+ const row = inbound.findByPrefix(id ?? "");
621
+ if (!row) throw new Error(`no message ${id}. Run: openmsg held`);
622
+ if (row.status !== "held") throw new Error(`message ${id} is "${row.status}", and only a held message is accepted`);
623
+ if (args.includes("--always")) {
624
+ permissions.set(row.project, row.from.owner, "accept");
625
+ console.log(`${row.from.label} (${row.from.owner}) is now "accept" in ${row.project}`);
626
+ }
627
+ const out = await gateway.release(row, { deliver: deliverLocal, log: (line) => console.log(line) });
628
+ console.log(`${out.status}${out.reason ? `: ${out.detail ?? out.reason}` : ""} (${row.messageId})`);
629
+ }
630
+
631
+
632
+
633
+ // A flag with a value, such as --label alice. It gives null when the flag is
634
+ // absent, and it refuses a flag with no value.
635
+ function flag(args, name) {
636
+ const i = args.indexOf(`--${name}`);
637
+ if (i === -1) return null;
638
+ const value = args[i + 1];
639
+ if (value === undefined || value.startsWith("--")) throw new Error(`--${name} needs a value`);
640
+ return value;
641
+ }
642
+
643
+ // The arguments that are not a flag and not the value of a flag. A token that
644
+ // starts with a dash is not possible here, and the reader stays simple.
645
+ function positional(args, withValue = []) {
646
+ const out = [];
647
+ for (let i = 0; i < args.length; i += 1) {
648
+ const a = args[i];
649
+ if (!a.startsWith("--")) {
650
+ out.push(a);
651
+ continue;
652
+ }
653
+ if (withValue.includes(a.slice(2))) i += 1;
654
+ }
655
+ return out;
656
+ }
657
+
658
+ function cmdId(args) {
659
+ const [sub, ...rest] = args;
660
+ if (sub === "create") {
661
+ const record = identity.create({ label: flag(rest, "label"), force: rest.includes("--force") });
662
+ console.log(`identity ${record.ownerId} (${record.label})`);
663
+ console.log(`fingerprint ${identity.fingerprint(record)}`);
664
+ console.log(`keys in ${identity.paths().dir}`);
665
+ console.log("Read the fingerprint to the other person, by voice, before the first message.");
666
+ return;
667
+ }
668
+ if (sub === "show" || sub === undefined) {
669
+ const record = identity.load();
670
+ if (rest.includes("--json")) {
671
+ console.log(JSON.stringify({ ...record, fingerprint: identity.fingerprint(record) }, null, 2));
672
+ return;
673
+ }
674
+ console.log(`owner ${record.ownerId}`);
675
+ console.log(`label ${record.label}`);
676
+ console.log(`fingerprint ${identity.fingerprint(record)}`);
677
+ console.log(`created ${record.createdAt}`);
678
+ return;
679
+ }
680
+ throw new Error("usage: openmsg id create | openmsg id show");
681
+ }
682
+
683
+ function cmdInvite(args) {
684
+ const [sub, ...rest] = args;
685
+ if (sub === "create") {
686
+ const out = invite.create({
687
+ label: flag(rest, "project"),
688
+ projectId: flag(rest, "project-id"),
689
+ hours: Number(flag(rest, "hours") ?? invite.DEFAULT_HOURS),
690
+ endpoint: flag(rest, "endpoint") ?? gateway.settings().endpoint ?? null,
691
+ });
692
+ console.log(`project ${out.project.id} (${out.project.label})`);
693
+ console.log(`fingerprint ${out.fingerprint}`);
694
+ console.log(`expires ${out.body.expiresAt}`);
695
+ console.log("");
696
+ console.log(out.token);
697
+ console.log("");
698
+ console.log("Send the token by any channel. Read the fingerprint by voice, and never in the");
699
+ console.log("same channel, because a channel that carries both carries a false invitation too.");
700
+ return;
701
+ }
702
+ if (sub === "show") {
703
+ const body = invite.open(positional(rest)[0]);
704
+ console.log(`type ${body.type}`);
705
+ console.log(`owner ${body.identity.ownerId} (${body.identity.label})`);
706
+ console.log(`fingerprint ${identity.fingerprint(body.identity)}`);
707
+ console.log(`project ${body.project.id} (${body.project.label})`);
708
+ console.log(`expires ${body.expiresAt}`);
709
+ console.log("The signature matches the text. It does not say who made the key.");
710
+ return;
711
+ }
712
+ if (sub === "accept") {
713
+ const [token] = positional(rest, ["fingerprint", "endpoint"]);
714
+ const out = invite.accept(token, flag(rest, "fingerprint"), {
715
+ endpoint: flag(rest, "endpoint") ?? gateway.settings().endpoint ?? null,
716
+ });
717
+ console.log(`${out.peer.ownerId} (${out.peer.label}) is now a member of ${out.project.id}`);
718
+ if (out.reply) {
719
+ console.log("");
720
+ console.log(`Send this answer back. Your fingerprint is ${out.reply.fingerprint}.`);
721
+ console.log("");
722
+ console.log(out.reply.token);
723
+ }
724
+ return;
725
+ }
726
+ throw new Error('usage: openmsg invite create | invite show <token> | invite accept <token> --fingerprint "<value>"');
727
+ }
728
+
729
+ async function cmdDir(args) {
730
+ const [sub, ...rest] = args;
731
+ if (sub === "list" || sub === undefined) {
732
+ if (rest.includes("--json")) {
733
+ console.log(JSON.stringify(directory.read(), null, 2));
734
+ return;
735
+ }
736
+ const me = identity.exists() ? identity.load().ownerId : null;
737
+ const all = directory.projects();
738
+ if (all.length === 0) {
739
+ console.log("no project in the directory. Run: openmsg invite create");
740
+ return;
741
+ }
742
+ for (const p of all) {
743
+ console.log(`${p.id} ${p.label}`);
744
+ for (const m of directory.members(p.id)) {
745
+ const mine = m.ownerId === me ? " (you)" : "";
746
+ console.log(` ${m.ownerId} ${m.label.padEnd(12)} ${m.fingerprint}${mine}`);
747
+ }
748
+ for (const r of directory.revoked(p.id)) {
749
+ console.log(` revoked ${r.ownerId} at ${r.at}${r.reason ? ` · ${r.reason}` : ""}`);
750
+ }
751
+ for (const r of directory.revokedDevices(p.id)) {
752
+ console.log(` revoked machine ${r.device} at ${r.at}${r.reason ? ` · ${r.reason}` : ""}`);
753
+ }
754
+ }
755
+ return;
756
+ }
757
+ if (sub === "endpoint") {
758
+ const [who, url] = positional(rest, ["project"]);
759
+ const project = projectId(rest);
760
+ const member = memberOf(project, who);
761
+ const record = directory.setEndpoint(project, member.ownerId, url);
762
+ console.log(`${record.label} (${record.ownerId}) answers at ${record.endpoint}`);
763
+ return;
764
+ }
765
+ if (sub === "sync") {
766
+ const url = gateway.settings().relay;
767
+ if (!url) throw new Error("no relay. Run: openmsg relay use <url>");
768
+ return relaylink.open(url).then(async (link) => {
769
+ const named = flag(rest, "project");
770
+ const rows = await gateway.syncDirectory(link, {
771
+ log: (line) => console.log(line),
772
+ projects: named ? [named] : [],
773
+ });
774
+ link.close();
775
+ const total = rows.reduce((n, r) => n + r.added.length + r.updated.length + r.revoked.length, 0);
776
+ console.log(`${rows.length} projects, ${total} changes, ${directory.pending().length} owners wait for you`);
777
+ });
778
+ }
779
+ if (sub === "pending") {
780
+ const rows = directory.pending(flag(rest, "project") ?? null);
781
+ if (rows.length === 0) {
782
+ console.log("nobody waits");
783
+ return;
784
+ }
785
+ for (const r of rows) {
786
+ console.log(`${r.ownerId} ${String(r.label).padEnd(12)} ${r.fingerprint} ${r.project}`);
787
+ }
788
+ console.log("Compare a fingerprint with that person, and then:");
789
+ console.log(' openmsg dir accept <owner> --fingerprint "<value>"');
790
+ return;
791
+ }
792
+ if (sub === "accept") {
793
+ const [who] = positional(rest, ["fingerprint", "project"]);
794
+ const project = projectId(rest);
795
+ const record = dirsync.acceptPending(project, who, flag(rest, "fingerprint"));
796
+ console.log(`${record.label} (${record.ownerId}) is now a member of ${project}`);
797
+ return;
798
+ }
799
+ if (sub === "revoke-device") {
800
+ const [projectId, deviceId] = positional(rest, ["reason"]);
801
+ const record = directory.revokeDevice(projectId, deviceId, flag(rest, "reason"));
802
+ console.log(`revoked the machine ${record.device} in ${projectId} at ${record.at}`);
803
+ console.log("The identity of that person holds. Only that machine stops.");
804
+ return;
805
+ }
806
+ if (sub === "revoke") {
807
+ const [projectId, ownerId] = positional(rest, ["reason"]);
808
+ const record = directory.revoke(projectId, ownerId, flag(rest, "reason"));
809
+ console.log(`revoked ${record.ownerId} in ${projectId} at ${record.at}`);
810
+ return;
811
+ }
812
+ throw new Error("usage: openmsg dir list | dir endpoint <owner> <url> | dir revoke <project-id> <owner-id>");
813
+ }
814
+
148
815
  // Agents read the instruction block. It says "openmsg" when the command is on
149
816
  // the PATH of the user, and the full path to the file when it is not.
150
817
  function commandName() {
@@ -164,10 +831,8 @@ const [cmd, ...args] = process.argv.slice(2);
164
831
  try {
165
832
  if (cmd === "list") await cmdList();
166
833
  else if (cmd === "send") {
167
- const flag = args.indexOf("--reply-to");
168
- const replyTo = flag === -1 ? null : args[flag + 1];
169
- const rest = flag === -1 ? args : [...args.slice(0, flag), ...args.slice(flag + 2)];
170
- await cmdSend(rest[0], rest.slice(1).join(" "), replyTo);
834
+ const rest = positional(args, ["reply-to", "project"]);
835
+ await cmdSend(rest[0], rest.slice(1).join(" "), flag(args, "reply-to"), args);
171
836
  }
172
837
  else if (cmd === "inbox") await cmdInbox(args);
173
838
  else if (cmd === "install") {
@@ -191,6 +856,20 @@ try {
191
856
  const out = await runHook(args[0] ?? "");
192
857
  console.log(JSON.stringify(out));
193
858
  }
859
+ else if (cmd === "gateway") await cmdGateway(args);
860
+ else if (cmd === "device") await cmdDevice(args);
861
+ else if (cmd === "relay") await cmdRelay(args);
862
+ else if (cmd === "outbox") cmdOutbox(args);
863
+ else if (cmd === "publish") await cmdPublish(args);
864
+ else if (cmd === "unpublish") cmdUnpublish(args);
865
+ else if (cmd === "permit") cmdPermit(args);
866
+ else if (cmd === "held") cmdHeld(args);
867
+ else if (cmd === "accept") await cmdAccept(args);
868
+ else if (cmd === "ack") await cmdAck(args);
869
+ else if (cmd === "limits") cmdLimits();
870
+ else if (cmd === "id") cmdId(args);
871
+ else if (cmd === "invite") cmdInvite(args);
872
+ else if (cmd === "dir") await cmdDir(args);
194
873
  else if (cmd === "whoami") console.log(address(await self()));
195
874
  else console.log(USAGE);
196
875
  } catch (e) {