openmsg 0.7.0 → 0.8.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
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // openmsg: send a message from one AI coding agent to another.
3
3
  import { allAgents, findAgent, self, claudeAgents } from "./registry.mjs";
4
- import { createMessage, address, textOf, MAX_HOPS } from "./envelope.mjs";
4
+ import { createMessage, address, textOf, MAX_HOPS, layoutOfAnswer, layoutOfSpawnPrompt, compose } from "./envelope.mjs";
5
+ import * as asks from "./asks.mjs";
5
6
  import * as mailbox from "./mailbox.mjs";
6
7
  import * as projectbox from "./projectbox.mjs";
7
8
  import { runHook } from "./hook.mjs";
@@ -26,6 +27,9 @@ import * as notes from "./notes.mjs";
26
27
  import * as webhooks from "./webhooks.mjs";
27
28
  import * as mcpagents from "./mcpagents.mjs";
28
29
  import * as mcp from "./mcp.mjs";
30
+ import { createOAuth } from "./oauth.mjs";
31
+ import * as spawn from "./spawn.mjs";
32
+ import * as voiceowners from "./voiceowners.mjs";
29
33
  import { fileURLToPath } from "node:url";
30
34
  import fs from "node:fs";
31
35
  import path from "node:path";
@@ -53,10 +57,30 @@ const USAGE = `openmsg — messages between AI coding agents
53
57
  [--allow <address>] an address that it can write to. "*" stands for any text
54
58
  [--per-minute <n>] how many messages it sends in one minute
55
59
  openmsg mcp remove <name> take that agent away
60
+ openmsg mcp trust <name> a request from that chat counts as a request of yours
61
+ openmsg mcp untrust <name> stop that
62
+ openmsg ask "<question>" ask the owner, when the owner is not at this machine
63
+ [--image <file.png|jpg>] a screenshot to show, up to 4. The question becomes a review
64
+ [--option "<text>"] an option to choose, 2 to 6. The question becomes a review
65
+ openmsg asks [--json] the questions that wait for the owner
66
+ openmsg asks --history the answers of the last 30 days
67
+ openmsg answer <id> yes|no the answer of the owner. The session that asked gets it as a message
68
+ openmsg answer <id> [--choice <option or number>] [--comment "<text>"] the answer to a review
56
69
  openmsg mcp list the agents that read through MCP
57
70
  openmsg mcp serve --as <name> the MCP server of that agent, on the standard input and output
58
71
  [--http --port <n>] the same server over HTTP on the loopback address, behind a token
59
72
  [--token-file <file>] the file of that token. openmsg makes it when it is not there
73
+ [--oauth --public-url <url>] OAuth too, for a product that takes no fixed token, such as Gemini
74
+ openmsg spawn <dir> open a Claude Code session there, in tmux, and give its address
75
+ [--account <name>] the account: "default" is ~/.claude, "work" is ~/.claude-work
76
+ [--prompt "<text>"] the first message of the session
77
+ [--trust-folder] say yes to the folder question of Claude Code. Ask your user first
78
+ [--no-window] open no window of Terminal.app
79
+ openmsg spawn --list the sessions that openmsg opened, and the accounts
80
+ openmsg close <agent> stop a session. Its transcript stays, for claude --resume
81
+ openmsg close --idle [<hours>] stop each session that openmsg opened and that had no turn (12 hours)
82
+ openmsg operator start open the session that a chat of yours talks to, in ~/.openmsg/operator
83
+ [--account <name>]
60
84
  openmsg hook <vendor> run inside a hook of claude, cursor, or gemini
61
85
  openmsg install let every agent on this machine answer messages
62
86
  openmsg install --hooks add the hooks for claude, cursor, and gemini
@@ -80,6 +104,8 @@ For the agents of another person, on another machine:
80
104
  openmsg unpublish <alias> take a session back
81
105
  openmsg unpublish --all go back to the sessions that you named
82
106
  openmsg permit <owner> <accept|hold|refuse>
107
+ openmsg trust <owner> that identity is yours, such as a bot: its request counts as yours
108
+ openmsg untrust <owner> stop that
83
109
  openmsg held [<id>] [--text] the messages that wait for you
84
110
  openmsg held --all every message from another person, and its state
85
111
  openmsg accept <id> [--always] give a held message to the agent
@@ -130,12 +156,18 @@ async function cmdList(args = []) {
130
156
  ]);
131
157
  const agents = args.includes("--all") ? all : all.filter((a) => !a.background);
132
158
  const hidden = all.length - agents.length;
133
- if (agents.length === 0) {
134
- console.log(hidden ? `no running agents found. ${hidden} background sessions: openmsg list --all` : "no running agents found");
159
+ // The agents of other people, from the last routing data on this machine.
160
+ // An agent with a shell finds them here, and needs no MCP connector.
161
+ const others = directory.remoteAgents();
162
+ if (args.includes("--json")) {
163
+ const local = agents.map(({ transport, ...a }) => ({ ...a, you: sameSession(a, me) }));
164
+ const far = others.map((r) => ({ ...r, remote: true, you: false }));
165
+ console.log(JSON.stringify([...local, ...far], null, 1));
135
166
  return;
136
167
  }
137
- if (args.includes("--json")) {
138
- console.log(JSON.stringify(agents.map(({ transport, ...a }) => ({ ...a, you: sameSession(a, me) })), null, 1));
168
+ if (agents.length === 0) {
169
+ console.log(hidden ? `no running agents found. ${hidden} background sessions: openmsg list --all` : "no running agents found");
170
+ printRemote(others);
139
171
  return;
140
172
  }
141
173
  const width = Math.max(...agents.map((a) => address(a).length));
@@ -151,6 +183,18 @@ async function cmdList(args = []) {
151
183
  console.log(` ${[about, tilde(a.cwd)].filter(Boolean).join(" · ")}`);
152
184
  }
153
185
  if (hidden) console.log(`\n${hidden} background sessions not shown. See them: openmsg list --all`);
186
+ printRemote(others);
187
+ }
188
+
189
+ // The routing data can be old: the other gateway answered at that time.
190
+ function printRemote(others) {
191
+ if (others.length === 0) return;
192
+ console.log("\nagents of other people, from the last answer of their gateway:");
193
+ const width = Math.max(...others.map((r) => r.address.length));
194
+ for (const r of others) console.log(`${r.address.padEnd(width)} ${r.status.padEnd(9)} as of ${ago(Date.parse(r.at))} ago`);
195
+ if (others.some((r) => r.status === "stale")) {
196
+ console.log("stale: the answer is older than 10 minutes, and that gateway can be offline now. A send tells.");
197
+ }
154
198
  }
155
199
 
156
200
  async function cmdNote(args) {
@@ -226,6 +270,9 @@ async function cmdSend(target, text, replyTo = null, args = []) {
226
270
  }
227
271
 
228
272
  const result = await deliverLocal(to, message);
273
+ if (mcpagents.speaksForOwner(from)) {
274
+ mcpagents.recordVoice({ from: address(from), to: address(to), messageId: message.messageId, text });
275
+ }
229
276
 
230
277
  // "delivered" means an adapter pushed the message into the live session.
231
278
  // "queued" means it waits in the mailbox for an agent that reads it at the
@@ -376,9 +423,9 @@ async function cmdMcp(args) {
376
423
  if (args[i] === "--allow") {
377
424
  if (args[i + 1] === undefined) throw new Error('--allow needs an address, such as "claude:*"');
378
425
  allow.push(args[++i]);
379
- } else if (["--per-minute", "--as", "--port", "--token-file", "--path"].includes(args[i])) {
426
+ } else if (["--per-minute", "--as", "--port", "--token-file", "--path", "--public-url"].includes(args[i])) {
380
427
  i += 1;
381
- } else if (args[i] !== "--http") words.push(args[i]);
428
+ } else if (args[i] !== "--http" && args[i] !== "--oauth") words.push(args[i]);
382
429
  }
383
430
  const [sub, name] = words;
384
431
  if (sub === "serve") {
@@ -397,7 +444,17 @@ async function cmdMcp(args) {
397
444
  }
398
445
  const token = fs.readFileSync(file, "utf8").trim();
399
446
  const stamp = (line) => console.log(`${new Date().toISOString()} ${line}`);
400
- const running = await mcp.serveHttp({ name: as, token, port: Number(flag(args, "port") ?? 7812), route: flag(args, "path") ?? "/mcp", log: stamp });
447
+ const route = flag(args, "path") ?? "/mcp";
448
+ // OAuth, for a product that takes no fixed token. The owner approves each
449
+ // connection with the secret of the token file.
450
+ let oauth = null;
451
+ if (args.includes("--oauth")) {
452
+ const publicUrl = flag(args, "public-url");
453
+ if (!publicUrl) throw new Error("--oauth needs --public-url <the https address of the route, as the network sees it>");
454
+ oauth = createOAuth({ name: as, ownerSecret: token, publicUrl, route, file: path.join(identity.home(), `mcp-${as}.oauth.json`), log: stamp });
455
+ }
456
+ const running = await mcp.serveHttp({ name: as, token, port: Number(flag(args, "port") ?? 7812), route, log: stamp, oauth });
457
+ if (oauth) stamp(`OAuth: the address for the product is ${flag(args, "public-url")}. The approval page asks for the secret in ${file}`);
401
458
  stamp(`mcp:${as} listens on ${running.url}, and each request needs the token in ${file}`);
402
459
  stamp('The header of a request: "Authorization: Bearer <token>". A proxy in front gives the address to the network, with TLS.');
403
460
  const stop = () => running.close().then(() => process.exit(0));
@@ -419,6 +476,20 @@ async function cmdMcp(args) {
419
476
  console.log(`The command of its connector: openmsg mcp serve --as ${row.name}`);
420
477
  return;
421
478
  }
479
+ if (sub === "trust" || sub === "untrust") {
480
+ if (!name) throw new Error(`usage: openmsg mcp ${sub} <name>`);
481
+ mcpagents.setVoice(name, sub === "trust");
482
+ if (sub === "untrust") {
483
+ console.log(`A message from mcp:${name} is a message from another agent again. It approves no action.`);
484
+ return;
485
+ }
486
+ console.log(`A request from mcp:${name} now counts as a request of yours, for each agent on this machine.`);
487
+ console.log("It does not approve an action that deletes data, that cannot be undone, or that changes a permission.");
488
+ console.log("The model behind that chat reads text of other people, and such text can try to make it send.");
489
+ console.log("Keep the question that the chat product asks before each send. That question is the one bound.");
490
+ console.log(`Each such message is in ${path.join(identity.home(), "voice.jsonl")}. To stop: openmsg mcp untrust ${name}`);
491
+ return;
492
+ }
422
493
  if (sub === "remove") {
423
494
  if (!name) throw new Error("usage: openmsg mcp remove <name>");
424
495
  console.log(mcpagents.remove(name) ? `mcp:${name} is gone` : `no agent mcp:${name}`);
@@ -429,11 +500,249 @@ async function cmdMcp(args) {
429
500
  if (rows.length === 0) console.log("no agent reads through MCP. Run: openmsg mcp add <name>");
430
501
  for (const a of rows) {
431
502
  const row = mcpagents.get(a.name);
432
- console.log(`${address(a)} writes to: ${row.allow.join(", ") || "nobody"} · ${row.perMinute} in one minute`);
503
+ const voice = row.voice ? " · speaks for the owner" : "";
504
+ console.log(`${address(a)} writes to: ${row.allow.join(", ") || "nobody"} · ${row.perMinute} in one minute${voice}`);
433
505
  }
434
506
  return;
435
507
  }
436
- throw new Error("usage: openmsg mcp add <name> | mcp remove <name> | mcp list | mcp serve --as <name>");
508
+ throw new Error("usage: openmsg mcp add <name> | mcp remove <name> | mcp trust <name> | mcp untrust <name> | mcp list | mcp serve --as <name>");
509
+ }
510
+
511
+ // A session that openmsg opens for a chat of the owner. The owner is away,
512
+ // and no session runs in that project yet.
513
+ async function cmdSpawn(args) {
514
+ if (args.includes("--list")) {
515
+ const rows = spawn.running();
516
+ if (rows.length === 0) console.log("openmsg opened no session that runs now");
517
+ for (const r of rows) console.log(`${(r.address ?? "(no address yet)").padEnd(28)} ${r.tmux} ${r.account} ${r.dir} since ${r.startedAt}`);
518
+ console.log(`accounts: ${spawn.accounts().map((a) => `${a.name} (${a.dir})`).join(", ")}`);
519
+ console.log(`at most ${process.env.OPENMSG_SPAWN_MAX ?? spawn.DEFAULT_MAX} at one time. To look at one: tmux attach -t <tmux name>`);
520
+ return;
521
+ }
522
+ const [dir] = positional(args, ["account", "prompt"]);
523
+ if (!dir) throw new Error('usage: openmsg spawn <dir> [--account <name>] [--prompt "<text>"] [--trust-folder] [--no-window]');
524
+ // A session that waits too long for a turn closes first, so it takes no place.
525
+ for (const { row, agent } of spawn.idle()) {
526
+ const done = await spawn.close({ agent, tmuxName: row.tmux });
527
+ if (done.stopped) console.log(`closed ${row.address ?? row.tmux}: no turn for ${spawn.DEFAULT_IDLE_HOURS} hours`);
528
+ }
529
+ // A session that runs this command writes the first message for the owner.
530
+ // The new session must see that, and not a message that its user typed.
531
+ let prompt = flag(args, "prompt");
532
+ if (prompt && AGENT_ENV.some((name) => process.env[name])) {
533
+ const from = await self();
534
+ if (from && !from.unresolved) prompt = compose(layoutOfSpawnPrompt(address(from), prompt));
535
+ }
536
+ const out = await spawn.open({
537
+ dir,
538
+ account: flag(args, "account"),
539
+ prompt,
540
+ trustFolder: args.includes("--trust-folder"),
541
+ view: !args.includes("--no-window"),
542
+ });
543
+ if (!out.agent) {
544
+ const why = out.alive
545
+ ? "it runs, but discovery does not find it yet. Look again with: openmsg list"
546
+ : "it stopped before it started. Look at: tmux ls";
547
+ console.log(`opened ${out.tmux} in ${out.dir}, and ${why}`);
548
+ return;
549
+ }
550
+ console.log(`opened claude:${out.agent.name} in ${out.dir}, with the account ${out.account}`);
551
+ console.log(`To write to it: openmsg send "claude:${out.agent.name}" "<text>"`);
552
+ console.log(`To close it: openmsg close "claude:${out.agent.name}"`);
553
+ console.log(`It runs in tmux as ${out.tmux}${out.viewed ? ", and a window of Terminal.app shows it" : ""}. To look at it: tmux attach -t ${out.tmux}`);
554
+ }
555
+
556
+ async function cmdClose(args) {
557
+ if (args.includes("--idle")) {
558
+ const [hours] = positional(args.filter((a) => a !== "--idle"));
559
+ const rows = spawn.idle({ hours: hours === undefined ? spawn.DEFAULT_IDLE_HOURS : Number(hours) });
560
+ if (rows.length === 0) console.log("no session that openmsg opened is idle that long");
561
+ for (const { row, agent } of rows) {
562
+ const done = await spawn.close({ agent, tmuxName: row.tmux });
563
+ console.log(`${done.stopped ? "closed" : "could not close"} ${row.address ?? row.tmux}`);
564
+ }
565
+ return;
566
+ }
567
+ const [target] = positional(args);
568
+ if (!target) throw new Error("usage: openmsg close <agent> | close --idle [<hours>]");
569
+ let agent = null;
570
+ let tmuxName = null;
571
+ if (/^om-/.test(target)) tmuxName = target;
572
+ else {
573
+ agent = await findAgent(target);
574
+ if (sameSession(agent, await self())) {
575
+ throw new Error(`${address(agent)} is this session. A session does not close itself with openmsg`);
576
+ }
577
+ // A program, a chat, or a webhook agent has no process on this machine.
578
+ if (!agent.pid || !["claude", "codex", "opencode", "cursor", "gemini"].includes(agent.vendor)) {
579
+ throw new Error(`${address(agent)} has no process on this machine, so there is nothing to close`);
580
+ }
581
+ if (agent.vendor !== "claude") {
582
+ throw new Error(`openmsg closes a Claude Code session only. ${address(agent)} is ${agent.vendor}`);
583
+ }
584
+ }
585
+ const done = await spawn.close({ agent, tmuxName });
586
+ if (!done.stopped) throw new Error(`${target} did not stop. Its process can still run: look at it with ps`);
587
+ console.log(`closed ${agent ? address(agent) : target}${done.opened ? ", and its tmux session" : ""}`);
588
+ const again = spawn.resumeCommand(done);
589
+ if (again) console.log(`The transcript stays. To open it again: ${again}`);
590
+ }
591
+
592
+ const OPERATOR_DIR = () => path.join(identity.home(), "operator");
593
+
594
+ // The session that a chat of the owner talks to. It opens sessions, closes
595
+ // them, and writes to them. Its instructions are in the CLAUDE.md of its
596
+ // directory, and the owner can change that file.
597
+ async function cmdOperator(args) {
598
+ const [sub] = positional(args, ["account"]);
599
+ if (sub !== "start") throw new Error("usage: openmsg operator start [--account <name>]");
600
+ const dir = OPERATOR_DIR();
601
+ fs.mkdirSync(dir, { recursive: true });
602
+ const instructions = path.join(dir, "CLAUDE.md");
603
+ if (!fs.existsSync(instructions)) {
604
+ const template = fileURLToPath(new URL("../operator/CLAUDE.md", import.meta.url));
605
+ fs.copyFileSync(template, instructions);
606
+ console.log(`wrote ${instructions}`);
607
+ }
608
+ const real = fs.realpathSync(dir);
609
+ const live = claudeAgents().find((a) => a.cwd && fs.existsSync(a.cwd) && fs.realpathSync(a.cwd) === real && !a.background);
610
+ if (live) {
611
+ console.log(`the operator runs already: claude:${live.name}`);
612
+ } else {
613
+ const out = await spawn.open({
614
+ dir,
615
+ account: flag(args, "account"),
616
+ // The owner runs this command, and the folder holds only the file above.
617
+ trustFolder: true,
618
+ role: "operator",
619
+ view: !args.includes("--no-window"),
620
+ });
621
+ if (!out.agent) throw new Error(`the operator did not start. Look at: tmux attach -t ${out.tmux}`);
622
+ console.log(`the operator runs: claude:${out.agent.name}, in tmux as ${out.tmux}`);
623
+ }
624
+ const label = identity.exists() ? identity.load().label : "<your label>";
625
+ console.log(`A chat or a bot of yours writes to it with: openmsg send "project:${path.basename(dir)}@${label}" "<text>"`);
626
+ console.log(`On this machine: openmsg send "project:${dir}" "<text>"`);
627
+ }
628
+
629
+ // An identity on another machine that belongs to the owner, such as a bot.
630
+ // Only the owner runs this command.
631
+ function cmdTrust(args, on) {
632
+ const [who] = positional(args, ["project"]);
633
+ if (!who) throw new Error(`usage: openmsg ${on ? "trust" : "untrust"} <owner>`);
634
+ if (AGENT_ENV.some((name) => process.env[name])) {
635
+ throw new Error("only the owner changes this mark. This command runs inside a session of an agent");
636
+ }
637
+ const member = memberOf(projectId(args), who);
638
+ if (identity.exists() && member.ownerId === identity.load().ownerId) throw new Error("that is your own identity on this machine");
639
+ voiceowners.set(member.ownerId, member.label, on);
640
+ if (!on) {
641
+ console.log(`A message from ${member.label} is a message from another person again. It approves no action.`);
642
+ return;
643
+ }
644
+ console.log(`A request from ${member.label} (${member.ownerId}) now counts as a request of yours, for each session on this machine.`);
645
+ console.log("It does not approve an action that deletes data, that cannot be undone, or that changes a permission.");
646
+ console.log(`Give this mark only to an identity that is yours, such as your own bot. Whoever controls ${member.label} then works on this machine in your name.`);
647
+ console.log(`Each such message is in ${path.join(identity.home(), "voice.jsonl")}. To stop: openmsg untrust ${member.label}`);
648
+ }
649
+
650
+ // An agent asks its owner, and the owner is not at the machine.
651
+ // Each value of a flag that can come more than one time.
652
+ function flags(args, name) {
653
+ const out = [];
654
+ for (let i = 0; i < args.length; i += 1) {
655
+ if (args[i] !== `--${name}`) continue;
656
+ const value = args[i + 1];
657
+ if (value === undefined || value.startsWith("--")) throw new Error(`--${name} needs a value`);
658
+ out.push(value);
659
+ i += 1;
660
+ }
661
+ return out;
662
+ }
663
+
664
+ async function cmdAsk(args) {
665
+ const question = positional(args, ["image", "option"]).join(" ");
666
+ if (!question) throw new Error('usage: openmsg ask "<one question, with the exact action>" [--image <file>] [--option "<text>"]');
667
+ const from = await self();
668
+ if (!from || from.unresolved || ["shell", "mcp", "webhook"].includes(from.vendor)) {
669
+ throw new Error("only a session on this machine asks its owner. openmsg did not find the session of this command");
670
+ }
671
+ const row = asks.put({ from, question, images: flags(args, "image"), options: flags(args, "option") });
672
+ console.log(`The ${row.kind === "review" ? "review" : "question"} ${row.id} waits for your user.`);
673
+ console.log(row.kind === "review"
674
+ ? "The answer arrives in this session as a message from your user: an option, a comment, or both. Wait for it before you build on one option."
675
+ : "The answer arrives in this session as a message from your user. Do not do the action before it arrives.");
676
+ console.log("If a chat of your user asked for this work, tell that chat that a question waits for the owner.");
677
+ }
678
+
679
+ function cmdAsks(args) {
680
+ if (args.includes("--history")) {
681
+ const done = asks.history();
682
+ if (done.length === 0) console.log("no question has an answer yet");
683
+ for (const r of done) {
684
+ const said = r.answer === "feedback" ? [r.choice && `chose: ${r.choice}`, r.comment && `comment: ${r.comment}`].filter(Boolean).join("\n ") : null;
685
+ console.log(`${r.answeredAt} ${r.answer.padEnd(3)} ${address(r.from)} through ${r.via}\n ${r.question}${said ? `\n ${said}` : ""}`);
686
+ }
687
+ return;
688
+ }
689
+ const rows = asks.waiting();
690
+ if (args.includes("--json")) {
691
+ console.log(JSON.stringify(rows.map((r) => ({
692
+ id: r.id, kind: r.kind ?? "approval", from: address(r.from), dir: r.from.cwd, question: r.question, askedAt: r.askedAt,
693
+ ...(r.kind === "review" ? { options: r.options, images: r.images.map((name) => path.join(asks.filesDir(), name)) } : {}),
694
+ })), null, 1));
695
+ return;
696
+ }
697
+ if (rows.length === 0) console.log("no question waits for the owner");
698
+ for (const r of rows) {
699
+ if (r.kind === "review") {
700
+ const lines = [...r.options.map((o, i) => `${i + 1}. ${o}`), ...r.images.map((name) => `image: ${path.join(asks.filesDir(), name)}`)];
701
+ console.log(`${r.id} review ${address(r.from)} ${r.askedAt}\n ${r.question}${lines.map((l) => `\n ${l}`).join("")}\n openmsg answer ${r.id} --choice <n> --comment "<text>"`);
702
+ } else console.log(`${r.id} ${address(r.from)} ${r.askedAt}\n ${r.question}\n openmsg answer ${r.id} yes | openmsg answer ${r.id} no`);
703
+ }
704
+ }
705
+
706
+ // The environment of a command that an agent runs. The owner answers, and an
707
+ // agent does not answer its own question. A program with the account of the
708
+ // owner can take these names away, so this is a guard against a mistake, and
709
+ // not a wall.
710
+ const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_MESSAGING_SOCKET", "CODEX_THREAD_ID", "OPENCODE_SESSION_ID", "OPENMSG_SELF"];
711
+
712
+ async function cmdAnswer(args) {
713
+ const [id, word] = positional(args, ["via", "choice", "comment"]);
714
+ const isReview = args.includes("--choice") || args.includes("--comment");
715
+ if (!id || (isReview ? word !== undefined : !["yes", "no"].includes(word))) {
716
+ throw new Error('usage: openmsg answer <id> yes|no, or openmsg answer <id> [--choice <option or number>] [--comment "<text>"]');
717
+ }
718
+ if (AGENT_ENV.some((name) => process.env[name])) {
719
+ throw new Error("only the owner answers a question. This command runs inside a session of an agent");
720
+ }
721
+ const via = { via: flag(args, "via") ?? "the command line" };
722
+ const row = isReview
723
+ ? asks.review(id, { choice: flag(args, "choice"), comment: flag(args, "comment") }, via)
724
+ : asks.answer(id, word === "yes", via);
725
+ const live = (await allAgents()).find((a) => a.vendor === row.from.vendor && a.id === row.from.id);
726
+ const to = live ?? row.from;
727
+ const parts = layoutOfAnswer(row);
728
+ const message = createMessage({
729
+ from: { vendor: "owner", id: "owner", name: "owner" },
730
+ to,
731
+ text: parts.body,
732
+ });
733
+ if (!live) {
734
+ // The session ended. The answer waits in its mailbox, as a record.
735
+ mailbox.put(to, { ...message, rendered: compose(parts) }, "queued");
736
+ console.log(`${said(row)} is the answer to ${row.id}. The session ${address(to)} ended, and the answer is in its mailbox.`);
737
+ return;
738
+ }
739
+ const result = await deliverLocal(live, message, { parts });
740
+ if (!result.stored) mailbox.put(live, { ...message, rendered: compose(parts) }, result.delivered ? "delivered" : "queued");
741
+ console.log(`${said(row)} is the answer to ${row.id}, and ${address(live)} ${result.delivered ? "has it" : "reads it at the end of its next turn"}.`);
742
+ }
743
+
744
+ function said(row) {
745
+ return row.answer === "feedback" ? (row.choice ? `"${row.choice}"` : "a comment") : row.answer;
437
746
  }
438
747
 
439
748
  function cmdWebhook(args) {
@@ -567,6 +876,11 @@ async function cmdSendRemote(target, text, replyTo, args) {
567
876
  if (row.live === false && row.vendor !== "project") {
568
877
  console.error(`openmsg: the session ${row.alias}@${label} does not run now. The next session in its directory takes the message.`);
569
878
  }
879
+ // An earlier message to this agent that nobody read. A second message does
880
+ // not help a busy agent, and it costs one more run of an agent that pays.
881
+ for (const quiet of outbox.silent({ alias: `${alias}@${label}` })) {
882
+ console.error(`openmsg: ${outbox.silenceNote(quiet)}`);
883
+ }
570
884
  // The message is sealed for the machine that holds that session, and the
571
885
  // routing data of that machine gave this key.
572
886
  const sealTo = row.sealTo ?? null;
@@ -630,7 +944,7 @@ async function cmdSendRemote(target, text, replyTo, args) {
630
944
  const receipt = await waitForReceipt(receipts, message.messageId, 3000);
631
945
  link.close();
632
946
  if (receipt) {
633
- outbox.setState(message.messageId, receipt.status, { reason: receipt.reason ?? null });
947
+ outbox.advance(message.messageId, receipt.status, { reason: receipt.reason ?? null });
634
948
  out = { status: receipt.status, reason: receipt.reason };
635
949
  } else {
636
950
  out = { status: "relay-holds" };
@@ -799,7 +1113,8 @@ async function cmdRelay(args) {
799
1113
 
800
1114
  function cmdOutbox(args) {
801
1115
  const rows = args.includes("--all") ? outbox.list() : outbox.waiting();
802
- if (rows.length === 0) {
1116
+ const quiet = outbox.silent();
1117
+ if (rows.length === 0 && quiet.length === 0) {
803
1118
  console.log(args.includes("--all") ? "the outbox is empty" : "no message waits for a receipt");
804
1119
  return;
805
1120
  }
@@ -807,6 +1122,11 @@ function cmdOutbox(args) {
807
1122
  const where = r.pending ? " (on this machine, the relay did not answer)" : "";
808
1123
  console.log(`${r.messageId.slice(0, 8)} ${String(r.state).padEnd(16)} to ${r.alias ?? r.to} ${r.at}${where}`);
809
1124
  }
1125
+ if (quiet.length > 0) {
1126
+ if (rows.length > 0) console.log("");
1127
+ console.log("no answer:");
1128
+ for (const r of quiet) console.log(` ${outbox.silenceNote(r)}`);
1129
+ }
810
1130
  }
811
1131
 
812
1132
  async function cmdGateway(args) {
@@ -1215,6 +1535,14 @@ try {
1215
1535
  else if (cmd === "dir") await cmdDir(args);
1216
1536
  else if (cmd === "webhook") cmdWebhook(args);
1217
1537
  else if (cmd === "mcp") await cmdMcp(args);
1538
+ else if (cmd === "ask") await cmdAsk(args);
1539
+ else if (cmd === "asks") cmdAsks(args);
1540
+ else if (cmd === "answer") await cmdAnswer(args);
1541
+ else if (cmd === "spawn") await cmdSpawn(args);
1542
+ else if (cmd === "close") await cmdClose(args);
1543
+ else if (cmd === "operator") await cmdOperator(args);
1544
+ else if (cmd === "trust") cmdTrust(args, true);
1545
+ else if (cmd === "untrust") cmdTrust(args, false);
1218
1546
  else if (cmd === "whoami") console.log(address(await self()));
1219
1547
  else console.log(USAGE);
1220
1548
  } catch (e) {
package/src/directory.mjs CHANGED
@@ -111,6 +111,32 @@ export function routingOf(projectId, ownerId) {
111
111
  return project(projectId)?.members?.[ownerId]?.routing ?? null;
112
112
  }
113
113
 
114
+ // The agents of other people, from the last routing data that this machine
115
+ // holds. A revoked member gives no row, and one address gives one row.
116
+ export const STALE_MS = 10 * 60 * 1000;
117
+
118
+ export function remoteAgents() {
119
+ const out = [];
120
+ const seen = new Set();
121
+ for (const entry of projects()) {
122
+ for (const m of members(entry.id)) {
123
+ for (const row of m.routing?.rows ?? []) {
124
+ const address = `${row.alias}@${m.label}`;
125
+ if (seen.has(address)) continue;
126
+ seen.add(address);
127
+ // The routing data is the answer of the other gateway at that time, and
128
+ // not its state now. Data older than STALE_MS says "stale", because
129
+ // that gateway can be offline now.
130
+ const age = Date.now() - Date.parse(m.routing.at);
131
+ const status =
132
+ row.vendor === "project" ? "directory" : row.live === false ? "ended" : age > STALE_MS ? "stale" : "live";
133
+ out.push({ address, owner: m.label, project: entry.label ?? entry.id, status, at: m.routing.at });
134
+ }
135
+ }
136
+ }
137
+ return out;
138
+ }
139
+
114
140
  // A machine of a member, and not the member. One stolen machine costs one
115
141
  // delegation, and the identity of that person holds.
116
142
  export function revokeDevice(projectId, deviceId, reason = null, { owner = null } = {}) {
package/src/envelope.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // The openmsg envelope. The field names follow the A2A Message object, so the
2
2
  // same message can travel over A2A on HTTP later.
3
3
  import { randomUUID } from "node:crypto";
4
+ import { speaksForOwner } from "./mcpagents.mjs";
4
5
 
5
6
  // A chain of replies inside one conversation. It stops a loop between two
6
7
  // agents that answer each other without end. At the limit, the agent asks its
@@ -64,7 +65,14 @@ export function header(fields) {
64
65
  // adapter shows the frame and the body apart in its own way, and the model
65
66
  // reads the same words in each case.
66
67
  export function layout(head, body, foot) {
67
- return { head, body: clean(body), foot };
68
+ return { head, body: unframed(clean(body)), foot };
69
+ }
70
+
71
+ // A sender can write a line of dashes, and then lines that look like the
72
+ // lines of openmsg after the text. The lines after the text say who the
73
+ // sender is, so no line of the text is a line of dashes.
74
+ export function unframed(text) {
75
+ return text.replace(/^[ \t]*[─━—–-]{8,}[ \t]*$/gmu, "- - -");
68
76
  }
69
77
 
70
78
  // With `ansi`, each line of the frame is gray, and each line of the body is
@@ -82,6 +90,64 @@ export function bodyRange(parts) {
82
90
  return { start, end: start + Buffer.byteLength(parts.body) };
83
91
  }
84
92
 
93
+ // The lines for a chat that the owner marked with `openmsg mcp trust`. The
94
+ // first line is the one that the instruction block of each agent names.
95
+ export const VOICE = (from) => [
96
+ `From ${from}, a chat that your user writes in. Your user chose this: a request from this chat counts as a request of your user.`,
97
+ "It does not approve an action that deletes data, that cannot be undone, or that changes a permission, a configuration, or an instruction file. For such an action, ask your user.",
98
+ 'When your user is not at this machine, ask with: openmsg ask "<one question, with the exact action>". The answer arrives as a message.',
99
+ 'To show your user a screenshot or a choice: openmsg ask "<question>" --image <file.png> --option "<A>" --option "<B>". The answer is an option, a comment, or both.',
100
+ ];
101
+
102
+ // The first message of a session that another session opened with
103
+ // `openmsg spawn`, for a request of the owner from a chat of the owner. The
104
+ // new session reads it as a message that its user typed, so the frame says
105
+ // who wrote it and what it approves.
106
+ export function layoutOfSpawnPrompt(from, text) {
107
+ return layout(
108
+ header([["From", from]]),
109
+ text,
110
+ [
111
+ RULE,
112
+ `From ${from}, the session that opened this session. Your user is away, and asked ${from} for this work from a chat that your user writes in.`,
113
+ "It counts as a request of your user. It does not approve an action that deletes data, that cannot be undone, or that changes a permission, a configuration, or an instruction file.",
114
+ 'For such an action, ask your user with: openmsg ask "<one question, with the exact action>"',
115
+ 'To show your user a screenshot or a choice: openmsg ask "<question>" --image <file.png> --option "<A>" --option "<B>"',
116
+ `To answer: openmsg send "${from}" "<your answer>"`,
117
+ ],
118
+ );
119
+ }
120
+
121
+ // The layout of the answer of the owner to a question of `openmsg ask`.
122
+ export function layoutOfAnswer(row) {
123
+ if (row.answer === "feedback") {
124
+ const lines = [`Question: ${row.question}`];
125
+ if (row.choice) lines.push(`Choice: ${row.choice}`);
126
+ if (row.comment) lines.push(`Comment: ${row.comment}`);
127
+ return layout(
128
+ header([["From", "your user"], ["Id", row.id]]),
129
+ lines.join("\n"),
130
+ [
131
+ RULE,
132
+ `From your user, through ${row.via}. It is the answer to the review that this session asked with openmsg ask.`,
133
+ "It is the choice and the feedback of your user on that review. It does not approve an action that deletes data, that cannot be undone, or that changes a permission, a configuration, or an instruction file.",
134
+ ],
135
+ );
136
+ }
137
+ const yes = row.answer === "yes";
138
+ return layout(
139
+ header([["From", "your user"], ["Id", row.id]]),
140
+ `Question: ${row.question}\nAnswer: ${yes ? "yes" : "no"}`,
141
+ [
142
+ RULE,
143
+ `From your user, through ${row.via}. It is the answer to the question that this session asked with openmsg ask.`,
144
+ yes
145
+ ? "It approves the one action of that question, and no other action."
146
+ : "Your user said no. Do not do that action.",
147
+ ],
148
+ );
149
+ }
150
+
85
151
  // The layout of a message of 0.1. The header states the source, so the
86
152
  // receiving model never treats the message as an instruction from its user.
87
153
  export function layoutOf(message) {
@@ -89,6 +155,9 @@ export function layoutOf(message) {
89
155
  const id = shortId(message.messageId);
90
156
  // A script, such as a scheduled check, is not a session. It takes no answer.
91
157
  const script = message.openmsg.from.vendor === "shell" || message.openmsg.from.unresolved;
158
+ if (speaksForOwner(message.openmsg.from)) {
159
+ return layout(header([["From", from], ["Id", id]]), textOf(message), [RULE, ...VOICE(from), `To answer: openmsg send "${from}" "<your answer>" --reply-to ${id}`]);
160
+ }
92
161
  return layout(
93
162
  header([["From", from], ["Id", id]]),
94
163
  textOf(message),