openmsg 0.4.6 → 0.5.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/README.md CHANGED
@@ -35,9 +35,10 @@ An address is `<vendor>:<name>`, for example `claude:api-worker`.
35
35
  |---|---|---|
36
36
  | Claude Code | The inbox socket of the session | Works, tested live |
37
37
  | Codex | `codex queue` on the shared app-server daemon | Works, tested live |
38
- | OpenCode | `POST /session/{id}/prompt_async` on its local server | Delivery tested live. A reply needs a model account |
38
+ | OpenCode | 2.x: `POST /api/session/{id}/prompt` on the shared service, with the password from `~/.local/state/opencode/service.json`. 1.x: `POST /session/{id}/prompt_async` | Works both ways, tested live with 2.2.6 |
39
39
  | Cursor CLI | A hook reads the mailbox at the end of each turn | Written, tested with fixtures. A live test needs `CURSOR_API_KEY` |
40
40
  | Gemini CLI | The same hook, as an AfterAgent deny | Written, tested with fixtures. Gemini CLI is not installed here |
41
+ | An agent that wakes on an HTTP request | `openmsg webhook add <name> <url>`. The request carries a notice with no text of the sender, and the agent reads the message with `openmsg inbox` | Works, tested live with a hosted bot on its own machine, through a relay on a private network |
41
42
  | Other agents | `tmux send-keys` | Not started |
42
43
 
43
44
  A reply is a new message. The receiving agent answers with `openmsg send`. No
@@ -137,6 +138,37 @@ for a message to a directory:
137
138
  openmsg install --hooks
138
139
  ```
139
140
 
141
+ ## Troubleshooting
142
+
143
+ ### `EPERM: operation not permitted` on macOS
144
+
145
+ The symptoms:
146
+
147
+ - `openmsg list` or `openmsg send` stops with `EPERM: operation not permitted, open '.../src/cli.mjs'`.
148
+ - Codex shows `Hook failed: hook exited with code 126`.
149
+
150
+ The cause: macOS protects `~/Desktop`, `~/Documents`, and `~/Downloads`. A
151
+ program in a terminal gets access to these folders through the terminal app.
152
+ When the terminal app loses this access, every agent in that terminal loses it
153
+ too. An update of the terminal app can cause this. On 2026-10-22, an update of
154
+ Cursor caused it on one Mac. The sandbox of the agent is not the cause.
155
+
156
+ To find the process that macOS blocks:
157
+
158
+ ```
159
+ log show --last 10m --predicate 'eventMessage CONTAINS "System Policy"' | grep deny
160
+ ```
161
+
162
+ To correct the fault:
163
+
164
+ 1. Open System Settings > Privacy & Security > Full Disk Access.
165
+ 2. Remove the terminal app (Cursor, VS Code, iTerm, or Terminal), then add it again.
166
+ 3. Quit the terminal app, then open it again. A running app keeps the old state.
167
+
168
+ Until you do this, an agent in that terminal still receives a message, because
169
+ the entry point of each vendor is outside these folders. The agent cannot send
170
+ a message.
171
+
140
172
  ## How each vendor lets a message in
141
173
 
142
174
  [`research/2026-09-19-transport-research.md`](https://github.com/marciob/openmsg/blob/main/research/2026-09-19-transport-research.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openmsg",
3
- "version": "0.4.6",
3
+ "version": "0.5.0",
4
4
  "description": "Messages between AI coding agents of different vendors, on one machine or between two people, sealed end to end.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  // Source: packages/opencode/src/cli/cmd/tui/routes/session/index.tsx (v1.1.11),
13
13
  // packages/opencode/src/session/message-v2.ts.
14
14
  import { render, RULE } from "../envelope.mjs";
15
+ import { opencodeService, opencodeServiceFile } from "../registry.mjs";
15
16
 
16
17
  export function partsOf({ head, body, foot }) {
17
18
  const cut = foot.indexOf(RULE) + 1;
@@ -20,7 +21,33 @@ export function partsOf({ head, body, foot }) {
20
21
  return rest.length ? [shown, { type: "text", synthetic: true, text: rest.join("\n") }] : [shown];
21
22
  }
22
23
 
24
+ // OpenCode 2 has no `prompt_async` and no part list. `/api/.../prompt` takes one
25
+ // text. `/api/.../synthetic` exists, but the server runs each item of the inbox
26
+ // as its own turn: a hidden notice after the text arrives one turn late, and it
27
+ // costs a second call to the model. So the whole text goes in one prompt, and
28
+ // the person sees the notice too. `queue` waits for a turn that runs now.
29
+ // Source: GET /openapi.json of `opencode serve --service`, version 2.2.6, and a
30
+ // live test on 2026-11-07.
31
+ async function deliverV2(agent, message, { text, layout }) {
32
+ const service = opencodeService();
33
+ if (!service) throw new Error(`opencode: no running service in ${opencodeServiceFile()}`);
34
+ const body = {
35
+ text: layout ? [...layout.head, layout.body, ...layout.foot].join("\n") : (text ?? render(message)),
36
+ delivery: "queue",
37
+ metadata: { openmsg: message?.messageId ?? true },
38
+ };
39
+ const res = await fetch(`${agent.transport.base}/api/session/${agent.id}/prompt`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json", authorization: service.auth },
42
+ body: JSON.stringify(body),
43
+ signal: AbortSignal.timeout(5000),
44
+ });
45
+ if (!res.ok) throw new Error(`opencode ${res.status}: ${(await res.text()).slice(0, 200)}`);
46
+ return { delivered: true, transport: "http" };
47
+ }
48
+
23
49
  export async function deliver(agent, message, { text = null, layout = null } = {}) {
50
+ if (agent.transport?.api === 2) return deliverV2(agent, message, { text, layout });
24
51
  const url = `${agent.transport.base}/session/${agent.id}/prompt_async`;
25
52
  const parts = layout ? partsOf(layout) : [{ type: "text", text: text ?? render(message) }];
26
53
  const res = await fetch(url, {
@@ -0,0 +1,49 @@
1
+ // The adapter for an agent that wakes on an HTTP request.
2
+ //
3
+ // The request carries a notice, and it never carries the text of the sender.
4
+ // The URL of a webhook is on a network, and a person who learns it can send a
5
+ // request of their own. A request with the text of a message would therefore
6
+ // let that person write to the agent with no signature. With a notice alone,
7
+ // a false request wakes the agent, and the agent finds an empty mailbox.
8
+ //
9
+ // The agent reads the message with `openmsg inbox`. That command reads the
10
+ // mailbox on the machine of the agent, and only openmsg writes there.
11
+
12
+ // A sender chooses the id of its message. Only an id with the shape of a UUID
13
+ // goes into the notice, so no text of the sender travels in that field.
14
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15
+
16
+ export function notice(agent, message) {
17
+ return {
18
+ openmsg: "message-waiting",
19
+ agent: `${agent.vendor}:${agent.name}`,
20
+ messageId: UUID.test(String(message?.messageId ?? "")) ? message.messageId : null,
21
+ text:
22
+ "A message waits for you in openmsg. Run this command to read it: openmsg inbox. " +
23
+ "This notice is not the message, and it approves no action.",
24
+ };
25
+ }
26
+
27
+ export async function deliver(agent, message, { timeoutMs = 10_000 } = {}) {
28
+ const url = agent.transport?.url;
29
+ if (!url) throw new Error(`the agent ${agent.name} has no webhook address`);
30
+ let res;
31
+ try {
32
+ res = await fetch(url, {
33
+ method: "POST",
34
+ // The owner can name a header that the webhook asks for, such as a key.
35
+ headers: { ...(agent.transport.headers ?? {}), "content-type": "application/json" },
36
+ body: JSON.stringify(notice(agent, message)),
37
+ signal: AbortSignal.timeout(timeoutMs),
38
+ // A redirect can send the notice to an address that the owner did not give.
39
+ redirect: "error",
40
+ });
41
+ } catch (e) {
42
+ // The message of the error can hold the URL, and the URL is a secret.
43
+ throw new Error(`the webhook of ${agent.name} did not answer (${e.cause?.code ?? e.name})`);
44
+ }
45
+ // The body is not read. Nothing that the webhook answers reaches a model.
46
+ await res.body?.cancel().catch(() => {});
47
+ if (!res.ok) throw new Error(`the webhook of ${agent.name} answered ${res.status}`);
48
+ return { delivered: true, transport: "webhook" };
49
+ }
package/src/cli.mjs CHANGED
@@ -23,6 +23,7 @@ import * as limits from "./limits.mjs";
23
23
  import * as device from "./device.mjs";
24
24
  import * as dirsync from "./dirsync.mjs";
25
25
  import * as notes from "./notes.mjs";
26
+ import * as webhooks from "./webhooks.mjs";
26
27
  import { fileURLToPath } from "node:url";
27
28
  import fs from "node:fs";
28
29
  import path from "node:path";
@@ -41,6 +42,10 @@ const USAGE = `openmsg — messages between AI coding agents
41
42
  openmsg waiting the project messages that wait for a session
42
43
  openmsg inbox [--json] [--all] show the messages for this agent
43
44
  openmsg whoami show how this agent is addressed
45
+ openmsg webhook add <name> <url> name an agent that wakes on an HTTP request
46
+ [--header "Name: value"] a header that the webhook asks for, such as a key
47
+ openmsg webhook remove <name> take that agent away
48
+ openmsg webhook list the agents that wake on an HTTP request
44
49
  openmsg hook <vendor> run inside a hook of claude, cursor, or gemini
45
50
  openmsg install let every agent on this machine answer messages
46
51
  openmsg install --hooks add the hooks for claude, cursor, and gemini
@@ -60,7 +65,9 @@ For the agents of another person, on another machine:
60
65
  openmsg dir revoke <project-id> <owner-id> [--reason <text>]
61
66
  openmsg gateway start [--port <n>] [--host <h>]
62
67
  openmsg publish <agent> let the project reach this session
68
+ openmsg publish --all let the project reach every session, and each new one
63
69
  openmsg unpublish <alias> take a session back
70
+ openmsg unpublish --all go back to the sessions that you named
64
71
  openmsg permit <owner> <accept|hold|refuse>
65
72
  openmsg held [<id>] [--text] the messages that wait for you
66
73
  openmsg held --all every message from another person, and its state
@@ -198,7 +205,8 @@ async function cmdSend(target, text, replyTo = null, args = []) {
198
205
  if (message.openmsg.hops.length > MAX_HOPS) {
199
206
  throw new Error(
200
207
  `hop limit reached: this conversation already passed through ${message.openmsg.hops.length - 1} agents. ` +
201
- "Tell your user instead.",
208
+ "Ask your user if they want to continue. If the user says yes, send the text again " +
209
+ "as a new message, without --reply-to. A new message starts a new conversation.",
202
210
  );
203
211
  }
204
212
 
@@ -207,10 +215,14 @@ async function cmdSend(target, text, replyTo = null, args = []) {
207
215
  // "delivered" means an adapter pushed the message into the live session.
208
216
  // "queued" means it waits in the mailbox for an agent that reads it at the
209
217
  // end of a turn.
210
- mailbox.put(to, message, result.delivered ? "delivered" : "queued");
218
+ // The adapter of a webhook agent writes the mailbox before it sends its
219
+ // notice, so the agent that wakes finds the message.
220
+ if (!result.stored) mailbox.put(to, message, result.delivered ? "delivered" : "queued");
211
221
  const how = result.delivered
212
222
  ? `sent to ${address(to)} over ${result.transport}`
213
- : `queued for ${address(to)} in the mailbox. That agent reads it at the end of its next turn`;
223
+ : result.detail
224
+ ? `queued for ${address(to)} in the mailbox, because ${result.detail}. That agent reads it at its next check`
225
+ : `queued for ${address(to)} in the mailbox. That agent reads it at the end of its next turn`;
214
226
  console.log(`${how} (${message.messageId})`);
215
227
  }
216
228
 
@@ -303,11 +315,67 @@ async function cmdInbox(args) {
303
315
  console.log("no messages");
304
316
  } else {
305
317
  for (const r of rows) {
306
- console.log(`from ${address(r.openmsg.from)} at ${r.createdAt}\n${r.parts.map((p) => p.text).join("\n")}\n`);
318
+ // A message for a webhook agent holds the text that a model reads: the
319
+ // header, the text of the sender, and the notice after it. A session
320
+ // of another vendor got those words from its adapter.
321
+ if (r.rendered) console.log(`${r.rendered}\n`);
322
+ else console.log(`from ${address(r.openmsg.from)} at ${r.createdAt}\n${r.parts.map((p) => p.text).join("\n")}\n`);
307
323
  }
308
324
  }
309
325
  }
310
326
  mailbox.markRead(me, rows.map((r) => r.messageId));
327
+ await acknowledgeRead(rows);
328
+ }
329
+
330
+ // A read of the mailbox is an event from the agent, and rule 1 of section 8
331
+ // of the spec of 0.2 gives it the state "agent-acknowledged". Only a message
332
+ // from another person has a row in that store.
333
+ async function acknowledgeRead(rows) {
334
+ for (const r of rows) {
335
+ if (r.openmsg?.version !== remote.VERSION) continue;
336
+ const row = inbound.find(r.messageId);
337
+ if (!row || !["queued", "adapter-accepted"].includes(row.status)) continue;
338
+ inbound.setStatus(row.messageId, "agent-acknowledged");
339
+ // The sender learns the state when a way to it exists. A read never fails
340
+ // because the sender is offline.
341
+ await gateway.reportState(row, "agent-acknowledged").catch(() => {});
342
+ }
343
+ }
344
+
345
+ function cmdWebhook(args) {
346
+ // --header can come more than one time, and each one takes the next word.
347
+ const headers = [];
348
+ const words = [];
349
+ for (let i = 0; i < args.length; i++) {
350
+ if (args[i] === "--header") {
351
+ if (args[i + 1] === undefined) throw new Error('--header needs a value, such as "Authorization: Bearer <key>"');
352
+ headers.push(args[++i]);
353
+ } else words.push(args[i]);
354
+ }
355
+ const [sub, name, url] = words;
356
+ if (sub === "add") {
357
+ if (!name || !url) throw new Error('usage: openmsg webhook add <name> <url> [--header "Name: value"]');
358
+ const row = webhooks.add(name, url, { headers });
359
+ console.log(`webhook:${row.name} wakes on a request to the address that you gave`);
360
+ const names = Object.keys(row.headers);
361
+ if (names.length > 0) console.log(`Each request carries the header ${names.join(", ")}. Its value is a secret too.`);
362
+ console.log("That address is a secret. A person who holds it can wake the agent, and cannot write to it.");
363
+ console.log(`The agent names itself with: export OPENMSG_SELF=webhook:${row.name}`);
364
+ return;
365
+ }
366
+ if (sub === "remove") {
367
+ if (!name) throw new Error("usage: openmsg webhook remove <name>");
368
+ console.log(webhooks.remove(name) ? `webhook:${name} is gone` : `no agent webhook:${name}`);
369
+ return;
370
+ }
371
+ if (sub === undefined || sub === "list") {
372
+ const rows = webhooks.agents();
373
+ if (rows.length === 0) console.log("no agent wakes on an HTTP request. Run: openmsg webhook add <name> <url>");
374
+ // The host shows which service takes the notice. The path holds the secret.
375
+ for (const a of rows) console.log(`${address(a)} ${new URL(a.transport.url).host}`);
376
+ return;
377
+ }
378
+ throw new Error("usage: openmsg webhook add <name> <url> | webhook remove <name> | webhook list");
311
379
  }
312
380
 
313
381
  // --- version 0.2: identity, invitations, and the directory ----------------
@@ -627,7 +695,8 @@ async function cmdGateway(args) {
627
695
  }
628
696
  console.log(`gateway of ${me.label} (${me.ownerId}) listens on ${running.url}`);
629
697
  const rows = published.list();
630
- if (rows.length === 0) console.log("nothing is published. Run: openmsg publish <agent>");
698
+ for (const id of published.openProjects()) stamp(`every session of this machine is published in ${id}`);
699
+ if (rows.length === 0 && published.openProjects().length === 0) console.log("nothing is published. Run: openmsg publish <agent>");
631
700
  for (const r of rows) console.log(`published ${r.alias} · project ${r.project} · epoch ${r.epoch}`);
632
701
  const stop = () => {
633
702
  console.log("gateway stopped");
@@ -639,9 +708,18 @@ async function cmdGateway(args) {
639
708
 
640
709
  async function cmdPublish(args) {
641
710
  const [query] = positional(args, ["project"]);
711
+ if (args.includes("--all")) {
712
+ const project = projectId(args);
713
+ published.setOpen(project, true);
714
+ console.log(`every session of this machine can be reached in ${project}, and each new session too`);
715
+ console.log("A member of that project can write to each of them. Your permission for each sender still holds.");
716
+ console.log("Stop it: openmsg unpublish --all. A gateway that runs takes the change at once.");
717
+ return;
718
+ }
642
719
  if (!query) {
643
720
  const rows = published.list();
644
- if (rows.length === 0) console.log("nothing is published");
721
+ for (const id of published.openProjects()) console.log(`${"every session".padEnd(28)} ${id} each session that runs, and each new one`);
722
+ if (rows.length === 0 && published.openProjects().length === 0) console.log("nothing is published");
645
723
  for (const r of rows) console.log(`${r.alias.padEnd(28)} ${r.project} epoch ${r.epoch} session ${r.session}`);
646
724
  return;
647
725
  }
@@ -653,6 +731,11 @@ async function cmdPublish(args) {
653
731
 
654
732
  function cmdUnpublish(args) {
655
733
  const project = projectId(args);
734
+ if (args.includes("--all")) {
735
+ const was = published.setOpen(project, false);
736
+ console.log(was ? `only the sessions that you named are published in ${project} now` : `${project} did not take every session`);
737
+ return;
738
+ }
656
739
  const [alias] = positional(args, ["project"]);
657
740
  const gone = published.unpublish(project, alias);
658
741
  console.log(gone ? `${alias} is not published any more` : `${alias} was not published in ${project}`);
@@ -814,7 +897,7 @@ function cmdInvite(args) {
814
897
  label: flag(rest, "project"),
815
898
  projectId: flag(rest, "project-id"),
816
899
  hours: Number(flag(rest, "hours") ?? invite.DEFAULT_HOURS),
817
- endpoint: flag(rest, "endpoint") ?? gateway.settings().endpoint ?? null,
900
+ endpoint: flag(rest, "endpoint") ?? gateway.advertised(),
818
901
  });
819
902
  console.log(`project ${out.project.id} (${out.project.label})`);
820
903
  console.log(`fingerprint ${out.fingerprint}`);
@@ -839,7 +922,7 @@ function cmdInvite(args) {
839
922
  if (sub === "accept") {
840
923
  const [token] = positional(rest, ["fingerprint", "endpoint"]);
841
924
  const out = invite.accept(token, flag(rest, "fingerprint"), {
842
- endpoint: flag(rest, "endpoint") ?? gateway.settings().endpoint ?? null,
925
+ endpoint: flag(rest, "endpoint") ?? gateway.advertised(),
843
926
  });
844
927
  console.log(`${out.peer.ownerId} (${out.peer.label}) is now a member of ${out.project.id}`);
845
928
  if (out.reply) {
@@ -1000,6 +1083,7 @@ try {
1000
1083
  else if (cmd === "id") cmdId(args);
1001
1084
  else if (cmd === "invite") cmdInvite(args);
1002
1085
  else if (cmd === "dir") await cmdDir(args);
1086
+ else if (cmd === "webhook") cmdWebhook(args);
1003
1087
  else if (cmd === "whoami") console.log(address(await self()));
1004
1088
  else console.log(USAGE);
1005
1089
  } catch (e) {
package/src/deliver.mjs CHANGED
@@ -4,6 +4,8 @@
4
4
  import * as claude from "./adapters/claude.mjs";
5
5
  import * as opencode from "./adapters/opencode.mjs";
6
6
  import * as codex from "./adapters/codex.mjs";
7
+ import * as webhook from "./adapters/webhook.mjs";
8
+ import * as mailbox from "./mailbox.mjs";
7
9
  import { layoutOf, compose, bodyRange } from "./envelope.mjs";
8
10
 
9
11
  // `parts` is the layout of the text that the model reads: the frame and the text
@@ -28,7 +30,26 @@ export async function deliverLocal(agent, message, { text = null, parts = null }
28
30
  }
29
31
  if (agent.vendor === "opencode") return opencode.deliver(agent, message, parts ? { layout: parts } : { text });
30
32
  if (agent.vendor === "codex") return codex.deliver(agent, message, { text: plain, highlight: parts ? bodyRange(parts) : null });
33
+ if (agent.vendor === "webhook") return wake(agent, message, plain);
31
34
  // An agent with no push entry point, such as Gemini CLI or Cursor CLI, reads
32
35
  // its mailbox at the end of a turn. The message waits there.
33
36
  return { delivered: false, transport: "mailbox" };
34
37
  }
38
+
39
+ // An agent that wakes on an HTTP request. The message goes to the mailbox
40
+ // first, with the text that the model reads, and the request goes after it.
41
+ // The agent that wakes therefore always finds the message. `stored` tells the
42
+ // caller that the mailbox holds the message already.
43
+ async function wake(agent, message, rendered) {
44
+ // A message that arrives a second time, before the agent read the first
45
+ // copy, does not go to the mailbox twice. The agent still gets a new notice.
46
+ const waits = mailbox.list(agent, { unreadOnly: true }).some((m) => m.messageId === message.messageId);
47
+ if (!waits) mailbox.put(agent, { ...message, rendered }, "queued");
48
+ try {
49
+ return { ...(await webhook.deliver(agent, message)), stored: true };
50
+ } catch (e) {
51
+ // A notice that failed loses no message. The message waits in the mailbox,
52
+ // and the agent reads it at its next check.
53
+ return { delivered: false, transport: "mailbox", stored: true, detail: e.message };
54
+ }
55
+ }
package/src/dirsync.mjs CHANGED
@@ -24,7 +24,7 @@ import * as identity from "./identity.mjs";
24
24
  import * as device from "./device.mjs";
25
25
  import * as directory from "./directory.mjs";
26
26
  import * as permissions from "./permissions.mjs";
27
- import { settings } from "./settings.mjs";
27
+ import { settings, advertised } from "./settings.mjs";
28
28
 
29
29
  export const KINDS = ["self", "roster", "revoke-device"];
30
30
  export const MAX_RECORD_BYTES = 16 * 1024;
@@ -52,7 +52,7 @@ export function selfRecord(project) {
52
52
  owner: me.ownerId,
53
53
  label: me.label,
54
54
  keys: me.keys,
55
- endpoint: settings().endpoint ?? null,
55
+ endpoint: advertised(),
56
56
  at: new Date().toISOString(),
57
57
  });
58
58
  }
package/src/envelope.mjs CHANGED
@@ -3,8 +3,9 @@
3
3
  import { randomUUID } from "node:crypto";
4
4
 
5
5
  // A chain of replies inside one conversation. It stops a loop between two
6
- // agents that answer each other without end.
7
- export const MAX_HOPS = 8;
6
+ // agents that answer each other without end. At the limit, the agent asks its
7
+ // user, and a new message starts a new chain.
8
+ export const MAX_HOPS = 100;
8
9
 
9
10
  export function createMessage({ from, to, text, contextId, replyTo }) {
10
11
  return {
package/src/gateway.mjs CHANGED
@@ -31,7 +31,7 @@ import * as relaylink from "./relaylink.mjs";
31
31
  import * as limits from "./limits.mjs";
32
32
  import * as device from "./device.mjs";
33
33
  import * as dirsync from "./dirsync.mjs";
34
- import { settings, saveSettings, endpointFor } from "./settings.mjs";
34
+ import { settings, saveSettings, endpointFor, advertised } from "./settings.mjs";
35
35
 
36
36
  export const PATHS = {
37
37
  message: "/openmsg/v2/message",
@@ -45,7 +45,7 @@ export const REQUEST_WINDOW_MS = 120_000;
45
45
 
46
46
  // --- the address of this gateway -----------------------------------------
47
47
 
48
- export { settings, saveSettings, endpointFor };
48
+ export { settings, saveSettings, endpointFor, advertised };
49
49
 
50
50
  // --- signatures on a request and on an answer ------------------------------
51
51
 
@@ -84,11 +84,67 @@ async function liveAgents(vendor, { maxAgeMs = 5000 } = {}) {
84
84
  return rows;
85
85
  }
86
86
 
87
+ // The vendors whose sessions an open project reaches. OPENMSG_OPEN_VENDORS
88
+ // holds another list, with a comma between the names. A webhook agent is not
89
+ // a session, so its owner publishes it by name.
90
+ function openVendors() {
91
+ const named = process.env.OPENMSG_OPEN_VENDORS;
92
+ return named ? named.split(",").map((v) => v.trim()).filter(Boolean) : ["claude", "codex", "opencode", "cursor", "gemini"];
93
+ }
94
+
95
+ // A row for a session that the owner did not name, in a project that takes
96
+ // every session. Its epoch is 1, because the session id names it, and a new
97
+ // session under the same name has another id.
98
+ function openRow(projectId, agent) {
99
+ return {
100
+ project: projectId,
101
+ alias: published.aliasOf(agent),
102
+ vendor: agent.vendor,
103
+ name: agent.name ?? agent.id,
104
+ session: agent.id,
105
+ epoch: 1,
106
+ open: true,
107
+ };
108
+ }
109
+
110
+ // Every row of a project: the sessions that the owner named, and, in an open
111
+ // project, each other session that runs now. A background session, such as a
112
+ // program that uses the SDK, is not a session of a person, and it stays out.
113
+ async function rowsOf(projectId) {
114
+ const rows = published.list(projectId);
115
+ if (!published.isOpen(projectId)) return rows;
116
+ const sessions = new Set(rows.map((r) => r.session));
117
+ const aliases = new Set(rows.map((r) => r.alias));
118
+ for (const vendor of openVendors()) {
119
+ for (const agent of await liveAgents(vendor)) {
120
+ if (agent.vendor !== vendor || agent.background) continue;
121
+ // A name that the owner published holds its session and its epoch.
122
+ if (sessions.has(agent.id) || aliases.has(published.aliasOf(agent))) continue;
123
+ sessions.add(agent.id);
124
+ rows.push(openRow(projectId, agent));
125
+ }
126
+ }
127
+ return rows;
128
+ }
129
+
130
+ // The row of one session. The envelope names the vendor of its target, so an
131
+ // open project asks one vendor, and not all of them.
132
+ async function rowOf(projectId, session, vendorHint = null) {
133
+ const named = published.find(projectId, { session });
134
+ if (named || !published.isOpen(projectId)) return named;
135
+ const vendors = openVendors();
136
+ for (const vendor of vendorHint && vendors.includes(vendorHint) ? [vendorHint] : vendors) {
137
+ const agent = (await liveAgents(vendor, { maxAgeMs: 0 })).find((a) => a.vendor === vendor && a.id === session && !a.background);
138
+ if (agent) return published.find(projectId, { alias: published.aliasOf(agent) }) ? null : openRow(projectId, agent);
139
+ }
140
+ return null;
141
+ }
142
+
87
143
  // The two descriptions of section 9.4 of the spec. Presence is for a person,
88
144
  // and routing data is for a gateway. Neither one carries a working directory,
89
145
  // a socket path, or a token.
90
146
  export async function descriptions(projectId) {
91
- const rows = published.list(projectId);
147
+ const rows = await rowsOf(projectId);
92
148
  const byVendor = new Map();
93
149
  for (const vendor of new Set(rows.map((r) => r.vendor))) byVendor.set(vendor, await liveAgents(vendor));
94
150
  const presence = [];
@@ -130,7 +186,7 @@ async function handleRouting(request) {
130
186
  label: me.label,
131
187
  project: projectId,
132
188
  at: new Date().toISOString(),
133
- endpoint: settings().endpoint ?? null,
189
+ endpoint: advertised(),
134
190
  presence,
135
191
  routing,
136
192
  }),
@@ -249,7 +305,7 @@ export async function release(record, { deliver = deliverLocal, now = Date.now()
249
305
  }
250
306
  if (!(Date.parse(record.expiresAt) > now)) return stop("expired", `the deadline passed at ${record.expiresAt}`);
251
307
 
252
- const mine = published.find(record.project, { session: record.target.session });
308
+ const mine = await rowOf(record.project, record.target.session, record.message?.openmsg?.to?.vendor ?? null);
253
309
  if (!mine) return stop("not-published", "that session is not published in this project");
254
310
  if (record.target.epoch !== mine.epoch) {
255
311
  return stop("old-epoch", `the message names epoch ${record.target.epoch}, and the session runs epoch ${mine.epoch}`);
package/src/published.mjs CHANGED
@@ -62,6 +62,28 @@ export function unpublish(projectId, alias) {
62
62
  return gone;
63
63
  }
64
64
 
65
+ // An owner can select every session of the machine for one project. Each
66
+ // session that runs then, and each new session, is published there. The owner
67
+ // types that choice, and nothing else turns it on.
68
+ export function setOpen(projectId, on) {
69
+ const data = read();
70
+ const open = data.open ?? {};
71
+ const was = Boolean(open[projectId]);
72
+ if (on) open[projectId] = { at: open[projectId]?.at ?? new Date().toISOString() };
73
+ else delete open[projectId];
74
+ data.open = open;
75
+ save(data);
76
+ return was;
77
+ }
78
+
79
+ export function isOpen(projectId) {
80
+ return Boolean(read().open?.[projectId]);
81
+ }
82
+
83
+ export function openProjects() {
84
+ return Object.keys(read().open ?? {});
85
+ }
86
+
65
87
  export function list(projectId = null) {
66
88
  const data = read();
67
89
  const out = [];
package/src/registry.mjs CHANGED
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import os from "node:os";
6
6
  import { execFile } from "node:child_process";
7
7
  import { registered } from "./selfregistry.mjs";
8
+ import { agents as webhookAgents } from "./webhooks.mjs";
8
9
  import { promisify } from "node:util";
9
10
 
10
11
  const run = promisify(execFile);
@@ -196,9 +197,82 @@ async function pgrep(name) {
196
197
  return stdout.trim().split("\n").filter(Boolean);
197
198
  }
198
199
 
199
- // OpenCode runs an HTTP server for each user interface. The port is in the
200
- // listening sockets of the process.
201
- export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
200
+ // OpenCode 2 runs one shared server, `opencode serve --service`, and each user
201
+ // interface is a client of it. The server writes its address, its process id,
202
+ // and its password to one file. Every request needs the password, with Basic
203
+ // authentication and the user name "opencode". The API is under /api, and each
204
+ // answer holds its result in `data`.
205
+ // A test sets OPENMSG_OPENCODE_SERVICE to a file of its own.
206
+ export function opencodeServiceFile() {
207
+ return process.env.OPENMSG_OPENCODE_SERVICE || path.join(HOME, ".local", "state", "opencode", "service.json");
208
+ }
209
+
210
+ export function opencodeService(file = opencodeServiceFile()) {
211
+ try {
212
+ const s = JSON.parse(fs.readFileSync(file, "utf8"));
213
+ if (!s.url || !s.password) return null;
214
+ if (s.pid && !alive(s.pid)) return null;
215
+ return { base: s.url.replace(/\/$/, ""), pid: s.pid ?? null, auth: `Basic ${Buffer.from(`opencode:${s.password}`).toString("base64")}` };
216
+ } catch {
217
+ return null;
218
+ }
219
+ }
220
+
221
+ async function opencodeServiceAgents({ maxAgeMs, file } = {}) {
222
+ const service = opencodeService(file);
223
+ if (!service) return [];
224
+ const get = async (p) => {
225
+ const res = await fetch(`${service.base}${p}`, {
226
+ headers: { authorization: service.auth },
227
+ signal: AbortSignal.timeout(1500),
228
+ });
229
+ if (!res.ok) throw new Error(`opencode ${res.status}`);
230
+ return (await res.json()).data;
231
+ };
232
+ let sessions;
233
+ let active = {};
234
+ try {
235
+ sessions = await get("/api/session?parentID=null");
236
+ } catch {
237
+ return [];
238
+ }
239
+ try {
240
+ active = (await get("/api/session/active")) ?? {};
241
+ } catch {
242
+ // Without this list, the state of each session stays unknown.
243
+ }
244
+ const out = [];
245
+ for (const s of sessions ?? []) {
246
+ const updated = s.time?.updated ?? 0;
247
+ if (Date.now() - updated > maxAgeMs) continue;
248
+ const title = (s.title ?? "").trim();
249
+ const short = title && !title.startsWith("New session") ? title.slice(0, 32).replace(/\s+/g, "-") : s.id.slice(-4);
250
+ out.push({
251
+ vendor: "opencode",
252
+ id: s.id,
253
+ name: `${short}-${s.id.slice(-4)}`,
254
+ pid: service.pid,
255
+ cwd: s.location?.directory ?? null,
256
+ status: active[s.id] ? "busy" : "idle",
257
+ title: title && !title.startsWith("New session") ? title : null,
258
+ startedAt: s.time?.created ?? null,
259
+ updatedAt: updated,
260
+ transport: { kind: "http", base: service.base, api: 2 },
261
+ });
262
+ }
263
+ return out;
264
+ }
265
+
266
+ // OpenCode 1 runs an HTTP server for each user interface. The port is in the
267
+ // listening sockets of the process. OpenCode 2 has the shared server above.
268
+ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000, serviceFile } = {}) {
269
+ const service = await opencodeServiceAgents({ maxAgeMs, file: serviceFile });
270
+ const legacy = await opencodeLegacyAgents({ maxAgeMs, skipPid: service[0]?.pid });
271
+ const seen = new Set(service.map((a) => a.id));
272
+ return [...service, ...legacy.filter((a) => !seen.has(a.id))];
273
+ }
274
+
275
+ async function opencodeLegacyAgents({ maxAgeMs, skipPid = null }) {
202
276
  let pids = [];
203
277
  try {
204
278
  // `-x` matches the name of the program. `-f` matches the whole command
@@ -211,9 +285,12 @@ export async function opencodeAgents({ maxAgeMs = 24 * 3600 * 1000 } = {}) {
211
285
  const found = new Map();
212
286
  const out = [];
213
287
  for (const pid of pids) {
288
+ if (Number(pid) === skipPid) continue;
214
289
  let ports = [];
215
290
  try {
216
- const { stdout } = await run("lsof", ["-nP", "-p", pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]);
291
+ // `-a` joins the conditions. Without it, lsof gives the listening ports
292
+ // of every process, and openmsg asks each of them for sessions.
293
+ const { stdout } = await run("lsof", ["-a", "-nP", "-p", pid, "-iTCP", "-sTCP:LISTEN", "-Fn"]);
217
294
  ports = [...stdout.matchAll(/n\S*:(\d+)/g)].map((m) => Number(m[1]));
218
295
  } catch {
219
296
  continue;
@@ -359,7 +436,8 @@ export async function allAgents() {
359
436
  codexAgents(),
360
437
  ]);
361
438
  // An agent with no push entry point reports itself from its hook.
362
- return [...claude, ...opencode, ...codex, ...registered()];
439
+ // An agent that wakes on an HTTP request has no session. Its owner named it.
440
+ return [...claude, ...opencode, ...codex, ...registered(), ...webhookAgents()];
363
441
  }
364
442
 
365
443
  // Discovery of one vendor. The gateway needs the session of one published
@@ -372,6 +450,7 @@ export async function agentsOfVendor(vendor) {
372
450
  const live = await codexAgents();
373
451
  return live.length > 0 ? live : codexAgentsFromFiles();
374
452
  }
453
+ if (vendor === "webhook") return webhookAgents();
375
454
  return registered();
376
455
  }
377
456
 
@@ -452,6 +531,11 @@ export async function self() {
452
531
  // reply that pins the session id of the sender fails.
453
532
  if (process.env.OPENMSG_SELF) {
454
533
  const value = process.env.OPENMSG_SELF;
534
+ // A webhook agent is in one file, so its lookup asks no vendor.
535
+ if (value.startsWith("webhook:")) {
536
+ const known = webhookAgents().find((a) => `webhook:${a.name}` === value);
537
+ if (known) return known;
538
+ }
455
539
  try {
456
540
  return await findAgent(value);
457
541
  } catch {
@@ -474,7 +558,7 @@ export async function self() {
474
558
  // A Claude session started this command, but no session record holds its
475
559
  // socket. A shell name here is false: nobody can send to it, and an agent
476
560
  // gives it to other agents as its own address.
477
- if (!me) {
561
+ if (!me && !process.env.OPENCODE_SESSION_ID) {
478
562
  throw new Error(
479
563
  `this command runs in a Claude Code session, but openmsg cannot find the record of that session ` +
480
564
  `(socket ${socket}). openmsg reads ${claudeConfigDirs().map((d) => `${d}/sessions`).join(", ")}. ` +
@@ -482,6 +566,20 @@ export async function self() {
482
566
  );
483
567
  }
484
568
  }
569
+ // OpenCode 2 gives the session id to every shell command that it runs.
570
+ if (process.env.OPENCODE_SESSION_ID) {
571
+ const id = process.env.OPENCODE_SESSION_ID;
572
+ const known = (await opencodeAgents()).find((a) => a.id === id);
573
+ if (known) return known;
574
+ const service = opencodeService();
575
+ return {
576
+ vendor: "opencode",
577
+ id,
578
+ name: id.slice(-4),
579
+ cwd: process.cwd(),
580
+ transport: service ? { kind: "http", base: service.base, api: 2 } : { kind: "mailbox" },
581
+ };
582
+ }
485
583
  const line = await ancestors(process.ppid);
486
584
  let [codex, opencode] = await Promise.all([codexAgents(), opencodeAgents()]);
487
585
  if (codex.length === 0) codex = codexAgentsFromFiles({ maxAgeMs: 6 * 3600 * 1000 });
package/src/relaylink.mjs CHANGED
@@ -214,28 +214,52 @@ export async function open(url, handlers = {}) {
214
214
 
215
215
  // The gateway keeps the connection. A relay that stops, or a network that
216
216
  // fails, gives a wait that grows, and the gateway tries again.
217
- export async function keep(url, handlers = {}) {
217
+ //
218
+ // A connection can also stop with no sign: the relay restarts behind a
219
+ // private network, or its machine sleeps, and no FIN arrives. The gateway
220
+ // then holds a connection that carries nothing, and every message for it
221
+ // waits at the relay. The gateway therefore sends a ping at an interval. A
222
+ // relay that sends no frame for two and a half intervals is gone, and the
223
+ // gateway drops the connection and connects again.
224
+ export const HEARTBEAT_MS = 20_000;
225
+
226
+ export async function keep(url, handlers = {}, { heartbeatMs = HEARTBEAT_MS } = {}) {
218
227
  let link = null;
219
228
  let stopped = false;
220
229
  let wait = 1000;
230
+ let beat = null;
221
231
  const holder = {
222
232
  get link() {
223
233
  return link;
224
234
  },
225
235
  stop() {
226
236
  stopped = true;
237
+ clearInterval(beat);
227
238
  link?.close();
228
239
  },
229
240
  };
241
+ const watch = (current) => {
242
+ let seen = Date.now();
243
+ current.connection.on("message", () => {
244
+ seen = Date.now();
245
+ });
246
+ clearInterval(beat);
247
+ beat = setInterval(() => {
248
+ if (Date.now() - seen > heartbeatMs * 2.5) current.connection.drop();
249
+ else current.connection.send(JSON.stringify({ type: "ping" }));
250
+ }, heartbeatMs);
251
+ };
230
252
  const again = async () => {
231
253
  if (stopped) return;
232
254
  try {
233
255
  link = await open(url, { ...handlers, onClose: () => {
256
+ clearInterval(beat);
234
257
  handlers.onClose?.();
235
258
  link = null;
236
259
  if (!stopped) setTimeout(again, wait);
237
260
  } });
238
261
  wait = 1000;
262
+ watch(link);
239
263
  handlers.onOpen?.(link);
240
264
  } catch (e) {
241
265
  handlers.onError?.({ error: e.message });
package/src/remote.mjs CHANGED
@@ -82,7 +82,12 @@ export function createRemote({
82
82
  },
83
83
  };
84
84
  if (message.openmsg.hops.length > MAX_HOPS) {
85
- throw fail("hop-limit", `this conversation already passed through ${message.openmsg.hops.length - 1} agents`);
85
+ throw fail(
86
+ "hop-limit",
87
+ `this conversation already passed through ${message.openmsg.hops.length - 1} agents. ` +
88
+ "Ask your user if they want to continue. If the user says yes, send the text again " +
89
+ "as a new message, without --reply-to. A new message starts a new conversation.",
90
+ );
86
91
  }
87
92
  return signedView(message);
88
93
  }
package/src/settings.mjs CHANGED
@@ -25,6 +25,25 @@ export function saveSettings(next) {
25
25
  return data;
26
26
  }
27
27
 
28
+ // The address that this owner gives to other people, in an invitation, in the
29
+ // directory, and in the routing data. A loopback address means this machine
30
+ // alone. A gateway that listens there and uses a relay gives no address,
31
+ // because the relay is its way in. With that address in the directory, a
32
+ // sender on another machine writes to its own machine, and never to the relay.
33
+ const LOOPBACK = ["127.0.0.1", "localhost", "::1", "[::1]"];
34
+
35
+ export function advertised() {
36
+ const { endpoint, relay } = settings();
37
+ if (!endpoint) return null;
38
+ let host;
39
+ try {
40
+ host = new URL(endpoint).hostname;
41
+ } catch {
42
+ return null;
43
+ }
44
+ return relay && LOOPBACK.includes(host) ? null : endpoint;
45
+ }
46
+
28
47
  export function endpointFor(host, port) {
29
48
  const name = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
30
49
  return `http://${name}:${port}`;
@@ -0,0 +1,95 @@
1
+ // The agents that wake on an HTTP request. Such an agent has no session that
2
+ // another program can write to. Its owner gives openmsg one URL, and a POST to
3
+ // that URL starts a turn of the agent.
4
+ //
5
+ // The URL is a secret: a person who holds it can wake the agent. The file is
6
+ // therefore readable by its owner only, and no command prints the URL in the
7
+ // routing data or in `list --json`.
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import os from "node:os";
11
+
12
+ // The home reads from the environment at each call, as the mailbox does.
13
+ function file() {
14
+ return path.join(process.env.OPENMSG_HOME ?? path.join(os.homedir(), ".openmsg"), "webhooks.json");
15
+ }
16
+
17
+ function read() {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(file(), "utf8"));
20
+ } catch {
21
+ return {};
22
+ }
23
+ }
24
+
25
+ function save(data) {
26
+ fs.mkdirSync(path.dirname(file()), { recursive: true });
27
+ fs.writeFileSync(file(), JSON.stringify(data, null, 1), { mode: 0o600 });
28
+ // The mode of an existing file does not change on a write.
29
+ fs.chmodSync(file(), 0o600);
30
+ }
31
+
32
+ // A name is a part of an address, and of a file name of the mailbox.
33
+ const NAME = /^[a-z0-9][a-z0-9._-]{0,62}$/;
34
+
35
+ // A webhook can ask for a header, for example "Authorization: Bearer <key>".
36
+ // The value is a secret, as the URL is. A line break in a header starts a
37
+ // second header, so a value with one is refused. The error never holds the
38
+ // value.
39
+ const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
40
+
41
+ export function parseHeader(line) {
42
+ const at = String(line ?? "").indexOf(":");
43
+ const name = at === -1 ? "" : line.slice(0, at).trim();
44
+ const value = at === -1 ? "" : line.slice(at + 1).trim();
45
+ if (!HEADER_NAME.test(name) || value === "" || /[\r\n\0]/.test(value)) {
46
+ throw new Error('a header has the shape "Name: value", on one line');
47
+ }
48
+ if (name.toLowerCase() === "content-type") throw new Error("the notice is JSON, and its content-type does not change");
49
+ return [name, value];
50
+ }
51
+
52
+ export function add(name, url, { headers = [] } = {}) {
53
+ if (!NAME.test(String(name ?? ""))) {
54
+ throw new Error(`"${name}" is not a name. Use lowercase letters, digits, ".", "_", and "-"`);
55
+ }
56
+ let address;
57
+ try {
58
+ address = new URL(url);
59
+ } catch {
60
+ throw new Error(`"${url}" is not a URL`);
61
+ }
62
+ if (address.protocol !== "https:" && address.protocol !== "http:") {
63
+ throw new Error(`a webhook takes an http:// or https:// address, and "${url}" is neither`);
64
+ }
65
+ const extra = Object.fromEntries(headers.map(parseHeader));
66
+ const data = read();
67
+ data[name] = { url: address.href, headers: extra, addedAt: data[name]?.addedAt ?? new Date().toISOString() };
68
+ save(data);
69
+ return { name, ...data[name] };
70
+ }
71
+
72
+ export function remove(name) {
73
+ const data = read();
74
+ if (!data[name]) return false;
75
+ delete data[name];
76
+ save(data);
77
+ return true;
78
+ }
79
+
80
+ // The same shape that discovery gives for a session of a vendor. The name is
81
+ // also the id, because one name is one agent, and it has no session.
82
+ export function agents() {
83
+ return Object.entries(read()).map(([name, row]) => ({
84
+ vendor: "webhook",
85
+ id: name,
86
+ name,
87
+ pid: null,
88
+ cwd: null,
89
+ status: "waits",
90
+ title: "wakes on an HTTP request",
91
+ startedAt: null,
92
+ updatedAt: null,
93
+ transport: { kind: "webhook", url: row.url, headers: row.headers ?? {} },
94
+ }));
95
+ }
package/src/wsframe.mjs CHANGED
@@ -54,6 +54,9 @@ export class Connection extends EventEmitter {
54
54
  this.partsOpcode = null;
55
55
  this.closed = false;
56
56
  socket.on("data", (chunk) => this.read(chunk));
57
+ // A machine that sleeps, or a network that drops, sends no FIN. The
58
+ // operating system then asks the other side if it is there.
59
+ socket.setKeepAlive?.(true, 30_000);
57
60
  // "end" arrives when the other side sends FIN. A process that stops gives
58
61
  // FIN, and without this line the connection looks alive until the next
59
62
  // write fails.
@@ -172,6 +175,13 @@ export class Connection extends EventEmitter {
172
175
  this.end();
173
176
  }
174
177
 
178
+ // The end of a connection that does not answer. A close frame to a side
179
+ // that is gone waits for nothing, so the socket stops at once.
180
+ drop() {
181
+ this.socket.destroy();
182
+ this.end();
183
+ }
184
+
175
185
  end() {
176
186
  if (this.closed) return;
177
187
  this.closed = true;